blob: 174b983938246b7d43c45310cbd9faa6ee3f5b1b [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)
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000056 FLAG_ACCESSOR(kNative, is_native, set_native)
57 FLAG_ACCESSOR(kModule, is_module, set_module)
58 FLAG_ACCESSOR(kAllowLazyParsing, allow_lazy_parsing, set_allow_lazy_parsing)
59 FLAG_ACCESSOR(kAstValueFactoryOwned, ast_value_factory_owned,
60 set_ast_value_factory_owned)
61
62#undef FLAG_ACCESSOR
63
64 void set_parse_restriction(ParseRestriction restriction) {
65 SetFlag(kParseRestriction, restriction != NO_PARSE_RESTRICTION);
66 }
67
68 ParseRestriction parse_restriction() const {
69 return GetFlag(kParseRestriction) ? ONLY_SINGLE_FUNCTION_LITERAL
70 : NO_PARSE_RESTRICTION;
71 }
72
73 ScriptCompiler::ExternalSourceStream* source_stream() {
74 return source_stream_;
75 }
76 void set_source_stream(ScriptCompiler::ExternalSourceStream* source_stream) {
77 source_stream_ = source_stream;
78 }
79
80 ScriptCompiler::StreamedSource::Encoding source_stream_encoding() {
81 return source_stream_encoding_;
82 }
83 void set_source_stream_encoding(
84 ScriptCompiler::StreamedSource::Encoding source_stream_encoding) {
85 source_stream_encoding_ = source_stream_encoding;
86 }
87
88 v8::Extension* extension() { return extension_; }
89 void set_extension(v8::Extension* extension) { extension_ = extension; }
90
91 ScriptData** cached_data() { return cached_data_; }
92 void set_cached_data(ScriptData** cached_data) { cached_data_ = cached_data; }
93
94 ScriptCompiler::CompileOptions compile_options() { return compile_options_; }
95 void set_compile_options(ScriptCompiler::CompileOptions compile_options) {
96 compile_options_ = compile_options;
97 }
98
99 Scope* script_scope() { return script_scope_; }
100 void set_script_scope(Scope* script_scope) { script_scope_ = script_scope; }
101
102 AstValueFactory* ast_value_factory() { return ast_value_factory_; }
103 void set_ast_value_factory(AstValueFactory* ast_value_factory) {
104 ast_value_factory_ = ast_value_factory;
105 }
106
107 FunctionLiteral* literal() { return literal_; }
108 void set_literal(FunctionLiteral* literal) { literal_ = literal; }
109
110 Scope* scope() { return scope_; }
111 void set_scope(Scope* scope) { scope_ = scope; }
112
113 UnicodeCache* unicode_cache() { return unicode_cache_; }
114 void set_unicode_cache(UnicodeCache* unicode_cache) {
115 unicode_cache_ = unicode_cache;
116 }
117
118 uintptr_t stack_limit() { return stack_limit_; }
119 void set_stack_limit(uintptr_t stack_limit) { stack_limit_ = stack_limit; }
120
121 uint32_t hash_seed() { return hash_seed_; }
122 void set_hash_seed(uint32_t hash_seed) { hash_seed_ = hash_seed; }
123
124 //--------------------------------------------------------------------------
125 // TODO(titzer): these should not be part of ParseInfo.
126 //--------------------------------------------------------------------------
127 Isolate* isolate() { return isolate_; }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000128 Handle<SharedFunctionInfo> shared_info() { return shared_; }
129 Handle<Script> script() { return script_; }
130 Handle<Context> context() { return context_; }
131 void clear_script() { script_ = Handle<Script>::null(); }
132 void set_isolate(Isolate* isolate) { isolate_ = isolate; }
Ben Murdochda12d292016-06-02 14:46:10 +0100133 void set_shared_info(Handle<SharedFunctionInfo> shared) { shared_ = shared; }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000134 void set_context(Handle<Context> context) { context_ = context; }
135 void set_script(Handle<Script> script) { script_ = script; }
136 //--------------------------------------------------------------------------
137
138 LanguageMode language_mode() {
Ben Murdochda12d292016-06-02 14:46:10 +0100139 return construct_language_mode(is_strict_mode());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000140 }
141 void set_language_mode(LanguageMode language_mode) {
142 STATIC_ASSERT(LANGUAGE_END == 3);
Ben Murdochda12d292016-06-02 14:46:10 +0100143 set_strict_mode(is_strict(language_mode));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000144 }
145
146 void ReopenHandlesInNewHandleScope() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000147 shared_ = Handle<SharedFunctionInfo>(*shared_);
148 script_ = Handle<Script>(*script_);
149 context_ = Handle<Context>(*context_);
150 }
151
152#ifdef DEBUG
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,
Ben Murdochda12d292016-06-02 14:46:10 +0100165 kNative = 1 << 5,
166 kParseRestriction = 1 << 6,
167 kModule = 1 << 7,
168 kAllowLazyParsing = 1 << 8,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000169 // ---------- Output flags --------------------------
Ben Murdochda12d292016-06-02 14:46:10 +0100170 kAstValueFactoryOwned = 1 << 9
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000171 };
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_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000187 Handle<SharedFunctionInfo> shared_;
188 Handle<Script> script_;
189 Handle<Context> context_;
190
191 //----------- Inputs+Outputs of parsing and scope analysis -----------------
192 ScriptData** cached_data_; // used if available, populated if requested.
193 AstValueFactory* ast_value_factory_; // used if available, otherwise new.
194
195 //----------- Outputs of parsing and scope analysis ------------------------
196 FunctionLiteral* literal_; // produced by full parser.
197 Scope* scope_; // produced by scope analysis.
198
199 void SetFlag(Flag f) { flags_ |= f; }
200 void SetFlag(Flag f, bool v) { flags_ = v ? flags_ | f : flags_ & ~f; }
201 bool GetFlag(Flag f) const { return (flags_ & f) != 0; }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000202};
203
204class 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
217 explicit FunctionEntry(Vector<unsigned> backing)
218 : backing_(backing) { }
219
220 FunctionEntry() : backing_() { }
221
222 int start_pos() { return backing_[kStartPositionIndex]; }
223 int end_pos() { return backing_[kEndPositionIndex]; }
224 int literal_count() { return backing_[kLiteralCountIndex]; }
225 int property_count() { return backing_[kPropertyCountIndex]; }
226 LanguageMode language_mode() {
227 DCHECK(is_valid_language_mode(backing_[kLanguageModeIndex]));
228 return static_cast<LanguageMode>(backing_[kLanguageModeIndex]);
229 }
230 bool uses_super_property() { return backing_[kUsesSuperPropertyIndex]; }
231 bool calls_eval() { return backing_[kCallsEvalIndex]; }
232
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.
241class ParseData {
242 public:
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
257 unsigned* Data() { // Writable data as unsigned int array.
258 return reinterpret_cast<unsigned*>(const_cast<byte*>(script_data_->data()));
259 }
260
261 void Reject() { script_data_->Reject(); }
262
263 bool rejected() const { return script_data_->rejected(); }
264
265 private:
266 explicit ParseData(ScriptData* script_data) : script_data_(script_data) {}
267
268 bool IsSane();
269 unsigned Magic();
270 unsigned Version();
271 int FunctionsSize();
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
286class Parser;
287class SingletonLogger;
288
289
290struct ParserFormalParameters : FormalParametersBase {
291 struct Parameter {
292 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;
305 bool is_simple() const {
306 return pattern->IsVariableProxy() && initializer == nullptr && !is_rest;
307 }
308 };
309
310 explicit ParserFormalParameters(Scope* scope)
311 : FormalParametersBase(scope), params(4, scope->zone()) {}
312 ZoneList<Parameter> params;
313
314 int Arity() const { return params.length(); }
315 const Parameter& at(int i) const { return params[i]; }
316};
317
318
319class 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
Ben Murdoch097c5b22016-05-18 11:27:45 +0100330 typedef v8::internal::ExpressionClassifier<ParserTraits>
331 ExpressionClassifier;
332
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000333 // 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
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;
Ben Murdochc5610432016-08-08 18:44:38 +0100358 bool IsAwait(const AstRawString* identifier) const;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000359 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
370 static const AstRawString* AsIdentifier(Expression* expression) {
371 DCHECK(IsIdentifier(expression));
372 return expression->AsVariableProxy()->raw_name();
373 }
374
Ben Murdochc5610432016-08-08 18:44:38 +0100375 bool IsDirectEvalCall(Expression* expression) {
376 if (!expression->IsCall()) return false;
377 expression = expression->AsCall()->expression();
378 return IsIdentifier(expression) && IsEval(AsIdentifier(expression));
379 }
380
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000381 static bool IsBoilerplateProperty(ObjectLiteral::Property* property) {
382 return ObjectLiteral::IsBoilerplateProperty(property);
383 }
384
385 static bool IsArrayIndex(const AstRawString* string, uint32_t* index) {
386 return string->AsArrayIndex(index);
387 }
388
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.
395 static void PushLiteralName(FuncNameInferrer* fni, const AstRawString* id) {
396 fni->PushLiteralName(id);
397 }
398
399 void PushPropertyName(FuncNameInferrer* fni, Expression* expression);
400
401 static void InferFunctionName(FuncNameInferrer* fni,
402 FunctionLiteral* func_to_infer) {
403 fni->AddFunction(func_to_infer);
404 }
405
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000406 // 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
Ben Murdochda12d292016-06-02 14:46:10 +0100436 Expression* BuildIteratorResult(Expression* value, bool done);
437
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000438 // 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
Ben Murdochda12d292016-06-02 14:46:10 +0100458 void FinalizeIteratorUse(Variable* completion, Expression* condition,
459 Variable* iter, Block* iterator_use, Block* result);
460
Ben Murdoch097c5b22016-05-18 11:27:45 +0100461 Statement* FinalizeForOfStatement(ForOfStatement* loop, int pos);
462
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000463 // 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.
478 static const AstRawString* EmptyIdentifier() {
479 return NULL;
480 }
481 static Expression* EmptyExpression() {
482 return NULL;
483 }
484 static Literal* EmptyLiteral() {
485 return NULL;
486 }
487 static ObjectLiteralProperty* EmptyObjectLiteralProperty() { return NULL; }
488 static FunctionLiteral* EmptyFunctionLiteral() { return NULL; }
489
490 // Used in error return values.
491 static ZoneList<Expression*>* NullExpressionList() {
492 return NULL;
493 }
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);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100515 Expression* FunctionSentExpression(Scope* scope, AstNodeFactory* factory,
516 int pos);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000517 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);
526 ZoneList<v8::internal::Expression*>* NewExpressionList(int size, Zone* zone) {
527 return new(zone) ZoneList<v8::internal::Expression*>(size, zone);
528 }
529 ZoneList<ObjectLiteral::Property*>* NewPropertyList(int size, Zone* zone) {
530 return new(zone) ZoneList<ObjectLiteral::Property*>(size, zone);
531 }
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,
Ben Murdochc5610432016-08-08 18:44:38 +0100538 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);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000543
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,
Ben Murdoch097c5b22016-05-18 11:27:45 +0100553 Type::ExpressionClassifier* classifier);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000554 void ParseArrowFunctionFormalParameters(ParserFormalParameters* parameters,
Ben Murdochc5610432016-08-08 18:44:38 +0100555 Expression* params, int end_pos,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000556 bool* ok);
557 void ParseArrowFunctionFormalParameterList(
558 ParserFormalParameters* parameters, Expression* params,
559 const Scanner::Location& params_loc,
560 Scanner::Location* duplicate_loc, bool* ok);
561
Ben Murdochc5610432016-08-08 18:44:38 +0100562 V8_INLINE Expression* ParseAsyncFunctionExpression(bool* ok);
563
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000564 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,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000574 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
Ben Murdochda12d292016-06-02 14:46:10 +0100583 ClassLiteral* ParseClassLiteral(Type::ExpressionClassifier* classifier,
584 const AstRawString* name,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000585 Scanner::Location class_name_location,
586 bool name_is_strict_reserved, int pos,
587 bool* ok);
588
Ben Murdochc5610432016-08-08 18:44:38 +0100589 V8_INLINE void MarkCollectedTailCallExpressions();
Ben Murdochda12d292016-06-02 14:46:10 +0100590 V8_INLINE void MarkTailPosition(Expression* expression);
591
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000592 V8_INLINE void CheckConflictingVarDeclarations(v8::internal::Scope* scope,
593 bool* ok);
594
595 class TemplateLiteral : public ZoneObject {
596 public:
597 TemplateLiteral(Zone* zone, int pos)
598 : cooked_(8, zone), raw_(8, zone), expressions_(8, zone), pos_(pos) {}
599
600 const ZoneList<Expression*>* cooked() const { return &cooked_; }
601 const ZoneList<Expression*>* raw() const { return &raw_; }
602 const ZoneList<Expression*>* expressions() const { return &expressions_; }
603 int position() const { return pos_; }
604
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
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);
632 V8_INLINE Expression* NoTemplateTag() { return NULL; }
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);
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
Ben Murdochc5610432016-08-08 18:44:38 +0100647 Expression* ExpressionListToExpression(ZoneList<Expression*>* args);
648
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000649 // Rewrite all DestructuringAssignments in the current FunctionState.
650 V8_INLINE void RewriteDestructuringAssignments();
651
Ben Murdochda12d292016-06-02 14:46:10 +0100652 V8_INLINE Expression* RewriteExponentiation(Expression* left,
653 Expression* right, int pos);
654 V8_INLINE Expression* RewriteAssignExponentiation(Expression* left,
655 Expression* right, int pos);
656
Ben Murdochc5610432016-08-08 18:44:38 +0100657 V8_INLINE Expression* RewriteAwaitExpression(Expression* value, int pos);
658
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000659 V8_INLINE void QueueDestructuringAssignmentForRewriting(
660 Expression* assignment);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100661 V8_INLINE void QueueNonPatternForRewriting(Expression* expr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000662
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
Ben Murdoch097c5b22016-05-18 11:27:45 +0100670 V8_INLINE void RewriteNonPattern(Type::ExpressionClassifier* classifier,
671 bool* ok);
672
673 V8_INLINE Zone* zone() const;
674
675 V8_INLINE ZoneList<Expression*>* GetNonPatternList() const;
676
677 Expression* RewriteYieldStar(
678 Expression* generator, Expression* expression, int pos);
679
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000680 private:
681 Parser* parser_;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100682
Ben Murdochda12d292016-06-02 14:46:10 +0100683 void BuildIteratorClose(ZoneList<Statement*>* statements, Variable* iterator,
Ben Murdochc5610432016-08-08 18:44:38 +0100684 Variable* input, Variable* output);
685 void BuildIteratorCloseForCompletion(ZoneList<Statement*>* statements,
686 Variable* iterator,
687 Expression* completion);
Ben Murdochda12d292016-06-02 14:46:10 +0100688 Statement* CheckCallable(Variable* var, Expression* error, int pos);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000689};
690
691
692class Parser : public ParserBase<ParserTraits> {
693 public:
694 explicit Parser(ParseInfo* info);
695 ~Parser() {
696 delete reusable_preparser_;
697 reusable_preparser_ = NULL;
698 delete cached_parse_data_;
699 cached_parse_data_ = NULL;
700 }
701
702 // Parses the source code represented by the compilation info and sets its
703 // function literal. Returns false (and deallocates any allocated AST
704 // nodes) if parsing failed.
705 static bool ParseStatic(ParseInfo* info);
706 bool Parse(ParseInfo* info);
707 void ParseOnBackground(ParseInfo* info);
708
709 // Handle errors detected during parsing, move statistics to Isolate,
710 // internalize strings (move them to the heap).
711 void Internalize(Isolate* isolate, Handle<Script> script, bool error);
712 void HandleSourceURLComments(Isolate* isolate, Handle<Script> script);
713
714 private:
715 friend class ParserTraits;
716
Ben Murdochda12d292016-06-02 14:46:10 +0100717 // Runtime encoding of different completion modes.
718 enum CompletionKind {
719 kNormalCompletion,
720 kThrowCompletion,
721 kAbruptCompletion
722 };
723
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000724 // Limit the allowed number of local variables in a function. The hard limit
725 // is that offsets computed by FullCodeGenerator::StackOperand and similar
726 // functions are ints, and they should not overflow. In addition, accessing
727 // local variables creates user-controlled constants in the generated code,
728 // and we don't want too much user-controlled memory inside the code (this was
729 // the reason why this limit was introduced in the first place; see
730 // https://codereview.chromium.org/7003030/ ).
731 static const int kMaxNumFunctionLocals = 4194303; // 2^22-1
732
733 // Returns NULL if parsing failed.
734 FunctionLiteral* ParseProgram(Isolate* isolate, ParseInfo* info);
735
736 FunctionLiteral* ParseLazy(Isolate* isolate, ParseInfo* info);
737 FunctionLiteral* ParseLazy(Isolate* isolate, ParseInfo* info,
738 Utf16CharacterStream* source);
739
740 // Called by ParseProgram after setting up the scanner.
741 FunctionLiteral* DoParseProgram(ParseInfo* info);
742
743 void SetCachedData(ParseInfo* info);
744
745 ScriptCompiler::CompileOptions compile_options() const {
746 return compile_options_;
747 }
748 bool consume_cached_parse_data() const {
749 return compile_options_ == ScriptCompiler::kConsumeParserCache &&
750 cached_parse_data_ != NULL;
751 }
752 bool produce_cached_parse_data() const {
753 return compile_options_ == ScriptCompiler::kProduceParserCache;
754 }
755
756 // All ParseXXX functions take as the last argument an *ok parameter
757 // which is set to false if parsing failed; it is unchanged otherwise.
758 // By making the 'exception handling' explicit, we are forced to check
759 // for failure at the call sites.
760 void* ParseStatementList(ZoneList<Statement*>* body, int end_token, bool* ok);
761 Statement* ParseStatementListItem(bool* ok);
762 void* ParseModuleItemList(ZoneList<Statement*>* body, bool* ok);
763 Statement* ParseModuleItem(bool* ok);
764 const AstRawString* ParseModuleSpecifier(bool* ok);
765 Statement* ParseImportDeclaration(bool* ok);
766 Statement* ParseExportDeclaration(bool* ok);
767 Statement* ParseExportDefault(bool* ok);
768 void* ParseExportClause(ZoneList<const AstRawString*>* export_names,
769 ZoneList<Scanner::Location>* export_locations,
770 ZoneList<const AstRawString*>* local_names,
771 Scanner::Location* reserved_loc, bool* ok);
772 ZoneList<ImportDeclaration*>* ParseNamedImports(int pos, bool* ok);
Ben Murdochda12d292016-06-02 14:46:10 +0100773 Statement* ParseStatement(ZoneList<const AstRawString*>* labels,
774 AllowLabelledFunctionStatement allow_function,
775 bool* ok);
776 Statement* ParseSubStatement(ZoneList<const AstRawString*>* labels,
777 AllowLabelledFunctionStatement allow_function,
778 bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000779 Statement* ParseStatementAsUnlabelled(ZoneList<const AstRawString*>* labels,
780 bool* ok);
Ben Murdochc5610432016-08-08 18:44:38 +0100781 Statement* ParseFunctionDeclaration(bool* ok);
782 Statement* ParseHoistableDeclaration(ZoneList<const AstRawString*>* names,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000783 bool* ok);
Ben Murdochc5610432016-08-08 18:44:38 +0100784 Statement* ParseHoistableDeclaration(int pos, ParseFunctionFlags flags,
785 ZoneList<const AstRawString*>* names,
786 bool* ok);
787 Statement* ParseAsyncFunctionDeclaration(ZoneList<const AstRawString*>* names,
788 bool* ok);
789 Expression* ParseAsyncFunctionExpression(bool* ok);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100790 Statement* ParseFunctionDeclaration(int pos, bool is_generator,
791 ZoneList<const AstRawString*>* names,
792 bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000793 Statement* ParseClassDeclaration(ZoneList<const AstRawString*>* names,
794 bool* ok);
795 Statement* ParseNativeDeclaration(bool* ok);
796 Block* ParseBlock(ZoneList<const AstRawString*>* labels, bool* ok);
797 Block* ParseBlock(ZoneList<const AstRawString*>* labels,
798 bool finalize_block_scope, bool* ok);
799 Block* ParseVariableStatement(VariableDeclarationContext var_context,
800 ZoneList<const AstRawString*>* names,
801 bool* ok);
802 DoExpression* ParseDoExpression(bool* ok);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100803 Expression* ParseYieldStarExpression(bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000804
805 struct DeclarationDescriptor {
806 enum Kind { NORMAL, PARAMETER };
807 Parser* parser;
808 Scope* scope;
809 Scope* hoist_scope;
810 VariableMode mode;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000811 int declaration_pos;
812 int initialization_pos;
813 Kind declaration_kind;
814 };
815
816 struct DeclarationParsingResult {
817 struct Declaration {
818 Declaration(Expression* pattern, int initializer_position,
819 Expression* initializer)
820 : pattern(pattern),
821 initializer_position(initializer_position),
822 initializer(initializer) {}
823
824 Expression* pattern;
825 int initializer_position;
826 Expression* initializer;
827 };
828
829 DeclarationParsingResult()
830 : declarations(4),
831 first_initializer_loc(Scanner::Location::invalid()),
832 bindings_loc(Scanner::Location::invalid()) {}
833
834 Block* BuildInitializationBlock(ZoneList<const AstRawString*>* names,
835 bool* ok);
836
837 DeclarationDescriptor descriptor;
838 List<Declaration> declarations;
839 Scanner::Location first_initializer_loc;
840 Scanner::Location bindings_loc;
841 };
842
843 class PatternRewriter : private AstVisitor {
844 public:
845 static void DeclareAndInitializeVariables(
846 Block* block, const DeclarationDescriptor* declaration_descriptor,
847 const DeclarationParsingResult::Declaration* declaration,
848 ZoneList<const AstRawString*>* names, bool* ok);
849
Ben Murdoch097c5b22016-05-18 11:27:45 +0100850 static void RewriteDestructuringAssignment(Parser* parser,
851 RewritableExpression* expr,
852 Scope* Scope);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000853
854 static Expression* RewriteDestructuringAssignment(Parser* parser,
855 Assignment* assignment,
856 Scope* scope);
857
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000858 private:
859 PatternRewriter() {}
860
861#define DECLARE_VISIT(type) void Visit##type(v8::internal::type* node) override;
862 // Visiting functions for AST nodes make this an AstVisitor.
863 AST_NODE_LIST(DECLARE_VISIT)
864#undef DECLARE_VISIT
865 void Visit(AstNode* node) override;
866
867 enum PatternContext {
868 BINDING,
869 INITIALIZER,
870 ASSIGNMENT,
871 ASSIGNMENT_INITIALIZER
872 };
873
874 PatternContext context() const { return context_; }
875 void set_context(PatternContext context) { context_ = context; }
876
877 void RecurseIntoSubpattern(AstNode* pattern, Expression* value) {
878 Expression* old_value = current_value_;
879 current_value_ = value;
880 recursion_level_++;
881 pattern->Accept(this);
882 recursion_level_--;
883 current_value_ = old_value;
884 }
885
886 void VisitObjectLiteral(ObjectLiteral* node, Variable** temp_var);
887 void VisitArrayLiteral(ArrayLiteral* node, Variable** temp_var);
888
889 bool IsBindingContext() const { return IsBindingContext(context_); }
890 bool IsInitializerContext() const { return context_ != ASSIGNMENT; }
891 bool IsAssignmentContext() const { return IsAssignmentContext(context_); }
892 bool IsAssignmentContext(PatternContext c) const;
893 bool IsBindingContext(PatternContext c) const;
894 bool IsSubPattern() const { return recursion_level_ > 1; }
895 PatternContext SetAssignmentContextIfNeeded(Expression* node);
896 PatternContext SetInitializerContextIfNeeded(Expression* node);
897
Ben Murdochc5610432016-08-08 18:44:38 +0100898 void RewriteParameterScopes(Expression* expr);
899
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000900 Variable* CreateTempVar(Expression* value = nullptr);
901
902 AstNodeFactory* factory() const { return parser_->factory(); }
903 AstValueFactory* ast_value_factory() const {
904 return parser_->ast_value_factory();
905 }
906 Zone* zone() const { return parser_->zone(); }
907 Scope* scope() const { return scope_; }
908
909 Scope* scope_;
910 Parser* parser_;
911 PatternContext context_;
912 Expression* pattern_;
913 int initializer_position_;
914 Block* block_;
915 const DeclarationDescriptor* descriptor_;
916 ZoneList<const AstRawString*>* names_;
917 Expression* current_value_;
918 int recursion_level_;
919 bool* ok_;
920 };
921
Ben Murdoch097c5b22016-05-18 11:27:45 +0100922 Block* ParseVariableDeclarations(VariableDeclarationContext var_context,
923 DeclarationParsingResult* parsing_result,
924 ZoneList<const AstRawString*>* names,
925 bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000926 Statement* ParseExpressionOrLabelledStatement(
Ben Murdochda12d292016-06-02 14:46:10 +0100927 ZoneList<const AstRawString*>* labels,
928 AllowLabelledFunctionStatement allow_function, bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000929 IfStatement* ParseIfStatement(ZoneList<const AstRawString*>* labels,
930 bool* ok);
931 Statement* ParseContinueStatement(bool* ok);
932 Statement* ParseBreakStatement(ZoneList<const AstRawString*>* labels,
933 bool* ok);
934 Statement* ParseReturnStatement(bool* ok);
935 Statement* ParseWithStatement(ZoneList<const AstRawString*>* labels,
936 bool* ok);
937 CaseClause* ParseCaseClause(bool* default_seen_ptr, bool* ok);
938 Statement* ParseSwitchStatement(ZoneList<const AstRawString*>* labels,
939 bool* ok);
940 DoWhileStatement* ParseDoWhileStatement(ZoneList<const AstRawString*>* labels,
941 bool* ok);
942 WhileStatement* ParseWhileStatement(ZoneList<const AstRawString*>* labels,
943 bool* ok);
944 Statement* ParseForStatement(ZoneList<const AstRawString*>* labels, bool* ok);
945 Statement* ParseThrowStatement(bool* ok);
946 Expression* MakeCatchContext(Handle<String> id, VariableProxy* value);
947 TryStatement* ParseTryStatement(bool* ok);
948 DebuggerStatement* ParseDebuggerStatement(bool* ok);
Ben Murdochda12d292016-06-02 14:46:10 +0100949 // Parse a SubStatement in strict mode, or with an extra block scope in
950 // sloppy mode to handle
951 // ES#sec-functiondeclarations-in-ifstatement-statement-clauses
952 // The legacy parameter indicates whether function declarations are
953 // banned by the ES2015 specification in this location, and they are being
954 // permitted here to match previous V8 behavior.
955 Statement* ParseScopedStatement(ZoneList<const AstRawString*>* labels,
956 bool legacy, bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000957
958 // !%_IsJSReceiver(result = iterator.next()) &&
959 // %ThrowIteratorResultNotAnObject(result)
960 Expression* BuildIteratorNextResult(Expression* iterator, Variable* result,
961 int pos);
962
963
964 // Initialize the components of a for-in / for-of statement.
965 void InitializeForEachStatement(ForEachStatement* stmt, Expression* each,
Ben Murdochc5610432016-08-08 18:44:38 +0100966 Expression* subject, Statement* body,
967 int each_keyword_pos);
Ben Murdochda12d292016-06-02 14:46:10 +0100968 void InitializeForOfStatement(ForOfStatement* stmt, Expression* each,
969 Expression* iterable, Statement* body,
Ben Murdochc5610432016-08-08 18:44:38 +0100970 int next_result_pos = RelocInfo::kNoPosition);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000971 Statement* DesugarLexicalBindingsInForStatement(
Ben Murdoch097c5b22016-05-18 11:27:45 +0100972 Scope* inner_scope, VariableMode mode,
973 ZoneList<const AstRawString*>* names, ForStatement* loop, Statement* init,
974 Expression* cond, Statement* next, Statement* body, bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000975
Ben Murdochc5610432016-08-08 18:44:38 +0100976 void DesugarAsyncFunctionBody(const AstRawString* function_name, Scope* scope,
977 ZoneList<Statement*>* body,
978 Type::ExpressionClassifier* classifier,
979 FunctionKind kind, FunctionBody type,
980 bool accept_IN, int pos, bool* ok);
981
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000982 void RewriteDoExpression(Expression* expr, bool* ok);
983
984 FunctionLiteral* ParseFunctionLiteral(
985 const AstRawString* name, Scanner::Location function_name_location,
986 FunctionNameValidity function_name_validity, FunctionKind kind,
987 int function_token_position, FunctionLiteral::FunctionType type,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000988 LanguageMode language_mode, bool* ok);
989
Ben Murdochda12d292016-06-02 14:46:10 +0100990 ClassLiteral* ParseClassLiteral(ExpressionClassifier* classifier,
991 const AstRawString* name,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000992 Scanner::Location class_name_location,
993 bool name_is_strict_reserved, int pos,
994 bool* ok);
995
996 // Magical syntax support.
997 Expression* ParseV8Intrinsic(bool* ok);
998
999 // Get odd-ball literals.
1000 Literal* GetLiteralUndefined(int position);
1001
1002 // Check if the scope has conflicting var/let declarations from different
1003 // scopes. This covers for example
1004 //
1005 // function f() { { { var x; } let x; } }
1006 // function g() { { var x; let x; } }
1007 //
1008 // The var declarations are hoisted to the function scope, but originate from
1009 // a scope where the name has also been let bound or the var declaration is
1010 // hoisted over such a scope.
1011 void CheckConflictingVarDeclarations(Scope* scope, bool* ok);
1012
1013 // Insert initializer statements for var-bindings shadowing parameter bindings
1014 // from a non-simple parameter list.
1015 void InsertShadowingVarBindingInitializers(Block* block);
1016
1017 // Implement sloppy block-scoped functions, ES2015 Annex B 3.3
1018 void InsertSloppyBlockFunctionVarBindings(Scope* scope, bool* ok);
1019
1020 // Parser support
1021 VariableProxy* NewUnresolved(const AstRawString* name, VariableMode mode);
1022 Variable* Declare(Declaration* declaration,
1023 DeclarationDescriptor::Kind declaration_kind, bool resolve,
1024 bool* ok, Scope* declaration_scope = nullptr);
1025
1026 bool TargetStackContainsLabel(const AstRawString* label);
1027 BreakableStatement* LookupBreakTarget(const AstRawString* label, bool* ok);
1028 IterationStatement* LookupContinueTarget(const AstRawString* label, bool* ok);
1029
1030 Statement* BuildAssertIsCoercible(Variable* var);
1031
1032 // Factory methods.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001033 FunctionLiteral* DefaultConstructor(const AstRawString* name, bool call_super,
1034 Scope* scope, int pos, int end_pos,
1035 LanguageMode language_mode);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001036
1037 // Skip over a lazy function, either using cached data if we have it, or
1038 // by parsing the function with PreParser. Consumes the ending }.
1039 //
1040 // If bookmark is set, the (pre-)parser may decide to abort skipping
1041 // in order to force the function to be eagerly parsed, after all.
1042 // In this case, it'll reset the scanner using the bookmark.
1043 void SkipLazyFunctionBody(int* materialized_literal_count,
1044 int* expected_property_count, bool* ok,
1045 Scanner::BookmarkScope* bookmark = nullptr);
1046
1047 PreParser::PreParseResult ParseLazyFunctionBodyWithPreParser(
1048 SingletonLogger* logger, Scanner::BookmarkScope* bookmark = nullptr);
1049
1050 Block* BuildParameterInitializationBlock(
1051 const ParserFormalParameters& parameters, bool* ok);
Ben Murdochc5610432016-08-08 18:44:38 +01001052 Block* BuildRejectPromiseOnException(Block* block);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001053
1054 // Consumes the ending }.
1055 ZoneList<Statement*>* ParseEagerFunctionBody(
1056 const AstRawString* function_name, int pos,
1057 const ParserFormalParameters& parameters, FunctionKind kind,
1058 FunctionLiteral::FunctionType function_type, bool* ok);
1059
1060 void ThrowPendingError(Isolate* isolate, Handle<Script> script);
1061
1062 TemplateLiteralState OpenTemplateLiteral(int pos);
1063 void AddTemplateSpan(TemplateLiteralState* state, bool tail);
1064 void AddTemplateExpression(TemplateLiteralState* state,
1065 Expression* expression);
1066 Expression* CloseTemplateLiteral(TemplateLiteralState* state, int start,
1067 Expression* tag);
1068 uint32_t ComputeTemplateLiteralHash(const TemplateLiteral* lit);
1069
1070 ZoneList<v8::internal::Expression*>* PrepareSpreadArguments(
1071 ZoneList<v8::internal::Expression*>* list);
1072 Expression* SpreadCall(Expression* function,
1073 ZoneList<v8::internal::Expression*>* args, int pos);
1074 Expression* SpreadCallNew(Expression* function,
1075 ZoneList<v8::internal::Expression*>* args, int pos);
1076
1077 void SetLanguageMode(Scope* scope, LanguageMode mode);
1078 void RaiseLanguageMode(LanguageMode mode);
1079
Ben Murdochc5610432016-08-08 18:44:38 +01001080 V8_INLINE void MarkCollectedTailCallExpressions();
1081
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001082 V8_INLINE void RewriteDestructuringAssignments();
1083
Ben Murdochda12d292016-06-02 14:46:10 +01001084 V8_INLINE Expression* RewriteExponentiation(Expression* left,
1085 Expression* right, int pos);
1086 V8_INLINE Expression* RewriteAssignExponentiation(Expression* left,
1087 Expression* right, int pos);
1088
Ben Murdoch097c5b22016-05-18 11:27:45 +01001089 friend class NonPatternRewriter;
1090 V8_INLINE Expression* RewriteSpreads(ArrayLiteral* lit);
1091
1092 V8_INLINE void RewriteNonPattern(ExpressionClassifier* classifier, bool* ok);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001093
1094 friend class InitializerRewriter;
1095 void RewriteParameterInitializer(Expression* expr, Scope* scope);
1096
Ben Murdochc5610432016-08-08 18:44:38 +01001097 Expression* BuildCreateJSGeneratorObject(int pos, FunctionKind kind);
1098 Expression* BuildPromiseResolve(Expression* value, int pos);
1099 Expression* BuildPromiseReject(Expression* value, int pos);
1100
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001101 Scanner scanner_;
1102 PreParser* reusable_preparser_;
1103 Scope* original_scope_; // for ES5 function declarations in sloppy eval
1104 Target* target_stack_; // for break, continue statements
1105 ScriptCompiler::CompileOptions compile_options_;
1106 ParseData* cached_parse_data_;
1107
1108 PendingCompilationErrorHandler pending_error_handler_;
1109
1110 // Other information which will be stored in Parser and moved to Isolate after
1111 // parsing.
1112 int use_counts_[v8::Isolate::kUseCounterFeatureCount];
1113 int total_preparse_skipped_;
1114 HistogramTimer* pre_parse_timer_;
1115
1116 bool parsing_on_main_thread_;
1117};
1118
1119
1120bool ParserTraits::IsFutureStrictReserved(
1121 const AstRawString* identifier) const {
1122 return parser_->scanner()->IdentifierIsFutureStrictReserved(identifier);
1123}
1124
1125
1126Scope* ParserTraits::NewScope(Scope* parent_scope, ScopeType scope_type,
1127 FunctionKind kind) {
1128 return parser_->NewScope(parent_scope, scope_type, kind);
1129}
1130
1131
1132const AstRawString* ParserTraits::EmptyIdentifierString() {
1133 return parser_->ast_value_factory()->empty_string();
1134}
1135
1136
1137void ParserTraits::SkipLazyFunctionBody(int* materialized_literal_count,
1138 int* expected_property_count, bool* ok,
1139 Scanner::BookmarkScope* bookmark) {
1140 return parser_->SkipLazyFunctionBody(materialized_literal_count,
1141 expected_property_count, ok, bookmark);
1142}
1143
1144
1145ZoneList<Statement*>* ParserTraits::ParseEagerFunctionBody(
1146 const AstRawString* name, int pos, const ParserFormalParameters& parameters,
1147 FunctionKind kind, FunctionLiteral::FunctionType function_type, bool* ok) {
1148 return parser_->ParseEagerFunctionBody(name, pos, parameters, kind,
1149 function_type, ok);
1150}
1151
1152
1153void ParserTraits::CheckConflictingVarDeclarations(v8::internal::Scope* scope,
1154 bool* ok) {
1155 parser_->CheckConflictingVarDeclarations(scope, ok);
1156}
1157
1158
1159// Support for handling complex values (array and object literals) that
1160// can be fully handled at compile time.
1161class CompileTimeValue: public AllStatic {
1162 public:
1163 enum LiteralType {
1164 OBJECT_LITERAL_FAST_ELEMENTS,
1165 OBJECT_LITERAL_SLOW_ELEMENTS,
1166 ARRAY_LITERAL
1167 };
1168
1169 static bool IsCompileTimeValue(Expression* expression);
1170
1171 // Get the value as a compile time value.
1172 static Handle<FixedArray> GetValue(Isolate* isolate, Expression* expression);
1173
1174 // Get the type of a compile time value returned by GetValue().
1175 static LiteralType GetLiteralType(Handle<FixedArray> value);
1176
1177 // Get the elements array of a compile time value returned by GetValue().
1178 static Handle<FixedArray> GetElements(Handle<FixedArray> value);
1179
1180 private:
1181 static const int kLiteralTypeSlot = 0;
1182 static const int kElementsSlot = 1;
1183
1184 DISALLOW_IMPLICIT_CONSTRUCTORS(CompileTimeValue);
1185};
1186
1187
1188ParserTraits::TemplateLiteralState ParserTraits::OpenTemplateLiteral(int pos) {
1189 return parser_->OpenTemplateLiteral(pos);
1190}
1191
1192
1193void ParserTraits::AddTemplateSpan(TemplateLiteralState* state, bool tail) {
1194 parser_->AddTemplateSpan(state, tail);
1195}
1196
1197
1198void ParserTraits::AddTemplateExpression(TemplateLiteralState* state,
1199 Expression* expression) {
1200 parser_->AddTemplateExpression(state, expression);
1201}
1202
1203
1204Expression* ParserTraits::CloseTemplateLiteral(TemplateLiteralState* state,
1205 int start, Expression* tag) {
1206 return parser_->CloseTemplateLiteral(state, start, tag);
1207}
1208
1209
1210ZoneList<v8::internal::Expression*>* ParserTraits::PrepareSpreadArguments(
1211 ZoneList<v8::internal::Expression*>* list) {
1212 return parser_->PrepareSpreadArguments(list);
1213}
1214
1215
1216Expression* ParserTraits::SpreadCall(Expression* function,
1217 ZoneList<v8::internal::Expression*>* args,
1218 int pos) {
1219 return parser_->SpreadCall(function, args, pos);
1220}
1221
1222
1223Expression* ParserTraits::SpreadCallNew(
1224 Expression* function, ZoneList<v8::internal::Expression*>* args, int pos) {
1225 return parser_->SpreadCallNew(function, args, pos);
1226}
1227
1228
1229void ParserTraits::AddFormalParameter(ParserFormalParameters* parameters,
1230 Expression* pattern,
1231 Expression* initializer,
1232 int initializer_end_position,
1233 bool is_rest) {
1234 bool is_simple = pattern->IsVariableProxy() && initializer == nullptr;
1235 const AstRawString* name = is_simple
1236 ? pattern->AsVariableProxy()->raw_name()
1237 : parser_->ast_value_factory()->empty_string();
1238 parameters->params.Add(
1239 ParserFormalParameters::Parameter(name, pattern, initializer,
1240 initializer_end_position, is_rest),
1241 parameters->scope->zone());
1242}
1243
1244
1245void ParserTraits::DeclareFormalParameter(
1246 Scope* scope, const ParserFormalParameters::Parameter& parameter,
Ben Murdoch097c5b22016-05-18 11:27:45 +01001247 Type::ExpressionClassifier* classifier) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001248 bool is_duplicate = false;
1249 bool is_simple = classifier->is_simple_parameter_list();
1250 auto name = is_simple || parameter.is_rest
1251 ? parameter.name
1252 : parser_->ast_value_factory()->empty_string();
1253 auto mode = is_simple || parameter.is_rest ? VAR : TEMPORARY;
1254 if (!is_simple) scope->SetHasNonSimpleParameters();
1255 bool is_optional = parameter.initializer != nullptr;
1256 Variable* var = scope->DeclareParameter(
1257 name, mode, is_optional, parameter.is_rest, &is_duplicate);
1258 if (is_duplicate) {
1259 classifier->RecordDuplicateFormalParameterError(
1260 parser_->scanner()->location());
1261 }
1262 if (is_sloppy(scope->language_mode())) {
1263 // TODO(sigurds) Mark every parameter as maybe assigned. This is a
1264 // conservative approximation necessary to account for parameters
1265 // that are assigned via the arguments array.
1266 var->set_maybe_assigned();
1267 }
1268}
1269
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001270void ParserTraits::AddParameterInitializationBlock(
1271 const ParserFormalParameters& parameters,
Ben Murdochc5610432016-08-08 18:44:38 +01001272 ZoneList<v8::internal::Statement*>* body, bool is_async, bool* ok) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001273 if (!parameters.is_simple) {
1274 auto* init_block =
1275 parser_->BuildParameterInitializationBlock(parameters, ok);
1276 if (!*ok) return;
Ben Murdochc5610432016-08-08 18:44:38 +01001277
1278 if (is_async) {
1279 init_block = parser_->BuildRejectPromiseOnException(init_block);
1280 }
1281
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001282 if (init_block != nullptr) {
1283 body->Add(init_block, parser_->zone());
1284 }
1285 }
1286}
1287
Ben Murdochc5610432016-08-08 18:44:38 +01001288Expression* ParserTraits::ParseAsyncFunctionExpression(bool* ok) {
1289 return parser_->ParseAsyncFunctionExpression(ok);
1290}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001291
1292DoExpression* ParserTraits::ParseDoExpression(bool* ok) {
1293 return parser_->ParseDoExpression(ok);
1294}
1295
1296
1297} // namespace internal
1298} // namespace v8
1299
1300#endif // V8_PARSING_PARSER_H_