Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / v8 / src / scopes.cc
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.
4
5 #include "src/v8.h"
6
7 #include "src/scopes.h"
8
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"
14
15 namespace v8 {
16 namespace internal {
17
18 // ----------------------------------------------------------------------------
19 // Implementation of LocalsMap
20 //
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
25 //       this is ensured.
26
27 VariableMap::VariableMap(Zone* zone)
28     : ZoneHashMap(ZoneHashMap::PointersMatch, 8, ZoneAllocationPolicy(zone)),
29       zone_(zone) {}
30 VariableMap::~VariableMap() {}
31
32
33 Variable* VariableMap::Declare(Scope* scope, const AstRawString* name,
34                                VariableMode mode, bool is_valid_lhs,
35                                Variable::Kind kind,
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);
50   }
51   return reinterpret_cast<Variable*>(p->value);
52 }
53
54
55 Variable* VariableMap::Lookup(const AstRawString* name) {
56   Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash(),
57                                  false, ZoneAllocationPolicy(NULL));
58   if (p != NULL) {
59     DCHECK(reinterpret_cast<const AstRawString*>(p->key) == name);
60     DCHECK(p->value != NULL);
61     return reinterpret_cast<Variable*>(p->value);
62   }
63   return NULL;
64 }
65
66
67 // ----------------------------------------------------------------------------
68 // Implementation of Scope
69
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),
74       variables_(zone),
75       internals_(4, zone),
76       temps_(4, zone),
77       params_(4, zone),
78       unresolved_(16, zone),
79       decls_(4, 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),
85       zone_(zone) {
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());
90 }
91
92
93 Scope::Scope(Scope* inner_scope,
94              ScopeType scope_type,
95              Handle<ScopeInfo> scope_info,
96              AstValueFactory* value_factory,
97              Zone* zone)
98     : isolate_(zone->isolate()),
99       inner_scopes_(4, zone),
100       variables_(zone),
101       internals_(4, zone),
102       temps_(4, zone),
103       params_(4, zone),
104       unresolved_(16, zone),
105       decls_(4, zone),
106       interface_(NULL),
107       already_resolved_(true),
108       ast_value_factory_(value_factory),
109       zone_(zone) {
110   SetDefaults(scope_type, NULL, scope_info);
111   if (!scope_info.is_null()) {
112     num_heap_slots_ = scope_info_->ContextLength();
113   }
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);
118 }
119
120
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),
125       variables_(zone),
126       internals_(0, zone),
127       temps_(0, zone),
128       params_(0, zone),
129       unresolved_(0, zone),
130       decls_(0, zone),
131       interface_(NULL),
132       already_resolved_(true),
133       ast_value_factory_(value_factory),
134       zone_(zone) {
135   SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
136   AddInnerScope(inner_scope);
137   ++num_var_or_const_;
138   num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
139   Variable* variable = variables_.Declare(this,
140                                           catch_variable_name,
141                                           VAR,
142                                           true,  // Valid left-hand side.
143                                           Variable::NORMAL,
144                                           kCreatedInitialized);
145   AllocateHeapSlot(variable);
146 }
147
148
149 void Scope::SetDefaults(ScopeType scope_type,
150                         Scope* outer_scope,
151                         Handle<ScopeInfo> scope_info) {
152   outer_scope_ = outer_scope;
153   scope_type_ = scope_type;
154   scope_name_ = ast_value_factory_->empty_string();
155   dynamics_ = NULL;
156   receiver_ = NULL;
157   function_ = NULL;
158   arguments_ = NULL;
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;
172   num_heap_slots_ = 0;
173   num_modules_ = 0;
174   module_var_ = NULL,
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();
181   }
182 }
183
184
185 Scope* Scope::DeserializeScopeChain(Context* context, Scope* global_scope,
186                                     Zone* zone) {
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,
194                                           WITH_SCOPE,
195                                           Handle<ScopeInfo>::null(),
196                                           global_scope->ast_value_factory_,
197                                           zone);
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;
203       }
204     } else if (context->IsGlobalContext()) {
205       ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
206       current_scope = new(zone) Scope(current_scope,
207                                       GLOBAL_SCOPE,
208                                       Handle<ScopeInfo>(scope_info),
209                                       global_scope->ast_value_factory_,
210                                       zone);
211     } else if (context->IsModuleContext()) {
212       ScopeInfo* scope_info = ScopeInfo::cast(context->module()->scope_info());
213       current_scope = new(zone) Scope(current_scope,
214                                       MODULE_SCOPE,
215                                       Handle<ScopeInfo>(scope_info),
216                                       global_scope->ast_value_factory_,
217                                       zone);
218     } else if (context->IsFunctionContext()) {
219       ScopeInfo* scope_info = context->closure()->shared()->scope_info();
220       current_scope = new(zone) Scope(current_scope,
221                                       FUNCTION_SCOPE,
222                                       Handle<ScopeInfo>(scope_info),
223                                       global_scope->ast_value_factory_,
224                                       zone);
225     } else if (context->IsBlockContext()) {
226       ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
227       current_scope = new(zone) Scope(current_scope,
228                                       BLOCK_SCOPE,
229                                       Handle<ScopeInfo>(scope_info),
230                                       global_scope->ast_value_factory_,
231                                       zone);
232     } else {
233       DCHECK(context->IsCatchContext());
234       String* name = String::cast(context->extension());
235       current_scope = new (zone) Scope(
236           current_scope,
237           global_scope->ast_value_factory_->GetString(Handle<String>(name)),
238           global_scope->ast_value_factory_, zone);
239     }
240     if (contains_with) current_scope->RecordWithStatement();
241     if (innermost_scope == NULL) innermost_scope = current_scope;
242
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;
246     }
247     context = context->previous();
248   }
249
250   global_scope->AddInnerScope(current_scope);
251   global_scope->PropagateScopeInfo(false);
252   return (innermost_scope == NULL) ? global_scope : innermost_scope;
253 }
254
255
256 bool Scope::Analyze(CompilationInfo* info) {
257   DCHECK(info->function() != NULL);
258   Scope* scope = info->function()->scope();
259   Scope* top = scope;
260
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();
266   }
267
268   // Allocate the variables.
269   {
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;
274   }
275
276 #ifdef DEBUG
277   if (info->isolate()->bootstrapper()->IsActive()
278           ? FLAG_print_builtin_scopes
279           : FLAG_print_scopes) {
280     scope->Print();
281   }
282
283   if (FLAG_harmony_modules && FLAG_print_interfaces && top->is_global_scope()) {
284     PrintF("global : ");
285     top->interface()->Print();
286   }
287 #endif
288
289   info->PrepareForCompilation(scope);
290   return true;
291 }
292
293
294 void Scope::Initialize() {
295   DCHECK(!already_resolved());
296
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();
301   } else {
302     scope_inside_with_ = is_with_scope();
303   }
304
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
312   // invoking scripts
313   if (is_declaration_scope()) {
314     Variable* var =
315         variables_.Declare(this,
316                            ast_value_factory_->this_string(),
317                            VAR,
318                            false,
319                            Variable::THIS,
320                            kCreatedInitialized);
321     var->AllocateTo(Variable::PARAMETER, -1);
322     receiver_ = var;
323   } else {
324     DCHECK(outer_scope() != NULL);
325     receiver_ = outer_scope()->receiver();
326   }
327
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(),
334                        VAR,
335                        true,
336                        Variable::ARGUMENTS,
337                        kCreatedInitialized);
338   }
339 }
340
341
342 Scope* Scope::FinalizeBlockScope() {
343   DCHECK(is_block_scope());
344   DCHECK(internals_.is_empty());
345   DCHECK(temps_.is_empty());
346   DCHECK(params_.is_empty());
347
348   if (num_var_or_const() > 0) return this;
349
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);
354       break;
355     }
356   }
357
358   // Reparent inner scopes.
359   for (int i = 0; i < inner_scopes_.length(); i++) {
360     outer_scope()->AddInnerScope(inner_scopes_[i]);
361   }
362
363   // Move unresolved variables
364   for (int i = 0; i < unresolved_.length(); i++) {
365     outer_scope()->unresolved_.Add(unresolved_[i], zone());
366   }
367
368   return NULL;
369 }
370
371
372 Variable* Scope::LookupLocal(const AstRawString* name) {
373   Variable* result = variables_.Lookup(name);
374   if (result != NULL || scope_info_.is_null()) {
375     return result;
376   }
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);
384
385   // Check context slot lookup.
386   VariableMode mode;
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);
392   if (index < 0) {
393     // Check parameters.
394     index = scope_info_->ParameterIndex(*name_handle);
395     if (index < 0) return NULL;
396
397     mode = DYNAMIC;
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
402     // parameters.
403     maybe_assigned_flag = kMaybeAssigned;
404   }
405
406   Variable* var = variables_.Declare(this, name, mode, true, Variable::NORMAL,
407                                      init_flag, maybe_assigned_flag);
408   var->AllocateTo(location, index);
409   return var;
410 }
411
412
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.
419     VariableMode mode;
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);
430     return var;
431   } else {
432     return NULL;
433   }
434 }
435
436
437 Variable* Scope::Lookup(const AstRawString* name) {
438   for (Scope* scope = this;
439        scope != NULL;
440        scope = scope->outer_scope()) {
441     Variable* var = scope->LookupLocal(name);
442     if (var != NULL) return var;
443   }
444   return NULL;
445 }
446
447
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());
454   return var;
455 }
456
457
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));
467   ++num_var_or_const_;
468   return variables_.Declare(this, name, mode, true, Variable::NORMAL, init_flag,
469                             maybe_assigned_flag, interface);
470 }
471
472
473 Variable* Scope::DeclareDynamicGlobal(const AstRawString* name) {
474   DCHECK(is_global_scope());
475   return variables_.Declare(this,
476                             name,
477                             DYNAMIC_GLOBAL,
478                             true,
479                             Variable::NORMAL,
480                             kCreatedInitialized);
481 }
482
483
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);
490       return;
491     }
492   }
493 }
494
495
496 Variable* Scope::NewInternal(const AstRawString* name) {
497   DCHECK(!already_resolved());
498   Variable* var = new(zone()) Variable(this,
499                                        name,
500                                        INTERNAL,
501                                        false,
502                                        Variable::NORMAL,
503                                        kCreatedInitialized);
504   internals_.Add(var, zone());
505   return var;
506 }
507
508
509 Variable* Scope::NewTemporary(const AstRawString* name) {
510   DCHECK(!already_resolved());
511   Variable* var = new(zone()) Variable(this,
512                                        name,
513                                        TEMPORARY,
514                                        true,
515                                        Variable::NORMAL,
516                                        kCreatedInitialized);
517   temps_.Add(var, zone());
518   return var;
519 }
520
521
522 void Scope::AddDeclaration(Declaration* declaration) {
523   decls_.Add(declaration, zone());
524 }
525
526
527 void Scope::SetIllegalRedeclaration(Expression* expression) {
528   // Record only the first illegal redeclaration.
529   if (!HasIllegalRedeclaration()) {
530     illegal_redecl_ = expression;
531   }
532   DCHECK(HasIllegalRedeclaration());
533 }
534
535
536 void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
537   DCHECK(HasIllegalRedeclaration());
538   illegal_redecl_->Accept(visitor);
539 }
540
541
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();
548
549     // Iterate through all scopes until and including the declaration scope.
550     Scope* previous = NULL;
551     Scope* current = decl->scope();
552     do {
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) {
556         return decl;
557       }
558       previous = current;
559       current = current->outer_scope_;
560     } while (!previous->is_declaration_scope());
561   }
562   return NULL;
563 }
564
565
566 class VarAndOrder {
567  public:
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_;
573   }
574
575  private:
576   Variable* var_;
577   int order_;
578 };
579
580
581 void Scope::CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
582                                          ZoneList<Variable*>* context_locals) {
583   DCHECK(stack_locals != NULL);
584   DCHECK(context_locals != NULL);
585
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());
592     }
593   }
594
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());
603       } else {
604         DCHECK(var->IsStackLocal());
605         stack_locals->Add(var, zone());
606       }
607     }
608   }
609
610   // Collect declared local variables.
611   ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
612   for (VariableMap::Entry* p = variables_.Start();
613        p != NULL;
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());
618     }
619   }
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());
628     }
629   }
630 }
631
632
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();
641   }
642   PropagateScopeInfo(outer_scope_calls_sloppy_eval);
643
644   // 2) Allocate module instances.
645   if (FLAG_harmony_modules && (is_global_scope() || is_module_scope())) {
646     DCHECK(num_modules_ == 0);
647     AllocateModulesRecursively(this);
648   }
649
650   // 3) Resolve variables.
651   if (!ResolveVariablesRecursively(info, factory)) return false;
652
653   // 4) Allocate variables.
654   AllocateVariablesRecursively();
655
656   return true;
657 }
658
659
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
664   // return true.
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;
669   }
670   return true;
671 }
672
673
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();
681 }
682
683
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;
696     }
697   }
698   return true;
699 }
700
701
702 bool Scope::AllowsLazyCompilation() const {
703   return !force_eager_compilation_ && HasLazyCompilableOuterContext();
704 }
705
706
707 bool Scope::AllowsLazyCompilationWithoutContext() const {
708   return !force_eager_compilation_ && HasTrivialOuterContext();
709 }
710
711
712 int Scope::ContextChainLength(Scope* scope) {
713   int n = 0;
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);
720   }
721   return n;
722 }
723
724
725 Scope* Scope::GlobalScope() {
726   Scope* scope = this;
727   while (!scope->is_global_scope()) {
728     scope = scope->outer_scope();
729   }
730   return scope;
731 }
732
733
734 Scope* Scope::DeclarationScope() {
735   Scope* scope = this;
736   while (!scope->is_declaration_scope()) {
737     scope = scope->outer_scope();
738   }
739   return scope;
740 }
741
742
743 Handle<ScopeInfo> Scope::GetScopeInfo() {
744   if (scope_info_.is_null()) {
745     scope_info_ = ScopeInfo::Create(this, zone());
746   }
747   return scope_info_;
748 }
749
750
751 void Scope::GetNestedScopeChain(
752     List<Handle<ScopeInfo> >* chain,
753     int position) {
754   if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo()));
755
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);
763       return;
764     }
765   }
766 }
767
768
769 #ifdef DEBUG
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";
779   }
780   UNREACHABLE();
781   return NULL;
782 }
783
784
785 static void Indent(int n, const char* str) {
786   PrintF("%*s%s", n, "", str);
787 }
788
789
790 static void PrintName(const AstRawString* name) {
791   PrintF("%.*s", name->length(), name->raw_data());
792 }
793
794
795 static void PrintLocation(Variable* var) {
796   switch (var->location()) {
797     case Variable::UNALLOCATED:
798       break;
799     case Variable::PARAMETER:
800       PrintF("parameter[%d]", var->index());
801       break;
802     case Variable::LOCAL:
803       PrintF("local[%d]", var->index());
804       break;
805     case Variable::CONTEXT:
806       PrintF("context[%d]", var->index());
807       break;
808     case Variable::LOOKUP:
809       PrintF("lookup");
810       break;
811   }
812 }
813
814
815 static void PrintVar(int indent, Variable* var) {
816   if (var->is_used() || !var->IsUnallocated()) {
817     Indent(indent, Variable::Mode2String(var->mode()));
818     PrintF(" ");
819     PrintName(var->raw_name());
820     PrintF(";  // ");
821     PrintLocation(var);
822     bool comma = !var->IsUnallocated();
823     if (var->has_forced_context_allocation()) {
824       if (comma) PrintF(", ");
825       PrintF("forced context allocation");
826       comma = true;
827     }
828     if (var->maybe_assigned() == kMaybeAssigned) {
829       if (comma) PrintF(", ");
830       PrintF("maybe assigned");
831     }
832     PrintF("\n");
833   }
834 }
835
836
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);
841   }
842 }
843
844
845 void Scope::Print(int n) {
846   int n0 = (n > 0 ? n : 0);
847   int n1 = n0 + 2;  // indentation
848
849   // Print header.
850   Indent(n0, Header(scope_type_));
851   if (!scope_name_->IsEmpty()) {
852     PrintF(" ");
853     PrintName(scope_name_);
854   }
855
856   // Print parameters, if any.
857   if (is_function_scope()) {
858     PrintF(" (");
859     for (int i = 0; i < params_.length(); i++) {
860       if (i > 0) PrintF(", ");
861       PrintName(params_[i]->raw_name());
862     }
863     PrintF(")");
864   }
865
866   PrintF(" { // (%d, %d)\n", start_position(), end_position());
867
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());
872     PrintF("\n");
873   }
874
875   // Scope info.
876   if (HasTrivialOuterContext()) {
877     Indent(n1, "// scope has trivial outer context\n");
878   }
879   if (strict_mode() == STRICT) {
880     Indent(n1, "// strict mode scope\n");
881   }
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");
887   }
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_); }
893
894   // Print locals.
895   if (function_ != NULL) {
896     Indent(n1, "// function var:\n");
897     PrintVar(n1, function_->proxy()->var());
898   }
899
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]);
904     }
905   }
906
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]);
911     }
912   }
913
914   if (variables_.Start() != NULL) {
915     Indent(n1, "// local vars:\n");
916     PrintMap(n1, &variables_);
917   }
918
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));
924   }
925
926   // Print inner scopes (disable by providing negative n).
927   if (n >= 0) {
928     for (int i = 0; i < inner_scopes_.length(); i++) {
929       PrintF("\n");
930       inner_scopes_[i]->Print(n1);
931     }
932   }
933
934   Indent(n0, "}\n");
935 }
936 #endif  // DEBUG
937
938
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);
943   if (var == NULL) {
944     // Declare a new non-local.
945     InitializationFlag init_flag = (mode == VAR)
946         ? kCreatedInitialized : kNeedsInitialization;
947     var = map->Declare(NULL,
948                        name,
949                        mode,
950                        true,
951                        Variable::NORMAL,
952                        init_flag);
953     // Allocate it by giving it a dynamic lookup.
954     var->AllocateTo(Variable::LOOKUP, -1);
955   }
956   return var;
957 }
958
959
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;
968     return NULL;
969   }
970
971   // Try to find the variable in this scope.
972   Variable* var = LookupLocal(proxy->raw_name());
973
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.)
977   if (var != NULL) {
978     *binding_kind = BOUND;
979     return var;
980   }
981
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);
987   if (var != NULL) {
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();
993     }
994   } else {
995     DCHECK(is_global_scope());
996   }
997
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'
1005     // object).
1006     if (var != NULL && proxy->is_assigned()) var->set_maybe_assigned();
1007     *binding_kind = DYNAMIC_LOOKUP;
1008     return NULL;
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;
1018     }
1019   }
1020   return var;
1021 }
1022
1023
1024 bool Scope::ResolveVariable(CompilationInfo* info,
1025                             VariableProxy* proxy,
1026                             AstNodeFactory<AstNullVisitor>* factory) {
1027   DCHECK(info->global_scope()->is_global_scope());
1028
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;
1032
1033   // Otherwise, try to resolve the variable.
1034   BindingKind binding_kind;
1035   Variable* var = LookupRecursive(proxy, &binding_kind, factory);
1036   switch (binding_kind) {
1037     case BOUND:
1038       // We found a variable binding.
1039       break;
1040
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);
1050       } else {
1051         Variable* invalidated = var;
1052         var = NonLocal(proxy->raw_name(), DYNAMIC_LOCAL);
1053         var->set_local_if_not_shadowed(invalidated);
1054       }
1055       break;
1056
1057     case UNBOUND:
1058       // No binding has been found. Declare a variable on the global object.
1059       var = info->global_scope()->DeclareDynamicGlobal(proxy->raw_name());
1060       break;
1061
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);
1065       break;
1066
1067     case DYNAMIC_LOOKUP:
1068       // The variable could not be resolved statically.
1069       var = NonLocal(proxy->raw_name(), DYNAMIC);
1070       break;
1071   }
1072
1073   DCHECK(var != NULL);
1074   if (proxy->is_assigned()) var->set_maybe_assigned();
1075
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);
1087     return false;
1088   }
1089
1090   if (FLAG_harmony_modules) {
1091     bool ok;
1092 #ifdef DEBUG
1093     if (FLAG_print_interface_details) {
1094       PrintF("# Resolve %.*s:\n", var->raw_name()->length(),
1095              var->raw_name()->raw_data());
1096     }
1097 #endif
1098     proxy->interface()->Unify(var->interface(), zone(), &ok);
1099     if (!ok) {
1100 #ifdef DEBUG
1101       if (FLAG_print_interfaces) {
1102         PrintF("SCOPES TYPE ERROR\n");
1103         PrintF("proxy: ");
1104         proxy->interface()->Print();
1105         PrintF("var: ");
1106         var->interface()->Print();
1107       }
1108 #endif
1109
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);
1121       return false;
1122     }
1123   }
1124
1125   proxy->BindTo(var);
1126
1127   return true;
1128 }
1129
1130
1131 bool Scope::ResolveVariablesRecursively(
1132     CompilationInfo* info,
1133     AstNodeFactory<AstNullVisitor>* factory) {
1134   DCHECK(info->global_scope()->is_global_scope());
1135
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;
1139   }
1140
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))
1144       return false;
1145   }
1146
1147   return true;
1148 }
1149
1150
1151 void Scope::PropagateScopeInfo(bool outer_scope_calls_sloppy_eval ) {
1152   if (outer_scope_calls_sloppy_eval) {
1153     outer_scope_calls_sloppy_eval_ = true;
1154   }
1155
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;
1163     }
1164     if (inner->force_eager_compilation_) {
1165       force_eager_compilation_ = true;
1166     }
1167   }
1168 }
1169
1170
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
1174   // visible name.
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_ ||
1180        is_catch_scope() ||
1181        is_block_scope() ||
1182        is_module_scope() ||
1183        is_global_scope())) {
1184     var->set_is_used();
1185     if (scope_calls_eval_ || inner_scope_calls_eval_) var->set_maybe_assigned();
1186   }
1187   // Global variables do not need to be allocated.
1188   return !var->IsGlobalObjectProperty() && var->is_used();
1189 }
1190
1191
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
1196   // context.
1197   //
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_;
1211 }
1212
1213
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())) {
1218       return true;
1219     }
1220   }
1221   return false;
1222 }
1223
1224
1225 void Scope::AllocateStackSlot(Variable* var) {
1226   var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1227 }
1228
1229
1230 void Scope::AllocateHeapSlot(Variable* var) {
1231   var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1232 }
1233
1234
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
1239
1240   bool uses_sloppy_arguments = false;
1241
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.
1251
1252     // We are using 'arguments'. Tell the code generator that is needs to
1253     // allocate the arguments object by setting 'arguments_'.
1254     arguments_ = arguments;
1255
1256     // In strict mode 'arguments' does not alias formal parameters.
1257     // Therefore in strict mode we allocate parameters as if 'arguments'
1258     // were not used.
1259     uses_sloppy_arguments = strict_mode() == SLOPPY;
1260   }
1261
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();
1272     }
1273
1274     if (MustAllocate(var)) {
1275       if (MustAllocateInContext(var)) {
1276         DCHECK(var->IsUnallocated() || var->IsContextSlot());
1277         if (var->IsUnallocated()) {
1278           AllocateHeapSlot(var);
1279         }
1280       } else {
1281         DCHECK(var->IsUnallocated() || var->IsParameter());
1282         if (var->IsUnallocated()) {
1283           var->AllocateTo(Variable::PARAMETER, i);
1284         }
1285       }
1286     }
1287   }
1288 }
1289
1290
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);
1298     } else {
1299       AllocateStackSlot(var);
1300     }
1301   }
1302 }
1303
1304
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]);
1309   }
1310
1311   for (int i = 0; i < internals_.length(); i++) {
1312     AllocateNonParameterLocal(internals_[i]);
1313   }
1314
1315   ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
1316   for (VariableMap::Entry* p = variables_.Start();
1317        p != NULL;
1318        p = variables_.Next(p)) {
1319     Variable* var = reinterpret_cast<Variable*>(p->value);
1320     vars.Add(VarAndOrder(var, p->order), zone());
1321   }
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());
1326   }
1327
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());
1334   }
1335 }
1336
1337
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();
1342   }
1343
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;
1350
1351   // Allocate variables for this scope.
1352   // Parameters must be allocated first, if any.
1353   if (is_function_scope()) AllocateParameterLocals();
1354   AllocateNonParameterLocals();
1355
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());
1362
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;
1367   }
1368
1369   // Allocation done.
1370   DCHECK(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1371 }
1372
1373
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);
1379     module_var_ =
1380         host_scope->NewInternal(ast_value_factory_->dot_module_string());
1381     ++host_scope->num_modules_;
1382   }
1383
1384   for (int i = 0; i < inner_scopes_.length(); i++) {
1385     Scope* inner_scope = inner_scopes_.at(i);
1386     inner_scope->AllocateModulesRecursively(host_scope);
1387   }
1388 }
1389
1390
1391 int Scope::StackLocalCount() const {
1392   return num_stack_slots() -
1393       (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
1394 }
1395
1396
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);
1401 }
1402
1403 } }  // namespace v8::internal