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 Interface* interface) {
39 // AstRawStrings are unambiguous, i.e., the same string is always represented
40 // by the same AstRawString*.
41 // FIXME(marja): fix the type of Lookup.
42 Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
43 true, ZoneAllocationPolicy(zone()));
44 if (p->value == NULL) {
45 // The variable has not been declared yet -> insert it.
46 DCHECK(p->key == name);
47 p->value = new (zone())
48 Variable(scope, name, mode, is_valid_lhs, kind, initialization_flag,
49 maybe_assigned_flag, interface);
51 return reinterpret_cast<Variable*>(p->value);
55 Variable* VariableMap::Lookup(const AstRawString* name) {
56 Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
57 false, ZoneAllocationPolicy(NULL));
59 DCHECK(reinterpret_cast<const AstRawString*>(p->key) == name);
60 DCHECK(p->value != NULL);
61 return reinterpret_cast<Variable*>(p->value);
67 // ----------------------------------------------------------------------------
68 // Implementation of Scope
70 Scope::Scope(Scope* outer_scope, ScopeType scope_type,
71 AstValueFactory* ast_value_factory, Zone* zone)
72 : isolate_(zone->isolate()),
73 inner_scopes_(4, zone),
78 unresolved_(16, zone),
80 interface_(FLAG_harmony_modules &&
81 (scope_type == MODULE_SCOPE || scope_type == GLOBAL_SCOPE)
82 ? Interface::NewModule(zone) : NULL),
83 already_resolved_(false),
84 ast_value_factory_(ast_value_factory),
86 SetDefaults(scope_type, outer_scope, Handle<ScopeInfo>::null());
87 // The outermost scope must be a global scope.
88 DCHECK(scope_type == GLOBAL_SCOPE || outer_scope != NULL);
89 DCHECK(!HasIllegalRedeclaration());
93 Scope::Scope(Scope* inner_scope,
95 Handle<ScopeInfo> scope_info,
96 AstValueFactory* value_factory,
98 : isolate_(zone->isolate()),
99 inner_scopes_(4, zone),
104 unresolved_(16, zone),
107 already_resolved_(true),
108 ast_value_factory_(value_factory),
110 SetDefaults(scope_type, NULL, scope_info);
111 if (!scope_info.is_null()) {
112 num_heap_slots_ = scope_info_->ContextLength();
114 // Ensure at least MIN_CONTEXT_SLOTS to indicate a materialized context.
115 num_heap_slots_ = Max(num_heap_slots_,
116 static_cast<int>(Context::MIN_CONTEXT_SLOTS));
117 AddInnerScope(inner_scope);
121 Scope::Scope(Scope* inner_scope, const AstRawString* catch_variable_name,
122 AstValueFactory* value_factory, Zone* zone)
123 : isolate_(zone->isolate()),
124 inner_scopes_(1, zone),
129 unresolved_(0, zone),
132 already_resolved_(true),
133 ast_value_factory_(value_factory),
135 SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
136 AddInnerScope(inner_scope);
138 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
139 Variable* variable = variables_.Declare(this,
142 true, // Valid left-hand side.
144 kCreatedInitialized);
145 AllocateHeapSlot(variable);
149 void Scope::SetDefaults(ScopeType scope_type,
151 Handle<ScopeInfo> scope_info) {
152 outer_scope_ = outer_scope;
153 scope_type_ = scope_type;
154 scope_name_ = ast_value_factory_->empty_string();
159 illegal_redecl_ = NULL;
160 scope_inside_with_ = false;
161 scope_contains_with_ = false;
162 scope_calls_eval_ = false;
163 // Inherit the strict mode from the parent scope.
164 strict_mode_ = outer_scope != NULL ? outer_scope->strict_mode_ : SLOPPY;
165 outer_scope_calls_sloppy_eval_ = false;
166 inner_scope_calls_eval_ = false;
167 force_eager_compilation_ = false;
168 force_context_allocation_ = (outer_scope != NULL && !is_function_scope())
169 ? outer_scope->has_forced_context_allocation() : false;
170 num_var_or_const_ = 0;
171 num_stack_slots_ = 0;
175 scope_info_ = scope_info;
176 start_position_ = RelocInfo::kNoPosition;
177 end_position_ = RelocInfo::kNoPosition;
178 if (!scope_info.is_null()) {
179 scope_calls_eval_ = scope_info->CallsEval();
180 strict_mode_ = scope_info->strict_mode();
185 Scope* Scope::DeserializeScopeChain(Context* context, Scope* global_scope,
187 // Reconstruct the outer scope chain from a closure's context chain.
188 Scope* current_scope = NULL;
189 Scope* innermost_scope = NULL;
190 bool contains_with = false;
191 while (!context->IsNativeContext()) {
192 if (context->IsWithContext()) {
193 Scope* with_scope = new(zone) Scope(current_scope,
195 Handle<ScopeInfo>::null(),
196 global_scope->ast_value_factory_,
198 current_scope = with_scope;
199 // All the inner scopes are inside a with.
200 contains_with = true;
201 for (Scope* s = innermost_scope; s != NULL; s = s->outer_scope()) {
202 s->scope_inside_with_ = true;
204 } else if (context->IsGlobalContext()) {
205 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
206 current_scope = new(zone) Scope(current_scope,
208 Handle<ScopeInfo>(scope_info),
209 global_scope->ast_value_factory_,
211 } else if (context->IsModuleContext()) {
212 ScopeInfo* scope_info = ScopeInfo::cast(context->module()->scope_info());
213 current_scope = new(zone) Scope(current_scope,
215 Handle<ScopeInfo>(scope_info),
216 global_scope->ast_value_factory_,
218 } else if (context->IsFunctionContext()) {
219 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
220 current_scope = new(zone) Scope(current_scope,
222 Handle<ScopeInfo>(scope_info),
223 global_scope->ast_value_factory_,
225 } else if (context->IsBlockContext()) {
226 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
227 current_scope = new(zone) Scope(current_scope,
229 Handle<ScopeInfo>(scope_info),
230 global_scope->ast_value_factory_,
233 DCHECK(context->IsCatchContext());
234 String* name = String::cast(context->extension());
235 current_scope = new (zone) Scope(
237 global_scope->ast_value_factory_->GetString(Handle<String>(name)),
238 global_scope->ast_value_factory_, zone);
240 if (contains_with) current_scope->RecordWithStatement();
241 if (innermost_scope == NULL) innermost_scope = current_scope;
243 // Forget about a with when we move to a context for a different function.
244 if (context->previous()->closure() != context->closure()) {
245 contains_with = false;
247 context = context->previous();
250 global_scope->AddInnerScope(current_scope);
251 global_scope->PropagateScopeInfo(false);
252 return (innermost_scope == NULL) ? global_scope : innermost_scope;
256 bool Scope::Analyze(CompilationInfo* info) {
257 DCHECK(info->function() != NULL);
258 Scope* scope = info->function()->scope();
261 // Traverse the scope tree up to the first unresolved scope or the global
262 // scope and start scope resolution and variable allocation from that scope.
263 while (!top->is_global_scope() &&
264 !top->outer_scope()->already_resolved()) {
265 top = top->outer_scope();
268 // Allocate the variables.
270 // Passing NULL as AstValueFactory is ok, because AllocateVariables doesn't
271 // need to create new strings or values.
272 AstNodeFactory<AstNullVisitor> ast_node_factory(info->zone(), NULL);
273 if (!top->AllocateVariables(info, &ast_node_factory)) return false;
277 if (info->isolate()->bootstrapper()->IsActive()
278 ? FLAG_print_builtin_scopes
279 : FLAG_print_scopes) {
283 if (FLAG_harmony_modules && FLAG_print_interfaces && top->is_global_scope()) {
285 top->interface()->Print();
289 info->PrepareForCompilation(scope);
294 void Scope::Initialize() {
295 DCHECK(!already_resolved());
297 // Add this scope as a new inner scope of the outer scope.
298 if (outer_scope_ != NULL) {
299 outer_scope_->inner_scopes_.Add(this, zone());
300 scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
302 scope_inside_with_ = is_with_scope();
305 // Declare convenience variables.
306 // Declare and allocate receiver (even for the global scope, and even
307 // if naccesses_ == 0).
308 // NOTE: When loading parameters in the global scope, we must take
309 // care not to access them as properties of the global object, but
310 // instead load them directly from the stack. Currently, the only
311 // such parameter is 'this' which is passed on the stack when
313 if (is_declaration_scope()) {
315 variables_.Declare(this,
316 ast_value_factory_->this_string(),
320 kCreatedInitialized);
321 var->AllocateTo(Variable::PARAMETER, -1);
324 DCHECK(outer_scope() != NULL);
325 receiver_ = outer_scope()->receiver();
328 if (is_function_scope()) {
329 // Declare 'arguments' variable which exists in all functions.
330 // Note that it might never be accessed, in which case it won't be
331 // allocated during variable allocation.
332 variables_.Declare(this,
333 ast_value_factory_->arguments_string(),
337 kCreatedInitialized);
342 Scope* Scope::FinalizeBlockScope() {
343 DCHECK(is_block_scope());
344 DCHECK(internals_.is_empty());
345 DCHECK(temps_.is_empty());
346 DCHECK(params_.is_empty());
348 if (num_var_or_const() > 0) return this;
350 // Remove this scope from outer scope.
351 for (int i = 0; i < outer_scope_->inner_scopes_.length(); i++) {
352 if (outer_scope_->inner_scopes_[i] == this) {
353 outer_scope_->inner_scopes_.Remove(i);
358 // Reparent inner scopes.
359 for (int i = 0; i < inner_scopes_.length(); i++) {
360 outer_scope()->AddInnerScope(inner_scopes_[i]);
363 // Move unresolved variables
364 for (int i = 0; i < unresolved_.length(); i++) {
365 outer_scope()->unresolved_.Add(unresolved_[i], zone());
372 Variable* Scope::LookupLocal(const AstRawString* name) {
373 Variable* result = variables_.Lookup(name);
374 if (result != NULL || scope_info_.is_null()) {
377 // The Scope is backed up by ScopeInfo. This means it cannot operate in a
378 // heap-independent mode, and all strings must be internalized immediately. So
379 // it's ok to get the Handle<String> here.
380 Handle<String> name_handle = name->string();
381 // If we have a serialized scope info, we might find the variable there.
382 // There should be no local slot with the given name.
383 DCHECK(scope_info_->StackSlotIndex(*name_handle) < 0);
385 // Check context slot lookup.
387 Variable::Location location = Variable::CONTEXT;
388 InitializationFlag init_flag;
389 MaybeAssignedFlag maybe_assigned_flag;
390 int index = ScopeInfo::ContextSlotIndex(scope_info_, name_handle, &mode,
391 &init_flag, &maybe_assigned_flag);
394 index = scope_info_->ParameterIndex(*name_handle);
395 if (index < 0) return NULL;
398 location = Variable::LOOKUP;
399 init_flag = kCreatedInitialized;
400 // Be conservative and flag parameters as maybe assigned. Better information
401 // would require ScopeInfo to serialize the maybe_assigned bit also for
403 maybe_assigned_flag = kMaybeAssigned;
406 Variable* var = variables_.Declare(this, name, mode, true, Variable::NORMAL,
407 init_flag, maybe_assigned_flag);
408 var->AllocateTo(location, index);
413 Variable* Scope::LookupFunctionVar(const AstRawString* name,
414 AstNodeFactory<AstNullVisitor>* factory) {
415 if (function_ != NULL && function_->proxy()->raw_name() == name) {
416 return function_->proxy()->var();
417 } else if (!scope_info_.is_null()) {
418 // If we are backed by a scope info, try to lookup the variable there.
420 int index = scope_info_->FunctionContextSlotIndex(*(name->string()), &mode);
421 if (index < 0) return NULL;
422 Variable* var = new(zone()) Variable(
423 this, name, mode, true /* is valid LHS */,
424 Variable::NORMAL, kCreatedInitialized);
425 VariableProxy* proxy = factory->NewVariableProxy(var);
426 VariableDeclaration* declaration = factory->NewVariableDeclaration(
427 proxy, mode, this, RelocInfo::kNoPosition);
428 DeclareFunctionVar(declaration);
429 var->AllocateTo(Variable::CONTEXT, index);
437 Variable* Scope::Lookup(const AstRawString* name) {
438 for (Scope* scope = this;
440 scope = scope->outer_scope()) {
441 Variable* var = scope->LookupLocal(name);
442 if (var != NULL) return var;
448 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);
453 params_.Add(var, zone());
458 Variable* Scope::DeclareLocal(const AstRawString* name, VariableMode mode,
459 InitializationFlag init_flag,
460 MaybeAssignedFlag maybe_assigned_flag,
461 Interface* interface) {
462 DCHECK(!already_resolved());
463 // This function handles VAR, LET, and CONST modes. DYNAMIC variables are
464 // introduces during variable allocation, INTERNAL variables are allocated
465 // explicitly, and TEMPORARY variables are allocated via NewTemporary().
466 DCHECK(IsDeclaredVariableMode(mode));
468 return variables_.Declare(this, name, mode, true, Variable::NORMAL, init_flag,
469 maybe_assigned_flag, interface);
473 Variable* Scope::DeclareDynamicGlobal(const AstRawString* name) {
474 DCHECK(is_global_scope());
475 return variables_.Declare(this,
480 kCreatedInitialized);
484 void Scope::RemoveUnresolved(VariableProxy* var) {
485 // Most likely (always?) any variable we want to remove
486 // was just added before, so we search backwards.
487 for (int i = unresolved_.length(); i-- > 0;) {
488 if (unresolved_[i] == var) {
489 unresolved_.Remove(i);
496 Variable* Scope::NewInternal(const AstRawString* name) {
497 DCHECK(!already_resolved());
498 Variable* var = new(zone()) Variable(this,
503 kCreatedInitialized);
504 internals_.Add(var, zone());
509 Variable* Scope::NewTemporary(const AstRawString* name) {
510 DCHECK(!already_resolved());
511 Variable* var = new(zone()) Variable(this,
516 kCreatedInitialized);
517 temps_.Add(var, zone());
522 void Scope::AddDeclaration(Declaration* declaration) {
523 decls_.Add(declaration, zone());
527 void Scope::SetIllegalRedeclaration(Expression* expression) {
528 // Record only the first illegal redeclaration.
529 if (!HasIllegalRedeclaration()) {
530 illegal_redecl_ = expression;
532 DCHECK(HasIllegalRedeclaration());
536 void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
537 DCHECK(HasIllegalRedeclaration());
538 illegal_redecl_->Accept(visitor);
542 Declaration* Scope::CheckConflictingVarDeclarations() {
543 int length = decls_.length();
544 for (int i = 0; i < length; i++) {
545 Declaration* decl = decls_[i];
546 if (decl->mode() != VAR) continue;
547 const AstRawString* name = decl->proxy()->raw_name();
549 // Iterate through all scopes until and including the declaration scope.
550 Scope* previous = NULL;
551 Scope* current = decl->scope();
553 // There is a conflict if there exists a non-VAR binding.
554 Variable* other_var = current->variables_.Lookup(name);
555 if (other_var != NULL && other_var->mode() != VAR) {
559 current = current->outer_scope_;
560 } while (!previous->is_declaration_scope());
568 VarAndOrder(Variable* var, int order) : var_(var), order_(order) { }
569 Variable* var() const { return var_; }
570 int order() const { return order_; }
571 static int Compare(const VarAndOrder* a, const VarAndOrder* b) {
572 return a->order_ - b->order_;
581 void Scope::CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
582 ZoneList<Variable*>* context_locals) {
583 DCHECK(stack_locals != NULL);
584 DCHECK(context_locals != NULL);
586 // Collect internals which are always allocated on the heap.
587 for (int i = 0; i < internals_.length(); i++) {
588 Variable* var = internals_[i];
589 if (var->is_used()) {
590 DCHECK(var->IsContextSlot());
591 context_locals->Add(var, zone());
595 // Collect temporaries which are always allocated on the stack, unless the
596 // context as a whole has forced context allocation.
597 for (int i = 0; i < temps_.length(); i++) {
598 Variable* var = temps_[i];
599 if (var->is_used()) {
600 if (var->IsContextSlot()) {
601 DCHECK(has_forced_context_allocation());
602 context_locals->Add(var, zone());
604 DCHECK(var->IsStackLocal());
605 stack_locals->Add(var, zone());
610 // Collect declared local variables.
611 ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
612 for (VariableMap::Entry* p = variables_.Start();
614 p = variables_.Next(p)) {
615 Variable* var = reinterpret_cast<Variable*>(p->value);
616 if (var->is_used()) {
617 vars.Add(VarAndOrder(var, p->order), zone());
620 vars.Sort(VarAndOrder::Compare);
621 int var_count = vars.length();
622 for (int i = 0; i < var_count; i++) {
623 Variable* var = vars[i].var();
624 if (var->IsStackLocal()) {
625 stack_locals->Add(var, zone());
626 } else if (var->IsContextSlot()) {
627 context_locals->Add(var, zone());
633 bool Scope::AllocateVariables(CompilationInfo* info,
634 AstNodeFactory<AstNullVisitor>* factory) {
635 // 1) Propagate scope information.
636 bool outer_scope_calls_sloppy_eval = false;
637 if (outer_scope_ != NULL) {
638 outer_scope_calls_sloppy_eval =
639 outer_scope_->outer_scope_calls_sloppy_eval() |
640 outer_scope_->calls_sloppy_eval();
642 PropagateScopeInfo(outer_scope_calls_sloppy_eval);
644 // 2) Allocate module instances.
645 if (FLAG_harmony_modules && (is_global_scope() || is_module_scope())) {
646 DCHECK(num_modules_ == 0);
647 AllocateModulesRecursively(this);
650 // 3) Resolve variables.
651 if (!ResolveVariablesRecursively(info, factory)) return false;
653 // 4) Allocate variables.
654 AllocateVariablesRecursively();
660 bool Scope::HasTrivialContext() const {
661 // A function scope has a trivial context if it always is the global
662 // context. We iteratively scan out the context chain to see if
663 // there is anything that makes this scope non-trivial; otherwise we
665 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
666 if (scope->is_eval_scope()) return false;
667 if (scope->scope_inside_with_) return false;
668 if (scope->num_heap_slots_ > 0) return false;
674 bool Scope::HasTrivialOuterContext() const {
675 Scope* outer = outer_scope_;
676 if (outer == NULL) return true;
677 // Note that the outer context may be trivial in general, but the current
678 // scope may be inside a 'with' statement in which case the outer context
679 // for this scope is not trivial.
680 return !scope_inside_with_ && outer->HasTrivialContext();
684 bool Scope::HasLazyCompilableOuterContext() const {
685 Scope* outer = outer_scope_;
686 if (outer == NULL) return true;
687 // We have to prevent lazy compilation if this scope is inside a with scope
688 // and all declaration scopes between them have empty contexts. Such
689 // declaration scopes may become invisible during scope info deserialization.
690 outer = outer->DeclarationScope();
691 bool found_non_trivial_declarations = false;
692 for (const Scope* scope = outer; scope != NULL; scope = scope->outer_scope_) {
693 if (scope->is_with_scope() && !found_non_trivial_declarations) return false;
694 if (scope->is_declaration_scope() && scope->num_heap_slots() > 0) {
695 found_non_trivial_declarations = true;
702 bool Scope::AllowsLazyCompilation() const {
703 return !force_eager_compilation_ && HasLazyCompilableOuterContext();
707 bool Scope::AllowsLazyCompilationWithoutContext() const {
708 return !force_eager_compilation_ && HasTrivialOuterContext();
712 int Scope::ContextChainLength(Scope* scope) {
714 for (Scope* s = this; s != scope; s = s->outer_scope_) {
715 DCHECK(s != NULL); // scope must be in the scope chain
716 if (s->is_with_scope() || s->num_heap_slots() > 0) n++;
717 // Catch and module scopes always have heap slots.
718 DCHECK(!s->is_catch_scope() || s->num_heap_slots() > 0);
719 DCHECK(!s->is_module_scope() || s->num_heap_slots() > 0);
725 Scope* Scope::GlobalScope() {
727 while (!scope->is_global_scope()) {
728 scope = scope->outer_scope();
734 Scope* Scope::DeclarationScope() {
736 while (!scope->is_declaration_scope()) {
737 scope = scope->outer_scope();
743 Handle<ScopeInfo> Scope::GetScopeInfo() {
744 if (scope_info_.is_null()) {
745 scope_info_ = ScopeInfo::Create(this, zone());
751 void Scope::GetNestedScopeChain(
752 List<Handle<ScopeInfo> >* chain,
754 if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo()));
756 for (int i = 0; i < inner_scopes_.length(); i++) {
757 Scope* scope = inner_scopes_[i];
758 int beg_pos = scope->start_position();
759 int end_pos = scope->end_position();
760 DCHECK(beg_pos >= 0 && end_pos >= 0);
761 if (beg_pos <= position && position < end_pos) {
762 scope->GetNestedScopeChain(chain, position);
770 static const char* Header(ScopeType scope_type) {
771 switch (scope_type) {
772 case EVAL_SCOPE: return "eval";
773 case FUNCTION_SCOPE: return "function";
774 case MODULE_SCOPE: return "module";
775 case GLOBAL_SCOPE: return "global";
776 case CATCH_SCOPE: return "catch";
777 case BLOCK_SCOPE: return "block";
778 case WITH_SCOPE: return "with";
785 static void Indent(int n, const char* str) {
786 PrintF("%*s%s", n, "", str);
790 static void PrintName(const AstRawString* name) {
791 PrintF("%.*s", name->length(), name->raw_data());
795 static void PrintLocation(Variable* var) {
796 switch (var->location()) {
797 case Variable::UNALLOCATED:
799 case Variable::PARAMETER:
800 PrintF("parameter[%d]", var->index());
802 case Variable::LOCAL:
803 PrintF("local[%d]", var->index());
805 case Variable::CONTEXT:
806 PrintF("context[%d]", var->index());
808 case Variable::LOOKUP:
815 static void PrintVar(int indent, Variable* var) {
816 if (var->is_used() || !var->IsUnallocated()) {
817 Indent(indent, Variable::Mode2String(var->mode()));
819 PrintName(var->raw_name());
822 bool comma = !var->IsUnallocated();
823 if (var->has_forced_context_allocation()) {
824 if (comma) PrintF(", ");
825 PrintF("forced context allocation");
828 if (var->maybe_assigned() == kMaybeAssigned) {
829 if (comma) PrintF(", ");
830 PrintF("maybe assigned");
837 static void PrintMap(int indent, VariableMap* map) {
838 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
839 Variable* var = reinterpret_cast<Variable*>(p->value);
840 PrintVar(indent, var);
845 void Scope::Print(int n) {
846 int n0 = (n > 0 ? n : 0);
847 int n1 = n0 + 2; // indentation
850 Indent(n0, Header(scope_type_));
851 if (!scope_name_->IsEmpty()) {
853 PrintName(scope_name_);
856 // Print parameters, if any.
857 if (is_function_scope()) {
859 for (int i = 0; i < params_.length(); i++) {
860 if (i > 0) PrintF(", ");
861 PrintName(params_[i]->raw_name());
866 PrintF(" { // (%d, %d)\n", start_position(), end_position());
868 // Function name, if any (named function literals, only).
869 if (function_ != NULL) {
870 Indent(n1, "// (local) function name: ");
871 PrintName(function_->proxy()->raw_name());
876 if (HasTrivialOuterContext()) {
877 Indent(n1, "// scope has trivial outer context\n");
879 if (strict_mode() == STRICT) {
880 Indent(n1, "// strict mode scope\n");
882 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
883 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
884 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
885 if (outer_scope_calls_sloppy_eval_) {
886 Indent(n1, "// outer scope calls 'eval' in sloppy context\n");
888 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
889 if (num_stack_slots_ > 0) { Indent(n1, "// ");
890 PrintF("%d stack slots\n", num_stack_slots_); }
891 if (num_heap_slots_ > 0) { Indent(n1, "// ");
892 PrintF("%d heap slots\n", num_heap_slots_); }
895 if (function_ != NULL) {
896 Indent(n1, "// function var:\n");
897 PrintVar(n1, function_->proxy()->var());
900 if (temps_.length() > 0) {
901 Indent(n1, "// temporary vars:\n");
902 for (int i = 0; i < temps_.length(); i++) {
903 PrintVar(n1, temps_[i]);
907 if (internals_.length() > 0) {
908 Indent(n1, "// internal vars:\n");
909 for (int i = 0; i < internals_.length(); i++) {
910 PrintVar(n1, internals_[i]);
914 if (variables_.Start() != NULL) {
915 Indent(n1, "// local vars:\n");
916 PrintMap(n1, &variables_);
919 if (dynamics_ != NULL) {
920 Indent(n1, "// dynamic vars:\n");
921 PrintMap(n1, dynamics_->GetMap(DYNAMIC));
922 PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
923 PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
926 // Print inner scopes (disable by providing negative n).
928 for (int i = 0; i < inner_scopes_.length(); i++) {
930 inner_scopes_[i]->Print(n1);
939 Variable* Scope::NonLocal(const AstRawString* name, VariableMode mode) {
940 if (dynamics_ == NULL) dynamics_ = new (zone()) DynamicScopePart(zone());
941 VariableMap* map = dynamics_->GetMap(mode);
942 Variable* var = map->Lookup(name);
944 // Declare a new non-local.
945 InitializationFlag init_flag = (mode == VAR)
946 ? kCreatedInitialized : kNeedsInitialization;
947 var = map->Declare(NULL,
953 // Allocate it by giving it a dynamic lookup.
954 var->AllocateTo(Variable::LOOKUP, -1);
960 Variable* Scope::LookupRecursive(VariableProxy* proxy,
961 BindingKind* binding_kind,
962 AstNodeFactory<AstNullVisitor>* factory) {
963 DCHECK(binding_kind != NULL);
964 if (already_resolved() && is_with_scope()) {
965 // Short-cut: if the scope is deserialized from a scope info, variable
966 // allocation is already fixed. We can simply return with dynamic lookup.
967 *binding_kind = DYNAMIC_LOOKUP;
971 // Try to find the variable in this scope.
972 Variable* var = LookupLocal(proxy->raw_name());
974 // We found a variable and we are done. (Even if there is an 'eval' in
975 // this scope which introduces the same variable again, the resulting
976 // variable remains the same.)
978 *binding_kind = BOUND;
982 // We did not find a variable locally. Check against the function variable,
983 // if any. We can do this for all scopes, since the function variable is
984 // only present - if at all - for function scopes.
985 *binding_kind = UNBOUND;
986 var = LookupFunctionVar(proxy->raw_name(), factory);
988 *binding_kind = BOUND;
989 } else if (outer_scope_ != NULL) {
990 var = outer_scope_->LookupRecursive(proxy, binding_kind, factory);
991 if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
992 var->ForceContextAllocation();
995 DCHECK(is_global_scope());
998 if (is_with_scope()) {
999 DCHECK(!already_resolved());
1000 // The current scope is a with scope, so the variable binding can not be
1001 // statically resolved. However, note that it was necessary to do a lookup
1002 // in the outer scope anyway, because if a binding exists in an outer scope,
1003 // the associated variable has to be marked as potentially being accessed
1004 // from inside of an inner with scope (the property may not be in the 'with'
1006 if (var != NULL && proxy->is_assigned()) var->set_maybe_assigned();
1007 *binding_kind = DYNAMIC_LOOKUP;
1009 } else if (calls_sloppy_eval()) {
1010 // A variable binding may have been found in an outer scope, but the current
1011 // scope makes a sloppy 'eval' call, so the found variable may not be
1012 // the correct one (the 'eval' may introduce a binding with the same name).
1013 // In that case, change the lookup result to reflect this situation.
1014 if (*binding_kind == BOUND) {
1015 *binding_kind = BOUND_EVAL_SHADOWED;
1016 } else if (*binding_kind == UNBOUND) {
1017 *binding_kind = UNBOUND_EVAL_SHADOWED;
1024 bool Scope::ResolveVariable(CompilationInfo* info,
1025 VariableProxy* proxy,
1026 AstNodeFactory<AstNullVisitor>* factory) {
1027 DCHECK(info->global_scope()->is_global_scope());
1029 // If the proxy is already resolved there's nothing to do
1030 // (functions and consts may be resolved by the parser).
1031 if (proxy->var() != NULL) return true;
1033 // Otherwise, try to resolve the variable.
1034 BindingKind binding_kind;
1035 Variable* var = LookupRecursive(proxy, &binding_kind, factory);
1036 switch (binding_kind) {
1038 // We found a variable binding.
1041 case BOUND_EVAL_SHADOWED:
1042 // We either found a variable binding that might be shadowed by eval or
1043 // gave up on it (e.g. by encountering a local with the same in the outer
1044 // scope which was not promoted to a context, this can happen if we use
1045 // debugger to evaluate arbitrary expressions at a break point).
1046 if (var->IsGlobalObjectProperty()) {
1047 var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1048 } else if (var->is_dynamic()) {
1049 var = NonLocal(proxy->raw_name(), DYNAMIC);
1051 Variable* invalidated = var;
1052 var = NonLocal(proxy->raw_name(), DYNAMIC_LOCAL);
1053 var->set_local_if_not_shadowed(invalidated);
1058 // No binding has been found. Declare a variable on the global object.
1059 var = info->global_scope()->DeclareDynamicGlobal(proxy->raw_name());
1062 case UNBOUND_EVAL_SHADOWED:
1063 // No binding has been found. But some scope makes a sloppy 'eval' call.
1064 var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1067 case DYNAMIC_LOOKUP:
1068 // The variable could not be resolved statically.
1069 var = NonLocal(proxy->raw_name(), DYNAMIC);
1073 DCHECK(var != NULL);
1074 if (proxy->is_assigned()) var->set_maybe_assigned();
1076 if (FLAG_harmony_scoping && strict_mode() == STRICT &&
1077 var->is_const_mode() && proxy->is_assigned()) {
1078 // Assignment to const. Throw a syntax error.
1079 MessageLocation location(
1080 info->script(), proxy->position(), proxy->position());
1081 Isolate* isolate = info->isolate();
1082 Factory* factory = isolate->factory();
1083 Handle<JSArray> array = factory->NewJSArray(0);
1084 Handle<Object> result =
1085 factory->NewSyntaxError("harmony_const_assign", array);
1086 isolate->Throw(*result, &location);
1090 if (FLAG_harmony_modules) {
1093 if (FLAG_print_interface_details) {
1094 PrintF("# Resolve %.*s:\n", var->raw_name()->length(),
1095 var->raw_name()->raw_data());
1098 proxy->interface()->Unify(var->interface(), zone(), &ok);
1101 if (FLAG_print_interfaces) {
1102 PrintF("SCOPES TYPE ERROR\n");
1104 proxy->interface()->Print();
1106 var->interface()->Print();
1110 // Inconsistent use of module. Throw a syntax error.
1111 // TODO(rossberg): generate more helpful error message.
1112 MessageLocation location(
1113 info->script(), proxy->position(), proxy->position());
1114 Isolate* isolate = info->isolate();
1115 Factory* factory = isolate->factory();
1116 Handle<JSArray> array = factory->NewJSArray(1);
1117 JSObject::SetElement(array, 0, var->name(), NONE, STRICT).Assert();
1118 Handle<Object> result =
1119 factory->NewSyntaxError("module_type_error", array);
1120 isolate->Throw(*result, &location);
1131 bool Scope::ResolveVariablesRecursively(
1132 CompilationInfo* info,
1133 AstNodeFactory<AstNullVisitor>* factory) {
1134 DCHECK(info->global_scope()->is_global_scope());
1136 // Resolve unresolved variables for this scope.
1137 for (int i = 0; i < unresolved_.length(); i++) {
1138 if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1141 // Resolve unresolved variables for inner scopes.
1142 for (int i = 0; i < inner_scopes_.length(); i++) {
1143 if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
1151 void Scope::PropagateScopeInfo(bool outer_scope_calls_sloppy_eval ) {
1152 if (outer_scope_calls_sloppy_eval) {
1153 outer_scope_calls_sloppy_eval_ = true;
1156 bool calls_sloppy_eval =
1157 this->calls_sloppy_eval() || outer_scope_calls_sloppy_eval_;
1158 for (int i = 0; i < inner_scopes_.length(); i++) {
1159 Scope* inner = inner_scopes_[i];
1160 inner->PropagateScopeInfo(calls_sloppy_eval);
1161 if (inner->scope_calls_eval_ || inner->inner_scope_calls_eval_) {
1162 inner_scope_calls_eval_ = true;
1164 if (inner->force_eager_compilation_) {
1165 force_eager_compilation_ = true;
1171 bool Scope::MustAllocate(Variable* var) {
1172 // Give var a read/write use if there is a chance it might be accessed
1173 // via an eval() call. This is only possible if the variable has a
1175 if ((var->is_this() || !var->raw_name()->IsEmpty()) &&
1176 (var->has_forced_context_allocation() ||
1177 scope_calls_eval_ ||
1178 inner_scope_calls_eval_ ||
1179 scope_contains_with_ ||
1182 is_module_scope() ||
1183 is_global_scope())) {
1185 if (scope_calls_eval_ || inner_scope_calls_eval_) var->set_maybe_assigned();
1187 // Global variables do not need to be allocated.
1188 return !var->IsGlobalObjectProperty() && var->is_used();
1192 bool Scope::MustAllocateInContext(Variable* var) {
1193 // If var is accessed from an inner scope, or if there is a possibility
1194 // that it might be accessed from the current or an inner scope (through
1195 // an eval() call or a runtime with lookup), it must be allocated in the
1198 // Exceptions: If the scope as a whole has forced context allocation, all
1199 // variables will have context allocation, even temporaries. Otherwise
1200 // temporary variables are always stack-allocated. Catch-bound variables are
1201 // always context-allocated.
1202 if (has_forced_context_allocation()) return true;
1203 if (var->mode() == TEMPORARY) return false;
1204 if (var->mode() == INTERNAL) return true;
1205 if (is_catch_scope() || is_block_scope() || is_module_scope()) return true;
1206 if (is_global_scope() && IsLexicalVariableMode(var->mode())) return true;
1207 return var->has_forced_context_allocation() ||
1208 scope_calls_eval_ ||
1209 inner_scope_calls_eval_ ||
1210 scope_contains_with_;
1214 bool Scope::HasArgumentsParameter() {
1215 for (int i = 0; i < params_.length(); i++) {
1216 if (params_[i]->name().is_identical_to(
1217 isolate_->factory()->arguments_string())) {
1225 void Scope::AllocateStackSlot(Variable* var) {
1226 var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1230 void Scope::AllocateHeapSlot(Variable* var) {
1231 var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1235 void Scope::AllocateParameterLocals() {
1236 DCHECK(is_function_scope());
1237 Variable* arguments = LookupLocal(ast_value_factory_->arguments_string());
1238 DCHECK(arguments != NULL); // functions have 'arguments' declared implicitly
1240 bool uses_sloppy_arguments = false;
1242 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
1243 // 'arguments' is used. Unless there is also a parameter called
1244 // 'arguments', we must be conservative and allocate all parameters to
1245 // the context assuming they will be captured by the arguments object.
1246 // If we have a parameter named 'arguments', a (new) value is always
1247 // assigned to it via the function invocation. Then 'arguments' denotes
1248 // that specific parameter value and cannot be used to access the
1249 // parameters, which is why we don't need to allocate an arguments
1250 // object in that case.
1252 // We are using 'arguments'. Tell the code generator that is needs to
1253 // allocate the arguments object by setting 'arguments_'.
1254 arguments_ = arguments;
1256 // In strict mode 'arguments' does not alias formal parameters.
1257 // Therefore in strict mode we allocate parameters as if 'arguments'
1259 uses_sloppy_arguments = strict_mode() == SLOPPY;
1262 // The same parameter may occur multiple times in the parameters_ list.
1263 // If it does, and if it is not copied into the context object, it must
1264 // receive the highest parameter index for that parameter; thus iteration
1265 // order is relevant!
1266 for (int i = params_.length() - 1; i >= 0; --i) {
1267 Variable* var = params_[i];
1268 DCHECK(var->scope() == this);
1269 if (uses_sloppy_arguments || has_forced_context_allocation()) {
1270 // Force context allocation of the parameter.
1271 var->ForceContextAllocation();
1274 if (MustAllocate(var)) {
1275 if (MustAllocateInContext(var)) {
1276 DCHECK(var->IsUnallocated() || var->IsContextSlot());
1277 if (var->IsUnallocated()) {
1278 AllocateHeapSlot(var);
1281 DCHECK(var->IsUnallocated() || var->IsParameter());
1282 if (var->IsUnallocated()) {
1283 var->AllocateTo(Variable::PARAMETER, i);
1291 void Scope::AllocateNonParameterLocal(Variable* var) {
1292 DCHECK(var->scope() == this);
1293 DCHECK(!var->IsVariable(isolate_->factory()->dot_result_string()) ||
1294 !var->IsStackLocal());
1295 if (var->IsUnallocated() && MustAllocate(var)) {
1296 if (MustAllocateInContext(var)) {
1297 AllocateHeapSlot(var);
1299 AllocateStackSlot(var);
1305 void Scope::AllocateNonParameterLocals() {
1306 // All variables that have no rewrite yet are non-parameter locals.
1307 for (int i = 0; i < temps_.length(); i++) {
1308 AllocateNonParameterLocal(temps_[i]);
1311 for (int i = 0; i < internals_.length(); i++) {
1312 AllocateNonParameterLocal(internals_[i]);
1315 ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
1316 for (VariableMap::Entry* p = variables_.Start();
1318 p = variables_.Next(p)) {
1319 Variable* var = reinterpret_cast<Variable*>(p->value);
1320 vars.Add(VarAndOrder(var, p->order), zone());
1322 vars.Sort(VarAndOrder::Compare);
1323 int var_count = vars.length();
1324 for (int i = 0; i < var_count; i++) {
1325 AllocateNonParameterLocal(vars[i].var());
1328 // For now, function_ must be allocated at the very end. If it gets
1329 // allocated in the context, it must be the last slot in the context,
1330 // because of the current ScopeInfo implementation (see
1331 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
1332 if (function_ != NULL) {
1333 AllocateNonParameterLocal(function_->proxy()->var());
1338 void Scope::AllocateVariablesRecursively() {
1339 // Allocate variables for inner scopes.
1340 for (int i = 0; i < inner_scopes_.length(); i++) {
1341 inner_scopes_[i]->AllocateVariablesRecursively();
1344 // If scope is already resolved, we still need to allocate
1345 // variables in inner scopes which might not had been resolved yet.
1346 if (already_resolved()) return;
1347 // The number of slots required for variables.
1348 num_stack_slots_ = 0;
1349 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
1351 // Allocate variables for this scope.
1352 // Parameters must be allocated first, if any.
1353 if (is_function_scope()) AllocateParameterLocals();
1354 AllocateNonParameterLocals();
1356 // Force allocation of a context for this scope if necessary. For a 'with'
1357 // scope and for a function scope that makes an 'eval' call we need a context,
1358 // even if no local variables were statically allocated in the scope.
1359 // Likewise for modules.
1360 bool must_have_context = is_with_scope() || is_module_scope() ||
1361 (is_function_scope() && calls_eval());
1363 // If we didn't allocate any locals in the local context, then we only
1364 // need the minimal number of slots if we must have a context.
1365 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1366 num_heap_slots_ = 0;
1370 DCHECK(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1374 void Scope::AllocateModulesRecursively(Scope* host_scope) {
1375 if (already_resolved()) return;
1376 if (is_module_scope()) {
1377 DCHECK(interface_->IsFrozen());
1378 DCHECK(module_var_ == NULL);
1380 host_scope->NewInternal(ast_value_factory_->dot_module_string());
1381 ++host_scope->num_modules_;
1384 for (int i = 0; i < inner_scopes_.length(); i++) {
1385 Scope* inner_scope = inner_scopes_.at(i);
1386 inner_scope->AllocateModulesRecursively(host_scope);
1391 int Scope::StackLocalCount() const {
1392 return num_stack_slots() -
1393 (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
1397 int Scope::ContextLocalCount() const {
1398 if (num_heap_slots() == 0) return 0;
1399 return num_heap_slots() - Context::MIN_CONTEXT_SLOTS -
1400 (function_ != NULL && function_->proxy()->var()->IsContextSlot() ? 1 : 0);
1403 } } // namespace v8::internal