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/accessors.h"
8 #include "src/bootstrapper.h"
9 #include "src/messages.h"
10 #include "src/parser.h"
11 #include "src/scopeinfo.h"
12 #include "src/scopes.h"
17 // ----------------------------------------------------------------------------
18 // Implementation of LocalsMap
20 // Note: We are storing the handle locations as key values in the hash map.
21 // When inserting a new variable via Declare(), we rely on the fact that
22 // the handle location remains alive for the duration of that variable
23 // use. Because a Variable holding a handle with the same location exists
26 VariableMap::VariableMap(Zone* zone)
27 : ZoneHashMap(ZoneHashMap::PointersMatch, 8, ZoneAllocationPolicy(zone)),
29 VariableMap::~VariableMap() {}
32 Variable* VariableMap::Declare(Scope* scope, const AstRawString* name,
33 VariableMode mode, Variable::Kind kind,
34 InitializationFlag initialization_flag,
35 MaybeAssignedFlag maybe_assigned_flag) {
36 // AstRawStrings are unambiguous, i.e., the same string is always represented
37 // by the same AstRawString*.
38 // FIXME(marja): fix the type of Lookup.
39 Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
40 true, ZoneAllocationPolicy(zone()));
41 if (p->value == NULL) {
42 // The variable has not been declared yet -> insert it.
43 DCHECK(p->key == name);
44 p->value = new (zone()) Variable(scope, name, mode, kind,
45 initialization_flag, maybe_assigned_flag);
47 return reinterpret_cast<Variable*>(p->value);
51 Variable* VariableMap::Lookup(const AstRawString* name) {
52 Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
53 false, ZoneAllocationPolicy(NULL));
55 DCHECK(reinterpret_cast<const AstRawString*>(p->key) == name);
56 DCHECK(p->value != NULL);
57 return reinterpret_cast<Variable*>(p->value);
63 // ----------------------------------------------------------------------------
64 // Implementation of Scope
66 Scope::Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
67 AstValueFactory* ast_value_factory, FunctionKind function_kind)
68 : inner_scopes_(4, zone),
73 unresolved_(16, zone),
76 scope_type == MODULE_SCOPE ? ModuleDescriptor::New(zone) : NULL),
77 already_resolved_(false),
78 ast_value_factory_(ast_value_factory),
80 SetDefaults(scope_type, outer_scope, Handle<ScopeInfo>::null(),
82 // The outermost scope must be a script scope.
83 DCHECK(scope_type == SCRIPT_SCOPE || outer_scope != NULL);
84 DCHECK(!HasIllegalRedeclaration());
88 Scope::Scope(Zone* zone, Scope* inner_scope, ScopeType scope_type,
89 Handle<ScopeInfo> scope_info, AstValueFactory* value_factory)
90 : inner_scopes_(4, zone),
95 unresolved_(16, zone),
97 module_descriptor_(NULL),
98 already_resolved_(true),
99 ast_value_factory_(value_factory),
101 SetDefaults(scope_type, NULL, scope_info);
102 if (!scope_info.is_null()) {
103 num_heap_slots_ = scope_info_->ContextLength();
105 // Ensure at least MIN_CONTEXT_SLOTS to indicate a materialized context.
106 num_heap_slots_ = Max(num_heap_slots_,
107 static_cast<int>(Context::MIN_CONTEXT_SLOTS));
108 AddInnerScope(inner_scope);
112 Scope::Scope(Zone* zone, Scope* inner_scope,
113 const AstRawString* catch_variable_name,
114 AstValueFactory* value_factory)
115 : inner_scopes_(1, zone),
120 unresolved_(0, zone),
122 module_descriptor_(NULL),
123 already_resolved_(true),
124 ast_value_factory_(value_factory),
126 SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
127 AddInnerScope(inner_scope);
129 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
130 Variable* variable = variables_.Declare(this,
134 kCreatedInitialized);
135 AllocateHeapSlot(variable);
139 void Scope::SetDefaults(ScopeType scope_type, Scope* outer_scope,
140 Handle<ScopeInfo> scope_info,
141 FunctionKind function_kind) {
142 outer_scope_ = outer_scope;
143 scope_type_ = scope_type;
144 function_kind_ = function_kind;
145 block_scope_is_class_scope_ = false;
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();
184 block_scope_is_class_scope_ = scope_info->block_scope_is_class_scope();
185 function_kind_ = scope_info->function_kind();
190 Scope* Scope::DeserializeScopeChain(Isolate* isolate, Zone* zone,
191 Context* context, Scope* script_scope) {
192 // Reconstruct the outer scope chain from a closure's context chain.
193 Scope* current_scope = NULL;
194 Scope* innermost_scope = NULL;
195 bool contains_with = false;
196 while (!context->IsNativeContext()) {
197 if (context->IsWithContext()) {
198 Scope* with_scope = new (zone)
199 Scope(zone, current_scope, WITH_SCOPE, Handle<ScopeInfo>::null(),
200 script_scope->ast_value_factory_);
201 current_scope = with_scope;
202 // All the inner scopes are inside a with.
203 contains_with = true;
204 for (Scope* s = innermost_scope; s != NULL; s = s->outer_scope()) {
205 s->scope_inside_with_ = true;
207 } else if (context->IsScriptContext()) {
208 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
209 current_scope = new (zone) Scope(zone, current_scope, SCRIPT_SCOPE,
210 Handle<ScopeInfo>(scope_info),
211 script_scope->ast_value_factory_);
212 } else if (context->IsModuleContext()) {
213 ScopeInfo* scope_info = ScopeInfo::cast(context->module()->scope_info());
214 current_scope = new (zone) Scope(zone, current_scope, MODULE_SCOPE,
215 Handle<ScopeInfo>(scope_info),
216 script_scope->ast_value_factory_);
217 } else if (context->IsFunctionContext()) {
218 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
219 current_scope = new (zone) Scope(zone, current_scope, FUNCTION_SCOPE,
220 Handle<ScopeInfo>(scope_info),
221 script_scope->ast_value_factory_);
222 if (scope_info->IsAsmFunction()) current_scope->asm_function_ = true;
223 if (scope_info->IsAsmModule()) current_scope->asm_module_ = true;
224 } else if (context->IsBlockContext()) {
225 ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
226 current_scope = new (zone)
227 Scope(zone, current_scope, BLOCK_SCOPE, Handle<ScopeInfo>(scope_info),
228 script_scope->ast_value_factory_);
230 DCHECK(context->IsCatchContext());
231 String* name = String::cast(context->extension());
232 current_scope = new (zone) Scope(
234 script_scope->ast_value_factory_->GetString(Handle<String>(name)),
235 script_scope->ast_value_factory_);
237 if (contains_with) current_scope->RecordWithStatement();
238 if (innermost_scope == NULL) innermost_scope = current_scope;
240 // Forget about a with when we move to a context for a different function.
241 if (context->previous()->closure() != context->closure()) {
242 contains_with = false;
244 context = context->previous();
247 script_scope->AddInnerScope(current_scope);
248 script_scope->PropagateScopeInfo(false);
249 return (innermost_scope == NULL) ? script_scope : innermost_scope;
253 bool Scope::Analyze(ParseInfo* info) {
254 DCHECK(info->function() != NULL);
255 DCHECK(info->scope() == 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_script_scope() &&
262 !top->outer_scope()->already_resolved()) {
263 top = top->outer_scope();
266 // Allocate the variables.
268 AstNodeFactory ast_node_factory(info->ast_value_factory());
269 if (!top->AllocateVariables(info, &ast_node_factory)) {
270 DCHECK(top->pending_error_handler_.has_pending_error());
271 top->pending_error_handler_.ThrowPendingError(info->isolate(),
278 if (info->isolate()->bootstrapper()->IsActive()
279 ? FLAG_print_builtin_scopes
280 : FLAG_print_scopes) {
285 info->set_scope(scope);
290 void Scope::Initialize() {
291 bool subclass_constructor = IsSubclassConstructor(function_kind_);
292 DCHECK(!already_resolved());
294 // Add this scope as a new inner scope of the outer scope.
295 if (outer_scope_ != NULL) {
296 outer_scope_->inner_scopes_.Add(this, zone());
297 scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
299 scope_inside_with_ = is_with_scope();
302 // Declare convenience variables.
303 // Declare and allocate receiver (even for the script scope, and even
304 // if naccesses_ == 0).
305 // NOTE: When loading parameters in the script scope, we must take
306 // care not to access them as properties of the global object, but
307 // instead load them directly from the stack. Currently, the only
308 // such parameter is 'this' which is passed on the stack when
310 if (is_declaration_scope()) {
311 DCHECK(!subclass_constructor || is_function_scope());
312 Variable* var = variables_.Declare(
313 this, ast_value_factory_->this_string(),
314 subclass_constructor ? CONST : VAR, Variable::THIS,
315 subclass_constructor ? kNeedsInitialization : kCreatedInitialized);
316 var->AllocateTo(Variable::PARAMETER, -1);
319 if (subclass_constructor) {
321 variables_.Declare(this, ast_value_factory_->new_target_string(),
322 CONST, Variable::NEW_TARGET, kCreatedInitialized);
323 new_target_->AllocateTo(Variable::PARAMETER, -2);
324 new_target_->set_is_used();
327 DCHECK(outer_scope() != NULL);
328 receiver_ = outer_scope()->receiver();
331 if (is_function_scope()) {
332 // Declare 'arguments' variable which exists in all functions.
333 // Note that it might never be accessed, in which case it won't be
334 // allocated during variable allocation.
335 variables_.Declare(this,
336 ast_value_factory_->arguments_string(),
339 kCreatedInitialized);
344 Scope* Scope::FinalizeBlockScope() {
345 DCHECK(is_block_scope());
346 DCHECK(internals_.is_empty());
347 DCHECK(temps_.is_empty());
348 DCHECK(params_.is_empty());
350 if (num_var_or_const() > 0) return this;
352 // Remove this scope from outer scope.
353 for (int i = 0; i < outer_scope_->inner_scopes_.length(); i++) {
354 if (outer_scope_->inner_scopes_[i] == this) {
355 outer_scope_->inner_scopes_.Remove(i);
360 // Reparent inner scopes.
361 for (int i = 0; i < inner_scopes_.length(); i++) {
362 outer_scope()->AddInnerScope(inner_scopes_[i]);
365 // Move unresolved variables
366 for (int i = 0; i < unresolved_.length(); i++) {
367 outer_scope()->unresolved_.Add(unresolved_[i], zone());
370 // Propagate usage flags to outer scope.
371 if (uses_arguments()) outer_scope_->RecordArgumentsUsage();
372 if (uses_super_property()) outer_scope_->RecordSuperPropertyUsage();
373 if (uses_this()) outer_scope_->RecordThisUsage();
379 Variable* Scope::LookupLocal(const AstRawString* name) {
380 Variable* result = variables_.Lookup(name);
381 if (result != NULL || scope_info_.is_null()) {
384 // The Scope is backed up by ScopeInfo. This means it cannot operate in a
385 // heap-independent mode, and all strings must be internalized immediately. So
386 // it's ok to get the Handle<String> here.
387 Handle<String> name_handle = name->string();
388 // If we have a serialized scope info, we might find the variable there.
389 // There should be no local slot with the given name.
390 DCHECK(scope_info_->StackSlotIndex(*name_handle) < 0);
392 // Check context slot lookup.
394 Variable::Location location = Variable::CONTEXT;
395 InitializationFlag init_flag;
396 MaybeAssignedFlag maybe_assigned_flag;
397 int index = ScopeInfo::ContextSlotIndex(scope_info_, name_handle, &mode,
398 &init_flag, &maybe_assigned_flag);
401 index = scope_info_->ParameterIndex(*name_handle);
402 if (index < 0) return NULL;
405 location = Variable::LOOKUP;
406 init_flag = kCreatedInitialized;
407 // Be conservative and flag parameters as maybe assigned. Better information
408 // would require ScopeInfo to serialize the maybe_assigned bit also for
410 maybe_assigned_flag = kMaybeAssigned;
413 Variable* var = variables_.Declare(this, name, mode, Variable::NORMAL,
414 init_flag, maybe_assigned_flag);
415 var->AllocateTo(location, index);
420 Variable* Scope::LookupFunctionVar(const AstRawString* name,
421 AstNodeFactory* factory) {
422 if (function_ != NULL && function_->proxy()->raw_name() == 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->string()), &mode);
428 if (index < 0) return NULL;
429 Variable* var = new (zone())
430 Variable(this, name, mode, Variable::NORMAL, kCreatedInitialized);
431 VariableProxy* proxy = factory->NewVariableProxy(var);
432 VariableDeclaration* declaration = factory->NewVariableDeclaration(
433 proxy, mode, this, RelocInfo::kNoPosition);
434 DeclareFunctionVar(declaration);
435 var->AllocateTo(Variable::CONTEXT, index);
443 Variable* Scope::Lookup(const AstRawString* name) {
444 for (Scope* scope = this;
446 scope = scope->outer_scope()) {
447 Variable* var = scope->LookupLocal(name);
448 if (var != NULL) return var;
454 Variable* Scope::DeclareParameter(const AstRawString* name, VariableMode mode,
456 DCHECK(!already_resolved());
457 DCHECK(is_function_scope());
458 Variable* var = variables_.Declare(this, name, mode, Variable::NORMAL,
459 kCreatedInitialized);
461 DCHECK_NULL(rest_parameter_);
462 rest_parameter_ = var;
463 rest_index_ = num_parameters();
465 params_.Add(var, zone());
470 Variable* Scope::DeclareLocal(const AstRawString* name, VariableMode mode,
471 InitializationFlag init_flag, Variable::Kind kind,
472 MaybeAssignedFlag maybe_assigned_flag) {
473 DCHECK(!already_resolved());
474 // This function handles VAR, LET, and CONST modes. DYNAMIC variables are
475 // introduces during variable allocation, INTERNAL variables are allocated
476 // explicitly, and TEMPORARY variables are allocated via NewTemporary().
477 DCHECK(IsDeclaredVariableMode(mode));
479 return variables_.Declare(this, name, mode, kind, init_flag,
480 maybe_assigned_flag);
484 Variable* Scope::DeclareDynamicGlobal(const AstRawString* name) {
485 DCHECK(is_script_scope());
486 return variables_.Declare(this,
490 kCreatedInitialized);
494 void Scope::RemoveUnresolved(VariableProxy* var) {
495 // Most likely (always?) any variable we want to remove
496 // was just added before, so we search backwards.
497 for (int i = unresolved_.length(); i-- > 0;) {
498 if (unresolved_[i] == var) {
499 unresolved_.Remove(i);
506 Variable* Scope::NewInternal(const AstRawString* name) {
507 DCHECK(!already_resolved());
508 Variable* var = new(zone()) Variable(this,
512 kCreatedInitialized);
513 internals_.Add(var, zone());
518 Variable* Scope::NewTemporary(const AstRawString* name) {
519 DCHECK(!already_resolved());
520 Variable* var = new(zone()) Variable(this,
524 kCreatedInitialized);
525 temps_.Add(var, zone());
530 void Scope::AddDeclaration(Declaration* declaration) {
531 decls_.Add(declaration, zone());
535 void Scope::SetIllegalRedeclaration(Expression* expression) {
536 // Record only the first illegal redeclaration.
537 if (!HasIllegalRedeclaration()) {
538 illegal_redecl_ = expression;
540 DCHECK(HasIllegalRedeclaration());
544 void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
545 DCHECK(HasIllegalRedeclaration());
546 illegal_redecl_->Accept(visitor);
550 Declaration* Scope::CheckConflictingVarDeclarations() {
551 int length = decls_.length();
552 for (int i = 0; i < length; i++) {
553 Declaration* decl = decls_[i];
554 if (decl->mode() != VAR) continue;
555 const AstRawString* name = decl->proxy()->raw_name();
557 // Iterate through all scopes until and including the declaration scope.
558 Scope* previous = NULL;
559 Scope* current = decl->scope();
561 // There is a conflict if there exists a non-VAR binding.
562 Variable* other_var = current->variables_.Lookup(name);
563 if (other_var != NULL && other_var->mode() != VAR) {
567 current = current->outer_scope_;
568 } while (!previous->is_declaration_scope());
576 VarAndOrder(Variable* var, int order) : var_(var), order_(order) { }
577 Variable* var() const { return var_; }
578 int order() const { return order_; }
579 static int Compare(const VarAndOrder* a, const VarAndOrder* b) {
580 return a->order_ - b->order_;
589 void Scope::CollectStackAndContextLocals(
590 ZoneList<Variable*>* stack_locals, ZoneList<Variable*>* context_locals,
591 ZoneList<Variable*>* strong_mode_free_variables) {
592 DCHECK(stack_locals != NULL);
593 DCHECK(context_locals != NULL);
595 // Collect internals which are always allocated on the heap.
596 for (int i = 0; i < internals_.length(); i++) {
597 Variable* var = internals_[i];
598 if (var->is_used()) {
599 DCHECK(var->IsContextSlot());
600 context_locals->Add(var, zone());
604 // Collect temporaries which are always allocated on the stack, unless the
605 // context as a whole has forced context allocation.
606 for (int i = 0; i < temps_.length(); i++) {
607 Variable* var = temps_[i];
608 if (var->is_used()) {
609 if (var->IsContextSlot()) {
610 DCHECK(has_forced_context_allocation());
611 context_locals->Add(var, zone());
613 DCHECK(var->IsStackLocal());
614 stack_locals->Add(var, zone());
619 // Collect declared local variables.
620 ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
621 for (VariableMap::Entry* p = variables_.Start();
623 p = variables_.Next(p)) {
624 Variable* var = reinterpret_cast<Variable*>(p->value);
625 if (strong_mode_free_variables && var->has_strong_mode_reference() &&
626 var->mode() == DYNAMIC_GLOBAL) {
627 strong_mode_free_variables->Add(var, zone());
630 if (var->is_used()) {
631 vars.Add(VarAndOrder(var, p->order), zone());
634 vars.Sort(VarAndOrder::Compare);
635 int var_count = vars.length();
636 for (int i = 0; i < var_count; i++) {
637 Variable* var = vars[i].var();
638 if (var->IsStackLocal()) {
639 stack_locals->Add(var, zone());
640 } else if (var->IsContextSlot()) {
641 context_locals->Add(var, zone());
647 bool Scope::AllocateVariables(ParseInfo* info, AstNodeFactory* factory) {
648 // 1) Propagate scope information.
649 bool outer_scope_calls_sloppy_eval = false;
650 if (outer_scope_ != NULL) {
651 outer_scope_calls_sloppy_eval =
652 outer_scope_->outer_scope_calls_sloppy_eval() |
653 outer_scope_->calls_sloppy_eval();
655 PropagateScopeInfo(outer_scope_calls_sloppy_eval);
657 // 2) Allocate module instances.
658 if (FLAG_harmony_modules && is_script_scope()) {
659 DCHECK(num_modules_ == 0);
663 // 3) Resolve variables.
664 if (!ResolveVariablesRecursively(info, factory)) return false;
666 // 4) Allocate variables.
667 AllocateVariablesRecursively(info->isolate());
673 bool Scope::HasTrivialContext() const {
674 // A function scope has a trivial context if it always is the global
675 // context. We iteratively scan out the context chain to see if
676 // there is anything that makes this scope non-trivial; otherwise we
678 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
679 if (scope->is_eval_scope()) return false;
680 if (scope->scope_inside_with_) return false;
681 if (scope->num_heap_slots_ > 0) return false;
687 bool Scope::HasTrivialOuterContext() const {
688 Scope* outer = outer_scope_;
689 if (outer == NULL) return true;
690 // Note that the outer context may be trivial in general, but the current
691 // scope may be inside a 'with' statement in which case the outer context
692 // for this scope is not trivial.
693 return !scope_inside_with_ && outer->HasTrivialContext();
697 bool Scope::HasLazyCompilableOuterContext() const {
698 Scope* outer = outer_scope_;
699 if (outer == NULL) return true;
700 // We have to prevent lazy compilation if this scope is inside a with scope
701 // and all declaration scopes between them have empty contexts. Such
702 // declaration scopes may become invisible during scope info deserialization.
703 outer = outer->DeclarationScope();
704 bool found_non_trivial_declarations = false;
705 for (const Scope* scope = outer; scope != NULL; scope = scope->outer_scope_) {
706 if (scope->is_with_scope() && !found_non_trivial_declarations) return false;
707 if (scope->is_declaration_scope() && scope->num_heap_slots() > 0) {
708 found_non_trivial_declarations = true;
715 bool Scope::AllowsLazyCompilation() const {
716 return !force_eager_compilation_ && HasLazyCompilableOuterContext();
720 bool Scope::AllowsLazyCompilationWithoutContext() const {
721 return !force_eager_compilation_ && HasTrivialOuterContext();
725 int Scope::ContextChainLength(Scope* scope) {
727 for (Scope* s = this; s != scope; s = s->outer_scope_) {
728 DCHECK(s != NULL); // scope must be in the scope chain
729 if (s->is_with_scope() || s->num_heap_slots() > 0) n++;
730 // Catch and module scopes always have heap slots.
731 DCHECK(!s->is_catch_scope() || s->num_heap_slots() > 0);
732 DCHECK(!s->is_module_scope() || s->num_heap_slots() > 0);
738 Scope* Scope::ScriptScope() {
740 while (!scope->is_script_scope()) {
741 scope = scope->outer_scope();
747 Scope* Scope::DeclarationScope() {
749 while (!scope->is_declaration_scope()) {
750 scope = scope->outer_scope();
756 Handle<ScopeInfo> Scope::GetScopeInfo(Isolate* isolate) {
757 if (scope_info_.is_null()) {
758 scope_info_ = ScopeInfo::Create(isolate, zone(), this);
764 void Scope::GetNestedScopeChain(Isolate* isolate,
765 List<Handle<ScopeInfo> >* chain, int position) {
766 if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo(isolate)));
768 for (int i = 0; i < inner_scopes_.length(); i++) {
769 Scope* scope = inner_scopes_[i];
770 int beg_pos = scope->start_position();
771 int end_pos = scope->end_position();
772 DCHECK(beg_pos >= 0 && end_pos >= 0);
773 if (beg_pos <= position && position < end_pos) {
774 scope->GetNestedScopeChain(isolate, chain, position);
781 void Scope::ReportMessage(int start_position, int end_position,
782 const char* message, const AstRawString* arg) {
783 // Propagate the error to the topmost scope targeted by this scope analysis
786 while (!top->is_script_scope() && !top->outer_scope()->already_resolved()) {
787 top = top->outer_scope();
790 top->pending_error_handler_.ReportMessageAt(start_position, end_position,
791 message, arg, kReferenceError);
796 static const char* Header(ScopeType scope_type) {
797 switch (scope_type) {
798 case EVAL_SCOPE: return "eval";
799 case FUNCTION_SCOPE: return "function";
800 case MODULE_SCOPE: return "module";
801 case SCRIPT_SCOPE: return "global";
802 case CATCH_SCOPE: return "catch";
803 case BLOCK_SCOPE: return "block";
804 case WITH_SCOPE: return "with";
805 case ARROW_SCOPE: return "arrow";
812 static void Indent(int n, const char* str) {
813 PrintF("%*s%s", n, "", str);
817 static void PrintName(const AstRawString* name) {
818 PrintF("%.*s", name->length(), name->raw_data());
822 static void PrintLocation(Variable* var) {
823 switch (var->location()) {
824 case Variable::UNALLOCATED:
826 case Variable::PARAMETER:
827 PrintF("parameter[%d]", var->index());
829 case Variable::LOCAL:
830 PrintF("local[%d]", var->index());
832 case Variable::CONTEXT:
833 PrintF("context[%d]", var->index());
835 case Variable::LOOKUP:
842 static void PrintVar(int indent, Variable* var) {
843 if (var->is_used() || !var->IsUnallocated()) {
844 Indent(indent, Variable::Mode2String(var->mode()));
846 PrintName(var->raw_name());
849 bool comma = !var->IsUnallocated();
850 if (var->has_forced_context_allocation()) {
851 if (comma) PrintF(", ");
852 PrintF("forced context allocation");
855 if (var->maybe_assigned() == kMaybeAssigned) {
856 if (comma) PrintF(", ");
857 PrintF("maybe assigned");
864 static void PrintMap(int indent, VariableMap* map) {
865 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
866 Variable* var = reinterpret_cast<Variable*>(p->value);
867 PrintVar(indent, var);
872 void Scope::Print(int n) {
873 int n0 = (n > 0 ? n : 0);
874 int n1 = n0 + 2; // indentation
877 Indent(n0, Header(scope_type_));
878 if (!scope_name_->IsEmpty()) {
880 PrintName(scope_name_);
883 // Print parameters, if any.
884 if (is_function_scope()) {
886 for (int i = 0; i < params_.length(); i++) {
887 if (i > 0) PrintF(", ");
888 PrintName(params_[i]->raw_name());
893 PrintF(" { // (%d, %d)\n", start_position(), end_position());
895 // Function name, if any (named function literals, only).
896 if (function_ != NULL) {
897 Indent(n1, "// (local) function name: ");
898 PrintName(function_->proxy()->raw_name());
903 if (HasTrivialOuterContext()) {
904 Indent(n1, "// scope has trivial outer context\n");
906 if (is_strong(language_mode())) {
907 Indent(n1, "// strong mode scope\n");
908 } else if (is_strict(language_mode())) {
909 Indent(n1, "// strict mode scope\n");
911 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
912 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
913 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
914 if (scope_uses_arguments_) Indent(n1, "// scope uses 'arguments'\n");
915 if (scope_uses_super_property_)
916 Indent(n1, "// scope uses 'super' property\n");
917 if (scope_uses_this_) Indent(n1, "// scope uses 'this'\n");
918 if (inner_scope_uses_arguments_) {
919 Indent(n1, "// inner scope uses 'arguments'\n");
921 if (inner_scope_uses_super_property_)
922 Indent(n1, "// inner scope uses 'super' property\n");
923 if (inner_scope_uses_this_) Indent(n1, "// inner scope uses 'this'\n");
924 if (outer_scope_calls_sloppy_eval_) {
925 Indent(n1, "// outer scope calls 'eval' in sloppy context\n");
927 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
928 if (num_stack_slots_ > 0) { Indent(n1, "// ");
929 PrintF("%d stack slots\n", num_stack_slots_); }
930 if (num_heap_slots_ > 0) { Indent(n1, "// ");
931 PrintF("%d heap slots\n", num_heap_slots_); }
934 if (function_ != NULL) {
935 Indent(n1, "// function var:\n");
936 PrintVar(n1, function_->proxy()->var());
939 if (temps_.length() > 0) {
940 Indent(n1, "// temporary vars:\n");
941 for (int i = 0; i < temps_.length(); i++) {
942 PrintVar(n1, temps_[i]);
946 if (internals_.length() > 0) {
947 Indent(n1, "// internal vars:\n");
948 for (int i = 0; i < internals_.length(); i++) {
949 PrintVar(n1, internals_[i]);
953 if (variables_.Start() != NULL) {
954 Indent(n1, "// local vars:\n");
955 PrintMap(n1, &variables_);
958 if (dynamics_ != NULL) {
959 Indent(n1, "// dynamic vars:\n");
960 PrintMap(n1, dynamics_->GetMap(DYNAMIC));
961 PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
962 PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
965 // Print inner scopes (disable by providing negative n).
967 for (int i = 0; i < inner_scopes_.length(); i++) {
969 inner_scopes_[i]->Print(n1);
978 Variable* Scope::NonLocal(const AstRawString* name, VariableMode mode) {
979 if (dynamics_ == NULL) dynamics_ = new (zone()) DynamicScopePart(zone());
980 VariableMap* map = dynamics_->GetMap(mode);
981 Variable* var = map->Lookup(name);
983 // Declare a new non-local.
984 InitializationFlag init_flag = (mode == VAR)
985 ? kCreatedInitialized : kNeedsInitialization;
986 var = map->Declare(NULL,
991 // Allocate it by giving it a dynamic lookup.
992 var->AllocateTo(Variable::LOOKUP, -1);
998 Variable* Scope::LookupRecursive(VariableProxy* proxy,
999 BindingKind* binding_kind,
1000 AstNodeFactory* factory) {
1001 DCHECK(binding_kind != NULL);
1002 if (already_resolved() && is_with_scope()) {
1003 // Short-cut: if the scope is deserialized from a scope info, variable
1004 // allocation is already fixed. We can simply return with dynamic lookup.
1005 *binding_kind = DYNAMIC_LOOKUP;
1009 // Try to find the variable in this scope.
1010 Variable* var = LookupLocal(proxy->raw_name());
1012 // We found a variable and we are done. (Even if there is an 'eval' in
1013 // this scope which introduces the same variable again, the resulting
1014 // variable remains the same.)
1016 *binding_kind = BOUND;
1020 // We did not find a variable locally. Check against the function variable,
1021 // if any. We can do this for all scopes, since the function variable is
1022 // only present - if at all - for function scopes.
1023 *binding_kind = UNBOUND;
1024 var = LookupFunctionVar(proxy->raw_name(), factory);
1026 *binding_kind = BOUND;
1027 } else if (outer_scope_ != NULL) {
1028 var = outer_scope_->LookupRecursive(proxy, binding_kind, factory);
1029 if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
1030 var->ForceContextAllocation();
1033 DCHECK(is_script_scope());
1036 if (is_with_scope()) {
1037 DCHECK(!already_resolved());
1038 // The current scope is a with scope, so the variable binding can not be
1039 // statically resolved. However, note that it was necessary to do a lookup
1040 // in the outer scope anyway, because if a binding exists in an outer scope,
1041 // the associated variable has to be marked as potentially being accessed
1042 // from inside of an inner with scope (the property may not be in the 'with'
1044 if (var != NULL && proxy->is_assigned()) var->set_maybe_assigned();
1045 *binding_kind = DYNAMIC_LOOKUP;
1047 } else if (calls_sloppy_eval()) {
1048 // A variable binding may have been found in an outer scope, but the current
1049 // scope makes a sloppy 'eval' call, so the found variable may not be
1050 // the correct one (the 'eval' may introduce a binding with the same name).
1051 // In that case, change the lookup result to reflect this situation.
1052 if (*binding_kind == BOUND) {
1053 *binding_kind = BOUND_EVAL_SHADOWED;
1054 } else if (*binding_kind == UNBOUND) {
1055 *binding_kind = UNBOUND_EVAL_SHADOWED;
1062 bool Scope::ResolveVariable(ParseInfo* info, VariableProxy* proxy,
1063 AstNodeFactory* factory) {
1064 DCHECK(info->script_scope()->is_script_scope());
1066 // If the proxy is already resolved there's nothing to do
1067 // (functions and consts may be resolved by the parser).
1068 if (proxy->is_resolved()) return true;
1070 // Otherwise, try to resolve the variable.
1071 BindingKind binding_kind;
1072 Variable* var = LookupRecursive(proxy, &binding_kind, factory);
1073 switch (binding_kind) {
1075 // We found a variable binding.
1076 if (is_strong(language_mode())) {
1077 if (!CheckStrongModeDeclaration(proxy, var)) return false;
1081 case BOUND_EVAL_SHADOWED:
1082 // We either found a variable binding that might be shadowed by eval or
1083 // gave up on it (e.g. by encountering a local with the same in the outer
1084 // scope which was not promoted to a context, this can happen if we use
1085 // debugger to evaluate arbitrary expressions at a break point).
1086 if (var->IsGlobalObjectProperty()) {
1087 var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1088 } else if (var->is_dynamic()) {
1089 var = NonLocal(proxy->raw_name(), DYNAMIC);
1091 Variable* invalidated = var;
1092 var = NonLocal(proxy->raw_name(), DYNAMIC_LOCAL);
1093 var->set_local_if_not_shadowed(invalidated);
1098 // No binding has been found. Declare a variable on the global object.
1099 var = info->script_scope()->DeclareDynamicGlobal(proxy->raw_name());
1102 case UNBOUND_EVAL_SHADOWED:
1103 // No binding has been found. But some scope makes a sloppy 'eval' call.
1104 var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1107 case DYNAMIC_LOOKUP:
1108 // The variable could not be resolved statically.
1109 var = NonLocal(proxy->raw_name(), DYNAMIC);
1113 DCHECK(var != NULL);
1114 if (proxy->is_assigned()) var->set_maybe_assigned();
1116 if (is_strong(language_mode())) {
1117 // Record that the variable is referred to from strong mode. Also, record
1119 var->RecordStrongModeReference(proxy->position(), proxy->end_position());
1128 bool Scope::CheckStrongModeDeclaration(VariableProxy* proxy, Variable* var) {
1129 // Check for declaration-after use (for variables) in strong mode. Note that
1130 // we can only do this in the case where we have seen the declaration. And we
1131 // always allow referencing functions (for now).
1133 // Allow referencing the class name from methods of that class, even though
1134 // the initializer position for class names is only after the body.
1135 Scope* scope = this;
1137 if (scope->ClassVariableForMethod() == var) return true;
1138 scope = scope->outer_scope();
1141 // If both the use and the declaration are inside an eval scope (possibly
1142 // indirectly), or one of them is, we need to check whether they are inside
1143 // the same eval scope or different ones.
1145 // TODO(marja,rossberg): Detect errors across different evals (depends on the
1146 // future of eval in strong mode).
1147 const Scope* eval_for_use = NearestOuterEvalScope();
1148 const Scope* eval_for_declaration = var->scope()->NearestOuterEvalScope();
1150 if (proxy->position() != RelocInfo::kNoPosition &&
1151 proxy->position() < var->initializer_position() && !var->is_function() &&
1152 eval_for_use == eval_for_declaration) {
1153 DCHECK(proxy->end_position() != RelocInfo::kNoPosition);
1154 ReportMessage(proxy->position(), proxy->end_position(),
1155 "strong_use_before_declaration", proxy->raw_name());
1162 Variable* Scope::ClassVariableForMethod() const {
1163 if (!is_function_scope()) return nullptr;
1164 if (IsInObjectLiteral(function_kind_)) return nullptr;
1165 if (!IsConciseMethod(function_kind_) && !IsConstructor(function_kind_) &&
1166 !IsAccessorFunction(function_kind_)) {
1169 DCHECK_NOT_NULL(outer_scope_);
1170 DCHECK(outer_scope_->is_class_scope());
1171 // The class scope contains at most one variable, the class name.
1172 DCHECK(outer_scope_->variables_.occupancy() <= 1);
1173 if (outer_scope_->variables_.occupancy() == 0) return nullptr;
1174 VariableMap::Entry* p = outer_scope_->variables_.Start();
1175 return reinterpret_cast<Variable*>(p->value);
1179 bool Scope::ResolveVariablesRecursively(ParseInfo* info,
1180 AstNodeFactory* factory) {
1181 DCHECK(info->script_scope()->is_script_scope());
1183 // Resolve unresolved variables for this scope.
1184 for (int i = 0; i < unresolved_.length(); i++) {
1185 if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1188 // Resolve unresolved variables for inner scopes.
1189 for (int i = 0; i < inner_scopes_.length(); i++) {
1190 if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
1198 void Scope::PropagateScopeInfo(bool outer_scope_calls_sloppy_eval ) {
1199 if (outer_scope_calls_sloppy_eval) {
1200 outer_scope_calls_sloppy_eval_ = true;
1203 bool calls_sloppy_eval =
1204 this->calls_sloppy_eval() || outer_scope_calls_sloppy_eval_;
1205 for (int i = 0; i < inner_scopes_.length(); i++) {
1206 Scope* inner = inner_scopes_[i];
1207 inner->PropagateScopeInfo(calls_sloppy_eval);
1208 if (inner->scope_calls_eval_ || inner->inner_scope_calls_eval_) {
1209 inner_scope_calls_eval_ = true;
1211 // If the inner scope is an arrow function, propagate the flags tracking
1212 // usage of arguments/super/this, but do not propagate them out from normal
1214 if (!inner->is_function_scope() || inner->is_arrow_scope()) {
1215 if (inner->scope_uses_arguments_ || inner->inner_scope_uses_arguments_) {
1216 inner_scope_uses_arguments_ = true;
1218 if (inner->scope_uses_super_property_ ||
1219 inner->inner_scope_uses_super_property_) {
1220 inner_scope_uses_super_property_ = true;
1222 if (inner->scope_uses_this_ || inner->inner_scope_uses_this_) {
1223 inner_scope_uses_this_ = true;
1226 if (inner->force_eager_compilation_) {
1227 force_eager_compilation_ = true;
1229 if (asm_module_ && inner->scope_type() == FUNCTION_SCOPE) {
1230 inner->asm_function_ = true;
1236 bool Scope::MustAllocate(Variable* var) {
1237 // Give var a read/write use if there is a chance it might be accessed
1238 // via an eval() call. This is only possible if the variable has a
1240 if ((var->is_this() || var->is_new_target() || !var->raw_name()->IsEmpty()) &&
1241 (var->has_forced_context_allocation() || scope_calls_eval_ ||
1242 inner_scope_calls_eval_ || scope_contains_with_ || is_catch_scope() ||
1243 is_block_scope() || is_module_scope() || is_script_scope())) {
1245 if (scope_calls_eval_ || inner_scope_calls_eval_) var->set_maybe_assigned();
1247 // Global variables do not need to be allocated.
1248 return !var->IsGlobalObjectProperty() && var->is_used();
1252 bool Scope::MustAllocateInContext(Variable* var) {
1253 // If var is accessed from an inner scope, or if there is a possibility
1254 // that it might be accessed from the current or an inner scope (through
1255 // an eval() call or a runtime with lookup), it must be allocated in the
1258 // Exceptions: If the scope as a whole has forced context allocation, all
1259 // variables will have context allocation, even temporaries. Otherwise
1260 // temporary variables are always stack-allocated. Catch-bound variables are
1261 // always context-allocated.
1262 if (has_forced_context_allocation()) return true;
1263 if (var->mode() == TEMPORARY) return false;
1264 if (var->mode() == INTERNAL) return true;
1265 if (is_catch_scope() || is_block_scope() || is_module_scope()) return true;
1266 if (is_script_scope() && IsLexicalVariableMode(var->mode())) return true;
1267 return var->has_forced_context_allocation() ||
1268 scope_calls_eval_ ||
1269 inner_scope_calls_eval_ ||
1270 scope_contains_with_;
1274 bool Scope::HasArgumentsParameter(Isolate* isolate) {
1275 for (int i = 0; i < params_.length(); i++) {
1276 if (params_[i]->name().is_identical_to(
1277 isolate->factory()->arguments_string())) {
1285 void Scope::AllocateStackSlot(Variable* var) {
1286 var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1290 void Scope::AllocateHeapSlot(Variable* var) {
1291 var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1295 void Scope::AllocateParameterLocals(Isolate* isolate) {
1296 DCHECK(is_function_scope());
1297 Variable* arguments = LookupLocal(ast_value_factory_->arguments_string());
1298 DCHECK(arguments != NULL); // functions have 'arguments' declared implicitly
1300 bool uses_sloppy_arguments = false;
1302 if (MustAllocate(arguments) && !HasArgumentsParameter(isolate)) {
1303 // 'arguments' is used. Unless there is also a parameter called
1304 // 'arguments', we must be conservative and allocate all parameters to
1305 // the context assuming they will be captured by the arguments object.
1306 // If we have a parameter named 'arguments', a (new) value is always
1307 // assigned to it via the function invocation. Then 'arguments' denotes
1308 // that specific parameter value and cannot be used to access the
1309 // parameters, which is why we don't need to allocate an arguments
1310 // object in that case.
1312 // We are using 'arguments'. Tell the code generator that is needs to
1313 // allocate the arguments object by setting 'arguments_'.
1314 arguments_ = arguments;
1316 // In strict mode 'arguments' does not alias formal parameters.
1317 // Therefore in strict mode we allocate parameters as if 'arguments'
1319 uses_sloppy_arguments = is_sloppy(language_mode());
1322 if (rest_parameter_ && !MustAllocate(rest_parameter_)) {
1323 rest_parameter_ = NULL;
1326 // The same parameter may occur multiple times in the parameters_ list.
1327 // If it does, and if it is not copied into the context object, it must
1328 // receive the highest parameter index for that parameter; thus iteration
1329 // order is relevant!
1330 for (int i = params_.length() - 1; i >= 0; --i) {
1331 Variable* var = params_[i];
1332 if (var == rest_parameter_) continue;
1334 DCHECK(var->scope() == this);
1335 if (uses_sloppy_arguments || has_forced_context_allocation()) {
1336 // Force context allocation of the parameter.
1337 var->ForceContextAllocation();
1340 if (MustAllocate(var)) {
1341 if (MustAllocateInContext(var)) {
1342 DCHECK(var->IsUnallocated() || var->IsContextSlot());
1343 if (var->IsUnallocated()) {
1344 AllocateHeapSlot(var);
1347 DCHECK(var->IsUnallocated() || var->IsParameter());
1348 if (var->IsUnallocated()) {
1349 var->AllocateTo(Variable::PARAMETER, i);
1357 void Scope::AllocateNonParameterLocal(Isolate* isolate, Variable* var) {
1358 DCHECK(var->scope() == this);
1359 DCHECK(!var->IsVariable(isolate->factory()->dot_result_string()) ||
1360 !var->IsStackLocal());
1361 if (var->IsUnallocated() && MustAllocate(var)) {
1362 if (MustAllocateInContext(var)) {
1363 AllocateHeapSlot(var);
1365 AllocateStackSlot(var);
1371 void Scope::AllocateNonParameterLocals(Isolate* isolate) {
1372 // All variables that have no rewrite yet are non-parameter locals.
1373 for (int i = 0; i < temps_.length(); i++) {
1374 AllocateNonParameterLocal(isolate, temps_[i]);
1377 for (int i = 0; i < internals_.length(); i++) {
1378 AllocateNonParameterLocal(isolate, internals_[i]);
1381 ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
1382 for (VariableMap::Entry* p = variables_.Start();
1384 p = variables_.Next(p)) {
1385 Variable* var = reinterpret_cast<Variable*>(p->value);
1386 vars.Add(VarAndOrder(var, p->order), zone());
1388 vars.Sort(VarAndOrder::Compare);
1389 int var_count = vars.length();
1390 for (int i = 0; i < var_count; i++) {
1391 AllocateNonParameterLocal(isolate, vars[i].var());
1394 // For now, function_ must be allocated at the very end. If it gets
1395 // allocated in the context, it must be the last slot in the context,
1396 // because of the current ScopeInfo implementation (see
1397 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
1398 if (function_ != NULL) {
1399 AllocateNonParameterLocal(isolate, function_->proxy()->var());
1402 if (rest_parameter_) {
1403 AllocateNonParameterLocal(isolate, rest_parameter_);
1408 void Scope::AllocateVariablesRecursively(Isolate* isolate) {
1409 // Allocate variables for inner scopes.
1410 for (int i = 0; i < inner_scopes_.length(); i++) {
1411 inner_scopes_[i]->AllocateVariablesRecursively(isolate);
1414 // If scope is already resolved, we still need to allocate
1415 // variables in inner scopes which might not had been resolved yet.
1416 if (already_resolved()) return;
1417 // The number of slots required for variables.
1418 num_stack_slots_ = 0;
1419 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
1421 // Allocate variables for this scope.
1422 // Parameters must be allocated first, if any.
1423 if (is_function_scope()) AllocateParameterLocals(isolate);
1424 AllocateNonParameterLocals(isolate);
1426 // Force allocation of a context for this scope if necessary. For a 'with'
1427 // scope and for a function scope that makes an 'eval' call we need a context,
1428 // even if no local variables were statically allocated in the scope.
1429 // Likewise for modules.
1430 bool must_have_context = is_with_scope() || is_module_scope() ||
1431 (is_function_scope() && calls_eval());
1433 // If we didn't allocate any locals in the local context, then we only
1434 // need the minimal number of slots if we must have a context.
1435 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1436 num_heap_slots_ = 0;
1440 DCHECK(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1444 void Scope::AllocateModules() {
1445 DCHECK(is_script_scope());
1446 DCHECK(!already_resolved());
1447 for (int i = 0; i < inner_scopes_.length(); i++) {
1448 Scope* scope = inner_scopes_.at(i);
1449 if (scope->is_module_scope()) {
1450 DCHECK(!scope->already_resolved());
1451 DCHECK(scope->module_descriptor_->IsFrozen());
1452 DCHECK_NULL(scope->module_var_);
1453 scope->module_var_ = NewInternal(ast_value_factory_->dot_module_string());
1460 int Scope::StackLocalCount() const {
1461 return num_stack_slots() -
1462 (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
1466 int Scope::ContextLocalCount() const {
1467 if (num_heap_slots() == 0) return 0;
1468 return num_heap_slots() - Context::MIN_CONTEXT_SLOTS -
1469 (function_ != NULL && function_->proxy()->var()->IsContextSlot() ? 1 : 0);
1471 } } // namespace v8::internal