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

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

Powered by Google App Engine
This is Rietveld 408576698