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.
7 #include "src/scopes.h"
9 #include "src/accessors.h"
10 #include "src/bootstrapper.h"
11 #include "src/compiler.h"
12 #include "src/messages.h"
13 #include "src/scopeinfo.h"
18 // ----------------------------------------------------------------------------
19 // Implementation of LocalsMap
21 // Note: We are storing the handle locations as key values in the hash map.
22 // When inserting a new variable via Declare(), we rely on the fact that
23 // the handle location remains alive for the duration of that variable
24 // use. Because a Variable holding a handle with the same location exists
27 VariableMap::VariableMap(Zone* zone)
28 : ZoneHashMap(ZoneHashMap::PointersMatch, 8, ZoneAllocationPolicy(zone)),
30 VariableMap::~VariableMap() {}
33 Variable* VariableMap::Declare(Scope* scope, const AstRawString* name,
34 VariableMode mode, bool is_valid_lhs,
36 InitializationFlag initialization_flag,
37 MaybeAssignedFlag maybe_assigned_flag) {
38 // AstRawStrings are unambiguous, i.e., the same string is always represented
39 // by the same AstRawString*.
40 // FIXME(marja): fix the type of Lookup.
41 Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
42 true, ZoneAllocationPolicy(zone()));
43 if (p->value == NULL) {
44 // The variable has not been declared yet -> insert it.
45 DCHECK(p->key == name);
46 p->value = new (zone()) Variable(scope, name, mode, is_valid_lhs, kind,
47 initialization_flag, maybe_assigned_flag);
49 return reinterpret_cast<Variable*>(p->value);
53 Variable* VariableMap::Lookup(const AstRawString* name) {
54 Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
55 false, ZoneAllocationPolicy(NULL));
57 DCHECK(reinterpret_cast<const AstRawString*>(p->key) == name);
58 DCHECK(p->value != NULL);
59 return reinterpret_cast<Variable*>(p->value);
65 // ----------------------------------------------------------------------------
66 // Implementation of Scope
68 Scope::Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
69 AstValueFactory* ast_value_factory)
70 : inner_scopes_(4, zone),
75 unresolved_(16, zone),
78 scope_type == MODULE_SCOPE ? ModuleDescriptor::New(zone) : NULL),
79 already_resolved_(false),
80 ast_value_factory_(ast_value_factory),
82 SetDefaults(scope_type, outer_scope, Handle<ScopeInfo>::null());
83 // The outermost scope must be a script scope.
84 DCHECK(scope_type == SCRIPT_SCOPE || outer_scope != NULL);
85 DCHECK(!HasIllegalRedeclaration());
89 Scope::Scope(Zone* zone, Scope* inner_scope, ScopeType scope_type,
90 Handle<ScopeInfo> scope_info, AstValueFactory* value_factory)
91 : inner_scopes_(4, zone),
96 unresolved_(16, zone),
98 module_descriptor_(NULL),
99 already_resolved_(true),
100 ast_value_factory_(value_factory),
102 SetDefaults(scope_type, NULL, scope_info);
103 if (!scope_info.is_null()) {
104 num_heap_slots_ = scope_info_->ContextLength();
106 // Ensure at least MIN_CONTEXT_SLOTS to indicate a materialized context.
107 num_heap_slots_ = Max(num_heap_slots_,
108 static_cast<int>(Context::MIN_CONTEXT_SLOTS));
109 AddInnerScope(inner_scope);
113 Scope::Scope(Zone* zone, Scope* inner_scope,
114 const AstRawString* catch_variable_name,
115 AstValueFactory* value_factory)
116 : inner_scopes_(1, zone),
121 unresolved_(0, zone),
123 module_descriptor_(NULL),
124 already_resolved_(true),
125 ast_value_factory_(value_factory),
127 SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
128 AddInnerScope(inner_scope);
130 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
131 Variable* variable = variables_.Declare(this,
134 true, // Valid left-hand side.
136 kCreatedInitialized);
137 AllocateHeapSlot(variable);
141 void Scope::SetDefaults(ScopeType scope_type,
143 Handle<ScopeInfo> scope_info) {
144 outer_scope_ = outer_scope;
145 scope_type_ = scope_type;
146 scope_name_ = ast_value_factory_->empty_string();
149 new_target_ = nullptr;
152 illegal_redecl_ = NULL;
153 scope_inside_with_ = false;
154 scope_contains_with_ = false;
155 scope_calls_eval_ = false;
156 scope_uses_arguments_ = false;
157 scope_uses_super_property_ = false;
158 scope_uses_this_ = false;
160 asm_function_ = outer_scope != NULL && outer_scope->asm_module_;
161 // Inherit the language mode from the parent scope.
162 language_mode_ = outer_scope != NULL ? outer_scope->language_mode_ : SLOPPY;
163 outer_scope_calls_sloppy_eval_ = false;
164 inner_scope_calls_eval_ = false;
165 inner_scope_uses_arguments_ = false;
166 inner_scope_uses_this_ = false;
167 inner_scope_uses_super_property_ = false;
168 force_eager_compilation_ = false;
169 force_context_allocation_ = (outer_scope != NULL && !is_function_scope())
170 ? outer_scope->has_forced_context_allocation() : false;
171 num_var_or_const_ = 0;
172 num_stack_slots_ = 0;
176 rest_parameter_ = NULL;
178 scope_info_ = scope_info;
179 start_position_ = RelocInfo::kNoPosition;
180 end_position_ = RelocInfo::kNoPosition;
181 if (!scope_info.is_null()) {
182 scope_calls_eval_ = scope_info->CallsEval();
183 language_mode_ = scope_info->language_mode();
188 Scope* Scope::DeserializeScopeChain(Isolate* isolate, Zone* zone,
189 Context* context, Scope* script_scope) {
190 // Reconstruct the outer scope chain from a closure's context chain.
191 Scope* current_scope = NULL;
192 Scope* innermost_scope = NULL;
193 bool contains_with = false;
194 while (!context->IsNativeContext()) {
195 if (context->IsWithContext()) {
196 Scope* with_scope = new (zone)
197 Scope(zone, current_scope, WITH_SCOPE, Handle<ScopeInfo>::null(),
198 script_scope->ast_value_factory_);
199 current_scope = with_scope;
200 // All the inner scopes are inside a with.
201 contains_with = true;
202 for (Scope* s = innermost_scope; s != NULL; s = s->outer_scope()) {
203 s->scope_inside_with_ = true;
205 } else if (context->IsScriptContext()) {
206 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
207 current_scope = new (zone) Scope(zone, current_scope, SCRIPT_SCOPE,
208 Handle<ScopeInfo>(scope_info),
209 script_scope->ast_value_factory_);
210 } else if (context->IsModuleContext()) {
211 ScopeInfo* scope_info = ScopeInfo::cast(context->module()->scope_info());
212 current_scope = new (zone) Scope(zone, current_scope, MODULE_SCOPE,
213 Handle<ScopeInfo>(scope_info),
214 script_scope->ast_value_factory_);
215 } else if (context->IsFunctionContext()) {
216 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
217 current_scope = new (zone) Scope(zone, current_scope, FUNCTION_SCOPE,
218 Handle<ScopeInfo>(scope_info),
219 script_scope->ast_value_factory_);
220 if (scope_info->IsAsmFunction()) current_scope->asm_function_ = true;
221 if (scope_info->IsAsmModule()) current_scope->asm_module_ = true;
222 } else if (context->IsBlockContext()) {
223 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
224 current_scope = new (zone)
225 Scope(zone, current_scope, BLOCK_SCOPE, Handle<ScopeInfo>(scope_info),
226 script_scope->ast_value_factory_);
228 DCHECK(context->IsCatchContext());
229 String* name = String::cast(context->extension());
230 current_scope = new (zone) Scope(
232 script_scope->ast_value_factory_->GetString(Handle<String>(name)),
233 script_scope->ast_value_factory_);
235 if (contains_with) current_scope->RecordWithStatement();
236 if (innermost_scope == NULL) innermost_scope = current_scope;
238 // Forget about a with when we move to a context for a different function.
239 if (context->previous()->closure() != context->closure()) {
240 contains_with = false;
242 context = context->previous();
245 script_scope->AddInnerScope(current_scope);
246 script_scope->PropagateScopeInfo(false);
247 return (innermost_scope == NULL) ? script_scope : innermost_scope;
251 bool Scope::Analyze(CompilationInfo* info) {
252 DCHECK(info->function() != NULL);
253 Scope* scope = info->function()->scope();
256 // Traverse the scope tree up to the first unresolved scope or the global
257 // scope and start scope resolution and variable allocation from that scope.
258 while (!top->is_script_scope() &&
259 !top->outer_scope()->already_resolved()) {
260 top = top->outer_scope();
263 // Allocate the variables.
265 AstNodeFactory ast_node_factory(info->ast_value_factory());
266 if (!top->AllocateVariables(info, &ast_node_factory)) return false;
270 if (info->isolate()->bootstrapper()->IsActive()
271 ? FLAG_print_builtin_scopes
272 : FLAG_print_scopes) {
277 info->PrepareForCompilation(scope);
282 void Scope::Initialize(bool subclass_constructor) {
283 DCHECK(!already_resolved());
285 // Add this scope as a new inner scope of the outer scope.
286 if (outer_scope_ != NULL) {
287 outer_scope_->inner_scopes_.Add(this, zone());
288 scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
290 scope_inside_with_ = is_with_scope();
293 // Declare convenience variables.
294 // Declare and allocate receiver (even for the script scope, and even
295 // if naccesses_ == 0).
296 // NOTE: When loading parameters in the script scope, we must take
297 // care not to access them as properties of the global object, but
298 // instead load them directly from the stack. Currently, the only
299 // such parameter is 'this' which is passed on the stack when
301 if (is_declaration_scope()) {
302 DCHECK(!subclass_constructor || is_function_scope());
303 Variable* var = variables_.Declare(
304 this, ast_value_factory_->this_string(),
305 subclass_constructor ? CONST : VAR, false, Variable::THIS,
306 subclass_constructor ? kNeedsInitialization : kCreatedInitialized);
307 var->AllocateTo(Variable::PARAMETER, -1);
310 if (subclass_constructor) {
311 new_target_ = variables_.Declare(
312 this, ast_value_factory_->new_target_string(), CONST, false,
313 Variable::NEW_TARGET, kCreatedInitialized);
314 new_target_->AllocateTo(Variable::PARAMETER, -2);
315 new_target_->set_is_used();
318 DCHECK(outer_scope() != NULL);
319 receiver_ = outer_scope()->receiver();
322 if (is_function_scope()) {
323 // Declare 'arguments' variable which exists in all functions.
324 // Note that it might never be accessed, in which case it won't be
325 // allocated during variable allocation.
326 variables_.Declare(this,
327 ast_value_factory_->arguments_string(),
331 kCreatedInitialized);
336 Scope* Scope::FinalizeBlockScope() {
337 DCHECK(is_block_scope());
338 DCHECK(internals_.is_empty());
339 DCHECK(temps_.is_empty());
340 DCHECK(params_.is_empty());
342 if (num_var_or_const() > 0) return this;
344 // Remove this scope from outer scope.
345 for (int i = 0; i < outer_scope_->inner_scopes_.length(); i++) {
346 if (outer_scope_->inner_scopes_[i] == this) {
347 outer_scope_->inner_scopes_.Remove(i);
352 // Reparent inner scopes.
353 for (int i = 0; i < inner_scopes_.length(); i++) {
354 outer_scope()->AddInnerScope(inner_scopes_[i]);
357 // Move unresolved variables
358 for (int i = 0; i < unresolved_.length(); i++) {
359 outer_scope()->unresolved_.Add(unresolved_[i], zone());
362 // Propagate usage flags to outer scope.
363 if (uses_arguments()) outer_scope_->RecordArgumentsUsage();
364 if (uses_super_property()) outer_scope_->RecordSuperPropertyUsage();
365 if (uses_this()) outer_scope_->RecordThisUsage();
371 Variable* Scope::LookupLocal(const AstRawString* name) {
372 Variable* result = variables_.Lookup(name);
373 if (result != NULL || scope_info_.is_null()) {
376 // The Scope is backed up by ScopeInfo. This means it cannot operate in a
377 // heap-independent mode, and all strings must be internalized immediately. So
378 // it's ok to get the Handle<String> here.
379 Handle<String> name_handle = name->string();
380 // If we have a serialized scope info, we might find the variable there.
381 // There should be no local slot with the given name.
382 DCHECK(scope_info_->StackSlotIndex(*name_handle) < 0);
384 // Check context slot lookup.
386 Variable::Location location = Variable::CONTEXT;
387 InitializationFlag init_flag;
388 MaybeAssignedFlag maybe_assigned_flag;
389 int index = ScopeInfo::ContextSlotIndex(scope_info_, name_handle, &mode,
390 &init_flag, &maybe_assigned_flag);
393 index = scope_info_->ParameterIndex(*name_handle);
394 if (index < 0) return NULL;
397 location = Variable::LOOKUP;
398 init_flag = kCreatedInitialized;
399 // Be conservative and flag parameters as maybe assigned. Better information
400 // would require ScopeInfo to serialize the maybe_assigned bit also for
402 maybe_assigned_flag = kMaybeAssigned;
405 Variable* var = variables_.Declare(this, name, mode, true, Variable::NORMAL,
406 init_flag, maybe_assigned_flag);
407 var->AllocateTo(location, index);
412 Variable* Scope::LookupFunctionVar(const AstRawString* name,
413 AstNodeFactory* factory) {
414 if (function_ != NULL && function_->proxy()->raw_name() == name) {
415 return function_->proxy()->var();
416 } else if (!scope_info_.is_null()) {
417 // If we are backed by a scope info, try to lookup the variable there.
419 int index = scope_info_->FunctionContextSlotIndex(*(name->string()), &mode);
420 if (index < 0) return NULL;
421 Variable* var = new(zone()) Variable(
422 this, name, mode, true /* is valid LHS */,
423 Variable::NORMAL, kCreatedInitialized);
424 VariableProxy* proxy = factory->NewVariableProxy(var);
425 VariableDeclaration* declaration = factory->NewVariableDeclaration(
426 proxy, mode, this, RelocInfo::kNoPosition);
427 DeclareFunctionVar(declaration);
428 var->AllocateTo(Variable::CONTEXT, index);
436 Variable* Scope::Lookup(const AstRawString* name) {
437 for (Scope* scope = this;
439 scope = scope->outer_scope()) {
440 Variable* var = scope->LookupLocal(name);
441 if (var != NULL) return var;
447 Variable* Scope::DeclareParameter(const AstRawString* name, VariableMode mode,
449 DCHECK(!already_resolved());
450 DCHECK(is_function_scope());
451 Variable* var = variables_.Declare(this, name, mode, true, Variable::NORMAL,
452 kCreatedInitialized);
454 DCHECK_NULL(rest_parameter_);
455 rest_parameter_ = var;
456 rest_index_ = num_parameters();
458 params_.Add(var, zone());
463 Variable* Scope::DeclareLocal(const AstRawString* name, VariableMode mode,
464 InitializationFlag init_flag,
465 MaybeAssignedFlag maybe_assigned_flag) {
466 DCHECK(!already_resolved());
467 // This function handles VAR, LET, and CONST modes. DYNAMIC variables are
468 // introduces during variable allocation, INTERNAL variables are allocated
469 // explicitly, and TEMPORARY variables are allocated via NewTemporary().
470 DCHECK(IsDeclaredVariableMode(mode));
472 return variables_.Declare(this, name, mode, true, Variable::NORMAL, init_flag,
473 maybe_assigned_flag);
477 Variable* Scope::DeclareDynamicGlobal(const AstRawString* name) {
478 DCHECK(is_script_scope());
479 return variables_.Declare(this,
484 kCreatedInitialized);
488 void Scope::RemoveUnresolved(VariableProxy* var) {
489 // Most likely (always?) any variable we want to remove
490 // was just added before, so we search backwards.
491 for (int i = unresolved_.length(); i-- > 0;) {
492 if (unresolved_[i] == var) {
493 unresolved_.Remove(i);
500 Variable* Scope::NewInternal(const AstRawString* name) {
501 DCHECK(!already_resolved());
502 Variable* var = new(zone()) Variable(this,
507 kCreatedInitialized);
508 internals_.Add(var, zone());
513 Variable* Scope::NewTemporary(const AstRawString* name) {
514 DCHECK(!already_resolved());
515 Variable* var = new(zone()) Variable(this,
520 kCreatedInitialized);
521 temps_.Add(var, zone());
526 void Scope::AddDeclaration(Declaration* declaration) {
527 decls_.Add(declaration, zone());
531 void Scope::SetIllegalRedeclaration(Expression* expression) {
532 // Record only the first illegal redeclaration.
533 if (!HasIllegalRedeclaration()) {
534 illegal_redecl_ = expression;
536 DCHECK(HasIllegalRedeclaration());
540 void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
541 DCHECK(HasIllegalRedeclaration());
542 illegal_redecl_->Accept(visitor);
546 Declaration* Scope::CheckConflictingVarDeclarations() {
547 int length = decls_.length();
548 for (int i = 0; i < length; i++) {
549 Declaration* decl = decls_[i];
550 if (decl->mode() != VAR) continue;
551 const AstRawString* name = decl->proxy()->raw_name();
553 // Iterate through all scopes until and including the declaration scope.
554 Scope* previous = NULL;
555 Scope* current = decl->scope();
557 // There is a conflict if there exists a non-VAR binding.
558 Variable* other_var = current->variables_.Lookup(name);
559 if (other_var != NULL && other_var->mode() != VAR) {
563 current = current->outer_scope_;
564 } while (!previous->is_declaration_scope());
572 VarAndOrder(Variable* var, int order) : var_(var), order_(order) { }
573 Variable* var() const { return var_; }
574 int order() const { return order_; }
575 static int Compare(const VarAndOrder* a, const VarAndOrder* b) {
576 return a->order_ - b->order_;
585 void Scope::CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
586 ZoneList<Variable*>* context_locals) {
587 DCHECK(stack_locals != NULL);
588 DCHECK(context_locals != NULL);
590 // Collect internals which are always allocated on the heap.
591 for (int i = 0; i < internals_.length(); i++) {
592 Variable* var = internals_[i];
593 if (var->is_used()) {
594 DCHECK(var->IsContextSlot());
595 context_locals->Add(var, zone());
599 // Collect temporaries which are always allocated on the stack, unless the
600 // context as a whole has forced context allocation.
601 for (int i = 0; i < temps_.length(); i++) {
602 Variable* var = temps_[i];
603 if (var->is_used()) {
604 if (var->IsContextSlot()) {
605 DCHECK(has_forced_context_allocation());
606 context_locals->Add(var, zone());
608 DCHECK(var->IsStackLocal());
609 stack_locals->Add(var, zone());
614 // Collect declared local variables.
615 ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
616 for (VariableMap::Entry* p = variables_.Start();
618 p = variables_.Next(p)) {
619 Variable* var = reinterpret_cast<Variable*>(p->value);
620 if (var->is_used()) {
621 vars.Add(VarAndOrder(var, p->order), zone());
624 vars.Sort(VarAndOrder::Compare);
625 int var_count = vars.length();
626 for (int i = 0; i < var_count; i++) {
627 Variable* var = vars[i].var();
628 if (var->IsStackLocal()) {
629 stack_locals->Add(var, zone());
630 } else if (var->IsContextSlot()) {
631 context_locals->Add(var, zone());
637 bool Scope::AllocateVariables(CompilationInfo* info, AstNodeFactory* factory) {
638 // 1) Propagate scope information.
639 bool outer_scope_calls_sloppy_eval = false;
640 if (outer_scope_ != NULL) {
641 outer_scope_calls_sloppy_eval =
642 outer_scope_->outer_scope_calls_sloppy_eval() |
643 outer_scope_->calls_sloppy_eval();
645 PropagateScopeInfo(outer_scope_calls_sloppy_eval);
647 // 2) Allocate module instances.
648 if (FLAG_harmony_modules && (is_script_scope() || is_module_scope())) {
649 DCHECK(num_modules_ == 0);
650 AllocateModulesRecursively(this);
653 // 3) Resolve variables.
654 if (!ResolveVariablesRecursively(info, factory)) return false;
656 // 4) Allocate variables.
657 AllocateVariablesRecursively(info->isolate());
663 bool Scope::HasTrivialContext() const {
664 // A function scope has a trivial context if it always is the global
665 // context. We iteratively scan out the context chain to see if
666 // there is anything that makes this scope non-trivial; otherwise we
668 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
669 if (scope->is_eval_scope()) return false;
670 if (scope->scope_inside_with_) return false;
671 if (scope->num_heap_slots_ > 0) return false;
677 bool Scope::HasTrivialOuterContext() const {
678 Scope* outer = outer_scope_;
679 if (outer == NULL) return true;
680 // Note that the outer context may be trivial in general, but the current
681 // scope may be inside a 'with' statement in which case the outer context
682 // for this scope is not trivial.
683 return !scope_inside_with_ && outer->HasTrivialContext();
687 bool Scope::HasLazyCompilableOuterContext() const {
688 Scope* outer = outer_scope_;
689 if (outer == NULL) return true;
690 // We have to prevent lazy compilation if this scope is inside a with scope
691 // and all declaration scopes between them have empty contexts. Such
692 // declaration scopes may become invisible during scope info deserialization.
693 outer = outer->DeclarationScope();
694 bool found_non_trivial_declarations = false;
695 for (const Scope* scope = outer; scope != NULL; scope = scope->outer_scope_) {
696 if (scope->is_with_scope() && !found_non_trivial_declarations) return false;
697 if (scope->is_declaration_scope() && scope->num_heap_slots() > 0) {
698 found_non_trivial_declarations = true;
705 bool Scope::AllowsLazyCompilation() const {
706 return !force_eager_compilation_ && HasLazyCompilableOuterContext();
710 bool Scope::AllowsLazyCompilationWithoutContext() const {
711 return !force_eager_compilation_ && HasTrivialOuterContext();
715 int Scope::ContextChainLength(Scope* scope) {
717 for (Scope* s = this; s != scope; s = s->outer_scope_) {
718 DCHECK(s != NULL); // scope must be in the scope chain
719 if (s->is_with_scope() || s->num_heap_slots() > 0) n++;
720 // Catch and module scopes always have heap slots.
721 DCHECK(!s->is_catch_scope() || s->num_heap_slots() > 0);
722 DCHECK(!s->is_module_scope() || s->num_heap_slots() > 0);
728 Scope* Scope::ScriptScope() {
730 while (!scope->is_script_scope()) {
731 scope = scope->outer_scope();
737 Scope* Scope::DeclarationScope() {
739 while (!scope->is_declaration_scope()) {
740 scope = scope->outer_scope();
746 Handle<ScopeInfo> Scope::GetScopeInfo(Isolate* isolate) {
747 if (scope_info_.is_null()) {
748 scope_info_ = ScopeInfo::Create(isolate, zone(), this);
754 void Scope::GetNestedScopeChain(Isolate* isolate,
755 List<Handle<ScopeInfo> >* chain, int position) {
756 if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo(isolate)));
758 for (int i = 0; i < inner_scopes_.length(); i++) {
759 Scope* scope = inner_scopes_[i];
760 int beg_pos = scope->start_position();
761 int end_pos = scope->end_position();
762 DCHECK(beg_pos >= 0 && end_pos >= 0);
763 if (beg_pos <= position && position < end_pos) {
764 scope->GetNestedScopeChain(isolate, chain, position);
772 static const char* Header(ScopeType scope_type) {
773 switch (scope_type) {
774 case EVAL_SCOPE: return "eval";
775 case FUNCTION_SCOPE: return "function";
776 case MODULE_SCOPE: return "module";
777 case SCRIPT_SCOPE: return "global";
778 case CATCH_SCOPE: return "catch";
779 case BLOCK_SCOPE: return "block";
780 case WITH_SCOPE: return "with";
781 case ARROW_SCOPE: return "arrow";
788 static void Indent(int n, const char* str) {
789 PrintF("%*s%s", n, "", str);
793 static void PrintName(const AstRawString* name) {
794 PrintF("%.*s", name->length(), name->raw_data());
798 static void PrintLocation(Variable* var) {
799 switch (var->location()) {
800 case Variable::UNALLOCATED:
802 case Variable::PARAMETER:
803 PrintF("parameter[%d]", var->index());
805 case Variable::LOCAL:
806 PrintF("local[%d]", var->index());
808 case Variable::CONTEXT:
809 PrintF("context[%d]", var->index());
811 case Variable::LOOKUP:
818 static void PrintVar(int indent, Variable* var) {
819 if (var->is_used() || !var->IsUnallocated()) {
820 Indent(indent, Variable::Mode2String(var->mode()));
822 PrintName(var->raw_name());
825 bool comma = !var->IsUnallocated();
826 if (var->has_forced_context_allocation()) {
827 if (comma) PrintF(", ");
828 PrintF("forced context allocation");
831 if (var->maybe_assigned() == kMaybeAssigned) {
832 if (comma) PrintF(", ");
833 PrintF("maybe assigned");
840 static void PrintMap(int indent, VariableMap* map) {
841 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
842 Variable* var = reinterpret_cast<Variable*>(p->value);
843 PrintVar(indent, var);
848 void Scope::Print(int n) {
849 int n0 = (n > 0 ? n : 0);
850 int n1 = n0 + 2; // indentation
853 Indent(n0, Header(scope_type_));
854 if (!scope_name_->IsEmpty()) {
856 PrintName(scope_name_);
859 // Print parameters, if any.
860 if (is_function_scope()) {
862 for (int i = 0; i < params_.length(); i++) {
863 if (i > 0) PrintF(", ");
864 PrintName(params_[i]->raw_name());
869 PrintF(" { // (%d, %d)\n", start_position(), end_position());
871 // Function name, if any (named function literals, only).
872 if (function_ != NULL) {
873 Indent(n1, "// (local) function name: ");
874 PrintName(function_->proxy()->raw_name());
879 if (HasTrivialOuterContext()) {
880 Indent(n1, "// scope has trivial outer context\n");
882 if (is_strong(language_mode())) {
883 Indent(n1, "// strong mode scope\n");
884 } else if (is_strict(language_mode())) {
885 Indent(n1, "// strict mode scope\n");
887 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
888 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
889 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
890 if (scope_uses_arguments_) Indent(n1, "// scope uses 'arguments'\n");
891 if (scope_uses_super_property_)
892 Indent(n1, "// scope uses 'super' property\n");
893 if (scope_uses_this_) Indent(n1, "// scope uses 'this'\n");
894 if (inner_scope_uses_arguments_) {
895 Indent(n1, "// inner scope uses 'arguments'\n");
897 if (inner_scope_uses_super_property_)
898 Indent(n1, "// inner scope uses 'super' property\n");
899 if (inner_scope_uses_this_) Indent(n1, "// inner scope uses 'this'\n");
900 if (outer_scope_calls_sloppy_eval_) {
901 Indent(n1, "// outer scope calls 'eval' in sloppy context\n");
903 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
904 if (num_stack_slots_ > 0) { Indent(n1, "// ");
905 PrintF("%d stack slots\n", num_stack_slots_); }
906 if (num_heap_slots_ > 0) { Indent(n1, "// ");
907 PrintF("%d heap slots\n", num_heap_slots_); }
910 if (function_ != NULL) {
911 Indent(n1, "// function var:\n");
912 PrintVar(n1, function_->proxy()->var());
915 if (temps_.length() > 0) {
916 Indent(n1, "// temporary vars:\n");
917 for (int i = 0; i < temps_.length(); i++) {
918 PrintVar(n1, temps_[i]);
922 if (internals_.length() > 0) {
923 Indent(n1, "// internal vars:\n");
924 for (int i = 0; i < internals_.length(); i++) {
925 PrintVar(n1, internals_[i]);
929 if (variables_.Start() != NULL) {
930 Indent(n1, "// local vars:\n");
931 PrintMap(n1, &variables_);
934 if (dynamics_ != NULL) {
935 Indent(n1, "// dynamic vars:\n");
936 PrintMap(n1, dynamics_->GetMap(DYNAMIC));
937 PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
938 PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
941 // Print inner scopes (disable by providing negative n).
943 for (int i = 0; i < inner_scopes_.length(); i++) {
945 inner_scopes_[i]->Print(n1);
954 Variable* Scope::NonLocal(const AstRawString* name, VariableMode mode) {
955 if (dynamics_ == NULL) dynamics_ = new (zone()) DynamicScopePart(zone());
956 VariableMap* map = dynamics_->GetMap(mode);
957 Variable* var = map->Lookup(name);
959 // Declare a new non-local.
960 InitializationFlag init_flag = (mode == VAR)
961 ? kCreatedInitialized : kNeedsInitialization;
962 var = map->Declare(NULL,
968 // Allocate it by giving it a dynamic lookup.
969 var->AllocateTo(Variable::LOOKUP, -1);
975 Variable* Scope::LookupRecursive(VariableProxy* proxy,
976 BindingKind* binding_kind,
977 AstNodeFactory* factory) {
978 DCHECK(binding_kind != NULL);
979 if (already_resolved() && is_with_scope()) {
980 // Short-cut: if the scope is deserialized from a scope info, variable
981 // allocation is already fixed. We can simply return with dynamic lookup.
982 *binding_kind = DYNAMIC_LOOKUP;
986 // Try to find the variable in this scope.
987 Variable* var = LookupLocal(proxy->raw_name());
989 // We found a variable and we are done. (Even if there is an 'eval' in
990 // this scope which introduces the same variable again, the resulting
991 // variable remains the same.)
993 *binding_kind = BOUND;
997 // We did not find a variable locally. Check against the function variable,
998 // if any. We can do this for all scopes, since the function variable is
999 // only present - if at all - for function scopes.
1000 *binding_kind = UNBOUND;
1001 var = LookupFunctionVar(proxy->raw_name(), factory);
1003 *binding_kind = BOUND;
1004 } else if (outer_scope_ != NULL) {
1005 var = outer_scope_->LookupRecursive(proxy, binding_kind, factory);
1006 if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
1007 var->ForceContextAllocation();
1010 DCHECK(is_script_scope());
1013 if (is_with_scope()) {
1014 DCHECK(!already_resolved());
1015 // The current scope is a with scope, so the variable binding can not be
1016 // statically resolved. However, note that it was necessary to do a lookup
1017 // in the outer scope anyway, because if a binding exists in an outer scope,
1018 // the associated variable has to be marked as potentially being accessed
1019 // from inside of an inner with scope (the property may not be in the 'with'
1021 if (var != NULL && proxy->is_assigned()) var->set_maybe_assigned();
1022 *binding_kind = DYNAMIC_LOOKUP;
1024 } else if (calls_sloppy_eval()) {
1025 // A variable binding may have been found in an outer scope, but the current
1026 // scope makes a sloppy 'eval' call, so the found variable may not be
1027 // the correct one (the 'eval' may introduce a binding with the same name).
1028 // In that case, change the lookup result to reflect this situation.
1029 if (*binding_kind == BOUND) {
1030 *binding_kind = BOUND_EVAL_SHADOWED;
1031 } else if (*binding_kind == UNBOUND) {
1032 *binding_kind = UNBOUND_EVAL_SHADOWED;
1039 bool Scope::ResolveVariable(CompilationInfo* info, VariableProxy* proxy,
1040 AstNodeFactory* factory) {
1041 DCHECK(info->script_scope()->is_script_scope());
1043 // If the proxy is already resolved there's nothing to do
1044 // (functions and consts may be resolved by the parser).
1045 if (proxy->is_resolved()) return true;
1047 // Otherwise, try to resolve the variable.
1048 BindingKind binding_kind;
1049 Variable* var = LookupRecursive(proxy, &binding_kind, factory);
1050 switch (binding_kind) {
1052 // We found a variable binding.
1055 case BOUND_EVAL_SHADOWED:
1056 // We either found a variable binding that might be shadowed by eval or
1057 // gave up on it (e.g. by encountering a local with the same in the outer
1058 // scope which was not promoted to a context, this can happen if we use
1059 // debugger to evaluate arbitrary expressions at a break point).
1060 if (var->IsGlobalObjectProperty()) {
1061 var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1062 } else if (var->is_dynamic()) {
1063 var = NonLocal(proxy->raw_name(), DYNAMIC);
1065 Variable* invalidated = var;
1066 var = NonLocal(proxy->raw_name(), DYNAMIC_LOCAL);
1067 var->set_local_if_not_shadowed(invalidated);
1072 // No binding has been found. Declare a variable on the global object.
1073 var = info->script_scope()->DeclareDynamicGlobal(proxy->raw_name());
1076 case UNBOUND_EVAL_SHADOWED:
1077 // No binding has been found. But some scope makes a sloppy 'eval' call.
1078 var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1081 case DYNAMIC_LOOKUP:
1082 // The variable could not be resolved statically.
1083 var = NonLocal(proxy->raw_name(), DYNAMIC);
1087 DCHECK(var != NULL);
1088 if (proxy->is_assigned()) var->set_maybe_assigned();
1096 bool Scope::ResolveVariablesRecursively(CompilationInfo* info,
1097 AstNodeFactory* factory) {
1098 DCHECK(info->script_scope()->is_script_scope());
1100 // Resolve unresolved variables for this scope.
1101 for (int i = 0; i < unresolved_.length(); i++) {
1102 if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1105 // Resolve unresolved variables for inner scopes.
1106 for (int i = 0; i < inner_scopes_.length(); i++) {
1107 if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
1115 void Scope::PropagateScopeInfo(bool outer_scope_calls_sloppy_eval ) {
1116 if (outer_scope_calls_sloppy_eval) {
1117 outer_scope_calls_sloppy_eval_ = true;
1120 bool calls_sloppy_eval =
1121 this->calls_sloppy_eval() || outer_scope_calls_sloppy_eval_;
1122 for (int i = 0; i < inner_scopes_.length(); i++) {
1123 Scope* inner = inner_scopes_[i];
1124 inner->PropagateScopeInfo(calls_sloppy_eval);
1125 if (inner->scope_calls_eval_ || inner->inner_scope_calls_eval_) {
1126 inner_scope_calls_eval_ = true;
1128 // If the inner scope is an arrow function, propagate the flags tracking
1129 // usage of arguments/super/this, but do not propagate them out from normal
1131 if (!inner->is_function_scope() || inner->is_arrow_scope()) {
1132 if (inner->scope_uses_arguments_ || inner->inner_scope_uses_arguments_) {
1133 inner_scope_uses_arguments_ = true;
1135 if (inner->scope_uses_super_property_ ||
1136 inner->inner_scope_uses_super_property_) {
1137 inner_scope_uses_super_property_ = true;
1139 if (inner->scope_uses_this_ || inner->inner_scope_uses_this_) {
1140 inner_scope_uses_this_ = true;
1143 if (inner->force_eager_compilation_) {
1144 force_eager_compilation_ = true;
1146 if (asm_module_ && inner->scope_type() == FUNCTION_SCOPE) {
1147 inner->asm_function_ = true;
1153 bool Scope::MustAllocate(Variable* var) {
1154 // Give var a read/write use if there is a chance it might be accessed
1155 // via an eval() call. This is only possible if the variable has a
1157 if ((var->is_this() || var->is_new_target() || !var->raw_name()->IsEmpty()) &&
1158 (var->has_forced_context_allocation() || scope_calls_eval_ ||
1159 inner_scope_calls_eval_ || scope_contains_with_ || is_catch_scope() ||
1160 is_block_scope() || is_module_scope() || is_script_scope())) {
1162 if (scope_calls_eval_ || inner_scope_calls_eval_) var->set_maybe_assigned();
1164 // Global variables do not need to be allocated.
1165 return !var->IsGlobalObjectProperty() && var->is_used();
1169 bool Scope::MustAllocateInContext(Variable* var) {
1170 // If var is accessed from an inner scope, or if there is a possibility
1171 // that it might be accessed from the current or an inner scope (through
1172 // an eval() call or a runtime with lookup), it must be allocated in the
1175 // Exceptions: If the scope as a whole has forced context allocation, all
1176 // variables will have context allocation, even temporaries. Otherwise
1177 // temporary variables are always stack-allocated. Catch-bound variables are
1178 // always context-allocated.
1179 if (has_forced_context_allocation()) return true;
1180 if (var->mode() == TEMPORARY) return false;
1181 if (var->mode() == INTERNAL) return true;
1182 if (is_catch_scope() || is_block_scope() || is_module_scope()) return true;
1183 if (is_script_scope() && IsLexicalVariableMode(var->mode())) return true;
1184 return var->has_forced_context_allocation() ||
1185 scope_calls_eval_ ||
1186 inner_scope_calls_eval_ ||
1187 scope_contains_with_;
1191 bool Scope::HasArgumentsParameter(Isolate* isolate) {
1192 for (int i = 0; i < params_.length(); i++) {
1193 if (params_[i]->name().is_identical_to(
1194 isolate->factory()->arguments_string())) {
1202 void Scope::AllocateStackSlot(Variable* var) {
1203 var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1207 void Scope::AllocateHeapSlot(Variable* var) {
1208 var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1212 void Scope::AllocateParameterLocals(Isolate* isolate) {
1213 DCHECK(is_function_scope());
1214 Variable* arguments = LookupLocal(ast_value_factory_->arguments_string());
1215 DCHECK(arguments != NULL); // functions have 'arguments' declared implicitly
1217 bool uses_sloppy_arguments = false;
1219 if (MustAllocate(arguments) && !HasArgumentsParameter(isolate)) {
1220 // 'arguments' is used. Unless there is also a parameter called
1221 // 'arguments', we must be conservative and allocate all parameters to
1222 // the context assuming they will be captured by the arguments object.
1223 // If we have a parameter named 'arguments', a (new) value is always
1224 // assigned to it via the function invocation. Then 'arguments' denotes
1225 // that specific parameter value and cannot be used to access the
1226 // parameters, which is why we don't need to allocate an arguments
1227 // object in that case.
1229 // We are using 'arguments'. Tell the code generator that is needs to
1230 // allocate the arguments object by setting 'arguments_'.
1231 arguments_ = arguments;
1233 // In strict mode 'arguments' does not alias formal parameters.
1234 // Therefore in strict mode we allocate parameters as if 'arguments'
1236 uses_sloppy_arguments = is_sloppy(language_mode());
1239 if (rest_parameter_ && !MustAllocate(rest_parameter_)) {
1240 rest_parameter_ = NULL;
1243 // The same parameter may occur multiple times in the parameters_ list.
1244 // If it does, and if it is not copied into the context object, it must
1245 // receive the highest parameter index for that parameter; thus iteration
1246 // order is relevant!
1247 for (int i = params_.length() - 1; i >= 0; --i) {
1248 Variable* var = params_[i];
1249 if (var == rest_parameter_) continue;
1251 DCHECK(var->scope() == this);
1252 if (uses_sloppy_arguments || has_forced_context_allocation()) {
1253 // Force context allocation of the parameter.
1254 var->ForceContextAllocation();
1257 if (MustAllocate(var)) {
1258 if (MustAllocateInContext(var)) {
1259 DCHECK(var->IsUnallocated() || var->IsContextSlot());
1260 if (var->IsUnallocated()) {
1261 AllocateHeapSlot(var);
1264 DCHECK(var->IsUnallocated() || var->IsParameter());
1265 if (var->IsUnallocated()) {
1266 var->AllocateTo(Variable::PARAMETER, i);
1274 void Scope::AllocateNonParameterLocal(Isolate* isolate, Variable* var) {
1275 DCHECK(var->scope() == this);
1276 DCHECK(!var->IsVariable(isolate->factory()->dot_result_string()) ||
1277 !var->IsStackLocal());
1278 if (var->IsUnallocated() && MustAllocate(var)) {
1279 if (MustAllocateInContext(var)) {
1280 AllocateHeapSlot(var);
1282 AllocateStackSlot(var);
1288 void Scope::AllocateNonParameterLocals(Isolate* isolate) {
1289 // All variables that have no rewrite yet are non-parameter locals.
1290 for (int i = 0; i < temps_.length(); i++) {
1291 AllocateNonParameterLocal(isolate, temps_[i]);
1294 for (int i = 0; i < internals_.length(); i++) {
1295 AllocateNonParameterLocal(isolate, internals_[i]);
1298 ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
1299 for (VariableMap::Entry* p = variables_.Start();
1301 p = variables_.Next(p)) {
1302 Variable* var = reinterpret_cast<Variable*>(p->value);
1303 vars.Add(VarAndOrder(var, p->order), zone());
1305 vars.Sort(VarAndOrder::Compare);
1306 int var_count = vars.length();
1307 for (int i = 0; i < var_count; i++) {
1308 AllocateNonParameterLocal(isolate, vars[i].var());
1311 // For now, function_ must be allocated at the very end. If it gets
1312 // allocated in the context, it must be the last slot in the context,
1313 // because of the current ScopeInfo implementation (see
1314 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
1315 if (function_ != NULL) {
1316 AllocateNonParameterLocal(isolate, function_->proxy()->var());
1319 if (rest_parameter_) {
1320 AllocateNonParameterLocal(isolate, rest_parameter_);
1325 void Scope::AllocateVariablesRecursively(Isolate* isolate) {
1326 // Allocate variables for inner scopes.
1327 for (int i = 0; i < inner_scopes_.length(); i++) {
1328 inner_scopes_[i]->AllocateVariablesRecursively(isolate);
1331 // If scope is already resolved, we still need to allocate
1332 // variables in inner scopes which might not had been resolved yet.
1333 if (already_resolved()) return;
1334 // The number of slots required for variables.
1335 num_stack_slots_ = 0;
1336 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
1338 // Allocate variables for this scope.
1339 // Parameters must be allocated first, if any.
1340 if (is_function_scope()) AllocateParameterLocals(isolate);
1341 AllocateNonParameterLocals(isolate);
1343 // Force allocation of a context for this scope if necessary. For a 'with'
1344 // scope and for a function scope that makes an 'eval' call we need a context,
1345 // even if no local variables were statically allocated in the scope.
1346 // Likewise for modules.
1347 bool must_have_context = is_with_scope() || is_module_scope() ||
1348 (is_function_scope() && calls_eval());
1350 // If we didn't allocate any locals in the local context, then we only
1351 // need the minimal number of slots if we must have a context.
1352 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1353 num_heap_slots_ = 0;
1357 DCHECK(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1361 void Scope::AllocateModulesRecursively(Scope* host_scope) {
1362 if (already_resolved()) return;
1363 if (is_module_scope()) {
1364 DCHECK(module_descriptor_->IsFrozen());
1365 DCHECK(module_var_ == NULL);
1367 host_scope->NewInternal(ast_value_factory_->dot_module_string());
1368 ++host_scope->num_modules_;
1371 for (int i = 0; i < inner_scopes_.length(); i++) {
1372 Scope* inner_scope = inner_scopes_.at(i);
1373 inner_scope->AllocateModulesRecursively(host_scope);
1378 int Scope::StackLocalCount() const {
1379 return num_stack_slots() -
1380 (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
1384 int Scope::ContextLocalCount() const {
1385 if (num_heap_slots() == 0) return 0;
1386 return num_heap_slots() - Context::MIN_CONTEXT_SLOTS -
1387 (function_ != NULL && function_->proxy()->var()->IsContextSlot() ? 1 : 0);
1390 } } // namespace v8::internal