1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
14 class CompilationInfo;
17 // A hash map to support fast variable declaration and lookup.
18 class VariableMap: public ZoneHashMap {
20 explicit VariableMap(Zone* zone);
22 virtual ~VariableMap();
24 Variable* Declare(Scope* scope, const AstRawString* name, VariableMode mode,
25 bool is_valid_lhs, Variable::Kind kind,
26 InitializationFlag initialization_flag,
27 MaybeAssignedFlag maybe_assigned_flag = kNotAssigned);
29 Variable* Lookup(const AstRawString* name);
31 Zone* zone() const { return zone_; }
38 // The dynamic scope part holds hash maps for the variables that will
39 // be looked up dynamically from within eval and with scopes. The objects
40 // are allocated on-demand from Scope::NonLocal to avoid wasting memory
41 // and setup time for scopes that don't need them.
42 class DynamicScopePart : public ZoneObject {
44 explicit DynamicScopePart(Zone* zone) {
45 for (int i = 0; i < 3; i++)
46 maps_[i] = new(zone->New(sizeof(VariableMap))) VariableMap(zone);
49 VariableMap* GetMap(VariableMode mode) {
50 int index = mode - DYNAMIC;
51 DCHECK(index >= 0 && index < 3);
56 VariableMap *maps_[3];
60 // Global invariants after AST construction: Each reference (i.e. identifier)
61 // to a JavaScript variable (including global properties) is represented by a
62 // VariableProxy node. Immediately after AST construction and before variable
63 // allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
64 // corresponding variable (though some are bound during parse time). Variable
65 // allocation binds each unresolved VariableProxy to one Variable and assigns
66 // a location. Note that many VariableProxy nodes may refer to the same Java-
69 class Scope: public ZoneObject {
71 // ---------------------------------------------------------------------------
74 Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
75 AstValueFactory* value_factory);
77 // Compute top scope and allocate variables. For lazy compilation the top
78 // scope only contains the single lazily compiled function, so this
79 // doesn't re-allocate variables repeatedly.
80 static bool Analyze(CompilationInfo* info);
82 static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone,
83 Context* context, Scope* script_scope);
85 // The scope name is only used for printing/debugging.
86 void SetScopeName(const AstRawString* scope_name) {
87 scope_name_ = scope_name;
90 void Initialize(bool subclass_constructor = false);
92 // Checks if the block scope is redundant, i.e. it does not contain any
93 // block scoped declarations. In that case it is removed from the scope
94 // tree and its children are reparented.
95 Scope* FinalizeBlockScope();
97 Zone* zone() const { return zone_; }
99 // ---------------------------------------------------------------------------
102 // Lookup a variable in this scope. Returns the variable or NULL if not found.
103 Variable* LookupLocal(const AstRawString* name);
105 // This lookup corresponds to a lookup in the "intermediate" scope sitting
106 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
107 // the name of named function literal is kept in an intermediate scope
108 // in between this scope and the next outer scope.)
109 Variable* LookupFunctionVar(const AstRawString* name,
110 AstNodeFactory* factory);
112 // Lookup a variable in this scope or outer scopes.
113 // Returns the variable or NULL if not found.
114 Variable* Lookup(const AstRawString* name);
116 // Declare the function variable for a function literal. This variable
117 // is in an intermediate scope between this function scope and the the
118 // outer scope. Only possible for function scopes; at most one variable.
119 void DeclareFunctionVar(VariableDeclaration* declaration) {
120 DCHECK(is_function_scope());
121 function_ = declaration;
124 // Declare a parameter in this scope. When there are duplicated
125 // parameters the rightmost one 'wins'. However, the implementation
126 // expects all parameters to be declared and from left to right.
127 Variable* DeclareParameter(const AstRawString* name, VariableMode mode,
128 bool is_rest = false);
130 // Declare a local variable in this scope. If the variable has been
131 // declared before, the previously declared variable is returned.
132 Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
133 InitializationFlag init_flag,
134 MaybeAssignedFlag maybe_assigned_flag = kNotAssigned);
136 // Declare an implicit global variable in this scope which must be a
137 // script scope. The variable was introduced (possibly from an inner
138 // scope) by a reference to an unresolved variable with no intervening
139 // with statements or eval calls.
140 Variable* DeclareDynamicGlobal(const AstRawString* name);
142 // Create a new unresolved variable.
143 VariableProxy* NewUnresolved(AstNodeFactory* factory,
144 const AstRawString* name,
145 int position = RelocInfo::kNoPosition) {
146 // Note that we must not share the unresolved variables with
147 // the same name because they may be removed selectively via
148 // RemoveUnresolved().
149 DCHECK(!already_resolved());
150 VariableProxy* proxy = factory->NewVariableProxy(name, false, position);
151 unresolved_.Add(proxy, zone_);
155 // Remove a unresolved variable. During parsing, an unresolved variable
156 // may have been added optimistically, but then only the variable name
157 // was used (typically for labels). If the variable was not declared, the
158 // addition introduced a new unresolved variable which may end up being
159 // allocated globally as a "ghost" variable. RemoveUnresolved removes
160 // such a variable again if it was added; otherwise this is a no-op.
161 void RemoveUnresolved(VariableProxy* var);
163 // Creates a new internal variable in this scope. The name is only used
164 // for printing and cannot be used to find the variable. In particular,
165 // the only way to get hold of the temporary is by keeping the Variable*
167 Variable* NewInternal(const AstRawString* name);
169 // Creates a new temporary variable in this scope. The name is only used
170 // for printing and cannot be used to find the variable. In particular,
171 // the only way to get hold of the temporary is by keeping the Variable*
172 // around. The name should not clash with a legitimate variable names.
173 Variable* NewTemporary(const AstRawString* name);
175 // Adds the specific declaration node to the list of declarations in
176 // this scope. The declarations are processed as part of entering
177 // the scope; see codegen.cc:ProcessDeclarations.
178 void AddDeclaration(Declaration* declaration);
180 // ---------------------------------------------------------------------------
181 // Illegal redeclaration support.
183 // Set an expression node that will be executed when the scope is
184 // entered. We only keep track of one illegal redeclaration node per
185 // scope - the first one - so if you try to set it multiple times
186 // the additional requests will be silently ignored.
187 void SetIllegalRedeclaration(Expression* expression);
189 // Visit the illegal redeclaration expression. Do not call if the
190 // scope doesn't have an illegal redeclaration node.
191 void VisitIllegalRedeclaration(AstVisitor* visitor);
193 // Check if the scope has (at least) one illegal redeclaration.
194 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
196 // For harmony block scoping mode: Check if the scope has conflicting var
197 // declarations, i.e. a var declaration that has been hoisted from a nested
198 // scope over a let binding of the same name.
199 Declaration* CheckConflictingVarDeclarations();
201 // ---------------------------------------------------------------------------
202 // Scope-specific info.
204 // Inform the scope that the corresponding code contains a with statement.
205 void RecordWithStatement() { scope_contains_with_ = true; }
207 // Inform the scope that the corresponding code contains an eval call.
208 void RecordEvalCall() { if (!is_script_scope()) scope_calls_eval_ = true; }
210 // Inform the scope that the corresponding code uses "arguments".
211 void RecordArgumentsUsage() { scope_uses_arguments_ = true; }
213 // Inform the scope that the corresponding code uses "super".
214 void RecordSuperPropertyUsage() { scope_uses_super_property_ = true; }
216 // Inform the scope that the corresponding code uses "this".
217 void RecordThisUsage() { scope_uses_this_ = true; }
219 // Set the language mode flag (unless disabled by a global flag).
220 void SetLanguageMode(LanguageMode language_mode) {
221 language_mode_ = language_mode;
224 // Set the ASM module flag.
225 void SetAsmModule() { asm_module_ = true; }
227 // Position in the source where this scope begins and ends.
229 // * For the scope of a with statement
231 // start position: start position of first token of 'stmt'
232 // end position: end position of last token of 'stmt'
233 // * For the scope of a block
235 // start position: start position of '{'
236 // end position: end position of '}'
237 // * For the scope of a function literal or decalaration
238 // function fun(a,b) { stmts }
239 // start position: start position of '('
240 // end position: end position of '}'
241 // * For the scope of a catch block
242 // try { stms } catch(e) { stmts }
243 // start position: start position of '('
244 // end position: end position of ')'
245 // * For the scope of a for-statement
246 // for (let x ...) stmt
247 // start position: start position of '('
248 // end position: end position of last token of 'stmt'
249 int start_position() const { return start_position_; }
250 void set_start_position(int statement_pos) {
251 start_position_ = statement_pos;
253 int end_position() const { return end_position_; }
254 void set_end_position(int statement_pos) {
255 end_position_ = statement_pos;
258 // In some cases we want to force context allocation for a whole scope.
259 void ForceContextAllocation() {
260 DCHECK(!already_resolved());
261 force_context_allocation_ = true;
263 bool has_forced_context_allocation() const {
264 return force_context_allocation_;
267 // ---------------------------------------------------------------------------
270 // Specific scope types.
271 bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
272 bool is_function_scope() const {
273 return scope_type_ == FUNCTION_SCOPE || scope_type_ == ARROW_SCOPE;
275 bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
276 bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
277 bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
278 bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
279 bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
280 bool is_arrow_scope() const { return scope_type_ == ARROW_SCOPE; }
281 bool is_declaration_scope() const {
282 return is_eval_scope() || is_function_scope() ||
283 is_module_scope() || is_script_scope();
285 bool is_strict_eval_scope() const {
286 return is_eval_scope() && is_strict(language_mode_);
289 // Information about which scopes calls eval.
290 bool calls_eval() const { return scope_calls_eval_; }
291 bool calls_sloppy_eval() {
292 return scope_calls_eval_ && is_sloppy(language_mode_);
294 bool outer_scope_calls_sloppy_eval() const {
295 return outer_scope_calls_sloppy_eval_;
297 bool asm_module() const { return asm_module_; }
298 bool asm_function() const { return asm_function_; }
300 // Is this scope inside a with statement.
301 bool inside_with() const { return scope_inside_with_; }
302 // Does this scope contain a with statement.
303 bool contains_with() const { return scope_contains_with_; }
305 // Does this scope access "arguments".
306 bool uses_arguments() const { return scope_uses_arguments_; }
307 // Does any inner scope access "arguments".
308 bool inner_uses_arguments() const { return inner_scope_uses_arguments_; }
309 // Does this scope access "super" property (super.foo).
310 bool uses_super_property() const { return scope_uses_super_property_; }
311 // Does any inner scope access "super" property.
312 bool inner_uses_super_property() const {
313 return inner_scope_uses_super_property_;
315 // Does this scope access "this".
316 bool uses_this() const { return scope_uses_this_; }
317 // Does any inner scope access "this".
318 bool inner_uses_this() const { return inner_scope_uses_this_; }
320 // ---------------------------------------------------------------------------
323 // The type of this scope.
324 ScopeType scope_type() const { return scope_type_; }
326 // The language mode of this scope.
327 LanguageMode language_mode() const { return language_mode_; }
329 // The variable corresponding to the 'this' value.
330 Variable* receiver() { return receiver_; }
332 // The variable corresponding to the 'new.target' value.
333 Variable* new_target_var() { return new_target_; }
335 // The variable holding the function literal for named function
336 // literals, or NULL. Only valid for function scopes.
337 VariableDeclaration* function() const {
338 DCHECK(is_function_scope());
342 // Parameters. The left-most parameter has index 0.
343 // Only valid for function scopes.
344 Variable* parameter(int index) const {
345 DCHECK(is_function_scope());
346 return params_[index];
349 // Returns the default function arity --- does not include rest parameters.
350 int default_function_length() const {
351 int count = params_.length();
352 if (rest_index_ >= 0) {
354 DCHECK(is_function_scope());
360 int num_parameters() const { return params_.length(); }
362 // A function can have at most one rest parameter. Returns Variable* or NULL.
363 Variable* rest_parameter(int* index) const {
364 *index = rest_index_;
365 if (rest_index_ < 0) return NULL;
366 return rest_parameter_;
369 bool has_rest_parameter() const {
370 return rest_index_ >= 0;
373 bool is_simple_parameter_list() const {
374 DCHECK(is_function_scope());
375 if (rest_index_ >= 0) return false;
379 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
380 Variable* arguments() const { return arguments_; }
382 // Declarations list.
383 ZoneList<Declaration*>* declarations() { return &decls_; }
386 ZoneList<Scope*>* inner_scopes() { return &inner_scopes_; }
388 // The scope immediately surrounding this scope, or NULL.
389 Scope* outer_scope() const { return outer_scope_; }
391 // The ModuleDescriptor for this scope; only for module scopes.
392 ModuleDescriptor* module() const { return module_descriptor_; }
394 // ---------------------------------------------------------------------------
395 // Variable allocation.
397 // Collect stack and context allocated local variables in this scope. Note
398 // that the function variable - if present - is not collected and should be
399 // handled separately.
400 void CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
401 ZoneList<Variable*>* context_locals);
403 // Current number of var or const locals.
404 int num_var_or_const() { return num_var_or_const_; }
406 // Result of variable allocation.
407 int num_stack_slots() const { return num_stack_slots_; }
408 int num_heap_slots() const { return num_heap_slots_; }
410 int StackLocalCount() const;
411 int ContextLocalCount() const;
413 // For script scopes, the number of module literals (including nested ones).
414 int num_modules() const { return num_modules_; }
416 // For module scopes, the host scope's internal variable binding this module.
417 Variable* module_var() const { return module_var_; }
419 // Make sure this scope and all outer scopes are eagerly compiled.
420 void ForceEagerCompilation() { force_eager_compilation_ = true; }
422 // Determine if we can use lazy compilation for this scope.
423 bool AllowsLazyCompilation() const;
425 // Determine if we can use lazy compilation for this scope without a context.
426 bool AllowsLazyCompilationWithoutContext() const;
428 // True if the outer context of this scope is always the native context.
429 bool HasTrivialOuterContext() const;
431 // True if the outer context allows lazy compilation of this scope.
432 bool HasLazyCompilableOuterContext() const;
434 // The number of contexts between this and scope; zero if this == scope.
435 int ContextChainLength(Scope* scope);
437 // Find the script scope.
438 // Used in modules implemenetation to find hosting scope.
439 // TODO(rossberg): is this needed?
440 Scope* ScriptScope();
442 // Find the first function, global, or eval scope. This is the scope
443 // where var declarations will be hoisted to in the implementation.
444 Scope* DeclarationScope();
446 Handle<ScopeInfo> GetScopeInfo(Isolate* isolate);
448 // Get the chain of nested scopes within this scope for the source statement
449 // position. The scopes will be added to the list from the outermost scope to
450 // the innermost scope. Only nested block, catch or with scopes are tracked
451 // and will be returned, but no inner function scopes.
452 void GetNestedScopeChain(Isolate* isolate, List<Handle<ScopeInfo> >* chain,
453 int statement_position);
455 // ---------------------------------------------------------------------------
456 // Strict mode support.
457 bool IsDeclared(const AstRawString* name) {
458 // During formal parameter list parsing the scope only contains
459 // two variables inserted at initialization: "this" and "arguments".
460 // "this" is an invalid parameter name and "arguments" is invalid parameter
461 // name in strict mode. Therefore looking up with the map which includes
462 // "this" and "arguments" in addition to all formal parameters is safe.
463 return variables_.Lookup(name) != NULL;
466 bool IsDeclaredParameter(const AstRawString* name) {
467 // If IsSimpleParameterList is false, duplicate parameters are not allowed,
468 // however `arguments` may be allowed if function is not strict code. Thus,
469 // the assumptions explained above do not hold.
470 return params_.Contains(variables_.Lookup(name));
473 // ---------------------------------------------------------------------------
477 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
480 // ---------------------------------------------------------------------------
483 friend class ParserFactory;
486 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
487 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes
490 ScopeType scope_type_;
492 // Debugging support.
493 const AstRawString* scope_name_;
495 // The variables declared in this scope:
497 // All user-declared variables (incl. parameters). For script scopes
498 // variables may be implicitly 'declared' by being used (possibly in
499 // an inner scope) with no intervening with statements or eval calls.
500 VariableMap variables_;
501 // Compiler-allocated (user-invisible) internals.
502 ZoneList<Variable*> internals_;
503 // Compiler-allocated (user-invisible) temporaries.
504 ZoneList<Variable*> temps_;
505 // Parameter list in source order.
506 ZoneList<Variable*> params_;
507 // Variables that must be looked up dynamically.
508 DynamicScopePart* dynamics_;
509 // Unresolved variables referred to from this scope.
510 ZoneList<VariableProxy*> unresolved_;
512 ZoneList<Declaration*> decls_;
513 // Convenience variable.
515 // Function variable, if any; function scopes only.
516 VariableDeclaration* function_;
517 // new.target variable, function scopes only.
518 Variable* new_target_;
519 // Convenience variable; function scopes only.
520 Variable* arguments_;
521 // Module descriptor; module scopes only.
522 ModuleDescriptor* module_descriptor_;
524 // Illegal redeclaration.
525 Expression* illegal_redecl_;
527 // Scope-specific information computed during parsing.
529 // This scope is inside a 'with' of some outer scope.
530 bool scope_inside_with_;
531 // This scope contains a 'with' statement.
532 bool scope_contains_with_;
533 // This scope or a nested catch scope or with scope contain an 'eval' call. At
534 // the 'eval' call site this scope is the declaration scope.
535 bool scope_calls_eval_;
536 // This scope uses "arguments".
537 bool scope_uses_arguments_;
538 // This scope uses "super" property ('super.foo').
539 bool scope_uses_super_property_;
540 // This scope uses "this".
541 bool scope_uses_this_;
542 // This scope contains an "use asm" annotation.
544 // This scope's outer context is an asm module.
546 // The language mode of this scope.
547 LanguageMode language_mode_;
552 // Computed via PropagateScopeInfo.
553 bool outer_scope_calls_sloppy_eval_;
554 bool inner_scope_calls_eval_;
555 bool inner_scope_uses_arguments_;
556 bool inner_scope_uses_super_property_;
557 bool inner_scope_uses_this_;
558 bool force_eager_compilation_;
559 bool force_context_allocation_;
561 // True if it doesn't need scope resolution (e.g., if the scope was
562 // constructed based on a serialized scope info or a catch context).
563 bool already_resolved_;
565 // Computed as variables are declared.
566 int num_var_or_const_;
568 // Computed via AllocateVariables; function, block and catch scopes only.
569 int num_stack_slots_;
572 // The number of modules (including nested ones).
575 // For module scopes, the host scope's internal variable binding this module.
576 Variable* module_var_;
579 Variable* rest_parameter_;
582 // Serialized scope info support.
583 Handle<ScopeInfo> scope_info_;
584 bool already_resolved() { return already_resolved_; }
586 // Create a non-local variable with a given name.
587 // These variables are looked up dynamically at runtime.
588 Variable* NonLocal(const AstRawString* name, VariableMode mode);
590 // Variable resolution.
591 // Possible results of a recursive variable lookup telling if and how a
592 // variable is bound. These are returned in the output parameter *binding_kind
593 // of the LookupRecursive function.
595 // The variable reference could be statically resolved to a variable binding
596 // which is returned. There is no 'with' statement between the reference and
597 // the binding and no scope between the reference scope (inclusive) and
598 // binding scope (exclusive) makes a sloppy 'eval' call.
601 // The variable reference could be statically resolved to a variable binding
602 // which is returned. There is no 'with' statement between the reference and
603 // the binding, but some scope between the reference scope (inclusive) and
604 // binding scope (exclusive) makes a sloppy 'eval' call, that might
605 // possibly introduce variable bindings shadowing the found one. Thus the
606 // found variable binding is just a guess.
609 // The variable reference could not be statically resolved to any binding
610 // and thus should be considered referencing a global variable. NULL is
611 // returned. The variable reference is not inside any 'with' statement and
612 // no scope between the reference scope (inclusive) and script scope
613 // (exclusive) makes a sloppy 'eval' call.
616 // The variable reference could not be statically resolved to any binding
617 // NULL is returned. The variable reference is not inside any 'with'
618 // statement, but some scope between the reference scope (inclusive) and
619 // script scope (exclusive) makes a sloppy 'eval' call, that might
620 // possibly introduce a variable binding. Thus the reference should be
621 // considered referencing a global variable unless it is shadowed by an
622 // 'eval' introduced binding.
623 UNBOUND_EVAL_SHADOWED,
625 // The variable could not be statically resolved and needs to be looked up
626 // dynamically. NULL is returned. There are two possible reasons:
627 // * A 'with' statement has been encountered and there is no variable
628 // binding for the name between the variable reference and the 'with'.
629 // The variable potentially references a property of the 'with' object.
630 // * The code is being executed as part of a call to 'eval' and the calling
631 // context chain contains either a variable binding for the name or it
632 // contains a 'with' context.
636 // Lookup a variable reference given by name recursively starting with this
637 // scope. If the code is executed because of a call to 'eval', the context
638 // parameter should be set to the calling context of 'eval'.
639 Variable* LookupRecursive(VariableProxy* proxy, BindingKind* binding_kind,
640 AstNodeFactory* factory);
642 bool ResolveVariable(CompilationInfo* info, VariableProxy* proxy,
643 AstNodeFactory* factory);
645 bool ResolveVariablesRecursively(CompilationInfo* info,
646 AstNodeFactory* factory);
649 void PropagateScopeInfo(bool outer_scope_calls_sloppy_eval);
650 bool HasTrivialContext() const;
653 bool MustAllocate(Variable* var);
654 bool MustAllocateInContext(Variable* var);
655 bool HasArgumentsParameter(Isolate* isolate);
657 // Variable allocation.
658 void AllocateStackSlot(Variable* var);
659 void AllocateHeapSlot(Variable* var);
660 void AllocateParameterLocals(Isolate* isolate);
661 void AllocateNonParameterLocal(Isolate* isolate, Variable* var);
662 void AllocateNonParameterLocals(Isolate* isolate);
663 void AllocateVariablesRecursively(Isolate* isolate);
664 void AllocateModulesRecursively(Scope* host_scope);
666 // Resolve and fill in the allocation information for all variables
667 // in this scopes. Must be called *after* all scopes have been
668 // processed (parsed) to ensure that unresolved variables can be
669 // resolved properly.
671 // In the case of code compiled and run using 'eval', the context
672 // parameter is the context in which eval was called. In all other
673 // cases the context parameter is an empty handle.
675 bool AllocateVariables(CompilationInfo* info, AstNodeFactory* factory);
678 // Construct a scope based on the scope info.
679 Scope(Zone* zone, Scope* inner_scope, ScopeType type,
680 Handle<ScopeInfo> scope_info, AstValueFactory* value_factory);
682 // Construct a catch scope with a binding for the name.
683 Scope(Zone* zone, Scope* inner_scope, const AstRawString* catch_variable_name,
684 AstValueFactory* value_factory);
686 void AddInnerScope(Scope* inner_scope) {
687 if (inner_scope != NULL) {
688 inner_scopes_.Add(inner_scope, zone_);
689 inner_scope->outer_scope_ = this;
693 void SetDefaults(ScopeType type,
695 Handle<ScopeInfo> scope_info);
697 AstValueFactory* ast_value_factory_;
701 } } // namespace v8::internal
703 #endif // V8_SCOPES_H_