Upstream version 11.39.258.0
[platform/framework/web/crosswalk.git] / src / v8 / src / preparser.h
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_PREPARSER_H
6 #define V8_PREPARSER_H
7
8 #include "src/v8.h"
9
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"
16
17 namespace v8 {
18 namespace internal {
19
20 // Common base class shared between parser and pre-parser. Traits encapsulate
21 // the differences between Parser and PreParser:
22
23 // - Return types: For example, Parser functions return Expression* and
24 // PreParser functions return PreParserExpression.
25
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
32 // used.
33
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.
37
38 // The traits are expected to contain the following typedefs:
39 // struct Traits {
40 //   // In particular...
41 //   struct Type {
42 //     // Used by FunctionState and BlockState.
43 //     typedef Scope;
44 //     typedef GeneratorVariable;
45 //     typedef Zone;
46 //     // Return types for traversing functions.
47 //     typedef Identifier;
48 //     typedef Expression;
49 //     typedef FunctionLiteral;
50 //     typedef ClassLiteral;
51 //     typedef ObjectLiteralProperty;
52 //     typedef Literal;
53 //     typedef ExpressionList;
54 //     typedef PropertyList;
55 //     // For constructing objects returned by the traversing functions.
56 //     typedef Factory;
57 //   };
58 //   // ...
59 // };
60
61 template <typename Traits>
62 class ParserBase : public Traits {
63  public:
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;
70
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),
77         scope_(NULL),
78         function_state_(NULL),
79         extension_(extension),
80         fni_(NULL),
81         log_(log),
82         mode_(PARSE_EAGERLY),  // Lazy mode must be set explicitly.
83         stack_limit_(stack_limit),
84         scanner_(scanner),
85         stack_overflow_(false),
86         allow_lazy_(false),
87         allow_natives_syntax_(false),
88         allow_arrow_functions_(false),
89         allow_harmony_object_literals_(false),
90         zone_(zone),
91         ast_node_id_gen_(ast_node_id_gen) {}
92
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();
102   }
103   bool allow_classes() const { return scanner()->HarmonyClasses(); }
104   bool allow_harmony_object_literals() const {
105     return allow_harmony_object_literals_;
106   }
107
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);
116   }
117   void set_allow_harmony_numeric_literals(bool allow) {
118     scanner()->SetHarmonyNumericLiterals(allow);
119   }
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;
123   }
124
125  protected:
126   friend class Traits::Checkpoint;
127
128   enum AllowEvalOrArgumentsAsIdentifier {
129     kAllowEvalOrArguments,
130     kDontAllowEvalOrArguments
131   };
132
133   enum Mode {
134     PARSE_LAZILY,
135     PARSE_EAGERLY
136   };
137
138   class CheckpointBase;
139   class ObjectLiteralChecker;
140
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 {
147    public:
148     BlockState(typename Traits::Type::Scope** scope_stack,
149                typename Traits::Type::Scope* scope)
150         : scope_stack_(scope_stack),
151           outer_scope_(*scope_stack),
152           scope_(scope) {
153       *scope_stack_ = scope_;
154     }
155     ~BlockState() { *scope_stack_ = outer_scope_; }
156
157    private:
158     typename Traits::Type::Scope** scope_stack_;
159     typename Traits::Type::Scope* outer_scope_;
160     typename Traits::Type::Scope* scope_;
161   };
162
163   class FunctionState BASE_EMBEDDED {
164    public:
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);
177     ~FunctionState();
178
179     int NextMaterializedLiteralIndex() {
180       return next_materialized_literal_index_++;
181     }
182     int materialized_literal_count() {
183       return next_materialized_literal_index_ - JSFunction::kLiteralsPrefixSize;
184     }
185
186     int NextHandlerIndex() { return next_handler_index_++; }
187     int handler_count() { return next_handler_index_; }
188
189     void AddProperty() { expected_property_count_++; }
190     int expected_property_count() { return expected_property_count_; }
191
192     void set_is_generator(bool is_generator) { is_generator_ = is_generator; }
193     bool is_generator() const { return is_generator_; }
194
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;
201     }
202     typename Traits::Type::GeneratorVariable* generator_object_variable()
203         const {
204       return generator_object_variable_;
205     }
206
207     typename Traits::Type::Factory* factory() { return &factory_; }
208
209    private:
210     // Used to assign an index to each literal that needs materialization in
211     // the function.  Includes regexp literals, and boilerplate for object and
212     // array literals.
213     int next_materialized_literal_index_;
214
215     // Used to assign a per-function index to try and catch handlers.
216     int next_handler_index_;
217
218     // Properties count estimation.
219     int expected_property_count_;
220
221     // Whether the function is a generator.
222     bool is_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_;
227
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_;
236
237     friend class ParserTraits;
238     friend class CheckpointBase;
239   };
240
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 {
246    public:
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_;
253     }
254
255     void Restore() {
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_;
260     }
261
262    private:
263     FunctionState* function_state_;
264     int next_materialized_literal_index_;
265     int next_handler_index_;
266     int expected_property_count_;
267   };
268
269   class ParsingModeScope BASE_EMBEDDED {
270    public:
271     ParsingModeScope(ParserBase* parser, Mode mode)
272         : parser_(parser),
273           old_mode_(parser->mode()) {
274       parser_->mode_ = mode;
275     }
276     ~ParsingModeScope() {
277       parser_->mode_ = old_mode_;
278     }
279
280    private:
281     ParserBase* parser_;
282     Mode old_mode_;
283   };
284
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_; }
293
294   INLINE(Token::Value peek()) {
295     if (stack_overflow_) return Token::ILLEGAL;
296     return scanner()->peek();
297   }
298
299   INLINE(Token::Value Next()) {
300     if (stack_overflow_) return Token::ILLEGAL;
301     {
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;
307       }
308     }
309     return scanner()->Next();
310   }
311
312   void Consume(Token::Value token) {
313     Token::Value next = Next();
314     USE(next);
315     USE(token);
316     DCHECK(next == token);
317   }
318
319   bool Check(Token::Value token) {
320     Token::Value next = peek();
321     if (next == token) {
322       Consume(next);
323       return true;
324     }
325     return false;
326   }
327
328   void Expect(Token::Value token, bool* ok) {
329     Token::Value next = Next();
330     if (next != token) {
331       ReportUnexpectedToken(next);
332       *ok = false;
333     }
334   }
335
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) {
341       Next();
342       return;
343     }
344     if (scanner()->HasAnyLineTerminatorBeforeNext() ||
345         tok == Token::RBRACE ||
346         tok == Token::EOS) {
347       return;
348     }
349     Expect(Token::SEMICOLON, ok);
350   }
351
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;
359   }
360
361   bool CheckContextualKeyword(Vector<const char> keyword) {
362     if (peek() == Token::IDENTIFIER &&
363         scanner()->is_next_contextual_keyword(keyword)) {
364       Consume(Token::IDENTIFIER);
365       return true;
366     }
367     return false;
368   }
369
370   void ExpectContextualKeyword(Vector<const char> keyword, bool* ok) {
371     Expect(Token::IDENTIFIER, ok);
372     if (!*ok) return;
373     if (!scanner()->is_literal_contextual_keyword(keyword)) {
374       ReportUnexpectedToken(scanner()->current_token());
375       *ok = false;
376     }
377   }
378
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();
387       *ok = false;
388     }
389   }
390
391   // Validates strict mode for function parameter lists. This has to be
392   // done after parsing the function, since the function can declare
393   // itself strict.
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,
401       bool* ok) {
402     if (this->IsEvalOrArguments(function_name)) {
403       Traits::ReportMessageAt(function_name_loc, "strict_eval_arguments");
404       *ok = false;
405       return;
406     }
407     if (function_name_is_strict_reserved) {
408       Traits::ReportMessageAt(function_name_loc, "unexpected_strict_reserved");
409       *ok = false;
410       return;
411     }
412     if (eval_args_error_loc.IsValid()) {
413       Traits::ReportMessageAt(eval_args_error_loc, "strict_eval_arguments");
414       *ok = false;
415       return;
416     }
417     if (dupe_error_loc.IsValid()) {
418       Traits::ReportMessageAt(dupe_error_loc, "strict_param_dupe");
419       *ok = false;
420       return;
421     }
422     if (reserved_loc.IsValid()) {
423       Traits::ReportMessageAt(reserved_loc, "unexpected_strict_reserved");
424       *ok = false;
425       return;
426     }
427   }
428
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);
434   }
435
436   typename Traits::Type::Factory* factory() {
437     return function_state_->factory();
438   }
439
440   StrictMode strict_mode() { return scope_->strict_mode(); }
441   bool is_generator() const { return function_state_->is_generator(); }
442
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);
448   }
449
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),
454                             is_reference_error);
455   }
456
457   void ReportUnexpectedToken(Token::Value token);
458
459   // Recursive descent functions:
460
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,
468       bool* ok);
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,
473       bool* ok);
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,
477                                             bool* is_set,
478                                             bool* ok);
479
480   ExpressionT ParseRegExpLiteral(bool seen_equal, bool* ok);
481
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,
486                                 bool* ok);
487   ExpressionT ParseObjectLiteral(bool* ok);
488   ObjectLiteralPropertyT ParsePropertyDefinition(ObjectLiteralChecker* checker,
489                                                  bool in_class, bool is_static,
490                                                  bool* ok);
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,
502                                                 bool* ok);
503   ExpressionT ParseArrowFunctionLiteral(int start_pos, ExpressionT params_ast,
504                                         bool* ok);
505   ExpressionT ParseClassLiteral(IdentifierT name,
506                                 Scanner::Location function_name_location,
507                                 bool name_is_strict_reserved, int pos,
508                                 bool* ok);
509
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);
516
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.
528   enum PropertyKind {
529     kNone = 0,
530     // Bit patterns representing different object literal property types.
531     kGetterProperty = 1,
532     kSetterProperty = 2,
533     kValueProperty = 7,
534     // Helper constants.
535     kValueFlag = 4
536   };
537
538   // Validation per ECMA 262 - 11.1.5 "Object Initializer".
539   class ObjectLiteralChecker {
540    public:
541     ObjectLiteralChecker(ParserBase* parser, StrictMode strict_mode)
542         : parser_(parser),
543           finder_(scanner()->unicode_cache()),
544           strict_mode_(strict_mode) {}
545
546     void CheckProperty(Token::Value property, PropertyKind type, bool* ok);
547
548    private:
549     ParserBase* parser() const { return parser_; }
550     Scanner* scanner() const { return parser_->scanner(); }
551
552     // Checks the type of conflict based on values coming from PropertyType.
553     bool HasConflict(PropertyKind type1, PropertyKind type2) {
554       return (type1 & type2) != 0;
555     }
556     bool IsDataDataConflict(PropertyKind type1, PropertyKind type2) {
557       return ((type1 & type2) & kValueFlag) != 0;
558     }
559     bool IsDataAccessorConflict(PropertyKind type1, PropertyKind type2) {
560       return ((type1 ^ type2) & kValueFlag) != 0;
561     }
562     bool IsAccessorAccessorConflict(PropertyKind type1, PropertyKind type2) {
563       return ((type1 | type2) & kValueFlag) == 0;
564     }
565
566     ParserBase* parser_;
567     DuplicateFinder finder_;
568     StrictMode strict_mode_;
569   };
570
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_;
576
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_;
582   Mode mode_;
583   uintptr_t stack_limit_;
584
585  private:
586   Scanner* scanner_;
587   bool stack_overflow_;
588
589   bool allow_lazy_;
590   bool allow_natives_syntax_;
591   bool allow_arrow_functions_;
592   bool allow_harmony_object_literals_;
593
594   typename Traits::Type::Zone* zone_;  // Only used by Parser.
595   AstNode::IdGen* ast_node_id_gen_;
596 };
597
598
599 class PreParserIdentifier {
600  public:
601   PreParserIdentifier() : type_(kUnknownIdentifier) {}
602   static PreParserIdentifier Default() {
603     return PreParserIdentifier(kUnknownIdentifier);
604   }
605   static PreParserIdentifier Eval() {
606     return PreParserIdentifier(kEvalIdentifier);
607   }
608   static PreParserIdentifier Arguments() {
609     return PreParserIdentifier(kArgumentsIdentifier);
610   }
611   static PreParserIdentifier FutureReserved() {
612     return PreParserIdentifier(kFutureReservedIdentifier);
613   }
614   static PreParserIdentifier FutureStrictReserved() {
615     return PreParserIdentifier(kFutureStrictReservedIdentifier);
616   }
617   static PreParserIdentifier Let() {
618     return PreParserIdentifier(kLetIdentifier);
619   }
620   static PreParserIdentifier Yield() {
621     return PreParserIdentifier(kYieldIdentifier);
622   }
623   static PreParserIdentifier Prototype() {
624     return PreParserIdentifier(kPrototypeIdentifier);
625   }
626   static PreParserIdentifier Constructor() {
627     return PreParserIdentifier(kConstructorIdentifier);
628   }
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;
636   }
637   bool IsFutureReserved() const { return type_ == kFutureReservedIdentifier; }
638   bool IsFutureStrictReserved() const {
639     return type_ == kFutureStrictReservedIdentifier;
640   }
641   bool IsValidStrictVariable() const { return type_ == kUnknownIdentifier; }
642
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; }
647
648   int position() const { return 0; }
649   int length() const { return 0; }
650
651  private:
652   enum Type {
653     kUnknownIdentifier,
654     kFutureReservedIdentifier,
655     kFutureStrictReservedIdentifier,
656     kLetIdentifier,
657     kYieldIdentifier,
658     kEvalIdentifier,
659     kArgumentsIdentifier,
660     kPrototypeIdentifier,
661     kConstructorIdentifier
662   };
663   explicit PreParserIdentifier(Type type) : type_(type) {}
664   Type type_;
665
666   friend class PreParserExpression;
667   friend class PreParserScope;
668 };
669
670
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
675 // use yet.
676 class PreParserExpression {
677  public:
678   static PreParserExpression Default() {
679     return PreParserExpression(kUnknownExpression);
680   }
681
682   static PreParserExpression FromIdentifier(PreParserIdentifier id) {
683     return PreParserExpression(kTypeIdentifier |
684                                (id.type_ << kIdentifierShift));
685   }
686
687   static PreParserExpression BinaryOperation(PreParserExpression left,
688                                              Token::Value op,
689                                              PreParserExpression right) {
690     int code = ((op == Token::COMMA) && !left.is_parenthesized() &&
691                 !right.is_parenthesized())
692                    ? left.ArrowParamListBit() & right.ArrowParamListBit()
693                    : 0;
694     return PreParserExpression(kTypeBinaryOperation | code);
695   }
696
697   static PreParserExpression EmptyArrowParamList() {
698     // Any expression for which IsValidArrowParamList() returns true
699     // will work here.
700     return FromIdentifier(PreParserIdentifier::Default());
701   }
702
703   static PreParserExpression StringLiteral() {
704     return PreParserExpression(kUnknownStringLiteral);
705   }
706
707   static PreParserExpression UseStrictStringLiteral() {
708     return PreParserExpression(kUseStrictString);
709   }
710
711   static PreParserExpression This() {
712     return PreParserExpression(kThisExpression);
713   }
714
715   static PreParserExpression Super() {
716     return PreParserExpression(kSuperExpression);
717   }
718
719   static PreParserExpression ThisProperty() {
720     return PreParserExpression(kThisPropertyExpression);
721   }
722
723   static PreParserExpression Property() {
724     return PreParserExpression(kPropertyExpression);
725   }
726
727   static PreParserExpression Call() {
728     return PreParserExpression(kCallExpression);
729   }
730
731   bool IsIdentifier() const { return (code_ & kTypeMask) == kTypeIdentifier; }
732
733   PreParserIdentifier AsIdentifier() const {
734     DCHECK(IsIdentifier());
735     return PreParserIdentifier(
736         static_cast<PreParserIdentifier::Type>(code_ >> kIdentifierShift));
737   }
738
739   bool IsStringLiteral() const {
740     return (code_ & kTypeMask) == kTypeStringLiteral;
741   }
742
743   bool IsUseStrictLiteral() const {
744     return (code_ & kUseStrictString) == kUseStrictString;
745   }
746
747   bool IsThis() const { return (code_ & kThisExpression) == kThisExpression; }
748
749   bool IsThisProperty() const {
750     return (code_ & kThisPropertyExpression) == kThisPropertyExpression;
751   }
752
753   bool IsProperty() const {
754     return (code_ & kPropertyExpression) == kPropertyExpression ||
755            (code_ & kThisPropertyExpression) == kThisPropertyExpression;
756   }
757
758   bool IsCall() const { return (code_ & kCallExpression) == kCallExpression; }
759
760   bool IsValidReferenceExpression() const {
761     return IsIdentifier() || IsProperty();
762   }
763
764   bool IsValidArrowParamList() const {
765     return (ArrowParamListBit() & kBinaryOperationArrowParamList) != 0 &&
766            (code_ & kMultiParenthesizedExpression) == 0;
767   }
768
769   // At the moment PreParser doesn't track these expression types.
770   bool IsFunctionLiteral() const { return false; }
771   bool IsCallNew() const { return false; }
772
773   PreParserExpression AsFunctionLiteral() { return *this; }
774
775   bool IsBinaryOperation() const {
776     return (code_ & kTypeMask) == kTypeBinaryOperation;
777   }
778
779   bool is_parenthesized() const {
780     return (code_ & kParenthesizedExpression) != 0;
781   }
782
783   void increase_parenthesization_level() {
784     code_ |= is_parenthesized() ? kMultiParenthesizedExpression
785                                 : kParenthesizedExpression;
786   }
787
788   // Dummy implementation for making expression->somefunc() work in both Parser
789   // and PreParser.
790   PreParserExpression* operator->() { return this; }
791
792   // More dummy implementations of things PreParser doesn't need to track:
793   void set_index(int index) {}  // For YieldExpressions
794   void set_parenthesized() {}
795
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) {}
800
801   bool operator==(const PreParserExpression& other) const {
802     return code_ == other.code_;
803   }
804   bool operator!=(const PreParserExpression& other) const {
805     return code_ != other.code_;
806   }
807
808  private:
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.
815   enum {
816     kUnknownExpression = 0,
817     kTypeMask = 1 | 2,
818     kParenthesizedExpression = (1 << 2),
819     kMultiParenthesizedExpression = (1 << 3),
820
821     // Identifiers
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,
828
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),
834
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)
842   };
843
844   explicit PreParserExpression(int expression_code) : code_(expression_code) {}
845
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())
854         return 0;
855       return kBinaryOperationArrowParamList;
856     }
857     return 0;
858   }
859
860   int code_;
861 };
862
863
864 // PreParserExpressionList doesn't actually store the expressions because
865 // PreParser doesn't need to.
866 class PreParserExpressionList {
867  public:
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_; }
873  private:
874   int length_;
875 };
876
877
878 class PreParserStatement {
879  public:
880   static PreParserStatement Default() {
881     return PreParserStatement(kUnknownStatement);
882   }
883
884   static PreParserStatement FunctionDeclaration() {
885     return PreParserStatement(kFunctionDeclaration);
886   }
887
888   // Creates expression statement from expression.
889   // Preserves being an unparenthesized string literal, possibly
890   // "use strict".
891   static PreParserStatement ExpressionStatement(
892       PreParserExpression expression) {
893     if (expression.IsUseStrictLiteral()) {
894       return PreParserStatement(kUseStrictExpressionStatement);
895     }
896     if (expression.IsStringLiteral()) {
897       return PreParserStatement(kStringLiteralExpressionStatement);
898     }
899     return Default();
900   }
901
902   bool IsStringLiteral() {
903     return code_ == kStringLiteralExpressionStatement;
904   }
905
906   bool IsUseStrictLiteral() {
907     return code_ == kUseStrictExpressionStatement;
908   }
909
910   bool IsFunctionDeclaration() {
911     return code_ == kFunctionDeclaration;
912   }
913
914  private:
915   enum Type {
916     kUnknownStatement,
917     kStringLiteralExpressionStatement,
918     kUseStrictExpressionStatement,
919     kFunctionDeclaration
920   };
921
922   explicit PreParserStatement(Type code) : code_(code) {}
923   Type code_;
924 };
925
926
927
928 // PreParserStatementList doesn't actually store the statements because
929 // the PreParser does not need them.
930 class PreParserStatementList {
931  public:
932   // These functions make list->Add(some_expression) work as no-ops.
933   PreParserStatementList() {}
934   PreParserStatementList* operator->() { return this; }
935   void Add(PreParserStatement, void*) {}
936 };
937
938
939 class PreParserScope {
940  public:
941   explicit PreParserScope(PreParserScope* outer_scope, ScopeType scope_type,
942                           void* = NULL)
943       : scope_type_(scope_type) {
944     strict_mode_ = outer_scope ? outer_scope->strict_mode() : SLOPPY;
945   }
946
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) {}
951
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; }
955
956   void set_start_position(int position) {}
957   void set_end_position(int position) {}
958
959   bool IsDeclared(const PreParserIdentifier& identifier) const { return false; }
960   void DeclareParameter(const PreParserIdentifier& identifier, VariableMode) {}
961
962   // Allow scope->Foo() to work.
963   PreParserScope* operator->() { return this; }
964
965  private:
966   ScopeType scope_type_;
967   StrictMode strict_mode_;
968 };
969
970
971 class PreParserFactory {
972  public:
973   PreParserFactory(void*, void*, void*) {}
974   PreParserExpression NewStringLiteral(PreParserIdentifier identifier,
975                                        int pos) {
976     return PreParserExpression::Default();
977   }
978   PreParserExpression NewNumberLiteral(double number,
979                                        int pos) {
980     return PreParserExpression::Default();
981   }
982   PreParserExpression NewRegExpLiteral(PreParserIdentifier js_pattern,
983                                        PreParserIdentifier js_flags,
984                                        int literal_index,
985                                        int pos) {
986     return PreParserExpression::Default();
987   }
988   PreParserExpression NewArrayLiteral(PreParserExpressionList values,
989                                       int literal_index,
990                                       int pos) {
991     return PreParserExpression::Default();
992   }
993   PreParserExpression NewObjectLiteralProperty(bool is_getter,
994                                                PreParserExpression value,
995                                                int pos, bool is_static) {
996     return PreParserExpression::Default();
997   }
998   PreParserExpression NewObjectLiteralProperty(PreParserExpression key,
999                                                PreParserExpression value,
1000                                                bool is_static) {
1001     return PreParserExpression::Default();
1002   }
1003   PreParserExpression NewObjectLiteral(PreParserExpressionList properties,
1004                                        int literal_index,
1005                                        int boilerplate_properties,
1006                                        bool has_function,
1007                                        int pos) {
1008     return PreParserExpression::Default();
1009   }
1010   PreParserExpression NewVariableProxy(void* variable) {
1011     return PreParserExpression::Default();
1012   }
1013   PreParserExpression NewProperty(PreParserExpression obj,
1014                                   PreParserExpression key,
1015                                   int pos) {
1016     if (obj.IsThis()) {
1017       return PreParserExpression::ThisProperty();
1018     }
1019     return PreParserExpression::Property();
1020   }
1021   PreParserExpression NewUnaryOperation(Token::Value op,
1022                                         PreParserExpression expression,
1023                                         int pos) {
1024     return PreParserExpression::Default();
1025   }
1026   PreParserExpression NewBinaryOperation(Token::Value op,
1027                                          PreParserExpression left,
1028                                          PreParserExpression right, int pos) {
1029     return PreParserExpression::BinaryOperation(left, op, right);
1030   }
1031   PreParserExpression NewCompareOperation(Token::Value op,
1032                                           PreParserExpression left,
1033                                           PreParserExpression right, int pos) {
1034     return PreParserExpression::Default();
1035   }
1036   PreParserExpression NewAssignment(Token::Value op,
1037                                     PreParserExpression left,
1038                                     PreParserExpression right,
1039                                     int pos) {
1040     return PreParserExpression::Default();
1041   }
1042   PreParserExpression NewYield(PreParserExpression generator_object,
1043                                PreParserExpression expression,
1044                                Yield::Kind yield_kind,
1045                                int pos) {
1046     return PreParserExpression::Default();
1047   }
1048   PreParserExpression NewConditional(PreParserExpression condition,
1049                                      PreParserExpression then_expression,
1050                                      PreParserExpression else_expression,
1051                                      int pos) {
1052     return PreParserExpression::Default();
1053   }
1054   PreParserExpression NewCountOperation(Token::Value op,
1055                                         bool is_prefix,
1056                                         PreParserExpression expression,
1057                                         int pos) {
1058     return PreParserExpression::Default();
1059   }
1060   PreParserExpression NewCall(PreParserExpression expression,
1061                               PreParserExpressionList arguments,
1062                               int pos) {
1063     return PreParserExpression::Call();
1064   }
1065   PreParserExpression NewCallNew(PreParserExpression expression,
1066                                  PreParserExpressionList arguments,
1067                                  int pos) {
1068     return PreParserExpression::Default();
1069   }
1070   PreParserStatement NewReturnStatement(PreParserExpression expression,
1071                                         int pos) {
1072     return PreParserStatement::Default();
1073   }
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,
1083       int position) {
1084     return PreParserExpression::Default();
1085   }
1086   PreParserExpression NewClassLiteral(PreParserIdentifier name,
1087                                       PreParserExpression extends,
1088                                       PreParserExpression constructor,
1089                                       PreParserExpressionList properties,
1090                                       int position) {
1091     return PreParserExpression::Default();
1092   }
1093
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;
1100     return &dummy;
1101   }
1102 };
1103
1104
1105 class PreParser;
1106
1107 class PreParserTraits {
1108  public:
1109   struct Type {
1110     // TODO(marja): To be removed. The Traits object should contain all the data
1111     // it needs.
1112     typedef PreParser* Parser;
1113
1114     // Used by FunctionState and BlockState.
1115     typedef PreParserScope Scope;
1116     typedef PreParserScope ScopePtr;
1117
1118     // PreParser doesn't need to store generator variables.
1119     typedef void GeneratorVariable;
1120     // No interaction with Zones.
1121     typedef void Zone;
1122
1123     typedef int AstProperties;
1124     typedef Vector<PreParserIdentifier> ParameterIdentifierVector;
1125
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;
1137
1138     // For constructing objects returned by the traversing functions.
1139     typedef PreParserFactory Factory;
1140   };
1141
1142   class Checkpoint;
1143
1144   explicit PreParserTraits(PreParser* pre_parser) : pre_parser_(pre_parser) {}
1145
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) {}
1152
1153   // Helper functions for recursive descent.
1154   static bool IsEvalOrArguments(PreParserIdentifier identifier) {
1155     return identifier.IsEvalOrArguments();
1156   }
1157
1158   static bool IsPrototype(PreParserIdentifier identifier) {
1159     return identifier.IsPrototype();
1160   }
1161
1162   static bool IsConstructor(PreParserIdentifier identifier) {
1163     return identifier.IsConstructor();
1164   }
1165
1166   // Returns true if the expression is of type "this.foo".
1167   static bool IsThisProperty(PreParserExpression expression) {
1168     return expression.IsThisProperty();
1169   }
1170
1171   static bool IsIdentifier(PreParserExpression expression) {
1172     return expression.IsIdentifier();
1173   }
1174
1175   static PreParserIdentifier AsIdentifier(PreParserExpression expression) {
1176     return expression.AsIdentifier();
1177   }
1178
1179   static bool IsFutureStrictReserved(PreParserIdentifier identifier) {
1180     return identifier.IsYield() || identifier.IsFutureStrictReserved();
1181   }
1182
1183   static bool IsBoilerplateProperty(PreParserExpression property) {
1184     // PreParser doesn't count boilerplate properties.
1185     return false;
1186   }
1187
1188   static bool IsArrayIndex(PreParserIdentifier string, uint32_t* index) {
1189     return false;
1190   }
1191
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.
1196     UNREACHABLE();
1197   }
1198   static void PushPropertyName(FuncNameInferrer* fni,
1199                                PreParserExpression expression) {
1200     // PreParser should not use FuncNameInferrer.
1201     UNREACHABLE();
1202   }
1203   static void InferFunctionName(FuncNameInferrer* fni,
1204                                 PreParserExpression expression) {
1205     // PreParser should not use FuncNameInferrer.
1206     UNREACHABLE();
1207   }
1208
1209   static void CheckFunctionLiteralInsideTopLevelObjectLiteral(
1210       PreParserScope* scope, PreParserExpression property, bool* has_function) {
1211   }
1212
1213   static void CheckAssigningFunctionLiteralToProperty(
1214       PreParserExpression left, PreParserExpression right) {}
1215
1216   // PreParser doesn't need to keep track of eval calls.
1217   static void CheckPossibleEvalCall(PreParserExpression expression,
1218                                     PreParserScope* scope) {}
1219
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.
1224     return expression;
1225   }
1226
1227   bool ShortcutNumericLiteralBinaryExpression(PreParserExpression* x,
1228                                               PreParserExpression y,
1229                                               Token::Value op,
1230                                               int pos,
1231                                               PreParserFactory* factory) {
1232     return false;
1233   }
1234
1235   bool BuildSIMD128LoadStoreExpression(
1236       PreParserExpression* expression,
1237       PreParserExpressionList arguments,
1238       int pos,
1239       PreParserFactory* factory) {
1240     return false;
1241   }
1242
1243   PreParserExpression BuildUnaryExpression(PreParserExpression expression,
1244                                            Token::Value op, int pos,
1245                                            PreParserFactory* factory) {
1246     return PreParserExpression::Default();
1247   }
1248
1249   PreParserExpression NewThrowReferenceError(const char* type, int pos) {
1250     return PreParserExpression::Default();
1251   }
1252   PreParserExpression NewThrowSyntaxError(
1253       const char* type, Handle<Object> arg, int pos) {
1254     return PreParserExpression::Default();
1255   }
1256   PreParserExpression NewThrowTypeError(
1257       const char* type, Handle<Object> arg, int pos) {
1258     return PreParserExpression::Default();
1259   }
1260   PreParserScope NewScope(PreParserScope* outer_scope, ScopeType scope_type) {
1261     return PreParserScope(outer_scope, scope_type);
1262   }
1263
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,
1270                        int end_pos,
1271                        const char* message,
1272                        const char* arg = NULL,
1273                        bool is_reference_error = false);
1274
1275   // "null" return type creators.
1276   static PreParserIdentifier EmptyIdentifier() {
1277     return PreParserIdentifier::Default();
1278   }
1279   static PreParserIdentifier EmptyIdentifierString() {
1280     return PreParserIdentifier::Default();
1281   }
1282   static PreParserExpression EmptyExpression() {
1283     return PreParserExpression::Default();
1284   }
1285   static PreParserExpression EmptyArrowParamList() {
1286     return PreParserExpression::EmptyArrowParamList();
1287   }
1288   static PreParserExpression EmptyLiteral() {
1289     return PreParserExpression::Default();
1290   }
1291   static PreParserExpression EmptyObjectLiteralProperty() {
1292     return PreParserExpression::Default();
1293   }
1294   static PreParserExpression EmptyFunctionLiteral() {
1295     return PreParserExpression::Default();
1296   }
1297   static PreParserExpressionList NullExpressionList() {
1298     return PreParserExpressionList();
1299   }
1300
1301   // Odd-ball literal creators.
1302   static PreParserExpression GetLiteralTheHole(int position,
1303                                                PreParserFactory* factory) {
1304     return PreParserExpression::Default();
1305   }
1306
1307   // Producing data during the recursive descent.
1308   PreParserIdentifier GetSymbol(Scanner* scanner);
1309   PreParserIdentifier GetNumberAsSymbol(Scanner* scanner);
1310
1311   static PreParserIdentifier GetNextSymbol(Scanner* scanner) {
1312     return PreParserIdentifier::Default();
1313   }
1314
1315   static PreParserExpression ThisExpression(PreParserScope* scope,
1316                                             PreParserFactory* factory) {
1317     return PreParserExpression::This();
1318   }
1319
1320   static PreParserExpression SuperReference(PreParserScope* scope,
1321                                             PreParserFactory* factory) {
1322     return PreParserExpression::Super();
1323   }
1324
1325   static PreParserExpression ClassLiteral(PreParserIdentifier name,
1326                                           PreParserExpression extends,
1327                                           PreParserExpression constructor,
1328                                           PreParserExpressionList properties,
1329                                           int position,
1330                                           PreParserFactory* factory) {
1331     return PreParserExpression::Default();
1332   }
1333
1334   static PreParserExpression ExpressionFromLiteral(
1335       Token::Value token, int pos, Scanner* scanner,
1336       PreParserFactory* factory) {
1337     return PreParserExpression::Default();
1338   }
1339
1340   static PreParserExpression ExpressionFromIdentifier(
1341       PreParserIdentifier name, int pos, PreParserScope* scope,
1342       PreParserFactory* factory) {
1343     return PreParserExpression::FromIdentifier(name);
1344   }
1345
1346   PreParserExpression ExpressionFromString(int pos,
1347                                            Scanner* scanner,
1348                                            PreParserFactory* factory = NULL);
1349
1350   PreParserExpression GetIterator(PreParserExpression iterable,
1351                                   PreParserFactory* factory) {
1352     return PreParserExpression::Default();
1353   }
1354
1355   static PreParserExpressionList NewExpressionList(int size, void* zone) {
1356     return PreParserExpressionList();
1357   }
1358
1359   static PreParserStatementList NewStatementList(int size, void* zone) {
1360     return PreParserStatementList();
1361   }
1362
1363   static PreParserExpressionList NewPropertyList(int size, void* zone) {
1364     return PreParserExpressionList();
1365   }
1366
1367   V8_INLINE void SkipLazyFunctionBody(PreParserIdentifier function_name,
1368                                       int* materialized_literal_count,
1369                                       int* expected_property_count, bool* ok) {
1370     UNREACHABLE();
1371   }
1372
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);
1377
1378   // Utility functions
1379   int DeclareArrowParametersFromExpression(PreParserExpression expression,
1380                                            PreParserScope* scope,
1381                                            Scanner::Location* dupe_loc,
1382                                            bool* ok) {
1383     // TODO(aperez): Detect duplicated identifiers in paramlists.
1384     *ok = expression.IsValidArrowParamList();
1385     return 0;
1386   }
1387
1388   static AstValueFactory* ast_value_factory() { return NULL; }
1389
1390   void CheckConflictingVarDeclarations(PreParserScope scope, bool* ok) {}
1391
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);
1399
1400  private:
1401   PreParser* pre_parser_;
1402 };
1403
1404
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.
1408
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> {
1418  public:
1419   typedef PreParserIdentifier Identifier;
1420   typedef PreParserExpression Expression;
1421   typedef PreParserStatement Statement;
1422
1423   enum PreParseResult {
1424     kPreParseStackOverflow,
1425     kPreParseSuccess
1426   };
1427
1428   PreParser(Scanner* scanner, ParserRecorder* log, uintptr_t stack_limit)
1429       : ParserBase<PreParserTraits>(scanner, stack_limit, NULL, log, NULL, NULL,
1430                                     this) {}
1431
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
1435   // during parsing.
1436   PreParseResult PreParseProgram() {
1437     PreParserScope scope(scope_, GLOBAL_SCOPE);
1438     FunctionState top_scope(&function_state_, &scope_, &scope);
1439     bool ok = true;
1440     int start_position = scanner()->peek_location().beg_pos;
1441     ParseSourceElements(Token::EOS, &ok);
1442     if (stack_overflow()) return kPreParseStackOverflow;
1443     if (!ok) {
1444       ReportUnexpectedToken(scanner()->current_token());
1445     } else if (scope_->strict_mode() == STRICT) {
1446       CheckOctalLiteral(start_position, scanner()->location().end_pos, &ok);
1447     }
1448     return kPreParseSuccess;
1449   }
1450
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
1458   // the final '}'.
1459   PreParseResult PreParseLazyFunction(StrictMode strict_mode,
1460                                       bool is_generator,
1461                                       ParserRecorder* log);
1462
1463  private:
1464   friend class PreParserTraits;
1465
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.
1470
1471   enum VariableDeclarationContext {
1472     kSourceElement,
1473     kStatement,
1474     kForStatement
1475   };
1476
1477   // If a list of variable declarations includes any initializers.
1478   enum VariableDeclarationProperties {
1479     kHasInitializers,
1480     kHasNoInitializers
1481   };
1482
1483
1484   enum SourceElements {
1485     kUnknownSourceElements
1486   };
1487
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,
1499                                    bool* ok);
1500   Statement ParseVariableDeclarations(VariableDeclarationContext var_context,
1501                                       VariableDeclarationProperties* decl_props,
1502                                       int* num_decl,
1503                                       bool* ok);
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);
1520
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);
1528
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);
1535
1536   bool CheckInOrOf(bool accept_OF);
1537 };
1538
1539
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);
1544
1545   ParseSourceElements(Token::RBRACE, ok);
1546   if (!*ok) return PreParserStatementList();
1547
1548   Expect(Token::RBRACE, ok);
1549   return PreParserStatementList();
1550 }
1551
1552
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);
1558 }
1559
1560
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);
1581 }
1582
1583
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);
1604 }
1605
1606
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);
1612 }
1613
1614
1615 template<class Traits>
1616 void ParserBase<Traits>::ReportUnexpectedToken(Token::Value token) {
1617   Scanner::Location source_location = scanner()->location();
1618
1619   // Four of the tokens are treated specially
1620   switch (token) {
1621     case Token::EOS:
1622       return ReportMessageAt(source_location, "unexpected_eos");
1623     case Token::NUMBER:
1624       return ReportMessageAt(source_location, "unexpected_token_number");
1625     case Token::STRING:
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");
1631     case Token::LET:
1632     case Token::YIELD:
1633     case Token::FUTURE_STRICT_RESERVED_WORD:
1634       return ReportMessageAt(source_location, strict_mode() == SLOPPY
1635           ? "unexpected_token_identifier" : "unexpected_strict_reserved");
1636     default:
1637       const char* name = Token::String(token);
1638       DCHECK(name != NULL);
1639       Traits::ReportMessageAt(source_location, "unexpected_token", name);
1640   }
1641 }
1642
1643
1644 template<class Traits>
1645 typename ParserBase<Traits>::IdentifierT ParserBase<Traits>::ParseIdentifier(
1646     AllowEvalOrArgumentsAsIdentifier allow_eval_or_arguments,
1647     bool* ok) {
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");
1654       *ok = false;
1655     }
1656     return name;
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());
1662   } else {
1663     this->ReportUnexpectedToken(next);
1664     *ok = false;
1665     return Traits::EmptyIdentifier();
1666   }
1667 }
1668
1669
1670 template <class Traits>
1671 typename ParserBase<Traits>::IdentifierT ParserBase<
1672     Traits>::ParseIdentifierOrStrictReservedWord(bool* is_strict_reserved,
1673                                                  bool* ok) {
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;
1681   } else {
1682     ReportUnexpectedToken(next);
1683     *ok = false;
1684     return Traits::EmptyIdentifier();
1685   }
1686   return this->GetSymbol(scanner());
1687 }
1688
1689
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);
1698     *ok = false;
1699     return Traits::EmptyIdentifier();
1700   }
1701   return this->GetSymbol(scanner());
1702 }
1703
1704
1705 template <class Traits>
1706 typename ParserBase<Traits>::IdentifierT
1707 ParserBase<Traits>::ParseIdentifierNameOrGetOrSet(bool* is_get,
1708                                                   bool* is_set,
1709                                                   bool* ok) {
1710   IdentifierT result = ParseIdentifierName(ok);
1711   if (!*ok) return Traits::EmptyIdentifier();
1712   scanner()->IsGetOrSet(is_get, is_set);
1713   return result;
1714 }
1715
1716
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)) {
1722     Next();
1723     ReportMessage("unterminated_regexp");
1724     *ok = false;
1725     return Traits::EmptyExpression();
1726   }
1727
1728   int literal_index = function_state_->NextMaterializedLiteralIndex();
1729
1730   IdentifierT js_pattern = this->GetNextSymbol(scanner());
1731   if (!scanner()->ScanRegExpFlags()) {
1732     Next();
1733     ReportMessage("invalid_regexp_flags");
1734     *ok = false;
1735     return Traits::EmptyExpression();
1736   }
1737   IdentifierT js_flags = this->GetNextSymbol(scanner());
1738   Next();
1739   return factory()->NewRegExpLiteral(js_pattern, js_flags, literal_index, pos);
1740 }
1741
1742
1743 #define CHECK_OK  ok); \
1744   if (!*ok) return this->EmptyExpression(); \
1745   ((void)0
1746 #define DUMMY )  // to make indentation work
1747 #undef DUMMY
1748
1749 // Used in functions where the return type is not ExpressionT.
1750 #define CHECK_OK_CUSTOM(x) ok); \
1751   if (!*ok) return this->x(); \
1752   ((void)0
1753 #define DUMMY )  // to make indentation work
1754 #undef DUMMY
1755
1756 template <class Traits>
1757 typename ParserBase<Traits>::ExpressionT
1758 ParserBase<Traits>::ParsePrimaryExpression(bool* ok) {
1759   // PrimaryExpression ::
1760   //   'this'
1761   //   'null'
1762   //   'true'
1763   //   'false'
1764   //   Identifier
1765   //   Number
1766   //   String
1767   //   ArrayLiteral
1768   //   ObjectLiteral
1769   //   RegExpLiteral
1770   //   ClassLiteral
1771   //   '(' Expression ')'
1772
1773   int pos = peek_position();
1774   ExpressionT result = this->EmptyExpression();
1775   Token::Value token = peek();
1776   switch (token) {
1777     case Token::THIS: {
1778       Consume(Token::THIS);
1779       result = this->ThisExpression(scope_, factory());
1780       break;
1781     }
1782
1783     case Token::NULL_LITERAL:
1784     case Token::TRUE_LITERAL:
1785     case Token::FALSE_LITERAL:
1786     case Token::NUMBER:
1787       Next();
1788       result = this->ExpressionFromLiteral(token, pos, scanner(), factory());
1789       break;
1790
1791     case Token::IDENTIFIER:
1792     case Token::LET:
1793     case Token::YIELD:
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());
1798       break;
1799     }
1800
1801     case Token::STRING: {
1802       Consume(Token::STRING);
1803       result = this->ExpressionFromString(pos, scanner(), factory());
1804       break;
1805     }
1806
1807     case Token::ASSIGN_DIV:
1808       result = this->ParseRegExpLiteral(true, CHECK_OK);
1809       break;
1810
1811     case Token::DIV:
1812       result = this->ParseRegExpLiteral(false, CHECK_OK);
1813       break;
1814
1815     case Token::LBRACK:
1816       result = this->ParseArrayLiteral(CHECK_OK);
1817       break;
1818
1819     case Token::LBRACE:
1820       result = this->ParseObjectLiteral(CHECK_OK);
1821       break;
1822
1823     case Token::LPAREN:
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);
1831       } else {
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);
1838       }
1839       break;
1840
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,
1849                                                    CHECK_OK);
1850         class_name_location = scanner()->location();
1851       }
1852       result = this->ParseClassLiteral(name, class_name_location,
1853                                        is_strict_reserved_name,
1854                                        class_token_position, CHECK_OK);
1855       break;
1856     }
1857
1858     case Token::MOD:
1859       if (allow_natives_syntax() || extension_ != NULL) {
1860         result = this->ParseV8Intrinsic(CHECK_OK);
1861         break;
1862       }
1863       // If we're not allowing special syntax we fall-through to the
1864       // default case.
1865
1866     default: {
1867       Next();
1868       ReportUnexpectedToken(token);
1869       *ok = false;
1870     }
1871   }
1872
1873   return result;
1874 }
1875
1876 // Precedence = 1
1877 template <class Traits>
1878 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseExpression(
1879     bool accept_IN, bool* ok) {
1880   // Expression ::
1881   //   AssignmentExpression
1882   //   Expression ',' AssignmentExpression
1883
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);
1890   }
1891   return result;
1892 }
1893
1894
1895 template <class Traits>
1896 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseArrayLiteral(
1897     bool* ok) {
1898   // ArrayLiteral ::
1899   //   '[' Expression? (',' Expression?)* ']'
1900
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());
1909     } else {
1910       elem = this->ParseAssignmentExpression(true, CHECK_OK);
1911     }
1912     values->Add(elem, zone_);
1913     if (peek() != Token::RBRACK) {
1914       Expect(Token::COMMA, CHECK_OK);
1915     }
1916   }
1917   Expect(Token::RBRACK, CHECK_OK);
1918
1919   // Update the scope information before the pre-parsing bailout.
1920   int literal_index = function_state_->NextMaterializedLiteralIndex();
1921
1922   return factory()->NewArrayLiteral(values, literal_index, pos);
1923 }
1924
1925
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();
1930   switch (next) {
1931     case Token::STRING:
1932       Consume(Token::STRING);
1933       return this->GetSymbol(scanner_);
1934     case Token::NUMBER:
1935       Consume(Token::NUMBER);
1936       return this->GetNumberAsSymbol(scanner_);
1937     case Token::STATIC:
1938       *is_static = true;
1939       // Fall through.
1940     default:
1941       return ParseIdentifierNameOrGetOrSet(is_get, is_set, ok);
1942   }
1943   UNREACHABLE();
1944   return this->EmptyIdentifier();
1945 }
1946
1947
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);
1957
1958   Token::Value name_token = peek();
1959   int next_pos = peek_position();
1960   IdentifierT name =
1961       ParsePropertyName(&is_get, &is_set, &name_is_static,
1962                         CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
1963
1964   if (fni_ != NULL) this->PushLiteralName(fni_, name);
1965
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));
1973
1974   } else if (is_generator ||
1975              (allow_harmony_object_literals_ && peek() == Token::LPAREN)) {
1976     // Concise Method
1977
1978     if (is_static && this->IsPrototype(name)) {
1979       ReportMessageAt(scanner()->location(), "static_prototype");
1980       *ok = false;
1981       return this->EmptyObjectLiteralProperty();
1982     }
1983     if (is_generator && in_class && !is_static && this->IsConstructor(name)) {
1984       ReportMessageAt(scanner()->location(), "constructor_special_method");
1985       *ok = false;
1986       return this->EmptyObjectLiteralProperty();
1987     }
1988
1989     checker->CheckProperty(name_token, kValueProperty,
1990                            CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
1991     FunctionKind kind = is_generator ? FunctionKind::kConciseGeneratorMethod
1992                                      : FunctionKind::kConciseMethod;
1993
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));
2000
2001   } else if (in_class && name_is_static && !is_static) {
2002     // static MethodDefinition
2003     return ParsePropertyDefinition(checker, true, true, ok);
2004
2005   } else if (is_get || is_set) {
2006     // Accessor
2007     bool dont_care = false;
2008     name_token = peek();
2009     name = ParsePropertyName(&dont_care, &dont_care, &dont_care,
2010                              CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
2011
2012     // Validate the property.
2013     if (is_static && this->IsPrototype(name)) {
2014       ReportMessageAt(scanner()->location(), "static_prototype");
2015       *ok = false;
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");
2022       *ok = false;
2023       return this->EmptyObjectLiteralProperty();
2024     }
2025     checker->CheckProperty(name_token,
2026                            is_get ? kGetterProperty : kSetterProperty,
2027                            CHECK_OK_CUSTOM(EmptyObjectLiteralProperty));
2028
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,
2037                                                is_static);
2038   } else {
2039     Token::Value next = Next();
2040     ReportUnexpectedToken(next);
2041     *ok = false;
2042     return this->EmptyObjectLiteralProperty();
2043   }
2044
2045   uint32_t index;
2046   LiteralT key = this->IsArrayIndex(name, &index)
2047                      ? factory()->NewNumberLiteral(index, next_pos)
2048                      : factory()->NewStringLiteral(name, next_pos);
2049
2050   return factory()->NewObjectLiteralProperty(key, value, is_static);
2051 }
2052
2053
2054 template <class Traits>
2055 typename ParserBase<Traits>::ExpressionT ParserBase<Traits>::ParseObjectLiteral(
2056     bool* ok) {
2057   // ObjectLiteral ::
2058   // '{' (PropertyDefinition (',' PropertyDefinition)* ','? )? '}'
2059
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;
2065
2066   ObjectLiteralChecker checker(this, strict_mode());
2067
2068   Expect(Token::LBRACE, CHECK_OK);
2069
2070   while (peek() != Token::RBRACE) {
2071     if (fni_ != NULL) fni_->Enter();
2072
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);
2077
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,
2082                                                           &has_function);
2083
2084     // Count CONSTANT or COMPUTED properties to maintain the enumeration order.
2085     if (this->IsBoilerplateProperty(property)) {
2086       number_of_boilerplate_properties++;
2087     }
2088     properties->Add(property, zone());
2089
2090     if (peek() != Token::RBRACE) {
2091       // Need {} because of the CHECK_OK macro.
2092       Expect(Token::COMMA, CHECK_OK);
2093     }
2094
2095     if (fni_ != NULL) {
2096       fni_->Infer();
2097       fni_->Leave();
2098     }
2099   }
2100   Expect(Token::RBRACE, CHECK_OK);
2101
2102   // Computation of literal_index must happen before pre parse bailout.
2103   int literal_index = function_state_->NextMaterializedLiteralIndex();
2104
2105   return factory()->NewObjectLiteral(properties,
2106                                      literal_index,
2107                                      number_of_boilerplate_properties,
2108                                      has_function,
2109                                      pos);
2110 }
2111
2112
2113 template <class Traits>
2114 typename Traits::Type::ExpressionList ParserBase<Traits>::ParseArguments(
2115     bool* ok) {
2116   // Arguments ::
2117   //   '(' (AssignmentExpression)*[','] ')'
2118
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);
2123   while (!done) {
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");
2129       *ok = false;
2130       return this->NullExpressionList();
2131     }
2132     done = (peek() == Token::RPAREN);
2133     if (!done) {
2134       // Need {} because of the CHECK_OK_CUSTOM macro.
2135       Expect(Token::COMMA, CHECK_OK_CUSTOM(NullExpressionList));
2136     }
2137   }
2138   Expect(Token::RPAREN, CHECK_OK_CUSTOM(NullExpressionList));
2139   return result;
2140 }
2141
2142 // Precedence = 2
2143 template <class Traits>
2144 typename ParserBase<Traits>::ExpressionT
2145 ParserBase<Traits>::ParseAssignmentExpression(bool accept_IN, bool* ok) {
2146   // AssignmentExpression ::
2147   //   ConditionalExpression
2148   //   ArrowFunction
2149   //   YieldExpression
2150   //   LeftHandSideExpression AssignmentOperator AssignmentExpression
2151
2152   Scanner::Location lhs_location = scanner()->peek_location();
2153
2154   if (peek() == Token::YIELD && is_generator()) {
2155     return this->ParseYieldExpression(ok);
2156   }
2157
2158   if (fni_ != NULL) fni_->Enter();
2159   typename Traits::Checkpoint checkpoint(this);
2160   ExpressionT expression =
2161       this->ParseConditionalExpression(accept_IN, CHECK_OK);
2162
2163   if (allow_arrow_functions() && peek() == Token::ARROW) {
2164     checkpoint.Restore();
2165     expression = this->ParseArrowFunctionLiteral(lhs_location.beg_pos,
2166                                                  expression, CHECK_OK);
2167     return expression;
2168   }
2169
2170   if (!Token::IsAssignmentOp(peek())) {
2171     if (fni_ != NULL) fni_->Leave();
2172     // Parsed conditional expression only (no assignment).
2173     return expression;
2174   }
2175
2176   expression = this->CheckAndRewriteReferenceExpression(
2177       expression, lhs_location, "invalid_lhs_in_assignment", CHECK_OK);
2178   expression = this->MarkExpressionAsAssigned(expression);
2179
2180   Token::Value op = Next();  // Get assignment operator.
2181   int pos = position();
2182   ExpressionT right = this->ParseAssignmentExpression(accept_IN, CHECK_OK);
2183
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();
2191   }
2192
2193   this->CheckAssigningFunctionLiteralToProperty(expression, right);
2194
2195   if (fni_ != NULL) {
2196     // Check if the right hand side is a call to avoid inferring a
2197     // name if we're dealing with "a = function(){...}();"-like
2198     // expression.
2199     if ((op == Token::INIT_VAR
2200          || op == Token::INIT_CONST_LEGACY
2201          || op == Token::ASSIGN)
2202         && (!right->IsCall() && !right->IsCallNew())) {
2203       fni_->Infer();
2204     } else {
2205       fni_->RemoveLastFunction();
2206     }
2207     fni_->Leave();
2208   }
2209
2210   return factory()->NewAssignment(op, expression, right, pos);
2211 }
2212
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;
2226     switch (peek()) {
2227       case Token::EOS:
2228       case Token::SEMICOLON:
2229       case Token::RBRACE:
2230       case Token::RBRACK:
2231       case Token::RPAREN:
2232       case Token::COLON:
2233       case Token::COMMA:
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)
2239           break;
2240         DCHECK_EQ(Yield::kDelegating, kind);
2241         // Delegating yields require an RHS; fall through.
2242       default:
2243         expression = ParseAssignmentExpression(false, CHECK_OK);
2244         break;
2245     }
2246   }
2247   if (kind == Yield::kDelegating) {
2248     // var iterator = subject[Symbol.iterator]();
2249     expression = this->GetIterator(expression, factory());
2250   }
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());
2255   }
2256   return yield;
2257 }
2258
2259
2260 // Precedence = 3
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
2267
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);
2280 }
2281
2282
2283 // Precedence >= 4
2284 template <class Traits>
2285 typename ParserBase<Traits>::ExpressionT
2286 ParserBase<Traits>::ParseBinaryExpression(int prec, bool accept_IN, bool* ok) {
2287   DCHECK(prec >= 4);
2288   ExpressionT x = this->ParseUnaryExpression(CHECK_OK);
2289   for (int prec1 = Precedence(peek(), accept_IN); prec1 >= prec; prec1--) {
2290     // prec1 >= 4
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);
2295
2296       if (this->ShortcutNumericLiteralBinaryExpression(&x, y, op, pos,
2297                                                        factory())) {
2298         continue;
2299       }
2300
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;
2307         switch (op) {
2308           case Token::NE: cmp = Token::EQ; break;
2309           case Token::NE_STRICT: cmp = Token::EQ_STRICT; break;
2310           default: break;
2311         }
2312         x = factory()->NewCompareOperation(cmp, x, y, pos);
2313         if (cmp != op) {
2314           // The comparison was negated - add a NOT.
2315           x = factory()->NewUnaryOperation(Token::NOT, x, pos);
2316         }
2317
2318       } else {
2319         // We have a "normal" binary operation.
2320         x = factory()->NewBinaryOperation(op, x, y, pos);
2321       }
2322     }
2323   }
2324   return x;
2325 }
2326
2327
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
2342
2343   Token::Value op = peek();
2344   if (Token::IsUnaryOp(op)) {
2345     op = Next();
2346     int pos = position();
2347     ExpressionT expression = ParseUnaryExpression(CHECK_OK);
2348
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");
2353       *ok = false;
2354       return this->EmptyExpression();
2355     }
2356
2357     // Allow Traits do rewrite the expression.
2358     return this->BuildUnaryExpression(expression, op, pos, factory());
2359   } else if (Token::IsCountOp(op)) {
2360     op = Next();
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);
2366
2367     return factory()->NewCountOperation(op,
2368                                         true /* prefix */,
2369                                         expression,
2370                                         position());
2371
2372   } else {
2373     return this->ParsePostfixExpression(ok);
2374   }
2375 }
2376
2377
2378 template <class Traits>
2379 typename ParserBase<Traits>::ExpressionT
2380 ParserBase<Traits>::ParsePostfixExpression(bool* ok) {
2381   // PostfixExpression ::
2382   //   LeftHandSideExpression ('++' | '--')?
2383
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);
2391
2392     Token::Value next = Next();
2393     expression =
2394         factory()->NewCountOperation(next,
2395                                      false /* postfix */,
2396                                      expression,
2397                                      position());
2398   }
2399   return expression;
2400 }
2401
2402
2403 template <class Traits>
2404 typename ParserBase<Traits>::ExpressionT
2405 ParserBase<Traits>::ParseLeftHandSideExpression(bool* ok) {
2406   // LeftHandSideExpression ::
2407   //   (NewExpression | MemberExpression) ...
2408
2409   ExpressionT result = this->ParseMemberWithNewPrefixesExpression(CHECK_OK);
2410
2411   while (true) {
2412     switch (peek()) {
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);
2419         break;
2420       }
2421
2422       case Token::LPAREN: {
2423         int pos;
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.
2427           pos = position();
2428         } else {
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();
2440           }
2441         }
2442         typename Traits::Type::ExpressionList args = ParseArguments(CHECK_OK);
2443
2444         if (this->BuildSIMD128LoadStoreExpression(
2445             &result, args, pos, factory()))
2446           break;
2447
2448         // Keep track of eval() calls since they disable all local variable
2449         // optimizations.
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();
2458         break;
2459       }
2460
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);
2468         break;
2469       }
2470
2471       default:
2472         return result;
2473     }
2474   }
2475 }
2476
2477
2478 template <class Traits>
2479 typename ParserBase<Traits>::ExpressionT
2480 ParserBase<Traits>::ParseMemberWithNewPrefixesExpression(bool* ok) {
2481   // NewExpression ::
2482   //   ('new')+ MemberExpression
2483
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.
2489
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
2497
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());
2504     } else {
2505       result = this->ParseMemberWithNewPrefixesExpression(CHECK_OK);
2506     }
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);
2514       return result;
2515     }
2516     // NewExpression without arguments.
2517     return factory()->NewCallNew(result, this->NewExpressionList(0, zone_),
2518                                  new_pos);
2519   }
2520   // No 'new' or 'super' keyword.
2521   return this->ParseMemberExpression(ok);
2522 }
2523
2524
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)*
2531
2532   // The '[' Expression ']' and '.' Identifier parts are parsed by
2533   // ParseMemberExpressionContinuation, and the Arguments part is parsed by the
2534   // caller.
2535
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,
2549                                                  CHECK_OK);
2550       function_name_location = scanner()->location();
2551       function_type = FunctionLiteral::NAMED_EXPRESSION;
2552     }
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,
2558         CHECK_OK);
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());
2566     } else {
2567       ReportMessageAt(Scanner::Location(beg_pos, position()),
2568                       "unexpected_super");
2569       *ok = false;
2570       return this->EmptyExpression();
2571     }
2572   } else {
2573     result = ParsePrimaryExpression(CHECK_OK);
2574   }
2575
2576   result = ParseMemberExpressionContinuation(result, CHECK_OK);
2577   return result;
2578 }
2579
2580
2581 template <class Traits>
2582 typename ParserBase<Traits>::ExpressionT
2583 ParserBase<Traits>::ParseMemberExpressionContinuation(ExpressionT expression,
2584                                                       bool* ok) {
2585   // Parses this part of MemberExpression:
2586   // ('[' Expression ']' | '.' Identifier)*
2587   while (true) {
2588     switch (peek()) {
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);
2594         if (fni_ != NULL) {
2595           this->PushPropertyName(fni_, index);
2596         }
2597         Expect(Token::RBRACK, CHECK_OK);
2598         break;
2599       }
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);
2606         if (fni_ != NULL) {
2607           this->PushLiteralName(fni_, name);
2608         }
2609         break;
2610       }
2611       default:
2612         return expression;
2613     }
2614   }
2615   DCHECK(false);
2616   return this->EmptyExpression();
2617 }
2618
2619
2620 template <class Traits>
2621 typename ParserBase<Traits>::ExpressionT ParserBase<
2622     Traits>::ParseArrowFunctionLiteral(int start_pos, ExpressionT params_ast,
2623                                        bool* ok) {
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;
2634
2635   {
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);
2641     if (!*ok) {
2642       ReportMessageAt(
2643           Scanner::Location(start_pos, scanner()->location().beg_pos),
2644           "malformed_arrow_function_parameter_list");
2645       return this->EmptyExpression();
2646     }
2647
2648     if (num_parameters > Code::kMaxArguments) {
2649       ReportMessageAt(Scanner::Location(params_ast->position(), position()),
2650                       "too_many_parameters");
2651       *ok = false;
2652       return this->EmptyExpression();
2653     }
2654
2655     Expect(Token::ARROW, CHECK_OK);
2656
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);
2667       } else {
2668         body = this->ParseEagerFunctionBody(
2669             this->EmptyIdentifier(), RelocInfo::kNoPosition, NULL,
2670             Token::INIT_VAR, false,  // Not a generator.
2671             CHECK_OK);
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();
2676       }
2677     } else {
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();
2687     }
2688
2689     scope->set_start_position(start_pos);
2690     scope->set_end_position(scanner()->location().end_pos);
2691
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,
2700         CHECK_OK);
2701
2702     // Validate strict mode.
2703     if (strict_mode() == STRICT) {
2704       CheckOctalLiteral(start_pos, scanner()->location().end_pos, CHECK_OK);
2705     }
2706
2707     if (allow_harmony_scoping() && strict_mode() == STRICT)
2708       this->CheckConflictingVarDeclarations(scope, CHECK_OK);
2709
2710     ast_properties = *factory()->visitor()->ast_properties();
2711     dont_optimize_reason = factory()->visitor()->dont_optimize_reason();
2712   }
2713
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,
2720       start_pos);
2721
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);
2725
2726   if (fni_ != NULL) this->InferFunctionName(fni_, function_literal);
2727
2728   return function_literal;
2729 }
2730
2731
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");
2739     *ok = false;
2740     return this->EmptyExpression();
2741   }
2742   if (this->IsEvalOrArguments(name)) {
2743     ReportMessageAt(class_name_location, "strict_eval_arguments");
2744     *ok = false;
2745     return this->EmptyExpression();
2746   }
2747
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);
2757
2758   ExpressionT extends = this->EmptyExpression();
2759   if (Check(Token::EXTENDS)) {
2760     extends = this->ParseLeftHandSideExpression(CHECK_OK);
2761   }
2762
2763   ObjectLiteralChecker checker(this, STRICT);
2764   typename Traits::Type::PropertyList properties =
2765       this->NewPropertyList(4, zone_);
2766   FunctionLiteralT constructor = this->EmptyFunctionLiteral();
2767
2768   Expect(Token::LBRACE, CHECK_OK);
2769   while (peek() != Token::RBRACE) {
2770     if (Check(Token::SEMICOLON)) continue;
2771     if (fni_ != NULL) fni_->Enter();
2772
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);
2777
2778     properties->Add(property, zone());
2779
2780     if (fni_ != NULL) {
2781       fni_->Infer();
2782       fni_->Leave();
2783     }
2784   }
2785   Expect(Token::RBRACE, CHECK_OK);
2786
2787   return this->ClassLiteral(name, extends, constructor, properties, pos,
2788                             factory());
2789 }
2790
2791
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);
2800     *ok = false;
2801     return this->EmptyExpression();
2802   } else if (expression->IsValidReferenceExpression()) {
2803     return expression;
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);
2810   } else {
2811     this->ReportMessageAt(location, message, true);
2812     *ok = false;
2813     return this->EmptyExpression();
2814   }
2815 }
2816
2817
2818 #undef CHECK_OK
2819 #undef CHECK_OK_CUSTOM
2820
2821
2822 template <typename Traits>
2823 void ParserBase<Traits>::ObjectLiteralChecker::CheckProperty(
2824     Token::Value property, PropertyKind type, bool* ok) {
2825   int old;
2826   if (property == Token::NUMBER) {
2827     old = scanner()->FindNumber(&finder_, type);
2828   } else {
2829     old = scanner()->FindSymbol(&finder_, type);
2830   }
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");
2840     } else {
2841       DCHECK(IsAccessorAccessorConflict(old_type, type));
2842       // Both accessors of the same type.
2843       parser()->ReportMessage("accessor_get_set");
2844     }
2845     *ok = false;
2846   }
2847 }
2848 } }  // v8::internal
2849
2850 #endif  // V8_PREPARSER_H