1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "bootstrapper.h"
35 #include "scopeinfo.h"
37 #include "allocation-inl.h"
44 // ----------------------------------------------------------------------------
45 // Implementation of LocalsMap
47 // Note: We are storing the handle locations as key values in the hash map.
48 // When inserting a new variable via Declare(), we rely on the fact that
49 // the handle location remains alive for the duration of that variable
50 // use. Because a Variable holding a handle with the same location exists
53 static bool Match(void* key1, void* key2) {
54 String* name1 = *reinterpret_cast<String**>(key1);
55 String* name2 = *reinterpret_cast<String**>(key2);
56 ASSERT(name1->IsSymbol());
57 ASSERT(name2->IsSymbol());
58 return name1 == name2;
62 VariableMap::VariableMap() : ZoneHashMap(Match, 8) {}
63 VariableMap::~VariableMap() {}
66 Variable* VariableMap::Declare(
72 InitializationFlag initialization_flag,
73 Interface* interface) {
74 Entry* p = ZoneHashMap::Lookup(name.location(), name->Hash(), true);
75 if (p->value == NULL) {
76 // The variable has not been declared yet -> insert it.
77 ASSERT(p->key == name.location());
78 p->value = new Variable(scope,
86 return reinterpret_cast<Variable*>(p->value);
90 Variable* VariableMap::Lookup(Handle<String> name) {
91 Entry* p = ZoneHashMap::Lookup(name.location(), name->Hash(), false);
93 ASSERT(*reinterpret_cast<String**>(p->key) == *name);
94 ASSERT(p->value != NULL);
95 return reinterpret_cast<Variable*>(p->value);
101 // ----------------------------------------------------------------------------
102 // Implementation of Scope
104 Scope::Scope(Scope* outer_scope, ScopeType type)
105 : isolate_(Isolate::Current()),
112 interface_(FLAG_harmony_modules &&
113 (type == MODULE_SCOPE || type == GLOBAL_SCOPE)
114 ? Interface::NewModule() : NULL),
115 already_resolved_(false) {
116 SetDefaults(type, outer_scope, Handle<ScopeInfo>::null());
117 // At some point we might want to provide outer scopes to
118 // eval scopes (by walking the stack and reading the scope info).
119 // In that case, the ASSERT below needs to be adjusted.
120 ASSERT_EQ(type == GLOBAL_SCOPE, outer_scope == NULL);
121 ASSERT(!HasIllegalRedeclaration());
125 Scope::Scope(Scope* inner_scope,
127 Handle<ScopeInfo> scope_info)
128 : isolate_(Isolate::Current()),
136 already_resolved_(true) {
137 SetDefaults(type, NULL, scope_info);
138 if (!scope_info.is_null()) {
139 num_heap_slots_ = scope_info_->ContextLength();
141 // Ensure at least MIN_CONTEXT_SLOTS to indicate a materialized context.
142 num_heap_slots_ = Max(num_heap_slots_,
143 static_cast<int>(Context::MIN_CONTEXT_SLOTS));
144 AddInnerScope(inner_scope);
148 Scope::Scope(Scope* inner_scope, Handle<String> catch_variable_name)
149 : isolate_(Isolate::Current()),
157 already_resolved_(true) {
158 SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
159 AddInnerScope(inner_scope);
161 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
162 Variable* variable = variables_.Declare(this,
165 true, // Valid left-hand side.
167 kCreatedInitialized);
168 AllocateHeapSlot(variable);
172 void Scope::SetDefaults(ScopeType type,
174 Handle<ScopeInfo> scope_info) {
175 outer_scope_ = outer_scope;
177 scope_name_ = isolate_->factory()->empty_symbol();
182 illegal_redecl_ = NULL;
183 scope_inside_with_ = false;
184 scope_contains_with_ = false;
185 scope_calls_eval_ = false;
186 // Inherit the strict mode from the parent scope.
187 language_mode_ = (outer_scope != NULL)
188 ? outer_scope->language_mode_ : CLASSIC_MODE;
189 qml_mode_flag_ = (outer_scope != NULL)
190 ? outer_scope->qml_mode_flag_ : kNonQmlMode;
191 outer_scope_calls_non_strict_eval_ = false;
192 inner_scope_calls_eval_ = false;
193 force_eager_compilation_ = false;
194 num_var_or_const_ = 0;
195 num_stack_slots_ = 0;
197 scope_info_ = scope_info;
198 start_position_ = RelocInfo::kNoPosition;
199 end_position_ = RelocInfo::kNoPosition;
200 if (!scope_info.is_null()) {
201 scope_calls_eval_ = scope_info->CallsEval();
202 language_mode_ = scope_info->language_mode();
207 Scope* Scope::DeserializeScopeChain(Context* context, Scope* global_scope) {
208 // Reconstruct the outer scope chain from a closure's context chain.
209 Scope* current_scope = NULL;
210 Scope* innermost_scope = NULL;
211 bool contains_with = false;
212 while (!context->IsGlobalContext()) {
213 if (context->IsWithContext()) {
214 Scope* with_scope = new Scope(current_scope,
216 Handle<ScopeInfo>::null());
217 current_scope = with_scope;
218 // All the inner scopes are inside a with.
219 contains_with = true;
220 for (Scope* s = innermost_scope; s != NULL; s = s->outer_scope()) {
221 s->scope_inside_with_ = true;
223 } else if (context->IsFunctionContext()) {
224 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
225 current_scope = new Scope(current_scope,
227 Handle<ScopeInfo>(scope_info));
228 } else if (context->IsBlockContext()) {
229 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
230 current_scope = new Scope(current_scope,
232 Handle<ScopeInfo>(scope_info));
234 ASSERT(context->IsCatchContext());
235 String* name = String::cast(context->extension());
236 current_scope = new Scope(current_scope, Handle<String>(name));
238 if (contains_with) current_scope->RecordWithStatement();
239 if (innermost_scope == NULL) innermost_scope = current_scope;
241 // Forget about a with when we move to a context for a different function.
242 if (context->previous()->closure() != context->closure()) {
243 contains_with = false;
245 context = context->previous();
248 global_scope->AddInnerScope(current_scope);
249 global_scope->PropagateScopeInfo(false);
250 return (innermost_scope == NULL) ? global_scope : innermost_scope;
254 bool Scope::Analyze(CompilationInfo* info) {
255 ASSERT(info->function() != NULL);
256 Scope* scope = info->function()->scope();
259 // Traverse the scope tree up to the first unresolved scope or the global
260 // scope and start scope resolution and variable allocation from that scope.
261 while (!top->is_global_scope() &&
262 !top->outer_scope()->already_resolved()) {
263 top = top->outer_scope();
266 // Allocate the variables.
268 AstNodeFactory<AstNullVisitor> ast_node_factory(info->isolate());
269 if (!top->AllocateVariables(info, &ast_node_factory)) return false;
273 if (info->isolate()->bootstrapper()->IsActive()
274 ? FLAG_print_builtin_scopes
275 : FLAG_print_scopes) {
279 if (FLAG_harmony_modules && FLAG_print_interfaces && top->is_global_scope()) {
281 top->interface()->Print();
285 if (FLAG_harmony_scoping) {
286 VariableProxy* proxy = scope->CheckAssignmentToConst();
288 // Found an assignment to const. Throw a syntax error.
289 MessageLocation location(info->script(),
292 Isolate* isolate = info->isolate();
293 Factory* factory = isolate->factory();
294 Handle<JSArray> array = factory->NewJSArray(0);
295 Handle<Object> result =
296 factory->NewSyntaxError("harmony_const_assign", array);
297 isolate->Throw(*result, &location);
302 info->SetScope(scope);
307 void Scope::Initialize() {
308 ASSERT(!already_resolved());
310 // Add this scope as a new inner scope of the outer scope.
311 if (outer_scope_ != NULL) {
312 outer_scope_->inner_scopes_.Add(this);
313 scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
315 scope_inside_with_ = is_with_scope();
318 // Declare convenience variables.
319 // Declare and allocate receiver (even for the global scope, and even
320 // if naccesses_ == 0).
321 // NOTE: When loading parameters in the global scope, we must take
322 // care not to access them as properties of the global object, but
323 // instead load them directly from the stack. Currently, the only
324 // such parameter is 'this' which is passed on the stack when
326 if (is_declaration_scope()) {
328 variables_.Declare(this,
329 isolate_->factory()->this_symbol(),
333 kCreatedInitialized);
334 var->AllocateTo(Variable::PARAMETER, -1);
337 ASSERT(outer_scope() != NULL);
338 receiver_ = outer_scope()->receiver();
341 if (is_function_scope()) {
342 // Declare 'arguments' variable which exists in all functions.
343 // Note that it might never be accessed, in which case it won't be
344 // allocated during variable allocation.
345 variables_.Declare(this,
346 isolate_->factory()->arguments_symbol(),
350 kCreatedInitialized);
355 Scope* Scope::FinalizeBlockScope() {
356 ASSERT(is_block_scope());
357 ASSERT(temps_.is_empty());
358 ASSERT(params_.is_empty());
360 if (num_var_or_const() > 0) return this;
362 // Remove this scope from outer scope.
363 for (int i = 0; i < outer_scope_->inner_scopes_.length(); i++) {
364 if (outer_scope_->inner_scopes_[i] == this) {
365 outer_scope_->inner_scopes_.Remove(i);
370 // Reparent inner scopes.
371 for (int i = 0; i < inner_scopes_.length(); i++) {
372 outer_scope()->AddInnerScope(inner_scopes_[i]);
375 // Move unresolved variables
376 for (int i = 0; i < unresolved_.length(); i++) {
377 outer_scope()->unresolved_.Add(unresolved_[i]);
384 Variable* Scope::LocalLookup(Handle<String> name) {
385 Variable* result = variables_.Lookup(name);
386 if (result != NULL || scope_info_.is_null()) {
389 // If we have a serialized scope info, we might find the variable there.
390 // There should be no local slot with the given name.
391 ASSERT(scope_info_->StackSlotIndex(*name) < 0);
393 // Check context slot lookup.
395 Variable::Location location = Variable::CONTEXT;
396 InitializationFlag init_flag;
397 int index = scope_info_->ContextSlotIndex(*name, &mode, &init_flag);
400 index = scope_info_->ParameterIndex(*name);
401 if (index < 0) return NULL;
404 location = Variable::LOOKUP;
405 init_flag = kCreatedInitialized;
409 variables_.Declare(this,
415 var->AllocateTo(location, index);
420 Variable* Scope::LookupFunctionVar(Handle<String> name,
421 AstNodeFactory<AstNullVisitor>* factory) {
422 if (function_ != NULL && function_->proxy()->name().is_identical_to(name)) {
423 return function_->proxy()->var();
424 } else if (!scope_info_.is_null()) {
425 // If we are backed by a scope info, try to lookup the variable there.
427 int index = scope_info_->FunctionContextSlotIndex(*name, &mode);
428 if (index < 0) return NULL;
429 Variable* var = new Variable(
430 this, name, mode, true /* is valid LHS */,
431 Variable::NORMAL, kCreatedInitialized);
432 VariableProxy* proxy = factory->NewVariableProxy(var);
433 VariableDeclaration* declaration =
434 factory->NewVariableDeclaration(proxy, mode, this);
435 DeclareFunctionVar(declaration);
436 var->AllocateTo(Variable::CONTEXT, index);
444 Variable* Scope::Lookup(Handle<String> name) {
445 for (Scope* scope = this;
447 scope = scope->outer_scope()) {
448 Variable* var = scope->LocalLookup(name);
449 if (var != NULL) return var;
455 void Scope::DeclareParameter(Handle<String> name, VariableMode mode) {
456 ASSERT(!already_resolved());
457 ASSERT(is_function_scope());
458 Variable* var = variables_.Declare(
459 this, name, mode, true, Variable::NORMAL, kCreatedInitialized);
464 Variable* Scope::DeclareLocal(Handle<String> name,
466 InitializationFlag init_flag,
467 Interface* interface) {
468 ASSERT(!already_resolved());
469 // This function handles VAR and CONST modes. DYNAMIC variables are
470 // introduces during variable allocation, INTERNAL variables are allocated
471 // explicitly, and TEMPORARY variables are allocated via NewTemporary().
472 ASSERT(mode == VAR ||
474 mode == CONST_HARMONY ||
477 return variables_.Declare(
478 this, name, mode, true, Variable::NORMAL, init_flag, interface);
482 Variable* Scope::DeclareGlobal(Handle<String> name) {
483 ASSERT(is_global_scope());
484 return variables_.Declare(this,
489 kCreatedInitialized);
493 void Scope::RemoveUnresolved(VariableProxy* var) {
494 // Most likely (always?) any variable we want to remove
495 // was just added before, so we search backwards.
496 for (int i = unresolved_.length(); i-- > 0;) {
497 if (unresolved_[i] == var) {
498 unresolved_.Remove(i);
505 Variable* Scope::NewTemporary(Handle<String> name) {
506 ASSERT(!already_resolved());
507 Variable* var = new Variable(this,
512 kCreatedInitialized);
518 void Scope::AddDeclaration(Declaration* declaration) {
519 decls_.Add(declaration);
523 void Scope::SetIllegalRedeclaration(Expression* expression) {
524 // Record only the first illegal redeclaration.
525 if (!HasIllegalRedeclaration()) {
526 illegal_redecl_ = expression;
528 ASSERT(HasIllegalRedeclaration());
532 void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
533 ASSERT(HasIllegalRedeclaration());
534 illegal_redecl_->Accept(visitor);
538 Declaration* Scope::CheckConflictingVarDeclarations() {
539 int length = decls_.length();
540 for (int i = 0; i < length; i++) {
541 Declaration* decl = decls_[i];
542 if (decl->mode() != VAR) continue;
543 Handle<String> name = decl->proxy()->name();
545 // Iterate through all scopes until and including the declaration scope.
546 Scope* previous = NULL;
547 Scope* current = decl->scope();
549 // There is a conflict if there exists a non-VAR binding.
550 Variable* other_var = current->variables_.Lookup(name);
551 if (other_var != NULL && other_var->mode() != VAR) {
555 current = current->outer_scope_;
556 } while (!previous->is_declaration_scope());
562 VariableProxy* Scope::CheckAssignmentToConst() {
564 if (is_extended_mode()) {
565 for (int i = 0; i < unresolved_.length(); i++) {
566 ASSERT(unresolved_[i]->var() != NULL);
567 if (unresolved_[i]->var()->is_const_mode() &&
568 unresolved_[i]->IsLValue()) {
569 return unresolved_[i];
574 // Check inner scopes.
575 for (int i = 0; i < inner_scopes_.length(); i++) {
576 VariableProxy* proxy = inner_scopes_[i]->CheckAssignmentToConst();
577 if (proxy != NULL) return proxy;
580 // No assignments to const found.
585 void Scope::CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
586 ZoneList<Variable*>* context_locals) {
587 ASSERT(stack_locals != NULL);
588 ASSERT(context_locals != NULL);
590 // Collect temporaries which are always allocated on the stack.
591 for (int i = 0; i < temps_.length(); i++) {
592 Variable* var = temps_[i];
593 if (var->is_used()) {
594 ASSERT(var->IsStackLocal());
595 stack_locals->Add(var);
599 // Collect declared local variables.
600 for (VariableMap::Entry* p = variables_.Start();
602 p = variables_.Next(p)) {
603 Variable* var = reinterpret_cast<Variable*>(p->value);
604 if (var->is_used()) {
605 if (var->IsStackLocal()) {
606 stack_locals->Add(var);
607 } else if (var->IsContextSlot()) {
608 context_locals->Add(var);
615 bool Scope::AllocateVariables(CompilationInfo* info,
616 AstNodeFactory<AstNullVisitor>* factory) {
617 // 1) Propagate scope information.
618 bool outer_scope_calls_non_strict_eval = false;
619 if (outer_scope_ != NULL) {
620 outer_scope_calls_non_strict_eval =
621 outer_scope_->outer_scope_calls_non_strict_eval() |
622 outer_scope_->calls_non_strict_eval();
624 PropagateScopeInfo(outer_scope_calls_non_strict_eval);
626 // 2) Resolve variables.
627 if (!ResolveVariablesRecursively(info, factory)) return false;
629 // 3) Allocate variables.
630 AllocateVariablesRecursively();
636 bool Scope::AllowsLazyCompilation() const {
637 return !force_eager_compilation_ && HasTrivialOuterContext();
641 bool Scope::HasTrivialContext() const {
642 // A function scope has a trivial context if it always is the global
643 // context. We iteratively scan out the context chain to see if
644 // there is anything that makes this scope non-trivial; otherwise we
646 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
647 if (scope->is_eval_scope()) return false;
648 if (scope->scope_inside_with_) return false;
649 if (scope->num_heap_slots_ > 0) return false;
655 bool Scope::HasTrivialOuterContext() const {
656 Scope* outer = outer_scope_;
657 if (outer == NULL) return true;
658 // Note that the outer context may be trivial in general, but the current
659 // scope may be inside a 'with' statement in which case the outer context
660 // for this scope is not trivial.
661 return !scope_inside_with_ && outer->HasTrivialContext();
665 bool Scope::AllowsLazyRecompilation() const {
666 return !force_eager_compilation_ &&
667 !TrivialDeclarationScopesBeforeWithScope();
671 bool Scope::TrivialDeclarationScopesBeforeWithScope() const {
672 Scope* outer = outer_scope_;
673 if (outer == NULL) return false;
674 outer = outer->DeclarationScope();
675 while (outer != NULL) {
676 if (outer->is_with_scope()) return true;
677 if (outer->is_declaration_scope() && outer->num_heap_slots() > 0)
679 outer = outer->outer_scope_;
685 int Scope::ContextChainLength(Scope* scope) {
687 for (Scope* s = this; s != scope; s = s->outer_scope_) {
688 ASSERT(s != NULL); // scope must be in the scope chain
689 if (s->num_heap_slots() > 0) n++;
695 Scope* Scope::DeclarationScope() {
697 while (!scope->is_declaration_scope()) {
698 scope = scope->outer_scope();
704 Handle<ScopeInfo> Scope::GetScopeInfo() {
705 if (scope_info_.is_null()) {
706 scope_info_ = ScopeInfo::Create(this);
712 void Scope::GetNestedScopeChain(
713 List<Handle<ScopeInfo> >* chain,
715 if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo()));
717 for (int i = 0; i < inner_scopes_.length(); i++) {
718 Scope* scope = inner_scopes_[i];
719 int beg_pos = scope->start_position();
720 int end_pos = scope->end_position();
721 ASSERT(beg_pos >= 0 && end_pos >= 0);
722 if (beg_pos <= position && position < end_pos) {
723 scope->GetNestedScopeChain(chain, position);
731 static const char* Header(ScopeType type) {
733 case EVAL_SCOPE: return "eval";
734 case FUNCTION_SCOPE: return "function";
735 case MODULE_SCOPE: return "module";
736 case GLOBAL_SCOPE: return "global";
737 case CATCH_SCOPE: return "catch";
738 case BLOCK_SCOPE: return "block";
739 case WITH_SCOPE: return "with";
746 static void Indent(int n, const char* str) {
747 PrintF("%*s%s", n, "", str);
751 static void PrintName(Handle<String> name) {
752 SmartArrayPointer<char> s = name->ToCString(DISALLOW_NULLS);
757 static void PrintLocation(Variable* var) {
758 switch (var->location()) {
759 case Variable::UNALLOCATED:
761 case Variable::PARAMETER:
762 PrintF("parameter[%d]", var->index());
764 case Variable::LOCAL:
765 PrintF("local[%d]", var->index());
767 case Variable::CONTEXT:
768 PrintF("context[%d]", var->index());
770 case Variable::LOOKUP:
777 static void PrintVar(int indent, Variable* var) {
778 if (var->is_used() || !var->IsUnallocated()) {
779 Indent(indent, Variable::Mode2String(var->mode()));
781 PrintName(var->name());
784 if (var->has_forced_context_allocation()) {
785 if (!var->IsUnallocated()) PrintF(", ");
786 PrintF("forced context allocation");
793 static void PrintMap(int indent, VariableMap* map) {
794 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
795 Variable* var = reinterpret_cast<Variable*>(p->value);
796 PrintVar(indent, var);
801 void Scope::Print(int n) {
802 int n0 = (n > 0 ? n : 0);
803 int n1 = n0 + 2; // indentation
806 Indent(n0, Header(type_));
807 if (scope_name_->length() > 0) {
809 PrintName(scope_name_);
812 // Print parameters, if any.
813 if (is_function_scope()) {
815 for (int i = 0; i < params_.length(); i++) {
816 if (i > 0) PrintF(", ");
817 PrintName(params_[i]->name());
822 PrintF(" { // (%d, %d)\n", start_position(), end_position());
824 // Function name, if any (named function literals, only).
825 if (function_ != NULL) {
826 Indent(n1, "// (local) function name: ");
827 PrintName(function_->proxy()->name());
832 if (HasTrivialOuterContext()) {
833 Indent(n1, "// scope has trivial outer context\n");
835 switch (language_mode()) {
839 Indent(n1, "// strict mode scope\n");
842 Indent(n1, "// extended mode scope\n");
845 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
846 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
847 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
848 if (outer_scope_calls_non_strict_eval_) {
849 Indent(n1, "// outer scope calls 'eval' in non-strict context\n");
851 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
852 if (num_stack_slots_ > 0) { Indent(n1, "// ");
853 PrintF("%d stack slots\n", num_stack_slots_); }
854 if (num_heap_slots_ > 0) { Indent(n1, "// ");
855 PrintF("%d heap slots\n", num_heap_slots_); }
858 Indent(n1, "// function var\n");
859 if (function_ != NULL) {
860 PrintVar(n1, function_->proxy()->var());
863 Indent(n1, "// temporary vars\n");
864 for (int i = 0; i < temps_.length(); i++) {
865 PrintVar(n1, temps_[i]);
868 Indent(n1, "// local vars\n");
869 PrintMap(n1, &variables_);
871 Indent(n1, "// dynamic vars\n");
872 if (dynamics_ != NULL) {
873 PrintMap(n1, dynamics_->GetMap(DYNAMIC));
874 PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
875 PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
878 // Print inner scopes (disable by providing negative n).
880 for (int i = 0; i < inner_scopes_.length(); i++) {
882 inner_scopes_[i]->Print(n1);
891 Variable* Scope::NonLocal(Handle<String> name, VariableMode mode) {
892 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
893 VariableMap* map = dynamics_->GetMap(mode);
894 Variable* var = map->Lookup(name);
896 // Declare a new non-local.
897 InitializationFlag init_flag = (mode == VAR)
898 ? kCreatedInitialized : kNeedsInitialization;
899 var = map->Declare(NULL,
905 // Allocate it by giving it a dynamic lookup.
906 var->AllocateTo(Variable::LOOKUP, -1);
912 Variable* Scope::LookupRecursive(Handle<String> name,
913 BindingKind* binding_kind,
914 AstNodeFactory<AstNullVisitor>* factory) {
915 ASSERT(binding_kind != NULL);
916 // Try to find the variable in this scope.
917 Variable* var = LocalLookup(name);
919 // We found a variable and we are done. (Even if there is an 'eval' in
920 // this scope which introduces the same variable again, the resulting
921 // variable remains the same.)
923 *binding_kind = BOUND;
927 // We did not find a variable locally. Check against the function variable,
928 // if any. We can do this for all scopes, since the function variable is
929 // only present - if at all - for function scopes.
930 *binding_kind = UNBOUND;
931 var = LookupFunctionVar(name, factory);
933 *binding_kind = BOUND;
934 } else if (outer_scope_ != NULL) {
935 var = outer_scope_->LookupRecursive(name, binding_kind, factory);
936 if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
937 var->ForceContextAllocation();
940 ASSERT(is_global_scope());
943 if (is_with_scope()) {
944 // The current scope is a with scope, so the variable binding can not be
945 // statically resolved. However, note that it was necessary to do a lookup
946 // in the outer scope anyway, because if a binding exists in an outer scope,
947 // the associated variable has to be marked as potentially being accessed
948 // from inside of an inner with scope (the property may not be in the 'with'
950 *binding_kind = DYNAMIC_LOOKUP;
952 } else if (calls_non_strict_eval()) {
953 // A variable binding may have been found in an outer scope, but the current
954 // scope makes a non-strict 'eval' call, so the found variable may not be
955 // the correct one (the 'eval' may introduce a binding with the same name).
956 // In that case, change the lookup result to reflect this situation.
957 if (*binding_kind == BOUND) {
958 *binding_kind = BOUND_EVAL_SHADOWED;
959 } else if (*binding_kind == UNBOUND) {
960 *binding_kind = UNBOUND_EVAL_SHADOWED;
967 bool Scope::ResolveVariable(CompilationInfo* info,
968 VariableProxy* proxy,
969 AstNodeFactory<AstNullVisitor>* factory) {
970 ASSERT(info->global_scope()->is_global_scope());
972 // If the proxy is already resolved there's nothing to do
973 // (functions and consts may be resolved by the parser).
974 if (proxy->var() != NULL) return true;
976 // Otherwise, try to resolve the variable.
977 BindingKind binding_kind;
978 Variable* var = LookupRecursive(proxy->name(), &binding_kind, factory);
979 switch (binding_kind) {
981 // We found a variable binding.
984 case BOUND_EVAL_SHADOWED:
985 // We either found a variable binding that might be shadowed by eval or
986 // gave up on it (e.g. by encountering a local with the same in the outer
987 // scope which was not promoted to a context, this can happen if we use
988 // debugger to evaluate arbitrary expressions at a break point).
989 if (var->is_global()) {
990 var = NonLocal(proxy->name(), DYNAMIC_GLOBAL);
993 Handle<GlobalObject> global = isolate_->global();
995 #ifdef ENABLE_DEBUGGER_SUPPORT
996 if (isolate_->debug()->IsLoaded() && isolate_->debug()->InDebugger()) {
997 // Get the context before the debugger was entered.
998 SaveContext *save = isolate_->save_context();
999 while (save != NULL && *save->context() == *isolate_->debug()->debug_context())
1000 save = save->prev();
1002 global = Handle<GlobalObject>(save->context()->global());
1006 if (is_qml_mode() && !global->HasProperty(*(proxy->name()))) {
1007 var->set_is_qml_global(true);
1010 } else if (var->is_dynamic()) {
1011 var = NonLocal(proxy->name(), DYNAMIC);
1013 Variable* invalidated = var;
1014 var = NonLocal(proxy->name(), DYNAMIC_LOCAL);
1015 var->set_local_if_not_shadowed(invalidated);
1020 // No binding has been found. Declare a variable in global scope.
1021 var = info->global_scope()->DeclareGlobal(proxy->name());
1023 if (is_qml_mode()) {
1024 Handle<GlobalObject> global = isolate_->global();
1026 #ifdef ENABLE_DEBUGGER_SUPPORT
1027 if (isolate_->debug()->IsLoaded() && isolate_->debug()->InDebugger()) {
1028 // Get the context before the debugger was entered.
1029 SaveContext *save = isolate_->save_context();
1030 while (save != NULL && *save->context() == *isolate_->debug()->debug_context())
1031 save = save->prev();
1033 global = Handle<GlobalObject>(save->context()->global());
1037 if (!global->HasProperty(*(proxy->name()))) {
1038 var->set_is_qml_global(true);
1044 case UNBOUND_EVAL_SHADOWED:
1045 // No binding has been found. But some scope makes a
1046 // non-strict 'eval' call.
1047 var = NonLocal(proxy->name(), DYNAMIC_GLOBAL);
1049 if (is_qml_mode()) {
1050 Handle<GlobalObject> global = isolate_->global();
1052 #ifdef ENABLE_DEBUGGER_SUPPORT
1053 if (isolate_->debug()->IsLoaded() && isolate_->debug()->InDebugger()) {
1054 // Get the context before the debugger was entered.
1055 SaveContext *save = isolate_->save_context();
1056 while (save != NULL && *save->context() == *isolate_->debug()->debug_context())
1057 save = save->prev();
1059 global = Handle<GlobalObject>(save->context()->global());
1063 if (is_qml_mode() && !global->HasProperty(*(proxy->name()))) {
1064 var->set_is_qml_global(true);
1070 case DYNAMIC_LOOKUP:
1071 // The variable could not be resolved statically.
1072 var = NonLocal(proxy->name(), DYNAMIC);
1076 ASSERT(var != NULL);
1079 if (FLAG_harmony_modules) {
1082 if (FLAG_print_interface_details)
1083 PrintF("# Resolve %s:\n", var->name()->ToAsciiArray());
1085 proxy->interface()->Unify(var->interface(), &ok);
1088 if (FLAG_print_interfaces) {
1089 PrintF("SCOPES TYPE ERROR\n");
1091 proxy->interface()->Print();
1093 var->interface()->Print();
1097 // Inconsistent use of module. Throw a syntax error.
1098 // TODO(rossberg): generate more helpful error message.
1099 MessageLocation location(info->script(),
1102 Isolate* isolate = Isolate::Current();
1103 Factory* factory = isolate->factory();
1104 Handle<JSArray> array = factory->NewJSArray(1);
1105 USE(JSObject::SetElement(array, 0, var->name(), NONE, kStrictMode));
1106 Handle<Object> result =
1107 factory->NewSyntaxError("module_type_error", array);
1108 isolate->Throw(*result, &location);
1117 bool Scope::ResolveVariablesRecursively(
1118 CompilationInfo* info,
1119 AstNodeFactory<AstNullVisitor>* factory) {
1120 ASSERT(info->global_scope()->is_global_scope());
1122 // Resolve unresolved variables for this scope.
1123 for (int i = 0; i < unresolved_.length(); i++) {
1124 if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1127 // Resolve unresolved variables for inner scopes.
1128 for (int i = 0; i < inner_scopes_.length(); i++) {
1129 if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
1137 bool Scope::PropagateScopeInfo(bool outer_scope_calls_non_strict_eval ) {
1138 if (outer_scope_calls_non_strict_eval) {
1139 outer_scope_calls_non_strict_eval_ = true;
1142 bool calls_non_strict_eval =
1143 this->calls_non_strict_eval() || outer_scope_calls_non_strict_eval_;
1144 for (int i = 0; i < inner_scopes_.length(); i++) {
1145 Scope* inner_scope = inner_scopes_[i];
1146 if (inner_scope->PropagateScopeInfo(calls_non_strict_eval)) {
1147 inner_scope_calls_eval_ = true;
1149 if (inner_scope->force_eager_compilation_) {
1150 force_eager_compilation_ = true;
1154 return scope_calls_eval_ || inner_scope_calls_eval_;
1158 bool Scope::MustAllocate(Variable* var) {
1159 // Give var a read/write use if there is a chance it might be accessed
1160 // via an eval() call. This is only possible if the variable has a
1162 if ((var->is_this() || var->name()->length() > 0) &&
1163 (var->has_forced_context_allocation() ||
1164 scope_calls_eval_ ||
1165 inner_scope_calls_eval_ ||
1166 scope_contains_with_ ||
1168 is_block_scope())) {
1169 var->set_is_used(true);
1171 // Global variables do not need to be allocated.
1172 return !var->is_global() && var->is_used();
1176 bool Scope::MustAllocateInContext(Variable* var) {
1177 // If var is accessed from an inner scope, or if there is a possibility
1178 // that it might be accessed from the current or an inner scope (through
1179 // an eval() call or a runtime with lookup), it must be allocated in the
1182 // Exceptions: temporary variables are never allocated in a context;
1183 // catch-bound variables are always allocated in a context.
1184 if (var->mode() == TEMPORARY) return false;
1185 if (is_catch_scope() || is_block_scope() || is_module_scope()) return true;
1186 return var->has_forced_context_allocation() ||
1187 scope_calls_eval_ ||
1188 inner_scope_calls_eval_ ||
1189 scope_contains_with_ ||
1194 bool Scope::HasArgumentsParameter() {
1195 for (int i = 0; i < params_.length(); i++) {
1196 if (params_[i]->name().is_identical_to(
1197 isolate_->factory()->arguments_symbol())) {
1205 void Scope::AllocateStackSlot(Variable* var) {
1206 var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1210 void Scope::AllocateHeapSlot(Variable* var) {
1211 var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1215 void Scope::AllocateParameterLocals() {
1216 ASSERT(is_function_scope());
1217 Variable* arguments = LocalLookup(isolate_->factory()->arguments_symbol());
1218 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
1220 bool uses_nonstrict_arguments = false;
1222 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
1223 // 'arguments' is used. Unless there is also a parameter called
1224 // 'arguments', we must be conservative and allocate all parameters to
1225 // the context assuming they will be captured by the arguments object.
1226 // If we have a parameter named 'arguments', a (new) value is always
1227 // assigned to it via the function invocation. Then 'arguments' denotes
1228 // that specific parameter value and cannot be used to access the
1229 // parameters, which is why we don't need to allocate an arguments
1230 // object in that case.
1232 // We are using 'arguments'. Tell the code generator that is needs to
1233 // allocate the arguments object by setting 'arguments_'.
1234 arguments_ = arguments;
1236 // In strict mode 'arguments' does not alias formal parameters.
1237 // Therefore in strict mode we allocate parameters as if 'arguments'
1239 uses_nonstrict_arguments = is_classic_mode();
1242 // The same parameter may occur multiple times in the parameters_ list.
1243 // If it does, and if it is not copied into the context object, it must
1244 // receive the highest parameter index for that parameter; thus iteration
1245 // order is relevant!
1246 for (int i = params_.length() - 1; i >= 0; --i) {
1247 Variable* var = params_[i];
1248 ASSERT(var->scope() == this);
1249 if (uses_nonstrict_arguments) {
1250 // Force context allocation of the parameter.
1251 var->ForceContextAllocation();
1254 if (MustAllocate(var)) {
1255 if (MustAllocateInContext(var)) {
1256 ASSERT(var->IsUnallocated() || var->IsContextSlot());
1257 if (var->IsUnallocated()) {
1258 AllocateHeapSlot(var);
1261 ASSERT(var->IsUnallocated() || var->IsParameter());
1262 if (var->IsUnallocated()) {
1263 var->AllocateTo(Variable::PARAMETER, i);
1271 void Scope::AllocateNonParameterLocal(Variable* var) {
1272 ASSERT(var->scope() == this);
1273 ASSERT(!var->IsVariable(isolate_->factory()->result_symbol()) ||
1274 !var->IsStackLocal());
1275 if (var->IsUnallocated() && MustAllocate(var)) {
1276 if (MustAllocateInContext(var)) {
1277 AllocateHeapSlot(var);
1279 AllocateStackSlot(var);
1285 void Scope::AllocateNonParameterLocals() {
1286 // All variables that have no rewrite yet are non-parameter locals.
1287 for (int i = 0; i < temps_.length(); i++) {
1288 AllocateNonParameterLocal(temps_[i]);
1291 for (VariableMap::Entry* p = variables_.Start();
1293 p = variables_.Next(p)) {
1294 Variable* var = reinterpret_cast<Variable*>(p->value);
1295 AllocateNonParameterLocal(var);
1298 // For now, function_ must be allocated at the very end. If it gets
1299 // allocated in the context, it must be the last slot in the context,
1300 // because of the current ScopeInfo implementation (see
1301 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
1302 if (function_ != NULL) {
1303 AllocateNonParameterLocal(function_->proxy()->var());
1308 void Scope::AllocateVariablesRecursively() {
1309 // Allocate variables for inner scopes.
1310 for (int i = 0; i < inner_scopes_.length(); i++) {
1311 inner_scopes_[i]->AllocateVariablesRecursively();
1314 // If scope is already resolved, we still need to allocate
1315 // variables in inner scopes which might not had been resolved yet.
1316 if (already_resolved()) return;
1317 // The number of slots required for variables.
1318 num_stack_slots_ = 0;
1319 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
1321 // Allocate variables for this scope.
1322 // Parameters must be allocated first, if any.
1323 if (is_function_scope()) AllocateParameterLocals();
1324 AllocateNonParameterLocals();
1326 // Force allocation of a context for this scope if necessary. For a 'with'
1327 // scope and for a function scope that makes an 'eval' call we need a context,
1328 // even if no local variables were statically allocated in the scope.
1329 // Likewise for modules.
1330 bool must_have_context = is_with_scope() || is_module_scope() ||
1331 (is_function_scope() && calls_eval());
1333 // If we didn't allocate any locals in the local context, then we only
1334 // need the minimal number of slots if we must have a context.
1335 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1336 num_heap_slots_ = 0;
1340 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1344 int Scope::StackLocalCount() const {
1345 return num_stack_slots() -
1346 (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
1350 int Scope::ContextLocalCount() const {
1351 if (num_heap_slots() == 0) return 0;
1352 return num_heap_slots() - Context::MIN_CONTEXT_SLOTS -
1353 (function_ != NULL && function_->proxy()->var()->IsContextSlot() ? 1 : 0);
1356 } } // namespace v8::internal