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