Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(78)

Side by Side Diff: src/ast/scopes.h

Issue 2209573002: Separate Scope into DeclarationScope and Scope (Closed) Base URL: https://chromium.googlesource.com/v8/v8.git@master
Patch Set: Addressed comments Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2012 the V8 project authors. All rights reserved. 1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef V8_AST_SCOPES_H_ 5 #ifndef V8_AST_SCOPES_H_
6 #define V8_AST_SCOPES_H_ 6 #define V8_AST_SCOPES_H_
7 7
8 #include "src/ast/ast.h" 8 #include "src/ast/ast.h"
9 #include "src/base/hashmap.h" 9 #include "src/base/hashmap.h"
10 #include "src/globals.h" 10 #include "src/globals.h"
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
77 77
78 // Global invariants after AST construction: Each reference (i.e. identifier) 78 // Global invariants after AST construction: Each reference (i.e. identifier)
79 // to a JavaScript variable (including global properties) is represented by a 79 // to a JavaScript variable (including global properties) is represented by a
80 // VariableProxy node. Immediately after AST construction and before variable 80 // VariableProxy node. Immediately after AST construction and before variable
81 // allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a 81 // allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
82 // corresponding variable (though some are bound during parse time). Variable 82 // corresponding variable (though some are bound during parse time). Variable
83 // allocation binds each unresolved VariableProxy to one Variable and assigns 83 // allocation binds each unresolved VariableProxy to one Variable and assigns
84 // a location. Note that many VariableProxy nodes may refer to the same Java- 84 // a location. Note that many VariableProxy nodes may refer to the same Java-
85 // Script variable. 85 // Script variable.
86 86
87 class DeclarationScope;
88
87 class Scope: public ZoneObject { 89 class Scope: public ZoneObject {
88 public: 90 public:
89 // --------------------------------------------------------------------------- 91 // ---------------------------------------------------------------------------
90 // Construction 92 // Construction
91 93
92 Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type, 94 Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type);
93 FunctionKind function_kind = kNormalFunction); 95
96 #ifdef DEBUG
97 // The scope name is only used for printing/debugging.
98 void SetScopeName(const AstRawString* scope_name) {
99 scope_name_ = scope_name;
100 }
101 #endif
102
103 // TODO(verwaest): Is this needed on Scope?
104 int num_parameters() const;
105
106 DeclarationScope* AsDeclarationScope();
107 const DeclarationScope* AsDeclarationScope() const;
94 108
95 class Snapshot final BASE_EMBEDDED { 109 class Snapshot final BASE_EMBEDDED {
96 public: 110 public:
97 explicit Snapshot(Scope* scope) 111 explicit Snapshot(Scope* scope);
98 : outer_scope_(scope),
99 top_inner_scope_(scope->inner_scope_),
100 top_unresolved_(scope->unresolved_),
101 top_temp_(scope->ClosureScope()->temps_.length()) {}
102 112
103 void Reparent(Scope* new_parent) const; 113 void Reparent(DeclarationScope* new_parent) const;
104 114
105 private: 115 private:
106 Scope* outer_scope_; 116 Scope* outer_scope_;
107 Scope* top_inner_scope_; 117 Scope* top_inner_scope_;
108 VariableProxy* top_unresolved_; 118 VariableProxy* top_unresolved_;
109 int top_temp_; 119 int top_temp_;
110 }; 120 };
111 121
112 // Compute top scope and allocate variables. For lazy compilation the top 122 // Compute top scope and allocate variables. For lazy compilation the top
113 // scope only contains the single lazily compiled function, so this 123 // scope only contains the single lazily compiled function, so this
114 // doesn't re-allocate variables repeatedly. 124 // doesn't re-allocate variables repeatedly.
115 static bool Analyze(ParseInfo* info); 125 static bool Analyze(ParseInfo* info);
116 126
117 static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone, 127 static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone,
118 Context* context, Scope* script_scope, 128 Context* context, Scope* script_scope,
119 AstValueFactory* ast_value_factory); 129 AstValueFactory* ast_value_factory);
120 130
121 #ifdef DEBUG
122 // The scope name is only used for printing/debugging.
123 void SetScopeName(const AstRawString* scope_name) {
124 scope_name_ = scope_name;
125 }
126 #endif
127
128 void DeclareThis(AstValueFactory* ast_value_factory);
129 void DeclareDefaultFunctionVariables(AstValueFactory* ast_value_factory);
130
131 // Checks if the block scope is redundant, i.e. it does not contain any 131 // Checks if the block scope is redundant, i.e. it does not contain any
132 // block scoped declarations. In that case it is removed from the scope 132 // block scoped declarations. In that case it is removed from the scope
133 // tree and its children are reparented. 133 // tree and its children are reparented.
134 Scope* FinalizeBlockScope(); 134 Scope* FinalizeBlockScope();
135 135
136 // Inserts outer_scope into this scope's scope chain (and removes this 136 // Inserts outer_scope into this scope's scope chain (and removes this
137 // from the current outer_scope_'s inner scope list). 137 // from the current outer_scope_'s inner scope list).
138 // Assumes outer_scope_ is non-null. 138 // Assumes outer_scope_ is non-null.
139 void ReplaceOuterScope(Scope* outer_scope); 139 void ReplaceOuterScope(Scope* outer_scope);
140 140
141 // Propagates any eagerly-gathered scope usage flags (such as calls_eval()) 141 // Propagates any eagerly-gathered scope usage flags (such as calls_eval())
142 // to the passed-in scope. 142 // to the passed-in scope.
143 void PropagateUsageFlagsToScope(Scope* other); 143 void PropagateUsageFlagsToScope(Scope* other);
144 144
145 Zone* zone() const { return variables_.zone(); } 145 Zone* zone() const { return variables_.zone(); }
146 146
147 // --------------------------------------------------------------------------- 147 // ---------------------------------------------------------------------------
148 // Declarations 148 // Declarations
149 149
150 // Lookup a variable in this scope. Returns the variable or NULL if not found. 150 // Lookup a variable in this scope. Returns the variable or NULL if not found.
151 Variable* LookupLocal(const AstRawString* name); 151 Variable* LookupLocal(const AstRawString* name);
152 152
153 // This lookup corresponds to a lookup in the "intermediate" scope sitting
154 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
155 // the name of named function literal is kept in an intermediate scope
156 // in between this scope and the next outer scope.)
157 Variable* LookupFunctionVar(const AstRawString* name,
158 AstNodeFactory* factory);
159
160 // Lookup a variable in this scope or outer scopes. 153 // Lookup a variable in this scope or outer scopes.
161 // Returns the variable or NULL if not found. 154 // Returns the variable or NULL if not found.
162 Variable* Lookup(const AstRawString* name); 155 Variable* Lookup(const AstRawString* name);
163 156
164 // Declare the function variable for a function literal. This variable
165 // is in an intermediate scope between this function scope and the the
166 // outer scope. Only possible for function scopes; at most one variable.
167 void DeclareFunctionVar(VariableDeclaration* declaration) {
168 DCHECK(is_function_scope());
169 // Handle implicit declaration of the function name in named function
170 // expressions before other declarations.
171 decls_.InsertAt(0, declaration, zone());
172 function_ = declaration;
173 }
174
175 // Declare a parameter in this scope. When there are duplicated
176 // parameters the rightmost one 'wins'. However, the implementation
177 // expects all parameters to be declared and from left to right.
178 Variable* DeclareParameter(const AstRawString* name, VariableMode mode,
179 bool is_optional, bool is_rest, bool* is_duplicate,
180 AstValueFactory* ast_value_factory);
181
182 // Declare a local variable in this scope. If the variable has been 157 // Declare a local variable in this scope. If the variable has been
183 // declared before, the previously declared variable is returned. 158 // declared before, the previously declared variable is returned.
184 Variable* DeclareLocal(const AstRawString* name, VariableMode mode, 159 Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
185 InitializationFlag init_flag, Variable::Kind kind, 160 InitializationFlag init_flag, Variable::Kind kind,
186 MaybeAssignedFlag maybe_assigned_flag = kNotAssigned); 161 MaybeAssignedFlag maybe_assigned_flag = kNotAssigned);
187 162
188 // Declare an implicit global variable in this scope which must be a 163 // Declarations list.
189 // script scope. The variable was introduced (possibly from an inner 164 ZoneList<Declaration*>* declarations() { return &decls_; }
marja 2016/08/04 07:58:08 Why is this in Scope, not in DeclarationScope?
190 // scope) by a reference to an unresolved variable with no intervening
191 // with statements or eval calls.
192 Variable* DeclareDynamicGlobal(const AstRawString* name);
193 165
194 // Create a new unresolved variable. 166 // Create a new unresolved variable.
195 VariableProxy* NewUnresolved(AstNodeFactory* factory, 167 VariableProxy* NewUnresolved(AstNodeFactory* factory,
196 const AstRawString* name, 168 const AstRawString* name,
197 Variable::Kind kind = Variable::NORMAL, 169 Variable::Kind kind = Variable::NORMAL,
198 int start_position = kNoSourcePosition, 170 int start_position = kNoSourcePosition,
199 int end_position = kNoSourcePosition) { 171 int end_position = kNoSourcePosition) {
200 // Note that we must not share the unresolved variables with 172 // Note that we must not share the unresolved variables with
201 // the same name because they may be removed selectively via 173 // the same name because they may be removed selectively via
202 // RemoveUnresolved(). 174 // RemoveUnresolved().
(...skipping 19 matching lines...) Expand all
222 // addition introduced a new unresolved variable which may end up being 194 // addition introduced a new unresolved variable which may end up being
223 // allocated globally as a "ghost" variable. RemoveUnresolved removes 195 // allocated globally as a "ghost" variable. RemoveUnresolved removes
224 // such a variable again if it was added; otherwise this is a no-op. 196 // such a variable again if it was added; otherwise this is a no-op.
225 bool RemoveUnresolved(VariableProxy* var); 197 bool RemoveUnresolved(VariableProxy* var);
226 198
227 // Creates a new temporary variable in this scope's TemporaryScope. The 199 // Creates a new temporary variable in this scope's TemporaryScope. The
228 // name is only used for printing and cannot be used to find the variable. 200 // name is only used for printing and cannot be used to find the variable.
229 // In particular, the only way to get hold of the temporary is by keeping the 201 // In particular, the only way to get hold of the temporary is by keeping the
230 // Variable* around. The name should not clash with a legitimate variable 202 // Variable* around. The name should not clash with a legitimate variable
231 // names. 203 // names.
204 // TODO(verwaest): Move to DeclarationScope?
232 Variable* NewTemporary(const AstRawString* name); 205 Variable* NewTemporary(const AstRawString* name);
233 206
234 // Remove a temporary variable. This is for adjusting the scope of
235 // temporaries used when desugaring parameter initializers.
236 // Returns the index at which it was found in this scope, or -1 if
237 // it was not found.
238 int RemoveTemporary(Variable* var);
239
240 // Adds a temporary variable in this scope's TemporaryScope. This is for
241 // adjusting the scope of temporaries used when desugaring parameter
242 // initializers.
243 void AddTemporary(Variable* var) {
244 // Temporaries are only placed in ClosureScopes.
245 DCHECK_EQ(ClosureScope(), this);
246 temps_.Add(var, zone());
247 }
248
249 // Adds the specific declaration node to the list of declarations in 207 // Adds the specific declaration node to the list of declarations in
250 // this scope. The declarations are processed as part of entering 208 // this scope. The declarations are processed as part of entering
251 // the scope; see codegen.cc:ProcessDeclarations. 209 // the scope; see codegen.cc:ProcessDeclarations.
252 void AddDeclaration(Declaration* declaration); 210 void AddDeclaration(Declaration* declaration);
253 211
254 // --------------------------------------------------------------------------- 212 // ---------------------------------------------------------------------------
255 // Illegal redeclaration support. 213 // Illegal redeclaration support.
256 214
257 // Check if the scope has conflicting var 215 // Check if the scope has conflicting var
258 // declarations, i.e. a var declaration that has been hoisted from a nested 216 // declarations, i.e. a var declaration that has been hoisted from a nested
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
348 // Predicates. 306 // Predicates.
349 307
350 // Specific scope types. 308 // Specific scope types.
351 bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; } 309 bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
352 bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; } 310 bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
353 bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; } 311 bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
354 bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; } 312 bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
355 bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; } 313 bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
356 bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; } 314 bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
357 bool is_with_scope() const { return scope_type_ == WITH_SCOPE; } 315 bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
358 bool is_arrow_scope() const {
359 return is_function_scope() && IsArrowFunction(function_kind_);
360 }
361 bool is_declaration_scope() const { return is_declaration_scope_; } 316 bool is_declaration_scope() const { return is_declaration_scope_; }
362 317
363 void set_is_declaration_scope() { is_declaration_scope_ = true; }
364
365 // Information about which scopes calls eval. 318 // Information about which scopes calls eval.
366 bool calls_eval() const { return scope_calls_eval_; } 319 bool calls_eval() const { return scope_calls_eval_; }
367 bool calls_sloppy_eval() const { 320 bool calls_sloppy_eval() const {
368 return scope_calls_eval_ && is_sloppy(language_mode_); 321 return scope_calls_eval_ && is_sloppy(language_mode_);
369 } 322 }
370 bool outer_scope_calls_sloppy_eval() const { 323 bool outer_scope_calls_sloppy_eval() const {
371 return outer_scope_calls_sloppy_eval_; 324 return outer_scope_calls_sloppy_eval_;
372 } 325 }
373 bool asm_module() const { return asm_module_; } 326 bool asm_module() const { return asm_module_; }
374 bool asm_function() const { return asm_function_; } 327 bool asm_function() const { return asm_function_; }
375 328
376 // Is this scope inside a with statement. 329 // Is this scope inside a with statement.
377 bool inside_with() const { return scope_inside_with_; } 330 bool inside_with() const { return scope_inside_with_; }
378 331
379 // Does this scope access "super" property (super.foo). 332 // Does this scope access "super" property (super.foo).
380 bool uses_super_property() const { return scope_uses_super_property_; } 333 bool uses_super_property() const { return scope_uses_super_property_; }
381 // Does this scope have the potential to execute declarations non-linearly? 334 // Does this scope have the potential to execute declarations non-linearly?
382 bool is_nonlinear() const { return scope_nonlinear_; } 335 bool is_nonlinear() const { return scope_nonlinear_; }
383 336
384 // Whether this needs to be represented by a runtime context. 337 // Whether this needs to be represented by a runtime context.
385 bool NeedsContext() const { 338 bool NeedsContext() const {
386 // Catch and module scopes always have heap slots. 339 // Catch and module scopes always have heap slots.
387 DCHECK(!is_catch_scope() || num_heap_slots() > 0); 340 DCHECK(!is_catch_scope() || num_heap_slots() > 0);
388 DCHECK(!is_module_scope() || num_heap_slots() > 0); 341 DCHECK(!is_module_scope() || num_heap_slots() > 0);
389 return is_with_scope() || num_heap_slots() > 0; 342 return is_with_scope() || num_heap_slots() > 0;
390 } 343 }
391 344
392 bool NeedsHomeObject() const {
393 return scope_uses_super_property_ ||
394 ((scope_calls_eval_ || inner_scope_calls_eval_) &&
395 (IsConciseMethod(function_kind()) ||
396 IsAccessorFunction(function_kind()) ||
397 IsClassConstructor(function_kind())));
398 }
399
400 // --------------------------------------------------------------------------- 345 // ---------------------------------------------------------------------------
401 // Accessors. 346 // Accessors.
402 347
403 // The type of this scope. 348 // The type of this scope.
404 ScopeType scope_type() const { return scope_type_; } 349 ScopeType scope_type() const { return scope_type_; }
405 350
406 FunctionKind function_kind() const { return function_kind_; }
407
408 // The language mode of this scope. 351 // The language mode of this scope.
409 LanguageMode language_mode() const { return language_mode_; } 352 LanguageMode language_mode() const { return language_mode_; }
410 353
411 // The variable corresponding to the 'this' value.
412 Variable* receiver() {
413 DCHECK(has_this_declaration());
414 DCHECK_NOT_NULL(receiver_);
415 return receiver_;
416 }
417
418 // TODO(wingo): Add a GLOBAL_SCOPE scope type which will lexically allocate
419 // "this" (and no other variable) on the native context. Script scopes then
420 // will not have a "this" declaration.
421 bool has_this_declaration() const {
422 return (is_function_scope() && !is_arrow_scope()) || is_module_scope();
423 }
424
425 // The variable corresponding to the 'new.target' value.
426 Variable* new_target_var() { return new_target_; }
427
428 // The variable holding the function literal for named function
429 // literals, or NULL. Only valid for function scopes.
430 VariableDeclaration* function() const {
431 DCHECK(is_function_scope());
432 return function_;
433 }
434
435 // Parameters. The left-most parameter has index 0.
436 // Only valid for function scopes.
437 Variable* parameter(int index) const {
438 DCHECK(is_function_scope());
439 return params_[index];
440 }
441
442 // Returns the default function arity excluding default or rest parameters.
443 int default_function_length() const { return arity_; }
444
445 // Returns the number of formal parameters, up to but not including the
446 // rest parameter index (if the function has rest parameters), i.e. it
447 // says 2 for
448 //
449 // function foo(a, b) { ... }
450 //
451 // and
452 //
453 // function foo(a, b, ...c) { ... }
454 //
455 // but for
456 //
457 // function foo(a, b, c = 1) { ... }
458 //
459 // we return 3 here.
460 int num_parameters() const {
461 return has_rest_parameter() ? params_.length() - 1 : params_.length();
462 }
463
464 // A function can have at most one rest parameter. Returns Variable* or NULL.
465 Variable* rest_parameter(int* index) const {
466 *index = rest_index_;
467 if (rest_index_ < 0) return NULL;
468 return rest_parameter_;
469 }
470
471 bool has_rest_parameter() const { return rest_index_ >= 0; }
472
473 bool has_simple_parameters() const {
474 return has_simple_parameters_;
475 }
476
477 // TODO(caitp): manage this state in a better way. PreParser must be able to
478 // communicate that the scope is non-simple, without allocating any parameters
479 // as the Parser does. This is necessary to ensure that TC39's proposed early
480 // error can be reported consistently regardless of whether lazily parsed or
481 // not.
482 void SetHasNonSimpleParameters() {
483 DCHECK(is_function_scope());
484 has_simple_parameters_ = false;
485 }
486
487 // Retrieve `IsSimpleParameterList` of current or outer function.
488 bool HasSimpleParameters() {
489 Scope* scope = ClosureScope();
490 return !scope->is_function_scope() || scope->has_simple_parameters();
491 }
492
493 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
494 Variable* arguments() const {
495 DCHECK(!is_arrow_scope() || arguments_ == nullptr);
496 return arguments_;
497 }
498
499 Variable* this_function_var() const {
500 // This is only used in derived constructors atm.
501 DCHECK(this_function_ == nullptr ||
502 (is_function_scope() && (IsClassConstructor(function_kind()) ||
503 IsConciseMethod(function_kind()) ||
504 IsAccessorFunction(function_kind()))));
505 return this_function_;
506 }
507
508 // Declarations list.
509 ZoneList<Declaration*>* declarations() { return &decls_; }
510
511 // inner_scope() and sibling() together implement the inner scope list of a 354 // inner_scope() and sibling() together implement the inner scope list of a
512 // scope. Inner scope points to the an inner scope of the function, and 355 // scope. Inner scope points to the an inner scope of the function, and
513 // "sibling" points to a next inner scope of the outer scope of this scope. 356 // "sibling" points to a next inner scope of the outer scope of this scope.
514 Scope* inner_scope() const { return inner_scope_; } 357 Scope* inner_scope() const { return inner_scope_; }
515 Scope* sibling() const { return sibling_; } 358 Scope* sibling() const { return sibling_; }
516 359
517 // The scope immediately surrounding this scope, or NULL. 360 // The scope immediately surrounding this scope, or NULL.
518 Scope* outer_scope() const { return outer_scope_; } 361 Scope* outer_scope() const { return outer_scope_; }
519 362
520 // The ModuleDescriptor for this scope; only for module scopes.
521 ModuleDescriptor* module() const { return module_descriptor_; }
522
523 const AstRawString* catch_variable_name() const { 363 const AstRawString* catch_variable_name() const {
524 DCHECK(is_catch_scope()); 364 DCHECK(is_catch_scope());
525 DCHECK_EQ(1, num_var()); 365 DCHECK_EQ(1, num_var());
526 return static_cast<AstRawString*>(variables_.Start()->key); 366 return static_cast<AstRawString*>(variables_.Start()->key);
527 } 367 }
528 368
529 // --------------------------------------------------------------------------- 369 // ---------------------------------------------------------------------------
530 // Variable allocation. 370 // Variable allocation.
531 371
532 // Collect stack and context allocated local variables in this scope. Note 372 // Collect stack and context allocated local variables in this scope. Note
(...skipping 29 matching lines...) Expand all
562 402
563 // The number of contexts between this and scope; zero if this == scope. 403 // The number of contexts between this and scope; zero if this == scope.
564 int ContextChainLength(Scope* scope); 404 int ContextChainLength(Scope* scope);
565 405
566 // The maximum number of nested contexts required for this scope and any inner 406 // The maximum number of nested contexts required for this scope and any inner
567 // scopes. 407 // scopes.
568 int MaxNestedContextChainLength(); 408 int MaxNestedContextChainLength();
569 409
570 // Find the first function, script, eval or (declaration) block scope. This is 410 // Find the first function, script, eval or (declaration) block scope. This is
571 // the scope where var declarations will be hoisted to in the implementation. 411 // the scope where var declarations will be hoisted to in the implementation.
572 Scope* DeclarationScope(); 412 DeclarationScope* GetDeclarationScope();
573 413
574 // Find the first non-block declaration scope. This should be either a script, 414 // Find the first non-block declaration scope. This should be either a script,
575 // function, or eval scope. Same as DeclarationScope(), but skips 415 // function, or eval scope. Same as DeclarationScope(), but skips declaration
576 // declaration "block" scopes. Used for differentiating associated 416 // "block" scopes. Used for differentiating associated function objects (i.e.,
577 // function objects (i.e., the scope for which a function prologue allocates 417 // the scope for which a function prologue allocates a context) or declaring
578 // a context) or declaring temporaries. 418 // temporaries.
579 Scope* ClosureScope(); 419 DeclarationScope* GetClosureScope();
580 420
581 // Find the first (non-arrow) function or script scope. This is where 421 // Find the first (non-arrow) function or script scope. This is where
582 // 'this' is bound, and what determines the function kind. 422 // 'this' is bound, and what determines the function kind.
583 Scope* ReceiverScope(); 423 DeclarationScope* GetReceiverScope();
584 424
585 Handle<ScopeInfo> GetScopeInfo(Isolate* isolate); 425 Handle<ScopeInfo> GetScopeInfo(Isolate* isolate);
586 426
587 Handle<StringSet> CollectNonLocals(Handle<StringSet> non_locals); 427 Handle<StringSet> CollectNonLocals(Handle<StringSet> non_locals);
588 428
589 // --------------------------------------------------------------------------- 429 // ---------------------------------------------------------------------------
590 // Strict mode support. 430 // Strict mode support.
591 bool IsDeclared(const AstRawString* name) { 431 bool IsDeclared(const AstRawString* name) {
592 // During formal parameter list parsing the scope only contains 432 // During formal parameter list parsing the scope only contains
593 // two variables inserted at initialization: "this" and "arguments". 433 // two variables inserted at initialization: "this" and "arguments".
594 // "this" is an invalid parameter name and "arguments" is invalid parameter 434 // "this" is an invalid parameter name and "arguments" is invalid parameter
595 // name in strict mode. Therefore looking up with the map which includes 435 // name in strict mode. Therefore looking up with the map which includes
596 // "this" and "arguments" in addition to all formal parameters is safe. 436 // "this" and "arguments" in addition to all formal parameters is safe.
597 return variables_.Lookup(name) != NULL; 437 return variables_.Lookup(name) != NULL;
598 } 438 }
599 439
600 bool IsDeclaredParameter(const AstRawString* name) {
601 // If IsSimpleParameterList is false, duplicate parameters are not allowed,
602 // however `arguments` may be allowed if function is not strict code. Thus,
603 // the assumptions explained above do not hold.
604 return params_.Contains(variables_.Lookup(name));
605 }
606
607 int num_var() const { return variables_.occupancy(); } 440 int num_var() const { return variables_.occupancy(); }
608 441
609 SloppyBlockFunctionMap* sloppy_block_function_map() {
610 return &sloppy_block_function_map_;
611 }
612
613 // To be called during parsing. Do just enough scope analysis that we can 442 // To be called during parsing. Do just enough scope analysis that we can
614 // discard the Scope for lazily compiled functions. In particular, this 443 // discard the Scope for lazily compiled functions. In particular, this
615 // records variables which cannot be resolved inside the Scope (we don't yet 444 // records variables which cannot be resolved inside the Scope (we don't yet
616 // know what they will resolve to since the outer Scopes are incomplete) and 445 // know what they will resolve to since the outer Scopes are incomplete) and
617 // migrates them into migrate_to. 446 // migrates them into migrate_to.
618 void AnalyzePartially(Scope* migrate_to, AstNodeFactory* ast_node_factory); 447 void AnalyzePartially(Scope* migrate_to, AstNodeFactory* ast_node_factory);
619 448
620 // --------------------------------------------------------------------------- 449 // ---------------------------------------------------------------------------
621 // Debugging. 450 // Debugging.
622 451
623 #ifdef DEBUG 452 #ifdef DEBUG
624 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively 453 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
625 454
626 // Check that the scope has positions assigned. 455 // Check that the scope has positions assigned.
627 void CheckScopePositions(); 456 void CheckScopePositions();
628 457
629 // Check that all Scopes in the scope tree use the same Zone. 458 // Check that all Scopes in the scope tree use the same Zone.
630 void CheckZones(); 459 void CheckZones();
631 #endif 460 #endif
632 461
633 // --------------------------------------------------------------------------- 462 // Retrieve `IsSimpleParameterList` of current or outer function.
634 // Implementation. 463 bool HasSimpleParameters();
464
635 private: 465 private:
636 // Scope tree. 466 // Scope tree.
637 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL 467 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
638 Scope* inner_scope_; // an inner scope of this scope 468 Scope* inner_scope_; // an inner scope of this scope
639 Scope* sibling_; // a sibling inner scope of the outer scope of this scope. 469 Scope* sibling_; // a sibling inner scope of the outer scope of this scope.
640 470
641 // Debugging support.
642 #ifdef DEBUG
643 const AstRawString* scope_name_;
644 #endif
645
646 // The variables declared in this scope: 471 // The variables declared in this scope:
647 // 472 //
648 // All user-declared variables (incl. parameters). For script scopes 473 // All user-declared variables (incl. parameters). For script scopes
649 // variables may be implicitly 'declared' by being used (possibly in 474 // variables may be implicitly 'declared' by being used (possibly in
650 // an inner scope) with no intervening with statements or eval calls. 475 // an inner scope) with no intervening with statements or eval calls.
651 VariableMap variables_; 476 VariableMap variables_;
652 // Compiler-allocated (user-invisible) temporaries. Due to the implementation
653 // of RemoveTemporary(), may contain nulls, which must be skipped-over during
654 // allocation and printing.
655 ZoneList<Variable*> temps_;
656 // Parameter list in source order.
657 ZoneList<Variable*> params_;
658 // Variables that must be looked up dynamically. 477 // Variables that must be looked up dynamically.
659 DynamicScopePart* dynamics_; 478 DynamicScopePart* dynamics_;
660 // Unresolved variables referred to from this scope. The proxies themselves 479 // Unresolved variables referred to from this scope. The proxies themselves
661 // form a linked list of all unresolved proxies. 480 // form a linked list of all unresolved proxies.
662 VariableProxy* unresolved_; 481 VariableProxy* unresolved_;
663 // Declarations. 482 // Declarations.
664 ZoneList<Declaration*> decls_; 483 ZoneList<Declaration*> decls_;
665 // Convenience variable.
666 Variable* receiver_;
667 // Function variable, if any; function scopes only.
668 VariableDeclaration* function_;
669 // new.target variable, function scopes only.
670 Variable* new_target_;
671 // Convenience variable; function scopes only.
672 Variable* arguments_;
673 // Convenience variable; Subclass constructor only
674 Variable* this_function_;
675 // Module descriptor; module scopes only.
676 ModuleDescriptor* module_descriptor_;
677
678 // Map of function names to lists of functions defined in sloppy blocks
679 SloppyBlockFunctionMap sloppy_block_function_map_;
680 484
681 // The scope type. 485 // The scope type.
682 const ScopeType scope_type_; 486 const ScopeType scope_type_;
683 // If the scope is a function scope, this is the function kind.
684 const FunctionKind function_kind_;
685 487
686 // Scope-specific information computed during parsing. 488 // Scope-specific information computed during parsing.
687 // 489 //
688 // The language mode of this scope. 490 // The language mode of this scope.
689 STATIC_ASSERT(LANGUAGE_END == 3); 491 STATIC_ASSERT(LANGUAGE_END == 3);
690 LanguageMode language_mode_ : 2; 492 LanguageMode language_mode_ : 2;
691 // This scope is inside a 'with' of some outer scope. 493 // This scope is inside a 'with' of some outer scope.
692 bool scope_inside_with_ : 1; 494 bool scope_inside_with_ : 1;
693 // This scope or a nested catch scope or with scope contain an 'eval' call. At 495 // This scope or a nested catch scope or with scope contain an 'eval' call. At
694 // the 'eval' call site this scope is the declaration scope. 496 // the 'eval' call site this scope is the declaration scope.
(...skipping 27 matching lines...) Expand all
722 524
723 // Source positions. 525 // Source positions.
724 int start_position_; 526 int start_position_;
725 int end_position_; 527 int end_position_;
726 528
727 // Computed via AllocateVariables; function, block and catch scopes only. 529 // Computed via AllocateVariables; function, block and catch scopes only.
728 int num_stack_slots_; 530 int num_stack_slots_;
729 int num_heap_slots_; 531 int num_heap_slots_;
730 int num_global_slots_; 532 int num_global_slots_;
731 533
732 // Info about the parameter list of a function.
733 int arity_;
734 int rest_index_;
735 Variable* rest_parameter_;
736
737 // Serialized scope info support. 534 // Serialized scope info support.
738 Handle<ScopeInfo> scope_info_; 535 Handle<ScopeInfo> scope_info_;
739 536
740 // Create a non-local variable with a given name. 537 // Create a non-local variable with a given name.
741 // These variables are looked up dynamically at runtime. 538 // These variables are looked up dynamically at runtime.
742 Variable* NonLocal(const AstRawString* name, VariableMode mode); 539 Variable* NonLocal(const AstRawString* name, VariableMode mode);
743 540
541 // Debugging support.
542 #ifdef DEBUG
543 const AstRawString* scope_name_;
544 #endif
545
744 // Variable resolution. 546 // Variable resolution.
745 // Possible results of a recursive variable lookup telling if and how a 547 // Possible results of a recursive variable lookup telling if and how a
746 // variable is bound. These are returned in the output parameter *binding_kind 548 // variable is bound. These are returned in the output parameter *binding_kind
747 // of the LookupRecursive function. 549 // of the LookupRecursive function.
748 enum BindingKind { 550 enum BindingKind {
749 // The variable reference could be statically resolved to a variable binding 551 // The variable reference could be statically resolved to a variable binding
750 // which is returned. There is no 'with' statement between the reference and 552 // which is returned. There is no 'with' statement between the reference and
751 // the binding and no scope between the reference scope (inclusive) and 553 // the binding and no scope between the reference scope (inclusive) and
752 // binding scope (exclusive) makes a sloppy 'eval' call. 554 // binding scope (exclusive) makes a sloppy 'eval' call.
753 BOUND, 555 BOUND,
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
809 void PropagateScopeInfo(bool outer_scope_calls_sloppy_eval); 611 void PropagateScopeInfo(bool outer_scope_calls_sloppy_eval);
810 bool HasTrivialContext() const; 612 bool HasTrivialContext() const;
811 613
812 // Predicates. 614 // Predicates.
813 bool MustAllocate(Variable* var); 615 bool MustAllocate(Variable* var);
814 bool MustAllocateInContext(Variable* var); 616 bool MustAllocateInContext(Variable* var);
815 617
816 // Variable allocation. 618 // Variable allocation.
817 void AllocateStackSlot(Variable* var); 619 void AllocateStackSlot(Variable* var);
818 void AllocateHeapSlot(Variable* var); 620 void AllocateHeapSlot(Variable* var);
819 void AllocateParameterLocals();
820 void AllocateNonParameterLocal(Variable* var, 621 void AllocateNonParameterLocal(Variable* var,
821 AstValueFactory* ast_value_factory); 622 AstValueFactory* ast_value_factory);
822 void AllocateDeclaredGlobal(Variable* var, 623 void AllocateDeclaredGlobal(Variable* var,
823 AstValueFactory* ast_value_factory); 624 AstValueFactory* ast_value_factory);
824 void AllocateNonParameterLocalsAndDeclaredGlobals( 625 void AllocateNonParameterLocalsAndDeclaredGlobals(
825 AstValueFactory* ast_value_factory); 626 AstValueFactory* ast_value_factory);
826 void AllocateVariablesRecursively(AstValueFactory* ast_value_factory); 627 void AllocateVariablesRecursively(AstValueFactory* ast_value_factory);
827 void AllocateParameter(Variable* var, int index);
828 void AllocateReceiver();
829 628
830 // Resolve and fill in the allocation information for all variables 629 // Resolve and fill in the allocation information for all variables
831 // in this scopes. Must be called *after* all scopes have been 630 // in this scopes. Must be called *after* all scopes have been
832 // processed (parsed) to ensure that unresolved variables can be 631 // processed (parsed) to ensure that unresolved variables can be
833 // resolved properly. 632 // resolved properly.
834 // 633 //
835 // In the case of code compiled and run using 'eval', the context 634 // In the case of code compiled and run using 'eval', the context
836 // parameter is the context in which eval was called. In all other 635 // parameter is the context in which eval was called. In all other
837 // cases the context parameter is an empty handle. 636 // cases the context parameter is an empty handle.
838 MUST_USE_RESULT 637 MUST_USE_RESULT
(...skipping 26 matching lines...) Expand all
865 if (scope->sibling_ == inner_scope) { 664 if (scope->sibling_ == inner_scope) {
866 scope->sibling_ = scope->sibling_->sibling_; 665 scope->sibling_ = scope->sibling_->sibling_;
867 return; 666 return;
868 } 667 }
869 } 668 }
870 } 669 }
871 670
872 void SetDefaults(); 671 void SetDefaults();
873 672
874 PendingCompilationErrorHandler pending_error_handler_; 673 PendingCompilationErrorHandler pending_error_handler_;
674
675 friend class DeclarationScope;
875 }; 676 };
876 677
678 class DeclarationScope : public Scope {
adamk 2016/08/04 00:18:51 Please give this a class comment. "DeclarationScop
Toon Verwaest 2016/08/04 12:01:17 Acknowledged.
Toon Verwaest 2016/08/04 12:01:17 I don't think it increases confusion. All scopes c
adamk 2016/08/04 16:31:28 I think this last paragraph is what makes me feel
679 public:
680 DeclarationScope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
681 FunctionKind function_kind = kNormalFunction);
682 DeclarationScope(Zone* zone, Scope* inner_scope, ScopeType scope_type,
683 Handle<ScopeInfo> scope_info);
684
685 bool IsDeclaredParameter(const AstRawString* name) {
686 // If IsSimpleParameterList is false, duplicate parameters are not allowed,
687 // however `arguments` may be allowed if function is not strict code. Thus,
688 // the assumptions explained above do not hold.
689 return params_.Contains(variables_.Lookup(name));
690 }
691
692 FunctionKind function_kind() const { return function_kind_; }
693
694 bool is_arrow_scope() const {
695 return is_function_scope() && IsArrowFunction(function_kind_);
696 }
697
698 bool NeedsHomeObject() const {
699 return scope_uses_super_property_ ||
700 ((scope_calls_eval_ || inner_scope_calls_eval_) &&
701 (IsConciseMethod(function_kind()) ||
702 IsAccessorFunction(function_kind()) ||
703 IsClassConstructor(function_kind())));
704 }
705
706 // The ModuleDescriptor for this scope; only for module scopes.
707 // TODO(verwaest): Move to ModuleScope?
708 ModuleDescriptor* module() const { return module_descriptor_; }
709
710 void DeclareThis(AstValueFactory* ast_value_factory);
711 void DeclareDefaultFunctionVariables(AstValueFactory* ast_value_factory);
712
713 // This lookup corresponds to a lookup in the "intermediate" scope sitting
714 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
715 // the name of named function literal is kept in an intermediate scope
716 // in between this scope and the next outer scope.)
717 Variable* LookupFunctionVar(const AstRawString* name,
718 AstNodeFactory* factory);
719
720 // Declare the function variable for a function literal. This variable
721 // is in an intermediate scope between this function scope and the the
722 // outer scope. Only possible for function scopes; at most one variable.
723 void DeclareFunctionVar(VariableDeclaration* declaration) {
724 DCHECK(is_function_scope());
725 // Handle implicit declaration of the function name in named function
726 // expressions before other declarations.
727 declarations()->InsertAt(0, declaration, zone());
728 function_ = declaration;
729 }
730
731 // Declare a parameter in this scope. When there are duplicated
732 // parameters the rightmost one 'wins'. However, the implementation
733 // expects all parameters to be declared and from left to right.
734 Variable* DeclareParameter(const AstRawString* name, VariableMode mode,
735 bool is_optional, bool is_rest, bool* is_duplicate,
736 AstValueFactory* ast_value_factory);
737
738 // Declare an implicit global variable in this scope which must be a
739 // script scope. The variable was introduced (possibly from an inner
740 // scope) by a reference to an unresolved variable with no intervening
741 // with statements or eval calls.
742 Variable* DeclareDynamicGlobal(const AstRawString* name);
743
744 // The variable corresponding to the 'this' value.
745 Variable* receiver() {
746 DCHECK(has_this_declaration());
747 DCHECK_NOT_NULL(receiver_);
748 return receiver_;
749 }
750
751 // TODO(wingo): Add a GLOBAL_SCOPE scope type which will lexically allocate
752 // "this" (and no other variable) on the native context. Script scopes then
753 // will not have a "this" declaration.
754 bool has_this_declaration() const {
755 return (is_function_scope() && !is_arrow_scope()) || is_module_scope();
756 }
757
758 // The variable corresponding to the 'new.target' value.
759 Variable* new_target_var() { return new_target_; }
760
761 // The variable holding the function literal for named function
762 // literals, or NULL. Only valid for function scopes.
763 VariableDeclaration* function() const {
764 DCHECK(is_function_scope());
765 return function_;
766 }
767
768 // Parameters. The left-most parameter has index 0.
769 // Only valid for function scopes.
770 Variable* parameter(int index) const {
771 DCHECK(is_function_scope());
772 return params_[index];
773 }
774
775 // Returns the default function arity excluding default or rest parameters.
776 int default_function_length() const { return arity_; }
777
778 // Returns the number of formal parameters, up to but not including the
779 // rest parameter index (if the function has rest parameters), i.e. it
780 // says 2 for
781 //
782 // function foo(a, b) { ... }
783 //
784 // and
785 //
786 // function foo(a, b, ...c) { ... }
787 //
788 // but for
789 //
790 // function foo(a, b, c = 1) { ... }
791 //
792 // we return 3 here.
793 int num_parameters() const {
794 return has_rest_parameter() ? params_.length() - 1 : params_.length();
795 }
796
797 // A function can have at most one rest parameter. Returns Variable* or NULL.
798 Variable* rest_parameter(int* index) const {
799 *index = rest_index_;
800 if (rest_index_ < 0) return NULL;
801 return rest_parameter_;
802 }
803
804 bool has_rest_parameter() const { return rest_index_ >= 0; }
805
806 bool has_simple_parameters() const { return has_simple_parameters_; }
807
808 // TODO(caitp): manage this state in a better way. PreParser must be able to
809 // communicate that the scope is non-simple, without allocating any parameters
810 // as the Parser does. This is necessary to ensure that TC39's proposed early
811 // error can be reported consistently regardless of whether lazily parsed or
812 // not.
813 void SetHasNonSimpleParameters() {
814 DCHECK(is_function_scope());
815 has_simple_parameters_ = false;
816 }
817
818 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
819 Variable* arguments() const {
820 DCHECK(!is_arrow_scope() || arguments_ == nullptr);
821 return arguments_;
822 }
823
824 Variable* this_function_var() const {
825 // This is only used in derived constructors atm.
826 DCHECK(this_function_ == nullptr ||
827 (is_function_scope() && (IsClassConstructor(function_kind()) ||
828 IsConciseMethod(function_kind()) ||
829 IsAccessorFunction(function_kind()))));
830 return this_function_;
831 }
832
833 // Remove a temporary variable. This is for adjusting the scope of
834 // temporaries used when desugaring parameter initializers.
835 // Returns the index at which it was found in this scope, or -1 if
836 // it was not found.
837 int RemoveTemporary(Variable* var);
838
839 // Adds a temporary variable in this scope's TemporaryScope. This is for
840 // adjusting the scope of temporaries used when desugaring parameter
841 // initializers.
842 void AddTemporary(Variable* var) {
843 // Temporaries are only placed in ClosureScopes.
844 DCHECK_EQ(GetClosureScope(), this);
845 temps_.Add(var, zone());
846 }
847
848 ZoneList<Variable*>* temps() { return &temps_; }
849
850 SloppyBlockFunctionMap* sloppy_block_function_map() {
851 return &sloppy_block_function_map_;
852 }
853
854 #ifdef DEBUG
855 void PrintParameters();
856 #endif
857
858 void AllocateLocals(AstValueFactory* ast_value_factory);
859 void AllocateParameterLocals();
860 void AllocateReceiver();
861
862 private:
863 void AllocateParameter(Variable* var, int index);
864
865 void SetDefaults();
866
867 // If the scope is a function scope, this is the function kind.
868 const FunctionKind function_kind_;
869
870 // Info about the parameter list of a function.
871 int arity_;
872 int rest_index_;
873 Variable* rest_parameter_;
874 // Compiler-allocated (user-invisible) temporaries. Due to the implementation
875 // of RemoveTemporary(), may contain nulls, which must be skipped-over during
876 // allocation and printing.
877 ZoneList<Variable*> temps_;
878 // Parameter list in source order.
879 ZoneList<Variable*> params_;
880 // Map of function names to lists of functions defined in sloppy blocks
881 SloppyBlockFunctionMap sloppy_block_function_map_;
882 // Convenience variable.
883 Variable* receiver_;
884 // Function variable, if any; function scopes only.
885 VariableDeclaration* function_;
886 // new.target variable, function scopes only.
887 Variable* new_target_;
888 // Convenience variable; function scopes only.
889 Variable* arguments_;
890 // Convenience variable; Subclass constructor only
891 Variable* this_function_;
892 // Module descriptor; module scopes only.
893 ModuleDescriptor* module_descriptor_;
894 };
895
877 } // namespace internal 896 } // namespace internal
878 } // namespace v8 897 } // namespace v8
879 898
880 #endif // V8_AST_SCOPES_H_ 899 #endif // V8_AST_SCOPES_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698