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.
10 #include "src/bailout-reason.h"
11 #include "src/func-name-inferrer.h"
12 #include "src/hashmap.h"
13 #include "src/scanner.h"
14 #include "src/scopes.h"
15 #include "src/token.h"
20 // Common base class shared between parser and pre-parser. Traits encapsulate
21 // the differences between Parser and PreParser:
23 // - Return types: For example, Parser functions return Expression* and
24 // PreParser functions return PreParserExpression.
26 // - Creating parse tree nodes: Parser generates an AST during the recursive
27 // descent. PreParser doesn't create a tree. Instead, it passes around minimal
28 // data objects (PreParserExpression, PreParserIdentifier etc.) which contain
29 // just enough data for the upper layer functions. PreParserFactory is
30 // responsible for creating these dummy objects. It provides a similar kind of
31 // interface as AstNodeFactory, so ParserBase doesn't need to care which one is
34 // - Miscellaneous other tasks interleaved with the recursive descent. For
35 // example, Parser keeps track of which function literals should be marked as
36 // pretenured, and PreParser doesn't care.
38 // The traits are expected to contain the following typedefs:
40 // // In particular...
42 // // Used by FunctionState and BlockState.
44 // typedef GeneratorVariable;
46 // // Return types for traversing functions.
47 // typedef Identifier;
48 // typedef Expression;
49 // typedef FunctionLiteral;
50 // typedef ClassLiteral;
51 // typedef ObjectLiteralProperty;
53 // typedef ExpressionList;
54 // typedef PropertyList;
55 // // For constructing objects returned by the traversing functions.
61 template <typename Traits>
62 class ParserBase : public Traits {
64 // Shorten type names defined by Traits.
65 typedef typename Traits::Type::Expression ExpressionT;
66 typedef typename Traits::Type::Identifier IdentifierT;
67 typedef typename Traits::Type::FunctionLiteral FunctionLiteralT;
68 typedef typename Traits::Type::Literal LiteralT;
69 typedef typename Traits::Type::ObjectLiteralProperty ObjectLiteralPropertyT;
71 ParserBase(Scanner* scanner, uintptr_t stack_limit, v8::Extension* extension,
72 ParserRecorder* log, typename Traits::Type::Zone* zone,
73 AstNode::IdGen* ast_node_id_gen,
74 typename Traits::Type::Parser this_object)
75 : Traits(this_object),
76 parenthesized_function_(false),
78 function_state_(NULL),
79 extension_(extension),
82 mode_(PARSE_EAGERLY), // Lazy mode must be set explicitly.
83 stack_limit_(stack_limit),
85 stack_overflow_(false),
87 allow_natives_syntax_(false),
88 allow_arrow_functions_(false),
89 allow_harmony_object_literals_(false),
91 ast_node_id_gen_(ast_node_id_gen) {}
93 // Getters that indicate whether certain syntactical constructs are
94 // allowed to be parsed by this instance of the parser.
95 bool allow_lazy() const { return allow_lazy_; }
96 bool allow_natives_syntax() const { return allow_natives_syntax_; }
97 bool allow_arrow_functions() const { return allow_arrow_functions_; }
98 bool allow_modules() const { return scanner()->HarmonyModules(); }
99 bool allow_harmony_scoping() const { return scanner()->HarmonyScoping(); }
100 bool allow_harmony_numeric_literals() const {
101 return scanner()->HarmonyNumericLiterals();
103 bool allow_classes() const { return scanner()->HarmonyClasses(); }
104 bool allow_harmony_object_literals() const {
105 return allow_harmony_object_literals_;
108 // Setters that determine whether certain syntactical constructs are
109 // allowed to be parsed by this instance of the parser.
110 void set_allow_lazy(bool allow) { allow_lazy_ = allow; }
111 void set_allow_natives_syntax(bool allow) { allow_natives_syntax_ = allow; }
112 void set_allow_arrow_functions(bool allow) { allow_arrow_functions_ = allow; }
113 void set_allow_modules(bool allow) { scanner()->SetHarmonyModules(allow); }
114 void set_allow_harmony_scoping(bool allow) {
115 scanner()->SetHarmonyScoping(allow);
117 void set_allow_harmony_numeric_literals(bool allow) {
118 scanner()->SetHarmonyNumericLiterals(allow);
120 void set_allow_classes(bool allow) { scanner()->SetHarmonyClasses(allow); }
121 void set_allow_harmony_object_literals(bool allow) {
122 allow_harmony_object_literals_ = allow;
126 friend class Traits::Checkpoint;
128 enum AllowEvalOrArgumentsAsIdentifier {
129 kAllowEvalOrArguments,
130 kDontAllowEvalOrArguments
138 class CheckpointBase;
139 class ObjectLiteralChecker;
141 // ---------------------------------------------------------------------------
142 // FunctionState and BlockState together implement the parser's scope stack.
143 // The parser's current scope is in scope_. BlockState and FunctionState
144 // constructors push on the scope stack and the destructors pop. They are also
145 // used to hold the parser's per-function and per-block state.
146 class BlockState BASE_EMBEDDED {
148 BlockState(typename Traits::Type::Scope** scope_stack,
149 typename Traits::Type::Scope* scope)
150 : scope_stack_(scope_stack),
151 outer_scope_(*scope_stack),
153 *scope_stack_ = scope_;
155 ~BlockState() { *scope_stack_ = outer_scope_; }
158 typename Traits::Type::Scope** scope_stack_;
159 typename Traits::Type::Scope* outer_scope_;
160 typename Traits::Type::Scope* scope_;
163 class FunctionState BASE_EMBEDDED {
165 FunctionState(FunctionState** function_state_stack,
166 typename Traits::Type::Scope** scope_stack,
167 typename Traits::Type::Scope* scope,
168 typename Traits::Type::Zone* zone = NULL,
169 AstValueFactory* ast_value_factory = NULL,
170 AstNode::IdGen* ast_node_id_gen = NULL);
171 FunctionState(FunctionState** function_state_stack,
172 typename Traits::Type::Scope** scope_stack,
173 typename Traits::Type::Scope** scope,
174 typename Traits::Type::Zone* zone = NULL,
175 AstValueFactory* ast_value_factory = NULL,
176 AstNode::IdGen* ast_node_id_gen = NULL);
179 int NextMaterializedLiteralIndex() {
180 return next_materialized_literal_index_++;
182 int materialized_literal_count() {
183 return next_materialized_literal_index_ - JSFunction::kLiteralsPrefixSize;
186 int NextHandlerIndex() { return next_handler_index_++; }
187 int handler_count() { return next_handler_index_; }
189 void AddProperty() { expected_property_count_++; }
190 int expected_property_count() { return expected_property_count_; }
192 void set_is_generator(bool is_generator) { is_generator_ = is_generator; }
193 bool is_generator() const { return is_generator_; }
195 void set_generator_object_variable(
196 typename Traits::Type::GeneratorVariable* variable) {
197 DCHECK(variable != NULL);
198 DCHECK(!is_generator());
199 generator_object_variable_ = variable;
200 is_generator_ = true;
202 typename Traits::Type::GeneratorVariable* generator_object_variable()
204 return generator_object_variable_;
207 typename Traits::Type::Factory* factory() { return &factory_; }
210 // Used to assign an index to each literal that needs materialization in
211 // the function. Includes regexp literals, and boilerplate for object and
213 int next_materialized_literal_index_;
215 // Used to assign a per-function index to try and catch handlers.
216 int next_handler_index_;
218 // Properties count estimation.
219 int expected_property_count_;
221 // Whether the function is a generator.
223 // For generators, this variable may hold the generator object. It variable
224 // is used by yield expressions and return statements. It is not necessary
225 // for generator functions to have this variable set.
226 Variable* generator_object_variable_;
228 FunctionState** function_state_stack_;
229 FunctionState* outer_function_state_;
230 typename Traits::Type::Scope** scope_stack_;
231 typename Traits::Type::Scope* outer_scope_;
232 AstNode::IdGen* ast_node_id_gen_; // Only used by ParserTraits.
233 AstNode::IdGen saved_id_gen_; // Ditto.
234 typename Traits::Type::Zone* extra_param_;
235 typename Traits::Type::Factory factory_;
237 friend class ParserTraits;
238 friend class CheckpointBase;
241 // Annoyingly, arrow functions first parse as comma expressions, then when we
242 // see the => we have to go back and reinterpret the arguments as being formal
243 // parameters. To do so we need to reset some of the parser state back to
244 // what it was before the arguments were first seen.
245 class CheckpointBase BASE_EMBEDDED {
247 explicit CheckpointBase(ParserBase* parser) {
248 function_state_ = parser->function_state_;
249 next_materialized_literal_index_ =
250 function_state_->next_materialized_literal_index_;
251 next_handler_index_ = function_state_->next_handler_index_;
252 expected_property_count_ = function_state_->expected_property_count_;
256 function_state_->next_materialized_literal_index_ =
257 next_materialized_literal_index_;
258 function_state_->next_handler_index_ = next_handler_index_;
259 function_state_->expected_property_count_ = expected_property_count_;
263 FunctionState* function_state_;
264 int next_materialized_literal_index_;
265 int next_handler_index_;
266 int expected_property_count_;
269 class ParsingModeScope BASE_EMBEDDED {
271 ParsingModeScope(ParserBase* parser, Mode mode)
273 old_mode_(parser->mode()) {
274 parser_->mode_ = mode;
276 ~ParsingModeScope() {
277 parser_->mode_ = old_mode_;
285 Scanner* scanner() const { return scanner_; }
286 int position() { return scanner_->location().beg_pos; }
287 int peek_position() { return scanner_->peek_location().beg_pos; }
288 bool stack_overflow() const { return stack_overflow_; }
289 void set_stack_overflow() { stack_overflow_ = true; }
290 Mode mode() const { return mode_; }
291 typename Traits::Type::Zone* zone() const { return zone_; }
292 AstNode::IdGen* ast_node_id_gen() const { return ast_node_id_gen_; }
294 INLINE(Token::Value peek()) {
295 if (stack_overflow_) return Token::ILLEGAL;
296 return scanner()->peek();
299 INLINE(Token::Value Next()) {
300 if (stack_overflow_) return Token::ILLEGAL;
302 if (GetCurrentStackPosition() < stack_limit_) {
303 // Any further calls to Next or peek will return the illegal token.
304 // The current call must return the next token, which might already
305 // have been peek'ed.
306 stack_overflow_ = true;
309 return scanner()->Next();
312 void Consume(Token::Value token) {
313 Token::Value next = Next();
316 DCHECK(next == token);
319 bool Check(Token::Value token) {
320 Token::Value next = peek();
328 void Expect(Token::Value token, bool* ok) {
329 Token::Value next = Next();
331 ReportUnexpectedToken(next);
336 void ExpectSemicolon(bool* ok) {
337 // Check for automatic semicolon insertion according to
338 // the rules given in ECMA-262, section 7.9, page 21.
339 Token::Value tok = peek();
340 if (tok == Token::SEMICOLON) {
344 if (scanner()->HasAnyLineTerminatorBeforeNext() ||
345 tok == Token::RBRACE ||
349 Expect(Token::SEMICOLON, ok);
352 bool peek_any_identifier() {
353 Token::Value next = peek();
354 return next == Token::IDENTIFIER ||
355 next == Token::FUTURE_RESERVED_WORD ||
356 next == Token::FUTURE_STRICT_RESERVED_WORD ||
357 next == Token::LET ||
358 next == Token::YIELD;
361 bool CheckContextualKeyword(Vector<const char> keyword) {
362 if (peek() == Token::IDENTIFIER &&
363 scanner()->is_next_contextual_keyword(keyword)) {
364 Consume(Token::IDENTIFIER);
370 void ExpectContextualKeyword(Vector<const char> keyword, bool* ok) {
371 Expect(Token::IDENTIFIER, ok);
373 if (!scanner()->is_literal_contextual_keyword(keyword)) {
374 ReportUnexpectedToken(scanner()->current_token());
379 // Checks whether an octal literal was last seen between beg_pos and end_pos.
380 // If so, reports an error. Only called for strict mode.
381 void CheckOctalLiteral(int beg_pos, int end_pos, bool* ok) {
382 Scanner::Location octal = scanner()->octal_position();
383 if (octal.IsValid() && beg_pos <= octal.beg_pos &&
384 octal.end_pos <= end_pos) {
385 ReportMessageAt(octal, "strict_octal_literal");
386 scanner()->clear_octal_position();
391 // Validates strict mode for function parameter lists. This has to be
392 // done after parsing the function, since the function can declare
394 void CheckStrictFunctionNameAndParameters(
395 IdentifierT function_name,
396 bool function_name_is_strict_reserved,
397 const Scanner::Location& function_name_loc,
398 const Scanner::Location& eval_args_error_loc,
399 const Scanner::Location& dupe_error_loc,
400 const Scanner::Location& reserved_loc,
402 if (this->IsEvalOrArguments(function_name)) {
403 Traits::ReportMessageAt(function_name_loc, "strict_eval_arguments");
407 if (function_name_is_strict_reserved) {
408 Traits::ReportMessageAt(function_name_loc, "unexpected_strict_reserved");
412 if (eval_args_error_loc.IsValid()) {
413 Traits::ReportMessageAt(eval_args_error_loc, "strict_eval_arguments");
417 if (dupe_error_loc.IsValid()) {
418 Traits::ReportMessageAt(dupe_error_loc, "strict_param_dupe");
422 if (reserved_loc.IsValid()) {
423 Traits::ReportMessageAt(reserved_loc, "unexpected_strict_reserved");
429 // Determine precedence of given token.
430 static int Precedence(Token::Value token, bool accept_IN) {
431 if (token == Token::IN && !accept_IN)
432 return 0; // 0 precedence will terminate binary expression parsing
433 return Token::Precedence(token);
436 typename Traits::Type::Factory* factory() {
437 return function_state_->factory();
440 StrictMode strict_mode() { return scope_->strict_mode(); }
441 bool is_generator() const { return function_state_->is_generator(); }
443 // Report syntax errors.
444 void ReportMessage(const char* message, const char* arg = NULL,
445 bool is_reference_error = false) {
446 Scanner::Location source_location = scanner()->location();
447 Traits::ReportMessageAt(source_location, message, arg, is_reference_error);
450 void ReportMessageAt(Scanner::Location location, const char* message,
451 bool is_reference_error = false) {
452 Traits::ReportMessageAt(location, message,
453 reinterpret_cast<const char*>(NULL),
457 void ReportUnexpectedToken(Token::Value token);
459 // Recursive descent functions:
461 // Parses an identifier that is valid for the current scope, in particular it
462 // fails on strict mode future reserved keywords in a strict scope. If
463 // allow_eval_or_arguments is kAllowEvalOrArguments, we allow "eval" or
464 // "arguments" as identifier even in strict mode (this is needed in cases like
465 // "var foo = eval;").
466 IdentifierT ParseIdentifier(
467 AllowEvalOrArgumentsAsIdentifier,
469 // Parses an identifier or a strict mode future reserved word, and indicate
470 // whether it is strict mode future reserved.
471 IdentifierT ParseIdentifierOrStrictReservedWord(
472 bool* is_strict_reserved,
474 IdentifierT ParseIdentifierName(bool* ok);
475 // Parses an identifier and determines whether or not it is 'get' or 'set'.
476 IdentifierT ParseIdentifierNameOrGetOrSet(bool* is_get,
480 ExpressionT ParseRegExpLiteral(bool seen_equal, bool* ok);
482 ExpressionT ParsePrimaryExpression(bool* ok);
483 ExpressionT ParseExpression(bool accept_IN, bool* ok);
484 ExpressionT ParseArrayLiteral(bool* ok);
485 IdentifierT ParsePropertyName(bool* is_get, bool* is_set, bool* is_static,
487 ExpressionT ParseObjectLiteral(bool* ok);
488 ObjectLiteralPropertyT ParsePropertyDefinition(ObjectLiteralChecker* checker,
489 bool in_class, bool is_static,
491 typename Traits::Type::ExpressionList ParseArguments(bool* ok);
492 ExpressionT ParseAssignmentExpression(bool accept_IN, bool* ok);
493 ExpressionT ParseYieldExpression(bool* ok);
494 ExpressionT ParseConditionalExpression(bool accept_IN, bool* ok);
495 ExpressionT ParseBinaryExpression(int prec, bool accept_IN, bool* ok);
496 ExpressionT ParseUnaryExpression(bool* ok);
497 ExpressionT ParsePostfixExpression(bool* ok);
498 ExpressionT ParseLeftHandSideExpression(bool* ok);
499 ExpressionT ParseMemberWithNewPrefixesExpression(bool* ok);
500 ExpressionT ParseMemberExpression(bool* ok);
501 ExpressionT ParseMemberExpressionContinuation(ExpressionT expression,
503 ExpressionT ParseArrowFunctionLiteral(int start_pos, ExpressionT params_ast,
505 ExpressionT ParseClassLiteral(IdentifierT name,
506 Scanner::Location function_name_location,
507 bool name_is_strict_reserved, int pos,
510 // Checks if the expression is a valid reference expression (e.g., on the
511 // left-hand side of assignments). Although ruled out by ECMA as early errors,
512 // we allow calls for web compatibility and rewrite them to a runtime throw.
513 ExpressionT CheckAndRewriteReferenceExpression(
514 ExpressionT expression,
515 Scanner::Location location, const char* message, bool* ok);
517 // Used to detect duplicates in object literals. Each of the values
518 // kGetterProperty, kSetterProperty and kValueProperty represents
519 // a type of object literal property. When parsing a property, its
520 // type value is stored in the DuplicateFinder for the property name.
521 // Values are chosen so that having intersection bits means the there is
522 // an incompatibility.
523 // I.e., you can add a getter to a property that already has a setter, since
524 // kGetterProperty and kSetterProperty doesn't intersect, but not if it
525 // already has a getter or a value. Adding the getter to an existing
526 // setter will store the value (kGetterProperty | kSetterProperty), which
527 // is incompatible with adding any further properties.
530 // Bit patterns representing different object literal property types.
538 // Validation per ECMA 262 - 11.1.5 "Object Initializer".
539 class ObjectLiteralChecker {
541 ObjectLiteralChecker(ParserBase* parser, StrictMode strict_mode)
543 finder_(scanner()->unicode_cache()),
544 strict_mode_(strict_mode) {}
546 void CheckProperty(Token::Value property, PropertyKind type, bool* ok);
549 ParserBase* parser() const { return parser_; }
550 Scanner* scanner() const { return parser_->scanner(); }
552 // Checks the type of conflict based on values coming from PropertyType.
553 bool HasConflict(PropertyKind type1, PropertyKind type2) {
554 return (type1 & type2) != 0;
556 bool IsDataDataConflict(PropertyKind type1, PropertyKind type2) {
557 return ((type1 & type2) & kValueFlag) != 0;
559 bool IsDataAccessorConflict(PropertyKind type1, PropertyKind type2) {
560 return ((type1 ^ type2) & kValueFlag) != 0;
562 bool IsAccessorAccessorConflict(PropertyKind type1, PropertyKind type2) {
563 return ((type1 | type2) & kValueFlag) == 0;
567 DuplicateFinder finder_;
568 StrictMode strict_mode_;
571 // If true, the next (and immediately following) function literal is
572 // preceded by a parenthesis.
573 // Heuristically that means that the function will be called immediately,
574 // so never lazily compile it.
575 bool parenthesized_function_;
577 typename Traits::Type::Scope* scope_; // Scope stack.
578 FunctionState* function_state_; // Function state stack.
579 v8::Extension* extension_;
580 FuncNameInferrer* fni_;
581 ParserRecorder* log_;
583 uintptr_t stack_limit_;
587 bool stack_overflow_;
590 bool allow_natives_syntax_;
591 bool allow_arrow_functions_;
592 bool allow_harmony_object_literals_;
594 typename Traits::Type::Zone* zone_; // Only used by Parser.
595 AstNode::IdGen* ast_node_id_gen_;
599 class PreParserIdentifier {
601 PreParserIdentifier() : type_(kUnknownIdentifier) {}
602 static PreParserIdentifier Default() {
603 return PreParserIdentifier(kUnknownIdentifier);
605 static PreParserIdentifier Eval() {
606 return PreParserIdentifier(kEvalIdentifier);
608 static PreParserIdentifier Arguments() {
609 return PreParserIdentifier(kArgumentsIdentifier);
611 static PreParserIdentifier FutureReserved() {
612 return PreParserIdentifier(kFutureReservedIdentifier);
614 static PreParserIdentifier FutureStrictReserved() {
615 return PreParserIdentifier(kFutureStrictReservedIdentifier);
617 static PreParserIdentifier Let() {
618 return PreParserIdentifier(kLetIdentifier);
620 static PreParserIdentifier Yield() {
621 return PreParserIdentifier(kYieldIdentifier);
623 static PreParserIdentifier Prototype() {
624 return PreParserIdentifier(kPrototypeIdentifier);
626 static PreParserIdentifier Constructor() {
627 return PreParserIdentifier(kConstructorIdentifier);
629 bool IsEval() const { return type_ == kEvalIdentifier; }
630 bool IsArguments() const { return type_ == kArgumentsIdentifier; }
631 bool IsYield() const { return type_ == kYieldIdentifier; }
632 bool IsPrototype() const { return type_ == kPrototypeIdentifier; }
633 bool IsConstructor() const { return type_ == kConstructorIdentifier; }
634 bool IsEvalOrArguments() const {
635 return type_ == kEvalIdentifier || type_ == kArgumentsIdentifier;
637 bool IsFutureReserved() const { return type_ == kFutureReservedIdentifier; }
638 bool IsFutureStrictReserved() const {
639 return type_ == kFutureStrictReservedIdentifier;
641 bool IsValidStrictVariable() const { return type_ == kUnknownIdentifier; }
643 // Allow identifier->name()[->length()] to work. The preparser
644 // does not need the actual positions/lengths of the identifiers.
645 const PreParserIdentifier* operator->() const { return this; }
646 const PreParserIdentifier raw_name() const { return *this; }
648 int position() const { return 0; }
649 int length() const { return 0; }
654 kFutureReservedIdentifier,
655 kFutureStrictReservedIdentifier,
659 kArgumentsIdentifier,
660 kPrototypeIdentifier,
661 kConstructorIdentifier
663 explicit PreParserIdentifier(Type type) : type_(type) {}
666 friend class PreParserExpression;
667 friend class PreParserScope;
671 // Bits 0 and 1 are used to identify the type of expression:
672 // If bit 0 is set, it's an identifier.
673 // if bit 1 is set, it's a string literal.
674 // If neither is set, it's no particular type, and both set isn't
676 class PreParserExpression {
678 static PreParserExpression Default() {
679 return PreParserExpression(kUnknownExpression);
682 static PreParserExpression FromIdentifier(PreParserIdentifier id) {
683 return PreParserExpression(kTypeIdentifier |
684 (id.type_ << kIdentifierShift));
687 static PreParserExpression BinaryOperation(PreParserExpression left,
689 PreParserExpression right) {
690 int code = ((op == Token::COMMA) && !left.is_parenthesized() &&
691 !right.is_parenthesized())
692 ? left.ArrowParamListBit() & right.ArrowParamListBit()
694 return PreParserExpression(kTypeBinaryOperation | code);
697 static PreParserExpression EmptyArrowParamList() {
698 // Any expression for which IsValidArrowParamList() returns true
700 return FromIdentifier(PreParserIdentifier::Default());
703 static PreParserExpression StringLiteral() {
704 return PreParserExpression(kUnknownStringLiteral);
707 static PreParserExpression UseStrictStringLiteral() {
708 return PreParserExpression(kUseStrictString);
711 static PreParserExpression This() {
712 return PreParserExpression(kThisExpression);
715 static PreParserExpression Super() {
716 return PreParserExpression(kSuperExpression);
719 static PreParserExpression ThisProperty() {
720 return PreParserExpression(kThisPropertyExpression);
723 static PreParserExpression Property() {
724 return PreParserExpression(kPropertyExpression);
727 static PreParserExpression Call() {
728 return PreParserExpression(kCallExpression);
731 bool IsIdentifier() const { return (code_ & kTypeMask) == kTypeIdentifier; }
733 PreParserIdentifier AsIdentifier() const {
734 DCHECK(IsIdentifier());
735 return PreParserIdentifier(
736 static_cast<PreParserIdentifier::Type>(code_ >> kIdentifierShift));
739 bool IsStringLiteral() const {
740 return (code_ & kTypeMask) == kTypeStringLiteral;
743 bool IsUseStrictLiteral() const {
744 return (code_ & kUseStrictString) == kUseStrictString;
747 bool IsThis() const { return (code_ & kThisExpression) == kThisExpression; }
749 bool IsThisProperty() const {
750 return (code_ & kThisPropertyExpression) == kThisPropertyExpression;
753 bool IsProperty() const {
754 return (code_ & kPropertyExpression) == kPropertyExpression ||
755 (code_ & kThisPropertyExpression) == kThisPropertyExpression;
758 bool IsCall() const { return (code_ & kCallExpression) == kCallExpression; }
760 bool IsValidReferenceExpression() const {
761 return IsIdentifier() || IsProperty();
764 bool IsValidArrowParamList() const {
765 return (ArrowParamListBit() & kBinaryOperationArrowParamList) != 0 &&
766 (code_ & kMultiParenthesizedExpression) == 0;
769 // At the moment PreParser doesn't track these expression types.
770 bool IsFunctionLiteral() const { return false; }
771 bool IsCallNew() const { return false; }
773 PreParserExpression AsFunctionLiteral() { return *this; }
775 bool IsBinaryOperation() const {
776 return (code_ & kTypeMask) == kTypeBinaryOperation;
779 bool is_parenthesized() const {
780 return (code_ & kParenthesizedExpression) != 0;
783 void increase_parenthesization_level() {
784 code_ |= is_parenthesized() ? kMultiParenthesizedExpression
785 : kParenthesizedExpression;
788 // Dummy implementation for making expression->somefunc() work in both Parser
790 PreParserExpression* operator->() { return this; }
792 // More dummy implementations of things PreParser doesn't need to track:
793 void set_index(int index) {} // For YieldExpressions
794 void set_parenthesized() {}
796 int position() const { return RelocInfo::kNoPosition; }
797 void set_function_token_position(int position) {}
798 void set_ast_properties(int* ast_properties) {}
799 void set_dont_optimize_reason(BailoutReason dont_optimize_reason) {}
801 bool operator==(const PreParserExpression& other) const {
802 return code_ == other.code_;
804 bool operator!=(const PreParserExpression& other) const {
805 return code_ != other.code_;
809 // Least significant 2 bits are used as expression type. The third least
810 // significant bit tracks whether an expression is parenthesized. If the
811 // expression is an identifier or a string literal, the other bits
812 // describe the type/ (see PreParserIdentifier::Type and string literal
813 // constants below). For binary operations, the other bits are flags
814 // which further describe the contents of the expression.
816 kUnknownExpression = 0,
818 kParenthesizedExpression = (1 << 2),
819 kMultiParenthesizedExpression = (1 << 3),
822 kTypeIdentifier = 1, // Used to detect labels.
823 kIdentifierShift = 5,
824 kTypeStringLiteral = 2, // Used to detect directive prologue.
825 kUnknownStringLiteral = kTypeStringLiteral,
826 kUseStrictString = kTypeStringLiteral | 32,
827 kStringLiteralMask = kUseStrictString,
829 // Binary operations. Those are needed to detect certain keywords and
830 // duplicated identifier in parameter lists for arrow functions, because
831 // they are initially parsed as comma-separated expressions.
832 kTypeBinaryOperation = 3,
833 kBinaryOperationArrowParamList = (1 << 4),
835 // Below here applies if neither identifier nor string literal. Reserve the
836 // 2 least significant bits for flags.
837 kThisExpression = (1 << 4),
838 kThisPropertyExpression = (2 << 4),
839 kPropertyExpression = (3 << 4),
840 kCallExpression = (4 << 4),
841 kSuperExpression = (5 << 4)
844 explicit PreParserExpression(int expression_code) : code_(expression_code) {}
846 V8_INLINE int ArrowParamListBit() const {
847 if (IsBinaryOperation()) return code_ & kBinaryOperationArrowParamList;
848 if (IsIdentifier()) {
849 const PreParserIdentifier ident = AsIdentifier();
850 // A valid identifier can be an arrow function parameter list
851 // except for eval, arguments, yield, and reserved keywords.
852 if (ident.IsEval() || ident.IsArguments() || ident.IsYield() ||
853 ident.IsFutureStrictReserved())
855 return kBinaryOperationArrowParamList;
864 // PreParserExpressionList doesn't actually store the expressions because
865 // PreParser doesn't need to.
866 class PreParserExpressionList {
868 // These functions make list->Add(some_expression) work (and do nothing).
869 PreParserExpressionList() : length_(0) {}
870 PreParserExpressionList* operator->() { return this; }
871 void Add(PreParserExpression, void*) { ++length_; }
872 int length() const { return length_; }
878 class PreParserStatement {
880 static PreParserStatement Default() {
881 return PreParserStatement(kUnknownStatement);
884 static PreParserStatement FunctionDeclaration() {
885 return PreParserStatement(kFunctionDeclaration);
888 // Creates expression statement from expression.
889 // Preserves being an unparenthesized string literal, possibly
891 static PreParserStatement ExpressionStatement(
892 PreParserExpression expression) {
893 if (expression.IsUseStrictLiteral()) {
894 return PreParserStatement(kUseStrictExpressionStatement);
896 if (expression.IsStringLiteral()) {
897 return PreParserStatement(kStringLiteralExpressionStatement);
902 bool IsStringLiteral() {
903 return code_ == kStringLiteralExpressionStatement;
906 bool IsUseStrictLiteral() {
907 return code_ == kUseStrictExpressionStatement;
910 bool IsFunctionDeclaration() {
911 return code_ == kFunctionDeclaration;
917 kStringLiteralExpressionStatement,
918 kUseStrictExpressionStatement,
922 explicit PreParserStatement(Type code) : code_(code) {}
928 // PreParserStatementList doesn't actually store the statements because
929 // the PreParser does not need them.
930 class PreParserStatementList {
932 // These functions make list->Add(some_expression) work as no-ops.
933 PreParserStatementList() {}
934 PreParserStatementList* operator->() { return this; }
935 void Add(PreParserStatement, void*) {}
939 class PreParserScope {
941 explicit PreParserScope(PreParserScope* outer_scope, ScopeType scope_type,
943 : scope_type_(scope_type) {
944 strict_mode_ = outer_scope ? outer_scope->strict_mode() : SLOPPY;
947 ScopeType type() { return scope_type_; }
948 StrictMode strict_mode() const { return strict_mode_; }
949 void SetStrictMode(StrictMode strict_mode) { strict_mode_ = strict_mode; }
950 void SetScopeName(PreParserIdentifier name) {}
952 // When PreParser is in use, lazy compilation is already being done,
953 // things cannot get lazier than that.
954 bool AllowsLazyCompilation() const { return false; }
956 void set_start_position(int position) {}
957 void set_end_position(int position) {}
959 bool IsDeclared(const PreParserIdentifier& identifier) const { return false; }
960 void DeclareParameter(const PreParserIdentifier& identifier, VariableMode) {}
962 // Allow scope->Foo() to work.
963 PreParserScope* operator->() { return this; }
966 ScopeType scope_type_;
967 StrictMode strict_mode_;
971 class PreParserFactory {
973 PreParserFactory(void*, void*, void*) {}
974 PreParserExpression NewStringLiteral(PreParserIdentifier identifier,
976 return PreParserExpression::Default();
978 PreParserExpression NewNumberLiteral(double number,
980 return PreParserExpression::Default();
982 PreParserExpression NewRegExpLiteral(PreParserIdentifier js_pattern,
983 PreParserIdentifier js_flags,
986 return PreParserExpression::Default();
988 PreParserExpression NewArrayLiteral(PreParserExpressionList values,
991 return PreParserExpression::Default();
993 PreParserExpression NewObjectLiteralProperty(bool is_getter,
994 PreParserExpression value,
995 int pos, bool is_static) {
996 return PreParserExpression::Default();
998 PreParserExpression NewObjectLiteralProperty(PreParserExpression key,
999 PreParserExpression value,
1001 return PreParserExpression::Default();
1003 PreParserExpression NewObjectLiteral(PreParserExpressionList properties,
1005 int boilerplate_properties,
1008 return PreParserExpression::Default();
1010 PreParserExpression NewVariableProxy(void* variable) {
1011 return PreParserExpression::Default();
1013 PreParserExpression NewProperty(PreParserExpression obj,
1014 PreParserExpression key,
1017 return PreParserExpression::ThisProperty();
1019 return PreParserExpression::Property();
1021 PreParserExpression NewUnaryOperation(Token::Value op,
1022 PreParserExpression expression,
1024 return PreParserExpression::Default();
1026 PreParserExpression NewBinaryOperation(Token::Value op,
1027 PreParserExpression left,
1028 PreParserExpression right, int pos) {
1029 return PreParserExpression::BinaryOperation(left, op, right);
1031 PreParserExpression NewCompareOperation(Token::Value op,
1032 PreParserExpression left,
1033 PreParserExpression right, int pos) {
1034 return PreParserExpression::Default();
1036 PreParserExpression NewAssignment(Token::Value op,
1037 PreParserExpression left,
1038 PreParserExpression right,
1040 return PreParserExpression::Default();
1042 PreParserExpression NewYield(PreParserExpression generator_object,
1043 PreParserExpression expression,
1044 Yield::Kind yield_kind,
1046 return PreParserExpression::Default();
1048 PreParserExpression NewConditional(PreParserExpression condition,
1049 PreParserExpression then_expression,
1050 PreParserExpression else_expression,
1052 return PreParserExpression::Default();
1054 PreParserExpression NewCountOperation(Token::Value op,
1056 PreParserExpression expression,
1058 return PreParserExpression::Default();
1060 PreParserExpression NewCall(PreParserExpression expression,
1061 PreParserExpressionList arguments,
1063 return PreParserExpression::Call();
1065 PreParserExpression NewCallNew(PreParserExpression expression,
1066 PreParserExpressionList arguments,
1068 return PreParserExpression::Default();
1070 PreParserStatement NewReturnStatement(PreParserExpression expression,
1072 return PreParserStatement::Default();
1074 PreParserExpression NewFunctionLiteral(
1075 PreParserIdentifier name, AstValueFactory* ast_value_factory,
1076 const PreParserScope& scope, PreParserStatementList body,
1077 int materialized_literal_count, int expected_property_count,
1078 int handler_count, int parameter_count,
1079 FunctionLiteral::ParameterFlag has_duplicate_parameters,
1080 FunctionLiteral::FunctionType function_type,
1081 FunctionLiteral::IsFunctionFlag is_function,
1082 FunctionLiteral::IsParenthesizedFlag is_parenthesized, FunctionKind kind,
1084 return PreParserExpression::Default();
1086 PreParserExpression NewClassLiteral(PreParserIdentifier name,
1087 PreParserExpression extends,
1088 PreParserExpression constructor,
1089 PreParserExpressionList properties,
1091 return PreParserExpression::Default();
1094 // Return the object itself as AstVisitor and implement the needed
1095 // dummy method right in this class.
1096 PreParserFactory* visitor() { return this; }
1097 BailoutReason dont_optimize_reason() { return kNoReason; }
1098 int* ast_properties() {
1099 static int dummy = 42;
1107 class PreParserTraits {
1110 // TODO(marja): To be removed. The Traits object should contain all the data
1112 typedef PreParser* Parser;
1114 // Used by FunctionState and BlockState.
1115 typedef PreParserScope Scope;
1116 typedef PreParserScope ScopePtr;
1118 // PreParser doesn't need to store generator variables.
1119 typedef void GeneratorVariable;
1120 // No interaction with Zones.
1123 typedef int AstProperties;
1124 typedef Vector<PreParserIdentifier> ParameterIdentifierVector;
1126 // Return types for traversing functions.
1127 typedef PreParserIdentifier Identifier;
1128 typedef PreParserExpression Expression;
1129 typedef PreParserExpression YieldExpression;
1130 typedef PreParserExpression FunctionLiteral;
1131 typedef PreParserExpression ClassLiteral;
1132 typedef PreParserExpression ObjectLiteralProperty;
1133 typedef PreParserExpression Literal;
1134 typedef PreParserExpressionList ExpressionList;
1135 typedef PreParserExpressionList PropertyList;
1136 typedef PreParserStatementList StatementList;
1138 // For constructing objects returned by the traversing functions.
1139 typedef PreParserFactory Factory;
1144 explicit PreParserTraits(PreParser* pre_parser) : pre_parser_(pre_parser) {}
1146 // Custom operations executed when FunctionStates are created and
1147 // destructed. (The PreParser doesn't need to do anything.)
1148 template <typename FunctionState>
1149 static void SetUpFunctionState(FunctionState* function_state) {}
1150 template <typename FunctionState>
1151 static void TearDownFunctionState(FunctionState* function_state) {}
1153 // Helper functions for recursive descent.
1154 static bool IsEvalOrArguments(PreParserIdentifier identifier) {
1155 return identifier.IsEvalOrArguments();
1158 static bool IsPrototype(PreParserIdentifier identifier) {
1159 return identifier.IsPrototype();
1162 static bool IsConstructor(PreParserIdentifier identifier) {
1163 return identifier.IsConstructor();
1166 // Returns true if the expression is of type "this.foo".
1167 static bool IsThisProperty(PreParserExpression expression) {
1168 return expression.IsThisProperty();
1171 static bool IsIdentifier(PreParserExpression expression) {
1172 return expression.IsIdentifier();
1175 static PreParserIdentifier AsIdentifier(PreParserExpression expression) {
1176 return expression.AsIdentifier();
1179 static bool IsFutureStrictReserved(PreParserIdentifier identifier) {
1180 return identifier.IsYield() || identifier.IsFutureStrictReserved();
1183 static bool IsBoilerplateProperty(PreParserExpression property) {
1184 // PreParser doesn't count boilerplate properties.
1188 static bool IsArrayIndex(PreParserIdentifier string, uint32_t* index) {
1192 // Functions for encapsulating the differences between parsing and preparsing;
1193 // operations interleaved with the recursive descent.
1194 static void PushLiteralName(FuncNameInferrer* fni, PreParserIdentifier id) {
1195 // PreParser should not use FuncNameInferrer.
1198 static void PushPropertyName(FuncNameInferrer* fni,
1199 PreParserExpression expression) {
1200 // PreParser should not use FuncNameInferrer.
1203 static void InferFunctionName(FuncNameInferrer* fni,
1204 PreParserExpression expression) {
1205 // PreParser should not use FuncNameInferrer.
1209 static void CheckFunctionLiteralInsideTopLevelObjectLiteral(
1210 PreParserScope* scope, PreParserExpression property, bool* has_function) {
1213 static void CheckAssigningFunctionLiteralToProperty(
1214 PreParserExpression left, PreParserExpression right) {}
1216 // PreParser doesn't need to keep track of eval calls.
1217 static void CheckPossibleEvalCall(PreParserExpression expression,
1218 PreParserScope* scope) {}
1220 static PreParserExpression MarkExpressionAsAssigned(
1221 PreParserExpression expression) {
1222 // TODO(marja): To be able to produce the same errors, the preparser needs
1223 // to start tracking which expressions are variables and which are assigned.
1227 bool ShortcutNumericLiteralBinaryExpression(PreParserExpression* x,
1228 PreParserExpression y,
1231 PreParserFactory* factory) {
1235 bool BuildSIMD128LoadStoreExpression(
1236 PreParserExpression* expression,
1237 PreParserExpressionList arguments,
1239 PreParserFactory* factory) {
1243 PreParserExpression BuildUnaryExpression(PreParserExpression expression,
1244 Token::Value op, int pos,
1245 PreParserFactory* factory) {
1246 return PreParserExpression::Default();
1249 PreParserExpression NewThrowReferenceError(const char* type, int pos) {
1250 return PreParserExpression::Default();
1252 PreParserExpression NewThrowSyntaxError(
1253 const char* type, Handle<Object> arg, int pos) {
1254 return PreParserExpression::Default();
1256 PreParserExpression NewThrowTypeError(
1257 const char* type, Handle<Object> arg, int pos) {
1258 return PreParserExpression::Default();
1260 PreParserScope NewScope(PreParserScope* outer_scope, ScopeType scope_type) {
1261 return PreParserScope(outer_scope, scope_type);
1264 // Reporting errors.
1265 void ReportMessageAt(Scanner::Location location,
1266 const char* message,
1267 const char* arg = NULL,
1268 bool is_reference_error = false);
1269 void ReportMessageAt(int start_pos,
1271 const char* message,
1272 const char* arg = NULL,
1273 bool is_reference_error = false);
1275 // "null" return type creators.
1276 static PreParserIdentifier EmptyIdentifier() {
1277 return PreParserIdentifier::Default();
1279 static PreParserIdentifier EmptyIdentifierString() {
1280 return PreParserIdentifier::Default();
1282 static PreParserExpression EmptyExpression() {
1283 return PreParserExpression::Default();
1285 static PreParserExpression EmptyArrowParamList() {
1286 return PreParserExpression::EmptyArrowParamList();
1288 static PreParserExpression EmptyLiteral() {
1289 return PreParserExpression::Default();
1291 static PreParserExpression EmptyObjectLiteralProperty() {
1292 return PreParserExpression::Default();
1294 static PreParserExpression EmptyFunctionLiteral() {
1295 return PreParserExpression::Default();
1297 static PreParserExpressionList NullExpressionList() {
1298 return PreParserExpressionList();
1301 // Odd-ball literal creators.
1302 static PreParserExpression GetLiteralTheHole(int position,
1303 PreParserFactory* factory) {
1304 return PreParserExpression::Default();
1307 // Producing data during the recursive descent.
1308 PreParserIdentifier GetSymbol(Scanner* scanner);
1309 PreParserIdentifier GetNumberAsSymbol(Scanner* scanner);
1311 static PreParserIdentifier GetNextSymbol(Scanner* scanner) {
1312 return PreParserIdentifier::Default();
1315 static PreParserExpression ThisExpression(PreParserScope* scope,
1316 PreParserFactory* factory) {
1317 return PreParserExpression::This();
1320 static PreParserExpression SuperReference(PreParserScope* scope,
1321 PreParserFactory* factory) {
1322 return PreParserExpression::Super();
1325 static PreParserExpression ClassLiteral(PreParserIdentifier name,
1326 PreParserExpression extends,
1327 PreParserExpression constructor,
1328 PreParserExpressionList properties,
1330 PreParserFactory* factory) {
1331 return PreParserExpression::Default();
1334 static PreParserExpression ExpressionFromLiteral(
1335 Token::Value token, int pos, Scanner* scanner,
1336 PreParserFactory* factory) {
1337 return PreParserExpression::Default();
1340 static PreParserExpression ExpressionFromIdentifier(
1341 PreParserIdentifier name, int pos, PreParserScope* scope,
1342 PreParserFactory* factory) {
1343 return PreParserExpression::FromIdentifier(name);
1346 PreParserExpression ExpressionFromString(int pos,
1348 PreParserFactory* factory = NULL);
1350 PreParserExpression GetIterator(PreParserExpression iterable,
1351 PreParserFactory* factory) {
1352 return PreParserExpression::Default();
1355 static PreParserExpressionList NewExpressionList(int size, void* zone) {
1356 return PreParserExpressionList();
1359 static PreParserStatementList NewStatementList(int size, void* zone) {
1360 return PreParserStatementList();
1363 static PreParserExpressionList NewPropertyList(int size, void* zone) {
1364 return PreParserExpressionList();
1367 V8_INLINE void SkipLazyFunctionBody(PreParserIdentifier function_name,
1368 int* materialized_literal_count,
1369 int* expected_property_count, bool* ok) {
1373 V8_INLINE PreParserStatementList
1374 ParseEagerFunctionBody(PreParserIdentifier function_name, int pos,
1375 Variable* fvar, Token::Value fvar_init_op,
1376 bool is_generator, bool* ok);
1378 // Utility functions
1379 int DeclareArrowParametersFromExpression(PreParserExpression expression,
1380 PreParserScope* scope,
1381 Scanner::Location* dupe_loc,
1383 // TODO(aperez): Detect duplicated identifiers in paramlists.
1384 *ok = expression.IsValidArrowParamList();
1388 static AstValueFactory* ast_value_factory() { return NULL; }
1390 void CheckConflictingVarDeclarations(PreParserScope scope, bool* ok) {}
1392 // Temporary glue; these functions will move to ParserBase.
1393 PreParserExpression ParseV8Intrinsic(bool* ok);
1394 PreParserExpression ParseFunctionLiteral(
1395 PreParserIdentifier name, Scanner::Location function_name_location,
1396 bool name_is_strict_reserved, FunctionKind kind,
1397 int function_token_position, FunctionLiteral::FunctionType type,
1398 FunctionLiteral::ArityRestriction arity_restriction, bool* ok);
1401 PreParser* pre_parser_;
1405 // Preparsing checks a JavaScript program and emits preparse-data that helps
1406 // a later parsing to be faster.
1407 // See preparse-data-format.h for the data format.
1409 // The PreParser checks that the syntax follows the grammar for JavaScript,
1410 // and collects some information about the program along the way.
1411 // The grammar check is only performed in order to understand the program
1412 // sufficiently to deduce some information about it, that can be used
1413 // to speed up later parsing. Finding errors is not the goal of pre-parsing,
1414 // rather it is to speed up properly written and correct programs.
1415 // That means that contextual checks (like a label being declared where
1416 // it is used) are generally omitted.
1417 class PreParser : public ParserBase<PreParserTraits> {
1419 typedef PreParserIdentifier Identifier;
1420 typedef PreParserExpression Expression;
1421 typedef PreParserStatement Statement;
1423 enum PreParseResult {
1424 kPreParseStackOverflow,
1428 PreParser(Scanner* scanner, ParserRecorder* log, uintptr_t stack_limit)
1429 : ParserBase<PreParserTraits>(scanner, stack_limit, NULL, log, NULL, NULL,
1432 // Pre-parse the program from the character stream; returns true on
1433 // success (even if parsing failed, the pre-parse data successfully
1434 // captured the syntax error), and false if a stack-overflow happened
1436 PreParseResult PreParseProgram() {
1437 PreParserScope scope(scope_, GLOBAL_SCOPE);
1438 FunctionState top_scope(&function_state_, &scope_, &scope);
1440 int start_position = scanner()->peek_location().beg_pos;
1441 ParseSourceElements(Token::EOS, &ok);
1442 if (stack_overflow()) return kPreParseStackOverflow;
1444 ReportUnexpectedToken(scanner()->current_token());
1445 } else if (scope_->strict_mode() == STRICT) {
1446 CheckOctalLiteral(start_position, scanner()->location().end_pos, &ok);
1448 return kPreParseSuccess;
1451 // Parses a single function literal, from the opening parentheses before
1452 // parameters to the closing brace after the body.
1453 // Returns a FunctionEntry describing the body of the function in enough
1454 // detail that it can be lazily compiled.
1455 // The scanner is expected to have matched the "function" or "function*"
1456 // keyword and parameters, and have consumed the initial '{'.
1457 // At return, unless an error occurred, the scanner is positioned before the
1459 PreParseResult PreParseLazyFunction(StrictMode strict_mode,
1461 ParserRecorder* log);
1464 friend class PreParserTraits;
1466 // These types form an algebra over syntactic categories that is just
1467 // rich enough to let us recognize and propagate the constructs that
1468 // are either being counted in the preparser data, or is important
1469 // to throw the correct syntax error exceptions.
1471 enum VariableDeclarationContext {
1477 // If a list of variable declarations includes any initializers.
1478 enum VariableDeclarationProperties {
1484 enum SourceElements {
1485 kUnknownSourceElements
1488 // All ParseXXX functions take as the last argument an *ok parameter
1489 // which is set to false if parsing failed; it is unchanged otherwise.
1490 // By making the 'exception handling' explicit, we are forced to check
1491 // for failure at the call sites.
1492 Statement ParseSourceElement(bool* ok);
1493 SourceElements ParseSourceElements(int end_token, bool* ok);
1494 Statement ParseStatement(bool* ok);
1495 Statement ParseFunctionDeclaration(bool* ok);
1496 Statement ParseClassDeclaration(bool* ok);
1497 Statement ParseBlock(bool* ok);
1498 Statement ParseVariableStatement(VariableDeclarationContext var_context,
1500 Statement ParseVariableDeclarations(VariableDeclarationContext var_context,
1501 VariableDeclarationProperties* decl_props,
1504 Statement ParseExpressionOrLabelledStatement(bool* ok);
1505 Statement ParseIfStatement(bool* ok);
1506 Statement ParseContinueStatement(bool* ok);
1507 Statement ParseBreakStatement(bool* ok);
1508 Statement ParseReturnStatement(bool* ok);
1509 Statement ParseWithStatement(bool* ok);
1510 Statement ParseSwitchStatement(bool* ok);
1511 Statement ParseDoWhileStatement(bool* ok);
1512 Statement ParseWhileStatement(bool* ok);
1513 Statement ParseForStatement(bool* ok);
1514 Statement ParseThrowStatement(bool* ok);
1515 Statement ParseTryStatement(bool* ok);
1516 Statement ParseDebuggerStatement(bool* ok);
1517 Expression ParseConditionalExpression(bool accept_IN, bool* ok);
1518 Expression ParseObjectLiteral(bool* ok);
1519 Expression ParseV8Intrinsic(bool* ok);
1521 V8_INLINE void SkipLazyFunctionBody(PreParserIdentifier function_name,
1522 int* materialized_literal_count,
1523 int* expected_property_count, bool* ok);
1524 V8_INLINE PreParserStatementList
1525 ParseEagerFunctionBody(PreParserIdentifier function_name, int pos,
1526 Variable* fvar, Token::Value fvar_init_op,
1527 bool is_generator, bool* ok);
1529 Expression ParseFunctionLiteral(
1530 Identifier name, Scanner::Location function_name_location,
1531 bool name_is_strict_reserved, FunctionKind kind, int function_token_pos,
1532 FunctionLiteral::FunctionType function_type,
1533 FunctionLiteral::ArityRestriction arity_restriction, bool* ok);
1534 void ParseLazyFunctionLiteralBody(bool* ok);
1536 bool CheckInOrOf(bool accept_OF);
1540 PreParserStatementList PreParser::ParseEagerFunctionBody(
1541 PreParserIdentifier function_name, int pos, Variable* fvar,
1542 Token::Value fvar_init_op, bool is_generator, bool* ok) {
1543 ParsingModeScope parsing_mode(this, PARSE_EAGERLY);
1545 ParseSourceElements(Token::RBRACE, ok);
1546 if (!*ok) return PreParserStatementList();
1548 Expect(Token::RBRACE, ok);
1549 return PreParserStatementList();
1553 PreParserStatementList PreParserTraits::ParseEagerFunctionBody(
1554 PreParserIdentifier function_name, int pos, Variable* fvar,
1555 Token::Value fvar_init_op, bool is_generator, bool* ok) {
1556 return pre_parser_->ParseEagerFunctionBody(function_name, pos, fvar,
1557 fvar_init_op, is_generator, ok);
1561 template <class Traits>
1562 ParserBase<Traits>::FunctionState::FunctionState(
1563 FunctionState** function_state_stack,
1564 typename Traits::Type::Scope** scope_stack,
1565 typename Traits::Type::Scope* scope, typename Traits::Type::Zone* zone,
1566 AstValueFactory* ast_value_factory, AstNode::IdGen* ast_node_id_gen)
1567 : next_materialized_literal_index_(JSFunction::kLiteralsPrefixSize),
1568 next_handler_index_(0),
1569 expected_property_count_(0),
1570 is_generator_(false),
1571 generator_object_variable_(NULL),
1572 function_state_stack_(function_state_stack),
1573 outer_function_state_(*function_state_stack),
1574 scope_stack_(scope_stack),
1575 outer_scope_(*scope_stack),
1576 ast_node_id_gen_(ast_node_id_gen),
1577 factory_(zone, ast_value_factory, ast_node_id_gen) {
1578 *scope_stack_ = scope;
1579 *function_state_stack = this;
1580 Traits::SetUpFunctionState(this);
1584 template <class Traits>
1585 ParserBase<Traits>::FunctionState::FunctionState(
1586 FunctionState** function_state_stack,
1587 typename Traits::Type::Scope** scope_stack,
1588 typename Traits::Type::Scope** scope, typename Traits::Type::Zone* zone,
1589 AstValueFactory* ast_value_factory, AstNode::IdGen* ast_node_id_gen)
1590 : next_materialized_literal_index_(JSFunction::kLiteralsPrefixSize),
1591 next_handler_index_(0),
1592 expected_property_count_(0),
1593 is_generator_(false),
1594 generator_object_variable_(NULL),
1595 function_state_stack_(function_state_stack),
1596 outer_function_state_(*function_state_stack),
1597 scope_stack_(scope_stack),
1598 outer_scope_(*scope_stack),
1599 ast_node_id_gen_(ast_node_id_gen),
1600 factory_(zone, ast_value_factory, ast_node_id_gen) {
1601 *scope_stack_ = *scope;
1602 *function_state_stack = this;
1603 Traits::SetUpFunctionState(this);
1607 template <class Traits>
1608 ParserBase<Traits>::FunctionState::~FunctionState() {
1609 *scope_stack_ = outer_scope_;
1610 *function_state_stack_ = outer_function_state_;
1611 Traits::TearDownFunctionState(this);
1615 template<class Traits>
1616 void ParserBase<Traits>::ReportUnexpectedToken(Token::Value token) {
1617 Scanner::Location source_location = scanner()->location();
1619 // Four of the tokens are treated specially
1622 return ReportMessageAt(source_location, "unexpected_eos");
1624 return ReportMessageAt(source_location, "unexpected_token_number");
1626 return ReportMessageAt(source_location, "unexpected_token_string");
1627 case Token::IDENTIFIER:
1628 return ReportMessageAt(source_location, "unexpected_token_identifier");
1629 case Token::FUTURE_RESERVED_WORD:
1630 return ReportMessageAt(source_location, "unexpected_reserved");
1633 case Token::FUTURE_STRICT_RESERVED_WORD:
1634 return ReportMessageAt(source_location, strict_mode() == SLOPPY
1635 ? "unexpected_token_identifier" : "unexpected_strict_reserved");
1637 const char* name = Token::String(token);
1638 DCHECK(name != NULL);
1639 Traits::ReportMessageAt(source_location, "unexpected_token", name);
1644 template<class Traits>
1645 typename ParserBase<Traits>::IdentifierT ParserBase<Traits>::ParseIdentifier(
1646 AllowEvalOrArgumentsAsIdentifier allow_eval_or_arguments,
1648 Token::Value next = Next();
1649 if (next == Token::IDENTIFIER) {
1650 IdentifierT name = this->GetSymbol(scanner());
1651 if (allow_eval_or_arguments == kDontAllowEvalOrArguments &&
1652 strict_mode() == STRICT && this->IsEvalOrArguments(name)) {
1653 ReportMessage("strict_eval_arguments");
1657 } else if (strict_mode() == SLOPPY &&
1658 (next == Token::FUTURE_STRICT_RESERVED_WORD ||
1659 (next == Token::LET) ||
1660 (next == Token::YIELD && !is_generator()))) {
1661 return this->GetSymbol(scanner());
1663 this->ReportUnexpectedToken(next);
1665 return Traits::EmptyIdentifier();
1670 template <class Traits>
1671 typename ParserBase<Traits>::IdentifierT ParserBase<
1672 Traits>::ParseIdentifierOrStrictReservedWord(bool* is_strict_reserved,
1674 Token::Value next = Next();
1675 if (next == Token::IDENTIFIER) {
1676 *is_strict_reserved = false;
1677 } else if (next == Token::FUTURE_STRICT_RESERVED_WORD ||
1678 next == Token::LET ||
1679 (next == Token::YIELD && !this->is_generator())) {
1680 *is_strict_reserved = true;
1682 ReportUnexpectedToken(next);
1684 return Traits::EmptyIdentifier();
1686 return this->GetSymbol(scanner());
1690 template <class Traits>
1691 typename ParserBase<Traits>::IdentifierT
1692 ParserBase<Traits>::ParseIdentifierName(bool* ok) {
1693 Token::Value next = Next();
1694 if (next != Token::IDENTIFIER && next != Token::FUTURE_RESERVED_WORD &&
1695 next != Token::LET && next != Token::YIELD &&
1696 next != Token::FUTURE_STRICT_RESERVED_WORD && !Token::IsKeyword(next)) {
1697 this->ReportUnexpectedToken(next);
1699 return Traits::EmptyIdentifier();
1701 return this->GetSymbol(scanner());
1705 template <class Traits>
1706 typename ParserBase<Traits>::IdentifierT
1707 ParserBase<Traits>::ParseIdentifierNameOrGetOrSet(bool* is_get,
1710 IdentifierT result = ParseIdentifierName(ok);
1711 if (!*ok) return Traits::EmptyIdentifier();
1712 scanner()->IsGetOrSet(is_get, is_set);
1717 template <class Traits>
1718 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseRegExpLiteral(
1719 bool seen_equal, bool* ok) {
1720 int pos = peek_position();
1721 if (!scanner()->ScanRegExpPattern(seen_equal)) {
1723 ReportMessage("unterminated_regexp");
1725 return Traits::EmptyExpression();
1728 int literal_index = function_state_->NextMaterializedLiteralIndex();
1730 IdentifierT js_pattern = this->GetNextSymbol(scanner());
1731 if (!scanner()->ScanRegExpFlags()) {
1733 ReportMessage("invalid_regexp_flags");
1735 return Traits::EmptyExpression();
1737 IdentifierT js_flags = this->GetNextSymbol(scanner());
1739 return factory()->NewRegExpLiteral(js_pattern, js_flags, literal_index, pos);
1743 #define CHECK_OK ok); \
1744 if (!*ok) return this->EmptyExpression(); \
1746 #define DUMMY ) // to make indentation work
1749 // Used in functions where the return type is not ExpressionT.
1750 #define CHECK_OK_CUSTOM(x) ok); \
1751 if (!*ok) return this->x(); \
1753 #define DUMMY ) // to make indentation work
1756 template <class Traits>
1757 typename ParserBase<Traits>::ExpressionT
1758 ParserBase<Traits>::ParsePrimaryExpression(bool* ok) {
1759 // PrimaryExpression ::
1771 // '(' Expression ')'
1773 int pos = peek_position();
1774 ExpressionT result = this->EmptyExpression();
1775 Token::Value token = peek();
1778 Consume(Token::THIS);
1779 result = this->ThisExpression(scope_, factory());
1783 case Token::NULL_LITERAL:
1784 case Token::TRUE_LITERAL:
1785 case Token::FALSE_LITERAL:
1788 result = this->ExpressionFromLiteral(token, pos, scanner(), factory());
1791 case Token::IDENTIFIER:
1794 case Token::FUTURE_STRICT_RESERVED_WORD: {
1795 // Using eval or arguments in this context is OK even in strict mode.
1796 IdentifierT name = ParseIdentifier(kAllowEvalOrArguments, CHECK_OK);
1797 result = this->ExpressionFromIdentifier(name, pos, scope_, factory());
1801 case Token::STRING: {
1802 Consume(Token::STRING);
1803 result = this->ExpressionFromString(pos, scanner(), factory());
1807 case Token::ASSIGN_DIV:
1808 result = this->ParseRegExpLiteral(true, CHECK_OK);
1812 result = this->ParseRegExpLiteral(false, CHECK_OK);
1816 result = this->ParseArrayLiteral(CHECK_OK);
1820 result = this->ParseObjectLiteral(CHECK_OK);
1824 Consume(Token::LPAREN);
1825 if (allow_arrow_functions() && peek() == Token::RPAREN) {
1826 // Arrow functions are the only expression type constructions
1827 // for which an empty parameter list "()" is valid input.
1828 Consume(Token::RPAREN);
1829 result = this->ParseArrowFunctionLiteral(
1830 pos, this->EmptyArrowParamList(), CHECK_OK);
1832 // Heuristically try to detect immediately called functions before
1833 // seeing the call parentheses.
1834 parenthesized_function_ = (peek() == Token::FUNCTION);
1835 result = this->ParseExpression(true, CHECK_OK);
1836 result->increase_parenthesization_level();
1837 Expect(Token::RPAREN, CHECK_OK);
1841 case Token::CLASS: {
1842 Consume(Token::CLASS);
1843 int class_token_position = position();
1844 IdentifierT name = this->EmptyIdentifier();
1845 bool is_strict_reserved_name = false;
1846 Scanner::Location class_name_location = Scanner::Location::invalid();
1847 if (peek_any_identifier()) {
1848 name = ParseIdentifierOrStrictReservedWord(&is_strict_reserved_name,
1850 class_name_location = scanner()->location();
1852 result = this->ParseClassLiteral(name, class_name_location,
1853 is_strict_reserved_name,
1854 class_token_position, CHECK_OK);
1859 if (allow_natives_syntax() || extension_ != NULL) {
1860 result = this->ParseV8Intrinsic(CHECK_OK);
1863 // If we're not allowing special syntax we fall-through to the
1868 ReportUnexpectedToken(token);
1877 template <class Traits>
1878 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseExpression(
1879 bool accept_IN, bool* ok) {
1881 // AssignmentExpression
1882 // Expression ',' AssignmentExpression
1884 ExpressionT result = this->ParseAssignmentExpression(accept_IN, CHECK_OK);
1885 while (peek() == Token::COMMA) {
1886 Expect(Token::COMMA, CHECK_OK);
1887 int pos = position();
1888 ExpressionT right = this->ParseAssignmentExpression(accept_IN, CHECK_OK);
1889 result = factory()->NewBinaryOperation(Token::COMMA, result, right, pos);
1895 template <class Traits>
1896 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseArrayLiteral(
1899 // '[' Expression? (',' Expression?)* ']'
1901 int pos = peek_position();
1902 typename Traits::Type::ExpressionList values =
1903 this->NewExpressionList(4, zone_);
1904 Expect(Token::LBRACK, CHECK_OK);
1905 while (peek() != Token::RBRACK) {
1906 ExpressionT elem = this->EmptyExpression();
1907 if (peek() == Token::COMMA) {
1908 elem = this->GetLiteralTheHole(peek_position(), factory());
1910 elem = this->ParseAssignmentExpression(true, CHECK_OK);
1912 values->Add(elem, zone_);
1913 if (peek() != Token::RBRACK) {
1914 Expect(Token::COMMA, CHECK_OK);
1917 Expect(Token::RBRACK, CHECK_OK);
1919 // Update the scope information before the pre-parsing bailout.
1920 int literal_index = function_state_->NextMaterializedLiteralIndex();
1922 return factory()->NewArrayLiteral(values, literal_index, pos);
1926 template <class Traits>
1927 typename ParserBase<Traits>::IdentifierT ParserBase<Traits>::ParsePropertyName(
1928 bool* is_get, bool* is_set, bool* is_static, bool* ok) {
1929 Token::Value next = peek();
1932 Consume(Token::STRING);
1933 return this->GetSymbol(scanner_);
1935 Consume(Token::NUMBER);
1936 return this->GetNumberAsSymbol(scanner_);
1941 return ParseIdentifierNameOrGetOrSet(is_get, is_set, ok);
1944 return this->EmptyIdentifier();
1948 template <class Traits>
1949 typename ParserBase<Traits>::ObjectLiteralPropertyT ParserBase<
1950 Traits>::ParsePropertyDefinition(ObjectLiteralChecker* checker,
1951 bool in_class, bool is_static, bool* ok) {
1952 ExpressionT value = this->EmptyExpression();
1953 bool is_get = false;
1954 bool is_set = false;
1955 bool name_is_static = false;
1956 bool is_generator = allow_harmony_object_literals_ && Check(Token::MUL);
1958 Token::Value name_token = peek();
1959 int next_pos = peek_position();
1961 ParsePropertyName(&is_get, &is_set, &name_is_static,
1962 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
1964 if (fni_ != NULL) this->PushLiteralName(fni_, name);
1966 if (!in_class && !is_generator && peek() == Token::COLON) {
1967 // PropertyDefinition : PropertyName ':' AssignmentExpression
1968 checker->CheckProperty(name_token, kValueProperty,
1969 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
1970 Consume(Token::COLON);
1971 value = this->ParseAssignmentExpression(
1972 true, CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
1974 } else if (is_generator ||
1975 (allow_harmony_object_literals_ && peek() == Token::LPAREN)) {
1978 if (is_static && this->IsPrototype(name)) {
1979 ReportMessageAt(scanner()->location(), "static_prototype");
1981 return this->EmptyObjectLiteralProperty();
1983 if (is_generator && in_class && !is_static && this->IsConstructor(name)) {
1984 ReportMessageAt(scanner()->location(), "constructor_special_method");
1986 return this->EmptyObjectLiteralProperty();
1989 checker->CheckProperty(name_token, kValueProperty,
1990 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
1991 FunctionKind kind = is_generator ? FunctionKind::kConciseGeneratorMethod
1992 : FunctionKind::kConciseMethod;
1994 value = this->ParseFunctionLiteral(
1995 name, scanner()->location(),
1996 false, // reserved words are allowed here
1997 kind, RelocInfo::kNoPosition, FunctionLiteral::ANONYMOUS_EXPRESSION,
1998 FunctionLiteral::NORMAL_ARITY,
1999 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
2001 } else if (in_class && name_is_static && !is_static) {
2002 // static MethodDefinition
2003 return ParsePropertyDefinition(checker, true, true, ok);
2005 } else if (is_get || is_set) {
2007 bool dont_care = false;
2008 name_token = peek();
2009 name = ParsePropertyName(&dont_care, &dont_care, &dont_care,
2010 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
2012 // Validate the property.
2013 if (is_static && this->IsPrototype(name)) {
2014 ReportMessageAt(scanner()->location(), "static_prototype");
2016 return this->EmptyObjectLiteralProperty();
2017 } else if (in_class && !is_static && this->IsConstructor(name)) {
2018 // ES6, spec draft rev 27, treats static get constructor as an error too.
2019 // https://bugs.ecmascript.org/show_bug.cgi?id=3223
2020 // TODO(arv): Update when bug is resolved.
2021 ReportMessageAt(scanner()->location(), "constructor_special_method");
2023 return this->EmptyObjectLiteralProperty();
2025 checker->CheckProperty(name_token,
2026 is_get ? kGetterProperty : kSetterProperty,
2027 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
2029 typename Traits::Type::FunctionLiteral value = this->ParseFunctionLiteral(
2030 name, scanner()->location(),
2031 false, // reserved words are allowed here
2032 FunctionKind::kNormalFunction, RelocInfo::kNoPosition,
2033 FunctionLiteral::ANONYMOUS_EXPRESSION,
2034 is_get ? FunctionLiteral::GETTER_ARITY : FunctionLiteral::SETTER_ARITY,
2035 CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
2036 return factory()->NewObjectLiteralProperty(is_get, value, next_pos,
2039 Token::Value next = Next();
2040 ReportUnexpectedToken(next);
2042 return this->EmptyObjectLiteralProperty();
2046 LiteralT key = this->IsArrayIndex(name, &index)
2047 ? factory()->NewNumberLiteral(index, next_pos)
2048 : factory()->NewStringLiteral(name, next_pos);
2050 return factory()->NewObjectLiteralProperty(key, value, is_static);
2054 template <class Traits>
2055 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseObjectLiteral(
2058 // '{' (PropertyDefinition (',' PropertyDefinition)* ','? )? '}'
2060 int pos = peek_position();
2061 typename Traits::Type::PropertyList properties =
2062 this->NewPropertyList(4, zone_);
2063 int number_of_boilerplate_properties = 0;
2064 bool has_function = false;
2066 ObjectLiteralChecker checker(this, strict_mode());
2068 Expect(Token::LBRACE, CHECK_OK);
2070 while (peek() != Token::RBRACE) {
2071 if (fni_ != NULL) fni_->Enter();
2073 const bool in_class = false;
2074 const bool is_static = false;
2075 ObjectLiteralPropertyT property =
2076 this->ParsePropertyDefinition(&checker, in_class, is_static, CHECK_OK);
2078 // Mark top-level object literals that contain function literals and
2079 // pretenure the literal so it can be added as a constant function
2080 // property. (Parser only.)
2081 this->CheckFunctionLiteralInsideTopLevelObjectLiteral(scope_, property,
2084 // Count CONSTANT or COMPUTED properties to maintain the enumeration order.
2085 if (this->IsBoilerplateProperty(property)) {
2086 number_of_boilerplate_properties++;
2088 properties->Add(property, zone());
2090 if (peek() != Token::RBRACE) {
2091 // Need {} because of the CHECK_OK macro.
2092 Expect(Token::COMMA, CHECK_OK);
2100 Expect(Token::RBRACE, CHECK_OK);
2102 // Computation of literal_index must happen before pre parse bailout.
2103 int literal_index = function_state_->NextMaterializedLiteralIndex();
2105 return factory()->NewObjectLiteral(properties,
2107 number_of_boilerplate_properties,
2113 template <class Traits>
2114 typename Traits::Type::ExpressionList ParserBase<Traits>::ParseArguments(
2117 // '(' (AssignmentExpression)*[','] ')'
2119 typename Traits::Type::ExpressionList result =
2120 this->NewExpressionList(4, zone_);
2121 Expect(Token::LPAREN, CHECK_OK_CUSTOM(NullExpressionList));
2122 bool done = (peek() == Token::RPAREN);
2124 ExpressionT argument = this->ParseAssignmentExpression(
2125 true, CHECK_OK_CUSTOM(NullExpressionList));
2126 result->Add(argument, zone_);
2127 if (result->length() > Code::kMaxArguments) {
2128 ReportMessage("too_many_arguments");
2130 return this->NullExpressionList();
2132 done = (peek() == Token::RPAREN);
2134 // Need {} because of the CHECK_OK_CUSTOM macro.
2135 Expect(Token::COMMA, CHECK_OK_CUSTOM(NullExpressionList));
2138 Expect(Token::RPAREN, CHECK_OK_CUSTOM(NullExpressionList));
2143 template <class Traits>
2144 typename ParserBase<Traits>::ExpressionT
2145 ParserBase<Traits>::ParseAssignmentExpression(bool accept_IN, bool* ok) {
2146 // AssignmentExpression ::
2147 // ConditionalExpression
2150 // LeftHandSideExpression AssignmentOperator AssignmentExpression
2152 Scanner::Location lhs_location = scanner()->peek_location();
2154 if (peek() == Token::YIELD && is_generator()) {
2155 return this->ParseYieldExpression(ok);
2158 if (fni_ != NULL) fni_->Enter();
2159 typename Traits::Checkpoint checkpoint(this);
2160 ExpressionT expression =
2161 this->ParseConditionalExpression(accept_IN, CHECK_OK);
2163 if (allow_arrow_functions() && peek() == Token::ARROW) {
2164 checkpoint.Restore();
2165 expression = this->ParseArrowFunctionLiteral(lhs_location.beg_pos,
2166 expression, CHECK_OK);
2170 if (!Token::IsAssignmentOp(peek())) {
2171 if (fni_ != NULL) fni_->Leave();
2172 // Parsed conditional expression only (no assignment).
2176 expression = this->CheckAndRewriteReferenceExpression(
2177 expression, lhs_location, "invalid_lhs_in_assignment", CHECK_OK);
2178 expression = this->MarkExpressionAsAssigned(expression);
2180 Token::Value op = Next(); // Get assignment operator.
2181 int pos = position();
2182 ExpressionT right = this->ParseAssignmentExpression(accept_IN, CHECK_OK);
2184 // TODO(1231235): We try to estimate the set of properties set by
2185 // constructors. We define a new property whenever there is an
2186 // assignment to a property of 'this'. We should probably only add
2187 // properties if we haven't seen them before. Otherwise we'll
2188 // probably overestimate the number of properties.
2189 if (op == Token::ASSIGN && this->IsThisProperty(expression)) {
2190 function_state_->AddProperty();
2193 this->CheckAssigningFunctionLiteralToProperty(expression, right);
2196 // Check if the right hand side is a call to avoid inferring a
2197 // name if we're dealing with "a = function(){...}();"-like
2199 if ((op == Token::INIT_VAR
2200 || op == Token::INIT_CONST_LEGACY
2201 || op == Token::ASSIGN)
2202 && (!right->IsCall() && !right->IsCallNew())) {
2205 fni_->RemoveLastFunction();
2210 return factory()->NewAssignment(op, expression, right, pos);
2213 template <class Traits>
2214 typename ParserBase<Traits>::ExpressionT
2215 ParserBase<Traits>::ParseYieldExpression(bool* ok) {
2216 // YieldExpression ::
2217 // 'yield' ([no line terminator] '*'? AssignmentExpression)?
2218 int pos = peek_position();
2219 Expect(Token::YIELD, CHECK_OK);
2220 ExpressionT generator_object =
2221 factory()->NewVariableProxy(function_state_->generator_object_variable());
2222 ExpressionT expression = Traits::EmptyExpression();
2223 Yield::Kind kind = Yield::kSuspend;
2224 if (!scanner()->HasAnyLineTerminatorBeforeNext()) {
2225 if (Check(Token::MUL)) kind = Yield::kDelegating;
2228 case Token::SEMICOLON:
2234 // The above set of tokens is the complete set of tokens that can appear
2235 // after an AssignmentExpression, and none of them can start an
2236 // AssignmentExpression. This allows us to avoid looking for an RHS for
2237 // a Yield::kSuspend operation, given only one look-ahead token.
2238 if (kind == Yield::kSuspend)
2240 DCHECK_EQ(Yield::kDelegating, kind);
2241 // Delegating yields require an RHS; fall through.
2243 expression = ParseAssignmentExpression(false, CHECK_OK);
2247 if (kind == Yield::kDelegating) {
2248 // var iterator = subject[Symbol.iterator]();
2249 expression = this->GetIterator(expression, factory());
2251 typename Traits::Type::YieldExpression yield =
2252 factory()->NewYield(generator_object, expression, kind, pos);
2253 if (kind == Yield::kDelegating) {
2254 yield->set_index(function_state_->NextHandlerIndex());
2261 template <class Traits>
2262 typename ParserBase<Traits>::ExpressionT
2263 ParserBase<Traits>::ParseConditionalExpression(bool accept_IN, bool* ok) {
2264 // ConditionalExpression ::
2265 // LogicalOrExpression
2266 // LogicalOrExpression '?' AssignmentExpression ':' AssignmentExpression
2268 int pos = peek_position();
2269 // We start using the binary expression parser for prec >= 4 only!
2270 ExpressionT expression = this->ParseBinaryExpression(4, accept_IN, CHECK_OK);
2271 if (peek() != Token::CONDITIONAL) return expression;
2272 Consume(Token::CONDITIONAL);
2273 // In parsing the first assignment expression in conditional
2274 // expressions we always accept the 'in' keyword; see ECMA-262,
2275 // section 11.12, page 58.
2276 ExpressionT left = ParseAssignmentExpression(true, CHECK_OK);
2277 Expect(Token::COLON, CHECK_OK);
2278 ExpressionT right = ParseAssignmentExpression(accept_IN, CHECK_OK);
2279 return factory()->NewConditional(expression, left, right, pos);
2284 template <class Traits>
2285 typename ParserBase<Traits>::ExpressionT
2286 ParserBase<Traits>::ParseBinaryExpression(int prec, bool accept_IN, bool* ok) {
2288 ExpressionT x = this->ParseUnaryExpression(CHECK_OK);
2289 for (int prec1 = Precedence(peek(), accept_IN); prec1 >= prec; prec1--) {
2291 while (Precedence(peek(), accept_IN) == prec1) {
2292 Token::Value op = Next();
2293 int pos = position();
2294 ExpressionT y = ParseBinaryExpression(prec1 + 1, accept_IN, CHECK_OK);
2296 if (this->ShortcutNumericLiteralBinaryExpression(&x, y, op, pos,
2301 // For now we distinguish between comparisons and other binary
2302 // operations. (We could combine the two and get rid of this
2303 // code and AST node eventually.)
2304 if (Token::IsCompareOp(op)) {
2305 // We have a comparison.
2306 Token::Value cmp = op;
2308 case Token::NE: cmp = Token::EQ; break;
2309 case Token::NE_STRICT: cmp = Token::EQ_STRICT; break;
2312 x = factory()->NewCompareOperation(cmp, x, y, pos);
2314 // The comparison was negated - add a NOT.
2315 x = factory()->NewUnaryOperation(Token::NOT, x, pos);
2319 // We have a "normal" binary operation.
2320 x = factory()->NewBinaryOperation(op, x, y, pos);
2328 template <class Traits>
2329 typename ParserBase<Traits>::ExpressionT
2330 ParserBase<Traits>::ParseUnaryExpression(bool* ok) {
2331 // UnaryExpression ::
2332 // PostfixExpression
2333 // 'delete' UnaryExpression
2334 // 'void' UnaryExpression
2335 // 'typeof' UnaryExpression
2336 // '++' UnaryExpression
2337 // '--' UnaryExpression
2338 // '+' UnaryExpression
2339 // '-' UnaryExpression
2340 // '~' UnaryExpression
2341 // '!' UnaryExpression
2343 Token::Value op = peek();
2344 if (Token::IsUnaryOp(op)) {
2346 int pos = position();
2347 ExpressionT expression = ParseUnaryExpression(CHECK_OK);
2349 // "delete identifier" is a syntax error in strict mode.
2350 if (op == Token::DELETE && strict_mode() == STRICT &&
2351 this->IsIdentifier(expression)) {
2352 ReportMessage("strict_delete");
2354 return this->EmptyExpression();
2357 // Allow Traits do rewrite the expression.
2358 return this->BuildUnaryExpression(expression, op, pos, factory());
2359 } else if (Token::IsCountOp(op)) {
2361 Scanner::Location lhs_location = scanner()->peek_location();
2362 ExpressionT expression = this->ParseUnaryExpression(CHECK_OK);
2363 expression = this->CheckAndRewriteReferenceExpression(
2364 expression, lhs_location, "invalid_lhs_in_prefix_op", CHECK_OK);
2365 this->MarkExpressionAsAssigned(expression);
2367 return factory()->NewCountOperation(op,
2373 return this->ParsePostfixExpression(ok);
2378 template <class Traits>
2379 typename ParserBase<Traits>::ExpressionT
2380 ParserBase<Traits>::ParsePostfixExpression(bool* ok) {
2381 // PostfixExpression ::
2382 // LeftHandSideExpression ('++' | '--')?
2384 Scanner::Location lhs_location = scanner()->peek_location();
2385 ExpressionT expression = this->ParseLeftHandSideExpression(CHECK_OK);
2386 if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
2387 Token::IsCountOp(peek())) {
2388 expression = this->CheckAndRewriteReferenceExpression(
2389 expression, lhs_location, "invalid_lhs_in_postfix_op", CHECK_OK);
2390 expression = this->MarkExpressionAsAssigned(expression);
2392 Token::Value next = Next();
2394 factory()->NewCountOperation(next,
2395 false /* postfix */,
2403 template <class Traits>
2404 typename ParserBase<Traits>::ExpressionT
2405 ParserBase<Traits>::ParseLeftHandSideExpression(bool* ok) {
2406 // LeftHandSideExpression ::
2407 // (NewExpression | MemberExpression) ...
2409 ExpressionT result = this->ParseMemberWithNewPrefixesExpression(CHECK_OK);
2413 case Token::LBRACK: {
2414 Consume(Token::LBRACK);
2415 int pos = position();
2416 ExpressionT index = ParseExpression(true, CHECK_OK);
2417 result = factory()->NewProperty(result, index, pos);
2418 Expect(Token::RBRACK, CHECK_OK);
2422 case Token::LPAREN: {
2424 if (scanner()->current_token() == Token::IDENTIFIER) {
2425 // For call of an identifier we want to report position of
2426 // the identifier as position of the call in the stack trace.
2429 // For other kinds of calls we record position of the parenthesis as
2430 // position of the call. Note that this is extremely important for
2431 // expressions of the form function(){...}() for which call position
2432 // should not point to the closing brace otherwise it will intersect
2433 // with positions recorded for function literal and confuse debugger.
2434 pos = peek_position();
2435 // Also the trailing parenthesis are a hint that the function will
2436 // be called immediately. If we happen to have parsed a preceding
2437 // function literal eagerly, we can also compile it eagerly.
2438 if (result->IsFunctionLiteral() && mode() == PARSE_EAGERLY) {
2439 result->AsFunctionLiteral()->set_parenthesized();
2442 typename Traits::Type::ExpressionList args = ParseArguments(CHECK_OK);
2444 if (this->BuildSIMD128LoadStoreExpression(
2445 &result, args, pos, factory()))
2448 // Keep track of eval() calls since they disable all local variable
2450 // The calls that need special treatment are the
2451 // direct eval calls. These calls are all of the form eval(...), with
2452 // no explicit receiver.
2453 // These calls are marked as potentially direct eval calls. Whether
2454 // they are actually direct calls to eval is determined at run time.
2455 this->CheckPossibleEvalCall(result, scope_);
2456 result = factory()->NewCall(result, args, pos);
2457 if (fni_ != NULL) fni_->RemoveLastFunction();
2461 case Token::PERIOD: {
2462 Consume(Token::PERIOD);
2463 int pos = position();
2464 IdentifierT name = ParseIdentifierName(CHECK_OK);
2465 result = factory()->NewProperty(
2466 result, factory()->NewStringLiteral(name, pos), pos);
2467 if (fni_ != NULL) this->PushLiteralName(fni_, name);
2478 template <class Traits>
2479 typename ParserBase<Traits>::ExpressionT
2480 ParserBase<Traits>::ParseMemberWithNewPrefixesExpression(bool* ok) {
2482 // ('new')+ MemberExpression
2484 // The grammar for new expressions is pretty warped. We can have several 'new'
2485 // keywords following each other, and then a MemberExpression. When we see '('
2486 // after the MemberExpression, it's associated with the rightmost unassociated
2487 // 'new' to create a NewExpression with arguments. However, a NewExpression
2488 // can also occur without arguments.
2490 // Examples of new expression:
2491 // new foo.bar().baz means (new (foo.bar)()).baz
2492 // new foo()() means (new foo())()
2493 // new new foo()() means (new (new foo())())
2494 // new new foo means new (new foo)
2495 // new new foo() means new (new foo())
2496 // new new foo().bar().baz means (new (new foo()).bar()).baz
2498 if (peek() == Token::NEW) {
2499 Consume(Token::NEW);
2500 int new_pos = position();
2501 ExpressionT result = this->EmptyExpression();
2502 if (Check(Token::SUPER)) {
2503 result = this->SuperReference(scope_, factory());
2505 result = this->ParseMemberWithNewPrefixesExpression(CHECK_OK);
2507 if (peek() == Token::LPAREN) {
2508 // NewExpression with arguments.
2509 typename Traits::Type::ExpressionList args =
2510 this->ParseArguments(CHECK_OK);
2511 result = factory()->NewCallNew(result, args, new_pos);
2512 // The expression can still continue with . or [ after the arguments.
2513 result = this->ParseMemberExpressionContinuation(result, CHECK_OK);
2516 // NewExpression without arguments.
2517 return factory()->NewCallNew(result, this->NewExpressionList(0, zone_),
2520 // No 'new' or 'super' keyword.
2521 return this->ParseMemberExpression(ok);
2525 template <class Traits>
2526 typename ParserBase<Traits>::ExpressionT
2527 ParserBase<Traits>::ParseMemberExpression(bool* ok) {
2528 // MemberExpression ::
2529 // (PrimaryExpression | FunctionLiteral | ClassLiteral)
2530 // ('[' Expression ']' | '.' Identifier | Arguments)*
2532 // The '[' Expression ']' and '.' Identifier parts are parsed by
2533 // ParseMemberExpressionContinuation, and the Arguments part is parsed by the
2536 // Parse the initial primary or function expression.
2537 ExpressionT result = this->EmptyExpression();
2538 if (peek() == Token::FUNCTION) {
2539 Consume(Token::FUNCTION);
2540 int function_token_position = position();
2541 bool is_generator = Check(Token::MUL);
2542 IdentifierT name = this->EmptyIdentifier();
2543 bool is_strict_reserved_name = false;
2544 Scanner::Location function_name_location = Scanner::Location::invalid();
2545 FunctionLiteral::FunctionType function_type =
2546 FunctionLiteral::ANONYMOUS_EXPRESSION;
2547 if (peek_any_identifier()) {
2548 name = ParseIdentifierOrStrictReservedWord(&is_strict_reserved_name,
2550 function_name_location = scanner()->location();
2551 function_type = FunctionLiteral::NAMED_EXPRESSION;
2553 result = this->ParseFunctionLiteral(
2554 name, function_name_location, is_strict_reserved_name,
2555 is_generator ? FunctionKind::kGeneratorFunction
2556 : FunctionKind::kNormalFunction,
2557 function_token_position, function_type, FunctionLiteral::NORMAL_ARITY,
2559 } else if (peek() == Token::SUPER) {
2560 int beg_pos = position();
2561 Consume(Token::SUPER);
2562 Token::Value next = peek();
2563 if (next == Token::PERIOD || next == Token::LBRACK ||
2564 next == Token::LPAREN) {
2565 result = this->SuperReference(scope_, factory());
2567 ReportMessageAt(Scanner::Location(beg_pos, position()),
2568 "unexpected_super");
2570 return this->EmptyExpression();
2573 result = ParsePrimaryExpression(CHECK_OK);
2576 result = ParseMemberExpressionContinuation(result, CHECK_OK);
2581 template <class Traits>
2582 typename ParserBase<Traits>::ExpressionT
2583 ParserBase<Traits>::ParseMemberExpressionContinuation(ExpressionT expression,
2585 // Parses this part of MemberExpression:
2586 // ('[' Expression ']' | '.' Identifier)*
2589 case Token::LBRACK: {
2590 Consume(Token::LBRACK);
2591 int pos = position();
2592 ExpressionT index = this->ParseExpression(true, CHECK_OK);
2593 expression = factory()->NewProperty(expression, index, pos);
2595 this->PushPropertyName(fni_, index);
2597 Expect(Token::RBRACK, CHECK_OK);
2600 case Token::PERIOD: {
2601 Consume(Token::PERIOD);
2602 int pos = position();
2603 IdentifierT name = ParseIdentifierName(CHECK_OK);
2604 expression = factory()->NewProperty(
2605 expression, factory()->NewStringLiteral(name, pos), pos);
2607 this->PushLiteralName(fni_, name);
2616 return this->EmptyExpression();
2620 template <class Traits>
2621 typename ParserBase<Traits>::ExpressionT ParserBase<
2622 Traits>::ParseArrowFunctionLiteral(int start_pos, ExpressionT params_ast,
2624 // TODO(aperez): Change this to use ARROW_SCOPE
2625 typename Traits::Type::ScopePtr scope =
2626 this->NewScope(scope_, FUNCTION_SCOPE);
2627 typename Traits::Type::StatementList body;
2628 typename Traits::Type::AstProperties ast_properties;
2629 BailoutReason dont_optimize_reason = kNoReason;
2630 int num_parameters = -1;
2631 int materialized_literal_count = -1;
2632 int expected_property_count = -1;
2633 int handler_count = 0;
2636 FunctionState function_state(&function_state_, &scope_, &scope, zone(),
2637 this->ast_value_factory(), ast_node_id_gen_);
2638 Scanner::Location dupe_error_loc = Scanner::Location::invalid();
2639 num_parameters = Traits::DeclareArrowParametersFromExpression(
2640 params_ast, scope_, &dupe_error_loc, ok);
2643 Scanner::Location(start_pos, scanner()->location().beg_pos),
2644 "malformed_arrow_function_parameter_list");
2645 return this->EmptyExpression();
2648 if (num_parameters > Code::kMaxArguments) {
2649 ReportMessageAt(Scanner::Location(params_ast->position(), position()),
2650 "too_many_parameters");
2652 return this->EmptyExpression();
2655 Expect(Token::ARROW, CHECK_OK);
2657 if (peek() == Token::LBRACE) {
2658 // Multiple statemente body
2659 Consume(Token::LBRACE);
2660 bool is_lazily_parsed =
2661 (mode() == PARSE_LAZILY && scope_->AllowsLazyCompilation());
2662 if (is_lazily_parsed) {
2663 body = this->NewStatementList(0, zone());
2664 this->SkipLazyFunctionBody(this->EmptyIdentifier(),
2665 &materialized_literal_count,
2666 &expected_property_count, CHECK_OK);
2668 body = this->ParseEagerFunctionBody(
2669 this->EmptyIdentifier(), RelocInfo::kNoPosition, NULL,
2670 Token::INIT_VAR, false, // Not a generator.
2672 materialized_literal_count =
2673 function_state.materialized_literal_count();
2674 expected_property_count = function_state.expected_property_count();
2675 handler_count = function_state.handler_count();
2678 // Single-expression body
2679 int pos = position();
2680 parenthesized_function_ = false;
2681 ExpressionT expression = ParseAssignmentExpression(true, CHECK_OK);
2682 body = this->NewStatementList(1, zone());
2683 body->Add(factory()->NewReturnStatement(expression, pos), zone());
2684 materialized_literal_count = function_state.materialized_literal_count();
2685 expected_property_count = function_state.expected_property_count();
2686 handler_count = function_state.handler_count();
2689 scope->set_start_position(start_pos);
2690 scope->set_end_position(scanner()->location().end_pos);
2692 // Arrow function *parameter lists* are always checked as in strict mode.
2693 bool function_name_is_strict_reserved = false;
2694 Scanner::Location function_name_loc = Scanner::Location::invalid();
2695 Scanner::Location eval_args_error_loc = Scanner::Location::invalid();
2696 Scanner::Location reserved_loc = Scanner::Location::invalid();
2697 this->CheckStrictFunctionNameAndParameters(
2698 this->EmptyIdentifier(), function_name_is_strict_reserved,
2699 function_name_loc, eval_args_error_loc, dupe_error_loc, reserved_loc,
2702 // Validate strict mode.
2703 if (strict_mode() == STRICT) {
2704 CheckOctalLiteral(start_pos, scanner()->location().end_pos, CHECK_OK);
2707 if (allow_harmony_scoping() && strict_mode() == STRICT)
2708 this->CheckConflictingVarDeclarations(scope, CHECK_OK);
2710 ast_properties = *factory()->visitor()->ast_properties();
2711 dont_optimize_reason = factory()->visitor()->dont_optimize_reason();
2714 FunctionLiteralT function_literal = factory()->NewFunctionLiteral(
2715 this->EmptyIdentifierString(), this->ast_value_factory(), scope, body,
2716 materialized_literal_count, expected_property_count, handler_count,
2717 num_parameters, FunctionLiteral::kNoDuplicateParameters,
2718 FunctionLiteral::ANONYMOUS_EXPRESSION, FunctionLiteral::kIsFunction,
2719 FunctionLiteral::kNotParenthesized, FunctionKind::kArrowFunction,
2722 function_literal->set_function_token_position(start_pos);
2723 function_literal->set_ast_properties(&ast_properties);
2724 function_literal->set_dont_optimize_reason(dont_optimize_reason);
2726 if (fni_ != NULL) this->InferFunctionName(fni_, function_literal);
2728 return function_literal;
2732 template <class Traits>
2733 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseClassLiteral(
2734 IdentifierT name, Scanner::Location class_name_location,
2735 bool name_is_strict_reserved, int pos, bool* ok) {
2736 // All parts of a ClassDeclaration or a ClassExpression are strict code.
2737 if (name_is_strict_reserved) {
2738 ReportMessageAt(class_name_location, "unexpected_strict_reserved");
2740 return this->EmptyExpression();
2742 if (this->IsEvalOrArguments(name)) {
2743 ReportMessageAt(class_name_location, "strict_eval_arguments");
2745 return this->EmptyExpression();
2748 // TODO(arv): Implement scopes and name binding in class body only.
2749 // TODO(arv): Maybe add CLASS_SCOPE?
2750 typename Traits::Type::ScopePtr extends_scope =
2751 this->NewScope(scope_, BLOCK_SCOPE);
2752 FunctionState extends_function_state(
2753 &function_state_, &scope_, &extends_scope, zone(),
2754 this->ast_value_factory(), ast_node_id_gen_);
2755 scope_->SetStrictMode(STRICT);
2756 scope_->SetScopeName(name);
2758 ExpressionT extends = this->EmptyExpression();
2759 if (Check(Token::EXTENDS)) {
2760 extends = this->ParseLeftHandSideExpression(CHECK_OK);
2763 ObjectLiteralChecker checker(this, STRICT);
2764 typename Traits::Type::PropertyList properties =
2765 this->NewPropertyList(4, zone_);
2766 FunctionLiteralT constructor = this->EmptyFunctionLiteral();
2768 Expect(Token::LBRACE, CHECK_OK);
2769 while (peek() != Token::RBRACE) {
2770 if (Check(Token::SEMICOLON)) continue;
2771 if (fni_ != NULL) fni_->Enter();
2773 const bool in_class = true;
2774 const bool is_static = false;
2775 ObjectLiteralPropertyT property =
2776 this->ParsePropertyDefinition(&checker, in_class, is_static, CHECK_OK);
2778 properties->Add(property, zone());
2785 Expect(Token::RBRACE, CHECK_OK);
2787 return this->ClassLiteral(name, extends, constructor, properties, pos,
2792 template <typename Traits>
2793 typename ParserBase<Traits>::ExpressionT
2794 ParserBase<Traits>::CheckAndRewriteReferenceExpression(
2795 ExpressionT expression,
2796 Scanner::Location location, const char* message, bool* ok) {
2797 if (strict_mode() == STRICT && this->IsIdentifier(expression) &&
2798 this->IsEvalOrArguments(this->AsIdentifier(expression))) {
2799 this->ReportMessageAt(location, "strict_eval_arguments", false);
2801 return this->EmptyExpression();
2802 } else if (expression->IsValidReferenceExpression()) {
2804 } else if (expression->IsCall()) {
2805 // If it is a call, make it a runtime error for legacy web compatibility.
2806 // Rewrite `expr' to `expr[throw ReferenceError]'.
2807 int pos = location.beg_pos;
2808 ExpressionT error = this->NewThrowReferenceError(message, pos);
2809 return factory()->NewProperty(expression, error, pos);
2811 this->ReportMessageAt(location, message, true);
2813 return this->EmptyExpression();
2819 #undef CHECK_OK_CUSTOM
2822 template <typename Traits>
2823 void ParserBase<Traits>::ObjectLiteralChecker::CheckProperty(
2824 Token::Value property, PropertyKind type, bool* ok) {
2826 if (property == Token::NUMBER) {
2827 old = scanner()->FindNumber(&finder_, type);
2829 old = scanner()->FindSymbol(&finder_, type);
2831 PropertyKind old_type = static_cast<PropertyKind>(old);
2832 if (HasConflict(old_type, type)) {
2833 if (IsDataDataConflict(old_type, type)) {
2834 // Both are data properties.
2835 if (strict_mode_ == SLOPPY) return;
2836 parser()->ReportMessage("strict_duplicate_property");
2837 } else if (IsDataAccessorConflict(old_type, type)) {
2838 // Both a data and an accessor property with the same name.
2839 parser()->ReportMessage("accessor_data_property");
2841 DCHECK(IsAccessorAccessorConflict(old_type, type));
2842 // Both accessors of the same type.
2843 parser()->ReportMessage("accessor_get_set");
2850 #endif // V8_PREPARSER_H