[V8] Introduce a QML compilation mode
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / scopes.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #include "v8.h"
29
30 #include "scopes.h"
31
32 #include "bootstrapper.h"
33 #include "compiler.h"
34 #include "messages.h"
35 #include "scopeinfo.h"
36
37 #include "allocation-inl.h"
38
39 #include "debug.h"
40
41 namespace v8 {
42 namespace internal {
43
44 // ----------------------------------------------------------------------------
45 // Implementation of LocalsMap
46 //
47 // Note: We are storing the handle locations as key values in the hash map.
48 //       When inserting a new variable via Declare(), we rely on the fact that
49 //       the handle location remains alive for the duration of that variable
50 //       use. Because a Variable holding a handle with the same location exists
51 //       this is ensured.
52
53 static bool Match(void* key1, void* key2) {
54   String* name1 = *reinterpret_cast<String**>(key1);
55   String* name2 = *reinterpret_cast<String**>(key2);
56   ASSERT(name1->IsSymbol());
57   ASSERT(name2->IsSymbol());
58   return name1 == name2;
59 }
60
61
62 VariableMap::VariableMap() : ZoneHashMap(Match, 8) {}
63 VariableMap::~VariableMap() {}
64
65
66 Variable* VariableMap::Declare(
67     Scope* scope,
68     Handle<String> name,
69     VariableMode mode,
70     bool is_valid_lhs,
71     Variable::Kind kind,
72     InitializationFlag initialization_flag,
73     Interface* interface) {
74   Entry* p = ZoneHashMap::Lookup(name.location(), name->Hash(), true);
75   if (p->value == NULL) {
76     // The variable has not been declared yet -> insert it.
77     ASSERT(p->key == name.location());
78     p->value = new Variable(scope,
79                             name,
80                             mode,
81                             is_valid_lhs,
82                             kind,
83                             initialization_flag,
84                             interface);
85   }
86   return reinterpret_cast<Variable*>(p->value);
87 }
88
89
90 Variable* VariableMap::Lookup(Handle<String> name) {
91   Entry* p = ZoneHashMap::Lookup(name.location(), name->Hash(), false);
92   if (p != NULL) {
93     ASSERT(*reinterpret_cast<String**>(p->key) == *name);
94     ASSERT(p->value != NULL);
95     return reinterpret_cast<Variable*>(p->value);
96   }
97   return NULL;
98 }
99
100
101 // ----------------------------------------------------------------------------
102 // Implementation of Scope
103
104 Scope::Scope(Scope* outer_scope, ScopeType type)
105     : isolate_(Isolate::Current()),
106       inner_scopes_(4),
107       variables_(),
108       temps_(4),
109       params_(4),
110       unresolved_(16),
111       decls_(4),
112       interface_(FLAG_harmony_modules &&
113                  (type == MODULE_SCOPE || type == GLOBAL_SCOPE)
114                      ? Interface::NewModule() : NULL),
115       already_resolved_(false) {
116   SetDefaults(type, outer_scope, Handle<ScopeInfo>::null());
117   // At some point we might want to provide outer scopes to
118   // eval scopes (by walking the stack and reading the scope info).
119   // In that case, the ASSERT below needs to be adjusted.
120   ASSERT_EQ(type == GLOBAL_SCOPE, outer_scope == NULL);
121   ASSERT(!HasIllegalRedeclaration());
122 }
123
124
125 Scope::Scope(Scope* inner_scope,
126              ScopeType type,
127              Handle<ScopeInfo> scope_info)
128     : isolate_(Isolate::Current()),
129       inner_scopes_(4),
130       variables_(),
131       temps_(4),
132       params_(4),
133       unresolved_(16),
134       decls_(4),
135       interface_(NULL),
136       already_resolved_(true) {
137   SetDefaults(type, NULL, scope_info);
138   if (!scope_info.is_null()) {
139     num_heap_slots_ = scope_info_->ContextLength();
140   }
141   // Ensure at least MIN_CONTEXT_SLOTS to indicate a materialized context.
142   num_heap_slots_ = Max(num_heap_slots_,
143                         static_cast<int>(Context::MIN_CONTEXT_SLOTS));
144   AddInnerScope(inner_scope);
145 }
146
147
148 Scope::Scope(Scope* inner_scope, Handle<String> catch_variable_name)
149     : isolate_(Isolate::Current()),
150       inner_scopes_(1),
151       variables_(),
152       temps_(0),
153       params_(0),
154       unresolved_(0),
155       decls_(0),
156       interface_(NULL),
157       already_resolved_(true) {
158   SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
159   AddInnerScope(inner_scope);
160   ++num_var_or_const_;
161   num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
162   Variable* variable = variables_.Declare(this,
163                                           catch_variable_name,
164                                           VAR,
165                                           true,  // Valid left-hand side.
166                                           Variable::NORMAL,
167                                           kCreatedInitialized);
168   AllocateHeapSlot(variable);
169 }
170
171
172 void Scope::SetDefaults(ScopeType type,
173                         Scope* outer_scope,
174                         Handle<ScopeInfo> scope_info) {
175   outer_scope_ = outer_scope;
176   type_ = type;
177   scope_name_ = isolate_->factory()->empty_symbol();
178   dynamics_ = NULL;
179   receiver_ = NULL;
180   function_ = NULL;
181   arguments_ = NULL;
182   illegal_redecl_ = NULL;
183   scope_inside_with_ = false;
184   scope_contains_with_ = false;
185   scope_calls_eval_ = false;
186   // Inherit the strict mode from the parent scope.
187   language_mode_ = (outer_scope != NULL)
188       ? outer_scope->language_mode_ : CLASSIC_MODE;
189   qml_mode_flag_ = (outer_scope != NULL)
190       ? outer_scope->qml_mode_flag_ : kNonQmlMode;
191   outer_scope_calls_non_strict_eval_ = false;
192   inner_scope_calls_eval_ = false;
193   force_eager_compilation_ = false;
194   num_var_or_const_ = 0;
195   num_stack_slots_ = 0;
196   num_heap_slots_ = 0;
197   scope_info_ = scope_info;
198   start_position_ = RelocInfo::kNoPosition;
199   end_position_ = RelocInfo::kNoPosition;
200   if (!scope_info.is_null()) {
201     scope_calls_eval_ = scope_info->CallsEval();
202     language_mode_ = scope_info->language_mode();
203   }
204 }
205
206
207 Scope* Scope::DeserializeScopeChain(Context* context, Scope* global_scope) {
208   // Reconstruct the outer scope chain from a closure's context chain.
209   Scope* current_scope = NULL;
210   Scope* innermost_scope = NULL;
211   bool contains_with = false;
212   while (!context->IsGlobalContext()) {
213     if (context->IsWithContext()) {
214       Scope* with_scope = new Scope(current_scope,
215                                     WITH_SCOPE,
216                                     Handle<ScopeInfo>::null());
217       current_scope = with_scope;
218       // All the inner scopes are inside a with.
219       contains_with = true;
220       for (Scope* s = innermost_scope; s != NULL; s = s->outer_scope()) {
221         s->scope_inside_with_ = true;
222       }
223     } else if (context->IsFunctionContext()) {
224       ScopeInfo* scope_info = context->closure()->shared()->scope_info();
225       current_scope = new Scope(current_scope,
226                                 FUNCTION_SCOPE,
227                                 Handle<ScopeInfo>(scope_info));
228     } else if (context->IsBlockContext()) {
229       ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
230       current_scope = new Scope(current_scope,
231                                 BLOCK_SCOPE,
232                                 Handle<ScopeInfo>(scope_info));
233     } else {
234       ASSERT(context->IsCatchContext());
235       String* name = String::cast(context->extension());
236       current_scope = new Scope(current_scope, Handle<String>(name));
237     }
238     if (contains_with) current_scope->RecordWithStatement();
239     if (innermost_scope == NULL) innermost_scope = current_scope;
240
241     // Forget about a with when we move to a context for a different function.
242     if (context->previous()->closure() != context->closure()) {
243       contains_with = false;
244     }
245     context = context->previous();
246   }
247
248   global_scope->AddInnerScope(current_scope);
249   global_scope->PropagateScopeInfo(false);
250   return (innermost_scope == NULL) ? global_scope : innermost_scope;
251 }
252
253
254 bool Scope::Analyze(CompilationInfo* info) {
255   ASSERT(info->function() != NULL);
256   Scope* scope = info->function()->scope();
257   Scope* top = scope;
258
259   // Traverse the scope tree up to the first unresolved scope or the global
260   // scope and start scope resolution and variable allocation from that scope.
261   while (!top->is_global_scope() &&
262          !top->outer_scope()->already_resolved()) {
263     top = top->outer_scope();
264   }
265
266   // Allocate the variables.
267   {
268     AstNodeFactory<AstNullVisitor> ast_node_factory(info->isolate());
269     if (!top->AllocateVariables(info, &ast_node_factory)) return false;
270   }
271
272 #ifdef DEBUG
273   if (info->isolate()->bootstrapper()->IsActive()
274           ? FLAG_print_builtin_scopes
275           : FLAG_print_scopes) {
276     scope->Print();
277   }
278
279   if (FLAG_harmony_modules && FLAG_print_interfaces && top->is_global_scope()) {
280     PrintF("global : ");
281     top->interface()->Print();
282   }
283 #endif
284
285   if (FLAG_harmony_scoping) {
286     VariableProxy* proxy = scope->CheckAssignmentToConst();
287     if (proxy != NULL) {
288       // Found an assignment to const. Throw a syntax error.
289       MessageLocation location(info->script(),
290                                proxy->position(),
291                                proxy->position());
292       Isolate* isolate = info->isolate();
293       Factory* factory = isolate->factory();
294       Handle<JSArray> array = factory->NewJSArray(0);
295       Handle<Object> result =
296           factory->NewSyntaxError("harmony_const_assign", array);
297       isolate->Throw(*result, &location);
298       return false;
299     }
300   }
301
302   info->SetScope(scope);
303   return true;
304 }
305
306
307 void Scope::Initialize() {
308   ASSERT(!already_resolved());
309
310   // Add this scope as a new inner scope of the outer scope.
311   if (outer_scope_ != NULL) {
312     outer_scope_->inner_scopes_.Add(this);
313     scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
314   } else {
315     scope_inside_with_ = is_with_scope();
316   }
317
318   // Declare convenience variables.
319   // Declare and allocate receiver (even for the global scope, and even
320   // if naccesses_ == 0).
321   // NOTE: When loading parameters in the global scope, we must take
322   // care not to access them as properties of the global object, but
323   // instead load them directly from the stack. Currently, the only
324   // such parameter is 'this' which is passed on the stack when
325   // invoking scripts
326   if (is_declaration_scope()) {
327     Variable* var =
328         variables_.Declare(this,
329                            isolate_->factory()->this_symbol(),
330                            VAR,
331                            false,
332                            Variable::THIS,
333                            kCreatedInitialized);
334     var->AllocateTo(Variable::PARAMETER, -1);
335     receiver_ = var;
336   } else {
337     ASSERT(outer_scope() != NULL);
338     receiver_ = outer_scope()->receiver();
339   }
340
341   if (is_function_scope()) {
342     // Declare 'arguments' variable which exists in all functions.
343     // Note that it might never be accessed, in which case it won't be
344     // allocated during variable allocation.
345     variables_.Declare(this,
346                        isolate_->factory()->arguments_symbol(),
347                        VAR,
348                        true,
349                        Variable::ARGUMENTS,
350                        kCreatedInitialized);
351   }
352 }
353
354
355 Scope* Scope::FinalizeBlockScope() {
356   ASSERT(is_block_scope());
357   ASSERT(temps_.is_empty());
358   ASSERT(params_.is_empty());
359
360   if (num_var_or_const() > 0) return this;
361
362   // Remove this scope from outer scope.
363   for (int i = 0; i < outer_scope_->inner_scopes_.length(); i++) {
364     if (outer_scope_->inner_scopes_[i] == this) {
365       outer_scope_->inner_scopes_.Remove(i);
366       break;
367     }
368   }
369
370   // Reparent inner scopes.
371   for (int i = 0; i < inner_scopes_.length(); i++) {
372     outer_scope()->AddInnerScope(inner_scopes_[i]);
373   }
374
375   // Move unresolved variables
376   for (int i = 0; i < unresolved_.length(); i++) {
377     outer_scope()->unresolved_.Add(unresolved_[i]);
378   }
379
380   return NULL;
381 }
382
383
384 Variable* Scope::LocalLookup(Handle<String> name) {
385   Variable* result = variables_.Lookup(name);
386   if (result != NULL || scope_info_.is_null()) {
387     return result;
388   }
389   // If we have a serialized scope info, we might find the variable there.
390   // There should be no local slot with the given name.
391   ASSERT(scope_info_->StackSlotIndex(*name) < 0);
392
393   // Check context slot lookup.
394   VariableMode mode;
395   Variable::Location location = Variable::CONTEXT;
396   InitializationFlag init_flag;
397   int index = scope_info_->ContextSlotIndex(*name, &mode, &init_flag);
398   if (index < 0) {
399     // Check parameters.
400     index = scope_info_->ParameterIndex(*name);
401     if (index < 0) return NULL;
402
403     mode = DYNAMIC;
404     location = Variable::LOOKUP;
405     init_flag = kCreatedInitialized;
406   }
407
408   Variable* var =
409       variables_.Declare(this,
410                          name,
411                          mode,
412                          true,
413                          Variable::NORMAL,
414                          init_flag);
415   var->AllocateTo(location, index);
416   return var;
417 }
418
419
420 Variable* Scope::LookupFunctionVar(Handle<String> name,
421                                    AstNodeFactory<AstNullVisitor>* factory) {
422   if (function_ != NULL && function_->proxy()->name().is_identical_to(name)) {
423     return function_->proxy()->var();
424   } else if (!scope_info_.is_null()) {
425     // If we are backed by a scope info, try to lookup the variable there.
426     VariableMode mode;
427     int index = scope_info_->FunctionContextSlotIndex(*name, &mode);
428     if (index < 0) return NULL;
429     Variable* var = new Variable(
430         this, name, mode, true /* is valid LHS */,
431         Variable::NORMAL, kCreatedInitialized);
432     VariableProxy* proxy = factory->NewVariableProxy(var);
433     VariableDeclaration* declaration =
434         factory->NewVariableDeclaration(proxy, mode, this);
435     DeclareFunctionVar(declaration);
436     var->AllocateTo(Variable::CONTEXT, index);
437     return var;
438   } else {
439     return NULL;
440   }
441 }
442
443
444 Variable* Scope::Lookup(Handle<String> name) {
445   for (Scope* scope = this;
446        scope != NULL;
447        scope = scope->outer_scope()) {
448     Variable* var = scope->LocalLookup(name);
449     if (var != NULL) return var;
450   }
451   return NULL;
452 }
453
454
455 void Scope::DeclareParameter(Handle<String> name, VariableMode mode) {
456   ASSERT(!already_resolved());
457   ASSERT(is_function_scope());
458   Variable* var = variables_.Declare(
459       this, name, mode, true, Variable::NORMAL, kCreatedInitialized);
460   params_.Add(var);
461 }
462
463
464 Variable* Scope::DeclareLocal(Handle<String> name,
465                               VariableMode mode,
466                               InitializationFlag init_flag,
467                               Interface* interface) {
468   ASSERT(!already_resolved());
469   // This function handles VAR and CONST modes.  DYNAMIC variables are
470   // introduces during variable allocation, INTERNAL variables are allocated
471   // explicitly, and TEMPORARY variables are allocated via NewTemporary().
472   ASSERT(mode == VAR ||
473          mode == CONST ||
474          mode == CONST_HARMONY ||
475          mode == LET);
476   ++num_var_or_const_;
477   return variables_.Declare(
478       this, name, mode, true, Variable::NORMAL, init_flag, interface);
479 }
480
481
482 Variable* Scope::DeclareGlobal(Handle<String> name) {
483   ASSERT(is_global_scope());
484   return variables_.Declare(this,
485                             name,
486                             DYNAMIC_GLOBAL,
487                             true,
488                             Variable::NORMAL,
489                             kCreatedInitialized);
490 }
491
492
493 void Scope::RemoveUnresolved(VariableProxy* var) {
494   // Most likely (always?) any variable we want to remove
495   // was just added before, so we search backwards.
496   for (int i = unresolved_.length(); i-- > 0;) {
497     if (unresolved_[i] == var) {
498       unresolved_.Remove(i);
499       return;
500     }
501   }
502 }
503
504
505 Variable* Scope::NewTemporary(Handle<String> name) {
506   ASSERT(!already_resolved());
507   Variable* var = new Variable(this,
508                                name,
509                                TEMPORARY,
510                                true,
511                                Variable::NORMAL,
512                                kCreatedInitialized);
513   temps_.Add(var);
514   return var;
515 }
516
517
518 void Scope::AddDeclaration(Declaration* declaration) {
519   decls_.Add(declaration);
520 }
521
522
523 void Scope::SetIllegalRedeclaration(Expression* expression) {
524   // Record only the first illegal redeclaration.
525   if (!HasIllegalRedeclaration()) {
526     illegal_redecl_ = expression;
527   }
528   ASSERT(HasIllegalRedeclaration());
529 }
530
531
532 void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
533   ASSERT(HasIllegalRedeclaration());
534   illegal_redecl_->Accept(visitor);
535 }
536
537
538 Declaration* Scope::CheckConflictingVarDeclarations() {
539   int length = decls_.length();
540   for (int i = 0; i < length; i++) {
541     Declaration* decl = decls_[i];
542     if (decl->mode() != VAR) continue;
543     Handle<String> name = decl->proxy()->name();
544
545     // Iterate through all scopes until and including the declaration scope.
546     Scope* previous = NULL;
547     Scope* current = decl->scope();
548     do {
549       // There is a conflict if there exists a non-VAR binding.
550       Variable* other_var = current->variables_.Lookup(name);
551       if (other_var != NULL && other_var->mode() != VAR) {
552         return decl;
553       }
554       previous = current;
555       current = current->outer_scope_;
556     } while (!previous->is_declaration_scope());
557   }
558   return NULL;
559 }
560
561
562 VariableProxy* Scope::CheckAssignmentToConst() {
563   // Check this scope.
564   if (is_extended_mode()) {
565     for (int i = 0; i < unresolved_.length(); i++) {
566       ASSERT(unresolved_[i]->var() != NULL);
567       if (unresolved_[i]->var()->is_const_mode() &&
568           unresolved_[i]->IsLValue()) {
569         return unresolved_[i];
570       }
571     }
572   }
573
574   // Check inner scopes.
575   for (int i = 0; i < inner_scopes_.length(); i++) {
576     VariableProxy* proxy = inner_scopes_[i]->CheckAssignmentToConst();
577     if (proxy != NULL) return proxy;
578   }
579
580   // No assignments to const found.
581   return NULL;
582 }
583
584
585 void Scope::CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
586                                          ZoneList<Variable*>* context_locals) {
587   ASSERT(stack_locals != NULL);
588   ASSERT(context_locals != NULL);
589
590   // Collect temporaries which are always allocated on the stack.
591   for (int i = 0; i < temps_.length(); i++) {
592     Variable* var = temps_[i];
593     if (var->is_used()) {
594       ASSERT(var->IsStackLocal());
595       stack_locals->Add(var);
596     }
597   }
598
599   // Collect declared local variables.
600   for (VariableMap::Entry* p = variables_.Start();
601        p != NULL;
602        p = variables_.Next(p)) {
603     Variable* var = reinterpret_cast<Variable*>(p->value);
604     if (var->is_used()) {
605       if (var->IsStackLocal()) {
606         stack_locals->Add(var);
607       } else if (var->IsContextSlot()) {
608         context_locals->Add(var);
609       }
610     }
611   }
612 }
613
614
615 bool Scope::AllocateVariables(CompilationInfo* info,
616                               AstNodeFactory<AstNullVisitor>* factory) {
617   // 1) Propagate scope information.
618   bool outer_scope_calls_non_strict_eval = false;
619   if (outer_scope_ != NULL) {
620     outer_scope_calls_non_strict_eval =
621         outer_scope_->outer_scope_calls_non_strict_eval() |
622         outer_scope_->calls_non_strict_eval();
623   }
624   PropagateScopeInfo(outer_scope_calls_non_strict_eval);
625
626   // 2) Resolve variables.
627   if (!ResolveVariablesRecursively(info, factory)) return false;
628
629   // 3) Allocate variables.
630   AllocateVariablesRecursively();
631
632   return true;
633 }
634
635
636 bool Scope::AllowsLazyCompilation() const {
637   return !force_eager_compilation_ && HasTrivialOuterContext();
638 }
639
640
641 bool Scope::HasTrivialContext() const {
642   // A function scope has a trivial context if it always is the global
643   // context. We iteratively scan out the context chain to see if
644   // there is anything that makes this scope non-trivial; otherwise we
645   // return true.
646   for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
647     if (scope->is_eval_scope()) return false;
648     if (scope->scope_inside_with_) return false;
649     if (scope->num_heap_slots_ > 0) return false;
650   }
651   return true;
652 }
653
654
655 bool Scope::HasTrivialOuterContext() const {
656   Scope* outer = outer_scope_;
657   if (outer == NULL) return true;
658   // Note that the outer context may be trivial in general, but the current
659   // scope may be inside a 'with' statement in which case the outer context
660   // for this scope is not trivial.
661   return !scope_inside_with_ && outer->HasTrivialContext();
662 }
663
664
665 bool Scope::AllowsLazyRecompilation() const {
666   return !force_eager_compilation_ &&
667          !TrivialDeclarationScopesBeforeWithScope();
668 }
669
670
671 bool Scope::TrivialDeclarationScopesBeforeWithScope() const {
672   Scope* outer = outer_scope_;
673   if (outer == NULL) return false;
674   outer = outer->DeclarationScope();
675   while (outer != NULL) {
676     if (outer->is_with_scope()) return true;
677     if (outer->is_declaration_scope() && outer->num_heap_slots() > 0)
678       return false;
679     outer = outer->outer_scope_;
680   }
681   return false;
682 }
683
684
685 int Scope::ContextChainLength(Scope* scope) {
686   int n = 0;
687   for (Scope* s = this; s != scope; s = s->outer_scope_) {
688     ASSERT(s != NULL);  // scope must be in the scope chain
689     if (s->num_heap_slots() > 0) n++;
690   }
691   return n;
692 }
693
694
695 Scope* Scope::DeclarationScope() {
696   Scope* scope = this;
697   while (!scope->is_declaration_scope()) {
698     scope = scope->outer_scope();
699   }
700   return scope;
701 }
702
703
704 Handle<ScopeInfo> Scope::GetScopeInfo() {
705   if (scope_info_.is_null()) {
706     scope_info_ = ScopeInfo::Create(this);
707   }
708   return scope_info_;
709 }
710
711
712 void Scope::GetNestedScopeChain(
713     List<Handle<ScopeInfo> >* chain,
714     int position) {
715   if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo()));
716
717   for (int i = 0; i < inner_scopes_.length(); i++) {
718     Scope* scope = inner_scopes_[i];
719     int beg_pos = scope->start_position();
720     int end_pos = scope->end_position();
721     ASSERT(beg_pos >= 0 && end_pos >= 0);
722     if (beg_pos <= position && position < end_pos) {
723       scope->GetNestedScopeChain(chain, position);
724       return;
725     }
726   }
727 }
728
729
730 #ifdef DEBUG
731 static const char* Header(ScopeType type) {
732   switch (type) {
733     case EVAL_SCOPE: return "eval";
734     case FUNCTION_SCOPE: return "function";
735     case MODULE_SCOPE: return "module";
736     case GLOBAL_SCOPE: return "global";
737     case CATCH_SCOPE: return "catch";
738     case BLOCK_SCOPE: return "block";
739     case WITH_SCOPE: return "with";
740   }
741   UNREACHABLE();
742   return NULL;
743 }
744
745
746 static void Indent(int n, const char* str) {
747   PrintF("%*s%s", n, "", str);
748 }
749
750
751 static void PrintName(Handle<String> name) {
752   SmartArrayPointer<char> s = name->ToCString(DISALLOW_NULLS);
753   PrintF("%s", *s);
754 }
755
756
757 static void PrintLocation(Variable* var) {
758   switch (var->location()) {
759     case Variable::UNALLOCATED:
760       break;
761     case Variable::PARAMETER:
762       PrintF("parameter[%d]", var->index());
763       break;
764     case Variable::LOCAL:
765       PrintF("local[%d]", var->index());
766       break;
767     case Variable::CONTEXT:
768       PrintF("context[%d]", var->index());
769       break;
770     case Variable::LOOKUP:
771       PrintF("lookup");
772       break;
773   }
774 }
775
776
777 static void PrintVar(int indent, Variable* var) {
778   if (var->is_used() || !var->IsUnallocated()) {
779     Indent(indent, Variable::Mode2String(var->mode()));
780     PrintF(" ");
781     PrintName(var->name());
782     PrintF(";  // ");
783     PrintLocation(var);
784     if (var->has_forced_context_allocation()) {
785       if (!var->IsUnallocated()) PrintF(", ");
786       PrintF("forced context allocation");
787     }
788     PrintF("\n");
789   }
790 }
791
792
793 static void PrintMap(int indent, VariableMap* map) {
794   for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
795     Variable* var = reinterpret_cast<Variable*>(p->value);
796     PrintVar(indent, var);
797   }
798 }
799
800
801 void Scope::Print(int n) {
802   int n0 = (n > 0 ? n : 0);
803   int n1 = n0 + 2;  // indentation
804
805   // Print header.
806   Indent(n0, Header(type_));
807   if (scope_name_->length() > 0) {
808     PrintF(" ");
809     PrintName(scope_name_);
810   }
811
812   // Print parameters, if any.
813   if (is_function_scope()) {
814     PrintF(" (");
815     for (int i = 0; i < params_.length(); i++) {
816       if (i > 0) PrintF(", ");
817       PrintName(params_[i]->name());
818     }
819     PrintF(")");
820   }
821
822   PrintF(" { // (%d, %d)\n", start_position(), end_position());
823
824   // Function name, if any (named function literals, only).
825   if (function_ != NULL) {
826     Indent(n1, "// (local) function name: ");
827     PrintName(function_->proxy()->name());
828     PrintF("\n");
829   }
830
831   // Scope info.
832   if (HasTrivialOuterContext()) {
833     Indent(n1, "// scope has trivial outer context\n");
834   }
835   switch (language_mode()) {
836     case CLASSIC_MODE:
837       break;
838     case STRICT_MODE:
839       Indent(n1, "// strict mode scope\n");
840       break;
841     case EXTENDED_MODE:
842       Indent(n1, "// extended mode scope\n");
843       break;
844   }
845   if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
846   if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
847   if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
848   if (outer_scope_calls_non_strict_eval_) {
849     Indent(n1, "// outer scope calls 'eval' in non-strict context\n");
850   }
851   if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
852   if (num_stack_slots_ > 0) { Indent(n1, "// ");
853   PrintF("%d stack slots\n", num_stack_slots_); }
854   if (num_heap_slots_ > 0) { Indent(n1, "// ");
855   PrintF("%d heap slots\n", num_heap_slots_); }
856
857   // Print locals.
858   Indent(n1, "// function var\n");
859   if (function_ != NULL) {
860     PrintVar(n1, function_->proxy()->var());
861   }
862
863   Indent(n1, "// temporary vars\n");
864   for (int i = 0; i < temps_.length(); i++) {
865     PrintVar(n1, temps_[i]);
866   }
867
868   Indent(n1, "// local vars\n");
869   PrintMap(n1, &variables_);
870
871   Indent(n1, "// dynamic vars\n");
872   if (dynamics_ != NULL) {
873     PrintMap(n1, dynamics_->GetMap(DYNAMIC));
874     PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
875     PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
876   }
877
878   // Print inner scopes (disable by providing negative n).
879   if (n >= 0) {
880     for (int i = 0; i < inner_scopes_.length(); i++) {
881       PrintF("\n");
882       inner_scopes_[i]->Print(n1);
883     }
884   }
885
886   Indent(n0, "}\n");
887 }
888 #endif  // DEBUG
889
890
891 Variable* Scope::NonLocal(Handle<String> name, VariableMode mode) {
892   if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
893   VariableMap* map = dynamics_->GetMap(mode);
894   Variable* var = map->Lookup(name);
895   if (var == NULL) {
896     // Declare a new non-local.
897     InitializationFlag init_flag = (mode == VAR)
898         ? kCreatedInitialized : kNeedsInitialization;
899     var = map->Declare(NULL,
900                        name,
901                        mode,
902                        true,
903                        Variable::NORMAL,
904                        init_flag);
905     // Allocate it by giving it a dynamic lookup.
906     var->AllocateTo(Variable::LOOKUP, -1);
907   }
908   return var;
909 }
910
911
912 Variable* Scope::LookupRecursive(Handle<String> name,
913                                  BindingKind* binding_kind,
914                                  AstNodeFactory<AstNullVisitor>* factory) {
915   ASSERT(binding_kind != NULL);
916   // Try to find the variable in this scope.
917   Variable* var = LocalLookup(name);
918
919   // We found a variable and we are done. (Even if there is an 'eval' in
920   // this scope which introduces the same variable again, the resulting
921   // variable remains the same.)
922   if (var != NULL) {
923     *binding_kind = BOUND;
924     return var;
925   }
926
927   // We did not find a variable locally. Check against the function variable,
928   // if any. We can do this for all scopes, since the function variable is
929   // only present - if at all - for function scopes.
930   *binding_kind = UNBOUND;
931   var = LookupFunctionVar(name, factory);
932   if (var != NULL) {
933     *binding_kind = BOUND;
934   } else if (outer_scope_ != NULL) {
935     var = outer_scope_->LookupRecursive(name, binding_kind, factory);
936     if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
937       var->ForceContextAllocation();
938     }
939   } else {
940     ASSERT(is_global_scope());
941   }
942
943   if (is_with_scope()) {
944     // The current scope is a with scope, so the variable binding can not be
945     // statically resolved. However, note that it was necessary to do a lookup
946     // in the outer scope anyway, because if a binding exists in an outer scope,
947     // the associated variable has to be marked as potentially being accessed
948     // from inside of an inner with scope (the property may not be in the 'with'
949     // object).
950     *binding_kind = DYNAMIC_LOOKUP;
951     return NULL;
952   } else if (calls_non_strict_eval()) {
953     // A variable binding may have been found in an outer scope, but the current
954     // scope makes a non-strict 'eval' call, so the found variable may not be
955     // the correct one (the 'eval' may introduce a binding with the same name).
956     // In that case, change the lookup result to reflect this situation.
957     if (*binding_kind == BOUND) {
958       *binding_kind = BOUND_EVAL_SHADOWED;
959     } else if (*binding_kind == UNBOUND) {
960       *binding_kind = UNBOUND_EVAL_SHADOWED;
961     }
962   }
963   return var;
964 }
965
966
967 bool Scope::ResolveVariable(CompilationInfo* info,
968                             VariableProxy* proxy,
969                             AstNodeFactory<AstNullVisitor>* factory) {
970   ASSERT(info->global_scope()->is_global_scope());
971
972   // If the proxy is already resolved there's nothing to do
973   // (functions and consts may be resolved by the parser).
974   if (proxy->var() != NULL) return true;
975
976   // Otherwise, try to resolve the variable.
977   BindingKind binding_kind;
978   Variable* var = LookupRecursive(proxy->name(), &binding_kind, factory);
979   switch (binding_kind) {
980     case BOUND:
981       // We found a variable binding.
982       break;
983
984     case BOUND_EVAL_SHADOWED:
985       // We either found a variable binding that might be shadowed by eval  or
986       // gave up on it (e.g. by encountering a local with the same in the outer
987       // scope which was not promoted to a context, this can happen if we use
988       // debugger to evaluate arbitrary expressions at a break point).
989       if (var->is_global()) {
990         var = NonLocal(proxy->name(), DYNAMIC_GLOBAL);
991
992         if (is_qml_mode()) {
993           Handle<GlobalObject> global = isolate_->global();
994
995 #ifdef ENABLE_DEBUGGER_SUPPORT
996           if (isolate_->debug()->IsLoaded() && isolate_->debug()->InDebugger()) {
997             // Get the context before the debugger was entered.
998             SaveContext *save = isolate_->save_context();
999             while (save != NULL && *save->context() == *isolate_->debug()->debug_context())
1000               save = save->prev();
1001
1002             global = Handle<GlobalObject>(save->context()->global());
1003           }
1004 #endif
1005
1006           if (is_qml_mode() && !global->HasProperty(*(proxy->name()))) {
1007             var->set_is_qml_global(true);
1008           }
1009         }
1010       } else if (var->is_dynamic()) {
1011         var = NonLocal(proxy->name(), DYNAMIC);
1012       } else {
1013         Variable* invalidated = var;
1014         var = NonLocal(proxy->name(), DYNAMIC_LOCAL);
1015         var->set_local_if_not_shadowed(invalidated);
1016       }
1017       break;
1018
1019     case UNBOUND:
1020       // No binding has been found. Declare a variable in global scope.
1021       var = info->global_scope()->DeclareGlobal(proxy->name());
1022
1023       if (is_qml_mode()) {
1024         Handle<GlobalObject> global = isolate_->global();
1025
1026 #ifdef ENABLE_DEBUGGER_SUPPORT
1027         if (isolate_->debug()->IsLoaded() && isolate_->debug()->InDebugger()) {
1028           // Get the context before the debugger was entered.
1029           SaveContext *save = isolate_->save_context();
1030           while (save != NULL && *save->context() == *isolate_->debug()->debug_context())
1031             save = save->prev();
1032
1033           global = Handle<GlobalObject>(save->context()->global());
1034         }
1035 #endif
1036
1037         if (!global->HasProperty(*(proxy->name()))) {
1038           var->set_is_qml_global(true);
1039         }
1040       }
1041
1042       break;
1043
1044     case UNBOUND_EVAL_SHADOWED:
1045       // No binding has been found. But some scope makes a
1046       // non-strict 'eval' call.
1047       var = NonLocal(proxy->name(), DYNAMIC_GLOBAL);
1048
1049       if (is_qml_mode()) {
1050         Handle<GlobalObject> global = isolate_->global();
1051
1052 #ifdef ENABLE_DEBUGGER_SUPPORT
1053         if (isolate_->debug()->IsLoaded() && isolate_->debug()->InDebugger()) {
1054           // Get the context before the debugger was entered.
1055           SaveContext *save = isolate_->save_context();
1056           while (save != NULL && *save->context() == *isolate_->debug()->debug_context())
1057             save = save->prev();
1058
1059           global = Handle<GlobalObject>(save->context()->global());
1060         }
1061 #endif
1062
1063         if (is_qml_mode() && !global->HasProperty(*(proxy->name()))) {
1064           var->set_is_qml_global(true);
1065         }
1066       }
1067
1068       break;
1069
1070     case DYNAMIC_LOOKUP:
1071       // The variable could not be resolved statically.
1072       var = NonLocal(proxy->name(), DYNAMIC);
1073       break;
1074   }
1075
1076   ASSERT(var != NULL);
1077   proxy->BindTo(var);
1078
1079   if (FLAG_harmony_modules) {
1080     bool ok;
1081 #ifdef DEBUG
1082     if (FLAG_print_interface_details)
1083       PrintF("# Resolve %s:\n", var->name()->ToAsciiArray());
1084 #endif
1085     proxy->interface()->Unify(var->interface(), &ok);
1086     if (!ok) {
1087 #ifdef DEBUG
1088       if (FLAG_print_interfaces) {
1089         PrintF("SCOPES TYPE ERROR\n");
1090         PrintF("proxy: ");
1091         proxy->interface()->Print();
1092         PrintF("var: ");
1093         var->interface()->Print();
1094       }
1095 #endif
1096
1097       // Inconsistent use of module. Throw a syntax error.
1098       // TODO(rossberg): generate more helpful error message.
1099       MessageLocation location(info->script(),
1100                                proxy->position(),
1101                                proxy->position());
1102       Isolate* isolate = Isolate::Current();
1103       Factory* factory = isolate->factory();
1104       Handle<JSArray> array = factory->NewJSArray(1);
1105       USE(JSObject::SetElement(array, 0, var->name(), NONE, kStrictMode));
1106       Handle<Object> result =
1107           factory->NewSyntaxError("module_type_error", array);
1108       isolate->Throw(*result, &location);
1109       return false;
1110     }
1111   }
1112
1113   return true;
1114 }
1115
1116
1117 bool Scope::ResolveVariablesRecursively(
1118     CompilationInfo* info,
1119     AstNodeFactory<AstNullVisitor>* factory) {
1120   ASSERT(info->global_scope()->is_global_scope());
1121
1122   // Resolve unresolved variables for this scope.
1123   for (int i = 0; i < unresolved_.length(); i++) {
1124     if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1125   }
1126
1127   // Resolve unresolved variables for inner scopes.
1128   for (int i = 0; i < inner_scopes_.length(); i++) {
1129     if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
1130       return false;
1131   }
1132
1133   return true;
1134 }
1135
1136
1137 bool Scope::PropagateScopeInfo(bool outer_scope_calls_non_strict_eval ) {
1138   if (outer_scope_calls_non_strict_eval) {
1139     outer_scope_calls_non_strict_eval_ = true;
1140   }
1141
1142   bool calls_non_strict_eval =
1143       this->calls_non_strict_eval() || outer_scope_calls_non_strict_eval_;
1144   for (int i = 0; i < inner_scopes_.length(); i++) {
1145     Scope* inner_scope = inner_scopes_[i];
1146     if (inner_scope->PropagateScopeInfo(calls_non_strict_eval)) {
1147       inner_scope_calls_eval_ = true;
1148     }
1149     if (inner_scope->force_eager_compilation_) {
1150       force_eager_compilation_ = true;
1151     }
1152   }
1153
1154   return scope_calls_eval_ || inner_scope_calls_eval_;
1155 }
1156
1157
1158 bool Scope::MustAllocate(Variable* var) {
1159   // Give var a read/write use if there is a chance it might be accessed
1160   // via an eval() call.  This is only possible if the variable has a
1161   // visible name.
1162   if ((var->is_this() || var->name()->length() > 0) &&
1163       (var->has_forced_context_allocation() ||
1164        scope_calls_eval_ ||
1165        inner_scope_calls_eval_ ||
1166        scope_contains_with_ ||
1167        is_catch_scope() ||
1168        is_block_scope())) {
1169     var->set_is_used(true);
1170   }
1171   // Global variables do not need to be allocated.
1172   return !var->is_global() && var->is_used();
1173 }
1174
1175
1176 bool Scope::MustAllocateInContext(Variable* var) {
1177   // If var is accessed from an inner scope, or if there is a possibility
1178   // that it might be accessed from the current or an inner scope (through
1179   // an eval() call or a runtime with lookup), it must be allocated in the
1180   // context.
1181   //
1182   // Exceptions: temporary variables are never allocated in a context;
1183   // catch-bound variables are always allocated in a context.
1184   if (var->mode() == TEMPORARY) return false;
1185   if (is_catch_scope() || is_block_scope() || is_module_scope()) return true;
1186   return var->has_forced_context_allocation() ||
1187       scope_calls_eval_ ||
1188       inner_scope_calls_eval_ ||
1189       scope_contains_with_ ||
1190       var->is_global();
1191 }
1192
1193
1194 bool Scope::HasArgumentsParameter() {
1195   for (int i = 0; i < params_.length(); i++) {
1196     if (params_[i]->name().is_identical_to(
1197             isolate_->factory()->arguments_symbol())) {
1198       return true;
1199     }
1200   }
1201   return false;
1202 }
1203
1204
1205 void Scope::AllocateStackSlot(Variable* var) {
1206   var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1207 }
1208
1209
1210 void Scope::AllocateHeapSlot(Variable* var) {
1211   var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1212 }
1213
1214
1215 void Scope::AllocateParameterLocals() {
1216   ASSERT(is_function_scope());
1217   Variable* arguments = LocalLookup(isolate_->factory()->arguments_symbol());
1218   ASSERT(arguments != NULL);  // functions have 'arguments' declared implicitly
1219
1220   bool uses_nonstrict_arguments = false;
1221
1222   if (MustAllocate(arguments) && !HasArgumentsParameter()) {
1223     // 'arguments' is used. Unless there is also a parameter called
1224     // 'arguments', we must be conservative and allocate all parameters to
1225     // the context assuming they will be captured by the arguments object.
1226     // If we have a parameter named 'arguments', a (new) value is always
1227     // assigned to it via the function invocation. Then 'arguments' denotes
1228     // that specific parameter value and cannot be used to access the
1229     // parameters, which is why we don't need to allocate an arguments
1230     // object in that case.
1231
1232     // We are using 'arguments'. Tell the code generator that is needs to
1233     // allocate the arguments object by setting 'arguments_'.
1234     arguments_ = arguments;
1235
1236     // In strict mode 'arguments' does not alias formal parameters.
1237     // Therefore in strict mode we allocate parameters as if 'arguments'
1238     // were not used.
1239     uses_nonstrict_arguments = is_classic_mode();
1240   }
1241
1242   // The same parameter may occur multiple times in the parameters_ list.
1243   // If it does, and if it is not copied into the context object, it must
1244   // receive the highest parameter index for that parameter; thus iteration
1245   // order is relevant!
1246   for (int i = params_.length() - 1; i >= 0; --i) {
1247     Variable* var = params_[i];
1248     ASSERT(var->scope() == this);
1249     if (uses_nonstrict_arguments) {
1250       // Force context allocation of the parameter.
1251       var->ForceContextAllocation();
1252     }
1253
1254     if (MustAllocate(var)) {
1255       if (MustAllocateInContext(var)) {
1256         ASSERT(var->IsUnallocated() || var->IsContextSlot());
1257         if (var->IsUnallocated()) {
1258           AllocateHeapSlot(var);
1259         }
1260       } else {
1261         ASSERT(var->IsUnallocated() || var->IsParameter());
1262         if (var->IsUnallocated()) {
1263           var->AllocateTo(Variable::PARAMETER, i);
1264         }
1265       }
1266     }
1267   }
1268 }
1269
1270
1271 void Scope::AllocateNonParameterLocal(Variable* var) {
1272   ASSERT(var->scope() == this);
1273   ASSERT(!var->IsVariable(isolate_->factory()->result_symbol()) ||
1274          !var->IsStackLocal());
1275   if (var->IsUnallocated() && MustAllocate(var)) {
1276     if (MustAllocateInContext(var)) {
1277       AllocateHeapSlot(var);
1278     } else {
1279       AllocateStackSlot(var);
1280     }
1281   }
1282 }
1283
1284
1285 void Scope::AllocateNonParameterLocals() {
1286   // All variables that have no rewrite yet are non-parameter locals.
1287   for (int i = 0; i < temps_.length(); i++) {
1288     AllocateNonParameterLocal(temps_[i]);
1289   }
1290
1291   for (VariableMap::Entry* p = variables_.Start();
1292        p != NULL;
1293        p = variables_.Next(p)) {
1294     Variable* var = reinterpret_cast<Variable*>(p->value);
1295     AllocateNonParameterLocal(var);
1296   }
1297
1298   // For now, function_ must be allocated at the very end.  If it gets
1299   // allocated in the context, it must be the last slot in the context,
1300   // because of the current ScopeInfo implementation (see
1301   // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
1302   if (function_ != NULL) {
1303     AllocateNonParameterLocal(function_->proxy()->var());
1304   }
1305 }
1306
1307
1308 void Scope::AllocateVariablesRecursively() {
1309   // Allocate variables for inner scopes.
1310   for (int i = 0; i < inner_scopes_.length(); i++) {
1311     inner_scopes_[i]->AllocateVariablesRecursively();
1312   }
1313
1314   // If scope is already resolved, we still need to allocate
1315   // variables in inner scopes which might not had been resolved yet.
1316   if (already_resolved()) return;
1317   // The number of slots required for variables.
1318   num_stack_slots_ = 0;
1319   num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
1320
1321   // Allocate variables for this scope.
1322   // Parameters must be allocated first, if any.
1323   if (is_function_scope()) AllocateParameterLocals();
1324   AllocateNonParameterLocals();
1325
1326   // Force allocation of a context for this scope if necessary. For a 'with'
1327   // scope and for a function scope that makes an 'eval' call we need a context,
1328   // even if no local variables were statically allocated in the scope.
1329   // Likewise for modules.
1330   bool must_have_context = is_with_scope() || is_module_scope() ||
1331       (is_function_scope() && calls_eval());
1332
1333   // If we didn't allocate any locals in the local context, then we only
1334   // need the minimal number of slots if we must have a context.
1335   if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1336     num_heap_slots_ = 0;
1337   }
1338
1339   // Allocation done.
1340   ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1341 }
1342
1343
1344 int Scope::StackLocalCount() const {
1345   return num_stack_slots() -
1346       (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
1347 }
1348
1349
1350 int Scope::ContextLocalCount() const {
1351   if (num_heap_slots() == 0) return 0;
1352   return num_heap_slots() - Context::MIN_CONTEXT_SLOTS -
1353       (function_ != NULL && function_->proxy()->var()->IsContextSlot() ? 1 : 0);
1354 }
1355
1356 } }  // namespace v8::internal