[presubmit] Enable readability/namespace linter checking.
[platform/upstream/v8.git] / src / parser.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_PARSER_H_
6 #define V8_PARSER_H_
7
8 #include "src/allocation.h"
9 #include "src/ast.h"
10 #include "src/compiler.h"  // TODO(titzer): remove this include dependency
11 #include "src/pending-compilation-error-handler.h"
12 #include "src/preparse-data.h"
13 #include "src/preparse-data-format.h"
14 #include "src/preparser.h"
15 #include "src/scopes.h"
16
17 namespace v8 {
18
19 class ScriptCompiler;
20
21 namespace internal {
22
23 class Target;
24
25 // A container for the inputs, configuration options, and outputs of parsing.
26 class ParseInfo {
27  public:
28   explicit ParseInfo(Zone* zone);
29   ParseInfo(Zone* zone, Handle<JSFunction> function);
30   ParseInfo(Zone* zone, Handle<Script> script);
31   // TODO(all) Only used via Debug::FindSharedFunctionInfoInScript, remove?
32   ParseInfo(Zone* zone, Handle<SharedFunctionInfo> shared);
33
34   ~ParseInfo() {
35     if (ast_value_factory_owned()) {
36       delete ast_value_factory_;
37       set_ast_value_factory_owned(false);
38     }
39     ast_value_factory_ = nullptr;
40   }
41
42   Zone* zone() { return zone_; }
43
44 // Convenience accessor methods for flags.
45 #define FLAG_ACCESSOR(flag, getter, setter)     \
46   bool getter() const { return GetFlag(flag); } \
47   void setter() { SetFlag(flag); }              \
48   void setter(bool val) { SetFlag(flag, val); }
49
50   FLAG_ACCESSOR(kToplevel, is_toplevel, set_toplevel)
51   FLAG_ACCESSOR(kLazy, is_lazy, set_lazy)
52   FLAG_ACCESSOR(kEval, is_eval, set_eval)
53   FLAG_ACCESSOR(kGlobal, is_global, set_global)
54   FLAG_ACCESSOR(kStrictMode, is_strict_mode, set_strict_mode)
55   FLAG_ACCESSOR(kStrongMode, is_strong_mode, set_strong_mode)
56   FLAG_ACCESSOR(kNative, is_native, set_native)
57   FLAG_ACCESSOR(kModule, is_module, set_module)
58   FLAG_ACCESSOR(kAllowLazyParsing, allow_lazy_parsing, set_allow_lazy_parsing)
59   FLAG_ACCESSOR(kAstValueFactoryOwned, ast_value_factory_owned,
60                 set_ast_value_factory_owned)
61
62 #undef FLAG_ACCESSOR
63
64   void set_parse_restriction(ParseRestriction restriction) {
65     SetFlag(kParseRestriction, restriction != NO_PARSE_RESTRICTION);
66   }
67
68   ParseRestriction parse_restriction() const {
69     return GetFlag(kParseRestriction) ? ONLY_SINGLE_FUNCTION_LITERAL
70                                       : NO_PARSE_RESTRICTION;
71   }
72
73   ScriptCompiler::ExternalSourceStream* source_stream() {
74     return source_stream_;
75   }
76   void set_source_stream(ScriptCompiler::ExternalSourceStream* source_stream) {
77     source_stream_ = source_stream;
78   }
79
80   ScriptCompiler::StreamedSource::Encoding source_stream_encoding() {
81     return source_stream_encoding_;
82   }
83   void set_source_stream_encoding(
84       ScriptCompiler::StreamedSource::Encoding source_stream_encoding) {
85     source_stream_encoding_ = source_stream_encoding;
86   }
87
88   v8::Extension* extension() { return extension_; }
89   void set_extension(v8::Extension* extension) { extension_ = extension; }
90
91   ScriptData** cached_data() { return cached_data_; }
92   void set_cached_data(ScriptData** cached_data) { cached_data_ = cached_data; }
93
94   ScriptCompiler::CompileOptions compile_options() { return compile_options_; }
95   void set_compile_options(ScriptCompiler::CompileOptions compile_options) {
96     compile_options_ = compile_options;
97   }
98
99   Scope* script_scope() { return script_scope_; }
100   void set_script_scope(Scope* script_scope) { script_scope_ = script_scope; }
101
102   AstValueFactory* ast_value_factory() { return ast_value_factory_; }
103   void set_ast_value_factory(AstValueFactory* ast_value_factory) {
104     ast_value_factory_ = ast_value_factory;
105   }
106
107   FunctionLiteral* literal() { return literal_; }
108   void set_literal(FunctionLiteral* literal) { literal_ = literal; }
109
110   Scope* scope() { return scope_; }
111   void set_scope(Scope* scope) { scope_ = scope; }
112
113   UnicodeCache* unicode_cache() { return unicode_cache_; }
114   void set_unicode_cache(UnicodeCache* unicode_cache) {
115     unicode_cache_ = unicode_cache;
116   }
117
118   uintptr_t stack_limit() { return stack_limit_; }
119   void set_stack_limit(uintptr_t stack_limit) { stack_limit_ = stack_limit; }
120
121   uint32_t hash_seed() { return hash_seed_; }
122   void set_hash_seed(uint32_t hash_seed) { hash_seed_ = hash_seed; }
123
124   //--------------------------------------------------------------------------
125   // TODO(titzer): these should not be part of ParseInfo.
126   //--------------------------------------------------------------------------
127   Isolate* isolate() { return isolate_; }
128   Handle<JSFunction> closure() { return closure_; }
129   Handle<SharedFunctionInfo> shared_info() { return shared_; }
130   Handle<Script> script() { return script_; }
131   Handle<Context> context() { return context_; }
132   void clear_script() { script_ = Handle<Script>::null(); }
133   void set_isolate(Isolate* isolate) { isolate_ = isolate; }
134   void set_context(Handle<Context> context) { context_ = context; }
135   void set_script(Handle<Script> script) { script_ = script; }
136   //--------------------------------------------------------------------------
137
138   LanguageMode language_mode() {
139     return construct_language_mode(is_strict_mode(), is_strong_mode());
140   }
141   void set_language_mode(LanguageMode language_mode) {
142     STATIC_ASSERT(LANGUAGE_END == 3);
143     set_strict_mode(language_mode & STRICT_BIT);
144     set_strong_mode(language_mode & STRONG_BIT);
145   }
146
147   void ReopenHandlesInNewHandleScope() {
148     closure_ = Handle<JSFunction>(*closure_);
149     shared_ = Handle<SharedFunctionInfo>(*shared_);
150     script_ = Handle<Script>(*script_);
151     context_ = Handle<Context>(*context_);
152   }
153
154  private:
155   // Various configuration flags for parsing.
156   enum Flag {
157     // ---------- Input flags ---------------------------
158     kToplevel = 1 << 0,
159     kLazy = 1 << 1,
160     kEval = 1 << 2,
161     kGlobal = 1 << 3,
162     kStrictMode = 1 << 4,
163     kStrongMode = 1 << 5,
164     kNative = 1 << 6,
165     kParseRestriction = 1 << 7,
166     kModule = 1 << 8,
167     kAllowLazyParsing = 1 << 9,
168     // ---------- Output flags --------------------------
169     kAstValueFactoryOwned = 1 << 10
170   };
171
172   //------------- Inputs to parsing and scope analysis -----------------------
173   Zone* zone_;
174   unsigned flags_;
175   ScriptCompiler::ExternalSourceStream* source_stream_;
176   ScriptCompiler::StreamedSource::Encoding source_stream_encoding_;
177   v8::Extension* extension_;
178   ScriptCompiler::CompileOptions compile_options_;
179   Scope* script_scope_;
180   UnicodeCache* unicode_cache_;
181   uintptr_t stack_limit_;
182   uint32_t hash_seed_;
183
184   // TODO(titzer): Move handles and isolate out of ParseInfo.
185   Isolate* isolate_;
186   Handle<JSFunction> closure_;
187   Handle<SharedFunctionInfo> shared_;
188   Handle<Script> script_;
189   Handle<Context> context_;
190
191   //----------- Inputs+Outputs of parsing and scope analysis -----------------
192   ScriptData** cached_data_;  // used if available, populated if requested.
193   AstValueFactory* ast_value_factory_;  // used if available, otherwise new.
194
195   //----------- Outputs of parsing and scope analysis ------------------------
196   FunctionLiteral* literal_;  // produced by full parser.
197   Scope* scope_;              // produced by scope analysis.
198
199   void SetFlag(Flag f) { flags_ |= f; }
200   void SetFlag(Flag f, bool v) { flags_ = v ? flags_ | f : flags_ & ~f; }
201   bool GetFlag(Flag f) const { return (flags_ & f) != 0; }
202
203   void set_shared_info(Handle<SharedFunctionInfo> shared) { shared_ = shared; }
204   void set_closure(Handle<JSFunction> closure) { closure_ = closure; }
205 };
206
207 class FunctionEntry BASE_EMBEDDED {
208  public:
209   enum {
210     kStartPositionIndex,
211     kEndPositionIndex,
212     kLiteralCountIndex,
213     kPropertyCountIndex,
214     kLanguageModeIndex,
215     kUsesSuperPropertyIndex,
216     kCallsEvalIndex,
217     kSize
218   };
219
220   explicit FunctionEntry(Vector<unsigned> backing)
221     : backing_(backing) { }
222
223   FunctionEntry() : backing_() { }
224
225   int start_pos() { return backing_[kStartPositionIndex]; }
226   int end_pos() { return backing_[kEndPositionIndex]; }
227   int literal_count() { return backing_[kLiteralCountIndex]; }
228   int property_count() { return backing_[kPropertyCountIndex]; }
229   LanguageMode language_mode() {
230     DCHECK(is_valid_language_mode(backing_[kLanguageModeIndex]));
231     return static_cast<LanguageMode>(backing_[kLanguageModeIndex]);
232   }
233   bool uses_super_property() { return backing_[kUsesSuperPropertyIndex]; }
234   bool calls_eval() { return backing_[kCallsEvalIndex]; }
235
236   bool is_valid() { return !backing_.is_empty(); }
237
238  private:
239   Vector<unsigned> backing_;
240 };
241
242
243 // Wrapper around ScriptData to provide parser-specific functionality.
244 class ParseData {
245  public:
246   static ParseData* FromCachedData(ScriptData* cached_data) {
247     ParseData* pd = new ParseData(cached_data);
248     if (pd->IsSane()) return pd;
249     cached_data->Reject();
250     delete pd;
251     return NULL;
252   }
253
254   void Initialize();
255   FunctionEntry GetFunctionEntry(int start);
256   int FunctionCount();
257
258   bool HasError();
259
260   unsigned* Data() {  // Writable data as unsigned int array.
261     return reinterpret_cast<unsigned*>(const_cast<byte*>(script_data_->data()));
262   }
263
264   void Reject() { script_data_->Reject(); }
265
266   bool rejected() const { return script_data_->rejected(); }
267
268  private:
269   explicit ParseData(ScriptData* script_data) : script_data_(script_data) {}
270
271   bool IsSane();
272   unsigned Magic();
273   unsigned Version();
274   int FunctionsSize();
275   int Length() const {
276     // Script data length is already checked to be a multiple of unsigned size.
277     return script_data_->length() / sizeof(unsigned);
278   }
279
280   ScriptData* script_data_;
281   int function_index_;
282
283   DISALLOW_COPY_AND_ASSIGN(ParseData);
284 };
285
286 // ----------------------------------------------------------------------------
287 // REGEXP PARSING
288
289 // A BufferedZoneList is an automatically growing list, just like (and backed
290 // by) a ZoneList, that is optimized for the case of adding and removing
291 // a single element. The last element added is stored outside the backing list,
292 // and if no more than one element is ever added, the ZoneList isn't even
293 // allocated.
294 // Elements must not be NULL pointers.
295 template <typename T, int initial_size>
296 class BufferedZoneList {
297  public:
298   BufferedZoneList() : list_(NULL), last_(NULL) {}
299
300   // Adds element at end of list. This element is buffered and can
301   // be read using last() or removed using RemoveLast until a new Add or until
302   // RemoveLast or GetList has been called.
303   void Add(T* value, Zone* zone) {
304     if (last_ != NULL) {
305       if (list_ == NULL) {
306         list_ = new(zone) ZoneList<T*>(initial_size, zone);
307       }
308       list_->Add(last_, zone);
309     }
310     last_ = value;
311   }
312
313   T* last() {
314     DCHECK(last_ != NULL);
315     return last_;
316   }
317
318   T* RemoveLast() {
319     DCHECK(last_ != NULL);
320     T* result = last_;
321     if ((list_ != NULL) && (list_->length() > 0))
322       last_ = list_->RemoveLast();
323     else
324       last_ = NULL;
325     return result;
326   }
327
328   T* Get(int i) {
329     DCHECK((0 <= i) && (i < length()));
330     if (list_ == NULL) {
331       DCHECK_EQ(0, i);
332       return last_;
333     } else {
334       if (i == list_->length()) {
335         DCHECK(last_ != NULL);
336         return last_;
337       } else {
338         return list_->at(i);
339       }
340     }
341   }
342
343   void Clear() {
344     list_ = NULL;
345     last_ = NULL;
346   }
347
348   int length() {
349     int length = (list_ == NULL) ? 0 : list_->length();
350     return length + ((last_ == NULL) ? 0 : 1);
351   }
352
353   ZoneList<T*>* GetList(Zone* zone) {
354     if (list_ == NULL) {
355       list_ = new(zone) ZoneList<T*>(initial_size, zone);
356     }
357     if (last_ != NULL) {
358       list_->Add(last_, zone);
359       last_ = NULL;
360     }
361     return list_;
362   }
363
364  private:
365   ZoneList<T*>* list_;
366   T* last_;
367 };
368
369
370 // Accumulates RegExp atoms and assertions into lists of terms and alternatives.
371 class RegExpBuilder: public ZoneObject {
372  public:
373   explicit RegExpBuilder(Zone* zone);
374   void AddCharacter(uc16 character);
375   // "Adds" an empty expression. Does nothing except consume a
376   // following quantifier
377   void AddEmpty();
378   void AddAtom(RegExpTree* tree);
379   void AddAssertion(RegExpTree* tree);
380   void NewAlternative();  // '|'
381   void AddQuantifierToAtom(
382       int min, int max, RegExpQuantifier::QuantifierType type);
383   RegExpTree* ToRegExp();
384
385  private:
386   void FlushCharacters();
387   void FlushText();
388   void FlushTerms();
389   Zone* zone() const { return zone_; }
390
391   Zone* zone_;
392   bool pending_empty_;
393   ZoneList<uc16>* characters_;
394   BufferedZoneList<RegExpTree, 2> terms_;
395   BufferedZoneList<RegExpTree, 2> text_;
396   BufferedZoneList<RegExpTree, 2> alternatives_;
397 #ifdef DEBUG
398   enum {ADD_NONE, ADD_CHAR, ADD_TERM, ADD_ASSERT, ADD_ATOM} last_added_;
399 #define LAST(x) last_added_ = x;
400 #else
401 #define LAST(x)
402 #endif
403 };
404
405
406 class RegExpParser BASE_EMBEDDED {
407  public:
408   RegExpParser(FlatStringReader* in, Handle<String>* error, bool multiline_mode,
409                bool unicode, Isolate* isolate, Zone* zone);
410
411   static bool ParseRegExp(Isolate* isolate, Zone* zone, FlatStringReader* input,
412                           bool multiline, bool unicode,
413                           RegExpCompileData* result);
414
415   RegExpTree* ParsePattern();
416   RegExpTree* ParseDisjunction();
417   RegExpTree* ParseGroup();
418   RegExpTree* ParseCharacterClass();
419
420   // Parses a {...,...} quantifier and stores the range in the given
421   // out parameters.
422   bool ParseIntervalQuantifier(int* min_out, int* max_out);
423
424   // Parses and returns a single escaped character.  The character
425   // must not be 'b' or 'B' since they are usually handle specially.
426   uc32 ParseClassCharacterEscape();
427
428   // Checks whether the following is a length-digit hexadecimal number,
429   // and sets the value if it is.
430   bool ParseHexEscape(int length, uc32* value);
431   bool ParseUnicodeEscape(uc32* value);
432   bool ParseUnlimitedLengthHexNumber(int max_value, uc32* value);
433
434   uc32 ParseOctalLiteral();
435
436   // Tries to parse the input as a back reference.  If successful it
437   // stores the result in the output parameter and returns true.  If
438   // it fails it will push back the characters read so the same characters
439   // can be reparsed.
440   bool ParseBackReferenceIndex(int* index_out);
441
442   CharacterRange ParseClassAtom(uc16* char_class);
443   RegExpTree* ReportError(Vector<const char> message);
444   void Advance();
445   void Advance(int dist);
446   void Reset(int pos);
447
448   // Reports whether the pattern might be used as a literal search string.
449   // Only use if the result of the parse is a single atom node.
450   bool simple();
451   bool contains_anchor() { return contains_anchor_; }
452   void set_contains_anchor() { contains_anchor_ = true; }
453   int captures_started() { return captures_ == NULL ? 0 : captures_->length(); }
454   int position() { return next_pos_ - 1; }
455   bool failed() { return failed_; }
456
457   static bool IsSyntaxCharacter(uc32 c);
458
459   static const int kMaxCaptures = 1 << 16;
460   static const uc32 kEndMarker = (1 << 21);
461
462  private:
463   enum SubexpressionType {
464     INITIAL,
465     CAPTURE,  // All positive values represent captures.
466     POSITIVE_LOOKAHEAD,
467     NEGATIVE_LOOKAHEAD,
468     GROUPING
469   };
470
471   class RegExpParserState : public ZoneObject {
472    public:
473     RegExpParserState(RegExpParserState* previous_state,
474                       SubexpressionType group_type,
475                       int disjunction_capture_index,
476                       Zone* zone)
477         : previous_state_(previous_state),
478           builder_(new(zone) RegExpBuilder(zone)),
479           group_type_(group_type),
480           disjunction_capture_index_(disjunction_capture_index) {}
481     // Parser state of containing expression, if any.
482     RegExpParserState* previous_state() { return previous_state_; }
483     bool IsSubexpression() { return previous_state_ != NULL; }
484     // RegExpBuilder building this regexp's AST.
485     RegExpBuilder* builder() { return builder_; }
486     // Type of regexp being parsed (parenthesized group or entire regexp).
487     SubexpressionType group_type() { return group_type_; }
488     // Index in captures array of first capture in this sub-expression, if any.
489     // Also the capture index of this sub-expression itself, if group_type
490     // is CAPTURE.
491     int capture_index() { return disjunction_capture_index_; }
492
493    private:
494     // Linked list implementation of stack of states.
495     RegExpParserState* previous_state_;
496     // Builder for the stored disjunction.
497     RegExpBuilder* builder_;
498     // Stored disjunction type (capture, look-ahead or grouping), if any.
499     SubexpressionType group_type_;
500     // Stored disjunction's capture index (if any).
501     int disjunction_capture_index_;
502   };
503
504   Isolate* isolate() { return isolate_; }
505   Zone* zone() const { return zone_; }
506
507   uc32 current() { return current_; }
508   bool has_more() { return has_more_; }
509   bool has_next() { return next_pos_ < in()->length(); }
510   uc32 Next();
511   FlatStringReader* in() { return in_; }
512   void ScanForCaptures();
513
514   Isolate* isolate_;
515   Zone* zone_;
516   Handle<String>* error_;
517   ZoneList<RegExpCapture*>* captures_;
518   FlatStringReader* in_;
519   uc32 current_;
520   int next_pos_;
521   // The capture count is only valid after we have scanned for captures.
522   int capture_count_;
523   bool has_more_;
524   bool multiline_;
525   bool unicode_;
526   bool simple_;
527   bool contains_anchor_;
528   bool is_scanned_for_captures_;
529   bool failed_;
530 };
531
532 // ----------------------------------------------------------------------------
533 // JAVASCRIPT PARSING
534
535 class Parser;
536 class SingletonLogger;
537
538
539 struct ParserFormalParameters : FormalParametersBase {
540   struct Parameter {
541     Parameter(const AstRawString* name, Expression* pattern,
542               Expression* initializer, bool is_rest)
543         : name(name), pattern(pattern), initializer(initializer),
544           is_rest(is_rest) {}
545     const AstRawString* name;
546     Expression* pattern;
547     Expression* initializer;
548     bool is_rest;
549     bool is_simple() const {
550       return pattern->IsVariableProxy() && initializer == nullptr && !is_rest;
551     }
552   };
553
554   explicit ParserFormalParameters(Scope* scope)
555       : FormalParametersBase(scope), params(4, scope->zone()) {}
556   ZoneList<Parameter> params;
557
558   int Arity() const { return params.length(); }
559   const Parameter& at(int i) const { return params[i]; }
560 };
561
562
563 class ParserTraits {
564  public:
565   struct Type {
566     // TODO(marja): To be removed. The Traits object should contain all the data
567     // it needs.
568     typedef v8::internal::Parser* Parser;
569
570     typedef Variable GeneratorVariable;
571
572     typedef v8::internal::AstProperties AstProperties;
573
574     // Return types for traversing functions.
575     typedef const AstRawString* Identifier;
576     typedef v8::internal::Expression* Expression;
577     typedef Yield* YieldExpression;
578     typedef v8::internal::FunctionLiteral* FunctionLiteral;
579     typedef v8::internal::ClassLiteral* ClassLiteral;
580     typedef v8::internal::Literal* Literal;
581     typedef ObjectLiteral::Property* ObjectLiteralProperty;
582     typedef ZoneList<v8::internal::Expression*>* ExpressionList;
583     typedef ZoneList<ObjectLiteral::Property*>* PropertyList;
584     typedef ParserFormalParameters::Parameter FormalParameter;
585     typedef ParserFormalParameters FormalParameters;
586     typedef ZoneList<v8::internal::Statement*>* StatementList;
587
588     // For constructing objects returned by the traversing functions.
589     typedef AstNodeFactory Factory;
590   };
591
592   explicit ParserTraits(Parser* parser) : parser_(parser) {}
593
594   // Helper functions for recursive descent.
595   bool IsEval(const AstRawString* identifier) const;
596   bool IsArguments(const AstRawString* identifier) const;
597   bool IsEvalOrArguments(const AstRawString* identifier) const;
598   bool IsUndefined(const AstRawString* identifier) const;
599   V8_INLINE bool IsFutureStrictReserved(const AstRawString* identifier) const;
600
601   // Returns true if the expression is of type "this.foo".
602   static bool IsThisProperty(Expression* expression);
603
604   static bool IsIdentifier(Expression* expression);
605
606   bool IsPrototype(const AstRawString* identifier) const;
607
608   bool IsConstructor(const AstRawString* identifier) const;
609
610   static const AstRawString* AsIdentifier(Expression* expression) {
611     DCHECK(IsIdentifier(expression));
612     return expression->AsVariableProxy()->raw_name();
613   }
614
615   static bool IsBoilerplateProperty(ObjectLiteral::Property* property) {
616     return ObjectLiteral::IsBoilerplateProperty(property);
617   }
618
619   static bool IsArrayIndex(const AstRawString* string, uint32_t* index) {
620     return string->AsArrayIndex(index);
621   }
622
623   static Expression* GetPropertyValue(ObjectLiteral::Property* property) {
624     return property->value();
625   }
626
627   // Functions for encapsulating the differences between parsing and preparsing;
628   // operations interleaved with the recursive descent.
629   static void PushLiteralName(FuncNameInferrer* fni, const AstRawString* id) {
630     fni->PushLiteralName(id);
631   }
632
633   void PushPropertyName(FuncNameInferrer* fni, Expression* expression);
634
635   static void InferFunctionName(FuncNameInferrer* fni,
636                                 FunctionLiteral* func_to_infer) {
637     fni->AddFunction(func_to_infer);
638   }
639
640   static void CheckFunctionLiteralInsideTopLevelObjectLiteral(
641       Scope* scope, ObjectLiteralProperty* property, bool* has_function) {
642     Expression* value = property->value();
643     if (scope->DeclarationScope()->is_script_scope() &&
644         value->AsFunctionLiteral() != NULL) {
645       *has_function = true;
646       value->AsFunctionLiteral()->set_pretenure();
647     }
648   }
649
650   // If we assign a function literal to a property we pretenure the
651   // literal so it can be added as a constant function property.
652   static void CheckAssigningFunctionLiteralToProperty(Expression* left,
653                                                       Expression* right);
654
655   // Keep track of eval() calls since they disable all local variable
656   // optimizations. This checks if expression is an eval call, and if yes,
657   // forwards the information to scope.
658   void CheckPossibleEvalCall(Expression* expression, Scope* scope);
659
660   // Determine if the expression is a variable proxy and mark it as being used
661   // in an assignment or with a increment/decrement operator.
662   static Expression* MarkExpressionAsAssigned(Expression* expression);
663
664   // Returns true if we have a binary expression between two numeric
665   // literals. In that case, *x will be changed to an expression which is the
666   // computed value.
667   bool ShortcutNumericLiteralBinaryExpression(Expression** x, Expression* y,
668                                               Token::Value op, int pos,
669                                               AstNodeFactory* factory);
670
671   // Rewrites the following types of unary expressions:
672   // not <literal> -> true / false
673   // + <numeric literal> -> <numeric literal>
674   // - <numeric literal> -> <numeric literal with value negated>
675   // ! <literal> -> true / false
676   // The following rewriting rules enable the collection of type feedback
677   // without any special stub and the multiplication is removed later in
678   // Crankshaft's canonicalization pass.
679   // + foo -> foo * 1
680   // - foo -> foo * (-1)
681   // ~ foo -> foo ^(~0)
682   Expression* BuildUnaryExpression(Expression* expression, Token::Value op,
683                                    int pos, AstNodeFactory* factory);
684
685   // Generate AST node that throws a ReferenceError with the given type.
686   Expression* NewThrowReferenceError(MessageTemplate::Template message,
687                                      int pos);
688
689   // Generate AST node that throws a SyntaxError with the given
690   // type. The first argument may be null (in the handle sense) in
691   // which case no arguments are passed to the constructor.
692   Expression* NewThrowSyntaxError(MessageTemplate::Template message,
693                                   const AstRawString* arg, int pos);
694
695   // Generate AST node that throws a TypeError with the given
696   // type. Both arguments must be non-null (in the handle sense).
697   Expression* NewThrowTypeError(MessageTemplate::Template message,
698                                 const AstRawString* arg, int pos);
699
700   // Generic AST generator for throwing errors from compiled code.
701   Expression* NewThrowError(Runtime::FunctionId function_id,
702                             MessageTemplate::Template message,
703                             const AstRawString* arg, int pos);
704
705   // Reporting errors.
706   void ReportMessageAt(Scanner::Location source_location,
707                        MessageTemplate::Template message,
708                        const char* arg = NULL,
709                        ParseErrorType error_type = kSyntaxError);
710   void ReportMessage(MessageTemplate::Template message, const char* arg = NULL,
711                      ParseErrorType error_type = kSyntaxError);
712   void ReportMessage(MessageTemplate::Template message, const AstRawString* arg,
713                      ParseErrorType error_type = kSyntaxError);
714   void ReportMessageAt(Scanner::Location source_location,
715                        MessageTemplate::Template message,
716                        const AstRawString* arg,
717                        ParseErrorType error_type = kSyntaxError);
718
719   // "null" return type creators.
720   static const AstRawString* EmptyIdentifier() {
721     return NULL;
722   }
723   static Expression* EmptyExpression() {
724     return NULL;
725   }
726   static Literal* EmptyLiteral() {
727     return NULL;
728   }
729   static ObjectLiteralProperty* EmptyObjectLiteralProperty() { return NULL; }
730   static FunctionLiteral* EmptyFunctionLiteral() { return NULL; }
731
732   // Used in error return values.
733   static ZoneList<Expression*>* NullExpressionList() {
734     return NULL;
735   }
736   static const AstRawString* EmptyFormalParameter() { return NULL; }
737
738   // Non-NULL empty string.
739   V8_INLINE const AstRawString* EmptyIdentifierString();
740
741   // Odd-ball literal creators.
742   Literal* GetLiteralTheHole(int position, AstNodeFactory* factory);
743
744   // Producing data during the recursive descent.
745   const AstRawString* GetSymbol(Scanner* scanner);
746   const AstRawString* GetNextSymbol(Scanner* scanner);
747   const AstRawString* GetNumberAsSymbol(Scanner* scanner);
748
749   Expression* ThisExpression(Scope* scope, AstNodeFactory* factory,
750                              int pos = RelocInfo::kNoPosition);
751   Expression* SuperPropertyReference(Scope* scope, AstNodeFactory* factory,
752                                      int pos);
753   Expression* SuperCallReference(Scope* scope, AstNodeFactory* factory,
754                                  int pos);
755   Expression* NewTargetExpression(Scope* scope, AstNodeFactory* factory,
756                                   int pos);
757   Expression* DefaultConstructor(bool call_super, Scope* scope, int pos,
758                                  int end_pos, LanguageMode language_mode);
759   Literal* ExpressionFromLiteral(Token::Value token, int pos, Scanner* scanner,
760                                  AstNodeFactory* factory);
761   Expression* ExpressionFromIdentifier(const AstRawString* name,
762                                        int start_position, int end_position,
763                                        Scope* scope, AstNodeFactory* factory);
764   Expression* ExpressionFromString(int pos, Scanner* scanner,
765                                    AstNodeFactory* factory);
766   Expression* GetIterator(Expression* iterable, AstNodeFactory* factory);
767   ZoneList<v8::internal::Expression*>* NewExpressionList(int size, Zone* zone) {
768     return new(zone) ZoneList<v8::internal::Expression*>(size, zone);
769   }
770   ZoneList<ObjectLiteral::Property*>* NewPropertyList(int size, Zone* zone) {
771     return new(zone) ZoneList<ObjectLiteral::Property*>(size, zone);
772   }
773   ZoneList<v8::internal::Statement*>* NewStatementList(int size, Zone* zone) {
774     return new(zone) ZoneList<v8::internal::Statement*>(size, zone);
775   }
776
777   V8_INLINE void AddParameterInitializationBlock(
778       const ParserFormalParameters& parameters,
779       ZoneList<v8::internal::Statement*>* body, bool* ok);
780
781   V8_INLINE Scope* NewScope(Scope* parent_scope, ScopeType scope_type,
782                             FunctionKind kind = kNormalFunction);
783
784   V8_INLINE void AddFormalParameter(
785       ParserFormalParameters* parameters, Expression* pattern,
786       Expression* initializer, bool is_rest);
787   V8_INLINE void DeclareFormalParameter(
788       Scope* scope, const ParserFormalParameters::Parameter& parameter,
789       ExpressionClassifier* classifier);
790   void ParseArrowFunctionFormalParameters(ParserFormalParameters* parameters,
791                                           Expression* params,
792                                           const Scanner::Location& params_loc,
793                                           bool* ok);
794   void ParseArrowFunctionFormalParameterList(
795       ParserFormalParameters* parameters, Expression* params,
796       const Scanner::Location& params_loc,
797       Scanner::Location* duplicate_loc, bool* ok);
798
799   void ReindexLiterals(const ParserFormalParameters& parameters);
800
801   // Temporary glue; these functions will move to ParserBase.
802   Expression* ParseV8Intrinsic(bool* ok);
803   FunctionLiteral* ParseFunctionLiteral(
804       const AstRawString* name, Scanner::Location function_name_location,
805       FunctionNameValidity function_name_validity, FunctionKind kind,
806       int function_token_position, FunctionLiteral::FunctionType type,
807       FunctionLiteral::ArityRestriction arity_restriction,
808       LanguageMode language_mode, bool* ok);
809   V8_INLINE void SkipLazyFunctionBody(
810       int* materialized_literal_count, int* expected_property_count, bool* ok,
811       Scanner::BookmarkScope* bookmark = nullptr);
812   V8_INLINE ZoneList<Statement*>* ParseEagerFunctionBody(
813       const AstRawString* name, int pos,
814       const ParserFormalParameters& parameters, FunctionKind kind,
815       FunctionLiteral::FunctionType function_type, bool* ok);
816
817   ClassLiteral* ParseClassLiteral(const AstRawString* name,
818                                   Scanner::Location class_name_location,
819                                   bool name_is_strict_reserved, int pos,
820                                   bool* ok);
821
822   V8_INLINE void CheckConflictingVarDeclarations(v8::internal::Scope* scope,
823                                                  bool* ok);
824
825   class TemplateLiteral : public ZoneObject {
826    public:
827     TemplateLiteral(Zone* zone, int pos)
828         : cooked_(8, zone), raw_(8, zone), expressions_(8, zone), pos_(pos) {}
829
830     const ZoneList<Expression*>* cooked() const { return &cooked_; }
831     const ZoneList<Expression*>* raw() const { return &raw_; }
832     const ZoneList<Expression*>* expressions() const { return &expressions_; }
833     int position() const { return pos_; }
834
835     void AddTemplateSpan(Literal* cooked, Literal* raw, int end, Zone* zone) {
836       DCHECK_NOT_NULL(cooked);
837       DCHECK_NOT_NULL(raw);
838       cooked_.Add(cooked, zone);
839       raw_.Add(raw, zone);
840     }
841
842     void AddExpression(Expression* expression, Zone* zone) {
843       DCHECK_NOT_NULL(expression);
844       expressions_.Add(expression, zone);
845     }
846
847    private:
848     ZoneList<Expression*> cooked_;
849     ZoneList<Expression*> raw_;
850     ZoneList<Expression*> expressions_;
851     int pos_;
852   };
853
854   typedef TemplateLiteral* TemplateLiteralState;
855
856   V8_INLINE TemplateLiteralState OpenTemplateLiteral(int pos);
857   V8_INLINE void AddTemplateSpan(TemplateLiteralState* state, bool tail);
858   V8_INLINE void AddTemplateExpression(TemplateLiteralState* state,
859                                        Expression* expression);
860   V8_INLINE Expression* CloseTemplateLiteral(TemplateLiteralState* state,
861                                              int start, Expression* tag);
862   V8_INLINE Expression* NoTemplateTag() { return NULL; }
863   V8_INLINE static bool IsTaggedTemplate(const Expression* tag) {
864     return tag != NULL;
865   }
866
867   V8_INLINE ZoneList<v8::internal::Expression*>* PrepareSpreadArguments(
868       ZoneList<v8::internal::Expression*>* list);
869   V8_INLINE void MaterializeUnspreadArgumentsLiterals(int count) {}
870   V8_INLINE Expression* SpreadCall(Expression* function,
871                                    ZoneList<v8::internal::Expression*>* args,
872                                    int pos);
873   V8_INLINE Expression* SpreadCallNew(Expression* function,
874                                       ZoneList<v8::internal::Expression*>* args,
875                                       int pos);
876
877  private:
878   Parser* parser_;
879 };
880
881
882 class Parser : public ParserBase<ParserTraits> {
883  public:
884   explicit Parser(ParseInfo* info);
885   ~Parser() {
886     delete reusable_preparser_;
887     reusable_preparser_ = NULL;
888     delete cached_parse_data_;
889     cached_parse_data_ = NULL;
890   }
891
892   // Parses the source code represented by the compilation info and sets its
893   // function literal.  Returns false (and deallocates any allocated AST
894   // nodes) if parsing failed.
895   static bool ParseStatic(ParseInfo* info);
896   bool Parse(ParseInfo* info);
897   void ParseOnBackground(ParseInfo* info);
898
899   // Handle errors detected during parsing, move statistics to Isolate,
900   // internalize strings (move them to the heap).
901   void Internalize(Isolate* isolate, Handle<Script> script, bool error);
902   void HandleSourceURLComments(Isolate* isolate, Handle<Script> script);
903
904  private:
905   friend class ParserTraits;
906
907   // Limit the allowed number of local variables in a function. The hard limit
908   // is that offsets computed by FullCodeGenerator::StackOperand and similar
909   // functions are ints, and they should not overflow. In addition, accessing
910   // local variables creates user-controlled constants in the generated code,
911   // and we don't want too much user-controlled memory inside the code (this was
912   // the reason why this limit was introduced in the first place; see
913   // https://codereview.chromium.org/7003030/ ).
914   static const int kMaxNumFunctionLocals = 4194303;  // 2^22-1
915
916   // Returns NULL if parsing failed.
917   FunctionLiteral* ParseProgram(Isolate* isolate, ParseInfo* info);
918
919   FunctionLiteral* ParseLazy(Isolate* isolate, ParseInfo* info);
920   FunctionLiteral* ParseLazy(Isolate* isolate, ParseInfo* info,
921                              Utf16CharacterStream* source);
922
923   // Called by ParseProgram after setting up the scanner.
924   FunctionLiteral* DoParseProgram(ParseInfo* info);
925
926   void SetCachedData(ParseInfo* info);
927
928   bool inside_with() const { return scope_->inside_with(); }
929   ScriptCompiler::CompileOptions compile_options() const {
930     return compile_options_;
931   }
932   bool consume_cached_parse_data() const {
933     return compile_options_ == ScriptCompiler::kConsumeParserCache &&
934            cached_parse_data_ != NULL;
935   }
936   bool produce_cached_parse_data() const {
937     return compile_options_ == ScriptCompiler::kProduceParserCache;
938   }
939   Scope* DeclarationScope(VariableMode mode) {
940     return IsLexicalVariableMode(mode)
941         ? scope_ : scope_->DeclarationScope();
942   }
943
944   // All ParseXXX functions take as the last argument an *ok parameter
945   // which is set to false if parsing failed; it is unchanged otherwise.
946   // By making the 'exception handling' explicit, we are forced to check
947   // for failure at the call sites.
948   void* ParseStatementList(ZoneList<Statement*>* body, int end_token, bool* ok);
949   Statement* ParseStatementListItem(bool* ok);
950   void* ParseModuleItemList(ZoneList<Statement*>* body, bool* ok);
951   Statement* ParseModuleItem(bool* ok);
952   const AstRawString* ParseModuleSpecifier(bool* ok);
953   Statement* ParseImportDeclaration(bool* ok);
954   Statement* ParseExportDeclaration(bool* ok);
955   Statement* ParseExportDefault(bool* ok);
956   void* ParseExportClause(ZoneList<const AstRawString*>* export_names,
957                           ZoneList<Scanner::Location>* export_locations,
958                           ZoneList<const AstRawString*>* local_names,
959                           Scanner::Location* reserved_loc, bool* ok);
960   ZoneList<ImportDeclaration*>* ParseNamedImports(int pos, bool* ok);
961   Statement* ParseStatement(ZoneList<const AstRawString*>* labels, bool* ok);
962   Statement* ParseSubStatement(ZoneList<const AstRawString*>* labels, bool* ok);
963   Statement* ParseStatementAsUnlabelled(ZoneList<const AstRawString*>* labels,
964                                    bool* ok);
965   Statement* ParseFunctionDeclaration(ZoneList<const AstRawString*>* names,
966                                       bool* ok);
967   Statement* ParseClassDeclaration(ZoneList<const AstRawString*>* names,
968                                    bool* ok);
969   Statement* ParseNativeDeclaration(bool* ok);
970   Block* ParseBlock(ZoneList<const AstRawString*>* labels, bool* ok);
971   Block* ParseVariableStatement(VariableDeclarationContext var_context,
972                                 ZoneList<const AstRawString*>* names,
973                                 bool* ok);
974
975   struct DeclarationDescriptor {
976     enum Kind { NORMAL, PARAMETER };
977     Parser* parser;
978     Scope* declaration_scope;
979     Scope* scope;
980     Scope* hoist_scope;
981     VariableMode mode;
982     bool is_const;
983     bool needs_init;
984     int declaration_pos;
985     int initialization_pos;
986     Token::Value init_op;
987     Kind declaration_kind;
988   };
989
990   struct DeclarationParsingResult {
991     struct Declaration {
992       Declaration(Expression* pattern, int initializer_position,
993                   Expression* initializer)
994           : pattern(pattern),
995             initializer_position(initializer_position),
996             initializer(initializer) {}
997
998       Expression* pattern;
999       int initializer_position;
1000       Expression* initializer;
1001     };
1002
1003     DeclarationParsingResult()
1004         : declarations(4),
1005           first_initializer_loc(Scanner::Location::invalid()),
1006           bindings_loc(Scanner::Location::invalid()) {}
1007
1008     Block* BuildInitializationBlock(ZoneList<const AstRawString*>* names,
1009                                     bool* ok);
1010     const AstRawString* SingleName() const;
1011
1012     DeclarationDescriptor descriptor;
1013     List<Declaration> declarations;
1014     Scanner::Location first_initializer_loc;
1015     Scanner::Location bindings_loc;
1016   };
1017
1018   class PatternRewriter : private AstVisitor {
1019    public:
1020     static void DeclareAndInitializeVariables(
1021         Block* block, const DeclarationDescriptor* declaration_descriptor,
1022         const DeclarationParsingResult::Declaration* declaration,
1023         ZoneList<const AstRawString*>* names, bool* ok);
1024
1025     void set_initializer_position(int pos) { initializer_position_ = pos; }
1026
1027    private:
1028     PatternRewriter() {}
1029
1030 #define DECLARE_VISIT(type) void Visit##type(v8::internal::type* node) override;
1031     // Visiting functions for AST nodes make this an AstVisitor.
1032     AST_NODE_LIST(DECLARE_VISIT)
1033 #undef DECLARE_VISIT
1034     virtual void Visit(AstNode* node) override;
1035
1036     void RecurseIntoSubpattern(AstNode* pattern, Expression* value) {
1037       Expression* old_value = current_value_;
1038       current_value_ = value;
1039       pattern->Accept(this);
1040       current_value_ = old_value;
1041     }
1042
1043     Variable* CreateTempVar(Expression* value = nullptr);
1044
1045     AstNodeFactory* factory() const { return descriptor_->parser->factory(); }
1046     AstValueFactory* ast_value_factory() const {
1047       return descriptor_->parser->ast_value_factory();
1048     }
1049     bool inside_with() const { return descriptor_->parser->inside_with(); }
1050     Zone* zone() const { return descriptor_->parser->zone(); }
1051
1052     Expression* pattern_;
1053     int initializer_position_;
1054     Block* block_;
1055     const DeclarationDescriptor* descriptor_;
1056     ZoneList<const AstRawString*>* names_;
1057     Expression* current_value_;
1058     bool* ok_;
1059   };
1060
1061
1062   void ParseVariableDeclarations(VariableDeclarationContext var_context,
1063                                  DeclarationParsingResult* parsing_result,
1064                                  bool* ok);
1065   Statement* ParseExpressionOrLabelledStatement(
1066       ZoneList<const AstRawString*>* labels, bool* ok);
1067   IfStatement* ParseIfStatement(ZoneList<const AstRawString*>* labels,
1068                                 bool* ok);
1069   Statement* ParseContinueStatement(bool* ok);
1070   Statement* ParseBreakStatement(ZoneList<const AstRawString*>* labels,
1071                                  bool* ok);
1072   Statement* ParseReturnStatement(bool* ok);
1073   Statement* ParseWithStatement(ZoneList<const AstRawString*>* labels,
1074                                 bool* ok);
1075   CaseClause* ParseCaseClause(bool* default_seen_ptr, bool* ok);
1076   Statement* ParseSwitchStatement(ZoneList<const AstRawString*>* labels,
1077                                   bool* ok);
1078   DoWhileStatement* ParseDoWhileStatement(ZoneList<const AstRawString*>* labels,
1079                                           bool* ok);
1080   WhileStatement* ParseWhileStatement(ZoneList<const AstRawString*>* labels,
1081                                       bool* ok);
1082   Statement* ParseForStatement(ZoneList<const AstRawString*>* labels, bool* ok);
1083   Statement* ParseThrowStatement(bool* ok);
1084   Expression* MakeCatchContext(Handle<String> id, VariableProxy* value);
1085   TryStatement* ParseTryStatement(bool* ok);
1086   DebuggerStatement* ParseDebuggerStatement(bool* ok);
1087
1088   // Support for hamony block scoped bindings.
1089   Block* ParseScopedBlock(ZoneList<const AstRawString*>* labels, bool* ok);
1090
1091   // !%_IsSpecObject(result = iterator.next()) &&
1092   //     %ThrowIteratorResultNotAnObject(result)
1093   Expression* BuildIteratorNextResult(Expression* iterator, Variable* result,
1094                                       int pos);
1095
1096
1097   // Initialize the components of a for-in / for-of statement.
1098   void InitializeForEachStatement(ForEachStatement* stmt,
1099                                   Expression* each,
1100                                   Expression* subject,
1101                                   Statement* body);
1102   Statement* DesugarLexicalBindingsInForStatement(
1103       Scope* inner_scope, bool is_const, ZoneList<const AstRawString*>* names,
1104       ForStatement* loop, Statement* init, Expression* cond, Statement* next,
1105       Statement* body, bool* ok);
1106
1107   FunctionLiteral* ParseFunctionLiteral(
1108       const AstRawString* name, Scanner::Location function_name_location,
1109       FunctionNameValidity function_name_validity, FunctionKind kind,
1110       int function_token_position, FunctionLiteral::FunctionType type,
1111       FunctionLiteral::ArityRestriction arity_restriction,
1112       LanguageMode language_mode, bool* ok);
1113
1114
1115   ClassLiteral* ParseClassLiteral(const AstRawString* name,
1116                                   Scanner::Location class_name_location,
1117                                   bool name_is_strict_reserved, int pos,
1118                                   bool* ok);
1119
1120   // Magical syntax support.
1121   Expression* ParseV8Intrinsic(bool* ok);
1122
1123   // Get odd-ball literals.
1124   Literal* GetLiteralUndefined(int position);
1125
1126   // For harmony block scoping mode: Check if the scope has conflicting var/let
1127   // declarations from different scopes. It covers for example
1128   //
1129   // function f() { { { var x; } let x; } }
1130   // function g() { { var x; let x; } }
1131   //
1132   // The var declarations are hoisted to the function scope, but originate from
1133   // a scope where the name has also been let bound or the var declaration is
1134   // hoisted over such a scope.
1135   void CheckConflictingVarDeclarations(Scope* scope, bool* ok);
1136
1137   // Implement sloppy block-scoped functions, ES2015 Annex B 3.3
1138   void InsertSloppyBlockFunctionVarBindings(Scope* scope, bool* ok);
1139
1140   // Parser support
1141   VariableProxy* NewUnresolved(const AstRawString* name, VariableMode mode);
1142   Variable* Declare(Declaration* declaration,
1143                     DeclarationDescriptor::Kind declaration_kind, bool resolve,
1144                     bool* ok, Scope* declaration_scope = nullptr);
1145
1146   bool TargetStackContainsLabel(const AstRawString* label);
1147   BreakableStatement* LookupBreakTarget(const AstRawString* label, bool* ok);
1148   IterationStatement* LookupContinueTarget(const AstRawString* label, bool* ok);
1149
1150   void AddAssertIsConstruct(ZoneList<Statement*>* body, int pos);
1151   Statement* BuildAssertIsCoercible(Variable* var);
1152
1153   // Factory methods.
1154   FunctionLiteral* DefaultConstructor(bool call_super, Scope* scope, int pos,
1155                                       int end_pos, LanguageMode language_mode);
1156
1157   // Skip over a lazy function, either using cached data if we have it, or
1158   // by parsing the function with PreParser. Consumes the ending }.
1159   //
1160   // If bookmark is set, the (pre-)parser may decide to abort skipping
1161   // in order to force the function to be eagerly parsed, after all.
1162   // In this case, it'll reset the scanner using the bookmark.
1163   void SkipLazyFunctionBody(int* materialized_literal_count,
1164                             int* expected_property_count, bool* ok,
1165                             Scanner::BookmarkScope* bookmark = nullptr);
1166
1167   PreParser::PreParseResult ParseLazyFunctionBodyWithPreParser(
1168       SingletonLogger* logger, Scanner::BookmarkScope* bookmark = nullptr);
1169
1170   Block* BuildParameterInitializationBlock(
1171       const ParserFormalParameters& parameters, bool* ok);
1172
1173   // Consumes the ending }.
1174   ZoneList<Statement*>* ParseEagerFunctionBody(
1175       const AstRawString* function_name, int pos,
1176       const ParserFormalParameters& parameters, FunctionKind kind,
1177       FunctionLiteral::FunctionType function_type, bool* ok);
1178
1179   void ThrowPendingError(Isolate* isolate, Handle<Script> script);
1180
1181   TemplateLiteralState OpenTemplateLiteral(int pos);
1182   void AddTemplateSpan(TemplateLiteralState* state, bool tail);
1183   void AddTemplateExpression(TemplateLiteralState* state,
1184                              Expression* expression);
1185   Expression* CloseTemplateLiteral(TemplateLiteralState* state, int start,
1186                                    Expression* tag);
1187   uint32_t ComputeTemplateLiteralHash(const TemplateLiteral* lit);
1188
1189   ZoneList<v8::internal::Expression*>* PrepareSpreadArguments(
1190       ZoneList<v8::internal::Expression*>* list);
1191   Expression* SpreadCall(Expression* function,
1192                          ZoneList<v8::internal::Expression*>* args, int pos);
1193   Expression* SpreadCallNew(Expression* function,
1194                             ZoneList<v8::internal::Expression*>* args, int pos);
1195
1196   Scanner scanner_;
1197   PreParser* reusable_preparser_;
1198   Scope* original_scope_;  // for ES5 function declarations in sloppy eval
1199   Target* target_stack_;  // for break, continue statements
1200   ScriptCompiler::CompileOptions compile_options_;
1201   ParseData* cached_parse_data_;
1202
1203   PendingCompilationErrorHandler pending_error_handler_;
1204
1205   // Other information which will be stored in Parser and moved to Isolate after
1206   // parsing.
1207   int use_counts_[v8::Isolate::kUseCounterFeatureCount];
1208   int total_preparse_skipped_;
1209   HistogramTimer* pre_parse_timer_;
1210
1211   bool parsing_on_main_thread_;
1212 };
1213
1214
1215 bool ParserTraits::IsFutureStrictReserved(
1216     const AstRawString* identifier) const {
1217   return parser_->scanner()->IdentifierIsFutureStrictReserved(identifier);
1218 }
1219
1220
1221 Scope* ParserTraits::NewScope(Scope* parent_scope, ScopeType scope_type,
1222                               FunctionKind kind) {
1223   return parser_->NewScope(parent_scope, scope_type, kind);
1224 }
1225
1226
1227 const AstRawString* ParserTraits::EmptyIdentifierString() {
1228   return parser_->ast_value_factory()->empty_string();
1229 }
1230
1231
1232 void ParserTraits::SkipLazyFunctionBody(int* materialized_literal_count,
1233                                         int* expected_property_count, bool* ok,
1234                                         Scanner::BookmarkScope* bookmark) {
1235   return parser_->SkipLazyFunctionBody(materialized_literal_count,
1236                                        expected_property_count, ok, bookmark);
1237 }
1238
1239
1240 ZoneList<Statement*>* ParserTraits::ParseEagerFunctionBody(
1241     const AstRawString* name, int pos, const ParserFormalParameters& parameters,
1242     FunctionKind kind, FunctionLiteral::FunctionType function_type, bool* ok) {
1243   return parser_->ParseEagerFunctionBody(name, pos, parameters, kind,
1244                                          function_type, ok);
1245 }
1246
1247 void ParserTraits::CheckConflictingVarDeclarations(v8::internal::Scope* scope,
1248                                                    bool* ok) {
1249   parser_->CheckConflictingVarDeclarations(scope, ok);
1250 }
1251
1252
1253 // Support for handling complex values (array and object literals) that
1254 // can be fully handled at compile time.
1255 class CompileTimeValue: public AllStatic {
1256  public:
1257   enum LiteralType {
1258     OBJECT_LITERAL_FAST_ELEMENTS,
1259     OBJECT_LITERAL_SLOW_ELEMENTS,
1260     ARRAY_LITERAL
1261   };
1262
1263   static bool IsCompileTimeValue(Expression* expression);
1264
1265   // Get the value as a compile time value.
1266   static Handle<FixedArray> GetValue(Isolate* isolate, Expression* expression);
1267
1268   // Get the type of a compile time value returned by GetValue().
1269   static LiteralType GetLiteralType(Handle<FixedArray> value);
1270
1271   // Get the elements array of a compile time value returned by GetValue().
1272   static Handle<FixedArray> GetElements(Handle<FixedArray> value);
1273
1274  private:
1275   static const int kLiteralTypeSlot = 0;
1276   static const int kElementsSlot = 1;
1277
1278   DISALLOW_IMPLICIT_CONSTRUCTORS(CompileTimeValue);
1279 };
1280
1281
1282 ParserTraits::TemplateLiteralState ParserTraits::OpenTemplateLiteral(int pos) {
1283   return parser_->OpenTemplateLiteral(pos);
1284 }
1285
1286
1287 void ParserTraits::AddTemplateSpan(TemplateLiteralState* state, bool tail) {
1288   parser_->AddTemplateSpan(state, tail);
1289 }
1290
1291
1292 void ParserTraits::AddTemplateExpression(TemplateLiteralState* state,
1293                                          Expression* expression) {
1294   parser_->AddTemplateExpression(state, expression);
1295 }
1296
1297
1298 Expression* ParserTraits::CloseTemplateLiteral(TemplateLiteralState* state,
1299                                                int start, Expression* tag) {
1300   return parser_->CloseTemplateLiteral(state, start, tag);
1301 }
1302
1303
1304 ZoneList<v8::internal::Expression*>* ParserTraits::PrepareSpreadArguments(
1305     ZoneList<v8::internal::Expression*>* list) {
1306   return parser_->PrepareSpreadArguments(list);
1307 }
1308
1309
1310 Expression* ParserTraits::SpreadCall(Expression* function,
1311                                      ZoneList<v8::internal::Expression*>* args,
1312                                      int pos) {
1313   return parser_->SpreadCall(function, args, pos);
1314 }
1315
1316
1317 Expression* ParserTraits::SpreadCallNew(
1318     Expression* function, ZoneList<v8::internal::Expression*>* args, int pos) {
1319   return parser_->SpreadCallNew(function, args, pos);
1320 }
1321
1322
1323 void ParserTraits::AddFormalParameter(
1324     ParserFormalParameters* parameters,
1325     Expression* pattern, Expression* initializer, bool is_rest) {
1326   bool is_simple =
1327       !is_rest && pattern->IsVariableProxy() && initializer == nullptr;
1328   DCHECK(parser_->allow_harmony_destructuring() ||
1329          parser_->allow_harmony_rest_parameters() ||
1330          parser_->allow_harmony_default_parameters() || is_simple);
1331   const AstRawString* name = is_simple
1332                                  ? pattern->AsVariableProxy()->raw_name()
1333                                  : parser_->ast_value_factory()->empty_string();
1334   parameters->params.Add(
1335       ParserFormalParameters::Parameter(name, pattern, initializer, is_rest),
1336       parameters->scope->zone());
1337 }
1338
1339
1340 void ParserTraits::DeclareFormalParameter(
1341     Scope* scope, const ParserFormalParameters::Parameter& parameter,
1342     ExpressionClassifier* classifier) {
1343   bool is_duplicate = false;
1344   bool is_simple = classifier->is_simple_parameter_list();
1345   auto name = parameter.name;
1346   auto mode = is_simple ? VAR : TEMPORARY;
1347   if (!is_simple) scope->SetHasNonSimpleParameters();
1348   bool is_optional = parameter.initializer != nullptr;
1349   Variable* var = scope->DeclareParameter(
1350       name, mode, is_optional, parameter.is_rest, &is_duplicate);
1351   if (is_duplicate) {
1352     classifier->RecordDuplicateFormalParameterError(
1353         parser_->scanner()->location());
1354   }
1355   if (is_sloppy(scope->language_mode())) {
1356     // TODO(sigurds) Mark every parameter as maybe assigned. This is a
1357     // conservative approximation necessary to account for parameters
1358     // that are assigned via the arguments array.
1359     var->set_maybe_assigned();
1360   }
1361 }
1362
1363
1364 void ParserTraits::AddParameterInitializationBlock(
1365     const ParserFormalParameters& parameters,
1366     ZoneList<v8::internal::Statement*>* body, bool* ok) {
1367   if (!parameters.is_simple) {
1368     auto* init_block =
1369         parser_->BuildParameterInitializationBlock(parameters, ok);
1370     if (!*ok) return;
1371     if (init_block != nullptr) {
1372       body->Add(init_block, parser_->zone());
1373     }
1374   }
1375 }
1376 }  // namespace internal
1377 }  // namespace v8
1378
1379 #endif  // V8_PARSER_H_