blob: 88b1c66f3b0d3db87fcd8e64dacd3970fe8f4beb [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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 "prettyprinter.h"
31#include "scopeinfo.h"
32#include "scopes.h"
33
kasperl@chromium.org71affb52009-05-26 05:44:31 +000034namespace v8 {
35namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036
37// ----------------------------------------------------------------------------
38// A Zone allocator for use with LocalsMap.
39
40class ZoneAllocator: public Allocator {
41 public:
42 /* nothing to do */
43 virtual ~ZoneAllocator() {}
44
45 virtual void* New(size_t size) { return Zone::New(size); }
46
47 /* ignored - Zone is freed in one fell swoop */
48 virtual void Delete(void* p) {}
49};
50
51
52static ZoneAllocator LocalsMapAllocator;
53
54
55// ----------------------------------------------------------------------------
56// Implementation of LocalsMap
57//
58// Note: We are storing the handle locations as key values in the hash map.
59// When inserting a new variable via Declare(), we rely on the fact that
60// the handle location remains alive for the duration of that variable
61// use. Because a Variable holding a handle with the same location exists
62// this is ensured.
63
64static bool Match(void* key1, void* key2) {
65 String* name1 = *reinterpret_cast<String**>(key1);
66 String* name2 = *reinterpret_cast<String**>(key2);
67 ASSERT(name1->IsSymbol());
68 ASSERT(name2->IsSymbol());
69 return name1 == name2;
70}
71
72
73// Dummy constructor
74LocalsMap::LocalsMap(bool gotta_love_static_overloading) : HashMap() {}
75
76LocalsMap::LocalsMap() : HashMap(Match, &LocalsMapAllocator, 8) {}
77LocalsMap::~LocalsMap() {}
78
79
80Variable* LocalsMap::Declare(Scope* scope,
81 Handle<String> name,
82 Variable::Mode mode,
83 bool is_valid_LHS,
ager@chromium.org3e875802009-06-29 08:26:34 +000084 Variable::Kind kind) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000085 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), true);
86 if (p->value == NULL) {
87 // The variable has not been declared yet -> insert it.
88 ASSERT(p->key == name.location());
ager@chromium.org3e875802009-06-29 08:26:34 +000089 p->value = new Variable(scope, name, mode, is_valid_LHS, kind);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000090 }
91 return reinterpret_cast<Variable*>(p->value);
92}
93
94
95Variable* LocalsMap::Lookup(Handle<String> name) {
96 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), false);
97 if (p != NULL) {
98 ASSERT(*reinterpret_cast<String**>(p->key) == *name);
99 ASSERT(p->value != NULL);
100 return reinterpret_cast<Variable*>(p->value);
101 }
102 return NULL;
103}
104
105
106// ----------------------------------------------------------------------------
107// Implementation of Scope
108
109
110// Dummy constructor
111Scope::Scope()
112 : inner_scopes_(0),
113 locals_(false),
114 temps_(0),
115 params_(0),
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000116 dynamics_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 unresolved_(0),
118 decls_(0) {
119}
120
121
122Scope::Scope(Scope* outer_scope, Type type)
123 : outer_scope_(outer_scope),
124 inner_scopes_(4),
125 type_(type),
126 scope_name_(Factory::empty_symbol()),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000127 temps_(4),
128 params_(4),
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000129 dynamics_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000130 unresolved_(16),
131 decls_(4),
132 receiver_(NULL),
133 function_(NULL),
134 arguments_(NULL),
135 arguments_shadow_(NULL),
136 illegal_redecl_(NULL),
137 scope_inside_with_(false),
138 scope_contains_with_(false),
139 scope_calls_eval_(false),
140 outer_scope_calls_eval_(false),
141 inner_scope_calls_eval_(false),
ager@chromium.org381abbb2009-02-25 13:23:22 +0000142 outer_scope_is_eval_scope_(false),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000143 force_eager_compilation_(false),
144 num_stack_slots_(0),
145 num_heap_slots_(0) {
146 // At some point we might want to provide outer scopes to
147 // eval scopes (by walking the stack and reading the scope info).
148 // In that case, the ASSERT below needs to be adjusted.
149 ASSERT((type == GLOBAL_SCOPE || type == EVAL_SCOPE) == (outer_scope == NULL));
150 ASSERT(!HasIllegalRedeclaration());
151}
152
153
154void Scope::Initialize(bool inside_with) {
155 // Add this scope as a new inner scope of the outer scope.
156 if (outer_scope_ != NULL) {
157 outer_scope_->inner_scopes_.Add(this);
158 scope_inside_with_ = outer_scope_->scope_inside_with_ || inside_with;
159 } else {
160 scope_inside_with_ = inside_with;
161 }
162
163 // Declare convenience variables.
164 // Declare and allocate receiver (even for the global scope, and even
165 // if naccesses_ == 0).
166 // NOTE: When loading parameters in the global scope, we must take
167 // care not to access them as properties of the global object, but
168 // instead load them directly from the stack. Currently, the only
169 // such parameter is 'this' which is passed on the stack when
170 // invoking scripts
171 { Variable* var =
ager@chromium.org3e875802009-06-29 08:26:34 +0000172 locals_.Declare(this, Factory::this_symbol(), Variable::VAR,
173 false, Variable::THIS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000174 var->rewrite_ = new Slot(var, Slot::PARAMETER, -1);
175 receiver_ = new VariableProxy(Factory::this_symbol(), true, false);
176 receiver_->BindTo(var);
177 }
178
179 if (is_function_scope()) {
180 // Declare 'arguments' variable which exists in all functions.
181 // Note that it may never be accessed, in which case it won't
182 // be allocated during variable allocation.
ager@chromium.org3e875802009-06-29 08:26:34 +0000183 locals_.Declare(this, Factory::arguments_symbol(), Variable::VAR,
184 true, Variable::ARGUMENTS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000185 }
186}
187
188
189
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000190Variable* Scope::LookupLocal(Handle<String> name) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191 return locals_.Lookup(name);
192}
193
194
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000195Variable* Scope::Lookup(Handle<String> name) {
196 for (Scope* scope = this;
197 scope != NULL;
198 scope = scope->outer_scope()) {
199 Variable* var = scope->LookupLocal(name);
200 if (var != NULL) return var;
201 }
202 return NULL;
203}
204
205
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206Variable* Scope::DeclareFunctionVar(Handle<String> name) {
207 ASSERT(is_function_scope() && function_ == NULL);
ager@chromium.org3e875802009-06-29 08:26:34 +0000208 function_ = new Variable(this, name, Variable::CONST, true, Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000209 return function_;
210}
211
212
213Variable* Scope::Declare(Handle<String> name, Variable::Mode mode) {
214 // DYNAMIC variables are introduces during variable allocation,
215 // INTERNAL variables are allocated explicitly, and TEMPORARY
216 // variables are allocated via NewTemporary().
217 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
ager@chromium.org3e875802009-06-29 08:26:34 +0000218 return locals_.Declare(this, name, mode, true, Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219}
220
221
222void Scope::AddParameter(Variable* var) {
223 ASSERT(is_function_scope());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000224 ASSERT(LookupLocal(var->name()) == var);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000225 params_.Add(var);
226}
227
228
229VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
230 // Note that we must not share the unresolved variables with
231 // the same name because they may be removed selectively via
232 // RemoveUnresolved().
233 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
234 unresolved_.Add(proxy);
235 return proxy;
236}
237
238
239void Scope::RemoveUnresolved(VariableProxy* var) {
240 // Most likely (always?) any variable we want to remove
241 // was just added before, so we search backwards.
242 for (int i = unresolved_.length(); i-- > 0;) {
243 if (unresolved_[i] == var) {
244 unresolved_.Remove(i);
245 return;
246 }
247 }
248}
249
250
251VariableProxy* Scope::NewTemporary(Handle<String> name) {
ager@chromium.org3e875802009-06-29 08:26:34 +0000252 Variable* var = new Variable(this, name, Variable::TEMPORARY, true,
253 Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254 VariableProxy* tmp = new VariableProxy(name, false, false);
255 tmp->BindTo(var);
256 temps_.Add(var);
257 return tmp;
258}
259
260
261void Scope::AddDeclaration(Declaration* declaration) {
262 decls_.Add(declaration);
263}
264
265
266void Scope::SetIllegalRedeclaration(Expression* expression) {
267 // Only set the illegal redeclaration expression the
268 // first time the function is called.
269 if (!HasIllegalRedeclaration()) {
270 illegal_redecl_ = expression;
271 }
272 ASSERT(HasIllegalRedeclaration());
273}
274
275
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000276void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000277 ASSERT(HasIllegalRedeclaration());
278 illegal_redecl_->Accept(visitor);
279}
280
281
282template<class Allocator>
283void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
284 // Collect variables in this scope.
285 // Note that the function_ variable - if present - is not
286 // collected here but handled separately in ScopeInfo
287 // which is the current user of this function).
288 for (int i = 0; i < temps_.length(); i++) {
289 Variable* var = temps_[i];
290 if (var->var_uses()->is_used()) {
291 locals->Add(var);
292 }
293 }
294 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
295 Variable* var = reinterpret_cast<Variable*>(p->value);
296 if (var->var_uses()->is_used()) {
297 locals->Add(var);
298 }
299 }
300}
301
302
303// Make sure the method gets instantiated by the template system.
304template void Scope::CollectUsedVariables(
305 List<Variable*, FreeStoreAllocationPolicy>* locals);
306template void Scope::CollectUsedVariables(
307 List<Variable*, PreallocatedStorage>* locals);
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000308template void Scope::CollectUsedVariables(
309 List<Variable*, ZoneListAllocationPolicy>* locals);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310
311
ager@chromium.org381abbb2009-02-25 13:23:22 +0000312void Scope::AllocateVariables(Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313 ASSERT(outer_scope_ == NULL); // eval or global scopes only
314
315 // 1) Propagate scope information.
316 // If we are in an eval scope, we may have other outer scopes about
317 // which we don't know anything at this point. Thus we must be conservative
318 // and assume they may invoke eval themselves. Eventually we could capture
319 // this information in the ScopeInfo and then use it here (by traversing
320 // the call chain stack, at compile time).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000321 bool eval_scope = is_eval_scope();
322 PropagateScopeInfo(eval_scope, eval_scope);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323
324 // 2) Resolve variables.
325 Scope* global_scope = NULL;
326 if (is_global_scope()) global_scope = this;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000327 ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000328
329 // 3) Allocate variables.
330 AllocateVariablesRecursively();
331}
332
333
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334bool Scope::AllowsLazyCompilation() const {
335 return !force_eager_compilation_ && HasTrivialOuterContext();
336}
337
338
339bool Scope::HasTrivialContext() const {
340 // A function scope has a trivial context if it always is the global
341 // context. We iteratively scan out the context chain to see if
342 // there is anything that makes this scope non-trivial; otherwise we
343 // return true.
344 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
345 if (scope->is_eval_scope()) return false;
346 if (scope->scope_inside_with_) return false;
347 if (scope->num_heap_slots_ > 0) return false;
348 }
349 return true;
350}
351
352
353bool Scope::HasTrivialOuterContext() const {
354 Scope* outer = outer_scope_;
355 if (outer == NULL) return true;
356 // Note that the outer context may be trivial in general, but the current
357 // scope may be inside a 'with' statement in which case the outer context
358 // for this scope is not trivial.
359 return !scope_inside_with_ && outer->HasTrivialContext();
360}
361
362
363int Scope::ContextChainLength(Scope* scope) {
364 int n = 0;
365 for (Scope* s = this; s != scope; s = s->outer_scope_) {
366 ASSERT(s != NULL); // scope must be in the scope chain
367 if (s->num_heap_slots() > 0) n++;
368 }
369 return n;
370}
371
372
373#ifdef DEBUG
374static const char* Header(Scope::Type type) {
375 switch (type) {
376 case Scope::EVAL_SCOPE: return "eval";
377 case Scope::FUNCTION_SCOPE: return "function";
378 case Scope::GLOBAL_SCOPE: return "global";
379 }
380 UNREACHABLE();
381 return NULL;
382}
383
384
385static void Indent(int n, const char* str) {
386 PrintF("%*s%s", n, "", str);
387}
388
389
390static void PrintName(Handle<String> name) {
391 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
392 PrintF("%s", *s);
393}
394
395
396static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
397 if (var->var_uses()->is_used() || var->rewrite() != NULL) {
398 Indent(indent, Variable::Mode2String(var->mode()));
399 PrintF(" ");
400 PrintName(var->name());
401 PrintF("; // ");
402 if (var->rewrite() != NULL) PrintF("%s, ", printer->Print(var->rewrite()));
403 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access, ");
404 PrintF("var ");
405 var->var_uses()->Print();
406 PrintF(", obj ");
407 var->obj_uses()->Print();
408 PrintF("\n");
409 }
410}
411
412
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000413static void PrintMap(PrettyPrinter* printer, int indent, LocalsMap* map) {
414 for (LocalsMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
415 Variable* var = reinterpret_cast<Variable*>(p->value);
416 PrintVar(printer, indent, var);
417 }
418}
419
420
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000421void Scope::Print(int n) {
422 int n0 = (n > 0 ? n : 0);
423 int n1 = n0 + 2; // indentation
424
425 // Print header.
426 Indent(n0, Header(type_));
427 if (scope_name_->length() > 0) {
428 PrintF(" ");
429 PrintName(scope_name_);
430 }
431
432 // Print parameters, if any.
433 if (is_function_scope()) {
434 PrintF(" (");
435 for (int i = 0; i < params_.length(); i++) {
436 if (i > 0) PrintF(", ");
437 PrintName(params_[i]->name());
438 }
439 PrintF(")");
440 }
441
442 PrintF(" {\n");
443
444 // Function name, if any (named function literals, only).
445 if (function_ != NULL) {
446 Indent(n1, "// (local) function name: ");
447 PrintName(function_->name());
448 PrintF("\n");
449 }
450
451 // Scope info.
452 if (HasTrivialOuterContext()) {
453 Indent(n1, "// scope has trivial outer context\n");
454 }
455 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
456 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
457 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
458 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
459 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
ager@chromium.org381abbb2009-02-25 13:23:22 +0000460 if (outer_scope_is_eval_scope_) {
461 Indent(n1, "// outer scope is 'eval' scope\n");
462 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000463 if (num_stack_slots_ > 0) { Indent(n1, "// ");
464 PrintF("%d stack slots\n", num_stack_slots_); }
465 if (num_heap_slots_ > 0) { Indent(n1, "// ");
466 PrintF("%d heap slots\n", num_heap_slots_); }
467
468 // Print locals.
469 PrettyPrinter printer;
470 Indent(n1, "// function var\n");
471 if (function_ != NULL) {
472 PrintVar(&printer, n1, function_);
473 }
474
475 Indent(n1, "// temporary vars\n");
476 for (int i = 0; i < temps_.length(); i++) {
477 PrintVar(&printer, n1, temps_[i]);
478 }
479
480 Indent(n1, "// local vars\n");
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000481 PrintMap(&printer, n1, &locals_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000483 Indent(n1, "// dynamic vars\n");
484 if (dynamics_ != NULL) {
485 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC));
486 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_LOCAL));
487 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_GLOBAL));
488 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000489
490 // Print inner scopes (disable by providing negative n).
491 if (n >= 0) {
492 for (int i = 0; i < inner_scopes_.length(); i++) {
493 PrintF("\n");
494 inner_scopes_[i]->Print(n1);
495 }
496 }
497
498 Indent(n0, "}\n");
499}
500#endif // DEBUG
501
502
ager@chromium.org381abbb2009-02-25 13:23:22 +0000503Variable* Scope::NonLocal(Handle<String> name, Variable::Mode mode) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000504 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
505 LocalsMap* map = dynamics_->GetMap(mode);
506 Variable* var = map->Lookup(name);
507 if (var == NULL) {
508 // Declare a new non-local.
ager@chromium.org3e875802009-06-29 08:26:34 +0000509 var = map->Declare(NULL, name, mode, true, Variable::NORMAL);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000510 // Allocate it by giving it a dynamic lookup.
511 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000512 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000513 return var;
514}
515
516
517// Lookup a variable starting with this scope. The result is either
518// the statically resolved (local!) variable belonging to an outer scope,
519// or NULL. It may be NULL because a) we couldn't find a variable, or b)
520// because the variable is just a guess (and may be shadowed by another
521// variable that is introduced dynamically via an 'eval' call or a 'with'
522// statement).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000523Variable* Scope::LookupRecursive(Handle<String> name,
524 bool inner_lookup,
525 Variable** invalidated_local) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000526 // If we find a variable, but the current scope calls 'eval', the found
527 // variable may not be the correct one (the 'eval' may introduce a
528 // property with the same name). In that case, remember that the variable
529 // found is just a guess.
530 bool guess = scope_calls_eval_;
531
532 // Try to find the variable in this scope.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000533 Variable* var = LookupLocal(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000534
535 if (var != NULL) {
536 // We found a variable. If this is not an inner lookup, we are done.
537 // (Even if there is an 'eval' in this scope which introduces the
538 // same variable again, the resulting variable remains the same.
539 // Note that enclosing 'with' statements are handled at the call site.)
540 if (!inner_lookup)
541 return var;
542
543 } else {
544 // We did not find a variable locally. Check against the function variable,
545 // if any. We can do this for all scopes, since the function variable is
546 // only present - if at all - for function scopes.
547 //
548 // This lookup corresponds to a lookup in the "intermediate" scope sitting
549 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
550 // the name of named function literal is kept in an intermediate scope
ager@chromium.org32912102009-01-16 10:38:43 +0000551 // in between this scope and the next outer scope.)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000552 if (function_ != NULL && function_->name().is_identical_to(name)) {
553 var = function_;
554
555 } else if (outer_scope_ != NULL) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000556 var = outer_scope_->LookupRecursive(name, true, invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557 // We may have found a variable in an outer scope. However, if
558 // the current scope is inside a 'with', the actual variable may
559 // be a property introduced via the 'with' statement. Then, the
560 // variable we may have found is just a guess.
561 if (scope_inside_with_)
562 guess = true;
563 }
564
565 // If we did not find a variable, we are done.
566 if (var == NULL)
567 return NULL;
568 }
569
570 ASSERT(var != NULL);
571
572 // If this is a lookup from an inner scope, mark the variable.
573 if (inner_lookup)
574 var->is_accessed_from_inner_scope_ = true;
575
576 // If the variable we have found is just a guess, invalidate the result.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000577 if (guess) {
578 *invalidated_local = var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579 var = NULL;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000580 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000581
582 return var;
583}
584
585
ager@chromium.org381abbb2009-02-25 13:23:22 +0000586void Scope::ResolveVariable(Scope* global_scope,
587 Handle<Context> context,
588 VariableProxy* proxy) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 ASSERT(global_scope == NULL || global_scope->is_global_scope());
590
591 // If the proxy is already resolved there's nothing to do
592 // (functions and consts may be resolved by the parser).
593 if (proxy->var() != NULL) return;
594
595 // Otherwise, try to resolve the variable.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000596 Variable* invalidated_local = NULL;
597 Variable* var = LookupRecursive(proxy->name(), false, &invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598
599 if (proxy->inside_with()) {
600 // If we are inside a local 'with' statement, all bets are off
601 // and we cannot resolve the proxy to a local variable even if
602 // we found an outer matching variable.
603 // Note that we must do a lookup anyway, because if we find one,
604 // we must mark that variable as potentially accessed from this
605 // inner scope (the property may not be in the 'with' object).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000606 var = NonLocal(proxy->name(), Variable::DYNAMIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607
608 } else {
609 // We are not inside a local 'with' statement.
610
611 if (var == NULL) {
612 // We did not find the variable. We have a global variable
613 // if we are in the global scope (we know already that we
614 // are outside a 'with' statement) or if there is no way
615 // that the variable might be introduced dynamically (through
616 // a local or outer eval() call, or an outer 'with' statement),
617 // or we don't know about the outer scope (because we are
618 // in an eval scope).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000619 if (is_global_scope() ||
620 !(scope_inside_with_ || outer_scope_is_eval_scope_ ||
621 scope_calls_eval_ || outer_scope_calls_eval_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000622 // We must have a global variable.
623 ASSERT(global_scope != NULL);
624 var = new Variable(global_scope, proxy->name(),
ager@chromium.org3e875802009-06-29 08:26:34 +0000625 Variable::DYNAMIC, true, Variable::NORMAL);
ager@chromium.org381abbb2009-02-25 13:23:22 +0000626
627 } else if (scope_inside_with_) {
628 // If we are inside a with statement we give up and look up
629 // the variable at runtime.
630 var = NonLocal(proxy->name(), Variable::DYNAMIC);
631
632 } else if (invalidated_local != NULL) {
633 // No with statements are involved and we found a local
634 // variable that might be shadowed by eval introduced
635 // variables.
636 var = NonLocal(proxy->name(), Variable::DYNAMIC_LOCAL);
637 var->set_local_if_not_shadowed(invalidated_local);
638
639 } else if (outer_scope_is_eval_scope_) {
640 // No with statements and we did not find a local and the code
641 // is executed with a call to eval. The context contains
642 // scope information that we can use to determine if the
643 // variable is global if it is not shadowed by eval-introduced
644 // variables.
645 if (context->GlobalIfNotShadowedByEval(proxy->name())) {
646 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
647
648 } else {
649 var = NonLocal(proxy->name(), Variable::DYNAMIC);
650 }
651
652 } else {
653 // No with statements and we did not find a local and the code
654 // is not executed with a call to eval. We know that this
655 // variable is global unless it is shadowed by eval-introduced
656 // variables.
657 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000658 }
659 }
660 }
661
662 proxy->BindTo(var);
663}
664
665
ager@chromium.org381abbb2009-02-25 13:23:22 +0000666void Scope::ResolveVariablesRecursively(Scope* global_scope,
667 Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000668 ASSERT(global_scope == NULL || global_scope->is_global_scope());
669
670 // Resolve unresolved variables for this scope.
671 for (int i = 0; i < unresolved_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000672 ResolveVariable(global_scope, context, unresolved_[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673 }
674
675 // Resolve unresolved variables for inner scopes.
676 for (int i = 0; i < inner_scopes_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000677 inner_scopes_[i]->ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678 }
679}
680
681
ager@chromium.org381abbb2009-02-25 13:23:22 +0000682bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval,
683 bool outer_scope_is_eval_scope) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000684 if (outer_scope_calls_eval) {
685 outer_scope_calls_eval_ = true;
686 }
687
ager@chromium.org381abbb2009-02-25 13:23:22 +0000688 if (outer_scope_is_eval_scope) {
689 outer_scope_is_eval_scope_ = true;
690 }
691
692 bool calls_eval = scope_calls_eval_ || outer_scope_calls_eval_;
693 bool is_eval = is_eval_scope() || outer_scope_is_eval_scope_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000694 for (int i = 0; i < inner_scopes_.length(); i++) {
695 Scope* inner_scope = inner_scopes_[i];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000696 if (inner_scope->PropagateScopeInfo(calls_eval, is_eval)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697 inner_scope_calls_eval_ = true;
698 }
699 if (inner_scope->force_eager_compilation_) {
700 force_eager_compilation_ = true;
701 }
702 }
703
704 return scope_calls_eval_ || inner_scope_calls_eval_;
705}
706
707
708bool Scope::MustAllocate(Variable* var) {
709 // Give var a read/write use if there is a chance it might be
710 // accessed via an eval() call, or if it is a global variable.
711 // This is only possible if the variable has a visible name.
712 if ((var->is_this() || var->name()->length() > 0) &&
713 (var->is_accessed_from_inner_scope_ ||
714 scope_calls_eval_ || inner_scope_calls_eval_ ||
715 scope_contains_with_ || var->is_global())) {
716 var->var_uses()->RecordAccess(1);
717 }
718 return var->var_uses()->is_used();
719}
720
721
722bool Scope::MustAllocateInContext(Variable* var) {
723 // If var is accessed from an inner scope, or if there is a
724 // possibility that it might be accessed from the current or
725 // an inner scope (through an eval() call), it must be allocated
726 // in the context.
727 // Exceptions: Global variables and temporary variables must
728 // never be allocated in the (FixedArray part of the) context.
729 return
730 var->mode() != Variable::TEMPORARY &&
731 (var->is_accessed_from_inner_scope_ ||
732 scope_calls_eval_ || inner_scope_calls_eval_ ||
733 scope_contains_with_ || var->is_global());
734}
735
736
737bool Scope::HasArgumentsParameter() {
738 for (int i = 0; i < params_.length(); i++) {
739 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
740 return true;
741 }
742 return false;
743}
744
745
746void Scope::AllocateStackSlot(Variable* var) {
747 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
748}
749
750
751void Scope::AllocateHeapSlot(Variable* var) {
752 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
753}
754
755
756void Scope::AllocateParameterLocals() {
757 ASSERT(is_function_scope());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000758 Variable* arguments = LookupLocal(Factory::arguments_symbol());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000759 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
760 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
761 // 'arguments' is used. Unless there is also a parameter called
762 // 'arguments', we must be conservative and access all parameters via
763 // the arguments object: The i'th parameter is rewritten into
764 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
765 // (new) value is always assigned to it via the function
766 // invocation. Then 'arguments' denotes that specific parameter value
767 // and cannot be used to access the parameters, which is why we don't
768 // need to rewrite in that case.
769 //
770 // (*) Instead of having a parameter called 'arguments', we may have an
771 // assignment to 'arguments' in the function body, at some arbitrary
772 // point in time (possibly through an 'eval()' call!). After that
773 // assignment any re-write of parameters would be invalid (was bug
774 // 881452). Thus, we introduce a shadow '.arguments'
775 // variable which also points to the arguments object. For rewrites we
776 // use '.arguments' which remains valid even if we assign to
777 // 'arguments'. To summarize: If we need to rewrite, we allocate an
778 // 'arguments' object dynamically upon function invocation. The compiler
779 // introduces 2 local variables 'arguments' and '.arguments', both of
780 // which originally point to the arguments object that was
781 // allocated. All parameters are rewritten into property accesses via
782 // the '.arguments' variable. Thus, any changes to properties of
783 // 'arguments' are reflected in the variables and vice versa. If the
784 // 'arguments' variable is changed, '.arguments' still points to the
785 // correct arguments object and the rewrites still work.
786
787 // We are using 'arguments'. Tell the code generator that is needs to
788 // allocate the arguments object by setting 'arguments_'.
789 arguments_ = new VariableProxy(Factory::arguments_symbol(), false, false);
790 arguments_->BindTo(arguments);
791
792 // We also need the '.arguments' shadow variable. Declare it and create
793 // and bind the corresponding proxy. It's ok to declare it only now
794 // because it's a local variable that is allocated after the parameters
795 // have been allocated.
796 //
797 // Note: This is "almost" at temporary variable but we cannot use
798 // NewTemporary() because the mode needs to be INTERNAL since this
799 // variable may be allocated in the heap-allocated context (temporaries
800 // are never allocated in the context).
801 Variable* arguments_shadow =
802 new Variable(this, Factory::arguments_shadow_symbol(),
ager@chromium.org3e875802009-06-29 08:26:34 +0000803 Variable::INTERNAL, true, Variable::ARGUMENTS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000804 arguments_shadow_ =
805 new VariableProxy(Factory::arguments_shadow_symbol(), false, false);
806 arguments_shadow_->BindTo(arguments_shadow);
807 temps_.Add(arguments_shadow);
808
809 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
810 for (int i = 0; i < params_.length(); i++) {
811 Variable* var = params_[i];
812 ASSERT(var->scope() == this);
813 if (MustAllocate(var)) {
814 if (MustAllocateInContext(var)) {
815 // It is ok to set this only now, because arguments is a local
816 // variable that is allocated after the parameters have been
817 // allocated.
818 arguments_shadow->is_accessed_from_inner_scope_ = true;
819 }
820 var->rewrite_ =
821 new Property(arguments_shadow_,
822 new Literal(Handle<Object>(Smi::FromInt(i))),
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000823 RelocInfo::kNoPosition,
824 Property::SYNTHETIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000825 arguments_shadow->var_uses()->RecordUses(var->var_uses());
826 }
827 }
828
829 } else {
830 // The arguments object is not used, so we can access parameters directly.
831 // The same parameter may occur multiple times in the parameters_ list.
832 // If it does, and if it is not copied into the context object, it must
833 // receive the highest parameter index for that parameter; thus iteration
834 // order is relevant!
835 for (int i = 0; i < params_.length(); i++) {
836 Variable* var = params_[i];
837 ASSERT(var->scope() == this);
838 if (MustAllocate(var)) {
839 if (MustAllocateInContext(var)) {
840 ASSERT(var->rewrite_ == NULL ||
841 (var->slot() != NULL && var->slot()->type() == Slot::CONTEXT));
842 if (var->rewrite_ == NULL) {
843 // Only set the heap allocation if the parameter has not
844 // been allocated yet.
845 AllocateHeapSlot(var);
846 }
847 } else {
848 ASSERT(var->rewrite_ == NULL ||
849 (var->slot() != NULL &&
850 var->slot()->type() == Slot::PARAMETER));
851 // Set the parameter index always, even if the parameter
852 // was seen before! (We need to access the actual parameter
853 // supplied for the last occurrence of a multiply declared
854 // parameter.)
855 var->rewrite_ = new Slot(var, Slot::PARAMETER, i);
856 }
857 }
858 }
859 }
860}
861
862
863void Scope::AllocateNonParameterLocal(Variable* var) {
864 ASSERT(var->scope() == this);
865 ASSERT(var->rewrite_ == NULL ||
866 (!var->IsVariable(Factory::result_symbol())) ||
867 (var->slot() == NULL || var->slot()->type() != Slot::LOCAL));
868 if (MustAllocate(var) && var->rewrite_ == NULL) {
869 if (MustAllocateInContext(var)) {
870 AllocateHeapSlot(var);
871 } else {
872 AllocateStackSlot(var);
873 }
874 }
875}
876
877
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878void Scope::AllocateNonParameterLocals() {
879 // Each variable occurs exactly once in the locals_ list; all
880 // variables that have no rewrite yet are non-parameter locals.
881
882 // Sort them according to use such that the locals with more uses
883 // get allocated first.
884 if (FLAG_usage_computation) {
885 // This is currently not implemented.
886 }
887
888 for (int i = 0; i < temps_.length(); i++) {
889 AllocateNonParameterLocal(temps_[i]);
890 }
891
892 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
893 Variable* var = reinterpret_cast<Variable*>(p->value);
894 AllocateNonParameterLocal(var);
895 }
896
897 // Note: For now, function_ must be allocated at the very end. If
898 // it gets allocated in the context, it must be the last slot in the
899 // context, because of the current ScopeInfo implementation (see
900 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
901 if (function_ != NULL) {
902 AllocateNonParameterLocal(function_);
903 }
904}
905
906
907void Scope::AllocateVariablesRecursively() {
908 // The number of slots required for variables.
909 num_stack_slots_ = 0;
910 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
911
912 // Allocate variables for inner scopes.
913 for (int i = 0; i < inner_scopes_.length(); i++) {
914 inner_scopes_[i]->AllocateVariablesRecursively();
915 }
916
917 // Allocate variables for this scope.
918 // Parameters must be allocated first, if any.
919 if (is_function_scope()) AllocateParameterLocals();
920 AllocateNonParameterLocals();
921
922 // Allocate context if necessary.
923 bool must_have_local_context = false;
924 if (scope_calls_eval_ || scope_contains_with_) {
925 // The context for the eval() call or 'with' statement in this scope.
926 // Unless we are in the global or an eval scope, we need a local
927 // context even if we didn't statically allocate any locals in it,
928 // and the compiler will access the context variable. If we are
929 // not in an inner scope, the scope is provided from the outside.
930 must_have_local_context = is_function_scope();
931 }
932
933 // If we didn't allocate any locals in the local context, then we only
934 // need the minimal number of slots if we must have a local context.
935 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
936 !must_have_local_context) {
937 num_heap_slots_ = 0;
938 }
939
940 // Allocation done.
941 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
942}
943
944} } // namespace v8::internal