5 #ifndef V8_PARSING_PARSER_H_ 6 #define V8_PARSING_PARSER_H_ 10 #include "src/ast/ast-source-ranges.h" 11 #include "src/ast/ast.h" 12 #include "src/ast/scopes.h" 13 #include "src/base/compiler-specific.h" 14 #include "src/base/threaded-list.h" 15 #include "src/globals.h" 16 #include "src/parsing/parser-base.h" 17 #include "src/parsing/parsing.h" 18 #include "src/parsing/preparser.h" 19 #include "src/pointer-with-payload.h" 20 #include "src/zone/zone-chunk-list.h" 28 class ConsumedPreParsedScopeData;
31 class ParserTargetScope;
32 class PendingCompilationErrorHandler;
33 class PreParsedScopeData;
42 kNumInnerFunctionsIndex,
47 : backing_(backing) { }
53 :
public BitField<bool, LanguageModeField::kNext, 1> {};
55 static uint32_t EncodeFlags(LanguageMode language_mode,
56 bool uses_super_property) {
57 return LanguageModeField::encode(language_mode) |
58 UsesSuperPropertyField::encode(uses_super_property);
61 int start_pos()
const {
return backing_[kStartPositionIndex]; }
62 int end_pos()
const {
return backing_[kEndPositionIndex]; }
63 int num_parameters()
const {
return backing_[kNumParametersIndex]; }
64 LanguageMode language_mode()
const {
65 return LanguageModeField::decode(backing_[kFlagsIndex]);
67 bool uses_super_property()
const {
68 return UsesSuperPropertyField::decode(backing_[kFlagsIndex]);
70 int num_inner_functions()
const {
return backing_[kNumInnerFunctionsIndex]; }
72 bool is_valid()
const {
return !backing_.is_empty(); }
75 Vector<unsigned> backing_;
89 int initializer_end_position,
bool is_rest)
91 name_and_is_rest(initializer, is_rest),
94 initializer_end_position(initializer_end_position) {}
101 Expression* initializer()
const {
return name_and_is_rest.GetPointer(); }
103 int initializer_end_position;
104 inline bool is_rest()
const {
return name_and_is_rest.GetPayload(); }
107 bool is_simple()
const {
108 return pattern->IsVariableProxy() && initializer() ==
nullptr &&
112 Parameter** next() {
return &next_parameter; }
113 Parameter*
const* next()
const {
return &next_parameter; }
117 bool has_duplicate()
const {
return duplicate_loc.IsValid(); }
119 explicit ParserFormalParameters(DeclarationScope* scope)
120 : FormalParametersBase(scope) {}
121 base::ThreadedList<Parameter> params;
122 Scanner::Location duplicate_loc = Scanner::Location::invalid();
159 static constexpr
bool ExpressionClassifierReportErrors =
true;
162 class V8_EXPORT_PRIVATE
Parser :
public NON_EXPORTED_BASE(ParserBase<Parser>) {
166 delete reusable_preparser_;
167 reusable_preparser_ =
nullptr;
170 static bool IsPreParser() {
return false; }
176 void InitializeEmptyScopeChain(
ParseInfo* info);
198 friend bool v8::internal::parsing::ParseFunction(
201 bool AllowsLazyParsingWithoutUnresolvedVariables()
const {
202 return scope()->AllowsLazyParsingWithoutUnresolvedVariables(
206 bool parse_lazily()
const {
return mode_ == PARSE_LAZILY; }
207 enum Mode { PARSE_LAZILY, PARSE_EAGERLY };
209 class ParsingModeScope {
211 ParsingModeScope(
Parser* parser, Mode mode)
212 : parser_(parser), old_mode_(parser->mode_) {
213 parser_->mode_ = mode;
215 ~ParsingModeScope() { parser_->mode_ = old_mode_; }
223 enum CompletionKind {
230 return scope()->NewTemporary(name);
233 void PrepareGeneratorVariables();
258 if (reusable_preparser_ ==
nullptr) {
260 &preparser_zone_, &scanner_, stack_limit_, ast_value_factory(),
261 pending_error_handler(), runtime_call_stats_, logger_, -1,
262 parsing_module_, parsing_on_main_thread_);
263 #define SET_ALLOW(name) reusable_preparser_->set_allow_##name(allow_##name()); 265 SET_ALLOW(harmony_public_fields);
266 SET_ALLOW(harmony_static_fields);
267 SET_ALLOW(harmony_dynamic_import);
268 SET_ALLOW(harmony_import_meta);
269 SET_ALLOW(harmony_private_fields);
270 SET_ALLOW(harmony_private_methods);
271 SET_ALLOW(eval_cache);
274 return reusable_preparser_;
280 void ParseImportDeclaration();
283 void ParseExportStar();
284 struct ExportClauseData {
297 : import_name(import_name),
298 local_name(local_name),
299 location(location) {}
302 Block* BuildInitializationBlock(DeclarationParsingResult* parsing_result,
312 void RewriteCatchPattern(CatchInfo* catch_info);
313 void ValidateCatchBlock(
const CatchInfo& catch_info);
316 Block* finally_block,
318 const CatchInfo& catch_info,
int pos);
319 void GetUnexpectedTokenMessage(Token::Value token, MessageTemplate* message,
321 void ParseAndRewriteGeneratorFunctionBody(
int pos, FunctionKind kind,
323 void ParseAndRewriteAsyncGeneratorFunctionBody(
325 void DeclareFunctionNameVar(
const AstRawString* function_name,
326 FunctionLiteral::FunctionType function_type,
331 int pos,
bool is_sloppy_block_function,
340 return identifier == other;
345 int class_token_pos,
int end_pos);
346 void DeclareClassVariable(
const AstRawString* name, ClassInfo* class_info,
347 int class_token_pos);
348 void DeclareClassProperty(
const AstRawString* class_name,
351 ClassLiteralProperty::Kind kind,
bool is_static,
352 bool is_constructor,
bool is_computed_name,
353 bool is_private, ClassInfo* class_info);
355 ClassInfo* class_info,
int pos,
int end_pos);
360 Scope* NewHiddenCatchScope();
364 void DeclareAndInitializeVariables(
365 Block* block,
const DeclarationDescriptor* declaration_descriptor,
366 const DeclarationParsingResult::Declaration* declaration,
380 IteratorType
type,
int pos);
388 bool finalize, IteratorType
type,
389 int next_result_pos = kNoSourcePosition);
391 Block* RewriteForVarInLegacy(
const ForInfo& for_info);
392 void DesugarBindingInForEachStatement(ForInfo* for_info,
Block** body_block,
394 Block* CreateForEachStatementTDZ(
Block* init_block,
const ForInfo& for_info);
396 Statement* DesugarLexicalBindingsInForStatement(
402 FunctionNameValidity function_name_validity, FunctionKind kind,
403 int function_token_position, FunctionLiteral::FunctionType
type,
404 LanguageMode language_mode,
408 object_literal->CalculateEmitStore(main_zone());
409 return object_literal;
421 void CheckConflictingVarDeclarations(
Scope* scope);
423 bool IsPropertyWithPrivateFieldKey(
Expression* property);
427 void InsertShadowingVarBindingInitializers(
Block* block);
433 VariableKind kind = NORMAL_VARIABLE);
436 DeclarationDescriptor::Kind declaration_kind,
437 VariableMode mode, InitializationFlag init,
438 Scope* declaration_scope =
nullptr,
439 int var_end_pos = kNoSourcePosition);
443 InitializationFlag init,
int pos);
445 bool TargetStackContainsLabel(
const AstRawString* label);
453 int pos,
int end_pos);
466 bool SkipFunction(
const AstRawString* function_name, FunctionKind kind,
467 FunctionLiteral::FunctionType function_type,
470 bool may_abort, FunctionLiteral::EagerCompileHint* hint);
472 Block* BuildParameterInitializationBlock(
474 Block* BuildRejectPromiseOnException(
Block* block);
478 int pos, FunctionKind kind, FunctionLiteral::FunctionType function_type,
480 int* function_length,
bool* has_duplicate_parameters,
481 int* expected_property_count,
int* suspend_count,
488 TemplateLiteral(
Zone* zone,
int pos)
489 : cooked_(8, zone), raw_(8, zone), expressions_(8, zone), pos_(pos) {}
494 int position()
const {
return pos_; }
497 int end,
Zone* zone) {
498 DCHECK_NOT_NULL(raw);
499 cooked_.Add(cooked, zone);
504 expressions_.Add(expression, zone);
514 typedef TemplateLiteral* TemplateLiteralState;
516 TemplateLiteralState OpenTemplateLiteral(
int pos);
523 void AddTemplateSpan(TemplateLiteralState* state,
bool should_cook,
525 void AddTemplateExpression(TemplateLiteralState* state,
527 Expression* CloseTemplateLiteral(TemplateLiteralState* state,
int start,
534 Call::PossiblyEval is_possibly_eval);
539 void SetLanguageMode(
Scope* scope, LanguageMode mode);
543 void RewriteDestructuringAssignments();
547 void QueueDestructuringAssignmentForRewriting(
551 void RewriteParameterInitializer(
Expression* expr);
553 Expression* BuildInitialYield(
int pos, FunctionKind kind);
554 Assignment* BuildCreateJSGeneratorObject(
int pos, FunctionKind kind);
555 Variable* AsyncGeneratorAwaitVariable();
558 Expression* NewThrowError(Runtime::FunctionId function_id,
567 IteratorType
type,
int pos);
586 V8_INLINE
bool IsEval(
const AstRawString* identifier)
const {
587 return identifier == ast_value_factory()->eval_string();
590 V8_INLINE
bool IsAsync(
const AstRawString* identifier)
const {
591 return identifier == ast_value_factory()->async_string();
594 V8_INLINE
bool IsArguments(
const AstRawString* identifier)
const {
595 return identifier == ast_value_factory()->arguments_string();
598 V8_INLINE
bool IsEvalOrArguments(
const AstRawString* identifier)
const {
599 return IsEval(identifier) || IsArguments(identifier);
603 V8_INLINE
static bool IsThisProperty(
Expression* expression) {
604 DCHECK_NOT_NULL(expression);
605 Property*
property = expression->AsProperty();
606 return property !=
nullptr &&
property->obj()->IsVariableProxy() &&
607 property->obj()->AsVariableProxy()->is_this();
613 V8_INLINE
static bool IsIdentifier(
Expression* expression) {
615 return operand !=
nullptr && !operand->is_this() &&
616 !operand->is_new_target();
620 DCHECK(IsIdentifier(expression));
621 return expression->AsVariableProxy()->raw_name();
625 return expression->AsVariableProxy();
628 V8_INLINE
bool IsConstructor(
const AstRawString* identifier)
const {
629 return identifier == ast_value_factory()->constructor_string();
632 V8_INLINE
bool IsName(
const AstRawString* identifier)
const {
633 return identifier == ast_value_factory()->name_string();
636 V8_INLINE
static bool IsBoilerplateProperty(
638 return !
property->IsPrototype();
641 V8_INLINE
bool IsNative(
Expression* expr)
const {
642 DCHECK_NOT_NULL(expr);
643 return expr->IsVariableProxy() &&
644 expr->AsVariableProxy()->raw_name() ==
645 ast_value_factory()->native_string();
648 V8_INLINE
static bool IsArrayIndex(
const AstRawString*
string,
650 return string->AsArrayIndex(index);
656 V8_INLINE
bool IsStringLiteral(
Statement* statement,
659 if (e_stat ==
nullptr)
return false;
660 Literal* literal = e_stat->expression()->AsLiteral();
661 if (literal ==
nullptr || !literal->IsString())
return false;
662 return arg ==
nullptr || literal->AsRawString() == arg;
665 V8_INLINE
void GetDefaultStrings(
668 *default_string = ast_value_factory()->default_string();
669 *star_default_star_string = ast_value_factory()->star_default_star_string();
674 V8_INLINE
void PushLiteralName(
const AstRawString*
id) {
675 fni_.PushLiteralName(
id);
678 V8_INLINE
void PushVariableName(
const AstRawString*
id) {
679 fni_.PushVariableName(
id);
682 V8_INLINE
void PushPropertyName(
Expression* expression) {
683 if (expression->IsPropertyName()) {
684 fni_.PushLiteralName(expression->AsLiteral()->AsRawPropertyName());
686 fni_.PushLiteralName(ast_value_factory()->anonymous_function_string());
690 V8_INLINE
void PushEnclosingName(
const AstRawString* name) {
691 fni_.PushEnclosingName(name);
694 V8_INLINE
void AddFunctionForNameInference(
FunctionLiteral* func_to_infer) {
695 fni_.AddFunction(func_to_infer);
698 V8_INLINE
void InferFunctionName() { fni_.Infer(); }
702 V8_INLINE
static void CheckAssigningFunctionLiteralToProperty(
704 DCHECK_NOT_NULL(left);
705 if (left->IsProperty() && right->IsFunctionLiteral()) {
706 right->AsFunctionLiteral()->set_pretenure();
710 V8_INLINE
static void MarkPatternAsAssigned(
Expression* expression) {}
714 V8_INLINE
static void MarkExpressionAsAssigned(
Expression* expression) {
715 DCHECK_NOT_NULL(expression);
716 if (expression->IsVariableProxy()) {
717 expression->AsVariableProxy()->set_is_assigned();
723 if (expr->IsStringLiteral())
return expr;
726 return factory()->NewCallRuntime(Runtime::kInlineToString, args,
734 Token::Value op,
int pos);
752 V8_INLINE
Expression* NewThrowReferenceError(MessageTemplate message,
754 return NewThrowError(Runtime::kNewReferenceError, message,
755 ast_value_factory()->empty_string(), pos);
761 V8_INLINE
Expression* NewThrowSyntaxError(MessageTemplate message,
763 return NewThrowError(Runtime::kNewSyntaxError, message, arg, pos);
768 V8_INLINE
Expression* NewThrowTypeError(MessageTemplate message,
770 return NewThrowError(Runtime::kNewTypeError, message, arg, pos);
775 MessageTemplate message,
const char* arg =
nullptr,
776 ParseErrorType error_type = kSyntaxError) {
777 if (stack_overflow()) {
784 pending_error_handler()->ReportMessageAt(source_location.beg_pos,
785 source_location.end_pos, message,
787 scanner_.set_parser_error();
792 V8_INLINE
void ReportUnidentifiableError() { UNREACHABLE(); }
796 ParseErrorType error_type = kSyntaxError) {
797 if (stack_overflow()) {
804 pending_error_handler()->ReportMessageAt(source_location.beg_pos,
805 source_location.end_pos, message,
807 scanner_.set_parser_error();
811 V8_INLINE
static std::nullptr_t NullIdentifier() {
return nullptr; }
812 V8_INLINE
static std::nullptr_t NullExpression() {
return nullptr; }
813 V8_INLINE
static std::nullptr_t NullLiteralProperty() {
return nullptr; }
820 V8_INLINE
static std::nullptr_t NullStatement() {
return nullptr; }
823 template <
typename T>
824 V8_INLINE
static bool IsNull(
T subject) {
825 return subject ==
nullptr;
829 V8_INLINE
const AstRawString* EmptyIdentifierString()
const {
830 return ast_value_factory()->empty_string();
835 const AstRawString* result = scanner()->CurrentSymbol(ast_value_factory());
836 DCHECK_NOT_NULL(result);
841 return scanner()->NextSymbol(ast_value_factory());
844 V8_INLINE
const AstRawString* GetNumberAsSymbol()
const {
845 double double_value = scanner()->DoubleValue();
847 const char*
string = DoubleToCString(double_value, ArrayVector(array));
848 return ast_value_factory()->GetOneByteString(
string);
851 V8_INLINE
Expression* ThisExpression(
int pos = kNoSourcePosition) {
852 return NewUnresolved(ast_value_factory()->this_string(), pos,
856 Expression* NewSuperPropertyReference(
int pos);
861 Expression* ExpressionFromLiteral(Token::Value token,
int pos);
865 InferName infer = InferName::kYes) {
866 if (infer == InferName::kYes) {
867 fni_.PushVariableName(name);
869 return NewUnresolved(name, start_position);
891 return factory()->NewExpressionStatement(
892 factory()->NewThrow(exception, pos), pos);
898 int initializer_end_position,
900 parameters->UpdateArityAndFunctionLength(initializer !=
nullptr, is_rest);
901 bool has_simple_name = pattern->IsVariableProxy() && initializer ==
nullptr;
903 ? pattern->AsVariableProxy()->raw_name()
904 : ast_value_factory()->empty_string();
905 auto parameter =
new (parameters->scope->zone())
907 scanner()->location().beg_pos,
908 initializer_end_position, is_rest);
910 parameters->params.Add(parameter);
914 ValidateFormalParameterInitializer();
915 bool is_simple = parameters->is_simple;
917 if (!is_simple) scope->SetHasNonSimpleParameters();
918 for (
auto parameter : parameters->params) {
919 bool is_optional = parameter->initializer() !=
nullptr;
924 if (is_simple && !parameters->has_duplicate() &&
925 scope->LookupLocal(parameter->name)) {
926 parameters->duplicate_loc =
928 parameter->position + parameter->name->length());
930 scope->DeclareParameter(
931 is_simple ? parameter->name : ast_value_factory()->empty_string(),
932 is_simple ? VariableMode::kVar : VariableMode::kTemporary,
933 is_optional, parameter->is_rest(), ast_value_factory(),
934 parameter->position);
938 void DeclareArrowFunctionFormalParameters(
951 void SetFunctionNameFromIdentifierRef(
Expression* value,
955 GetReportedErrorList()
const {
956 return function_state_->GetReportedErrorList();
959 V8_INLINE
void CountUsage(v8::Isolate::UseCounterFeature feature) {
960 ++use_counts_[feature];
965 V8_INLINE
bool ParsingDynamicFunctionDeclaration()
const {
966 return parameters_end_pos_ != kNoSourcePosition;
969 V8_INLINE
void ConvertBinaryToNaryOperationSourceRange(
971 if (source_range_map_ ==
nullptr)
return;
972 DCHECK_NULL(source_range_map_->Find(nary_op));
976 source_range_map_->Find(binary_op));
977 if (ranges ==
nullptr)
return;
979 SourceRange range = ranges->GetRange(SourceRangeKind::kRight);
980 source_range_map_->Insert(
984 V8_INLINE
void AppendNaryOperationSourceRange(
NaryOperation* node,
986 if (source_range_map_ ==
nullptr)
return;
989 if (ranges ==
nullptr)
return;
991 ranges->AddRange(range);
992 DCHECK_EQ(node->subsequent_length(), ranges->RangeCount());
995 V8_INLINE
void RecordBlockSourceRange(
Block* node,
996 int32_t continuation_position) {
997 if (source_range_map_ ==
nullptr)
return;
998 source_range_map_->Insert(
1002 V8_INLINE
void RecordCaseClauseSourceRange(
CaseClause* node,
1004 if (source_range_map_ ==
nullptr)
return;
1005 source_range_map_->Insert(node,
1009 V8_INLINE
void RecordConditionalSourceRange(
Expression* node,
1012 if (source_range_map_ ==
nullptr)
return;
1013 source_range_map_->Insert(
1014 node->AsConditional(),
1018 V8_INLINE
void RecordBinaryOperationSourceRange(
1020 if (source_range_map_ ==
nullptr)
return;
1021 source_range_map_->Insert(node->AsBinaryOperation(),
1026 V8_INLINE
void RecordJumpStatementSourceRange(
Statement* node,
1027 int32_t continuation_position) {
1028 if (source_range_map_ ==
nullptr)
return;
1029 source_range_map_->Insert(
1030 static_cast<JumpStatement*>(node),
1034 V8_INLINE
void RecordIfStatementSourceRange(
Statement* node,
1037 if (source_range_map_ ==
nullptr)
return;
1038 source_range_map_->Insert(
1039 node->AsIfStatement(),
1043 V8_INLINE
void RecordIterationStatementSourceRange(
1045 if (source_range_map_ ==
nullptr)
return;
1046 source_range_map_->Insert(
1050 V8_INLINE
void RecordSuspendSourceRange(
Expression* node,
1051 int32_t continuation_position) {
1052 if (source_range_map_ ==
nullptr)
return;
1053 source_range_map_->Insert(static_cast<Suspend*>(node),
1058 V8_INLINE
void RecordSwitchStatementSourceRange(
1059 Statement* node, int32_t continuation_position) {
1060 if (source_range_map_ ==
nullptr)
return;
1061 source_range_map_->Insert(
1062 node->AsSwitchStatement(),
1066 V8_INLINE
void RecordThrowSourceRange(
Statement* node,
1067 int32_t continuation_position) {
1068 if (source_range_map_ ==
nullptr)
return;
1070 Throw* throw_expr = expr_stmt->expression()->AsThrow();
1071 source_range_map_->Insert(
1075 V8_INLINE
void RecordTryCatchStatementSourceRange(
1077 if (source_range_map_ ==
nullptr)
return;
1078 source_range_map_->Insert(
1082 V8_INLINE
void RecordTryFinallyStatementSourceRange(
1084 if (source_range_map_ ==
nullptr)
return;
1085 source_range_map_->Insert(
1093 ParseInfo* info()
const {
return info_; }
1096 friend class PreParserZoneScope;
1100 Zone preparser_zone_;
1110 ScriptCompiler::CompileOptions compile_options_;
1113 int number_of_named_namespace_exports_ = 0;
1117 int use_counts_[v8::Isolate::kUseCounterFeatureCount];
1118 int total_preparse_skipped_;
1127 int parameters_end_pos_;
1139 : variable_(&parser->impl()->target_stack_),
1140 statement_(statement),
1141 previous_(parser->impl()->target_stack_) {
1142 parser->impl()->target_stack_ =
this;
1159 : variable_(&parser->impl()->target_stack_),
1160 previous_(parser->impl()->target_stack_) {
1161 parser->impl()->target_stack_ =
nullptr;
1174 #endif // V8_PARSING_PARSER_H_