Line data Source code
1 : // Copyright 2012 the V8 project authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #ifndef V8_PARSING_PARSER_BASE_H_
6 : #define V8_PARSING_PARSER_BASE_H_
7 :
8 : #include <stdint.h>
9 : #include <vector>
10 :
11 : #include "src/ast/ast-source-ranges.h"
12 : #include "src/ast/ast.h"
13 : #include "src/ast/scopes.h"
14 : #include "src/bailout-reason.h"
15 : #include "src/base/flags.h"
16 : #include "src/base/hashmap.h"
17 : #include "src/base/v8-fallthrough.h"
18 : #include "src/counters.h"
19 : #include "src/globals.h"
20 : #include "src/log.h"
21 : #include "src/message-template.h"
22 : #include "src/parsing/expression-scope.h"
23 : #include "src/parsing/func-name-inferrer.h"
24 : #include "src/parsing/scanner.h"
25 : #include "src/parsing/token.h"
26 : #include "src/pointer-with-payload.h"
27 : #include "src/zone/zone-chunk-list.h"
28 :
29 : namespace v8 {
30 : namespace internal {
31 :
32 : enum FunctionNameValidity {
33 : kFunctionNameIsStrictReserved,
34 : kSkipFunctionNameCheck,
35 : kFunctionNameValidityUnknown
36 : };
37 :
38 : enum AllowLabelledFunctionStatement {
39 : kAllowLabelledFunctionStatement,
40 : kDisallowLabelledFunctionStatement,
41 : };
42 :
43 : enum ParsingArrowHeadFlag { kCertainlyNotArrowHead, kMaybeArrowHead };
44 :
45 : enum class ParseFunctionFlag : uint8_t {
46 : kIsNormal = 0,
47 : kIsGenerator = 1 << 0,
48 : kIsAsync = 1 << 1
49 : };
50 :
51 : typedef base::Flags<ParseFunctionFlag> ParseFunctionFlags;
52 :
53 : struct FormalParametersBase {
54 5170305 : explicit FormalParametersBase(DeclarationScope* scope) : scope(scope) {}
55 :
56 : int num_parameters() const {
57 : // Don't include the rest parameter into the function's formal parameter
58 : // count (esp. the SharedFunctionInfo::internal_formal_parameter_count,
59 : // which says whether we need to create an arguments adaptor frame).
60 4287862 : return arity - has_rest;
61 : }
62 :
63 7761961 : void UpdateArityAndFunctionLength(bool is_optional, bool is_rest) {
64 7761961 : if (!is_optional && !is_rest && function_length == arity) {
65 7623322 : ++function_length;
66 : }
67 7761961 : ++arity;
68 7761961 : }
69 :
70 : DeclarationScope* scope;
71 : bool has_rest = false;
72 : bool is_simple = true;
73 : int function_length = 0;
74 : int arity = 0;
75 : };
76 :
77 : // Stack-allocated scope to collect source ranges from the parser.
78 : class SourceRangeScope final {
79 : public:
80 190756 : SourceRangeScope(const Scanner* scanner, SourceRange* range)
81 190756 : : scanner_(scanner), range_(range) {
82 4052082 : range_->start = scanner->peek_location().beg_pos;
83 : DCHECK_NE(range_->start, kNoSourcePosition);
84 : DCHECK_EQ(range_->end, kNoSourcePosition);
85 190756 : }
86 :
87 190773 : ~SourceRangeScope() {
88 : DCHECK_EQ(kNoSourcePosition, range_->end);
89 4242925 : range_->end = scanner_->location().end_pos;
90 : DCHECK_NE(range_->end, kNoSourcePosition);
91 190773 : }
92 :
93 : private:
94 : const Scanner* scanner_;
95 : SourceRange* range_;
96 :
97 : DISALLOW_IMPLICIT_CONSTRUCTORS(SourceRangeScope);
98 : };
99 :
100 : // ----------------------------------------------------------------------------
101 : // The RETURN_IF_PARSE_ERROR macro is a convenient macro to enforce error
102 : // handling for functions that may fail (by returning if there was an parser
103 : // error).
104 : //
105 : // Usage:
106 : // foo = ParseFoo(); // may fail
107 : // RETURN_IF_PARSE_ERROR
108 : //
109 : // SAFE_USE(foo);
110 :
111 : #define RETURN_IF_PARSE_ERROR \
112 : if (has_error()) return impl()->NullStatement();
113 :
114 : // Common base class template shared between parser and pre-parser.
115 : // The Impl parameter is the actual class of the parser/pre-parser,
116 : // following the Curiously Recurring Template Pattern (CRTP).
117 : // The structure of the parser objects is roughly the following:
118 : //
119 : // // A structure template containing type definitions, needed to
120 : // // avoid a cyclic dependency.
121 : // template <typename Impl>
122 : // struct ParserTypes;
123 : //
124 : // // The parser base object, which should just implement pure
125 : // // parser behavior. The Impl parameter is the actual derived
126 : // // class (according to CRTP), which implements impure parser
127 : // // behavior.
128 : // template <typename Impl>
129 : // class ParserBase { ... };
130 : //
131 : // // And then, for each parser variant (e.g., parser, preparser, etc):
132 : // class Parser;
133 : //
134 : // template <>
135 : // class ParserTypes<Parser> { ... };
136 : //
137 : // class Parser : public ParserBase<Parser> { ... };
138 : //
139 : // The parser base object implements pure parsing, according to the
140 : // language grammar. Different parser implementations may exhibit
141 : // different parser-driven behavior that is not considered as pure
142 : // parsing, e.g., early error detection and reporting, AST generation, etc.
143 :
144 : // The ParserTypes structure encapsulates the differences in the
145 : // types used in parsing methods. E.g., Parser methods use Expression*
146 : // and PreParser methods use PreParserExpression. For any given parser
147 : // implementation class Impl, it is expected to contain the following typedefs:
148 : //
149 : // template <>
150 : // struct ParserTypes<Impl> {
151 : // // Synonyms for ParserBase<Impl> and Impl, respectively.
152 : // typedef Base;
153 : // typedef Impl;
154 : // // Return types for traversing functions.
155 : // typedef Identifier;
156 : // typedef Expression;
157 : // typedef FunctionLiteral;
158 : // typedef ObjectLiteralProperty;
159 : // typedef ClassLiteralProperty;
160 : // typedef ExpressionList;
161 : // typedef ObjectPropertyList;
162 : // typedef ClassPropertyList;
163 : // typedef FormalParameters;
164 : // typedef Statement;
165 : // typedef StatementList;
166 : // typedef Block;
167 : // typedef BreakableStatement;
168 : // typedef ForStatement;
169 : // typedef IterationStatement;
170 : // // For constructing objects returned by the traversing functions.
171 : // typedef Factory;
172 : // // For other implementation-specific tasks.
173 : // typedef Target;
174 : // typedef TargetScope;
175 : // };
176 :
177 : template <typename Impl>
178 : struct ParserTypes;
179 :
180 : enum class ParsePropertyKind : uint8_t {
181 : kAccessorGetter,
182 : kAccessorSetter,
183 : kValue,
184 : kShorthand,
185 : kAssign,
186 : kMethod,
187 : kClassField,
188 : kShorthandOrClassField,
189 : kSpread,
190 : kNotSet
191 : };
192 :
193 : template <typename Impl>
194 6703195 : class ParserBase {
195 : public:
196 : // Shorten type names defined by ParserTypes<Impl>.
197 : typedef ParserTypes<Impl> Types;
198 : typedef typename v8::internal::ExpressionScope<Types> ExpressionScope;
199 : typedef typename v8::internal::ExpressionParsingScope<Types>
200 : ExpressionParsingScope;
201 : typedef typename v8::internal::AccumulationScope<Types> AccumulationScope;
202 : typedef typename v8::internal::ArrowHeadParsingScope<Types>
203 : ArrowHeadParsingScope;
204 : typedef typename v8::internal::VariableDeclarationParsingScope<Types>
205 : VariableDeclarationParsingScope;
206 : typedef typename v8::internal::ParameterDeclarationParsingScope<Types>
207 : ParameterDeclarationParsingScope;
208 :
209 : // Return types for traversing functions.
210 : typedef typename Types::Block BlockT;
211 : typedef typename Types::BreakableStatement BreakableStatementT;
212 : typedef typename Types::ClassLiteralProperty ClassLiteralPropertyT;
213 : typedef typename Types::ClassPropertyList ClassPropertyListT;
214 : typedef typename Types::Expression ExpressionT;
215 : typedef typename Types::ExpressionList ExpressionListT;
216 : typedef typename Types::FormalParameters FormalParametersT;
217 : typedef typename Types::ForStatement ForStatementT;
218 : typedef typename Types::FunctionLiteral FunctionLiteralT;
219 : typedef typename Types::Identifier IdentifierT;
220 : typedef typename Types::IterationStatement IterationStatementT;
221 : typedef typename Types::ObjectLiteralProperty ObjectLiteralPropertyT;
222 : typedef typename Types::ObjectPropertyList ObjectPropertyListT;
223 : typedef typename Types::Statement StatementT;
224 : typedef typename Types::StatementList StatementListT;
225 : typedef typename Types::Suspend SuspendExpressionT;
226 : // For constructing objects returned by the traversing functions.
227 : typedef typename Types::Factory FactoryT;
228 : // Other implementation-specific tasks.
229 : typedef typename Types::FuncNameInferrer FuncNameInferrer;
230 : typedef typename Types::FuncNameInferrer::State FuncNameInferrerState;
231 : typedef typename Types::SourceRange SourceRange;
232 : typedef typename Types::SourceRangeScope SourceRangeScope;
233 : typedef typename Types::Target TargetT;
234 : typedef typename Types::TargetScope TargetScopeT;
235 :
236 : // All implementation-specific methods must be called through this.
237 131020769 : Impl* impl() { return static_cast<Impl*>(this); }
238 : const Impl* impl() const { return static_cast<const Impl*>(this); }
239 :
240 3351409 : ParserBase(Zone* zone, Scanner* scanner, uintptr_t stack_limit,
241 : v8::Extension* extension, AstValueFactory* ast_value_factory,
242 : PendingCompilationErrorHandler* pending_error_handler,
243 : RuntimeCallStats* runtime_call_stats, Logger* logger,
244 : int script_id, bool parsing_module, bool parsing_on_main_thread)
245 : : scope_(nullptr),
246 : original_scope_(nullptr),
247 : function_state_(nullptr),
248 : extension_(extension),
249 : fni_(ast_value_factory),
250 : ast_value_factory_(ast_value_factory),
251 : ast_node_factory_(ast_value_factory, zone),
252 : runtime_call_stats_(runtime_call_stats),
253 : logger_(logger),
254 : parsing_on_main_thread_(parsing_on_main_thread),
255 : parsing_module_(parsing_module),
256 : stack_limit_(stack_limit),
257 : pending_error_handler_(pending_error_handler),
258 : zone_(zone),
259 : expression_scope_(nullptr),
260 : scanner_(scanner),
261 : function_literal_id_(0),
262 : script_id_(script_id),
263 : default_eager_compile_hint_(FunctionLiteral::kShouldLazyCompile),
264 : allow_natives_(false),
265 : allow_harmony_public_fields_(false),
266 : allow_harmony_static_fields_(false),
267 : allow_harmony_dynamic_import_(false),
268 : allow_harmony_import_meta_(false),
269 : allow_harmony_private_fields_(false),
270 : allow_harmony_private_methods_(false),
271 10964457 : allow_eval_cache_(true) {
272 3351358 : pointer_buffer_.reserve(32);
273 3351559 : variable_buffer_.reserve(32);
274 3351587 : }
275 :
276 : #define ALLOW_ACCESSORS(name) \
277 : bool allow_##name() const { return allow_##name##_; } \
278 : void set_allow_##name(bool allow) { allow_##name##_ = allow; }
279 :
280 3351388 : ALLOW_ACCESSORS(natives);
281 3351358 : ALLOW_ACCESSORS(harmony_public_fields);
282 3351358 : ALLOW_ACCESSORS(harmony_static_fields);
283 108323902 : ALLOW_ACCESSORS(harmony_dynamic_import);
284 3351358 : ALLOW_ACCESSORS(harmony_import_meta);
285 3351358 : ALLOW_ACCESSORS(harmony_private_methods);
286 2807320 : ALLOW_ACCESSORS(eval_cache);
287 :
288 : #undef ALLOW_ACCESSORS
289 :
290 40721272 : V8_INLINE bool has_error() const { return scanner()->has_parser_error(); }
291 : bool allow_harmony_numeric_separator() const {
292 : return scanner()->allow_harmony_numeric_separator();
293 : }
294 2950414 : void set_allow_harmony_numeric_separator(bool allow) {
295 : scanner()->set_allow_harmony_numeric_separator(allow);
296 : }
297 :
298 477299 : bool allow_harmony_private_fields() const {
299 477299 : return scanner()->allow_harmony_private_fields();
300 : }
301 3351358 : void set_allow_harmony_private_fields(bool allow) {
302 : scanner()->set_allow_harmony_private_fields(allow);
303 : }
304 :
305 : uintptr_t stack_limit() const { return stack_limit_; }
306 :
307 : void set_stack_limit(uintptr_t stack_limit) { stack_limit_ = stack_limit; }
308 :
309 : void set_default_eager_compile_hint(
310 : FunctionLiteral::EagerCompileHint eager_compile_hint) {
311 2441005 : default_eager_compile_hint_ = eager_compile_hint;
312 : }
313 :
314 : FunctionLiteral::EagerCompileHint default_eager_compile_hint() const {
315 : return default_eager_compile_hint_;
316 : }
317 :
318 : int loop_nesting_depth() const {
319 13303037 : return function_state_->loop_nesting_depth();
320 : }
321 :
322 5386210 : int GetNextFunctionLiteralId() { return ++function_literal_id_; }
323 : int GetLastFunctionLiteralId() const { return function_literal_id_; }
324 :
325 3172459 : void SkipFunctionLiterals(int delta) { function_literal_id_ += delta; }
326 :
327 4887450 : void ResetFunctionLiteralId() { function_literal_id_ = 0; }
328 :
329 : // The Zone where the parsing outputs are stored.
330 3294074 : Zone* main_zone() const { return ast_value_factory()->zone(); }
331 :
332 : // The current Zone, which might be the main zone or a temporary Zone.
333 1464582 : Zone* zone() const { return zone_; }
334 :
335 : protected:
336 : friend class v8::internal::ExpressionScope<ParserTypes<Impl>>;
337 : friend class v8::internal::ExpressionParsingScope<ParserTypes<Impl>>;
338 : friend class v8::internal::ArrowHeadParsingScope<ParserTypes<Impl>>;
339 :
340 : enum VariableDeclarationContext {
341 : kStatementListItem,
342 : kStatement,
343 : kForStatement
344 : };
345 :
346 : class ClassLiteralChecker;
347 :
348 : // ---------------------------------------------------------------------------
349 : // BlockState and FunctionState implement the parser's scope stack.
350 : // The parser's current scope is in scope_. BlockState and FunctionState
351 : // constructors push on the scope stack and the destructors pop. They are also
352 : // used to hold the parser's per-funcion state.
353 : class BlockState {
354 : public:
355 372336 : BlockState(Scope** scope_stack, Scope* scope)
356 23703466 : : scope_stack_(scope_stack), outer_scope_(*scope_stack) {
357 23706077 : *scope_stack_ = scope;
358 372336 : }
359 :
360 4844889 : BlockState(Zone* zone, Scope** scope_stack)
361 : : BlockState(scope_stack,
362 9690224 : new (zone) Scope(zone, *scope_stack, BLOCK_SCOPE)) {}
363 :
364 23703207 : ~BlockState() { *scope_stack_ = outer_scope_; }
365 :
366 : private:
367 : Scope** const scope_stack_;
368 : Scope* const outer_scope_;
369 : };
370 :
371 : class FunctionState final : public BlockState {
372 : public:
373 : FunctionState(FunctionState** function_state_stack, Scope** scope_stack,
374 : DeclarationScope* scope);
375 : ~FunctionState();
376 :
377 120009945 : DeclarationScope* scope() const { return scope_->AsDeclarationScope(); }
378 :
379 4605598 : void AddProperty() { expected_property_count_++; }
380 : int expected_property_count() { return expected_property_count_; }
381 :
382 : void DisableOptimization(BailoutReason reason) {
383 1761 : dont_optimize_reason_ = reason;
384 : }
385 : BailoutReason dont_optimize_reason() { return dont_optimize_reason_; }
386 :
387 469946 : void AddSuspend() { suspend_count_++; }
388 : int suspend_count() const { return suspend_count_; }
389 43959 : bool CanSuspend() const { return suspend_count_ > 0; }
390 :
391 239393397 : FunctionKind kind() const { return scope()->function_kind(); }
392 :
393 : bool next_function_is_likely_called() const {
394 : return next_function_is_likely_called_;
395 : }
396 :
397 : bool previous_function_was_likely_called() const {
398 : return previous_function_was_likely_called_;
399 : }
400 :
401 : void set_next_function_is_likely_called() {
402 616216 : next_function_is_likely_called_ = true;
403 : }
404 :
405 5704599 : void RecordFunctionOrEvalCall() { contains_function_or_eval_ = true; }
406 : bool contains_function_or_eval() const {
407 : return contains_function_or_eval_;
408 : }
409 :
410 : class FunctionOrEvalRecordingScope {
411 : public:
412 : explicit FunctionOrEvalRecordingScope(FunctionState* state)
413 255790 : : state_and_prev_value_(state, state->contains_function_or_eval_) {
414 255790 : state->contains_function_or_eval_ = false;
415 : }
416 : ~FunctionOrEvalRecordingScope() {
417 255784 : bool found = state_and_prev_value_->contains_function_or_eval_;
418 255784 : if (!found) {
419 227981 : state_and_prev_value_->contains_function_or_eval_ =
420 : state_and_prev_value_.GetPayload();
421 : }
422 : }
423 :
424 : private:
425 : PointerWithPayload<FunctionState, bool, 1> state_and_prev_value_;
426 : };
427 :
428 : class LoopScope {
429 : public:
430 : explicit LoopScope(FunctionState* function_state)
431 : : function_state_(function_state) {
432 998594 : function_state_->loop_nesting_depth_++;
433 : }
434 :
435 998680 : ~LoopScope() { function_state_->loop_nesting_depth_--; }
436 :
437 : private:
438 : FunctionState* function_state_;
439 : };
440 :
441 : int loop_nesting_depth() const { return loop_nesting_depth_; }
442 :
443 : private:
444 : // Properties count estimation.
445 : int expected_property_count_;
446 :
447 : // How many suspends are needed for this function.
448 : int suspend_count_;
449 :
450 : // How deeply nested we currently are in this function.
451 : int loop_nesting_depth_ = 0;
452 :
453 : FunctionState** function_state_stack_;
454 : FunctionState* outer_function_state_;
455 : DeclarationScope* scope_;
456 :
457 : // A reason, if any, why this function should not be optimized.
458 : BailoutReason dont_optimize_reason_;
459 :
460 : // Record whether the next (=== immediately following) function literal is
461 : // preceded by a parenthesis / exclamation mark. Also record the previous
462 : // state.
463 : // These are managed by the FunctionState constructor; the caller may only
464 : // call set_next_function_is_likely_called.
465 : bool next_function_is_likely_called_;
466 : bool previous_function_was_likely_called_;
467 :
468 : // Track if a function or eval occurs within this FunctionState
469 : bool contains_function_or_eval_;
470 :
471 : friend Impl;
472 : };
473 :
474 : struct DeclarationDescriptor {
475 : VariableMode mode;
476 : VariableKind kind;
477 : int declaration_pos;
478 : int initialization_pos;
479 : };
480 :
481 : struct DeclarationParsingResult {
482 : struct Declaration {
483 : Declaration(ExpressionT pattern, int initializer_position,
484 : ExpressionT initializer)
485 : : pattern(pattern),
486 : initializer_position(initializer_position),
487 14338024 : initializer(initializer) {}
488 :
489 : ExpressionT pattern;
490 : int initializer_position;
491 : int value_beg_position = kNoSourcePosition;
492 : ExpressionT initializer;
493 : };
494 :
495 : DeclarationParsingResult()
496 : : first_initializer_loc(Scanner::Location::invalid()),
497 14031481 : bindings_loc(Scanner::Location::invalid()) {}
498 :
499 : DeclarationDescriptor descriptor;
500 : std::vector<Declaration> declarations;
501 : Scanner::Location first_initializer_loc;
502 : Scanner::Location bindings_loc;
503 : };
504 :
505 : struct CatchInfo {
506 : public:
507 412325 : explicit CatchInfo(ParserBase* parser)
508 : : pattern(parser->impl()->NullExpression()),
509 : variable(nullptr),
510 412303 : scope(nullptr) {}
511 : ExpressionT pattern;
512 : Variable* variable;
513 : Scope* scope;
514 : };
515 :
516 : struct ForInfo {
517 : public:
518 942621 : explicit ForInfo(ParserBase* parser)
519 : : bound_names(1, parser->zone()),
520 : mode(ForEachStatement::ENUMERATE),
521 : position(kNoSourcePosition),
522 1885286 : parsing_result() {}
523 : ZonePtrList<const AstRawString> bound_names;
524 : ForEachStatement::VisitMode mode;
525 : int position;
526 : DeclarationParsingResult parsing_result;
527 : };
528 :
529 : struct ClassInfo {
530 : public:
531 308480 : explicit ClassInfo(ParserBase* parser)
532 : : variable(nullptr),
533 : extends(parser->impl()->NullExpression()),
534 : properties(parser->impl()->NewClassPropertyList(4)),
535 : static_fields(parser->impl()->NewClassPropertyList(4)),
536 : instance_fields(parser->impl()->NewClassPropertyList(4)),
537 : constructor(parser->impl()->NullExpression()),
538 : has_seen_constructor(false),
539 : has_name_static_property(false),
540 : has_static_computed_names(false),
541 : has_static_class_fields(false),
542 : has_instance_members(false),
543 : is_anonymous(false),
544 : static_fields_scope(nullptr),
545 : instance_members_scope(nullptr),
546 1106938 : computed_field_count(0) {}
547 : Variable* variable;
548 : ExpressionT extends;
549 : ClassPropertyListT properties;
550 : ClassPropertyListT static_fields;
551 : ClassPropertyListT instance_fields;
552 : FunctionLiteralT constructor;
553 :
554 : bool has_seen_constructor;
555 : bool has_name_static_property;
556 : bool has_static_computed_names;
557 : bool has_static_class_fields;
558 : bool has_instance_members;
559 : bool is_anonymous;
560 : DeclarationScope* static_fields_scope;
561 : DeclarationScope* instance_members_scope;
562 : int computed_field_count;
563 : };
564 :
565 : enum class PropertyPosition { kObjectLiteral, kClassLiteral };
566 : struct ParsePropertyInfo {
567 : public:
568 1959004 : explicit ParsePropertyInfo(ParserBase* parser,
569 : AccumulationScope* accumulation_scope = nullptr)
570 : : accumulation_scope(accumulation_scope),
571 : name(parser->impl()->NullIdentifier()),
572 : position(PropertyPosition::kClassLiteral),
573 : function_flags(ParseFunctionFlag::kIsNormal),
574 : kind(ParsePropertyKind::kNotSet),
575 : is_computed_name(false),
576 : is_private(false),
577 : is_static(false),
578 7459377 : is_rest(false) {}
579 :
580 5435286 : bool ParsePropertyKindFromToken(Token::Value token) {
581 : // This returns true, setting the property kind, iff the given token is
582 : // one which must occur after a property name, indicating that the
583 : // previous token was in fact a name and not a modifier (like the "get" in
584 : // "get x").
585 5435286 : switch (token) {
586 : case Token::COLON:
587 4506464 : kind = ParsePropertyKind::kValue;
588 : return true;
589 : case Token::COMMA:
590 70158 : kind = ParsePropertyKind::kShorthand;
591 : return true;
592 : case Token::RBRACE:
593 110956 : kind = ParsePropertyKind::kShorthandOrClassField;
594 : return true;
595 : case Token::ASSIGN:
596 72279 : kind = ParsePropertyKind::kAssign;
597 : return true;
598 : case Token::LPAREN:
599 396595 : kind = ParsePropertyKind::kMethod;
600 : return true;
601 : case Token::MUL:
602 : case Token::SEMICOLON:
603 20774 : kind = ParsePropertyKind::kClassField;
604 : return true;
605 : default:
606 : break;
607 : }
608 : return false;
609 : }
610 :
611 : AccumulationScope* accumulation_scope;
612 : IdentifierT name;
613 : PropertyPosition position;
614 : ParseFunctionFlags function_flags;
615 : ParsePropertyKind kind;
616 : bool is_computed_name;
617 : bool is_private;
618 : bool is_static;
619 : bool is_rest;
620 : };
621 :
622 461278 : ClassLiteralProperty::Kind ClassPropertyKindFor(ParsePropertyKind kind) {
623 461278 : switch (kind) {
624 : case ParsePropertyKind::kAccessorGetter:
625 : return ClassLiteralProperty::GETTER;
626 : case ParsePropertyKind::kAccessorSetter:
627 : return ClassLiteralProperty::SETTER;
628 : case ParsePropertyKind::kMethod:
629 : return ClassLiteralProperty::METHOD;
630 : case ParsePropertyKind::kClassField:
631 : return ClassLiteralProperty::FIELD;
632 : default:
633 : // Only returns for deterministic kinds
634 0 : UNREACHABLE();
635 : }
636 : }
637 :
638 9924 : const AstRawString* ClassFieldVariableName(AstValueFactory* ast_value_factory,
639 : int index) {
640 9923 : std::string name = ".class-field-" + std::to_string(index);
641 19846 : return ast_value_factory->GetOneByteString(name.c_str());
642 : }
643 :
644 2950612 : DeclarationScope* NewScriptScope() const {
645 2950600 : return new (zone()) DeclarationScope(zone(), ast_value_factory());
646 : }
647 :
648 158922 : DeclarationScope* NewVarblockScope() const {
649 158924 : return new (zone()) DeclarationScope(zone(), scope(), BLOCK_SCOPE);
650 : }
651 :
652 61571 : ModuleScope* NewModuleScope(DeclarationScope* parent) const {
653 61571 : return new (zone()) ModuleScope(parent, ast_value_factory());
654 : }
655 :
656 961938 : DeclarationScope* NewEvalScope(Scope* parent) const {
657 961938 : return new (zone()) DeclarationScope(zone(), parent, EVAL_SCOPE);
658 : }
659 :
660 1658571 : Scope* NewScope(ScopeType scope_type) const {
661 1658571 : return NewScopeWithParent(scope(), scope_type);
662 : }
663 :
664 : // This constructor should only be used when absolutely necessary. Most scopes
665 : // should automatically use scope() as parent, and be fine with
666 : // NewScope(ScopeType) above.
667 1354338 : Scope* NewScopeWithParent(Scope* parent, ScopeType scope_type) const {
668 : // Must always use the specific constructors for the blacklisted scope
669 : // types.
670 : DCHECK_NE(FUNCTION_SCOPE, scope_type);
671 : DCHECK_NE(SCRIPT_SCOPE, scope_type);
672 : DCHECK_NE(MODULE_SCOPE, scope_type);
673 : DCHECK_NOT_NULL(parent);
674 1354366 : return new (zone()) Scope(zone(), parent, scope_type);
675 : }
676 :
677 : // Creates a function scope that always allocates in zone(). The function
678 : // scope itself is either allocated in zone() or in target_zone if one is
679 : // passed in.
680 5451370 : DeclarationScope* NewFunctionScope(FunctionKind kind,
681 6115706 : Zone* parse_zone = nullptr) const {
682 : DCHECK(ast_value_factory());
683 5451370 : if (parse_zone == nullptr) parse_zone = zone();
684 : DeclarationScope* result = new (zone())
685 5451409 : DeclarationScope(parse_zone, scope(), FUNCTION_SCOPE, kind);
686 :
687 : // Record presence of an inner function scope
688 5451843 : function_state_->RecordFunctionOrEvalCall();
689 :
690 : // TODO(verwaest): Move into the DeclarationScope constructor.
691 5451843 : if (!IsArrowFunction(kind)) {
692 4401940 : result->DeclareDefaultFunctionVariables(ast_value_factory());
693 : }
694 5451844 : return result;
695 : }
696 :
697 3544279 : V8_INLINE DeclarationScope* GetDeclarationScope() const {
698 3553379 : return scope()->GetDeclarationScope();
699 : }
700 1766 : V8_INLINE DeclarationScope* GetClosureScope() const {
701 1766 : return scope()->GetClosureScope();
702 : }
703 :
704 : VariableProxy* NewRawVariable(const AstRawString* name, int pos) {
705 : return factory()->ast_node_factory()->NewVariableProxy(
706 71499954 : name, NORMAL_VARIABLE, pos);
707 : }
708 :
709 2751264069 : Scanner* scanner() const { return scanner_; }
710 118671283 : AstValueFactory* ast_value_factory() const { return ast_value_factory_; }
711 47250646 : int position() const { return scanner_->location().beg_pos; }
712 835292213 : int peek_position() const { return scanner_->peek_location().beg_pos; }
713 125663007 : int end_position() const { return scanner_->location().end_pos; }
714 49431 : int peek_end_position() const { return scanner_->peek_location().end_pos; }
715 5020564 : bool stack_overflow() const {
716 5020564 : return pending_error_handler()->stack_overflow();
717 : }
718 23104 : void set_stack_overflow() {
719 11552 : scanner_->set_parser_error();
720 : pending_error_handler()->set_stack_overflow();
721 11552 : }
722 113106414 : void CheckStackOverflow() {
723 : // Any further calls to Next or peek will return the illegal token.
724 113106414 : if (GetCurrentStackPosition() < stack_limit_) set_stack_overflow();
725 113106088 : }
726 : int script_id() { return script_id_; }
727 2459253 : void set_script_id(int id) { script_id_ = id; }
728 :
729 1966101349 : V8_INLINE Token::Value peek() { return scanner()->peek(); }
730 :
731 : // Returns the position past the following semicolon (if it exists), and the
732 : // position past the end of the current token otherwise.
733 193313 : int PositionAfterSemicolon() {
734 193312 : return (peek() == Token::SEMICOLON) ? peek_end_position() : end_position();
735 : }
736 :
737 1927144 : V8_INLINE Token::Value PeekAhead() { return scanner()->PeekAhead(); }
738 :
739 188054675 : V8_INLINE Token::Value Next() { return scanner()->Next(); }
740 :
741 193810228 : V8_INLINE void Consume(Token::Value token) {
742 197279769 : Token::Value next = scanner()->Next();
743 : USE(next);
744 : USE(token);
745 : DCHECK_IMPLIES(!has_error(), next == token);
746 : }
747 :
748 168093985 : V8_INLINE bool Check(Token::Value token) {
749 203348749 : Token::Value next = scanner()->peek();
750 203346090 : if (next == token) {
751 : Consume(next);
752 : return true;
753 : }
754 : return false;
755 : }
756 :
757 55461227 : void Expect(Token::Value token) {
758 : Token::Value next = Next();
759 55462767 : if (V8_UNLIKELY(next != token)) {
760 805135 : ReportUnexpectedToken(next);
761 : }
762 55462767 : }
763 :
764 40906155 : void ExpectSemicolon() {
765 : // Check for automatic semicolon insertion according to
766 : // the rules given in ECMA-262, section 7.9, page 21.
767 : Token::Value tok = peek();
768 37548278 : if (V8_LIKELY(tok == Token::SEMICOLON)) {
769 : Next();
770 : return;
771 : }
772 5773769 : if (V8_LIKELY(scanner()->HasLineTerminatorBeforeNext() ||
773 : Token::IsAutoSemicolon(tok))) {
774 : return;
775 : }
776 :
777 1190203 : if (scanner()->current_token() == Token::AWAIT && !is_async_function()) {
778 9 : ReportMessageAt(scanner()->location(),
779 9 : MessageTemplate::kAwaitNotInAsyncFunction, kSyntaxError);
780 9 : return;
781 : }
782 :
783 1190167 : ReportUnexpectedToken(Next());
784 : }
785 :
786 44636276 : bool peek_any_identifier() { return Token::IsAnyIdentifier(peek()); }
787 :
788 1340667 : bool PeekContextualKeyword(const AstRawString* name) {
789 : return peek() == Token::IDENTIFIER &&
790 1340674 : scanner()->NextSymbol(ast_value_factory()) == name;
791 : }
792 :
793 708743 : bool CheckContextualKeyword(const AstRawString* name) {
794 708743 : if (PeekContextualKeyword(name)) {
795 : Consume(Token::IDENTIFIER);
796 196996 : return true;
797 : }
798 : return false;
799 : }
800 :
801 : void ExpectMetaProperty(const AstRawString* property_name,
802 : const char* full_name, int pos);
803 :
804 271181 : void ExpectContextualKeyword(const AstRawString* name) {
805 133420 : Expect(Token::IDENTIFIER);
806 133421 : if (V8_UNLIKELY(scanner()->CurrentSymbol(ast_value_factory()) != name)) {
807 9060 : ReportUnexpectedToken(scanner()->current_token());
808 : }
809 133419 : }
810 :
811 1503630 : bool CheckInOrOf(ForEachStatement::VisitMode* visit_mode) {
812 797212 : if (Check(Token::IN)) {
813 90737 : *visit_mode = ForEachStatement::ENUMERATE;
814 90737 : return true;
815 1412950 : } else if (CheckContextualKeyword(ast_value_factory()->of_string())) {
816 196044 : *visit_mode = ForEachStatement::ITERATE;
817 196044 : return true;
818 : }
819 : return false;
820 : }
821 :
822 504910 : bool PeekInOrOf() {
823 : return peek() == Token::IN ||
824 743689 : PeekContextualKeyword(ast_value_factory()->of_string());
825 : }
826 :
827 : // Checks whether an octal literal was last seen between beg_pos and end_pos.
828 : // Only called for strict mode strings.
829 2660403 : void CheckStrictOctalLiteral(int beg_pos, int end_pos) {
830 : Scanner::Location octal = scanner()->octal_position();
831 2659081 : if (octal.IsValid() && beg_pos <= octal.beg_pos &&
832 : octal.end_pos <= end_pos) {
833 1322 : MessageTemplate message = scanner()->octal_message();
834 : DCHECK_NE(message, MessageTemplate::kNone);
835 1322 : impl()->ReportMessageAt(octal, message);
836 : scanner()->clear_octal_position();
837 1322 : if (message == MessageTemplate::kStrictDecimalWithLeadingZero) {
838 0 : impl()->CountUsage(v8::Isolate::kDecimalWithLeadingZeroInStrictMode);
839 : }
840 : }
841 2659081 : }
842 :
843 : // Checks if an octal literal or an invalid hex or unicode escape sequence
844 : // appears in the current template literal token. In the presence of such,
845 : // either returns false or reports an error, depending on should_throw.
846 : // Otherwise returns true.
847 166414 : inline bool CheckTemplateEscapes(bool should_throw) {
848 : DCHECK(Token::IsTemplate(scanner()->current_token()));
849 153405 : if (!scanner()->has_invalid_template_escape()) return true;
850 :
851 : // Handle error case(s)
852 13009 : if (should_throw) {
853 6358 : impl()->ReportMessageAt(scanner()->invalid_template_escape_location(),
854 : scanner()->invalid_template_escape_message());
855 : }
856 13009 : scanner()->clear_invalid_template_escape_message();
857 13009 : return should_throw;
858 : }
859 :
860 : ExpressionT ParsePossibleDestructuringSubPattern(AccumulationScope* scope);
861 : void ClassifyParameter(IdentifierT parameter, int beg_pos, int end_pos);
862 : void ClassifyArrowParameter(AccumulationScope* accumulation_scope,
863 : int position, ExpressionT parameter);
864 :
865 : // Checking the name of a function literal. This has to be done after parsing
866 : // the function, since the function can declare itself strict.
867 4138885 : void CheckFunctionName(LanguageMode language_mode, IdentifierT function_name,
868 : FunctionNameValidity function_name_validity,
869 : const Scanner::Location& function_name_loc) {
870 4138885 : if (impl()->IsNull(function_name)) return;
871 4072533 : if (function_name_validity == kSkipFunctionNameCheck) return;
872 : // The function name needs to be checked in strict mode.
873 3038792 : if (is_sloppy(language_mode)) return;
874 :
875 411727 : if (impl()->IsEvalOrArguments(function_name)) {
876 623 : impl()->ReportMessageAt(function_name_loc,
877 : MessageTemplate::kStrictEvalArguments);
878 343 : return;
879 : }
880 411104 : if (function_name_validity == kFunctionNameIsStrictReserved) {
881 1789 : impl()->ReportMessageAt(function_name_loc,
882 : MessageTemplate::kUnexpectedStrictReserved);
883 219 : return;
884 : }
885 : }
886 :
887 4291205 : typename Types::Factory* factory() { return &ast_node_factory_; }
888 :
889 36364 : DeclarationScope* GetReceiverScope() const {
890 36364 : return scope()->GetReceiverScope();
891 : }
892 52188001 : LanguageMode language_mode() { return scope()->language_mode(); }
893 1815142 : void RaiseLanguageMode(LanguageMode mode) {
894 : LanguageMode old = scope()->language_mode();
895 1815142 : impl()->SetLanguageMode(scope(), old > mode ? old : mode);
896 1815142 : }
897 353710 : bool is_generator() const {
898 707423 : return IsGeneratorFunction(function_state_->kind());
899 : }
900 112317258 : bool is_async_function() const {
901 224630126 : return IsAsyncFunction(function_state_->kind());
902 : }
903 : bool is_async_generator() const {
904 : return IsAsyncGeneratorFunction(function_state_->kind());
905 : }
906 : bool is_resumable() const {
907 : return IsResumableFunction(function_state_->kind());
908 : }
909 :
910 : const PendingCompilationErrorHandler* pending_error_handler() const {
911 : return pending_error_handler_;
912 : }
913 : PendingCompilationErrorHandler* pending_error_handler() {
914 : return pending_error_handler_;
915 : }
916 :
917 : // Report syntax errors.
918 18400 : V8_NOINLINE void ReportMessage(MessageTemplate message) {
919 18400 : Scanner::Location source_location = scanner()->location();
920 18400 : impl()->ReportMessageAt(source_location, message,
921 : static_cast<const char*>(nullptr), kSyntaxError);
922 18400 : }
923 :
924 : template <typename T>
925 635 : V8_NOINLINE void ReportMessage(MessageTemplate message, T arg,
926 635 : ParseErrorType error_type = kSyntaxError) {
927 635 : Scanner::Location source_location = scanner()->location();
928 635 : impl()->ReportMessageAt(source_location, message, arg, error_type);
929 635 : }
930 :
931 25707 : V8_NOINLINE void ReportMessageAt(Scanner::Location location,
932 : MessageTemplate message,
933 : ParseErrorType error_type) {
934 25707 : impl()->ReportMessageAt(location, message,
935 : static_cast<const char*>(nullptr), error_type);
936 25707 : }
937 :
938 : V8_NOINLINE void ReportUnexpectedToken(Token::Value token);
939 : V8_NOINLINE void ReportUnexpectedTokenAt(
940 : Scanner::Location location, Token::Value token,
941 : MessageTemplate message = MessageTemplate::kUnexpectedToken);
942 :
943 5031754 : void ValidateFormalParameters(LanguageMode language_mode,
944 : const FormalParametersT& parameters,
945 : bool allow_duplicates) {
946 5031754 : if (!allow_duplicates) parameters.ValidateDuplicate(impl());
947 5031751 : if (is_strict(language_mode)) parameters.ValidateStrictMode(impl());
948 5031757 : }
949 :
950 : V8_INLINE IdentifierT ParseAndClassifyIdentifier(Token::Value token);
951 : // Parses an identifier or a strict mode future reserved word. Allows passing
952 : // in function_kind for the case of parsing the identifier in a function
953 : // expression, where the relevant "function_kind" bit is of the function being
954 : // parsed, not the containing function.
955 : V8_INLINE IdentifierT ParseIdentifier(FunctionKind function_kind);
956 : V8_INLINE IdentifierT ParseIdentifier() {
957 1848935 : return ParseIdentifier(function_state_->kind());
958 : }
959 : // Same as above but additionally disallows 'eval' and 'arguments' in strict
960 : // mode.
961 : IdentifierT ParseNonRestrictedIdentifier();
962 :
963 : V8_INLINE IdentifierT ParsePropertyName();
964 :
965 : ExpressionT ParsePropertyOrPrivatePropertyName();
966 :
967 : ExpressionT ParseRegExpLiteral();
968 :
969 : ExpressionT ParseBindingPattern();
970 : ExpressionT ParsePrimaryExpression();
971 :
972 : // Use when parsing an expression that is known to not be a pattern or part of
973 : // a pattern.
974 : V8_INLINE ExpressionT ParseExpression();
975 : V8_INLINE ExpressionT ParseAssignmentExpression();
976 :
977 : // These methods do not wrap the parsing of the expression inside a new
978 : // expression_scope; they use the outer expression_scope instead. They should
979 : // be used whenever we're parsing something with the "cover" grammar that
980 : // recognizes both patterns and non-patterns (which roughly corresponds to
981 : // what's inside the parentheses generated by the symbol
982 : // "CoverParenthesizedExpressionAndArrowParameterList" in the ES 2017
983 : // specification).
984 : ExpressionT ParseExpressionCoverGrammar();
985 : ExpressionT ParseAssignmentExpressionCoverGrammar();
986 :
987 : ExpressionT ParseArrowParametersWithRest(ExpressionListT* list,
988 : AccumulationScope* scope);
989 :
990 : ExpressionT ParseArrayLiteral();
991 :
992 : inline static bool IsAccessor(ParsePropertyKind kind) {
993 : return IsInRange(kind, ParsePropertyKind::kAccessorGetter,
994 : ParsePropertyKind::kAccessorSetter);
995 : }
996 :
997 : ExpressionT ParseProperty(ParsePropertyInfo* prop_info);
998 : ExpressionT ParseObjectLiteral();
999 : ClassLiteralPropertyT ParseClassPropertyDefinition(
1000 : ClassInfo* class_info, ParsePropertyInfo* prop_info, bool has_extends);
1001 : void CheckClassFieldName(IdentifierT name, bool is_static);
1002 : void CheckClassMethodName(IdentifierT name, ParsePropertyKind type,
1003 : ParseFunctionFlags flags, bool is_static,
1004 : bool* has_seen_constructor);
1005 : ExpressionT ParseMemberInitializer(ClassInfo* class_info, int beg_pos,
1006 : bool is_static);
1007 : ObjectLiteralPropertyT ParseObjectPropertyDefinition(
1008 : ParsePropertyInfo* prop_info, bool* has_seen_proto);
1009 : void ParseArguments(
1010 : ExpressionListT* args, bool* has_spread,
1011 : ParsingArrowHeadFlag maybe_arrow = kCertainlyNotArrowHead);
1012 :
1013 : ExpressionT ParseYieldExpression();
1014 : V8_INLINE ExpressionT ParseConditionalExpression();
1015 : ExpressionT ParseConditionalContinuation(ExpressionT expression, int pos);
1016 : ExpressionT ParseBinaryContinuation(ExpressionT x, int prec, int prec1);
1017 : V8_INLINE ExpressionT ParseBinaryExpression(int prec);
1018 : ExpressionT ParseUnaryOrPrefixExpression();
1019 : ExpressionT ParseAwaitExpression();
1020 : V8_INLINE ExpressionT ParseUnaryExpression();
1021 : V8_INLINE ExpressionT ParsePostfixExpression();
1022 : V8_INLINE ExpressionT ParseLeftHandSideExpression();
1023 : ExpressionT ParseLeftHandSideContinuation(ExpressionT expression);
1024 : ExpressionT ParseMemberWithPresentNewPrefixesExpression();
1025 : V8_INLINE ExpressionT ParseMemberWithNewPrefixesExpression();
1026 : ExpressionT ParseFunctionExpression();
1027 : V8_INLINE ExpressionT ParseMemberExpression();
1028 : V8_INLINE ExpressionT
1029 : ParseMemberExpressionContinuation(ExpressionT expression) {
1030 107491725 : if (!Token::IsMember(peek())) return expression;
1031 16894108 : return DoParseMemberExpressionContinuation(expression);
1032 : }
1033 : ExpressionT DoParseMemberExpressionContinuation(ExpressionT expression);
1034 :
1035 : ExpressionT ParseArrowFunctionLiteral(const FormalParametersT& parameters);
1036 : void ParseAsyncFunctionBody(Scope* scope, StatementListT* body);
1037 : ExpressionT ParseAsyncFunctionLiteral();
1038 : ExpressionT ParseClassLiteral(IdentifierT name,
1039 : Scanner::Location class_name_location,
1040 : bool name_is_strict_reserved,
1041 : int class_token_pos);
1042 : ExpressionT ParseTemplateLiteral(ExpressionT tag, int start, bool tagged);
1043 : ExpressionT ParseSuperExpression(bool is_new);
1044 : ExpressionT ParseImportExpressions();
1045 : ExpressionT ParseNewTargetExpression();
1046 :
1047 : V8_INLINE void ParseFormalParameter(FormalParametersT* parameters);
1048 : void ParseFormalParameterList(FormalParametersT* parameters);
1049 : void CheckArityRestrictions(int param_count, FunctionKind function_type,
1050 : bool has_rest, int formals_start_pos,
1051 : int formals_end_pos);
1052 :
1053 : void ParseVariableDeclarations(VariableDeclarationContext var_context,
1054 : DeclarationParsingResult* parsing_result);
1055 : StatementT ParseAsyncFunctionDeclaration(
1056 : ZonePtrList<const AstRawString>* names, bool default_export);
1057 : StatementT ParseFunctionDeclaration();
1058 : StatementT ParseHoistableDeclaration(ZonePtrList<const AstRawString>* names,
1059 : bool default_export);
1060 : StatementT ParseHoistableDeclaration(int pos, ParseFunctionFlags flags,
1061 : ZonePtrList<const AstRawString>* names,
1062 : bool default_export);
1063 : StatementT ParseClassDeclaration(ZonePtrList<const AstRawString>* names,
1064 : bool default_export);
1065 : StatementT ParseNativeDeclaration();
1066 :
1067 : // Whether we're parsing a single-expression arrow function or something else.
1068 : enum class FunctionBodyType { kExpression, kBlock };
1069 : // Consumes the ending }.
1070 : void ParseFunctionBody(StatementListT* body, IdentifierT function_name,
1071 : int pos, const FormalParametersT& parameters,
1072 : FunctionKind kind,
1073 : FunctionLiteral::FunctionType function_type,
1074 : FunctionBodyType body_type);
1075 :
1076 : // TODO(nikolaos, marja): The first argument should not really be passed
1077 : // by value. The method is expected to add the parsed statements to the
1078 : // list. This works because in the case of the parser, StatementListT is
1079 : // a pointer whereas the preparser does not really modify the body.
1080 : V8_INLINE void ParseStatementList(StatementListT* body,
1081 : Token::Value end_token);
1082 : StatementT ParseStatementListItem();
1083 :
1084 : StatementT ParseStatement(ZonePtrList<const AstRawString>* labels,
1085 : ZonePtrList<const AstRawString>* own_labels) {
1086 : return ParseStatement(labels, own_labels,
1087 4791542 : kDisallowLabelledFunctionStatement);
1088 : }
1089 : StatementT ParseStatement(ZonePtrList<const AstRawString>* labels,
1090 : ZonePtrList<const AstRawString>* own_labels,
1091 : AllowLabelledFunctionStatement allow_function);
1092 : BlockT ParseBlock(ZonePtrList<const AstRawString>* labels);
1093 :
1094 : // Parse a SubStatement in strict mode, or with an extra block scope in
1095 : // sloppy mode to handle
1096 : // ES#sec-functiondeclarations-in-ifstatement-statement-clauses
1097 : StatementT ParseScopedStatement(ZonePtrList<const AstRawString>* labels);
1098 :
1099 : StatementT ParseVariableStatement(VariableDeclarationContext var_context,
1100 : ZonePtrList<const AstRawString>* names);
1101 :
1102 : // Magical syntax support.
1103 : ExpressionT ParseV8Intrinsic();
1104 :
1105 : StatementT ParseDebuggerStatement();
1106 :
1107 : StatementT ParseExpressionOrLabelledStatement(
1108 : ZonePtrList<const AstRawString>* labels,
1109 : ZonePtrList<const AstRawString>* own_labels,
1110 : AllowLabelledFunctionStatement allow_function);
1111 : StatementT ParseIfStatement(ZonePtrList<const AstRawString>* labels);
1112 : StatementT ParseContinueStatement();
1113 : StatementT ParseBreakStatement(ZonePtrList<const AstRawString>* labels);
1114 : StatementT ParseReturnStatement();
1115 : StatementT ParseWithStatement(ZonePtrList<const AstRawString>* labels);
1116 : StatementT ParseDoWhileStatement(ZonePtrList<const AstRawString>* labels,
1117 : ZonePtrList<const AstRawString>* own_labels);
1118 : StatementT ParseWhileStatement(ZonePtrList<const AstRawString>* labels,
1119 : ZonePtrList<const AstRawString>* own_labels);
1120 : StatementT ParseThrowStatement();
1121 : StatementT ParseSwitchStatement(ZonePtrList<const AstRawString>* labels);
1122 : V8_INLINE StatementT ParseTryStatement();
1123 : StatementT ParseForStatement(ZonePtrList<const AstRawString>* labels,
1124 : ZonePtrList<const AstRawString>* own_labels);
1125 : StatementT ParseForEachStatementWithDeclarations(
1126 : int stmt_pos, ForInfo* for_info, ZonePtrList<const AstRawString>* labels,
1127 : ZonePtrList<const AstRawString>* own_labels, Scope* inner_block_scope);
1128 : StatementT ParseForEachStatementWithoutDeclarations(
1129 : int stmt_pos, ExpressionT expression, int lhs_beg_pos, int lhs_end_pos,
1130 : ForInfo* for_info, ZonePtrList<const AstRawString>* labels,
1131 : ZonePtrList<const AstRawString>* own_labels);
1132 :
1133 : // Parse a C-style for loop: 'for (<init>; <cond>; <next>) { ... }'
1134 : // "for (<init>;" is assumed to have been parser already.
1135 : ForStatementT ParseStandardForLoop(
1136 : int stmt_pos, ZonePtrList<const AstRawString>* labels,
1137 : ZonePtrList<const AstRawString>* own_labels, ExpressionT* cond,
1138 : StatementT* next, StatementT* body);
1139 : // Same as the above, but handles those cases where <init> is a
1140 : // lexical variable declaration.
1141 : StatementT ParseStandardForLoopWithLexicalDeclarations(
1142 : int stmt_pos, StatementT init, ForInfo* for_info,
1143 : ZonePtrList<const AstRawString>* labels,
1144 : ZonePtrList<const AstRawString>* own_labels);
1145 : StatementT ParseForAwaitStatement(
1146 : ZonePtrList<const AstRawString>* labels,
1147 : ZonePtrList<const AstRawString>* own_labels);
1148 :
1149 : bool IsNextLetKeyword();
1150 :
1151 : // Checks if the expression is a valid reference expression (e.g., on the
1152 : // left-hand side of assignments). Although ruled out by ECMA as early errors,
1153 : // we allow calls for web compatibility and rewrite them to a runtime throw.
1154 : ExpressionT RewriteInvalidReferenceExpression(
1155 : ExpressionT expression, int beg_pos, int end_pos, MessageTemplate message,
1156 : ParseErrorType type = kReferenceError);
1157 :
1158 : bool IsValidReferenceExpression(ExpressionT expression);
1159 :
1160 25835299 : bool IsAssignableIdentifier(ExpressionT expression) {
1161 25835368 : if (!impl()->IsIdentifier(expression)) return false;
1162 7533977 : if (is_strict(language_mode()) &&
1163 : impl()->IsEvalOrArguments(impl()->AsIdentifier(expression))) {
1164 : return false;
1165 : }
1166 3080051 : return true;
1167 : }
1168 :
1169 : FunctionKind FunctionKindForImpl(bool is_method, ParseFunctionFlags flags) {
1170 : static const FunctionKind kFunctionKinds[][2][2] = {
1171 : {
1172 : // is_method=false
1173 : {// is_generator=false
1174 : FunctionKind::kNormalFunction, FunctionKind::kAsyncFunction},
1175 : {// is_generator=true
1176 : FunctionKind::kGeneratorFunction,
1177 : FunctionKind::kAsyncGeneratorFunction},
1178 : },
1179 : {
1180 : // is_method=true
1181 : {// is_generator=false
1182 : FunctionKind::kConciseMethod, FunctionKind::kAsyncConciseMethod},
1183 : {// is_generator=true
1184 : FunctionKind::kConciseGeneratorMethod,
1185 : FunctionKind::kAsyncConciseGeneratorMethod},
1186 : }};
1187 : return kFunctionKinds[is_method]
1188 : [(flags & ParseFunctionFlag::kIsGenerator) != 0]
1189 3282866 : [(flags & ParseFunctionFlag::kIsAsync) != 0];
1190 : }
1191 :
1192 : inline FunctionKind FunctionKindFor(ParseFunctionFlags flags) {
1193 : const bool kIsMethod = false;
1194 : return FunctionKindForImpl(kIsMethod, flags);
1195 : }
1196 :
1197 : inline FunctionKind MethodKindFor(ParseFunctionFlags flags) {
1198 : const bool kIsMethod = true;
1199 : return FunctionKindForImpl(kIsMethod, flags);
1200 : }
1201 :
1202 : // Keep track of eval() calls since they disable all local variable
1203 : // optimizations. This checks if expression is an eval call, and if yes,
1204 : // forwards the information to scope.
1205 12932679 : Call::PossiblyEval CheckPossibleEvalCall(ExpressionT expression,
1206 : Scope* scope) {
1207 21594552 : if (impl()->IsIdentifier(expression) &&
1208 : impl()->IsEval(impl()->AsIdentifier(expression))) {
1209 : scope->RecordInnerScopeEvalCall();
1210 252756 : function_state_->RecordFunctionOrEvalCall();
1211 252756 : if (is_sloppy(scope->language_mode())) {
1212 : // For sloppy scopes we also have to record the call at function level,
1213 : // in case it includes declarations that will be hoisted.
1214 177316 : scope->GetDeclarationScope()->RecordEvalCall();
1215 : }
1216 :
1217 : // This call is only necessary to track evals that may be
1218 : // inside arrow function parameter lists. In that case,
1219 : // Scope::Snapshot::Reparent will move this bit down into
1220 : // the arrow function's scope.
1221 : scope->RecordEvalCall();
1222 :
1223 252753 : return Call::IS_POSSIBLY_EVAL;
1224 : }
1225 : return Call::NOT_EVAL;
1226 : }
1227 :
1228 : // Convenience method which determines the type of return statement to emit
1229 : // depending on the current function type.
1230 4207084 : inline StatementT BuildReturnStatement(ExpressionT expr, int pos,
1231 8094249 : int end_pos = kNoSourcePosition) {
1232 4207086 : if (impl()->IsNull(expr)) {
1233 46456 : expr = factory()->NewUndefinedLiteral(kNoSourcePosition);
1234 3887162 : } else if (is_async_generator()) {
1235 : // In async generators, if there is an explicit operand to the return
1236 : // statement, await the operand.
1237 25063 : expr = factory()->NewAwait(expr, kNoSourcePosition);
1238 26219 : function_state_->AddSuspend();
1239 : }
1240 4207109 : if (is_async_function()) {
1241 58694 : return factory()->NewAsyncReturnStatement(expr, pos, end_pos);
1242 : }
1243 2796882 : return factory()->NewReturnStatement(expr, pos, end_pos);
1244 : }
1245 :
1246 57160 : ModuleDescriptor* module() const {
1247 57160 : return scope()->AsModuleScope()->module();
1248 : }
1249 8701001 : Scope* scope() const { return scope_; }
1250 :
1251 : // Stack of expression expression_scopes.
1252 : // The top of the stack is always pointed to by expression_scope().
1253 : V8_INLINE ExpressionScope* expression_scope() const {
1254 : DCHECK_NOT_NULL(expression_scope_);
1255 : return expression_scope_;
1256 : }
1257 :
1258 : class AcceptINScope final {
1259 : public:
1260 29489992 : AcceptINScope(ParserBase* parser, bool accept_IN)
1261 83115488 : : parser_(parser), previous_accept_IN_(parser->accept_IN_) {
1262 83115488 : parser_->accept_IN_ = accept_IN;
1263 29489992 : }
1264 :
1265 73677480 : ~AcceptINScope() { parser_->accept_IN_ = previous_accept_IN_; }
1266 :
1267 : private:
1268 : ParserBase* parser_;
1269 : bool previous_accept_IN_;
1270 : };
1271 :
1272 : class ParameterParsingScope {
1273 : public:
1274 : ParameterParsingScope(Impl* parser, FormalParametersT* parameters)
1275 4311557 : : parser_(parser), parent_parameters_(parser_->parameters_) {
1276 4311557 : parser_->parameters_ = parameters;
1277 : }
1278 :
1279 4311542 : ~ParameterParsingScope() { parser_->parameters_ = parent_parameters_; }
1280 :
1281 : private:
1282 : Impl* parser_;
1283 : FormalParametersT* parent_parameters_;
1284 : };
1285 :
1286 : class FunctionBodyParsingScope {
1287 : public:
1288 : explicit FunctionBodyParsingScope(Impl* parser)
1289 : : parser_(parser), expression_scope_(parser_->expression_scope_) {
1290 : parser_->expression_scope_ = nullptr;
1291 : }
1292 :
1293 : ~FunctionBodyParsingScope() {
1294 : parser_->expression_scope_ = expression_scope_;
1295 : }
1296 :
1297 : private:
1298 : Impl* parser_;
1299 : ExpressionScope* expression_scope_;
1300 : };
1301 :
1302 91828 : std::vector<void*>* pointer_buffer() { return &pointer_buffer_; }
1303 : std::vector<void*>* variable_buffer() { return &variable_buffer_; }
1304 :
1305 : // Parser base's protected field members.
1306 :
1307 : Scope* scope_; // Scope stack.
1308 : Scope* original_scope_; // The top scope for the current parsing item.
1309 : FunctionState* function_state_; // Function state stack.
1310 : v8::Extension* extension_;
1311 : FuncNameInferrer fni_;
1312 : AstValueFactory* ast_value_factory_; // Not owned.
1313 : typename Types::Factory ast_node_factory_;
1314 : RuntimeCallStats* runtime_call_stats_;
1315 : internal::Logger* logger_;
1316 : bool parsing_on_main_thread_;
1317 : const bool parsing_module_;
1318 : uintptr_t stack_limit_;
1319 : PendingCompilationErrorHandler* pending_error_handler_;
1320 :
1321 : // Parser base's private field members.
1322 :
1323 : private:
1324 : Zone* zone_;
1325 : ExpressionScope* expression_scope_;
1326 :
1327 : std::vector<void*> pointer_buffer_;
1328 : std::vector<void*> variable_buffer_;
1329 :
1330 : Scanner* scanner_;
1331 :
1332 : int function_literal_id_;
1333 : int script_id_;
1334 :
1335 : FunctionLiteral::EagerCompileHint default_eager_compile_hint_;
1336 :
1337 : // This struct is used to move information about the next arrow function from
1338 : // the place where the arrow head was parsed to where the body will be parsed.
1339 : // Nothing can be parsed between the head and the body, so it will be consumed
1340 : // immediately after it's produced.
1341 : // Preallocating the struct as part of the parser minimizes the cost of
1342 : // supporting arrow functions on non-arrow expressions.
1343 3351358 : struct NextArrowFunctionInfo {
1344 : Scanner::Location strict_parameter_error_location =
1345 : Scanner::Location::invalid();
1346 : MessageTemplate strict_parameter_error_message = MessageTemplate::kNone;
1347 : DeclarationScope* scope = nullptr;
1348 :
1349 : bool HasInitialState() const { return scope == nullptr; }
1350 :
1351 : void Reset() {
1352 831330 : scope = nullptr;
1353 : ClearStrictParameterError();
1354 : DCHECK(HasInitialState());
1355 : }
1356 :
1357 : // Tracks strict-mode parameter violations of sloppy-mode arrow heads in
1358 : // case the function ends up becoming strict mode. Only one global place to
1359 : // track this is necessary since arrow functions with none-simple parameters
1360 : // cannot become strict-mode later on.
1361 : void ClearStrictParameterError() {
1362 3773235 : strict_parameter_error_location = Scanner::Location::invalid();
1363 3773235 : strict_parameter_error_message = MessageTemplate::kNone;
1364 : }
1365 : };
1366 :
1367 : FormalParametersT* parameters_;
1368 : NextArrowFunctionInfo next_arrow_function_info_;
1369 :
1370 : bool accept_IN_ = true;
1371 :
1372 : bool allow_natives_;
1373 : bool allow_harmony_public_fields_;
1374 : bool allow_harmony_static_fields_;
1375 : bool allow_harmony_dynamic_import_;
1376 : bool allow_harmony_import_meta_;
1377 : bool allow_harmony_private_fields_;
1378 : bool allow_harmony_private_methods_;
1379 : bool allow_eval_cache_;
1380 : };
1381 :
1382 : template <typename Impl>
1383 52975 : ParserBase<Impl>::FunctionState::FunctionState(
1384 : FunctionState** function_state_stack, Scope** scope_stack,
1385 : DeclarationScope* scope)
1386 : : BlockState(scope_stack, scope),
1387 : expected_property_count_(0),
1388 : suspend_count_(0),
1389 : function_state_stack_(function_state_stack),
1390 : outer_function_state_(*function_state_stack),
1391 : scope_(scope),
1392 : dont_optimize_reason_(BailoutReason::kNoReason),
1393 : next_function_is_likely_called_(false),
1394 : previous_function_was_likely_called_(false),
1395 11108476 : contains_function_or_eval_(false) {
1396 11108476 : *function_state_stack = this;
1397 11108476 : if (outer_function_state_) {
1398 5711722 : outer_function_state_->previous_function_was_likely_called_ =
1399 : outer_function_state_->next_function_is_likely_called_;
1400 5711722 : outer_function_state_->next_function_is_likely_called_ = false;
1401 : }
1402 52975 : }
1403 :
1404 : template <typename Impl>
1405 52975 : ParserBase<Impl>::FunctionState::~FunctionState() {
1406 11108551 : *function_state_stack_ = outer_function_state_;
1407 52975 : }
1408 :
1409 : template <typename Impl>
1410 3319106 : void ParserBase<Impl>::ReportUnexpectedToken(Token::Value token) {
1411 5078496 : return ReportUnexpectedTokenAt(scanner_->location(), token);
1412 : }
1413 :
1414 : template <typename Impl>
1415 3328162 : void ParserBase<Impl>::ReportUnexpectedTokenAt(
1416 : Scanner::Location source_location, Token::Value token,
1417 : MessageTemplate message) {
1418 1763886 : const char* arg = nullptr;
1419 1763886 : impl()->GetUnexpectedTokenMessage(token, &message, &source_location, &arg);
1420 : if (Impl::IsPreParser()) {
1421 : impl()->ReportUnidentifiableError();
1422 : } else {
1423 1763886 : impl()->ReportMessageAt(source_location, message, arg);
1424 : }
1425 3328162 : }
1426 :
1427 : template <typename Impl>
1428 : typename ParserBase<Impl>::IdentifierT
1429 255959 : ParserBase<Impl>::ParseAndClassifyIdentifier(Token::Value next) {
1430 : DCHECK_EQ(scanner()->current_token(), next);
1431 : STATIC_ASSERT(Token::IDENTIFIER + 1 == Token::ASYNC);
1432 71339530 : if (V8_LIKELY(IsInRange(next, Token::IDENTIFIER, Token::ASYNC))) {
1433 71239115 : IdentifierT name = impl()->GetSymbol();
1434 71341827 : if (V8_UNLIKELY(impl()->IsArguments(name) &&
1435 : scope()->ShouldBanArguments())) {
1436 5600 : ReportMessage(MessageTemplate::kArgumentsDisallowedInInitializer);
1437 : return impl()->EmptyIdentifierString();
1438 : }
1439 38446357 : return name;
1440 : }
1441 :
1442 200104 : if (!Token::IsValidIdentifier(next, language_mode(), is_generator(),
1443 237328 : parsing_module_ || is_async_function())) {
1444 34155 : ReportUnexpectedToken(next);
1445 16025 : return impl()->EmptyIdentifierString();
1446 : }
1447 :
1448 65897 : if (next == Token::AWAIT) {
1449 44674 : expression_scope()->RecordAsyncArrowParametersError(
1450 : scanner()->location(), MessageTemplate::kAwaitBindingIdentifier);
1451 22337 : return impl()->GetSymbol();
1452 : }
1453 :
1454 : DCHECK(Token::IsStrictReservedWord(next));
1455 87120 : expression_scope()->RecordStrictModeParameterError(
1456 : scanner()->location(), MessageTemplate::kUnexpectedStrictReserved);
1457 43560 : return impl()->GetSymbol();
1458 : }
1459 :
1460 : template <class Impl>
1461 : typename ParserBase<Impl>::IdentifierT ParserBase<Impl>::ParseIdentifier(
1462 : FunctionKind function_kind) {
1463 : Token::Value next = Next();
1464 :
1465 2761560 : if (!Token::IsValidIdentifier(
1466 2761605 : next, language_mode(), IsGeneratorFunction(function_kind),
1467 5523300 : parsing_module_ || IsAsyncFunction(function_kind))) {
1468 9879 : ReportUnexpectedToken(next);
1469 5514 : return impl()->EmptyIdentifierString();
1470 : }
1471 :
1472 2751681 : return impl()->GetSymbol();
1473 : }
1474 :
1475 : template <typename Impl>
1476 : typename ParserBase<Impl>::IdentifierT
1477 364635 : ParserBase<Impl>::ParseNonRestrictedIdentifier() {
1478 : IdentifierT result = ParseIdentifier();
1479 :
1480 381757 : if (is_strict(language_mode()) &&
1481 17407 : V8_UNLIKELY(impl()->IsEvalOrArguments(result))) {
1482 286 : impl()->ReportMessageAt(scanner()->location(),
1483 : MessageTemplate::kStrictEvalArguments);
1484 : }
1485 :
1486 364350 : return result;
1487 : }
1488 :
1489 : template <typename Impl>
1490 : typename ParserBase<Impl>::IdentifierT ParserBase<Impl>::ParsePropertyName() {
1491 : Token::Value next = Next();
1492 279431 : if (V8_LIKELY(Token::IsPropertyName(next))) return impl()->GetSymbol();
1493 :
1494 149397 : ReportUnexpectedToken(next);
1495 69726 : return impl()->EmptyIdentifierString();
1496 : }
1497 :
1498 : template <typename Impl>
1499 : typename ParserBase<Impl>::ExpressionT
1500 14491593 : ParserBase<Impl>::ParsePropertyOrPrivatePropertyName() {
1501 : int pos = position();
1502 : IdentifierT name;
1503 : ExpressionT key;
1504 : Token::Value next = Next();
1505 14491898 : if (V8_LIKELY(Token::IsPropertyName(next))) {
1506 8901073 : name = impl()->GetSymbol();
1507 14479162 : key = factory()->NewStringLiteral(name, pos);
1508 13500 : } else if (allow_harmony_private_fields() && next == Token::PRIVATE_NAME) {
1509 3248 : name = impl()->GetSymbol();
1510 3248 : key = impl()->ExpressionFromIdentifier(name, pos, InferName::kNo);
1511 : } else {
1512 7397 : ReportUnexpectedToken(next);
1513 7397 : return impl()->FailureExpression();
1514 : }
1515 : impl()->PushLiteralName(name);
1516 14485278 : return key;
1517 : }
1518 :
1519 : template <typename Impl>
1520 160662 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseRegExpLiteral() {
1521 : int pos = peek_position();
1522 80445 : if (!scanner()->ScanRegExpPattern()) {
1523 : Next();
1524 279 : ReportMessage(MessageTemplate::kUnterminatedRegExp);
1525 279 : return impl()->FailureExpression();
1526 : }
1527 :
1528 : IdentifierT js_pattern = impl()->GetNextSymbol();
1529 80217 : Maybe<RegExp::Flags> flags = scanner()->ScanRegExpFlags();
1530 80218 : if (flags.IsNothing()) {
1531 : Next();
1532 610 : ReportMessage(MessageTemplate::kMalformedRegExpFlags);
1533 610 : return impl()->FailureExpression();
1534 : }
1535 48736 : int js_flags = flags.FromJust();
1536 : Next();
1537 97472 : return factory()->NewRegExpLiteral(js_pattern, js_flags, pos);
1538 : }
1539 :
1540 : template <typename Impl>
1541 22004386 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseBindingPattern() {
1542 : // Pattern ::
1543 : // Identifier
1544 : // ArrayLiteral
1545 : // ObjectLiteral
1546 :
1547 : int beg_pos = peek_position();
1548 : Token::Value token = peek();
1549 : ExpressionT result;
1550 :
1551 22000914 : if (Token::IsAnyIdentifier(token)) {
1552 8564041 : IdentifierT name = ParseAndClassifyIdentifier(Next());
1553 24020992 : if (V8_UNLIKELY(is_strict(language_mode()) &&
1554 : impl()->IsEvalOrArguments(name))) {
1555 3759 : impl()->ReportMessageAt(scanner()->location(),
1556 : MessageTemplate::kStrictEvalArguments);
1557 3759 : return impl()->FailureExpression();
1558 : }
1559 21718875 : return impl()->ExpressionFromIdentifier(name, beg_pos);
1560 : }
1561 :
1562 278553 : CheckStackOverflow();
1563 :
1564 278553 : if (token == Token::LBRACK) {
1565 58516 : result = ParseArrayLiteral();
1566 220037 : } else if (token == Token::LBRACE) {
1567 172270 : result = ParseObjectLiteral();
1568 : } else {
1569 47767 : ReportUnexpectedToken(Next());
1570 47767 : return impl()->FailureExpression();
1571 : }
1572 :
1573 230784 : return result;
1574 : }
1575 :
1576 : template <typename Impl>
1577 : typename ParserBase<Impl>::ExpressionT
1578 213555957 : ParserBase<Impl>::ParsePrimaryExpression() {
1579 104940813 : CheckStackOverflow();
1580 :
1581 : // PrimaryExpression ::
1582 : // 'this'
1583 : // 'null'
1584 : // 'true'
1585 : // 'false'
1586 : // Identifier
1587 : // Number
1588 : // String
1589 : // ArrayLiteral
1590 : // ObjectLiteral
1591 : // RegExpLiteral
1592 : // ClassLiteral
1593 : // '(' Expression ')'
1594 : // TemplateLiteral
1595 : // do Block
1596 : // AsyncFunctionLiteral
1597 :
1598 : int beg_pos = peek_position();
1599 : Token::Value token = peek();
1600 :
1601 104989816 : if (Token::IsAnyIdentifier(token)) {
1602 : Consume(token);
1603 :
1604 : FunctionKind kind = FunctionKind::kArrowFunction;
1605 :
1606 49664163 : if (V8_UNLIKELY(token == Token::ASYNC &&
1607 : !scanner()->HasLineTerminatorBeforeNext())) {
1608 : // async function ...
1609 43554 : if (peek() == Token::FUNCTION) return ParseAsyncFunctionLiteral();
1610 :
1611 : // async Identifier => ...
1612 23016 : if (peek_any_identifier() && PeekAhead() == Token::ARROW) {
1613 : token = Next();
1614 : beg_pos = position();
1615 : kind = FunctionKind::kAsyncArrowFunction;
1616 : }
1617 : }
1618 :
1619 49599185 : if (V8_UNLIKELY(peek() == Token::ARROW)) {
1620 : ArrowHeadParsingScope parsing_scope(impl(), kind);
1621 234556 : IdentifierT name = ParseAndClassifyIdentifier(token);
1622 293938 : ClassifyParameter(name, beg_pos, end_position());
1623 293929 : next_arrow_function_info_.scope = parsing_scope.ValidateAndCreateScope();
1624 : FunctionState function_state(&function_state_, &scope_,
1625 293944 : next_arrow_function_info_.scope);
1626 234560 : return impl()->ExpressionFromIdentifier(name, beg_pos, InferName::kNo);
1627 : }
1628 :
1629 29709707 : IdentifierT name = ParseAndClassifyIdentifier(token);
1630 49319496 : return impl()->ExpressionFromIdentifier(name, beg_pos);
1631 : }
1632 :
1633 55379914 : if (Token::IsLiteral(token)) {
1634 26026467 : return impl()->ExpressionFromLiteral(Next(), beg_pos);
1635 : }
1636 :
1637 12611367 : switch (token) {
1638 : case Token::THIS: {
1639 : Consume(Token::THIS);
1640 2487412 : return impl()->ThisExpression(beg_pos);
1641 : }
1642 :
1643 : case Token::ASSIGN_DIV:
1644 : case Token::DIV:
1645 80449 : return ParseRegExpLiteral();
1646 :
1647 : case Token::LBRACK:
1648 1136611 : return ParseArrayLiteral();
1649 :
1650 : case Token::LBRACE:
1651 1164695 : return ParseObjectLiteral();
1652 :
1653 : case Token::LPAREN: {
1654 : Consume(Token::LPAREN);
1655 3487268 : if (Check(Token::RPAREN)) {
1656 : // ()=>x. The continuation that consumes the => is in
1657 : // ParseAssignmentExpressionCoverGrammar.
1658 434698 : if (peek() != Token::ARROW) ReportUnexpectedToken(Token::RPAREN);
1659 434696 : next_arrow_function_info_.scope =
1660 434698 : NewFunctionScope(FunctionKind::kArrowFunction);
1661 550626 : return factory()->NewEmptyParentheses(beg_pos);
1662 : }
1663 3052568 : Scope::Snapshot scope_snapshot(scope());
1664 : ArrowHeadParsingScope maybe_arrow(impl(), FunctionKind::kArrowFunction);
1665 : // Heuristically try to detect immediately called functions before
1666 : // seeing the call parentheses.
1667 5509142 : if (peek() == Token::FUNCTION ||
1668 : (peek() == Token::ASYNC && PeekAhead() == Token::FUNCTION)) {
1669 615911 : function_state_->set_next_function_is_likely_called();
1670 : }
1671 : AcceptINScope scope(this, true);
1672 3052493 : ExpressionT expr = ParseExpressionCoverGrammar();
1673 : expr->mark_parenthesized();
1674 3052552 : Expect(Token::RPAREN);
1675 :
1676 3052510 : if (peek() == Token::ARROW) {
1677 114837 : next_arrow_function_info_.scope = maybe_arrow.ValidateAndCreateScope();
1678 114844 : scope_snapshot.Reparent(next_arrow_function_info_.scope);
1679 : } else {
1680 2937673 : maybe_arrow.ValidateExpression();
1681 : }
1682 :
1683 1898316 : return expr;
1684 : }
1685 :
1686 : case Token::CLASS: {
1687 : Consume(Token::CLASS);
1688 : int class_token_pos = position();
1689 58997 : IdentifierT name = impl()->NullIdentifier();
1690 : bool is_strict_reserved_name = false;
1691 136499 : Scanner::Location class_name_location = Scanner::Location::invalid();
1692 136499 : if (peek_any_identifier()) {
1693 1684 : name = ParseAndClassifyIdentifier(Next());
1694 18057 : class_name_location = scanner()->location();
1695 : is_strict_reserved_name =
1696 : Token::IsStrictReservedWord(scanner()->current_token());
1697 : }
1698 : return ParseClassLiteral(name, class_name_location,
1699 136499 : is_strict_reserved_name, class_token_pos);
1700 : }
1701 :
1702 : case Token::TEMPLATE_SPAN:
1703 : case Token::TEMPLATE_TAIL:
1704 59271 : return ParseTemplateLiteral(impl()->NullExpression(), beg_pos, false);
1705 :
1706 : case Token::MOD:
1707 128251 : if (allow_natives() || extension_ != nullptr) {
1708 128125 : return ParseV8Intrinsic();
1709 : }
1710 : break;
1711 :
1712 : default:
1713 : break;
1714 : }
1715 :
1716 898368 : ReportUnexpectedToken(Next());
1717 898368 : return impl()->FailureExpression();
1718 : }
1719 :
1720 : template <typename Impl>
1721 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseExpression() {
1722 29379287 : ExpressionParsingScope expression_scope(impl());
1723 58759868 : AcceptINScope scope(this, true);
1724 29379995 : ExpressionT result = ParseExpressionCoverGrammar();
1725 29379911 : expression_scope.ValidateExpression();
1726 41871804 : return result;
1727 : }
1728 :
1729 : template <typename Impl>
1730 : typename ParserBase<Impl>::ExpressionT
1731 : ParserBase<Impl>::ParseAssignmentExpression() {
1732 24788080 : ExpressionParsingScope expression_scope(impl());
1733 24788458 : ExpressionT result = ParseAssignmentExpressionCoverGrammar();
1734 24787652 : expression_scope.ValidateExpression();
1735 24787488 : return result;
1736 : }
1737 :
1738 : template <typename Impl>
1739 : typename ParserBase<Impl>::ExpressionT
1740 113183815 : ParserBase<Impl>::ParseExpressionCoverGrammar() {
1741 : // Expression ::
1742 : // AssignmentExpression
1743 : // Expression ',' AssignmentExpression
1744 :
1745 15823369 : ExpressionListT list(pointer_buffer());
1746 : ExpressionT expression;
1747 52634354 : AccumulationScope accumulation_scope(expression_scope());
1748 : while (true) {
1749 39571732 : if (V8_UNLIKELY(peek() == Token::ELLIPSIS)) {
1750 10381 : return ParseArrowParametersWithRest(&list, &accumulation_scope);
1751 : }
1752 :
1753 : int expr_pos = peek_position();
1754 39561351 : expression = ParseAssignmentExpressionCoverGrammar();
1755 :
1756 39557434 : ClassifyArrowParameter(&accumulation_scope, expr_pos, expression);
1757 18495369 : list.Add(expression);
1758 :
1759 39560677 : if (!Check(Token::COMMA)) break;
1760 :
1761 2762101 : if (peek() == Token::RPAREN && PeekAhead() == Token::ARROW) {
1762 : // a trailing comma is allowed at the end of an arrow parameter list
1763 : break;
1764 : }
1765 :
1766 : // Pass on the 'set_next_function_is_likely_called' flag if we have
1767 : // several function literals separated by comma.
1768 2760937 : if (peek() == Token::FUNCTION &&
1769 : function_state_->previous_function_was_likely_called()) {
1770 16 : function_state_->set_next_function_is_likely_called();
1771 : }
1772 : }
1773 :
1774 : // Return the single element if the list is empty. We need to do this because
1775 : // callers of this function care about the type of the result if there was
1776 : // only a single assignment expression. The preparser would lose this
1777 : // information otherwise.
1778 52617499 : if (list.length() == 1) return expression;
1779 21044768 : return impl()->ExpressionListToExpression(list);
1780 : }
1781 :
1782 : template <typename Impl>
1783 : typename ParserBase<Impl>::ExpressionT
1784 10381 : ParserBase<Impl>::ParseArrowParametersWithRest(
1785 2843 : typename ParserBase<Impl>::ExpressionListT* list,
1786 20762 : AccumulationScope* accumulation_scope) {
1787 : Consume(Token::ELLIPSIS);
1788 :
1789 5365 : Scanner::Location ellipsis = scanner()->location();
1790 : int pattern_pos = peek_position();
1791 10381 : ExpressionT pattern = ParseBindingPattern();
1792 10381 : ClassifyArrowParameter(accumulation_scope, pattern_pos, pattern);
1793 :
1794 : expression_scope()->RecordNonSimpleParameter();
1795 :
1796 10381 : if (V8_UNLIKELY(peek() == Token::ASSIGN)) {
1797 140 : ReportMessage(MessageTemplate::kRestDefaultInitializer);
1798 140 : return impl()->FailureExpression();
1799 : }
1800 :
1801 : ExpressionT spread =
1802 5295 : factory()->NewSpread(pattern, ellipsis.beg_pos, pattern_pos);
1803 10241 : if (V8_UNLIKELY(peek() == Token::COMMA)) {
1804 360 : ReportMessage(MessageTemplate::kParamAfterRest);
1805 360 : return impl()->FailureExpression();
1806 : }
1807 :
1808 : // 'x, y, ...z' in CoverParenthesizedExpressionAndArrowParameterList only
1809 : // as the formal parameters of'(x, y, ...z) => foo', and is not itself a
1810 : // valid expression.
1811 18493 : if (peek() != Token::RPAREN || PeekAhead() != Token::ARROW) {
1812 7038 : ReportUnexpectedTokenAt(ellipsis, Token::ELLIPSIS);
1813 7038 : return impl()->FailureExpression();
1814 : }
1815 :
1816 : list->Add(spread);
1817 1657 : return impl()->ExpressionListToExpression(*list);
1818 : }
1819 :
1820 : template <typename Impl>
1821 2452235 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseArrayLiteral() {
1822 : // ArrayLiteral ::
1823 : // '[' Expression? (',' Expression?)* ']'
1824 :
1825 : int pos = peek_position();
1826 785466 : ExpressionListT values(pointer_buffer());
1827 : int first_spread_index = -1;
1828 : Consume(Token::LBRACK);
1829 :
1830 1980774 : AccumulationScope accumulation_scope(expression_scope());
1831 :
1832 12943823 : while (!Check(Token::RBRACK)) {
1833 : ExpressionT elem;
1834 10576885 : if (peek() == Token::COMMA) {
1835 2148897 : elem = factory()->NewTheHoleLiteral();
1836 8427947 : } else if (Check(Token::ELLIPSIS)) {
1837 : int start_pos = position();
1838 : int expr_pos = peek_position();
1839 : AcceptINScope scope(this, true);
1840 : ExpressionT argument =
1841 41020 : ParsePossibleDestructuringSubPattern(&accumulation_scope);
1842 41018 : elem = factory()->NewSpread(argument, start_pos, expr_pos);
1843 :
1844 18293 : if (first_spread_index < 0) {
1845 17220 : first_spread_index = values.length();
1846 : }
1847 :
1848 63741 : if (argument->IsAssignment()) {
1849 3215 : expression_scope()->RecordPatternError(
1850 : Scanner::Location(start_pos, end_position()),
1851 : MessageTemplate::kInvalidDestructuringTarget);
1852 : }
1853 :
1854 41017 : if (peek() == Token::COMMA) {
1855 7189 : expression_scope()->RecordPatternError(
1856 : Scanner::Location(start_pos, end_position()),
1857 : MessageTemplate::kElementAfterRest);
1858 : }
1859 : } else {
1860 : AcceptINScope scope(this, true);
1861 8386927 : elem = ParsePossibleDestructuringSubPattern(&accumulation_scope);
1862 : }
1863 7812446 : values.Add(elem);
1864 10576813 : if (peek() != Token::RBRACK) {
1865 9972924 : Expect(Token::COMMA);
1866 9973183 : if (elem->IsFailureExpression()) return elem;
1867 : }
1868 : }
1869 :
1870 1184394 : return factory()->NewArrayLiteral(values, first_spread_index, pos);
1871 : }
1872 :
1873 : template <class Impl>
1874 5499484 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseProperty(
1875 5232123 : ParsePropertyInfo* prop_info) {
1876 : DCHECK_EQ(prop_info->kind, ParsePropertyKind::kNotSet);
1877 : DCHECK_EQ(prop_info->function_flags, ParseFunctionFlag::kIsNormal);
1878 : DCHECK(!prop_info->is_computed_name);
1879 :
1880 5499461 : if (Check(Token::ASYNC)) {
1881 : Token::Value token = peek();
1882 65306 : if ((token != Token::MUL && prop_info->ParsePropertyKindFromToken(token)) ||
1883 : scanner()->HasLineTerminatorBeforeNext()) {
1884 5520 : prop_info->name = impl()->GetSymbol();
1885 : impl()->PushLiteralName(prop_info->name);
1886 5520 : return factory()->NewStringLiteral(prop_info->name, position());
1887 : }
1888 29253 : prop_info->function_flags = ParseFunctionFlag::kIsAsync;
1889 29253 : prop_info->kind = ParsePropertyKind::kMethod;
1890 : }
1891 :
1892 5493850 : if (Check(Token::MUL)) {
1893 : prop_info->function_flags |= ParseFunctionFlag::kIsGenerator;
1894 46298 : prop_info->kind = ParsePropertyKind::kMethod;
1895 : }
1896 :
1897 10921684 : if (prop_info->kind == ParsePropertyKind::kNotSet &&
1898 : Check(Token::IDENTIFIER)) {
1899 1062949 : IdentifierT symbol = impl()->GetSymbol();
1900 2932905 : if (!prop_info->ParsePropertyKindFromToken(peek())) {
1901 162596 : if (impl()->IdentifierEquals(symbol, ast_value_factory()->get_string())) {
1902 42842 : prop_info->kind = ParsePropertyKind::kAccessorGetter;
1903 38456 : } else if (impl()->IdentifierEquals(symbol,
1904 : ast_value_factory()->set_string())) {
1905 34580 : prop_info->kind = ParsePropertyKind::kAccessorSetter;
1906 : }
1907 : }
1908 2932838 : if (!IsAccessor(prop_info->kind)) {
1909 2855432 : prop_info->name = symbol;
1910 : impl()->PushLiteralName(prop_info->name);
1911 4679966 : return factory()->NewStringLiteral(prop_info->name, position());
1912 : }
1913 : }
1914 :
1915 : int pos = peek_position();
1916 :
1917 : // For non computed property names we normalize the name a bit:
1918 : //
1919 : // "12" -> 12
1920 : // 12.3 -> "12.3"
1921 : // 12.30 -> "12.3"
1922 : // identifier -> "identifier"
1923 : //
1924 : // This is important because we use the property name as a key in a hash
1925 : // table when we compute constant properties.
1926 : bool is_array_index;
1927 : uint32_t index;
1928 2638542 : switch (peek()) {
1929 : case Token::PRIVATE_NAME:
1930 49832 : prop_info->is_private = true;
1931 : is_array_index = false;
1932 : Consume(Token::PRIVATE_NAME);
1933 49833 : if (prop_info->kind == ParsePropertyKind::kNotSet) {
1934 32473 : prop_info->ParsePropertyKindFromToken(peek());
1935 : }
1936 49833 : prop_info->name = impl()->GetSymbol();
1937 123899 : if (prop_info->position == PropertyPosition::kObjectLiteral ||
1938 : (!allow_harmony_private_methods() &&
1939 24953 : (IsAccessor(prop_info->kind) ||
1940 : prop_info->kind == ParsePropertyKind::kMethod))) {
1941 2640 : ReportUnexpectedToken(Next());
1942 2640 : return impl()->FailureExpression();
1943 : }
1944 : break;
1945 :
1946 : case Token::STRING:
1947 : Consume(Token::STRING);
1948 92061 : prop_info->name = impl()->GetSymbol();
1949 : is_array_index = impl()->IsArrayIndex(prop_info->name, &index);
1950 92059 : break;
1951 :
1952 : case Token::SMI:
1953 : Consume(Token::SMI);
1954 1449655 : index = scanner()->smi_value();
1955 : is_array_index = true;
1956 : // Token::SMI were scanned from their canonical representation.
1957 2123232 : prop_info->name = impl()->GetSymbol();
1958 2123233 : break;
1959 :
1960 : case Token::NUMBER: {
1961 : Consume(Token::NUMBER);
1962 7225 : prop_info->name = impl()->GetNumberAsSymbol();
1963 : is_array_index = impl()->IsArrayIndex(prop_info->name, &index);
1964 7225 : break;
1965 : }
1966 : case Token::LBRACK: {
1967 65314 : prop_info->name = impl()->NullIdentifier();
1968 65314 : prop_info->is_computed_name = true;
1969 : Consume(Token::LBRACK);
1970 : AcceptINScope scope(this, true);
1971 : ExpressionT expression = ParseAssignmentExpression();
1972 65315 : Expect(Token::RBRACK);
1973 65316 : if (prop_info->kind == ParsePropertyKind::kNotSet) {
1974 59443 : prop_info->ParsePropertyKindFromToken(peek());
1975 : }
1976 33506 : return expression;
1977 : }
1978 :
1979 : case Token::ELLIPSIS:
1980 24502 : if (prop_info->kind == ParsePropertyKind::kNotSet) {
1981 24182 : prop_info->name = impl()->NullIdentifier();
1982 : Consume(Token::ELLIPSIS);
1983 : AcceptINScope scope(this, true);
1984 : int start_pos = peek_position();
1985 : ExpressionT expression =
1986 24182 : ParsePossibleDestructuringSubPattern(prop_info->accumulation_scope);
1987 24182 : prop_info->kind = ParsePropertyKind::kSpread;
1988 :
1989 24182 : if (!IsValidReferenceExpression(expression)) {
1990 8246 : expression_scope()->RecordDeclarationError(
1991 : Scanner::Location(start_pos, end_position()),
1992 : MessageTemplate::kInvalidRestBindingPattern);
1993 8246 : expression_scope()->RecordPatternError(
1994 : Scanner::Location(start_pos, end_position()),
1995 : MessageTemplate::kInvalidRestAssignmentPattern);
1996 : }
1997 :
1998 24182 : if (peek() != Token::RBRACE) {
1999 23486 : expression_scope()->RecordPatternError(
2000 : scanner()->location(), MessageTemplate::kElementAfterRest);
2001 : }
2002 13005 : return expression;
2003 : }
2004 : V8_FALLTHROUGH;
2005 :
2006 : default:
2007 276697 : prop_info->name = ParsePropertyName();
2008 : is_array_index = false;
2009 276697 : break;
2010 : }
2011 :
2012 2546407 : if (prop_info->kind == ParsePropertyKind::kNotSet) {
2013 2385159 : prop_info->ParsePropertyKindFromToken(peek());
2014 : }
2015 1669286 : impl()->PushLiteralName(prop_info->name);
2016 1669286 : return is_array_index ? factory()->NewNumberLiteral(index, pos)
2017 5667866 : : factory()->NewStringLiteral(prop_info->name, pos);
2018 : }
2019 :
2020 : template <typename Impl>
2021 : typename ParserBase<Impl>::ClassLiteralPropertyT
2022 607737 : ParserBase<Impl>::ParseClassPropertyDefinition(ClassInfo* class_info,
2023 : ParsePropertyInfo* prop_info,
2024 1399340 : bool has_extends) {
2025 : DCHECK_NOT_NULL(class_info);
2026 : DCHECK_EQ(prop_info->position, PropertyPosition::kClassLiteral);
2027 :
2028 : Token::Value name_token = peek();
2029 : DCHECK_IMPLIES(name_token == Token::PRIVATE_NAME,
2030 : allow_harmony_private_fields());
2031 :
2032 607740 : int property_beg_pos = scanner()->peek_location().beg_pos;
2033 : int name_token_position = property_beg_pos;
2034 : ExpressionT name_expression;
2035 607740 : if (name_token == Token::STATIC) {
2036 : Consume(Token::STATIC);
2037 107468 : name_token_position = scanner()->peek_location().beg_pos;
2038 107468 : if (peek() == Token::LPAREN) {
2039 240 : prop_info->kind = ParsePropertyKind::kMethod;
2040 : // TODO(bakkot) specialize on 'static'
2041 240 : prop_info->name = impl()->GetSymbol();
2042 120 : name_expression =
2043 : factory()->NewStringLiteral(prop_info->name, position());
2044 321683 : } else if (peek() == Token::ASSIGN || peek() == Token::SEMICOLON ||
2045 : peek() == Token::RBRACE) {
2046 : // TODO(bakkot) specialize on 'static'
2047 800 : prop_info->name = impl()->GetSymbol();
2048 400 : name_expression =
2049 : factory()->NewStringLiteral(prop_info->name, position());
2050 : } else {
2051 106428 : prop_info->is_static = true;
2052 106428 : name_expression = ParseProperty(prop_info);
2053 : }
2054 : } else {
2055 500275 : name_expression = ParseProperty(prop_info);
2056 : }
2057 :
2058 714147 : if (!class_info->has_name_static_property && prop_info->is_static &&
2059 : impl()->IsName(prop_info->name)) {
2060 117 : class_info->has_name_static_property = true;
2061 : }
2062 :
2063 607725 : switch (prop_info->kind) {
2064 : case ParsePropertyKind::kAssign:
2065 : case ParsePropertyKind::kClassField:
2066 : case ParsePropertyKind::kShorthandOrClassField:
2067 : case ParsePropertyKind::kNotSet: // This case is a name followed by a name
2068 : // or other property. Here we have to
2069 : // assume that's an uninitialized field
2070 : // followed by a linebreak followed by a
2071 : // property, with ASI adding the
2072 : // semicolon. If not, there will be a
2073 : // syntax error after parsing the first
2074 : // name as an uninitialized field.
2075 220473 : if (allow_harmony_public_fields() || allow_harmony_private_fields()) {
2076 111518 : prop_info->kind = ParsePropertyKind::kClassField;
2077 : DCHECK_IMPLIES(prop_info->is_computed_name, !prop_info->is_private);
2078 :
2079 162865 : if (prop_info->is_static && !allow_harmony_static_fields()) {
2080 11840 : ReportUnexpectedToken(Next());
2081 11840 : return impl()->NullLiteralProperty();
2082 : }
2083 :
2084 99678 : if (!prop_info->is_computed_name) {
2085 89754 : CheckClassFieldName(prop_info->name, prop_info->is_static);
2086 : }
2087 :
2088 : ExpressionT initializer = ParseMemberInitializer(
2089 99678 : class_info, property_beg_pos, prop_info->is_static);
2090 99677 : ExpectSemicolon();
2091 :
2092 : ClassLiteralPropertyT result = factory()->NewClassLiteralProperty(
2093 : name_expression, initializer, ClassLiteralProperty::FIELD,
2094 : prop_info->is_static, prop_info->is_computed_name,
2095 51006 : prop_info->is_private);
2096 51005 : impl()->SetFunctionNameFromPropertyName(result, prop_info->name);
2097 :
2098 99678 : return result;
2099 :
2100 : } else {
2101 46100 : ReportUnexpectedToken(Next());
2102 46100 : return impl()->NullLiteralProperty();
2103 : }
2104 :
2105 : case ParsePropertyKind::kMethod: {
2106 : // MethodDefinition
2107 : // PropertyName '(' StrictFormalParameters ')' '{' FunctionBody '}'
2108 : // '*' PropertyName '(' StrictFormalParameters ')' '{' FunctionBody '}'
2109 : // async PropertyName '(' StrictFormalParameters ')'
2110 : // '{' FunctionBody '}'
2111 : // async '*' PropertyName '(' StrictFormalParameters ')'
2112 : // '{' FunctionBody '}'
2113 :
2114 403000 : if (!prop_info->is_computed_name) {
2115 395282 : CheckClassMethodName(prop_info->name, ParsePropertyKind::kMethod,
2116 : prop_info->function_flags, prop_info->is_static,
2117 395282 : &class_info->has_seen_constructor);
2118 : }
2119 :
2120 : FunctionKind kind = MethodKindFor(prop_info->function_flags);
2121 :
2122 774259 : if (!prop_info->is_static && impl()->IsConstructor(prop_info->name)) {
2123 20241 : class_info->has_seen_constructor = true;
2124 20241 : kind = has_extends ? FunctionKind::kDerivedConstructor
2125 : : FunctionKind::kBaseConstructor;
2126 : }
2127 :
2128 : ExpressionT value = impl()->ParseFunctionLiteral(
2129 : prop_info->name, scanner()->location(), kSkipFunctionNameCheck, kind,
2130 : name_token_position, FunctionLiteral::kAccessorOrMethod,
2131 805996 : language_mode(), nullptr);
2132 :
2133 : ClassLiteralPropertyT result = factory()->NewClassLiteralProperty(
2134 : name_expression, value, ClassLiteralProperty::METHOD,
2135 : prop_info->is_static, prop_info->is_computed_name,
2136 360566 : prop_info->is_private);
2137 360563 : impl()->SetFunctionNameFromPropertyName(result, prop_info->name);
2138 403026 : return result;
2139 : }
2140 :
2141 : case ParsePropertyKind::kAccessorGetter:
2142 : case ParsePropertyKind::kAccessorSetter: {
2143 : DCHECK_EQ(prop_info->function_flags, ParseFunctionFlag::kIsNormal);
2144 45569 : bool is_get = prop_info->kind == ParsePropertyKind::kAccessorGetter;
2145 :
2146 45569 : if (!prop_info->is_computed_name) {
2147 41988 : CheckClassMethodName(prop_info->name, prop_info->kind,
2148 : ParseFunctionFlag::kIsNormal, prop_info->is_static,
2149 106909 : &class_info->has_seen_constructor);
2150 : // Make sure the name expression is a string since we need a Name for
2151 : // Runtime_DefineAccessorPropertyUnchecked and since we can determine
2152 : // this statically we can skip the extra runtime check.
2153 23711 : name_expression = factory()->NewStringLiteral(
2154 : prop_info->name, name_expression->position());
2155 : }
2156 :
2157 : FunctionKind kind = is_get ? FunctionKind::kGetterFunction
2158 45569 : : FunctionKind::kSetterFunction;
2159 :
2160 : FunctionLiteralT value = impl()->ParseFunctionLiteral(
2161 : prop_info->name, scanner()->location(), kSkipFunctionNameCheck, kind,
2162 : name_token_position, FunctionLiteral::kAccessorOrMethod,
2163 91138 : language_mode(), nullptr);
2164 :
2165 : ClassLiteralProperty::Kind property_kind =
2166 26080 : is_get ? ClassLiteralProperty::GETTER : ClassLiteralProperty::SETTER;
2167 : ClassLiteralPropertyT result = factory()->NewClassLiteralProperty(
2168 : name_expression, value, property_kind, prop_info->is_static,
2169 26080 : prop_info->is_computed_name, prop_info->is_private);
2170 : const AstRawString* prefix =
2171 26080 : is_get ? ast_value_factory()->get_space_string()
2172 26080 : : ast_value_factory()->set_space_string();
2173 26080 : impl()->SetFunctionNameFromPropertyName(result, prop_info->name, prefix);
2174 45569 : return result;
2175 : }
2176 : case ParsePropertyKind::kValue:
2177 : case ParsePropertyKind::kShorthand:
2178 : case ParsePropertyKind::kSpread:
2179 1538 : ReportUnexpectedTokenAt(
2180 : Scanner::Location(name_token_position, name_expression->position()),
2181 1556 : name_token);
2182 1538 : return impl()->NullLiteralProperty();
2183 : }
2184 0 : UNREACHABLE();
2185 : }
2186 :
2187 : template <typename Impl>
2188 99678 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseMemberInitializer(
2189 99677 : ClassInfo* class_info, int beg_pos, bool is_static) {
2190 : DeclarationScope* initializer_scope =
2191 : is_static ? class_info->static_fields_scope
2192 99678 : : class_info->instance_members_scope;
2193 :
2194 99678 : if (initializer_scope == nullptr) {
2195 91077 : initializer_scope =
2196 : NewFunctionScope(FunctionKind::kClassMembersInitializerFunction);
2197 : // TODO(gsathya): Make scopes be non contiguous.
2198 : initializer_scope->set_start_position(beg_pos);
2199 : initializer_scope->SetLanguageMode(LanguageMode::kStrict);
2200 : }
2201 :
2202 : ExpressionT initializer;
2203 99678 : if (Check(Token::ASSIGN)) {
2204 : FunctionState initializer_state(&function_state_, &scope_,
2205 32779 : initializer_scope);
2206 :
2207 : AcceptINScope scope(this, true);
2208 : initializer = ParseAssignmentExpression();
2209 : } else {
2210 33651 : initializer = factory()->NewUndefinedLiteral(kNoSourcePosition);
2211 : }
2212 :
2213 : initializer_scope->set_end_position(end_position());
2214 99677 : if (is_static) {
2215 39507 : class_info->static_fields_scope = initializer_scope;
2216 39507 : class_info->has_static_class_fields = true;
2217 : } else {
2218 60170 : class_info->instance_members_scope = initializer_scope;
2219 60170 : class_info->has_instance_members = true;
2220 : }
2221 :
2222 99677 : return initializer;
2223 : }
2224 :
2225 : template <typename Impl>
2226 : typename ParserBase<Impl>::ObjectLiteralPropertyT
2227 4892710 : ParserBase<Impl>::ParseObjectPropertyDefinition(ParsePropertyInfo* prop_info,
2228 10119133 : bool* has_seen_proto) {
2229 : DCHECK_EQ(prop_info->position, PropertyPosition::kObjectLiteral);
2230 : Token::Value name_token = peek();
2231 4892716 : Scanner::Location next_loc = scanner()->peek_location();
2232 :
2233 4892716 : ExpressionT name_expression = ParseProperty(prop_info);
2234 4892905 : IdentifierT name = prop_info->name;
2235 4892905 : ParseFunctionFlags function_flags = prop_info->function_flags;
2236 4892905 : ParsePropertyKind kind = prop_info->kind;
2237 :
2238 4892905 : switch (prop_info->kind) {
2239 : case ParsePropertyKind::kSpread:
2240 : DCHECK_EQ(function_flags, ParseFunctionFlag::kIsNormal);
2241 : DCHECK(!prop_info->is_computed_name);
2242 : DCHECK_EQ(Token::ELLIPSIS, name_token);
2243 :
2244 24164 : prop_info->is_computed_name = true;
2245 24164 : prop_info->is_rest = true;
2246 :
2247 : return factory()->NewObjectLiteralProperty(
2248 : factory()->NewTheHoleLiteral(), name_expression,
2249 33476 : ObjectLiteralProperty::SPREAD, true);
2250 :
2251 : case ParsePropertyKind::kValue: {
2252 : DCHECK_EQ(function_flags, ParseFunctionFlag::kIsNormal);
2253 :
2254 13443081 : if (!prop_info->is_computed_name &&
2255 : impl()->IdentifierEquals(name, ast_value_factory()->proto_string())) {
2256 9402 : if (*has_seen_proto) {
2257 : expression_scope()->RecordExpressionError(
2258 : scanner()->location(), MessageTemplate::kDuplicateProto);
2259 : }
2260 9402 : *has_seen_proto = true;
2261 : }
2262 : Consume(Token::COLON);
2263 : AcceptINScope scope(this, true);
2264 : ExpressionT value =
2265 4505046 : ParsePossibleDestructuringSubPattern(prop_info->accumulation_scope);
2266 :
2267 : ObjectLiteralPropertyT result = factory()->NewObjectLiteralProperty(
2268 2907833 : name_expression, value, prop_info->is_computed_name);
2269 2907843 : impl()->SetFunctionNameFromPropertyName(result, name);
2270 1596955 : return result;
2271 : }
2272 :
2273 : case ParsePropertyKind::kAssign:
2274 : case ParsePropertyKind::kShorthandOrClassField:
2275 : case ParsePropertyKind::kShorthand: {
2276 : // PropertyDefinition
2277 : // IdentifierReference
2278 : // CoverInitializedName
2279 : //
2280 : // CoverInitializedName
2281 : // IdentifierReference Initializer?
2282 : DCHECK_EQ(function_flags, ParseFunctionFlag::kIsNormal);
2283 :
2284 398456 : if (!Token::IsValidIdentifier(name_token, language_mode(), is_generator(),
2285 394434 : parsing_module_ || is_async_function())) {
2286 8907 : ReportUnexpectedToken(Next());
2287 8907 : return impl()->NullLiteralProperty();
2288 : }
2289 :
2290 : DCHECK(!prop_info->is_computed_name);
2291 :
2292 190319 : if (name_token == Token::LET) {
2293 52 : expression_scope()->RecordLexicalDeclarationError(
2294 : scanner()->location(), MessageTemplate::kLetInLexicalBinding);
2295 : }
2296 190318 : if (name_token == Token::AWAIT) {
2297 : DCHECK(!is_async_function());
2298 : expression_scope()->RecordAsyncArrowParametersError(
2299 : next_loc, MessageTemplate::kAwaitBindingIdentifier);
2300 : }
2301 : ExpressionT lhs =
2302 190318 : impl()->ExpressionFromIdentifier(name, next_loc.beg_pos);
2303 190325 : if (!IsAssignableIdentifier(lhs)) {
2304 1140 : expression_scope()->RecordPatternError(
2305 : next_loc, MessageTemplate::kStrictEvalArguments);
2306 : }
2307 :
2308 : ExpressionT value;
2309 190327 : if (peek() == Token::ASSIGN) {
2310 : Consume(Token::ASSIGN);
2311 : {
2312 : AcceptINScope scope(this, true);
2313 : ExpressionT rhs = ParseAssignmentExpression();
2314 13153 : value = factory()->NewAssignment(Token::ASSIGN, lhs, rhs,
2315 : kNoSourcePosition);
2316 13153 : impl()->SetFunctionNameFromIdentifierRef(rhs, lhs);
2317 : }
2318 31200 : expression_scope()->RecordExpressionError(
2319 : Scanner::Location(next_loc.beg_pos, end_position()),
2320 : MessageTemplate::kInvalidCoverInitializedName);
2321 : } else {
2322 : value = lhs;
2323 : }
2324 :
2325 : ObjectLiteralPropertyT result = factory()->NewObjectLiteralProperty(
2326 65903 : name_expression, value, ObjectLiteralProperty::COMPUTED, false);
2327 65895 : impl()->SetFunctionNameFromPropertyName(result, name);
2328 190329 : return result;
2329 : }
2330 :
2331 : case ParsePropertyKind::kMethod: {
2332 : // MethodDefinition
2333 : // PropertyName '(' StrictFormalParameters ')' '{' FunctionBody '}'
2334 : // '*' PropertyName '(' StrictFormalParameters ')' '{' FunctionBody '}'
2335 :
2336 119864 : expression_scope()->RecordPatternError(
2337 : Scanner::Location(next_loc.beg_pos, end_position()),
2338 : MessageTemplate::kInvalidDestructuringTarget);
2339 :
2340 : FunctionKind kind = MethodKindFor(function_flags);
2341 :
2342 : ExpressionT value = impl()->ParseFunctionLiteral(
2343 : name, scanner()->location(), kSkipFunctionNameCheck, kind,
2344 : next_loc.beg_pos, FunctionLiteral::kAccessorOrMethod, language_mode(),
2345 119862 : nullptr);
2346 :
2347 : ObjectLiteralPropertyT result = factory()->NewObjectLiteralProperty(
2348 : name_expression, value, ObjectLiteralProperty::COMPUTED,
2349 34351 : prop_info->is_computed_name);
2350 34348 : impl()->SetFunctionNameFromPropertyName(result, name);
2351 59939 : return result;
2352 : }
2353 :
2354 : case ParsePropertyKind::kAccessorGetter:
2355 : case ParsePropertyKind::kAccessorSetter: {
2356 : DCHECK_EQ(function_flags, ParseFunctionFlag::kIsNormal);
2357 31851 : bool is_get = kind == ParsePropertyKind::kAccessorGetter;
2358 :
2359 63702 : expression_scope()->RecordPatternError(
2360 : Scanner::Location(next_loc.beg_pos, end_position()),
2361 : MessageTemplate::kInvalidDestructuringTarget);
2362 :
2363 19273 : if (!prop_info->is_computed_name) {
2364 : // Make sure the name expression is a string since we need a Name for
2365 : // Runtime_DefineAccessorPropertyUnchecked and since we can determine
2366 : // this statically we can skip the extra runtime check.
2367 18702 : name_expression =
2368 : factory()->NewStringLiteral(name, name_expression->position());
2369 : }
2370 :
2371 : FunctionKind kind = is_get ? FunctionKind::kGetterFunction
2372 31852 : : FunctionKind::kSetterFunction;
2373 :
2374 : FunctionLiteralT value = impl()->ParseFunctionLiteral(
2375 : name, scanner()->location(), kSkipFunctionNameCheck, kind,
2376 : next_loc.beg_pos, FunctionLiteral::kAccessorOrMethod, language_mode(),
2377 63704 : nullptr);
2378 :
2379 : ObjectLiteralPropertyT result = factory()->NewObjectLiteralProperty(
2380 : name_expression, value,
2381 : is_get ? ObjectLiteralProperty::GETTER
2382 : : ObjectLiteralProperty::SETTER,
2383 19279 : prop_info->is_computed_name);
2384 : const AstRawString* prefix =
2385 19278 : is_get ? ast_value_factory()->get_space_string()
2386 19278 : : ast_value_factory()->set_space_string();
2387 19278 : impl()->SetFunctionNameFromPropertyName(result, name, prefix);
2388 31854 : return result;
2389 : }
2390 :
2391 : case ParsePropertyKind::kClassField:
2392 : case ParsePropertyKind::kNotSet:
2393 72678 : ReportUnexpectedToken(Next());
2394 72678 : return impl()->NullLiteralProperty();
2395 : }
2396 0 : UNREACHABLE();
2397 : }
2398 :
2399 : template <typename Impl>
2400 2673971 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseObjectLiteral() {
2401 : // ObjectLiteral ::
2402 : // '{' (PropertyDefinition (',' PropertyDefinition)* ','? )? '}'
2403 :
2404 : int pos = peek_position();
2405 615913 : ObjectPropertyListT properties(pointer_buffer());
2406 : int number_of_boilerplate_properties = 0;
2407 :
2408 : bool has_computed_names = false;
2409 : bool has_rest_property = false;
2410 1336913 : bool has_seen_proto = false;
2411 :
2412 : Consume(Token::LBRACE);
2413 1952945 : AccumulationScope accumulation_scope(expression_scope());
2414 :
2415 10523799 : while (!Check(Token::RBRACE)) {
2416 3074096 : FuncNameInferrerState fni_state(&fni_);
2417 :
2418 1818640 : ParsePropertyInfo prop_info(this, &accumulation_scope);
2419 4892742 : prop_info.position = PropertyPosition::kObjectLiteral;
2420 1818597 : ObjectLiteralPropertyT property =
2421 4892742 : ParseObjectPropertyDefinition(&prop_info, &has_seen_proto);
2422 4974249 : if (impl()->IsNull(property)) return impl()->FailureExpression();
2423 :
2424 3038539 : if (prop_info.is_computed_name) {
2425 : has_computed_names = true;
2426 : }
2427 :
2428 4811079 : if (prop_info.is_rest) {
2429 : has_rest_property = true;
2430 : }
2431 :
2432 3038515 : if (impl()->IsBoilerplateProperty(property) && !has_computed_names) {
2433 : // Count CONSTANT or COMPUTED properties to maintain the enumeration
2434 : // order.
2435 3003917 : number_of_boilerplate_properties++;
2436 : }
2437 :
2438 3038515 : properties.Add(property);
2439 :
2440 4811080 : if (peek() != Token::RBRACE) {
2441 3907844 : Expect(Token::COMMA);
2442 : }
2443 :
2444 : fni_.Infer();
2445 : }
2446 :
2447 : // In pattern rewriter, we rewrite rest property to call out to a
2448 : // runtime function passing all the other properties as arguments to
2449 : // this runtime function. Here, we make sure that the number of
2450 : // properties is less than number of arguments allowed for a runtime
2451 : // call.
2452 1261630 : if (has_rest_property && properties.length() > Code::kMaxArguments) {
2453 20 : expression_scope()->RecordPatternError(Scanner::Location(pos, position()),
2454 : MessageTemplate::kTooManyArguments);
2455 : }
2456 :
2457 : return impl()->InitializeObjectLiteral(factory()->NewObjectLiteral(
2458 1881887 : properties, number_of_boilerplate_properties, pos, has_rest_property));
2459 : }
2460 :
2461 : template <typename Impl>
2462 13575166 : void ParserBase<Impl>::ParseArguments(
2463 22846481 : typename ParserBase<Impl>::ExpressionListT* args, bool* has_spread,
2464 41795853 : ParsingArrowHeadFlag maybe_arrow) {
2465 : // Arguments ::
2466 : // '(' (AssignmentExpression)*[','] ')'
2467 :
2468 13575166 : *has_spread = false;
2469 : Consume(Token::LPAREN);
2470 13576915 : AccumulationScope accumulation_scope(expression_scope());
2471 :
2472 36657935 : while (peek() != Token::RPAREN) {
2473 : int start_pos = peek_position();
2474 : bool is_spread = Check(Token::ELLIPSIS);
2475 : int expr_pos = peek_position();
2476 :
2477 : AcceptINScope scope(this, true);
2478 18944346 : ExpressionT argument = ParseAssignmentExpressionCoverGrammar();
2479 :
2480 18941943 : if (V8_UNLIKELY(maybe_arrow == kMaybeArrowHead)) {
2481 9005 : ClassifyArrowParameter(&accumulation_scope, expr_pos, argument);
2482 9005 : if (is_spread) {
2483 : expression_scope()->RecordNonSimpleParameter();
2484 438 : if (argument->IsAssignment()) {
2485 : expression_scope()->RecordAsyncArrowParametersError(
2486 : scanner()->location(), MessageTemplate::kRestDefaultInitializer);
2487 : }
2488 438 : if (peek() == Token::COMMA) {
2489 : expression_scope()->RecordAsyncArrowParametersError(
2490 : scanner()->peek_location(), MessageTemplate::kParamAfterRest);
2491 : }
2492 : }
2493 : }
2494 18941943 : if (is_spread) {
2495 12941 : *has_spread = true;
2496 5320 : argument = factory()->NewSpread(argument, start_pos, expr_pos);
2497 : }
2498 : args->Add(argument);
2499 18946234 : if (!Check(Token::COMMA)) break;
2500 : }
2501 :
2502 13574759 : if (args->length() > Code::kMaxArguments) {
2503 29 : ReportMessage(MessageTemplate::kTooManyArguments);
2504 13576105 : return;
2505 : }
2506 :
2507 27149460 : Scanner::Location location = scanner_->location();
2508 13576152 : if (!Check(Token::RPAREN)) {
2509 9864 : impl()->ReportMessageAt(location, MessageTemplate::kUnterminatedArgList);
2510 13576152 : }
2511 : }
2512 :
2513 : // Precedence = 2
2514 : template <typename Impl>
2515 : typename ParserBase<Impl>::ExpressionT
2516 123436777 : ParserBase<Impl>::ParseAssignmentExpressionCoverGrammar() {
2517 : // AssignmentExpression ::
2518 : // ConditionalExpression
2519 : // ArrowFunction
2520 : // YieldExpression
2521 : // LeftHandSideExpression AssignmentOperator AssignmentExpression
2522 : int lhs_beg_pos = peek_position();
2523 :
2524 96325934 : if (peek() == Token::YIELD && is_generator()) {
2525 43253 : return ParseYieldExpression();
2526 : }
2527 :
2528 50879161 : FuncNameInferrerState fni_state(&fni_);
2529 :
2530 : DCHECK_IMPLIES(!has_error(), next_arrow_function_info_.HasInitialState());
2531 :
2532 46932504 : ExpressionT expression = ParseConditionalExpression();
2533 :
2534 : Token::Value op = peek();
2535 :
2536 96208981 : if (!Token::IsArrowOrAssignmentOp(op)) return expression;
2537 :
2538 : // Arrow functions.
2539 12357707 : if (V8_UNLIKELY(op == Token::ARROW)) {
2540 : Scanner::Location loc(lhs_beg_pos, end_position());
2541 :
2542 1347303 : if (!impl()->IsIdentifier(expression) && !expression->is_parenthesized()) {
2543 19258 : impl()->ReportMessageAt(
2544 : Scanner::Location(expression->position(), position()),
2545 : MessageTemplate::kMalformedArrowFunParamList);
2546 12842 : return impl()->FailureExpression();
2547 : }
2548 :
2549 828719 : DeclarationScope* scope = next_arrow_function_info_.scope;
2550 : scope->set_start_position(lhs_beg_pos);
2551 :
2552 : FormalParametersT parameters(scope);
2553 372698 : parameters.set_strict_parameter_error(
2554 : next_arrow_function_info_.strict_parameter_error_location,
2555 : next_arrow_function_info_.strict_parameter_error_message);
2556 828719 : parameters.is_simple = scope->has_simple_parameters();
2557 : next_arrow_function_info_.Reset();
2558 :
2559 372698 : impl()->DeclareArrowFunctionFormalParameters(¶meters, expression, loc);
2560 :
2561 828733 : expression = ParseArrowFunctionLiteral(parameters);
2562 :
2563 828727 : return expression;
2564 : }
2565 :
2566 11516155 : if (V8_LIKELY(impl()->IsAssignableIdentifier(expression))) {
2567 3193537 : if (expression->is_parenthesized()) {
2568 2273 : expression_scope()->RecordDeclarationError(
2569 : Scanner::Location(lhs_beg_pos, end_position()),
2570 : MessageTemplate::kInvalidDestructuringTarget);
2571 : }
2572 : expression_scope()->MarkIdentifierAsAssigned();
2573 8322374 : } else if (expression->IsProperty()) {
2574 8127992 : expression_scope()->RecordDeclarationError(
2575 : Scanner::Location(lhs_beg_pos, end_position()),
2576 : MessageTemplate::kInvalidPropertyBindingPattern);
2577 194382 : } else if (expression->IsPattern() && op == Token::ASSIGN) {
2578 : // Destructuring assignmment.
2579 183867 : if (expression->is_parenthesized()) {
2580 1716 : expression_scope()->RecordPatternError(
2581 : Scanner::Location(lhs_beg_pos, end_position()),
2582 : MessageTemplate::kInvalidDestructuringTarget);
2583 : }
2584 : expression_scope()->ValidateAsPattern(expression, lhs_beg_pos,
2585 : end_position());
2586 : } else {
2587 : DCHECK(!IsValidReferenceExpression(expression));
2588 10515 : expression = RewriteInvalidReferenceExpression(
2589 : expression, lhs_beg_pos, end_position(),
2590 : MessageTemplate::kInvalidLhsInAssignment);
2591 : }
2592 :
2593 : Consume(op);
2594 : int op_position = position();
2595 :
2596 : ExpressionT right = ParseAssignmentExpression();
2597 :
2598 11516290 : if (op == Token::ASSIGN) {
2599 : // We try to estimate the set of properties set by constructors. We define a
2600 : // new property whenever there is an assignment to a property of 'this'. We
2601 : // should probably only add properties if we haven't seen them before.
2602 : // Otherwise we'll probably overestimate the number of properties.
2603 11128108 : if (impl()->IsThisProperty(expression)) function_state_->AddProperty();
2604 :
2605 : impl()->CheckAssigningFunctionLiteralToProperty(expression, right);
2606 :
2607 : // Check if the right hand side is a call to avoid inferring a
2608 : // name if we're dealing with "a = function(){...}();"-like
2609 : // expression.
2610 5555551 : if (right->IsCall() || right->IsCallNew()) {
2611 : fni_.RemoveLastFunction();
2612 : } else {
2613 : fni_.Infer();
2614 : }
2615 :
2616 5555470 : impl()->SetFunctionNameFromIdentifierRef(right, expression);
2617 : } else {
2618 388139 : expression_scope()->RecordPatternError(
2619 : Scanner::Location(lhs_beg_pos, end_position()),
2620 : MessageTemplate::kInvalidDestructuringTarget);
2621 : fni_.RemoveLastFunction();
2622 : }
2623 :
2624 5653529 : return factory()->NewAssignment(op, expression, right, op_position);
2625 : }
2626 :
2627 : template <typename Impl>
2628 : typename ParserBase<Impl>::ExpressionT
2629 129754 : ParserBase<Impl>::ParseYieldExpression() {
2630 : // YieldExpression ::
2631 : // 'yield' ([no line terminator] '*'? AssignmentExpression)?
2632 : int pos = peek_position();
2633 86502 : expression_scope()->RecordParameterInitializerError(
2634 : scanner()->peek_location(), MessageTemplate::kYieldInParameter);
2635 : Consume(Token::YIELD);
2636 :
2637 43252 : CheckStackOverflow();
2638 :
2639 : // The following initialization is necessary.
2640 : ExpressionT expression = impl()->NullExpression();
2641 : bool delegating = false; // yield*
2642 43252 : if (!scanner()->HasLineTerminatorBeforeNext()) {
2643 41399 : if (Check(Token::MUL)) delegating = true;
2644 : switch (peek()) {
2645 : case Token::EOS:
2646 : case Token::SEMICOLON:
2647 : case Token::RBRACE:
2648 : case Token::RBRACK:
2649 : case Token::RPAREN:
2650 : case Token::COLON:
2651 : case Token::COMMA:
2652 : case Token::IN:
2653 : // The above set of tokens is the complete set of tokens that can appear
2654 : // after an AssignmentExpression, and none of them can start an
2655 : // AssignmentExpression. This allows us to avoid looking for an RHS for
2656 : // a regular yield, given only one look-ahead token.
2657 11839 : if (!delegating) break;
2658 : // Delegating yields require an RHS; fall through.
2659 : V8_FALLTHROUGH;
2660 : default:
2661 29962 : expression = ParseAssignmentExpressionCoverGrammar();
2662 29962 : break;
2663 : }
2664 : }
2665 :
2666 43253 : if (delegating) {
2667 2219 : ExpressionT yieldstar = factory()->NewYieldStar(expression, pos);
2668 5491 : impl()->RecordSuspendSourceRange(yieldstar, PositionAfterSemicolon());
2669 5491 : function_state_->AddSuspend();
2670 10982 : if (IsAsyncGeneratorFunction(function_state_->kind())) {
2671 : // iterator_close and delegated_iterator_output suspend ids.
2672 2781 : function_state_->AddSuspend();
2673 2781 : function_state_->AddSuspend();
2674 : }
2675 5491 : return yieldstar;
2676 : }
2677 :
2678 : // Hackily disambiguate o from o.next and o [Symbol.iterator]().
2679 : // TODO(verwaest): Come up with a better solution.
2680 : ExpressionT yield =
2681 17773 : factory()->NewYield(expression, pos, Suspend::kOnExceptionThrow);
2682 37763 : impl()->RecordSuspendSourceRange(yield, PositionAfterSemicolon());
2683 37761 : function_state_->AddSuspend();
2684 37761 : return yield;
2685 : }
2686 :
2687 : // Precedence = 3
2688 : template <typename Impl>
2689 : typename ParserBase<Impl>::ExpressionT
2690 96230859 : ParserBase<Impl>::ParseConditionalExpression() {
2691 : // ConditionalExpression ::
2692 : // LogicalOrExpression
2693 : // LogicalOrExpression '?' AssignmentExpression ':' AssignmentExpression
2694 :
2695 96230859 : int pos = peek_position();
2696 : // We start using the binary expression parser for prec >= 4 only!
2697 : ExpressionT expression = ParseBinaryExpression(4);
2698 : return peek() == Token::CONDITIONAL
2699 : ? ParseConditionalContinuation(expression, pos)
2700 96207891 : : expression;
2701 : }
2702 :
2703 : template <typename Impl>
2704 : typename ParserBase<Impl>::ExpressionT
2705 283081 : ParserBase<Impl>::ParseConditionalContinuation(ExpressionT expression,
2706 97027 : int pos) {
2707 : SourceRange then_range, else_range;
2708 :
2709 : ExpressionT left;
2710 : {
2711 : SourceRangeScope range_scope(scanner(), &then_range);
2712 : Consume(Token::CONDITIONAL);
2713 : // In parsing the first assignment expression in conditional
2714 : // expressions we always accept the 'in' keyword; see ECMA-262,
2715 : // section 11.12, page 58.
2716 : AcceptINScope scope(this, true);
2717 : left = ParseAssignmentExpression();
2718 : }
2719 : ExpressionT right;
2720 : {
2721 : SourceRangeScope range_scope(scanner(), &else_range);
2722 283097 : Expect(Token::COLON);
2723 : right = ParseAssignmentExpression();
2724 : }
2725 48515 : ExpressionT expr = factory()->NewConditional(expression, left, right, pos);
2726 : impl()->RecordConditionalSourceRange(expr, then_range, else_range);
2727 283099 : return expr;
2728 : }
2729 :
2730 : // Precedence >= 4
2731 : template <typename Impl>
2732 : typename ParserBase<Impl>::ExpressionT
2733 11024788 : ParserBase<Impl>::ParseBinaryContinuation(ExpressionT x, int prec, int prec1) {
2734 56837278 : do {
2735 : // prec1 >= 4
2736 191737392 : while (Token::Precedence(peek(), accept_IN_) == prec1) {
2737 : SourceRange right_range;
2738 : int pos = peek_position();
2739 : ExpressionT y;
2740 : Token::Value op;
2741 : {
2742 : SourceRangeScope right_range_scope(scanner(), &right_range);
2743 : op = Next();
2744 :
2745 : const bool is_right_associative = op == Token::EXP;
2746 10619747 : const int next_prec = is_right_associative ? prec1 : prec1 + 1;
2747 : y = ParseBinaryExpression(next_prec);
2748 : }
2749 :
2750 : // For now we distinguish between comparisons and other binary
2751 : // operations. (We could combine the two and get rid of this
2752 : // code and AST node eventually.)
2753 10618108 : if (Token::IsCompareOp(op)) {
2754 : // We have a comparison.
2755 : Token::Value cmp = op;
2756 929396 : switch (op) {
2757 27262 : case Token::NE: cmp = Token::EQ; break;
2758 157554 : case Token::NE_STRICT: cmp = Token::EQ_STRICT; break;
2759 : default: break;
2760 : }
2761 4973862 : x = factory()->NewCompareOperation(cmp, x, y, pos);
2762 929393 : if (cmp != op) {
2763 : // The comparison was negated - add a NOT.
2764 369637 : x = factory()->NewUnaryOperation(Token::NOT, x, pos);
2765 : }
2766 2662060 : } else if (!impl()->ShortcutNumericLiteralBinaryExpression(&x, y, op,
2767 : pos) &&
2768 1016815 : !impl()->CollapseNaryExpression(&x, y, op, pos, right_range)) {
2769 : // We have a "normal" binary operation.
2770 6326450 : x = factory()->NewBinaryOperation(op, x, y, pos);
2771 699044 : if (op == Token::OR || op == Token::AND) {
2772 : impl()->RecordBinaryOperationSourceRange(x, right_range);
2773 : }
2774 : }
2775 : }
2776 56837278 : --prec1;
2777 : } while (prec1 >= prec);
2778 :
2779 8455302 : return x;
2780 : }
2781 :
2782 : // Precedence >= 4
2783 : template <typename Impl>
2784 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseBinaryExpression(
2785 : int prec) {
2786 : DCHECK_GE(prec, 4);
2787 : ExpressionT x = ParseUnaryExpression();
2788 213655424 : int prec1 = Token::Precedence(peek(), accept_IN_);
2789 106824472 : if (prec1 >= prec) {
2790 8455249 : return ParseBinaryContinuation(x, prec, prec1);
2791 : }
2792 : return x;
2793 : }
2794 :
2795 : template <typename Impl>
2796 : typename ParserBase<Impl>::ExpressionT
2797 5361925 : ParserBase<Impl>::ParseUnaryOrPrefixExpression() {
2798 : Token::Value op = Next();
2799 : int pos = position();
2800 :
2801 : // Assume "! function ..." indicates the function is likely to be called.
2802 2732725 : if (op == Token::NOT && peek() == Token::FUNCTION) {
2803 289 : function_state_->set_next_function_is_likely_called();
2804 : }
2805 :
2806 2119251 : CheckStackOverflow();
2807 :
2808 : int expression_position = peek_position();
2809 1350659 : ExpressionT expression = ParseUnaryExpression();
2810 :
2811 2119151 : if (Token::IsUnaryOp(op)) {
2812 1860529 : if (op == Token::DELETE) {
2813 26053 : if (impl()->IsIdentifier(expression) && is_strict(language_mode())) {
2814 : // "delete identifier" is a syntax error in strict mode.
2815 1066 : ReportMessage(MessageTemplate::kStrictDelete);
2816 1066 : return impl()->FailureExpression();
2817 : }
2818 :
2819 22270 : if (impl()->IsPropertyWithPrivateFieldKey(expression)) {
2820 2400 : ReportMessage(MessageTemplate::kDeletePrivateField);
2821 2400 : return impl()->FailureExpression();
2822 : }
2823 : }
2824 :
2825 1857059 : if (peek() == Token::EXP) {
2826 2880 : ReportUnexpectedToken(Next());
2827 2880 : return impl()->FailureExpression();
2828 : }
2829 :
2830 : // Allow the parser's implementation to rewrite the expression.
2831 664463 : return impl()->BuildUnaryExpression(expression, op, pos);
2832 : }
2833 :
2834 : DCHECK(Token::IsCountOp(op));
2835 :
2836 258622 : if (V8_LIKELY(IsValidReferenceExpression(expression))) {
2837 253033 : if (impl()->IsIdentifier(expression)) {
2838 : expression_scope()->MarkIdentifierAsAssigned();
2839 : }
2840 : } else {
2841 5597 : expression = RewriteInvalidReferenceExpression(
2842 : expression, expression_position, end_position(),
2843 : MessageTemplate::kInvalidLhsInPrefixOp);
2844 : }
2845 :
2846 : return factory()->NewCountOperation(op, true /* prefix */, expression,
2847 201601 : position());
2848 : }
2849 :
2850 : template <typename Impl>
2851 : typename ParserBase<Impl>::ExpressionT
2852 133844 : ParserBase<Impl>::ParseAwaitExpression() {
2853 106802 : expression_scope()->RecordParameterInitializerError(
2854 : scanner()->peek_location(),
2855 : MessageTemplate::kAwaitExpressionFormalParameter);
2856 : int await_pos = peek_position();
2857 : Consume(Token::AWAIT);
2858 :
2859 53403 : CheckStackOverflow();
2860 :
2861 : ExpressionT value = ParseUnaryExpression();
2862 :
2863 27041 : ExpressionT expr = factory()->NewAwait(value, await_pos);
2864 53403 : function_state_->AddSuspend();
2865 53403 : impl()->RecordSuspendSourceRange(expr, PositionAfterSemicolon());
2866 53403 : return expr;
2867 : }
2868 :
2869 : template <typename Impl>
2870 : typename ParserBase<Impl>::ExpressionT
2871 106902838 : ParserBase<Impl>::ParseUnaryExpression() {
2872 : // UnaryExpression ::
2873 : // PostfixExpression
2874 : // 'delete' UnaryExpression
2875 : // 'void' UnaryExpression
2876 : // 'typeof' UnaryExpression
2877 : // '++' UnaryExpression
2878 : // '--' UnaryExpression
2879 : // '+' UnaryExpression
2880 : // '-' UnaryExpression
2881 : // '~' UnaryExpression
2882 : // '!' UnaryExpression
2883 : // [+Await] AwaitExpression[?Yield]
2884 :
2885 : Token::Value op = peek();
2886 109019773 : if (Token::IsUnaryOrCountOp(op)) return ParseUnaryOrPrefixExpression();
2887 106902838 : if (is_async_function() && op == Token::AWAIT) {
2888 53406 : return ParseAwaitExpression();
2889 : }
2890 : return ParsePostfixExpression();
2891 : }
2892 :
2893 : template <typename Impl>
2894 : typename ParserBase<Impl>::ExpressionT
2895 214669533 : ParserBase<Impl>::ParsePostfixExpression() {
2896 : // PostfixExpression ::
2897 : // LeftHandSideExpression ('++' | '--')?
2898 :
2899 106848000 : int lhs_beg_pos = peek_position();
2900 : ExpressionT expression = ParseLeftHandSideExpression();
2901 212633104 : if (!scanner()->HasLineTerminatorBeforeNext() && Token::IsCountOp(peek())) {
2902 785604 : if (V8_UNLIKELY(!IsValidReferenceExpression(expression))) {
2903 2835 : expression = RewriteInvalidReferenceExpression(
2904 : expression, lhs_beg_pos, end_position(),
2905 2835 : MessageTemplate::kInvalidLhsInPostfixOp);
2906 : }
2907 785562 : if (impl()->IsIdentifier(expression)) {
2908 764182 : expression_scope()->MarkIdentifierAsAssigned();
2909 : }
2910 :
2911 : Token::Value next = Next();
2912 785595 : expression =
2913 : factory()->NewCountOperation(next,
2914 : false /* postfix */,
2915 : expression,
2916 : position());
2917 : }
2918 : return expression;
2919 : }
2920 :
2921 : template <typename Impl>
2922 : typename ParserBase<Impl>::ExpressionT
2923 : ParserBase<Impl>::ParseLeftHandSideExpression() {
2924 : // LeftHandSideExpression ::
2925 : // (NewExpression | MemberExpression) ...
2926 :
2927 : ExpressionT result = ParseMemberWithNewPrefixesExpression();
2928 106989591 : if (!Token::IsPropertyOrCall(peek())) return result;
2929 12698624 : return ParseLeftHandSideContinuation(result);
2930 : }
2931 :
2932 : template <typename Impl>
2933 : typename ParserBase<Impl>::ExpressionT
2934 41155732 : ParserBase<Impl>::ParseLeftHandSideContinuation(ExpressionT result) {
2935 : DCHECK(Token::IsPropertyOrCall(peek()));
2936 :
2937 34086691 : if (V8_UNLIKELY(peek() == Token::LPAREN && impl()->IsIdentifier(result) &&
2938 : scanner()->current_token() == Token::ASYNC &&
2939 : !scanner()->HasLineTerminatorBeforeNext())) {
2940 : DCHECK(impl()->IsAsync(impl()->AsIdentifier(result)));
2941 : int pos = position();
2942 :
2943 : ArrowHeadParsingScope maybe_arrow(impl(),
2944 : FunctionKind::kAsyncArrowFunction);
2945 15551 : Scope::Snapshot scope_snapshot(scope());
2946 :
2947 7909 : ExpressionListT args(pointer_buffer());
2948 : bool has_spread;
2949 15552 : ParseArguments(&args, &has_spread, kMaybeArrowHead);
2950 15555 : if (V8_LIKELY(peek() == Token::ARROW)) {
2951 6330 : fni_.RemoveAsyncKeywordFromEnd();
2952 11291 : next_arrow_function_info_.scope = maybe_arrow.ValidateAndCreateScope();
2953 11293 : scope_snapshot.Reparent(next_arrow_function_info_.scope);
2954 : // async () => ...
2955 20968 : if (!args.length()) return factory()->NewEmptyParentheses(pos);
2956 : // async ( Arguments ) => ...
2957 2982 : ExpressionT result = impl()->ExpressionListToExpression(args);
2958 : result->mark_parenthesized();
2959 5682 : return result;
2960 : }
2961 :
2962 4263 : if (has_spread) {
2963 9 : result = impl()->SpreadCall(result, args, pos, Call::NOT_EVAL);
2964 : } else {
2965 4254 : result = factory()->NewCall(result, args, pos, Call::NOT_EVAL);
2966 : }
2967 :
2968 4263 : maybe_arrow.ValidateExpression();
2969 :
2970 : fni_.RemoveLastFunction();
2971 4263 : if (!Token::IsPropertyOrCall(peek())) return result;
2972 : }
2973 :
2974 13240328 : do {
2975 13239643 : switch (peek()) {
2976 : /* Property */
2977 : case Token::LBRACK: {
2978 : Consume(Token::LBRACK);
2979 : int pos = position();
2980 : AcceptINScope scope(this, true);
2981 20444 : ExpressionT index = ParseExpressionCoverGrammar();
2982 20443 : result = factory()->NewProperty(result, index, pos);
2983 20443 : Expect(Token::RBRACK);
2984 : break;
2985 : }
2986 :
2987 : /* Property */
2988 : case Token::PERIOD: {
2989 : Consume(Token::PERIOD);
2990 : int pos = position();
2991 285882 : ExpressionT key = ParsePropertyOrPrivatePropertyName();
2992 285884 : result = factory()->NewProperty(result, key, pos);
2993 82176 : break;
2994 : }
2995 :
2996 : /* Call */
2997 : case Token::LPAREN: {
2998 : int pos;
2999 6516415 : if (Token::IsCallable(scanner()->current_token())) {
3000 : // For call of an identifier we want to report position of
3001 : // the identifier as position of the call in the stack trace.
3002 : pos = position();
3003 : } else {
3004 : // For other kinds of calls we record position of the parenthesis as
3005 : // position of the call. Note that this is extremely important for
3006 : // expressions of the form function(){...}() for which call position
3007 : // should not point to the closing brace otherwise it will intersect
3008 : // with positions recorded for function literal and confuse debugger.
3009 : pos = peek_position();
3010 : // Also the trailing parenthesis are a hint that the function will
3011 : // be called immediately. If we happen to have parsed a preceding
3012 : // function literal eagerly, we can also compile it eagerly.
3013 162668 : if (result->IsFunctionLiteral()) {
3014 215414 : result->AsFunctionLiteral()->SetShouldEagerCompile();
3015 : result->AsFunctionLiteral()->mark_as_iife();
3016 : }
3017 : }
3018 : bool has_spread;
3019 6516429 : ExpressionListT args(pointer_buffer());
3020 12931858 : ParseArguments(&args, &has_spread);
3021 :
3022 : // Keep track of eval() calls since they disable all local variable
3023 : // optimizations.
3024 : // The calls that need special treatment are the
3025 : // direct eval calls. These calls are all of the form eval(...), with
3026 : // no explicit receiver.
3027 : // These calls are marked as potentially direct eval calls. Whether
3028 : // they are actually direct calls to eval is determined at run time.
3029 : Call::PossiblyEval is_possibly_eval =
3030 12932713 : CheckPossibleEvalCall(result, scope());
3031 :
3032 12932771 : if (has_spread) {
3033 9553 : result = impl()->SpreadCall(result, args, pos, is_possibly_eval);
3034 : } else {
3035 12923234 : result = factory()->NewCall(result, args, pos, is_possibly_eval);
3036 : }
3037 :
3038 : fni_.RemoveLastFunction();
3039 : break;
3040 : }
3041 :
3042 : /* Call */
3043 : default:
3044 : DCHECK(Token::IsTemplate(peek()));
3045 1488 : result = ParseTemplateLiteral(result, position(), true);
3046 1489 : break;
3047 : }
3048 : } while (Token::IsPropertyOrCall(peek()));
3049 6257622 : return result;
3050 : }
3051 :
3052 : template <typename Impl>
3053 : typename ParserBase<Impl>::ExpressionT
3054 1284979 : ParserBase<Impl>::ParseMemberWithPresentNewPrefixesExpression() {
3055 : // NewExpression ::
3056 : // ('new')+ MemberExpression
3057 : //
3058 : // NewTarget ::
3059 : // 'new' '.' 'target'
3060 :
3061 : // The grammar for new expressions is pretty warped. We can have several 'new'
3062 : // keywords following each other, and then a MemberExpression. When we see '('
3063 : // after the MemberExpression, it's associated with the rightmost unassociated
3064 : // 'new' to create a NewExpression with arguments. However, a NewExpression
3065 : // can also occur without arguments.
3066 :
3067 : // Examples of new expression:
3068 : // new foo.bar().baz means (new (foo.bar)()).baz
3069 : // new foo()() means (new foo())()
3070 : // new new foo()() means (new (new foo())())
3071 : // new new foo means new (new foo)
3072 : // new new foo() means new (new foo())
3073 : // new new foo().bar().baz means (new (new foo()).bar()).baz
3074 : Consume(Token::NEW);
3075 : int new_pos = position();
3076 : ExpressionT result;
3077 :
3078 554499 : CheckStackOverflow();
3079 :
3080 554389 : if (peek() == Token::SUPER) {
3081 : const bool is_new = true;
3082 7738 : result = ParseSuperExpression(is_new);
3083 1083203 : } else if (allow_harmony_dynamic_import() && peek() == Token::IMPORT &&
3084 : (!allow_harmony_import_meta() || PeekAhead() == Token::LPAREN)) {
3085 2000 : impl()->ReportMessageAt(scanner()->peek_location(),
3086 : MessageTemplate::kImportCallNotNewExpression);
3087 2000 : return impl()->FailureExpression();
3088 544674 : } else if (peek() == Token::PERIOD) {
3089 8042 : result = ParseNewTargetExpression();
3090 2983 : return ParseMemberExpressionContinuation(result);
3091 : } else {
3092 366741 : result = ParseMemberWithNewPrefixesExpression();
3093 : }
3094 544413 : if (peek() == Token::LPAREN) {
3095 : // NewExpression with arguments.
3096 : {
3097 146265 : ExpressionListT args(pointer_buffer());
3098 : bool has_spread;
3099 499786 : ParseArguments(&args, &has_spread);
3100 :
3101 499747 : if (has_spread) {
3102 367 : result = impl()->SpreadCallNew(result, args, new_pos);
3103 : } else {
3104 499381 : result = factory()->NewCallNew(result, args, new_pos);
3105 : }
3106 : }
3107 : // The expression can still continue with . or [ after the arguments.
3108 146277 : return ParseMemberExpressionContinuation(result);
3109 : }
3110 : // NewExpression without arguments.
3111 26645 : ExpressionListT args(pointer_buffer());
3112 26645 : return factory()->NewCallNew(result, args, new_pos);
3113 : }
3114 :
3115 : template <typename Impl>
3116 : typename ParserBase<Impl>::ExpressionT
3117 : ParserBase<Impl>::ParseMemberWithNewPrefixesExpression() {
3118 : return peek() == Token::NEW ? ParseMemberWithPresentNewPrefixesExpression()
3119 107522907 : : ParseMemberExpression();
3120 : }
3121 :
3122 : template <typename Impl>
3123 : typename ParserBase<Impl>::ExpressionT
3124 4755651 : ParserBase<Impl>::ParseFunctionExpression() {
3125 : Consume(Token::FUNCTION);
3126 : int function_token_position = position();
3127 :
3128 : FunctionKind function_kind = Check(Token::MUL)
3129 : ? FunctionKind::kGeneratorFunction
3130 1926184 : : FunctionKind::kNormalFunction;
3131 80781 : IdentifierT name = impl()->NullIdentifier();
3132 : bool is_strict_reserved_name = Token::IsStrictReservedWord(peek());
3133 1926187 : Scanner::Location function_name_location = Scanner::Location::invalid();
3134 : FunctionLiteral::FunctionType function_type =
3135 : FunctionLiteral::kAnonymousExpression;
3136 1845403 : if (impl()->ParsingDynamicFunctionDeclaration()) {
3137 : // We don't want dynamic functions to actually declare their name
3138 : // "anonymous". We just want that name in the toString().
3139 : Consume(Token::IDENTIFIER);
3140 : DCHECK_IMPLIES(!has_error(),
3141 : scanner()->CurrentSymbol(ast_value_factory()) ==
3142 : ast_value_factory()->anonymous_string());
3143 1585668 : } else if (peek_any_identifier()) {
3144 22970 : name = ParseIdentifier(function_kind);
3145 903541 : function_name_location = scanner()->location();
3146 : function_type = FunctionLiteral::kNamedExpression;
3147 : }
3148 : FunctionLiteralT result = impl()->ParseFunctionLiteral(
3149 : name, function_name_location,
3150 : is_strict_reserved_name ? kFunctionNameIsStrictReserved
3151 : : kFunctionNameValidityUnknown,
3152 : function_kind, function_token_position, function_type, language_mode(),
3153 1925973 : nullptr);
3154 : // TODO(verwaest): FailureFunctionLiteral?
3155 1926881 : if (impl()->IsNull(result)) return impl()->FailureExpression();
3156 80781 : return result;
3157 : }
3158 :
3159 : template <typename Impl>
3160 : typename ParserBase<Impl>::ExpressionT
3161 105007035 : ParserBase<Impl>::ParseMemberExpression() {
3162 : // MemberExpression ::
3163 : // (PrimaryExpression | FunctionLiteral | ClassLiteral)
3164 : // ('[' Expression ']' | '.' Identifier | Arguments | TemplateLiteral)*
3165 : //
3166 : // CallExpression ::
3167 : // (SuperCall | ImportCall)
3168 : // ('[' Expression ']' | '.' Identifier | Arguments | TemplateLiteral)*
3169 : //
3170 : // The '[' Expression ']' and '.' Identifier parts are parsed by
3171 : // ParseMemberExpressionContinuation, and the Arguments part is parsed by the
3172 : // caller.
3173 :
3174 : // Parse the initial primary or function expression.
3175 53452531 : ExpressionT result;
3176 106962166 : if (peek() == Token::FUNCTION) {
3177 1926188 : result = ParseFunctionExpression();
3178 105027618 : } else if (peek() == Token::SUPER) {
3179 : const bool is_new = false;
3180 20583 : result = ParseSuperExpression(is_new);
3181 203763208 : } else if (allow_harmony_dynamic_import() && peek() == Token::IMPORT) {
3182 31717 : result = ParseImportExpressions();
3183 : } else {
3184 104971156 : result = ParsePrimaryExpression();
3185 : }
3186 :
3187 : return ParseMemberExpressionContinuation(result);
3188 : }
3189 :
3190 : template <typename Impl>
3191 : typename ParserBase<Impl>::ExpressionT
3192 133324 : ParserBase<Impl>::ParseImportExpressions() {
3193 : DCHECK(allow_harmony_dynamic_import());
3194 :
3195 : Consume(Token::IMPORT);
3196 : int pos = position();
3197 57216 : if (allow_harmony_import_meta() && peek() == Token::PERIOD) {
3198 49226 : ExpectMetaProperty(ast_value_factory()->meta_string(), "import.meta", pos);
3199 24613 : if (!parsing_module_) {
3200 13478 : impl()->ReportMessageAt(scanner()->location(),
3201 : MessageTemplate::kImportMetaOutsideModule);
3202 13478 : return impl()->FailureExpression();
3203 : }
3204 :
3205 3210 : return impl()->ImportMetaExpression(pos);
3206 : }
3207 7105 : Expect(Token::LPAREN);
3208 7104 : if (peek() == Token::RPAREN) {
3209 80 : impl()->ReportMessageAt(scanner()->location(),
3210 : MessageTemplate::kImportMissingSpecifier);
3211 80 : return impl()->FailureExpression();
3212 : }
3213 : AcceptINScope scope(this, true);
3214 7024 : ExpressionT arg = ParseAssignmentExpressionCoverGrammar();
3215 7025 : Expect(Token::RPAREN);
3216 :
3217 3598 : return factory()->NewImportCallExpression(arg, pos);
3218 : }
3219 :
3220 : template <typename Impl>
3221 28320 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseSuperExpression(
3222 43851 : bool is_new) {
3223 : Consume(Token::SUPER);
3224 : int pos = position();
3225 :
3226 28323 : DeclarationScope* scope = GetReceiverScope();
3227 : FunctionKind kind = scope->function_kind();
3228 65632 : if (IsConciseMethod(kind) || IsAccessorFunction(kind) ||
3229 : IsClassConstructor(kind)) {
3230 16971 : if (Token::IsProperty(peek())) {
3231 : scope->RecordSuperPropertyUsage();
3232 2758 : return impl()->NewSuperPropertyReference(pos);
3233 : }
3234 : // new super() is never allowed.
3235 : // super() is only allowed in derived constructor
3236 23474 : if (!is_new && peek() == Token::LPAREN && IsDerivedConstructor(kind)) {
3237 : // TODO(rossberg): This might not be the correct FunctionState for the
3238 : // method here.
3239 2745 : return impl()->NewSuperCallReference(pos);
3240 : }
3241 : }
3242 :
3243 15528 : impl()->ReportMessageAt(scanner()->location(),
3244 : MessageTemplate::kUnexpectedSuper);
3245 15525 : return impl()->FailureExpression();
3246 : }
3247 :
3248 : template <typename Impl>
3249 32653 : void ParserBase<Impl>::ExpectMetaProperty(const AstRawString* property_name,
3250 32654 : const char* full_name, int pos) {
3251 : Consume(Token::PERIOD);
3252 32655 : ExpectContextualKeyword(property_name);
3253 32654 : if (V8_UNLIKELY(scanner()->literal_contains_escapes())) {
3254 210 : impl()->ReportMessageAt(Scanner::Location(pos, end_position()),
3255 : MessageTemplate::kInvalidEscapedMetaProperty,
3256 : full_name);
3257 : }
3258 32654 : }
3259 :
3260 : template <typename Impl>
3261 : typename ParserBase<Impl>::ExpressionT
3262 18060 : ParserBase<Impl>::ParseNewTargetExpression() {
3263 : int pos = position();
3264 16080 : ExpectMetaProperty(ast_value_factory()->target_string(), "new.target", pos);
3265 :
3266 8039 : if (!GetReceiverScope()->is_function_scope()) {
3267 1980 : impl()->ReportMessageAt(scanner()->location(),
3268 : MessageTemplate::kUnexpectedNewTarget);
3269 1980 : return impl()->FailureExpression();
3270 : }
3271 :
3272 2003 : return impl()->NewTargetExpression(pos);
3273 : }
3274 :
3275 : template <typename Impl>
3276 : typename ParserBase<Impl>::ExpressionT
3277 35233920 : ParserBase<Impl>::DoParseMemberExpressionContinuation(ExpressionT expression) {
3278 : DCHECK(Token::IsMember(peek()));
3279 : // Parses this part of MemberExpression:
3280 : // ('[' Expression ']' | '.' Identifier | TemplateLiteral)*
3281 18340809 : do {
3282 18339296 : switch (peek()) {
3283 : case Token::LBRACK: {
3284 : Consume(Token::LBRACK);
3285 : int pos = position();
3286 : AcceptINScope scope(this, true);
3287 4121770 : ExpressionT index = ParseExpressionCoverGrammar();
3288 4121792 : expression = factory()->NewProperty(expression, index, pos);
3289 : impl()->PushPropertyName(index);
3290 4121783 : Expect(Token::RBRACK);
3291 : break;
3292 : }
3293 : case Token::PERIOD: {
3294 : Consume(Token::PERIOD);
3295 : int pos = peek_position();
3296 14206308 : ExpressionT key = ParsePropertyOrPrivatePropertyName();
3297 14206854 : expression = factory()->NewProperty(expression, key, pos);
3298 5501288 : break;
3299 : }
3300 : default: {
3301 : DCHECK(Token::IsTemplate(peek()));
3302 : int pos;
3303 12734 : if (scanner()->current_token() == Token::IDENTIFIER) {
3304 : pos = position();
3305 : } else {
3306 : pos = peek_position();
3307 1785 : if (expression->IsFunctionLiteral()) {
3308 : // If the tag function looks like an IIFE, set_parenthesized() to
3309 : // force eager compilation.
3310 750 : expression->AsFunctionLiteral()->SetShouldEagerCompile();
3311 : }
3312 : }
3313 12734 : expression = ParseTemplateLiteral(expression, pos, true);
3314 12734 : break;
3315 : }
3316 : }
3317 : } while (Token::IsMember(peek()));
3318 16894659 : return expression;
3319 : }
3320 :
3321 : template <typename Impl>
3322 19099913 : void ParserBase<Impl>::ParseFormalParameter(FormalParametersT* parameters) {
3323 : // FormalParameter[Yield,GeneratorParameter] :
3324 : // BindingElement[?Yield, ?GeneratorParameter]
3325 3899665 : FuncNameInferrerState fni_state(&fni_);
3326 7638861 : int pos = peek_position();
3327 7638855 : ExpressionT pattern = ParseBindingPattern();
3328 7638922 : if (impl()->IsIdentifier(pattern)) {
3329 15122835 : ClassifyParameter(impl()->AsIdentifier(pattern), pos, end_position());
3330 : } else {
3331 77543 : parameters->is_simple = false;
3332 : }
3333 :
3334 : ExpressionT initializer = impl()->NullExpression();
3335 7638904 : if (Check(Token::ASSIGN)) {
3336 112238 : parameters->is_simple = false;
3337 :
3338 112238 : if (parameters->has_rest) {
3339 0 : ReportMessage(MessageTemplate::kRestDefaultInitializer);
3340 22 : return;
3341 : }
3342 :
3343 112238 : AcceptINScope scope(this, true);
3344 : initializer = ParseAssignmentExpression();
3345 112236 : impl()->SetFunctionNameFromIdentifierRef(initializer, pattern);
3346 : }
3347 :
3348 11538576 : impl()->AddFormalParameter(parameters, pattern, initializer, end_position(),
3349 3899668 : parameters->has_rest);
3350 : }
3351 :
3352 : template <typename Impl>
3353 7132813 : void ParserBase<Impl>::ParseFormalParameterList(FormalParametersT* parameters) {
3354 : // FormalParameters[Yield] :
3355 : // [empty]
3356 : // FunctionRestParameter[?Yield]
3357 : // FormalParameterList[?Yield]
3358 : // FormalParameterList[?Yield] ,
3359 : // FormalParameterList[?Yield] , FunctionRestParameter[?Yield]
3360 : //
3361 : // FormalParameterList[Yield] :
3362 : // FormalParameter[?Yield]
3363 : // FormalParameterList[?Yield] , FormalParameter[?Yield]
3364 : ParameterParsingScope scope(impl(), parameters);
3365 :
3366 : DCHECK_EQ(0, parameters->arity);
3367 :
3368 4292572 : if (peek() != Token::RPAREN) {
3369 : while (true) {
3370 : // Add one since we're going to be adding a parameter.
3371 7619810 : if (parameters->arity + 1 > Code::kMaxArguments) {
3372 18 : ReportMessage(MessageTemplate::kTooManyParameters);
3373 18 : return;
3374 : }
3375 7619706 : parameters->has_rest = Check(Token::ELLIPSIS);
3376 : ParseFormalParameter(parameters);
3377 :
3378 7619561 : if (parameters->has_rest) {
3379 14981 : parameters->is_simple = false;
3380 14981 : if (peek() == Token::COMMA) {
3381 3200 : impl()->ReportMessageAt(scanner()->peek_location(),
3382 : MessageTemplate::kParamAfterRest);
3383 3200 : return;
3384 : }
3385 : break;
3386 : }
3387 7604626 : if (!Check(Token::COMMA)) break;
3388 5195067 : if (peek() == Token::RPAREN) {
3389 : // allow the trailing comma
3390 : break;
3391 : }
3392 : }
3393 : }
3394 :
3395 : impl()->DeclareFormalParameters(parameters);
3396 : }
3397 :
3398 : template <typename Impl>
3399 13821666 : void ParserBase<Impl>::ParseVariableDeclarations(
3400 : VariableDeclarationContext var_context,
3401 121504860 : DeclarationParsingResult* parsing_result) {
3402 : // VariableDeclarations ::
3403 : // ('var' | 'const' | 'let') (Identifier ('=' AssignmentExpression)?)+[',']
3404 : //
3405 : // ES6:
3406 : // FIXME(marja, nikolaos): Add an up-to-date comment about ES6 variable
3407 : // declaration syntax.
3408 :
3409 : DCHECK_NOT_NULL(parsing_result);
3410 13821666 : parsing_result->descriptor.kind = NORMAL_VARIABLE;
3411 13821666 : parsing_result->descriptor.declaration_pos = peek_position();
3412 13821666 : parsing_result->descriptor.initialization_pos = peek_position();
3413 :
3414 13821753 : switch (peek()) {
3415 : case Token::VAR:
3416 11677106 : parsing_result->descriptor.mode = VariableMode::kVar;
3417 : Consume(Token::VAR);
3418 : break;
3419 : case Token::CONST:
3420 : Consume(Token::CONST);
3421 : DCHECK_NE(var_context, kStatement);
3422 537684 : parsing_result->descriptor.mode = VariableMode::kConst;
3423 537684 : break;
3424 : case Token::LET:
3425 : Consume(Token::LET);
3426 : DCHECK_NE(var_context, kStatement);
3427 1606811 : parsing_result->descriptor.mode = VariableMode::kLet;
3428 1606811 : break;
3429 : default:
3430 0 : UNREACHABLE(); // by current callers
3431 : break;
3432 : }
3433 :
3434 : int bindings_start = peek_position();
3435 14278921 : do {
3436 : // Parse binding pattern.
3437 9346320 : FuncNameInferrerState fni_state(&fni_);
3438 :
3439 : ExpressionT pattern = impl()->NullExpression();
3440 : int decl_pos = peek_position();
3441 : {
3442 : VariableDeclarationParsingScope declaration(
3443 14342863 : impl(), parsing_result->descriptor.mode);
3444 14342863 : pattern = ParseBindingPattern();
3445 :
3446 14342938 : if (IsLexicalVariableMode(parsing_result->descriptor.mode)) {
3447 2340734 : if (impl()->IsIdentifier(pattern)) {
3448 2198778 : if (impl()->IsLet(impl()->AsIdentifier(pattern))) {
3449 2200 : impl()->ReportMessageAt(
3450 : Scanner::Location(bindings_start, end_position()),
3451 : MessageTemplate::kLetInLexicalBinding);
3452 : }
3453 : }
3454 : }
3455 : }
3456 14342995 : Scanner::Location variable_loc = scanner()->location();
3457 :
3458 : ExpressionT value = impl()->NullExpression();
3459 : int initializer_position = kNoSourcePosition;
3460 : int value_beg_position = kNoSourcePosition;
3461 14343098 : if (Check(Token::ASSIGN)) {
3462 : value_beg_position = peek_position();
3463 :
3464 : {
3465 11527929 : AcceptINScope scope(this, var_context != kForStatement);
3466 : value = ParseAssignmentExpression();
3467 : }
3468 : variable_loc.end_pos = end_position();
3469 :
3470 11527538 : if (!parsing_result->first_initializer_loc.IsValid()) {
3471 11406846 : parsing_result->first_initializer_loc = variable_loc;
3472 : }
3473 :
3474 : // Don't infer if it is "a = function(){...}();"-like expression.
3475 7053996 : if (impl()->IsIdentifier(pattern)) {
3476 7027392 : if (!value->IsCall() && !value->IsCallNew()) {
3477 : fni_.Infer();
3478 : } else {
3479 : fni_.RemoveLastFunction();
3480 : }
3481 : }
3482 :
3483 7054075 : impl()->SetFunctionNameFromIdentifierRef(value, pattern);
3484 :
3485 : // End position of the initializer is after the assignment expression.
3486 : initializer_position = end_position();
3487 : } else {
3488 2815169 : if (var_context != kForStatement || !PeekInOrOf()) {
3489 : // ES6 'const' and binding patterns require initializers.
3490 5163685 : if (parsing_result->descriptor.mode == VariableMode::kConst ||
3491 : !impl()->IsIdentifier(pattern)) {
3492 129224 : impl()->ReportMessageAt(
3493 : Scanner::Location(decl_pos, end_position()),
3494 : MessageTemplate::kDeclarationMissingInitializer,
3495 : !impl()->IsIdentifier(pattern) ? "destructuring" : "const");
3496 13887250 : return;
3497 : }
3498 : // 'let x' initializes 'x' to undefined.
3499 2527519 : if (parsing_result->descriptor.mode == VariableMode::kLet) {
3500 195117 : value = factory()->NewUndefinedLiteral(position());
3501 : }
3502 : }
3503 :
3504 : // End position of the initializer is after the variable.
3505 : initializer_position = position();
3506 : }
3507 :
3508 : typename DeclarationParsingResult::Declaration decl(
3509 : pattern, initializer_position, value);
3510 14278112 : decl.value_beg_position = value_beg_position;
3511 14278112 : parsing_result->declarations.push_back(decl);
3512 : } while (Check(Token::COMMA));
3513 :
3514 13758026 : parsing_result->bindings_loc =
3515 : Scanner::Location(bindings_start, end_position());
3516 : }
3517 :
3518 : template <typename Impl>
3519 : typename ParserBase<Impl>::StatementT
3520 3192 : ParserBase<Impl>::ParseFunctionDeclaration() {
3521 : Consume(Token::FUNCTION);
3522 :
3523 : int pos = position();
3524 : ParseFunctionFlags flags = ParseFunctionFlag::kIsNormal;
3525 1436 : if (Check(Token::MUL)) {
3526 320 : impl()->ReportMessageAt(
3527 : scanner()->location(),
3528 : MessageTemplate::kGeneratorInSingleStatementContext);
3529 320 : return impl()->NullStatement();
3530 : }
3531 1116 : return ParseHoistableDeclaration(pos, flags, nullptr, false);
3532 : }
3533 :
3534 : template <typename Impl>
3535 : typename ParserBase<Impl>::StatementT
3536 1001669 : ParserBase<Impl>::ParseHoistableDeclaration(
3537 1001775 : ZonePtrList<const AstRawString>* names, bool default_export) {
3538 : Consume(Token::FUNCTION);
3539 :
3540 : int pos = position();
3541 : ParseFunctionFlags flags = ParseFunctionFlag::kIsNormal;
3542 1001766 : if (Check(Token::MUL)) {
3543 : flags |= ParseFunctionFlag::kIsGenerator;
3544 : }
3545 1001766 : return ParseHoistableDeclaration(pos, flags, names, default_export);
3546 : }
3547 :
3548 : template <typename Impl>
3549 : typename ParserBase<Impl>::StatementT
3550 1157194 : ParserBase<Impl>::ParseHoistableDeclaration(
3551 : int pos, ParseFunctionFlags flags, ZonePtrList<const AstRawString>* names,
3552 3240456 : bool default_export) {
3553 1157194 : CheckStackOverflow();
3554 :
3555 : // FunctionDeclaration ::
3556 : // 'function' Identifier '(' FormalParameters ')' '{' FunctionBody '}'
3557 : // 'function' '(' FormalParameters ')' '{' FunctionBody '}'
3558 : // GeneratorDeclaration ::
3559 : // 'function' '*' Identifier '(' FormalParameters ')' '{' FunctionBody '}'
3560 : // 'function' '*' '(' FormalParameters ')' '{' FunctionBody '}'
3561 : //
3562 : // The anonymous forms are allowed iff [default_export] is true.
3563 : //
3564 : // 'function' and '*' (if present) have been consumed by the caller.
3565 :
3566 : DCHECK_IMPLIES((flags & ParseFunctionFlag::kIsAsync) != 0,
3567 : (flags & ParseFunctionFlag::kIsGenerator) == 0);
3568 :
3569 1311587 : if ((flags & ParseFunctionFlag::kIsAsync) != 0 && Check(Token::MUL)) {
3570 : // Async generator
3571 : flags |= ParseFunctionFlag::kIsGenerator;
3572 : }
3573 :
3574 : IdentifierT name;
3575 : FunctionNameValidity name_validity;
3576 : IdentifierT variable_name;
3577 1157319 : if (default_export && peek() == Token::LPAREN) {
3578 : impl()->GetDefaultStrings(&name, &variable_name);
3579 : name_validity = kSkipFunctionNameCheck;
3580 : } else {
3581 : bool is_strict_reserved = Token::IsStrictReservedWord(peek());
3582 : name = ParseIdentifier();
3583 1157191 : name_validity = is_strict_reserved ? kFunctionNameIsStrictReserved
3584 : : kFunctionNameValidityUnknown;
3585 : variable_name = name;
3586 : }
3587 :
3588 926022 : FuncNameInferrerState fni_state(&fni_);
3589 : impl()->PushEnclosingName(name);
3590 :
3591 : FunctionKind kind = FunctionKindFor(flags);
3592 :
3593 : FunctionLiteralT function = impl()->ParseFunctionLiteral(
3594 : name, scanner()->location(), name_validity, kind, pos,
3595 2314402 : FunctionLiteral::kDeclaration, language_mode(), nullptr);
3596 :
3597 : // In ES6, a function behaves as a lexical binding, except in
3598 : // a script scope, or the initial scope of eval or another function.
3599 : VariableMode mode =
3600 1129325 : (!scope()->is_declaration_scope() || scope()->is_module_scope())
3601 : ? VariableMode::kLet
3602 2286562 : : VariableMode::kVar;
3603 : // Async functions don't undergo sloppy mode block scoped hoisting, and don't
3604 : // allow duplicates in a block. Both are represented by the
3605 : // sloppy_block_function_map. Don't add them to the map for async functions.
3606 : // Generators are also supposed to be prohibited; currently doing this behind
3607 : // a flag and UseCounting violations to assess web compatibility.
3608 : bool is_sloppy_block_function = is_sloppy(language_mode()) &&
3609 : !scope()->is_declaration_scope() &&
3610 1157237 : flags == ParseFunctionFlag::kIsNormal;
3611 :
3612 : return impl()->DeclareFunction(variable_name, function, mode, pos,
3613 : end_position(), is_sloppy_block_function,
3614 2083255 : names);
3615 : }
3616 :
3617 : template <typename Impl>
3618 173376 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseClassDeclaration(
3619 451454 : ZonePtrList<const AstRawString>* names, bool default_export) {
3620 : // ClassDeclaration ::
3621 : // 'class' Identifier ('extends' LeftHandExpression)? '{' ClassBody '}'
3622 : // 'class' ('extends' LeftHandExpression)? '{' ClassBody '}'
3623 : //
3624 : // The anonymous form is allowed iff [default_export] is true.
3625 : //
3626 : // 'class' is expected to be consumed by the caller.
3627 : //
3628 : // A ClassDeclaration
3629 : //
3630 : // class C { ... }
3631 : //
3632 : // has the same semantics as:
3633 : //
3634 : // let C = class C { ... };
3635 : //
3636 : // so rewrite it as such.
3637 :
3638 : int class_token_pos = position();
3639 68683 : IdentifierT name = impl()->NullIdentifier();
3640 : bool is_strict_reserved = Token::IsStrictReservedWord(peek());
3641 : IdentifierT variable_name = impl()->NullIdentifier();
3642 173452 : if (default_export && (peek() == Token::EXTENDS || peek() == Token::LBRACE)) {
3643 : impl()->GetDefaultStrings(&name, &variable_name);
3644 : } else {
3645 : name = ParseIdentifier();
3646 : variable_name = name;
3647 : }
3648 :
3649 173381 : ExpressionParsingScope no_expression_scope(impl());
3650 : ExpressionT value = ParseClassLiteral(name, scanner()->location(),
3651 346764 : is_strict_reserved, class_token_pos);
3652 : no_expression_scope.ValidateExpression();
3653 : int end_pos = position();
3654 : return impl()->DeclareClass(variable_name, value, names, class_token_pos,
3655 278078 : end_pos);
3656 : }
3657 :
3658 : // Language extension which is only enabled for source files loaded
3659 : // through the API's extension mechanism. A native function
3660 : // declaration is resolved by looking up the function through a
3661 : // callback provided by the extension.
3662 : template <typename Impl>
3663 : typename ParserBase<Impl>::StatementT
3664 3522 : ParserBase<Impl>::ParseNativeDeclaration() {
3665 1761 : function_state_->DisableOptimization(BailoutReason::kNativeFunctionLiteral);
3666 :
3667 : int pos = peek_position();
3668 : Consume(Token::FUNCTION);
3669 : // Allow "eval" or "arguments" for backward compatibility.
3670 : IdentifierT name = ParseIdentifier();
3671 1761 : Expect(Token::LPAREN);
3672 1761 : if (peek() != Token::RPAREN) {
3673 0 : do {
3674 : ParseIdentifier();
3675 : } while (Check(Token::COMMA));
3676 : }
3677 1761 : Expect(Token::RPAREN);
3678 1761 : Expect(Token::SEMICOLON);
3679 1761 : return impl()->DeclareNative(name, pos);
3680 : }
3681 :
3682 : template <typename Impl>
3683 : typename ParserBase<Impl>::StatementT
3684 154387 : ParserBase<Impl>::ParseAsyncFunctionDeclaration(
3685 154387 : ZonePtrList<const AstRawString>* names, bool default_export) {
3686 : // AsyncFunctionDeclaration ::
3687 : // async [no LineTerminator here] function BindingIdentifier[Await]
3688 : // ( FormalParameters[Await] ) { AsyncFunctionBody }
3689 : DCHECK_EQ(scanner()->current_token(), Token::ASYNC);
3690 : int pos = position();
3691 : DCHECK(!scanner()->HasLineTerminatorBeforeNext());
3692 : Consume(Token::FUNCTION);
3693 : ParseFunctionFlags flags = ParseFunctionFlag::kIsAsync;
3694 154390 : return ParseHoistableDeclaration(pos, flags, names, default_export);
3695 : }
3696 :
3697 : template <typename Impl>
3698 2696335 : void ParserBase<Impl>::ParseFunctionBody(
3699 29703 : StatementListT* body, IdentifierT function_name, int pos,
3700 : const FormalParametersT& parameters, FunctionKind kind,
3701 4377801 : FunctionLiteral::FunctionType function_type, FunctionBodyType body_type) {
3702 1820395 : if (IsResumableFunction(kind)) impl()->PrepareGeneratorVariables();
3703 :
3704 2696342 : DeclarationScope* function_scope = parameters.scope;
3705 : DeclarationScope* inner_scope = function_scope;
3706 :
3707 : // Building the parameter initialization block declares the parameters.
3708 : // TODO(verwaest): Rely on ArrowHeadParsingScope instead.
3709 2696342 : if (V8_UNLIKELY(!parameters.is_simple)) {
3710 167106 : if (has_error()) return;
3711 51805 : BlockT init_block = impl()->BuildParameterInitializationBlock(parameters);
3712 54365 : if (IsAsyncFunction(kind) && !IsAsyncGeneratorFunction(kind)) {
3713 1765 : init_block = impl()->BuildRejectPromiseOnException(init_block);
3714 : }
3715 : body->Add(init_block);
3716 51805 : if (has_error()) return;
3717 :
3718 50216 : inner_scope = NewVarblockScope();
3719 50218 : inner_scope->set_start_position(scanner()->location().beg_pos);
3720 : }
3721 :
3722 1800636 : StatementListT inner_body(pointer_buffer());
3723 :
3724 : {
3725 2637899 : BlockState block_state(&scope_, inner_scope);
3726 :
3727 2637899 : if (body_type == FunctionBodyType::kExpression) {
3728 : ExpressionT expression = ParseAssignmentExpression();
3729 :
3730 644951 : if (IsAsyncFunction(kind)) {
3731 2245 : BlockT block = factory()->NewBlock(1, true);
3732 2246 : impl()->RewriteAsyncFunctionBody(&inner_body, block, expression);
3733 : } else {
3734 641362 : inner_body.Add(
3735 : BuildReturnStatement(expression, expression->position()));
3736 : }
3737 : } else {
3738 : DCHECK(accept_IN_);
3739 : DCHECK_EQ(FunctionBodyType::kBlock, body_type);
3740 : // If we are parsing the source as if it is wrapped in a function, the
3741 : // source ends without a closing brace.
3742 : Token::Value closing_token = function_type == FunctionLiteral::kWrapped
3743 : ? Token::EOS
3744 1992925 : : Token::RBRACE;
3745 :
3746 1992925 : if (IsAsyncGeneratorFunction(kind)) {
3747 24123 : impl()->ParseAndRewriteAsyncGeneratorFunctionBody(pos, kind,
3748 : &inner_body);
3749 1932125 : } else if (IsGeneratorFunction(kind)) {
3750 24692 : impl()->ParseAndRewriteGeneratorFunctionBody(pos, kind, &inner_body);
3751 1876734 : } else if (IsAsyncFunction(kind)) {
3752 91300 : ParseAsyncFunctionBody(inner_scope, &inner_body);
3753 : } else {
3754 : ParseStatementList(&inner_body, closing_token);
3755 : }
3756 :
3757 1992944 : if (IsDerivedConstructor(kind)) {
3758 5912 : inner_body.Add(factory()->NewReturnStatement(impl()->ThisExpression(),
3759 : kNoSourcePosition));
3760 : }
3761 1992944 : Expect(closing_token);
3762 : }
3763 : }
3764 :
3765 : scope()->set_end_position(end_position());
3766 :
3767 : bool allow_duplicate_parameters = false;
3768 :
3769 2637899 : if (V8_LIKELY(parameters.is_simple)) {
3770 : DCHECK_EQ(inner_scope, function_scope);
3771 2587681 : if (is_sloppy(function_scope->language_mode())) {
3772 1017836 : impl()->InsertSloppyBlockFunctionVarBindings(function_scope);
3773 : }
3774 5420339 : allow_duplicate_parameters = is_sloppy(function_scope->language_mode()) &&
3775 : !IsConciseMethod(kind) &&
3776 : !IsArrowFunction(kind);
3777 : } else {
3778 : DCHECK_NOT_NULL(inner_scope);
3779 : DCHECK_EQ(function_scope, scope());
3780 : DCHECK_EQ(function_scope, inner_scope->outer_scope());
3781 28115 : impl()->SetLanguageMode(function_scope, inner_scope->language_mode());
3782 :
3783 50217 : if (is_sloppy(inner_scope->language_mode())) {
3784 16283 : impl()->InsertSloppyBlockFunctionVarBindings(inner_scope);
3785 : }
3786 :
3787 : inner_scope->set_end_position(end_position());
3788 50217 : if (inner_scope->FinalizeBlockScope() != nullptr) {
3789 10499 : BlockT inner_block = factory()->NewBlock(true, inner_body);
3790 : inner_body.Rewind();
3791 10500 : inner_body.Add(inner_block);
3792 : inner_block->set_scope(inner_scope);
3793 : const AstRawString* conflict = inner_scope->FindVariableDeclaredIn(
3794 10764 : function_scope, VariableMode::kLastLexicalVariableMode);
3795 10764 : if (conflict != nullptr) {
3796 90 : impl()->ReportVarRedeclarationIn(conflict, inner_scope);
3797 : }
3798 10500 : impl()->CheckConflictingVarDeclarations(inner_scope);
3799 10499 : impl()->InsertShadowingVarBindingInitializers(inner_block);
3800 : }
3801 : }
3802 :
3803 2637870 : ValidateFormalParameters(language_mode(), parameters,
3804 2637870 : allow_duplicate_parameters);
3805 :
3806 2637873 : if (!IsArrowFunction(kind)) {
3807 : // Declare arguments after parsing the function since lexical 'arguments'
3808 : // masks the arguments object. Declare arguments before declaring the
3809 : // function var since the arguments object masks 'function arguments'.
3810 1639467 : function_scope->DeclareArguments(ast_value_factory());
3811 : }
3812 :
3813 1800632 : impl()->DeclareFunctionNameVar(function_name, function_type, function_scope);
3814 :
3815 : inner_body.MergeInto(body);
3816 : }
3817 :
3818 : template <typename Impl>
3819 4116491 : void ParserBase<Impl>::CheckArityRestrictions(int param_count,
3820 : FunctionKind function_kind,
3821 : bool has_rest,
3822 : int formals_start_pos,
3823 : int formals_end_pos) {
3824 4116491 : if (IsGetterFunction(function_kind)) {
3825 44861 : if (param_count != 0) {
3826 6162 : impl()->ReportMessageAt(
3827 : Scanner::Location(formals_start_pos, formals_end_pos),
3828 : MessageTemplate::kBadGetterArity);
3829 : }
3830 4071630 : } else if (IsSetterFunction(function_kind)) {
3831 37077 : if (param_count != 1) {
3832 1022 : impl()->ReportMessageAt(
3833 : Scanner::Location(formals_start_pos, formals_end_pos),
3834 : MessageTemplate::kBadSetterArity);
3835 : }
3836 37077 : if (has_rest) {
3837 900 : impl()->ReportMessageAt(
3838 : Scanner::Location(formals_start_pos, formals_end_pos),
3839 : MessageTemplate::kBadSetterRestParameter);
3840 : }
3841 : }
3842 4116491 : }
3843 :
3844 : template <typename Impl>
3845 1598331 : bool ParserBase<Impl>::IsNextLetKeyword() {
3846 : DCHECK_EQ(Token::LET, peek());
3847 : Token::Value next_next = PeekAhead();
3848 1598768 : switch (next_next) {
3849 : case Token::LBRACE:
3850 : case Token::LBRACK:
3851 : case Token::IDENTIFIER:
3852 : case Token::STATIC:
3853 : case Token::LET: // `let let;` is disallowed by static semantics, but the
3854 : // token must be first interpreted as a keyword in order
3855 : // for those semantics to apply. This ensures that ASI is
3856 : // not honored when a LineTerminator separates the
3857 : // tokens.
3858 : case Token::YIELD:
3859 : case Token::AWAIT:
3860 : case Token::ASYNC:
3861 : return true;
3862 : case Token::FUTURE_STRICT_RESERVED_WORD:
3863 3280 : return is_sloppy(language_mode());
3864 : default:
3865 8378 : return false;
3866 : }
3867 : }
3868 :
3869 : template <typename Impl>
3870 : typename ParserBase<Impl>::ExpressionT
3871 1023801 : ParserBase<Impl>::ParseArrowFunctionLiteral(
3872 1684489 : const FormalParametersT& formal_parameters) {
3873 : const RuntimeCallCounterId counters[2][2] = {
3874 : {RuntimeCallCounterId::kParseBackgroundArrowFunctionLiteral,
3875 : RuntimeCallCounterId::kParseArrowFunctionLiteral},
3876 : {RuntimeCallCounterId::kPreParseBackgroundArrowFunctionLiteral,
3877 1023801 : RuntimeCallCounterId::kPreParseArrowFunctionLiteral}};
3878 : RuntimeCallTimerScope runtime_timer(
3879 : runtime_call_stats_,
3880 1023801 : counters[Impl::IsPreParser()][parsing_on_main_thread_]);
3881 : base::ElapsedTimer timer;
3882 1023801 : if (V8_UNLIKELY(FLAG_log_function_events)) timer.Start();
3883 :
3884 : DCHECK_IMPLIES(!has_error(), peek() == Token::ARROW);
3885 2047602 : if (scanner_->HasLineTerminatorBeforeNext()) {
3886 : // ASI inserts `;` after arrow parameters if a line terminator is found.
3887 : // `=> ...` is never a valid expression, so report as syntax error.
3888 : // If next token is not `=>`, it's a syntax error anyways.
3889 480 : ReportUnexpectedTokenAt(scanner_->peek_location(), Token::ARROW);
3890 480 : return impl()->FailureExpression();
3891 : }
3892 :
3893 : int expected_property_count = -1;
3894 : int suspend_count = 0;
3895 : int function_literal_id = GetNextFunctionLiteralId();
3896 :
3897 1023321 : FunctionKind kind = formal_parameters.scope->function_kind();
3898 : FunctionLiteral::EagerCompileHint eager_compile_hint =
3899 567535 : default_eager_compile_hint_;
3900 567535 : bool can_preparse = impl()->parse_lazily() &&
3901 567535 : eager_compile_hint == FunctionLiteral::kShouldLazyCompile;
3902 : // TODO(marja): consider lazy-parsing inner arrow functions too. is_this
3903 : // handling in Scope::ResolveVariable needs to change.
3904 : bool is_lazy_top_level_function =
3905 896819 : can_preparse && impl()->AllowsLazyParsingWithoutUnresolvedVariables();
3906 : bool has_braces = true;
3907 567541 : ProducedPreparseData* produced_preparse_data = nullptr;
3908 567541 : StatementListT body(pointer_buffer());
3909 : {
3910 : FunctionState function_state(&function_state_, &scope_,
3911 1023327 : formal_parameters.scope);
3912 :
3913 : Consume(Token::ARROW);
3914 :
3915 1023340 : if (peek() == Token::LBRACE) {
3916 : // Multiple statement body
3917 : DCHECK_EQ(scope(), formal_parameters.scope);
3918 :
3919 127793 : if (is_lazy_top_level_function) {
3920 : // FIXME(marja): Arrow function parameters will be parsed even if the
3921 : // body is preparsed; move relevant parts of parameter handling to
3922 : // simulate consistent parameter handling.
3923 :
3924 : // Building the parameter initialization block declares the parameters.
3925 : // TODO(verwaest): Rely on ArrowHeadParsingScope instead.
3926 27266 : if (!formal_parameters.is_simple) {
3927 3326 : impl()->BuildParameterInitializationBlock(formal_parameters);
3928 6045 : if (has_error()) return impl()->FailureExpression();
3929 : }
3930 :
3931 : // For arrow functions, we don't need to retrieve data about function
3932 : // parameters.
3933 27212 : int dummy_num_parameters = -1;
3934 : DCHECK_NE(kind & FunctionKind::kArrowFunction, 0);
3935 : bool did_preparse_successfully = impl()->SkipFunction(
3936 : nullptr, kind, FunctionLiteral::kAnonymousExpression,
3937 : formal_parameters.scope, &dummy_num_parameters,
3938 27212 : &produced_preparse_data);
3939 :
3940 : DCHECK_NULL(produced_preparse_data);
3941 :
3942 27214 : if (did_preparse_successfully) {
3943 : // Validate parameter names. We can do this only after preparsing the
3944 : // function, since the function can declare itself strict.
3945 24603 : ValidateFormalParameters(language_mode(), formal_parameters, false);
3946 : } else {
3947 : // In case we did not sucessfully preparse the function because of an
3948 : // unidentified error we do a full reparse to return the error.
3949 : // Parse again in the outer scope, since the language mode may change.
3950 2611 : BlockState block_state(&scope_, scope()->outer_scope());
3951 : ExpressionT expression = ParseConditionalExpression();
3952 2611 : DeclarationScope* function_scope = next_arrow_function_info_.scope;
3953 : FunctionState function_state(&function_state_, &scope_,
3954 : function_scope);
3955 : Scanner::Location loc(function_scope->start_position(),
3956 2611 : end_position());
3957 : FormalParametersT parameters(function_scope);
3958 2611 : parameters.is_simple = function_scope->has_simple_parameters();
3959 2611 : impl()->DeclareArrowFunctionFormalParameters(¶meters, expression,
3960 : loc);
3961 : next_arrow_function_info_.Reset();
3962 :
3963 : Consume(Token::ARROW);
3964 : Consume(Token::LBRACE);
3965 :
3966 : AcceptINScope scope(this, true);
3967 2611 : ParseFunctionBody(&body, impl()->NullIdentifier(), kNoSourcePosition,
3968 : parameters, kind,
3969 : FunctionLiteral::kAnonymousExpression,
3970 : FunctionBodyType::kBlock);
3971 2611 : CHECK(has_error());
3972 : return impl()->FailureExpression();
3973 : }
3974 : } else {
3975 : Consume(Token::LBRACE);
3976 : AcceptINScope scope(this, true);
3977 350944 : ParseFunctionBody(&body, impl()->NullIdentifier(), kNoSourcePosition,
3978 : formal_parameters, kind,
3979 : FunctionLiteral::kAnonymousExpression,
3980 851763 : FunctionBodyType::kBlock);
3981 100526 : expected_property_count = function_state.expected_property_count();
3982 : }
3983 : } else {
3984 : // Single-expression body
3985 : has_braces = false;
3986 645141 : ParseFunctionBody(&body, impl()->NullIdentifier(), kNoSourcePosition,
3987 : formal_parameters, kind,
3988 : FunctionLiteral::kAnonymousExpression,
3989 1055890 : FunctionBodyType::kExpression);
3990 439723 : expected_property_count = function_state.expected_property_count();
3991 : }
3992 :
3993 2809007 : formal_parameters.scope->set_end_position(end_position());
3994 :
3995 : // Validate strict mode.
3996 1020627 : if (is_strict(language_mode())) {
3997 658632 : CheckStrictOctalLiteral(formal_parameters.scope->start_position(),
3998 658632 : end_position());
3999 : }
4000 564849 : impl()->CheckConflictingVarDeclarations(formal_parameters.scope);
4001 :
4002 564856 : suspend_count = function_state.suspend_count();
4003 : }
4004 :
4005 : FunctionLiteralT function_literal = factory()->NewFunctionLiteral(
4006 : impl()->EmptyIdentifierString(), formal_parameters.scope, body,
4007 : expected_property_count, formal_parameters.num_parameters(),
4008 : formal_parameters.function_length,
4009 : FunctionLiteral::kNoDuplicateParameters,
4010 : FunctionLiteral::kAnonymousExpression, eager_compile_hint,
4011 : formal_parameters.scope->start_position(), has_braces,
4012 1694584 : function_literal_id, produced_preparse_data);
4013 :
4014 : function_literal->set_suspend_count(suspend_count);
4015 564892 : function_literal->set_function_token_position(
4016 : formal_parameters.scope->start_position());
4017 :
4018 : impl()->AddFunctionForNameInference(function_literal);
4019 :
4020 1020668 : if (V8_UNLIKELY((FLAG_log_function_events))) {
4021 16 : Scope* scope = formal_parameters.scope;
4022 8 : double ms = timer.Elapsed().InMillisecondsF();
4023 : const char* event_name =
4024 4 : is_lazy_top_level_function ? "preparse-no-resolution" : "parse";
4025 : const char* name = "arrow function";
4026 8 : logger_->FunctionEvent(event_name, script_id(), ms, scope->start_position(),
4027 : scope->end_position(), name, strlen(name));
4028 : }
4029 :
4030 1020667 : return function_literal;
4031 : }
4032 :
4033 : template <typename Impl>
4034 309874 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseClassLiteral(
4035 : IdentifierT name, Scanner::Location class_name_location,
4036 778979 : bool name_is_strict_reserved, int class_token_pos) {
4037 : bool is_anonymous = impl()->IsNull(name);
4038 :
4039 : // All parts of a ClassDeclaration and ClassExpression are strict code.
4040 309874 : if (!is_anonymous) {
4041 191435 : if (name_is_strict_reserved) {
4042 1080 : impl()->ReportMessageAt(class_name_location,
4043 : MessageTemplate::kUnexpectedStrictReserved);
4044 1080 : return impl()->FailureExpression();
4045 : }
4046 190355 : if (impl()->IsEvalOrArguments(name)) {
4047 320 : impl()->ReportMessageAt(class_name_location,
4048 : MessageTemplate::kStrictEvalArguments);
4049 320 : return impl()->FailureExpression();
4050 : }
4051 : }
4052 :
4053 : Scope* block_scope = NewScope(BLOCK_SCOPE);
4054 308481 : BlockState block_state(&scope_, block_scope);
4055 308481 : RaiseLanguageMode(LanguageMode::kStrict);
4056 :
4057 308483 : ClassInfo class_info(this);
4058 308479 : class_info.is_anonymous = is_anonymous;
4059 181499 : impl()->DeclareClassVariable(name, &class_info, class_token_pos);
4060 :
4061 : scope()->set_start_position(end_position());
4062 308482 : if (Check(Token::EXTENDS)) {
4063 60174 : FuncNameInferrerState fni_state(&fni_);
4064 111430 : ExpressionParsingScope scope(impl());
4065 111429 : class_info.extends = ParseLeftHandSideExpression();
4066 60172 : scope.ValidateExpression();
4067 : }
4068 :
4069 308480 : Expect(Token::LBRACE);
4070 :
4071 435457 : const bool has_extends = !impl()->IsNull(class_info.extends);
4072 1511173 : while (peek() != Token::RBRACE) {
4073 685958 : if (Check(Token::SEMICOLON)) continue;
4074 467273 : FuncNameInferrerState fni_state(&fni_);
4075 : // If we haven't seen the constructor yet, it potentially is the next
4076 : // property.
4077 467273 : bool is_constructor = !class_info.has_seen_constructor;
4078 140461 : ParsePropertyInfo prop_info(this);
4079 140461 : prop_info.position = PropertyPosition::kClassLiteral;
4080 : ClassLiteralPropertyT property =
4081 607734 : ParseClassPropertyDefinition(&class_info, &prop_info, has_extends);
4082 :
4083 754213 : if (has_error()) return impl()->FailureExpression();
4084 :
4085 : ClassLiteralProperty::Kind property_kind =
4086 461283 : ClassPropertyKindFor(prop_info.kind);
4087 461279 : if (!class_info.has_static_computed_names && prop_info.is_static &&
4088 : prop_info.is_computed_name) {
4089 5124 : class_info.has_static_computed_names = true;
4090 : }
4091 393838 : is_constructor &= class_info.has_seen_constructor;
4092 :
4093 461279 : if (V8_UNLIKELY(property_kind == ClassLiteralProperty::FIELD)) {
4094 61295 : if (prop_info.is_computed_name) {
4095 : DCHECK(!prop_info.is_private);
4096 9924 : class_info.computed_field_count++;
4097 : }
4098 :
4099 61295 : impl()->DeclareClassField(property, prop_info.name, prop_info.is_static,
4100 : prop_info.is_computed_name,
4101 : prop_info.is_private, &class_info);
4102 : } else {
4103 362135 : impl()->DeclareClassProperty(name, property, is_constructor, &class_info);
4104 : }
4105 : impl()->InferFunctionName();
4106 : }
4107 :
4108 162013 : Expect(Token::RBRACE);
4109 : int end_pos = end_position();
4110 : block_scope->set_end_position(end_pos);
4111 : return impl()->RewriteClassLiteral(block_scope, name, &class_info,
4112 108057 : class_token_pos, end_pos);
4113 : }
4114 :
4115 : template <typename Impl>
4116 91298 : void ParserBase<Impl>::ParseAsyncFunctionBody(Scope* scope,
4117 91299 : StatementListT* body) {
4118 : BlockT block = impl()->NullBlock();
4119 : {
4120 39947 : StatementListT statements(pointer_buffer());
4121 : ParseStatementList(&statements, Token::RBRACE);
4122 39949 : block = factory()->NewBlock(true, statements);
4123 : }
4124 79898 : impl()->RewriteAsyncFunctionBody(
4125 : body, block, factory()->NewUndefinedLiteral(kNoSourcePosition));
4126 : scope->set_end_position(end_position());
4127 91299 : }
4128 :
4129 : template <typename Impl>
4130 : typename ParserBase<Impl>::ExpressionT
4131 42610 : ParserBase<Impl>::ParseAsyncFunctionLiteral() {
4132 : // AsyncFunctionLiteral ::
4133 : // async [no LineTerminator here] function ( FormalParameters[Await] )
4134 : // { AsyncFunctionBody }
4135 : //
4136 : // async [no LineTerminator here] function BindingIdentifier[Await]
4137 : // ( FormalParameters[Await] ) { AsyncFunctionBody }
4138 : DCHECK_EQ(scanner()->current_token(), Token::ASYNC);
4139 : int pos = position();
4140 : Consume(Token::FUNCTION);
4141 8060 : IdentifierT name = impl()->NullIdentifier();
4142 : FunctionLiteral::FunctionType type = FunctionLiteral::kAnonymousExpression;
4143 :
4144 : ParseFunctionFlags flags = ParseFunctionFlag::kIsAsync;
4145 21305 : if (Check(Token::MUL)) flags |= ParseFunctionFlag::kIsGenerator;
4146 : const FunctionKind kind = FunctionKindFor(flags);
4147 : bool is_strict_reserved = Token::IsStrictReservedWord(peek());
4148 :
4149 13245 : if (impl()->ParsingDynamicFunctionDeclaration()) {
4150 : // We don't want dynamic functions to actually declare their name
4151 : // "anonymous". We just want that name in the toString().
4152 :
4153 : // Consuming token we did not peek yet, which could lead to a ILLEGAL token
4154 : // in the case of a stackoverflow.
4155 : Consume(Token::IDENTIFIER);
4156 : DCHECK_IMPLIES(!has_error(),
4157 : scanner()->CurrentSymbol(ast_value_factory()) ==
4158 : ast_value_factory()->anonymous_string());
4159 20695 : } else if (peek_any_identifier()) {
4160 : type = FunctionLiteral::kNamedExpression;
4161 3604 : name = ParseIdentifier(kind);
4162 : }
4163 : FunctionLiteralT result = impl()->ParseFunctionLiteral(
4164 : name, scanner()->location(),
4165 : is_strict_reserved ? kFunctionNameIsStrictReserved
4166 : : kFunctionNameValidityUnknown,
4167 42610 : kind, pos, type, language_mode(), nullptr);
4168 21565 : if (impl()->IsNull(result)) return impl()->FailureExpression();
4169 8060 : return result;
4170 : }
4171 :
4172 : template <typename Impl>
4173 73493 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseTemplateLiteral(
4174 211583 : ExpressionT tag, int start, bool tagged) {
4175 : // A TemplateLiteral is made up of 0 or more TEMPLATE_SPAN tokens (literal
4176 : // text followed by a substitution expression), finalized by a single
4177 : // TEMPLATE_TAIL.
4178 : //
4179 : // In terms of draft language, TEMPLATE_SPAN may be either the TemplateHead or
4180 : // TemplateMiddle productions, while TEMPLATE_TAIL is either TemplateTail, or
4181 : // NoSubstitutionTemplate.
4182 : //
4183 : // When parsing a TemplateLiteral, we must have scanned either an initial
4184 : // TEMPLATE_SPAN, or a TEMPLATE_TAIL.
4185 : DCHECK(peek() == Token::TEMPLATE_SPAN || peek() == Token::TEMPLATE_TAIL);
4186 :
4187 73493 : if (tagged) {
4188 : // TaggedTemplate expressions prevent the eval compilation cache from being
4189 : // used. This flag is only used if an eval is being parsed.
4190 : set_allow_eval_cache(false);
4191 : }
4192 :
4193 73493 : bool forbid_illegal_escapes = !tagged;
4194 :
4195 : // If we reach a TEMPLATE_TAIL first, we are parsing a NoSubstitutionTemplate.
4196 : // In this case we may simply consume the token and build a template with a
4197 : // single TEMPLATE_SPAN and no expressions.
4198 73495 : if (peek() == Token::TEMPLATE_TAIL) {
4199 : Consume(Token::TEMPLATE_TAIL);
4200 : int pos = position();
4201 9867 : typename Impl::TemplateLiteralState ts = impl()->OpenTemplateLiteral(pos);
4202 18400 : bool is_valid = CheckTemplateEscapes(forbid_illegal_escapes);
4203 9867 : impl()->AddTemplateSpan(&ts, is_valid, true);
4204 9867 : return impl()->CloseTemplateLiteral(&ts, start, tag);
4205 : }
4206 :
4207 : Consume(Token::TEMPLATE_SPAN);
4208 : int pos = position();
4209 28775 : typename Impl::TemplateLiteralState ts = impl()->OpenTemplateLiteral(pos);
4210 55099 : bool is_valid = CheckTemplateEscapes(forbid_illegal_escapes);
4211 28773 : impl()->AddTemplateSpan(&ts, is_valid, false);
4212 : Token::Value next;
4213 :
4214 : // If we open with a TEMPLATE_SPAN, we must scan the subsequent expression,
4215 : // and repeat if the following token is a TEMPLATE_SPAN as well (in this
4216 : // case, representing a TemplateMiddle).
4217 :
4218 79914 : do {
4219 : next = peek();
4220 :
4221 : int expr_pos = peek_position();
4222 : AcceptINScope scope(this, true);
4223 86472 : ExpressionT expression = ParseExpressionCoverGrammar();
4224 : impl()->AddTemplateExpression(&ts, expression);
4225 :
4226 86469 : if (peek() != Token::RBRACE) {
4227 6558 : impl()->ReportMessageAt(Scanner::Location(expr_pos, peek_position()),
4228 : MessageTemplate::kUnterminatedTemplateExpr);
4229 3460 : return impl()->FailureExpression();
4230 : }
4231 :
4232 : // If we didn't die parsing that expression, our next token should be a
4233 : // TEMPLATE_SPAN or TEMPLATE_TAIL.
4234 : next = scanner()->ScanTemplateContinuation();
4235 : Next();
4236 : pos = position();
4237 :
4238 79914 : bool is_valid = CheckTemplateEscapes(forbid_illegal_escapes);
4239 45200 : impl()->AddTemplateSpan(&ts, is_valid, next == Token::TEMPLATE_TAIL);
4240 : } while (next == Token::TEMPLATE_SPAN);
4241 :
4242 : DCHECK_IMPLIES(!has_error(), next == Token::TEMPLATE_TAIL);
4243 : // Once we've reached a TEMPLATE_TAIL, we can close the TemplateLiteral.
4244 25677 : return impl()->CloseTemplateLiteral(&ts, start, tag);
4245 : }
4246 :
4247 : template <typename Impl>
4248 : typename ParserBase<Impl>::ExpressionT
4249 27960 : ParserBase<Impl>::RewriteInvalidReferenceExpression(ExpressionT expression,
4250 : int beg_pos, int end_pos,
4251 : MessageTemplate message,
4252 2271 : ParseErrorType type) {
4253 : DCHECK(!IsValidReferenceExpression(expression));
4254 27960 : if (impl()->IsIdentifier(expression)) {
4255 : DCHECK(is_strict(language_mode()));
4256 : DCHECK(impl()->IsEvalOrArguments(impl()->AsIdentifier(expression)));
4257 :
4258 5383 : ReportMessageAt(Scanner::Location(beg_pos, end_pos),
4259 5383 : MessageTemplate::kStrictEvalArguments, kSyntaxError);
4260 5383 : return impl()->FailureExpression();
4261 : }
4262 27299 : if (expression->IsCall() && !expression->AsCall()->is_tagged_template()) {
4263 2271 : expression_scope()->RecordPatternError(
4264 : Scanner::Location(beg_pos, end_pos),
4265 : MessageTemplate::kInvalidDestructuringTarget);
4266 : // If it is a call, make it a runtime error for legacy web compatibility.
4267 : // Bug: https://bugs.chromium.org/p/v8/issues/detail?id=4480
4268 : // Rewrite `expr' to `expr[throw ReferenceError]'.
4269 2271 : impl()->CountUsage(
4270 : is_strict(language_mode())
4271 : ? v8::Isolate::kAssigmentExpressionLHSIsCallInStrict
4272 : : v8::Isolate::kAssigmentExpressionLHSIsCallInSloppy);
4273 1052 : ExpressionT error = impl()->NewThrowReferenceError(message, beg_pos);
4274 3490 : return factory()->NewProperty(expression, error, beg_pos);
4275 : }
4276 20306 : ReportMessageAt(Scanner::Location(beg_pos, end_pos), message, type);
4277 20306 : return impl()->FailureExpression();
4278 : }
4279 :
4280 : template <typename Impl>
4281 15148531 : void ParserBase<Impl>::ClassifyParameter(IdentifierT parameter, int begin,
4282 15755 : int end) {
4283 15148549 : if (impl()->IsEvalOrArguments(parameter)) {
4284 15755 : expression_scope()->RecordStrictModeParameterError(
4285 : Scanner::Location(begin, end), MessageTemplate::kStrictEvalArguments);
4286 : }
4287 15148549 : }
4288 :
4289 : template <typename Impl>
4290 39576416 : void ParserBase<Impl>::ClassifyArrowParameter(
4291 : AccumulationScope* accumulation_scope, int position,
4292 81167132 : ExpressionT parameter) {
4293 39576416 : accumulation_scope->Accumulate();
4294 117938183 : if (parameter->is_parenthesized() ||
4295 51582442 : !(impl()->IsIdentifier(parameter) || parameter->IsPattern() ||
4296 : parameter->IsAssignment())) {
4297 23080350 : expression_scope()->RecordDeclarationError(
4298 : Scanner::Location(position, end_position()),
4299 : MessageTemplate::kInvalidDestructuringTarget);
4300 16500996 : } else if (impl()->IsIdentifier(parameter)) {
4301 5162492 : ClassifyParameter(impl()->AsIdentifier(parameter), position,
4302 : end_position());
4303 : } else {
4304 : expression_scope()->RecordNonSimpleParameter();
4305 : }
4306 39581955 : }
4307 :
4308 : template <typename Impl>
4309 14025086 : bool ParserBase<Impl>::IsValidReferenceExpression(ExpressionT expression) {
4310 24893249 : return IsAssignableIdentifier(expression) || expression->IsProperty();
4311 : }
4312 :
4313 : template <typename Impl>
4314 : typename ParserBase<Impl>::ExpressionT
4315 12957058 : ParserBase<Impl>::ParsePossibleDestructuringSubPattern(
4316 36050028 : AccumulationScope* scope) {
4317 12957058 : if (scope) scope->Accumulate();
4318 : int begin = peek_position();
4319 21476928 : ExpressionT result = ParseAssignmentExpressionCoverGrammar();
4320 :
4321 12956808 : if (IsValidReferenceExpression(result)) {
4322 : // Parenthesized identifiers and property references are allowed as part of
4323 : // a larger assignment pattern, even though parenthesized patterns
4324 : // themselves are not allowed, e.g., "[(x)] = []". Only accumulate
4325 : // assignment pattern errors if the parsed expression is more complex.
4326 2427155 : if (impl()->IsIdentifier(result)) {
4327 2131262 : if (result->is_parenthesized()) {
4328 8353 : expression_scope()->RecordDeclarationError(
4329 : Scanner::Location(begin, end_position()),
4330 : MessageTemplate::kInvalidDestructuringTarget);
4331 : }
4332 : IdentifierT identifier = impl()->AsIdentifier(result);
4333 2131245 : ClassifyParameter(identifier, begin, end_position());
4334 2131244 : if (impl()->IsLet(identifier)) {
4335 1560 : expression_scope()->RecordLexicalDeclarationError(
4336 : Scanner::Location(begin, end_position()),
4337 : MessageTemplate::kLetInLexicalBinding);
4338 : }
4339 : } else {
4340 : DCHECK(result->IsProperty());
4341 295893 : expression_scope()->RecordDeclarationError(
4342 : Scanner::Location(begin, end_position()),
4343 : MessageTemplate::kInvalidPropertyBindingPattern);
4344 295890 : if (scope != nullptr) scope->ValidateExpression();
4345 : }
4346 31363430 : } else if (result->is_parenthesized() ||
4347 : (!result->IsPattern() && !result->IsAssignment())) {
4348 10174836 : expression_scope()->RecordPatternError(
4349 : Scanner::Location(begin, end_position()),
4350 : MessageTemplate::kInvalidDestructuringTarget);
4351 : }
4352 :
4353 12956942 : return result;
4354 : }
4355 :
4356 : template <typename Impl>
4357 128128 : typename ParserBase<Impl>::ExpressionT ParserBase<Impl>::ParseV8Intrinsic() {
4358 : // CallRuntime ::
4359 : // '%' Identifier Arguments
4360 :
4361 : int pos = peek_position();
4362 : Consume(Token::MOD);
4363 : // Allow "eval" or "arguments" for backward compatibility.
4364 : IdentifierT name = ParseIdentifier();
4365 128198 : if (peek() != Token::LPAREN) {
4366 0 : impl()->ReportUnexpectedToken(peek());
4367 0 : return impl()->FailureExpression();
4368 : }
4369 : bool has_spread;
4370 54711 : ExpressionListT args(pointer_buffer());
4371 128198 : ParseArguments(&args, &has_spread);
4372 :
4373 128208 : if (has_spread) {
4374 9 : ReportMessageAt(Scanner::Location(pos, position()),
4375 9 : MessageTemplate::kIntrinsicWithSpread, kSyntaxError);
4376 9 : return impl()->FailureExpression();
4377 : }
4378 :
4379 54719 : return impl()->NewV8Intrinsic(name, args, pos);
4380 : }
4381 :
4382 : template <typename Impl>
4383 : void ParserBase<Impl>::ParseStatementList(StatementListT* body,
4384 4563001 : Token::Value end_token) {
4385 : // StatementList ::
4386 : // (StatementListItem)* <end_token>
4387 : DCHECK_NOT_NULL(body);
4388 :
4389 8142547 : while (peek() == Token::STRING) {
4390 : bool use_strict = false;
4391 : bool use_asm = false;
4392 :
4393 1521004 : Scanner::Location token_loc = scanner()->peek_location();
4394 :
4395 1521005 : if (scanner()->NextLiteralEquals("use strict")) {
4396 : use_strict = true;
4397 1100454 : } else if (scanner()->NextLiteralEquals("use asm")) {
4398 : use_asm = true;
4399 : }
4400 :
4401 1521001 : StatementT stat = ParseStatementListItem();
4402 1529559 : if (impl()->IsNull(stat)) return;
4403 :
4404 1314095 : body->Add(stat);
4405 :
4406 1520996 : if (!impl()->IsStringLiteral(stat)) break;
4407 :
4408 1514743 : if (use_strict) {
4409 : // Directive "use strict" (ES5 14.1).
4410 420538 : RaiseLanguageMode(LanguageMode::kStrict);
4411 420538 : if (!scope()->HasSimpleParameters()) {
4412 : // TC39 deemed "use strict" directives to be an error when occurring
4413 : // in the body of a function with non-simple parameter list, on
4414 : // 29/7/2015. https://goo.gl/ueA7Ln
4415 8527 : impl()->ReportMessageAt(token_loc,
4416 : MessageTemplate::kIllegalLanguageModeDirective,
4417 : "use strict");
4418 : return;
4419 : }
4420 1094205 : } else if (use_asm) {
4421 : // Directive "use asm".
4422 4830 : impl()->SetAsmModule();
4423 : } else {
4424 : // Possibly an unknown directive.
4425 : // Should not change mode, but will increment usage counters
4426 : // as appropriate. Ditto usages below.
4427 1086122 : RaiseLanguageMode(LanguageMode::kSloppy);
4428 : }
4429 : }
4430 :
4431 : // Allocate a target stack to use for this set of source elements. This way,
4432 : // all scripts and functions get their own target stack thus avoiding illegal
4433 : // breaks and continues across functions.
4434 3046648 : TargetScopeT target_scope(this);
4435 39038286 : while (peek() != end_token) {
4436 33254222 : StatementT stat = ParseStatementListItem();
4437 34097748 : if (impl()->IsNull(stat)) return;
4438 32411616 : if (stat->IsEmptyStatement()) continue;
4439 17660556 : body->Add(stat);
4440 2595943 : }
4441 : }
4442 :
4443 : template <typename Impl>
4444 : typename ParserBase<Impl>::StatementT
4445 42528133 : ParserBase<Impl>::ParseStatementListItem() {
4446 : // ECMA 262 6th Edition
4447 : // StatementListItem[Yield, Return] :
4448 : // Statement[?Yield, ?Return]
4449 : // Declaration[?Yield]
4450 : //
4451 : // Declaration[Yield] :
4452 : // HoistableDeclaration[?Yield]
4453 : // ClassDeclaration[?Yield]
4454 : // LexicalDeclaration[In, ?Yield]
4455 : //
4456 : // HoistableDeclaration[Yield, Default] :
4457 : // FunctionDeclaration[?Yield, ?Default]
4458 : // GeneratorDeclaration[?Yield, ?Default]
4459 : //
4460 : // LexicalDeclaration[In, Yield] :
4461 : // LetOrConst BindingList[?In, ?Yield] ;
4462 :
4463 42372091 : switch (peek()) {
4464 : case Token::FUNCTION:
4465 1001323 : return ParseHoistableDeclaration(nullptr, false);
4466 : case Token::CLASS:
4467 : Consume(Token::CLASS);
4468 173313 : return ParseClassDeclaration(nullptr, false);
4469 : case Token::VAR:
4470 : case Token::CONST:
4471 11729622 : return ParseVariableStatement(kStatementListItem, nullptr);
4472 : case Token::LET:
4473 1349006 : if (IsNextLetKeyword()) {
4474 1341376 : return ParseVariableStatement(kStatementListItem, nullptr);
4475 : }
4476 : break;
4477 : case Token::ASYNC:
4478 310242 : if (PeekAhead() == Token::FUNCTION &&
4479 : !scanner()->HasLineTerminatorAfterNext()) {
4480 : Consume(Token::ASYNC);
4481 154263 : return ParseAsyncFunctionDeclaration(nullptr, false);
4482 : }
4483 : break;
4484 : default:
4485 : break;
4486 : }
4487 27972491 : return ParseStatement(nullptr, nullptr, kAllowLabelledFunctionStatement);
4488 : }
4489 :
4490 : template <typename Impl>
4491 32796004 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseStatement(
4492 : ZonePtrList<const AstRawString>* labels,
4493 : ZonePtrList<const AstRawString>* own_labels,
4494 955664 : AllowLabelledFunctionStatement allow_function) {
4495 : // Statement ::
4496 : // Block
4497 : // VariableStatement
4498 : // EmptyStatement
4499 : // ExpressionStatement
4500 : // IfStatement
4501 : // IterationStatement
4502 : // ContinueStatement
4503 : // BreakStatement
4504 : // ReturnStatement
4505 : // WithStatement
4506 : // LabelledStatement
4507 : // SwitchStatement
4508 : // ThrowStatement
4509 : // TryStatement
4510 : // DebuggerStatement
4511 :
4512 : // {own_labels} is always a subset of {labels}.
4513 : DCHECK_IMPLIES(labels == nullptr, own_labels == nullptr);
4514 :
4515 : // Note: Since labels can only be used by 'break' and 'continue'
4516 : // statements, which themselves are only valid within blocks,
4517 : // iterations or 'switch' statements (i.e., BreakableStatements),
4518 : // labels can be simply ignored in all other cases; except for
4519 : // trivial labeled break statements 'label: break label' which is
4520 : // parsed into an empty statement.
4521 32795685 : switch (peek()) {
4522 : case Token::LBRACE:
4523 3130647 : return ParseBlock(labels);
4524 : case Token::SEMICOLON:
4525 : Next();
4526 262360 : return factory()->EmptyStatement();
4527 : case Token::IF:
4528 3240438 : return ParseIfStatement(labels);
4529 : case Token::DO:
4530 18942 : return ParseDoWhileStatement(labels, own_labels);
4531 : case Token::WHILE:
4532 37038 : return ParseWhileStatement(labels, own_labels);
4533 : case Token::FOR:
4534 1076569 : if (V8_UNLIKELY(is_async_function() && PeekAhead() == Token::AWAIT)) {
4535 128542 : return ParseForAwaitStatement(labels, own_labels);
4536 : }
4537 814139 : return ParseForStatement(labels, own_labels);
4538 : case Token::CONTINUE:
4539 55456 : return ParseContinueStatement();
4540 : case Token::BREAK:
4541 196968 : return ParseBreakStatement(labels);
4542 : case Token::RETURN:
4543 3541507 : return ParseReturnStatement();
4544 : case Token::THROW:
4545 277242 : return ParseThrowStatement();
4546 : case Token::TRY: {
4547 : // It is somewhat complicated to have labels on try-statements.
4548 : // When breaking out of a try-finally statement, one must take
4549 : // great care not to treat it as a fall-through. It is much easier
4550 : // just to wrap the entire try-statement in a statement block and
4551 : // put the labels there.
4552 509574 : if (labels == nullptr) return ParseTryStatement();
4553 113 : StatementListT statements(pointer_buffer());
4554 113 : BlockT result = factory()->NewBlock(false, labels);
4555 : TargetT target(this, result);
4556 : StatementT statement = ParseTryStatement();
4557 113 : statements.Add(statement);
4558 : result->InitializeStatements(statements, zone());
4559 0 : return result;
4560 : }
4561 : case Token::WITH:
4562 101378 : return ParseWithStatement(labels);
4563 : case Token::SWITCH:
4564 135900 : return ParseSwitchStatement(labels);
4565 : case Token::FUNCTION:
4566 : // FunctionDeclaration only allowed as a StatementListItem, not in
4567 : // an arbitrary Statement position. Exceptions such as
4568 : // ES#sec-functiondeclarations-in-ifstatement-statement-clauses
4569 : // are handled by calling ParseScopedStatement rather than
4570 : // ParseStatement directly.
4571 17196 : impl()->ReportMessageAt(scanner()->peek_location(),
4572 : is_strict(language_mode())
4573 : ? MessageTemplate::kStrictFunction
4574 : : MessageTemplate::kSloppyFunction);
4575 8598 : return impl()->NullStatement();
4576 : case Token::DEBUGGER:
4577 141853 : return ParseDebuggerStatement();
4578 : case Token::VAR:
4579 457 : return ParseVariableStatement(kStatement, nullptr);
4580 : case Token::ASYNC:
4581 5986 : if (!scanner()->HasLineTerminatorAfterNext() &&
4582 : PeekAhead() == Token::FUNCTION) {
4583 1280 : impl()->ReportMessageAt(
4584 : scanner()->peek_location(),
4585 : MessageTemplate::kAsyncFunctionInSingleStatementContext);
4586 1280 : return impl()->NullStatement();
4587 : }
4588 : V8_FALLTHROUGH;
4589 : default:
4590 : return ParseExpressionOrLabelledStatement(labels, own_labels,
4591 20176071 : allow_function);
4592 : }
4593 : }
4594 :
4595 : template <typename Impl>
4596 3951276 : typename ParserBase<Impl>::BlockT ParserBase<Impl>::ParseBlock(
4597 23591002 : ZonePtrList<const AstRawString>* labels) {
4598 : // Block ::
4599 : // '{' StatementList '}'
4600 :
4601 : // Parse the statements and collect escaping labels.
4602 971189 : BlockT body = factory()->NewBlock(false, labels);
4603 971198 : StatementListT statements(pointer_buffer());
4604 :
4605 3951285 : CheckStackOverflow();
4606 :
4607 : {
4608 7903082 : BlockState block_state(zone(), &scope_);
4609 : scope()->set_start_position(peek_position());
4610 : TargetT target(this, body);
4611 :
4612 3951819 : Expect(Token::LBRACE);
4613 :
4614 14224757 : while (peek() != Token::RBRACE) {
4615 6361103 : StatementT stat = ParseStatementListItem();
4616 6361241 : if (impl()->IsNull(stat)) return body;
4617 6321366 : if (stat->IsEmptyStatement()) continue;
4618 1661022 : statements.Add(stat);
4619 : }
4620 :
4621 3911855 : Expect(Token::RBRACE);
4622 :
4623 : int end_pos = end_position();
4624 : scope()->set_end_position(end_pos);
4625 :
4626 : impl()->RecordBlockSourceRange(body, end_pos);
4627 3911941 : body->set_scope(scope()->FinalizeBlockScope());
4628 : }
4629 :
4630 944617 : body->InitializeStatements(statements, zone_);
4631 3911730 : return body;
4632 : }
4633 :
4634 : template <typename Impl>
4635 3730097 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseScopedStatement(
4636 6064 : ZonePtrList<const AstRawString>* labels) {
4637 7014822 : if (is_strict(language_mode()) || peek() != Token::FUNCTION) {
4638 680901 : return ParseStatement(labels, nullptr);
4639 : } else {
4640 : // Make a block around the statement for a lexical binding
4641 : // is introduced by a FunctionDeclaration.
4642 1858 : BlockState block_state(zone(), &scope_);
4643 929 : scope()->set_start_position(scanner()->location().beg_pos);
4644 490 : BlockT block = factory()->NewBlock(1, false);
4645 929 : StatementT body = ParseFunctionDeclaration();
4646 490 : block->statements()->Add(body, zone());
4647 : scope()->set_end_position(end_position());
4648 929 : block->set_scope(scope()->FinalizeBlockScope());
4649 439 : return block;
4650 : }
4651 : }
4652 :
4653 : template <typename Impl>
4654 13088816 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseVariableStatement(
4655 : VariableDeclarationContext var_context,
4656 : ZonePtrList<const AstRawString>* names) {
4657 : // VariableStatement ::
4658 : // VariableDeclarations ';'
4659 :
4660 : // The scope of a var declared variable anywhere inside a function
4661 : // is the entire function (ECMA-262, 3rd, 10.1.3, and 12.2). Thus we can
4662 : // transform a source-level var declaration into a (Function) Scope
4663 : // declaration, and rewrite the source-level initialization into an assignment
4664 : // statement. We use a block to collect multiple assignments.
4665 : //
4666 : // We mark the block as initializer block because we don't want the
4667 : // rewriter to add a '.result' assignment to such a block (to get compliant
4668 : // behavior for code such as print(eval('var x = 7')), and for cosmetic
4669 : // reasons when pretty-printing. Also, unless an assignment (initialization)
4670 : // is inside an initializer block, it is ignored.
4671 :
4672 : DeclarationParsingResult parsing_result;
4673 13088816 : ParseVariableDeclarations(var_context, &parsing_result);
4674 13089721 : ExpectSemicolon();
4675 21762153 : return impl()->BuildInitializationBlock(&parsing_result, names);
4676 : }
4677 :
4678 : template <typename Impl>
4679 : typename ParserBase<Impl>::StatementT
4680 141851 : ParserBase<Impl>::ParseDebuggerStatement() {
4681 : // In ECMA-262 'debugger' is defined as a reserved keyword. In some browser
4682 : // contexts this is used as a statement which invokes the debugger as i a
4683 : // break point is present.
4684 : // DebuggerStatement ::
4685 : // 'debugger' ';'
4686 :
4687 : int pos = peek_position();
4688 : Consume(Token::DEBUGGER);
4689 141853 : ExpectSemicolon();
4690 194217 : return factory()->NewDebuggerStatement(pos);
4691 : }
4692 :
4693 : template <typename Impl>
4694 : typename ParserBase<Impl>::StatementT
4695 20180732 : ParserBase<Impl>::ParseExpressionOrLabelledStatement(
4696 : ZonePtrList<const AstRawString>* labels,
4697 : ZonePtrList<const AstRawString>* own_labels,
4698 10465428 : AllowLabelledFunctionStatement allow_function) {
4699 : // ExpressionStatement | LabelledStatement ::
4700 : // Expression ';'
4701 : // Identifier ':' Statement
4702 : //
4703 : // ExpressionStatement[Yield] :
4704 : // [lookahead notin {{, function, class, let [}] Expression[In, ?Yield] ;
4705 :
4706 : int pos = peek_position();
4707 :
4708 20180924 : switch (peek()) {
4709 : case Token::FUNCTION:
4710 : case Token::LBRACE:
4711 0 : UNREACHABLE(); // Always handled by the callers.
4712 : case Token::CLASS:
4713 308 : ReportUnexpectedToken(Next());
4714 308 : return impl()->NullStatement();
4715 : case Token::LET: {
4716 : Token::Value next_next = PeekAhead();
4717 : // "let" followed by either "[", "{" or an identifier means a lexical
4718 : // declaration, which should not appear here.
4719 : // However, ASI may insert a line break before an identifier or a brace.
4720 9166 : if (next_next != Token::LBRACK &&
4721 : ((next_next != Token::LBRACE && next_next != Token::IDENTIFIER) ||
4722 548 : scanner_->HasLineTerminatorAfterNext())) {
4723 : break;
4724 : }
4725 308 : impl()->ReportMessageAt(scanner()->peek_location(),
4726 : MessageTemplate::kUnexpectedLexicalDeclaration);
4727 308 : return impl()->NullStatement();
4728 : }
4729 : default:
4730 : break;
4731 : }
4732 :
4733 20180308 : bool starts_with_identifier = peek_any_identifier();
4734 : ExpressionT expr = ParseExpression();
4735 20214215 : if (peek() == Token::COLON && starts_with_identifier &&
4736 : impl()->IsIdentifier(expr)) {
4737 : // The whole expression was a single identifier, and not, e.g.,
4738 : // something starting with an identifier or a parenthesized identifier.
4739 15783 : impl()->DeclareLabel(&labels, &own_labels,
4740 : impl()->AsIdentifierExpression(expr));
4741 : Consume(Token::COLON);
4742 : // ES#sec-labelled-function-declarations Labelled Function Declarations
4743 37637 : if (peek() == Token::FUNCTION && is_sloppy(language_mode()) &&
4744 : allow_function == kAllowLabelledFunctionStatement) {
4745 507 : return ParseFunctionDeclaration();
4746 : }
4747 32445 : return ParseStatement(labels, own_labels, allow_function);
4748 : }
4749 :
4750 : // If we have an extension, we allow a native function declaration.
4751 : // A native function declaration starts with "native function" with
4752 : // no line-terminator between the two words.
4753 20156280 : if (extension_ != nullptr && peek() == Token::FUNCTION &&
4754 : !scanner()->HasLineTerminatorBeforeNext() && impl()->IsNative(expr) &&
4755 1766 : !scanner()->literal_contains_escapes()) {
4756 1761 : return ParseNativeDeclaration();
4757 : }
4758 :
4759 : // Parsed expression statement, followed by semicolon.
4760 20145740 : ExpectSemicolon();
4761 20528769 : if (expr->IsFailureExpression()) return impl()->NullStatement();
4762 19912353 : return factory()->NewExpressionStatement(expr, pos);
4763 : }
4764 :
4765 : template <typename Impl>
4766 3240440 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseIfStatement(
4767 1292782 : ZonePtrList<const AstRawString>* labels) {
4768 : // IfStatement ::
4769 : // 'if' '(' Expression ')' Statement ('else' Statement)?
4770 :
4771 : int pos = peek_position();
4772 : Consume(Token::IF);
4773 3240513 : Expect(Token::LPAREN);
4774 : ExpressionT condition = ParseExpression();
4775 3240632 : Expect(Token::RPAREN);
4776 :
4777 : SourceRange then_range, else_range;
4778 : StatementT then_statement = impl()->NullStatement();
4779 : {
4780 : SourceRangeScope range_scope(scanner(), &then_range);
4781 : // Make a copy of {labels} to avoid conflicts with any
4782 : // labels that may be applied to the else clause below.
4783 : auto labels_copy =
4784 : labels == nullptr
4785 : ? labels
4786 3241190 : : new (zone()) ZonePtrList<const AstRawString>(*labels, zone());
4787 3240624 : then_statement = ParseScopedStatement(labels_copy);
4788 : }
4789 :
4790 : StatementT else_statement = impl()->NullStatement();
4791 3240655 : if (Check(Token::ELSE)) {
4792 489613 : else_statement = ParseScopedStatement(labels);
4793 70562 : else_range = SourceRange::ContinuationOf(then_range, end_position());
4794 : } else {
4795 540267 : else_statement = factory()->EmptyStatement();
4796 : }
4797 : StatementT stmt =
4798 610829 : factory()->NewIfStatement(condition, then_statement, else_statement, pos);
4799 : impl()->RecordIfStatementSourceRange(stmt, then_range, else_range);
4800 3240652 : return stmt;
4801 : }
4802 :
4803 : template <typename Impl>
4804 : typename ParserBase<Impl>::StatementT
4805 124757 : ParserBase<Impl>::ParseContinueStatement() {
4806 : // ContinueStatement ::
4807 : // 'continue' Identifier? ';'
4808 :
4809 : int pos = peek_position();
4810 : Consume(Token::CONTINUE);
4811 : IdentifierT label = impl()->NullIdentifier();
4812 : Token::Value tok = peek();
4813 110738 : if (!scanner()->HasLineTerminatorBeforeNext() &&
4814 : !Token::IsAutoSemicolon(tok)) {
4815 : // ECMA allows "eval" or "arguments" as labels even in strict mode.
4816 : label = ParseIdentifier();
4817 : }
4818 14304 : IterationStatementT target = impl()->LookupContinueTarget(label);
4819 55455 : if (impl()->IsNull(target)) {
4820 : // Illegal continue statement.
4821 : MessageTemplate message = MessageTemplate::kIllegalContinue;
4822 457 : BreakableStatementT breakable_target = impl()->LookupBreakTarget(label);
4823 457 : if (impl()->IsNull(label)) {
4824 : message = MessageTemplate::kNoIterationStatement;
4825 362 : } else if (impl()->IsNull(breakable_target)) {
4826 : message = MessageTemplate::kUnknownLabel;
4827 : }
4828 457 : ReportMessage(message, label);
4829 457 : return impl()->NullStatement();
4830 : }
4831 54998 : ExpectSemicolon();
4832 13847 : StatementT stmt = factory()->NewContinueStatement(target, pos);
4833 : impl()->RecordJumpStatementSourceRange(stmt, end_position());
4834 55000 : return stmt;
4835 : }
4836 :
4837 : template <typename Impl>
4838 196961 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseBreakStatement(
4839 286720 : ZonePtrList<const AstRawString>* labels) {
4840 : // BreakStatement ::
4841 : // 'break' Identifier? ';'
4842 :
4843 : int pos = peek_position();
4844 : Consume(Token::BREAK);
4845 : IdentifierT label = impl()->NullIdentifier();
4846 : Token::Value tok = peek();
4847 393696 : if (!scanner()->HasLineTerminatorBeforeNext() &&
4848 : !Token::IsAutoSemicolon(tok)) {
4849 : // ECMA allows "eval" or "arguments" as labels even in strict mode.
4850 : label = ParseIdentifier();
4851 : }
4852 : // Parse labeled break statements that target themselves into
4853 : // empty statements, e.g. 'l1: l2: l3: break l2;'
4854 52382 : if (!impl()->IsNull(label) && impl()->ContainsLabel(labels, label)) {
4855 99 : ExpectSemicolon();
4856 99 : return factory()->EmptyStatement();
4857 : }
4858 44891 : BreakableStatementT target = impl()->LookupBreakTarget(label);
4859 196868 : if (impl()->IsNull(target)) {
4860 : // Illegal break statement.
4861 : MessageTemplate message = MessageTemplate::kIllegalBreak;
4862 133 : if (!impl()->IsNull(label)) {
4863 : message = MessageTemplate::kUnknownLabel;
4864 : }
4865 133 : ReportMessage(message, label);
4866 133 : return impl()->NullStatement();
4867 : }
4868 196735 : ExpectSemicolon();
4869 44761 : StatementT stmt = factory()->NewBreakStatement(target, pos);
4870 : impl()->RecordJumpStatementSourceRange(stmt, end_position());
4871 196747 : return stmt;
4872 : }
4873 :
4874 : template <typename Impl>
4875 12557622 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseReturnStatement() {
4876 : // ReturnStatement ::
4877 : // 'return' [no line terminator] Expression? ';'
4878 :
4879 : // Consume the return token. It is necessary to do that before
4880 : // reporting any errors on it, because of the way errors are
4881 : // reported (underlining).
4882 : Consume(Token::RETURN);
4883 3541829 : Scanner::Location loc = scanner()->location();
4884 :
4885 3541736 : switch (GetDeclarationScope()->scope_type()) {
4886 : case SCRIPT_SCOPE:
4887 : case EVAL_SCOPE:
4888 : case MODULE_SCOPE:
4889 103 : impl()->ReportMessageAt(loc, MessageTemplate::kIllegalReturn);
4890 103 : return impl()->NullStatement();
4891 : default:
4892 : break;
4893 : }
4894 :
4895 : Token::Value tok = peek();
4896 : ExpressionT return_value = impl()->NullExpression();
4897 7083133 : if (scanner()->HasLineTerminatorBeforeNext() || Token::IsAutoSemicolon(tok)) {
4898 640065 : if (IsDerivedConstructor(function_state_->kind())) {
4899 : return_value = impl()->ThisExpression(loc.beg_pos);
4900 : }
4901 : } else {
4902 : return_value = ParseExpression();
4903 : }
4904 3541620 : ExpectSemicolon();
4905 :
4906 966338 : return_value = impl()->RewriteReturn(return_value, loc.beg_pos);
4907 : int continuation_pos = end_position();
4908 : StatementT stmt =
4909 3541673 : BuildReturnStatement(return_value, loc.beg_pos, continuation_pos);
4910 : impl()->RecordJumpStatementSourceRange(stmt, end_position());
4911 3541595 : return stmt;
4912 : }
4913 :
4914 : template <typename Impl>
4915 101377 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseWithStatement(
4916 240067 : ZonePtrList<const AstRawString>* labels) {
4917 : // WithStatement ::
4918 : // 'with' '(' Expression ')' Statement
4919 :
4920 : Consume(Token::WITH);
4921 : int pos = position();
4922 :
4923 101379 : if (is_strict(language_mode())) {
4924 695 : ReportMessage(MessageTemplate::kStrictWith);
4925 695 : return impl()->NullStatement();
4926 : }
4927 :
4928 100684 : Expect(Token::LPAREN);
4929 : ExpressionT expr = ParseExpression();
4930 100684 : Expect(Token::RPAREN);
4931 :
4932 : Scope* with_scope = NewScope(WITH_SCOPE);
4933 : StatementT body = impl()->NullStatement();
4934 : {
4935 100684 : BlockState block_state(&scope_, with_scope);
4936 100684 : with_scope->set_start_position(scanner()->peek_location().beg_pos);
4937 : body = ParseStatement(labels, nullptr);
4938 : with_scope->set_end_position(end_position());
4939 : }
4940 76764 : return factory()->NewWithStatement(with_scope, expr, body, pos);
4941 : }
4942 :
4943 : template <typename Impl>
4944 18941 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseDoWhileStatement(
4945 : ZonePtrList<const AstRawString>* labels,
4946 8225 : ZonePtrList<const AstRawString>* own_labels) {
4947 : // DoStatement ::
4948 : // 'do' Statement 'while' '(' Expression ')' ';'
4949 18941 : typename FunctionState::LoopScope loop_scope(function_state_);
4950 :
4951 : auto loop =
4952 4112 : factory()->NewDoWhileStatement(labels, own_labels, peek_position());
4953 : TargetT target(this, loop);
4954 :
4955 : SourceRange body_range;
4956 : StatementT body = impl()->NullStatement();
4957 :
4958 : Consume(Token::DO);
4959 :
4960 18942 : CheckStackOverflow();
4961 : {
4962 : SourceRangeScope range_scope(scanner(), &body_range);
4963 : body = ParseStatement(nullptr, nullptr);
4964 : }
4965 18942 : Expect(Token::WHILE);
4966 18942 : Expect(Token::LPAREN);
4967 :
4968 : ExpressionT cond = ParseExpression();
4969 18942 : Expect(Token::RPAREN);
4970 :
4971 : // Allow do-statements to be terminated with and without
4972 : // semi-colons. This allows code such as 'do;while(0)return' to
4973 : // parse, which would not be the case if we had used the
4974 : // ExpectSemicolon() functionality here.
4975 : Check(Token::SEMICOLON);
4976 :
4977 : loop->Initialize(cond, body);
4978 : impl()->RecordIterationStatementSourceRange(loop, body_range);
4979 :
4980 33771 : return loop;
4981 : }
4982 :
4983 : template <typename Impl>
4984 37038 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseWhileStatement(
4985 : ZonePtrList<const AstRawString>* labels,
4986 34975 : ZonePtrList<const AstRawString>* own_labels) {
4987 : // WhileStatement ::
4988 : // 'while' '(' Expression ')' Statement
4989 37038 : typename FunctionState::LoopScope loop_scope(function_state_);
4990 :
4991 17487 : auto loop = factory()->NewWhileStatement(labels, own_labels, peek_position());
4992 : TargetT target(this, loop);
4993 :
4994 : SourceRange body_range;
4995 : StatementT body = impl()->NullStatement();
4996 :
4997 : Consume(Token::WHILE);
4998 37042 : Expect(Token::LPAREN);
4999 : ExpressionT cond = ParseExpression();
5000 37040 : Expect(Token::RPAREN);
5001 : {
5002 : SourceRangeScope range_scope(scanner(), &body_range);
5003 : body = ParseStatement(nullptr, nullptr);
5004 : }
5005 :
5006 : loop->Initialize(cond, body);
5007 : impl()->RecordIterationStatementSourceRange(loop, body_range);
5008 :
5009 56579 : return loop;
5010 : }
5011 :
5012 : template <typename Impl>
5013 595242 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseThrowStatement() {
5014 : // ThrowStatement ::
5015 : // 'throw' Expression ';'
5016 :
5017 : Consume(Token::THROW);
5018 : int pos = position();
5019 277250 : if (scanner()->HasLineTerminatorBeforeNext()) {
5020 177 : ReportMessage(MessageTemplate::kNewlineAfterThrow);
5021 177 : return impl()->NullStatement();
5022 : }
5023 : ExpressionT exception = ParseExpression();
5024 277077 : ExpectSemicolon();
5025 :
5026 : StatementT stmt = impl()->NewThrowStatement(exception, pos);
5027 : impl()->RecordThrowSourceRange(stmt, end_position());
5028 :
5029 277076 : return stmt;
5030 : }
5031 :
5032 : template <typename Impl>
5033 135897 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseSwitchStatement(
5034 1125731 : ZonePtrList<const AstRawString>* labels) {
5035 : // SwitchStatement ::
5036 : // 'switch' '(' Expression ')' '{' CaseClause* '}'
5037 : // CaseClause ::
5038 : // 'case' Expression ':' StatementList
5039 : // 'default' ':' StatementList
5040 :
5041 : int switch_pos = peek_position();
5042 :
5043 : Consume(Token::SWITCH);
5044 135900 : Expect(Token::LPAREN);
5045 : ExpressionT tag = ParseExpression();
5046 135903 : Expect(Token::RPAREN);
5047 :
5048 : auto switch_statement =
5049 14294 : factory()->NewSwitchStatement(labels, tag, switch_pos);
5050 :
5051 : {
5052 271806 : BlockState cases_block_state(zone(), &scope_);
5053 : scope()->set_start_position(switch_pos);
5054 : scope()->SetNonlinear();
5055 : TargetT target(this, switch_statement);
5056 :
5057 : bool default_seen = false;
5058 135903 : Expect(Token::LBRACE);
5059 1493387 : while (peek() != Token::RBRACE) {
5060 : // An empty label indicates the default case.
5061 : ExpressionT label = impl()->NullExpression();
5062 89433 : StatementListT statements(pointer_buffer());
5063 : SourceRange clause_range;
5064 : {
5065 : SourceRangeScope range_scope(scanner(), &clause_range);
5066 1223004 : if (Check(Token::CASE)) {
5067 : label = ParseExpression();
5068 : } else {
5069 127338 : Expect(Token::DEFAULT);
5070 127338 : if (default_seen) {
5071 18 : ReportMessage(MessageTemplate::kMultipleDefaultsInSwitch);
5072 18 : return impl()->NullStatement();
5073 : }
5074 : default_seen = true;
5075 : }
5076 1222875 : Expect(Token::COLON);
5077 6230176 : while (peek() != Token::CASE && peek() != Token::DEFAULT &&
5078 : peek() != Token::RBRACE) {
5079 1130515 : StatementT stat = ParseStatementListItem();
5080 1130621 : if (impl()->IsNull(stat)) return stat;
5081 1129406 : if (stat->IsEmptyStatement()) continue;
5082 120778 : statements.Add(stat);
5083 : }
5084 : }
5085 88679 : auto clause = factory()->NewCaseClause(label, statements);
5086 : impl()->RecordCaseClauseSourceRange(clause, clause_range);
5087 88679 : switch_statement->cases()->Add(clause, zone());
5088 : }
5089 134671 : Expect(Token::RBRACE);
5090 :
5091 : int end_pos = end_position();
5092 : scope()->set_end_position(end_pos);
5093 : impl()->RecordSwitchStatementSourceRange(switch_statement, end_pos);
5094 134671 : Scope* switch_scope = scope()->FinalizeBlockScope();
5095 134670 : if (switch_scope != nullptr) {
5096 924 : return impl()->RewriteSwitchStatement(switch_statement, switch_scope);
5097 : }
5098 119762 : return switch_statement;
5099 : }
5100 : }
5101 :
5102 : template <typename Impl>
5103 3882395 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseTryStatement() {
5104 : // TryStatement ::
5105 : // 'try' Block Catch
5106 : // 'try' Block Finally
5107 : // 'try' Block Catch Finally
5108 : //
5109 : // Catch ::
5110 : // 'catch' '(' Identifier ')' Block
5111 : //
5112 : // Finally ::
5113 : // 'finally' Block
5114 :
5115 : Consume(Token::TRY);
5116 97410 : int pos = position();
5117 :
5118 412556 : BlockT try_block = ParseBlock(nullptr);
5119 :
5120 412449 : CatchInfo catch_info(this);
5121 :
5122 451089 : if (peek() != Token::CATCH && peek() != Token::FINALLY) {
5123 1068 : ReportMessage(MessageTemplate::kNoCatchOrFinally);
5124 : return impl()->NullStatement();
5125 : }
5126 :
5127 96613 : SourceRange catch_range, finally_range;
5128 :
5129 314640 : BlockT catch_block = impl()->NullBlock();
5130 : {
5131 411257 : SourceRangeScope catch_range_scope(scanner(), &catch_range);
5132 411410 : if (Check(Token::CATCH)) {
5133 : bool has_binding;
5134 : has_binding = Check(Token::LPAREN);
5135 :
5136 373618 : if (has_binding) {
5137 372337 : catch_info.scope = NewScope(CATCH_SCOPE);
5138 372339 : catch_info.scope->set_start_position(scanner()->location().beg_pos);
5139 :
5140 : {
5141 372331 : BlockState catch_block_state(&scope_, catch_info.scope);
5142 181160 : StatementListT catch_statements(pointer_buffer());
5143 :
5144 : // Create a block scope to hold any lexical declarations created
5145 : // as part of destructuring the catch parameter.
5146 : {
5147 372326 : BlockState catch_variable_block_state(zone(), &scope_);
5148 744677 : scope()->set_start_position(position());
5149 :
5150 372336 : if (peek_any_identifier()) {
5151 363237 : IdentifierT identifier = ParseNonRestrictedIdentifier();
5152 365714 : RETURN_IF_PARSE_ERROR;
5153 723582 : catch_info.variable = impl()->DeclareCatchVariableName(
5154 : catch_info.scope, identifier);
5155 : } else {
5156 9095 : catch_info.variable = catch_info.scope->DeclareCatchVariableName(
5157 : ast_value_factory()->dot_catch_string());
5158 : VariableDeclarationParsingScope destructuring(impl(),
5159 9095 : VariableMode::kLet);
5160 9095 : catch_info.pattern = ParseBindingPattern();
5161 9095 : RETURN_IF_PARSE_ERROR;
5162 7619 : catch_statements.Add(impl()->RewriteCatchPattern(&catch_info));
5163 : }
5164 :
5165 367162 : Expect(Token::RPAREN);
5166 :
5167 456480 : BlockT inner_block = ParseBlock(nullptr);
5168 89324 : catch_statements.Add(inner_block);
5169 :
5170 : // Check for `catch(e) { let e; }` and similar errors.
5171 367174 : Scope* inner_scope = inner_block->scope();
5172 367162 : if (inner_scope != nullptr) {
5173 : const AstRawString* conflict = nullptr;
5174 2059 : if (impl()->IsNull(catch_info.pattern)) {
5175 1120 : const AstRawString* name = catch_info.variable->raw_name();
5176 1120 : if (inner_scope->LookupLocal(name)) conflict = name;
5177 : } else {
5178 512 : conflict = inner_scope->FindVariableDeclaredIn(
5179 : scope(), VariableMode::kVar);
5180 : }
5181 1632 : if (conflict != nullptr) {
5182 342 : impl()->ReportVarRedeclarationIn(conflict, inner_scope);
5183 : }
5184 : }
5185 :
5186 734307 : scope()->set_end_position(end_position());
5187 367158 : catch_block = factory()->NewBlock(false, catch_statements);
5188 367164 : catch_block->set_scope(scope()->FinalizeBlockScope());
5189 367161 : }
5190 : }
5191 :
5192 367165 : catch_info.scope->set_end_position(end_position());
5193 : } else {
5194 1281 : catch_block = ParseBlock(nullptr);
5195 : }
5196 94141 : }
5197 : }
5198 :
5199 : BlockT finally_block = impl()->NullBlock();
5200 : DCHECK(has_error() || peek() == Token::FINALLY ||
5201 : !impl()->IsNull(catch_block));
5202 : {
5203 406143 : SourceRangeScope range_scope(scanner(), &finally_range);
5204 406326 : if (Check(Token::FINALLY)) {
5205 40046 : finally_block = ParseBlock(nullptr);
5206 94138 : }
5207 : }
5208 :
5209 406329 : RETURN_IF_PARSE_ERROR;
5210 : return impl()->RewriteTryStatement(try_block, catch_block, catch_range,
5211 : finally_block, finally_range, catch_info,
5212 93099 : pos);
5213 : }
5214 :
5215 : template <typename Impl>
5216 814073 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseForStatement(
5217 : ZonePtrList<const AstRawString>* labels,
5218 2822108 : ZonePtrList<const AstRawString>* own_labels) {
5219 : // Either a standard for loop
5220 : // for (<init>; <cond>; <next>) { ... }
5221 : // or a for-each loop
5222 : // for (<each> of|in <iterable>) { ... }
5223 : //
5224 : // We parse a declaration/expression after the 'for (' and then read the first
5225 : // expression/declaration before we know if this is a for or a for-each.
5226 814073 : typename FunctionState::LoopScope loop_scope(function_state_);
5227 :
5228 : int stmt_pos = peek_position();
5229 814073 : ForInfo for_info(this);
5230 :
5231 : Consume(Token::FOR);
5232 814181 : Expect(Token::LPAREN);
5233 :
5234 1587565 : if (peek() == Token::CONST || (peek() == Token::LET && IsNextLetKeyword())) {
5235 : // The initializer contains lexical declarations,
5236 : // so create an in-between scope.
5237 511570 : BlockState for_state(zone(), &scope_);
5238 : scope()->set_start_position(position());
5239 :
5240 : // Also record whether inner functions or evals are found inside
5241 : // this loop, as this information is used to simplify the desugaring
5242 : // if none are found.
5243 : typename FunctionState::FunctionOrEvalRecordingScope recording_scope(
5244 255790 : function_state_);
5245 :
5246 : // Create an inner block scope which will be the parent scope of scopes
5247 : // possibly created by ParseVariableDeclarations.
5248 : Scope* inner_block_scope = NewScope(BLOCK_SCOPE);
5249 : {
5250 : BlockState inner_state(&scope_, inner_block_scope);
5251 255792 : ParseVariableDeclarations(kForStatement, &for_info.parsing_result);
5252 : }
5253 : DCHECK(IsLexicalVariableMode(for_info.parsing_result.descriptor.mode));
5254 255786 : for_info.position = position();
5255 :
5256 255786 : if (CheckInOrOf(&for_info.mode)) {
5257 : scope()->set_is_hidden();
5258 : return ParseForEachStatementWithDeclarations(
5259 135298 : stmt_pos, &for_info, labels, own_labels, inner_block_scope);
5260 : }
5261 :
5262 120485 : Expect(Token::SEMICOLON);
5263 :
5264 : // Parse the remaining code in the inner block scope since the declaration
5265 : // above was parsed there. We'll finalize the unnecessary outer block scope
5266 : // after parsing the rest of the loop.
5267 : StatementT result = impl()->NullStatement();
5268 120486 : inner_block_scope->set_start_position(scope()->start_position());
5269 : {
5270 : BlockState inner_state(&scope_, inner_block_scope);
5271 : StatementT init = impl()->BuildInitializationBlock(
5272 120484 : &for_info.parsing_result, &for_info.bound_names);
5273 :
5274 120485 : result = ParseStandardForLoopWithLexicalDeclarations(
5275 : stmt_pos, init, &for_info, labels, own_labels);
5276 : }
5277 120477 : Scope* finalized = scope()->FinalizeBlockScope();
5278 : DCHECK_NULL(finalized);
5279 : USE(finalized);
5280 120486 : return result;
5281 : }
5282 :
5283 : StatementT init = impl()->NullStatement();
5284 558345 : if (peek() == Token::VAR) {
5285 388314 : ParseVariableDeclarations(kForStatement, &for_info.parsing_result);
5286 : DCHECK_EQ(for_info.parsing_result.descriptor.mode, VariableMode::kVar);
5287 388346 : for_info.position = scanner()->location().beg_pos;
5288 :
5289 388346 : if (CheckInOrOf(&for_info.mode)) {
5290 : return ParseForEachStatementWithDeclarations(stmt_pos, &for_info, labels,
5291 34516 : own_labels, scope());
5292 : }
5293 :
5294 195252 : init = impl()->BuildInitializationBlock(&for_info.parsing_result, nullptr);
5295 170031 : } else if (peek() != Token::SEMICOLON) {
5296 : // The initializer does not contain declarations.
5297 : int lhs_beg_pos = peek_position();
5298 : int lhs_end_pos;
5299 : bool is_for_each;
5300 : ExpressionT expression;
5301 : {
5302 153119 : ExpressionParsingScope parsing_scope(impl());
5303 : AcceptINScope scope(this, false);
5304 153118 : expression = ParseExpressionCoverGrammar();
5305 : // Initializer is reference followed by in/of.
5306 : lhs_end_pos = end_position();
5307 153119 : is_for_each = CheckInOrOf(&for_info.mode);
5308 153119 : if (is_for_each) {
5309 116965 : if (expression->IsPattern()) {
5310 24199 : parsing_scope.ValidatePattern(expression, lhs_beg_pos, lhs_end_pos);
5311 : } else {
5312 92766 : expression = parsing_scope.ValidateAndRewriteReference(
5313 : expression, lhs_beg_pos, lhs_end_pos);
5314 : }
5315 : } else {
5316 : parsing_scope.ValidateExpression();
5317 : }
5318 : }
5319 :
5320 153117 : if (is_for_each) {
5321 : return ParseForEachStatementWithoutDeclarations(
5322 : stmt_pos, expression, lhs_beg_pos, lhs_end_pos, &for_info, labels,
5323 116965 : own_labels);
5324 : }
5325 : // Initializer is just an expression.
5326 19008 : init = factory()->NewExpressionStatement(expression, lhs_beg_pos);
5327 : }
5328 :
5329 406874 : Expect(Token::SEMICOLON);
5330 :
5331 : // Standard 'for' loop, we have parsed the initializer at this point.
5332 406878 : ExpressionT cond = impl()->NullExpression();
5333 406866 : StatementT next = impl()->NullStatement();
5334 406869 : StatementT body = impl()->NullStatement();
5335 : ForStatementT loop =
5336 406869 : ParseStandardForLoop(stmt_pos, labels, own_labels, &cond, &next, &body);
5337 409868 : RETURN_IF_PARSE_ERROR;
5338 223255 : loop->Initialize(init, cond, next, body);
5339 400386 : return loop;
5340 : }
5341 :
5342 : template <typename Impl>
5343 : typename ParserBase<Impl>::StatementT
5344 169797 : ParserBase<Impl>::ParseForEachStatementWithDeclarations(
5345 : int stmt_pos, ForInfo* for_info, ZonePtrList<const AstRawString>* labels,
5346 1181007 : ZonePtrList<const AstRawString>* own_labels, Scope* inner_block_scope) {
5347 : // Just one declaration followed by in/of.
5348 339594 : if (for_info->parsing_result.declarations.size() != 1) {
5349 6012 : impl()->ReportMessageAt(for_info->parsing_result.bindings_loc,
5350 : MessageTemplate::kForInOfLoopMultiBindings,
5351 : ForEachStatement::VisitModeString(for_info->mode));
5352 3006 : return impl()->NullStatement();
5353 : }
5354 173006 : if (for_info->parsing_result.first_initializer_loc.IsValid() &&
5355 : (is_strict(language_mode()) ||
5356 : for_info->mode == ForEachStatement::ITERATE ||
5357 1436 : IsLexicalVariableMode(for_info->parsing_result.descriptor.mode) ||
5358 212 : !impl()->IsIdentifier(
5359 : for_info->parsing_result.declarations[0].pattern))) {
5360 7086 : impl()->ReportMessageAt(for_info->parsing_result.first_initializer_loc,
5361 : MessageTemplate::kForInOfLoopInitializer,
5362 : ForEachStatement::VisitModeString(for_info->mode));
5363 3543 : return impl()->NullStatement();
5364 : }
5365 :
5366 93633 : BlockT init_block = impl()->RewriteForVarInLegacy(*for_info);
5367 :
5368 : auto loop = factory()->NewForEachStatement(for_info->mode, labels, own_labels,
5369 93636 : stmt_pos);
5370 : TargetT target(this, loop);
5371 :
5372 : ExpressionT enumerable = impl()->NullExpression();
5373 163246 : if (for_info->mode == ForEachStatement::ITERATE) {
5374 : AcceptINScope scope(this, true);
5375 : enumerable = ParseAssignmentExpression();
5376 : } else {
5377 : enumerable = ParseExpression();
5378 : }
5379 :
5380 163259 : Expect(Token::RPAREN);
5381 :
5382 163258 : if (IsLexicalVariableMode(for_info->parsing_result.descriptor.mode)) {
5383 : inner_block_scope->set_start_position(position());
5384 : }
5385 :
5386 93644 : ExpressionT each_variable = impl()->NullExpression();
5387 93644 : BlockT body_block = impl()->NullBlock();
5388 : {
5389 163258 : BlockState block_state(&scope_, inner_block_scope);
5390 :
5391 : SourceRange body_range;
5392 93644 : StatementT body = impl()->NullStatement();
5393 : {
5394 : SourceRangeScope range_scope(scanner(), &body_range);
5395 93646 : body = ParseStatement(nullptr, nullptr);
5396 : }
5397 : impl()->RecordIterationStatementSourceRange(loop, body_range);
5398 :
5399 93646 : impl()->DesugarBindingInForEachStatement(for_info, &body_block,
5400 : &each_variable);
5401 93641 : body_block->statements()->Add(body, zone());
5402 :
5403 163264 : if (IsLexicalVariableMode(for_info->parsing_result.descriptor.mode)) {
5404 : scope()->set_end_position(end_position());
5405 130942 : body_block->set_scope(scope()->FinalizeBlockScope());
5406 : }
5407 : }
5408 :
5409 93642 : loop->Initialize(each_variable, enumerable, body_block);
5410 :
5411 93642 : init_block = impl()->CreateForEachStatementTDZ(init_block, *for_info);
5412 :
5413 : // Parsed for-in loop w/ variable declarations.
5414 163266 : if (!impl()->IsNull(init_block)) {
5415 77119 : init_block->statements()->Add(loop, zone());
5416 131161 : if (IsLexicalVariableMode(for_info->parsing_result.descriptor.mode)) {
5417 : scope()->set_end_position(end_position());
5418 130947 : init_block->set_scope(scope()->FinalizeBlockScope());
5419 : }
5420 131160 : return init_block;
5421 : }
5422 :
5423 15579 : return loop;
5424 : }
5425 :
5426 : template <typename Impl>
5427 : typename ParserBase<Impl>::StatementT
5428 116964 : ParserBase<Impl>::ParseForEachStatementWithoutDeclarations(
5429 : int stmt_pos, ExpressionT expression, int lhs_beg_pos, int lhs_end_pos,
5430 : ForInfo* for_info, ZonePtrList<const AstRawString>* labels,
5431 59819 : ZonePtrList<const AstRawString>* own_labels) {
5432 : auto loop = factory()->NewForEachStatement(for_info->mode, labels, own_labels,
5433 59819 : stmt_pos);
5434 : TargetT target(this, loop);
5435 :
5436 : ExpressionT enumerable = impl()->NullExpression();
5437 116964 : if (for_info->mode == ForEachStatement::ITERATE) {
5438 : AcceptINScope scope(this, true);
5439 : enumerable = ParseAssignmentExpression();
5440 : } else {
5441 : enumerable = ParseExpression();
5442 : }
5443 :
5444 116965 : Expect(Token::RPAREN);
5445 :
5446 : StatementT body = impl()->NullStatement();
5447 : SourceRange body_range;
5448 : {
5449 : SourceRangeScope range_scope(scanner(), &body_range);
5450 : body = ParseStatement(nullptr, nullptr);
5451 : }
5452 : impl()->RecordIterationStatementSourceRange(loop, body_range);
5453 127384 : RETURN_IF_PARSE_ERROR;
5454 : loop->Initialize(expression, enumerable, body);
5455 96103 : return loop;
5456 : }
5457 :
5458 : template <typename Impl>
5459 : typename ParserBase<Impl>::StatementT
5460 120472 : ParserBase<Impl>::ParseStandardForLoopWithLexicalDeclarations(
5461 : int stmt_pos, StatementT init, ForInfo* for_info,
5462 : ZonePtrList<const AstRawString>* labels,
5463 654235 : ZonePtrList<const AstRawString>* own_labels) {
5464 : // The condition and the next statement of the for loop must be parsed
5465 : // in a new scope.
5466 : Scope* inner_scope = NewScope(BLOCK_SCOPE);
5467 : ForStatementT loop = impl()->NullStatement();
5468 120484 : ExpressionT cond = impl()->NullExpression();
5469 120484 : StatementT next = impl()->NullStatement();
5470 120484 : StatementT body = impl()->NullStatement();
5471 : {
5472 120484 : BlockState block_state(&scope_, inner_scope);
5473 120484 : scope()->set_start_position(scanner()->location().beg_pos);
5474 120484 : loop =
5475 : ParseStandardForLoop(stmt_pos, labels, own_labels, &cond, &next, &body);
5476 124348 : RETURN_IF_PARSE_ERROR;
5477 : scope()->set_end_position(end_position());
5478 : }
5479 :
5480 : scope()->set_end_position(end_position());
5481 113478 : if (for_info->bound_names.length() > 0 &&
5482 : function_state_->contains_function_or_eval()) {
5483 : scope()->set_is_hidden();
5484 : return impl()->DesugarLexicalBindingsInForStatement(
5485 17516 : loop, init, cond, next, body, inner_scope, *for_info);
5486 : } else {
5487 95627 : inner_scope = inner_scope->FinalizeBlockScope();
5488 : DCHECK_NULL(inner_scope);
5489 : USE(inner_scope);
5490 : }
5491 :
5492 95632 : Scope* for_scope = scope()->FinalizeBlockScope();
5493 95632 : if (for_scope != nullptr) {
5494 : // Rewrite a for statement of the form
5495 : // for (const x = i; c; n) b
5496 : //
5497 : // into
5498 : //
5499 : // {
5500 : // const x = i;
5501 : // for (; c; n) b
5502 : // }
5503 : //
5504 : DCHECK(!impl()->IsNull(init));
5505 39917 : BlockT block = factory()->NewBlock(2, false);
5506 39917 : block->statements()->Add(init, zone());
5507 39917 : block->statements()->Add(loop, zone());
5508 : block->set_scope(for_scope);
5509 39917 : loop->Initialize(impl()->NullStatement(), cond, next, body);
5510 95632 : return block;
5511 : }
5512 :
5513 0 : loop->Initialize(init, cond, next, body);
5514 0 : return loop;
5515 : }
5516 :
5517 : template <typename Impl>
5518 527285 : typename ParserBase<Impl>::ForStatementT ParserBase<Impl>::ParseStandardForLoop(
5519 : int stmt_pos, ZonePtrList<const AstRawString>* labels,
5520 : ZonePtrList<const AstRawString>* own_labels, ExpressionT* cond,
5521 287389 : StatementT* next, StatementT* body) {
5522 287346 : ForStatementT loop = factory()->NewForStatement(labels, own_labels, stmt_pos);
5523 : TargetT target(this, loop);
5524 :
5525 527341 : if (peek() != Token::SEMICOLON) {
5526 513183 : *cond = ParseExpression();
5527 : }
5528 527403 : Expect(Token::SEMICOLON);
5529 :
5530 527388 : if (peek() != Token::RPAREN) {
5531 : ExpressionT exp = ParseExpression();
5532 707972 : *next = factory()->NewExpressionStatement(exp, exp->position());
5533 : }
5534 527385 : Expect(Token::RPAREN);
5535 :
5536 : SourceRange body_range;
5537 : {
5538 : SourceRangeScope range_scope(scanner(), &body_range);
5539 527386 : *body = ParseStatement(nullptr, nullptr);
5540 : }
5541 : impl()->RecordIterationStatementSourceRange(loop, body_range);
5542 :
5543 527386 : return loop;
5544 : }
5545 :
5546 : template <typename Impl>
5547 128542 : typename ParserBase<Impl>::StatementT ParserBase<Impl>::ParseForAwaitStatement(
5548 : ZonePtrList<const AstRawString>* labels,
5549 1447996 : ZonePtrList<const AstRawString>* own_labels) {
5550 : // for await '(' ForDeclaration of AssignmentExpression ')'
5551 : DCHECK(is_async_function());
5552 128542 : typename FunctionState::LoopScope loop_scope(function_state_);
5553 :
5554 : int stmt_pos = peek_position();
5555 :
5556 128542 : ForInfo for_info(this);
5557 128542 : for_info.mode = ForEachStatement::ITERATE;
5558 :
5559 : // Create an in-between scope for let-bound iteration variables.
5560 257084 : BlockState for_state(zone(), &scope_);
5561 128542 : Expect(Token::FOR);
5562 128542 : Expect(Token::AWAIT);
5563 128542 : Expect(Token::LPAREN);
5564 128542 : scope()->set_start_position(scanner()->location().beg_pos);
5565 : scope()->set_is_hidden();
5566 :
5567 : auto loop = factory()->NewForOfStatement(labels, own_labels, stmt_pos,
5568 34652 : IteratorType::kAsync);
5569 : // Two suspends: one for next() and one for return()
5570 128542 : function_state_->AddSuspend();
5571 128542 : function_state_->AddSuspend();
5572 :
5573 : TargetT target(this, loop);
5574 :
5575 128542 : ExpressionT each_variable = impl()->NullExpression();
5576 :
5577 : bool has_declarations = false;
5578 : Scope* inner_block_scope = NewScope(BLOCK_SCOPE);
5579 :
5580 342228 : if (peek() == Token::VAR || peek() == Token::CONST ||
5581 33578 : (peek() == Token::LET && IsNextLetKeyword())) {
5582 : // The initializer contains declarations
5583 : // 'for' 'await' '(' ForDeclaration 'of' AssignmentExpression ')'
5584 : // Statement
5585 : // 'for' 'await' '(' 'var' ForBinding 'of' AssignmentExpression ')'
5586 : // Statement
5587 : has_declarations = true;
5588 :
5589 : {
5590 : BlockState inner_state(&scope_, inner_block_scope);
5591 88775 : ParseVariableDeclarations(kForStatement, &for_info.parsing_result);
5592 : }
5593 88775 : for_info.position = scanner()->location().beg_pos;
5594 :
5595 : // Only a single declaration is allowed in for-await-of loops
5596 177550 : if (for_info.parsing_result.declarations.size() != 1) {
5597 15760 : impl()->ReportMessageAt(for_info.parsing_result.bindings_loc,
5598 : MessageTemplate::kForInOfLoopMultiBindings,
5599 : "for-await-of");
5600 15760 : return impl()->NullStatement();
5601 : }
5602 :
5603 : // for-await-of's declarations do not permit initializers.
5604 73015 : if (for_info.parsing_result.first_initializer_loc.IsValid()) {
5605 14720 : impl()->ReportMessageAt(for_info.parsing_result.first_initializer_loc,
5606 : MessageTemplate::kForInOfLoopInitializer,
5607 : "for-await-of");
5608 14720 : return impl()->NullStatement();
5609 : }
5610 : } else {
5611 : // The initializer does not contain declarations.
5612 : // 'for' 'await' '(' LeftHandSideExpression 'of' AssignmentExpression ')'
5613 : // Statement
5614 : int lhs_beg_pos = peek_position();
5615 : BlockState inner_state(&scope_, inner_block_scope);
5616 39767 : ExpressionParsingScope parsing_scope(impl());
5617 39767 : ExpressionT lhs = each_variable = ParseLeftHandSideExpression();
5618 : int lhs_end_pos = end_position();
5619 :
5620 39767 : if (lhs->IsPattern()) {
5621 28070 : parsing_scope.ValidatePattern(lhs, lhs_beg_pos, lhs_end_pos);
5622 : } else {
5623 11697 : each_variable = parsing_scope.ValidateAndRewriteReference(
5624 : lhs, lhs_beg_pos, lhs_end_pos);
5625 : }
5626 : }
5627 :
5628 196124 : ExpectContextualKeyword(ast_value_factory()->of_string());
5629 :
5630 : const bool kAllowIn = true;
5631 : ExpressionT iterable = impl()->NullExpression();
5632 :
5633 : {
5634 : AcceptINScope scope(this, kAllowIn);
5635 : iterable = ParseAssignmentExpression();
5636 : }
5637 :
5638 98062 : Expect(Token::RPAREN);
5639 :
5640 26972 : StatementT body = impl()->NullStatement();
5641 : {
5642 : BlockState block_state(&scope_, inner_block_scope);
5643 98062 : scope()->set_start_position(scanner()->location().beg_pos);
5644 :
5645 : SourceRange body_range;
5646 : {
5647 : SourceRangeScope range_scope(scanner(), &body_range);
5648 26972 : body = ParseStatement(nullptr, nullptr);
5649 : scope()->set_end_position(end_position());
5650 : }
5651 : impl()->RecordIterationStatementSourceRange(loop, body_range);
5652 :
5653 98062 : if (has_declarations) {
5654 14727 : BlockT body_block = impl()->NullBlock();
5655 14727 : impl()->DesugarBindingInForEachStatement(&for_info, &body_block,
5656 : &each_variable);
5657 14727 : body_block->statements()->Add(body, zone());
5658 58295 : body_block->set_scope(scope()->FinalizeBlockScope());
5659 14727 : body = body_block;
5660 : } else {
5661 39767 : Scope* block_scope = scope()->FinalizeBlockScope();
5662 : DCHECK_NULL(block_scope);
5663 : USE(block_scope);
5664 : }
5665 : }
5666 :
5667 26972 : loop->Initialize(each_variable, iterable, body);
5668 :
5669 98062 : if (!has_declarations) {
5670 39767 : Scope* for_scope = scope()->FinalizeBlockScope();
5671 : DCHECK_NULL(for_scope);
5672 : USE(for_scope);
5673 27522 : return loop;
5674 : }
5675 :
5676 : BlockT init_block =
5677 14727 : impl()->CreateForEachStatementTDZ(impl()->NullBlock(), for_info);
5678 :
5679 : scope()->set_end_position(end_position());
5680 58295 : Scope* for_scope = scope()->FinalizeBlockScope();
5681 : // Parsed for-in loop w/ variable declarations.
5682 58295 : if (!impl()->IsNull(init_block)) {
5683 11728 : init_block->statements()->Add(loop, zone());
5684 : init_block->set_scope(for_scope);
5685 46516 : return init_block;
5686 : }
5687 : DCHECK_NULL(for_scope);
5688 8780 : return loop;
5689 : }
5690 :
5691 : template <typename Impl>
5692 437268 : void ParserBase<Impl>::CheckClassMethodName(IdentifierT name,
5693 : ParsePropertyKind type,
5694 : ParseFunctionFlags flags,
5695 : bool is_static,
5696 437268 : bool* has_seen_constructor) {
5697 : DCHECK(type == ParsePropertyKind::kMethod || IsAccessor(type));
5698 :
5699 437268 : AstValueFactory* avf = ast_value_factory();
5700 :
5701 437268 : if (is_static) {
5702 39011 : if (impl()->IdentifierEquals(name, avf->prototype_string())) {
5703 1094 : ReportMessage(MessageTemplate::kStaticPrototype);
5704 1094 : return;
5705 : }
5706 398257 : } else if (impl()->IdentifierEquals(name,
5707 : avf->private_constructor_string())) {
5708 960 : ReportMessage(MessageTemplate::kConstructorIsPrivate);
5709 960 : return;
5710 397297 : } else if (impl()->IdentifierEquals(name, avf->constructor_string())) {
5711 20756 : if (flags != ParseFunctionFlag::kIsNormal || IsAccessor(type)) {
5712 : MessageTemplate msg = (flags & ParseFunctionFlag::kIsGenerator) != 0
5713 : ? MessageTemplate::kConstructorIsGenerator
5714 : : (flags & ParseFunctionFlag::kIsAsync) != 0
5715 : ? MessageTemplate::kConstructorIsAsync
5716 1672 : : MessageTemplate::kConstructorIsAccessor;
5717 996 : ReportMessage(msg);
5718 996 : return;
5719 : }
5720 19760 : if (*has_seen_constructor) {
5721 98 : ReportMessage(MessageTemplate::kDuplicateConstructor);
5722 98 : return;
5723 : }
5724 19662 : *has_seen_constructor = true;
5725 19662 : return;
5726 : }
5727 : }
5728 :
5729 : template <typename Impl>
5730 89754 : void ParserBase<Impl>::CheckClassFieldName(IdentifierT name, bool is_static) {
5731 125669 : AstValueFactory* avf = ast_value_factory();
5732 125829 : if (is_static && impl()->IdentifierEquals(name, avf->prototype_string())) {
5733 160 : ReportMessage(MessageTemplate::kStaticPrototype);
5734 80 : return;
5735 : }
5736 :
5737 178708 : if (impl()->IdentifierEquals(name, avf->constructor_string()) ||
5738 : impl()->IdentifierEquals(name, avf->private_constructor_string())) {
5739 1120 : ReportMessage(MessageTemplate::kConstructorClassField);
5740 560 : return;
5741 : }
5742 : }
5743 :
5744 : #undef RETURN_IF_PARSE_ERROR
5745 :
5746 : } // namespace internal
5747 : } // namespace v8
5748 :
5749 : #endif // V8_PARSING_PARSER_BASE_H_
|