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