blob: 78ed0351800bde7746efc9d73a74afbf850ffc50 [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
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000074VariableMap::VariableMap(bool gotta_love_static_overloading) : HashMap() {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000075
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000076VariableMap::VariableMap() : HashMap(Match, &LocalsMapAllocator, 8) {}
77VariableMap::~VariableMap() {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078
79
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000080Variable* VariableMap::Declare(Scope* scope,
81 Handle<String> name,
82 Variable::Mode mode,
83 bool is_valid_lhs,
84 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());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +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
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000095Variable* VariableMap::Lookup(Handle<String> name) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000096 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),
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000113 variables_(false),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000114 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
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000171 Variable* var =
172 variables_.Declare(this, Factory::this_symbol(), Variable::VAR,
173 false, Variable::THIS);
174 var->rewrite_ = new Slot(var, Slot::PARAMETER, -1);
175 receiver_ = new VariableProxy(Factory::this_symbol(), true, false);
176 receiver_->BindTo(var);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000177
178 if (is_function_scope()) {
179 // Declare 'arguments' variable which exists in all functions.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000180 // Note that it might never be accessed, in which case it won't be
181 // allocated during variable allocation.
182 variables_.Declare(this, Factory::arguments_symbol(), Variable::VAR,
183 true, Variable::ARGUMENTS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000184 }
185}
186
187
188
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000189Variable* Scope::LocalLookup(Handle<String> name) {
190 return variables_.Lookup(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191}
192
193
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000194Variable* Scope::Lookup(Handle<String> name) {
195 for (Scope* scope = this;
196 scope != NULL;
197 scope = scope->outer_scope()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000198 Variable* var = scope->LocalLookup(name);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000199 if (var != NULL) return var;
200 }
201 return NULL;
202}
203
204
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000205Variable* Scope::DeclareFunctionVar(Handle<String> name) {
206 ASSERT(is_function_scope() && function_ == NULL);
ager@chromium.org3e875802009-06-29 08:26:34 +0000207 function_ = new Variable(this, name, Variable::CONST, true, Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000208 return function_;
209}
210
211
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000212Variable* Scope::DeclareLocal(Handle<String> name, Variable::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000213 // DYNAMIC variables are introduces during variable allocation,
214 // INTERNAL variables are allocated explicitly, and TEMPORARY
215 // variables are allocated via NewTemporary().
216 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000217 return variables_.Declare(this, name, mode, true, Variable::NORMAL);
218}
219
220
221Variable* Scope::DeclareGlobal(Handle<String> name) {
222 ASSERT(is_global_scope());
223 return variables_.Declare(this, name, Variable::DYNAMIC, true,
224 Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000225}
226
227
228void Scope::AddParameter(Variable* var) {
229 ASSERT(is_function_scope());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000230 ASSERT(LocalLookup(var->name()) == var);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000231 params_.Add(var);
232}
233
234
235VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
236 // Note that we must not share the unresolved variables with
237 // the same name because they may be removed selectively via
238 // RemoveUnresolved().
239 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
240 unresolved_.Add(proxy);
241 return proxy;
242}
243
244
245void Scope::RemoveUnresolved(VariableProxy* var) {
246 // Most likely (always?) any variable we want to remove
247 // was just added before, so we search backwards.
248 for (int i = unresolved_.length(); i-- > 0;) {
249 if (unresolved_[i] == var) {
250 unresolved_.Remove(i);
251 return;
252 }
253 }
254}
255
256
257VariableProxy* Scope::NewTemporary(Handle<String> name) {
ager@chromium.org3e875802009-06-29 08:26:34 +0000258 Variable* var = new Variable(this, name, Variable::TEMPORARY, true,
259 Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000260 VariableProxy* tmp = new VariableProxy(name, false, false);
261 tmp->BindTo(var);
262 temps_.Add(var);
263 return tmp;
264}
265
266
267void Scope::AddDeclaration(Declaration* declaration) {
268 decls_.Add(declaration);
269}
270
271
272void Scope::SetIllegalRedeclaration(Expression* expression) {
273 // Only set the illegal redeclaration expression the
274 // first time the function is called.
275 if (!HasIllegalRedeclaration()) {
276 illegal_redecl_ = expression;
277 }
278 ASSERT(HasIllegalRedeclaration());
279}
280
281
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000282void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000283 ASSERT(HasIllegalRedeclaration());
284 illegal_redecl_->Accept(visitor);
285}
286
287
288template<class Allocator>
289void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
290 // Collect variables in this scope.
291 // Note that the function_ variable - if present - is not
292 // collected here but handled separately in ScopeInfo
293 // which is the current user of this function).
294 for (int i = 0; i < temps_.length(); i++) {
295 Variable* var = temps_[i];
296 if (var->var_uses()->is_used()) {
297 locals->Add(var);
298 }
299 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000300 for (VariableMap::Entry* p = variables_.Start();
301 p != NULL;
302 p = variables_.Next(p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000303 Variable* var = reinterpret_cast<Variable*>(p->value);
304 if (var->var_uses()->is_used()) {
305 locals->Add(var);
306 }
307 }
308}
309
310
311// Make sure the method gets instantiated by the template system.
312template void Scope::CollectUsedVariables(
313 List<Variable*, FreeStoreAllocationPolicy>* locals);
314template void Scope::CollectUsedVariables(
315 List<Variable*, PreallocatedStorage>* locals);
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000316template void Scope::CollectUsedVariables(
317 List<Variable*, ZoneListAllocationPolicy>* locals);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318
319
ager@chromium.org381abbb2009-02-25 13:23:22 +0000320void Scope::AllocateVariables(Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000321 ASSERT(outer_scope_ == NULL); // eval or global scopes only
322
323 // 1) Propagate scope information.
324 // If we are in an eval scope, we may have other outer scopes about
325 // which we don't know anything at this point. Thus we must be conservative
326 // and assume they may invoke eval themselves. Eventually we could capture
327 // this information in the ScopeInfo and then use it here (by traversing
328 // the call chain stack, at compile time).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000329 bool eval_scope = is_eval_scope();
330 PropagateScopeInfo(eval_scope, eval_scope);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000331
332 // 2) Resolve variables.
333 Scope* global_scope = NULL;
334 if (is_global_scope()) global_scope = this;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000335 ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336
337 // 3) Allocate variables.
338 AllocateVariablesRecursively();
339}
340
341
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342bool Scope::AllowsLazyCompilation() const {
343 return !force_eager_compilation_ && HasTrivialOuterContext();
344}
345
346
347bool Scope::HasTrivialContext() const {
348 // A function scope has a trivial context if it always is the global
349 // context. We iteratively scan out the context chain to see if
350 // there is anything that makes this scope non-trivial; otherwise we
351 // return true.
352 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
353 if (scope->is_eval_scope()) return false;
354 if (scope->scope_inside_with_) return false;
355 if (scope->num_heap_slots_ > 0) return false;
356 }
357 return true;
358}
359
360
361bool Scope::HasTrivialOuterContext() const {
362 Scope* outer = outer_scope_;
363 if (outer == NULL) return true;
364 // Note that the outer context may be trivial in general, but the current
365 // scope may be inside a 'with' statement in which case the outer context
366 // for this scope is not trivial.
367 return !scope_inside_with_ && outer->HasTrivialContext();
368}
369
370
371int Scope::ContextChainLength(Scope* scope) {
372 int n = 0;
373 for (Scope* s = this; s != scope; s = s->outer_scope_) {
374 ASSERT(s != NULL); // scope must be in the scope chain
375 if (s->num_heap_slots() > 0) n++;
376 }
377 return n;
378}
379
380
381#ifdef DEBUG
382static const char* Header(Scope::Type type) {
383 switch (type) {
384 case Scope::EVAL_SCOPE: return "eval";
385 case Scope::FUNCTION_SCOPE: return "function";
386 case Scope::GLOBAL_SCOPE: return "global";
387 }
388 UNREACHABLE();
389 return NULL;
390}
391
392
393static void Indent(int n, const char* str) {
394 PrintF("%*s%s", n, "", str);
395}
396
397
398static void PrintName(Handle<String> name) {
399 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
400 PrintF("%s", *s);
401}
402
403
404static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
405 if (var->var_uses()->is_used() || var->rewrite() != NULL) {
406 Indent(indent, Variable::Mode2String(var->mode()));
407 PrintF(" ");
408 PrintName(var->name());
409 PrintF("; // ");
410 if (var->rewrite() != NULL) PrintF("%s, ", printer->Print(var->rewrite()));
411 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access, ");
412 PrintF("var ");
413 var->var_uses()->Print();
414 PrintF(", obj ");
415 var->obj_uses()->Print();
416 PrintF("\n");
417 }
418}
419
420
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000421static void PrintMap(PrettyPrinter* printer, int indent, VariableMap* map) {
422 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000423 Variable* var = reinterpret_cast<Variable*>(p->value);
424 PrintVar(printer, indent, var);
425 }
426}
427
428
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000429void Scope::Print(int n) {
430 int n0 = (n > 0 ? n : 0);
431 int n1 = n0 + 2; // indentation
432
433 // Print header.
434 Indent(n0, Header(type_));
435 if (scope_name_->length() > 0) {
436 PrintF(" ");
437 PrintName(scope_name_);
438 }
439
440 // Print parameters, if any.
441 if (is_function_scope()) {
442 PrintF(" (");
443 for (int i = 0; i < params_.length(); i++) {
444 if (i > 0) PrintF(", ");
445 PrintName(params_[i]->name());
446 }
447 PrintF(")");
448 }
449
450 PrintF(" {\n");
451
452 // Function name, if any (named function literals, only).
453 if (function_ != NULL) {
454 Indent(n1, "// (local) function name: ");
455 PrintName(function_->name());
456 PrintF("\n");
457 }
458
459 // Scope info.
460 if (HasTrivialOuterContext()) {
461 Indent(n1, "// scope has trivial outer context\n");
462 }
463 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
464 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
465 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
466 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
467 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
ager@chromium.org381abbb2009-02-25 13:23:22 +0000468 if (outer_scope_is_eval_scope_) {
469 Indent(n1, "// outer scope is 'eval' scope\n");
470 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471 if (num_stack_slots_ > 0) { Indent(n1, "// ");
472 PrintF("%d stack slots\n", num_stack_slots_); }
473 if (num_heap_slots_ > 0) { Indent(n1, "// ");
474 PrintF("%d heap slots\n", num_heap_slots_); }
475
476 // Print locals.
477 PrettyPrinter printer;
478 Indent(n1, "// function var\n");
479 if (function_ != NULL) {
480 PrintVar(&printer, n1, function_);
481 }
482
483 Indent(n1, "// temporary vars\n");
484 for (int i = 0; i < temps_.length(); i++) {
485 PrintVar(&printer, n1, temps_[i]);
486 }
487
488 Indent(n1, "// local vars\n");
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000489 PrintMap(&printer, n1, &variables_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000490
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000491 Indent(n1, "// dynamic vars\n");
492 if (dynamics_ != NULL) {
493 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC));
494 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_LOCAL));
495 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_GLOBAL));
496 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000497
498 // Print inner scopes (disable by providing negative n).
499 if (n >= 0) {
500 for (int i = 0; i < inner_scopes_.length(); i++) {
501 PrintF("\n");
502 inner_scopes_[i]->Print(n1);
503 }
504 }
505
506 Indent(n0, "}\n");
507}
508#endif // DEBUG
509
510
ager@chromium.org381abbb2009-02-25 13:23:22 +0000511Variable* Scope::NonLocal(Handle<String> name, Variable::Mode mode) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000512 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000513 VariableMap* map = dynamics_->GetMap(mode);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000514 Variable* var = map->Lookup(name);
515 if (var == NULL) {
516 // Declare a new non-local.
ager@chromium.org3e875802009-06-29 08:26:34 +0000517 var = map->Declare(NULL, name, mode, true, Variable::NORMAL);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000518 // Allocate it by giving it a dynamic lookup.
519 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000521 return var;
522}
523
524
525// Lookup a variable starting with this scope. The result is either
526// the statically resolved (local!) variable belonging to an outer scope,
527// or NULL. It may be NULL because a) we couldn't find a variable, or b)
528// because the variable is just a guess (and may be shadowed by another
529// variable that is introduced dynamically via an 'eval' call or a 'with'
530// statement).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000531Variable* Scope::LookupRecursive(Handle<String> name,
532 bool inner_lookup,
533 Variable** invalidated_local) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000534 // If we find a variable, but the current scope calls 'eval', the found
535 // variable may not be the correct one (the 'eval' may introduce a
536 // property with the same name). In that case, remember that the variable
537 // found is just a guess.
538 bool guess = scope_calls_eval_;
539
540 // Try to find the variable in this scope.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000541 Variable* var = LocalLookup(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000542
543 if (var != NULL) {
544 // We found a variable. If this is not an inner lookup, we are done.
545 // (Even if there is an 'eval' in this scope which introduces the
546 // same variable again, the resulting variable remains the same.
547 // Note that enclosing 'with' statements are handled at the call site.)
548 if (!inner_lookup)
549 return var;
550
551 } else {
552 // We did not find a variable locally. Check against the function variable,
553 // if any. We can do this for all scopes, since the function variable is
554 // only present - if at all - for function scopes.
555 //
556 // This lookup corresponds to a lookup in the "intermediate" scope sitting
557 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
558 // the name of named function literal is kept in an intermediate scope
ager@chromium.org32912102009-01-16 10:38:43 +0000559 // in between this scope and the next outer scope.)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000560 if (function_ != NULL && function_->name().is_identical_to(name)) {
561 var = function_;
562
563 } else if (outer_scope_ != NULL) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000564 var = outer_scope_->LookupRecursive(name, true, invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000565 // We may have found a variable in an outer scope. However, if
566 // the current scope is inside a 'with', the actual variable may
567 // be a property introduced via the 'with' statement. Then, the
568 // variable we may have found is just a guess.
569 if (scope_inside_with_)
570 guess = true;
571 }
572
573 // If we did not find a variable, we are done.
574 if (var == NULL)
575 return NULL;
576 }
577
578 ASSERT(var != NULL);
579
580 // If this is a lookup from an inner scope, mark the variable.
581 if (inner_lookup)
582 var->is_accessed_from_inner_scope_ = true;
583
584 // If the variable we have found is just a guess, invalidate the result.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000585 if (guess) {
586 *invalidated_local = var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000587 var = NULL;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000588 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589
590 return var;
591}
592
593
ager@chromium.org381abbb2009-02-25 13:23:22 +0000594void Scope::ResolveVariable(Scope* global_scope,
595 Handle<Context> context,
596 VariableProxy* proxy) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597 ASSERT(global_scope == NULL || global_scope->is_global_scope());
598
599 // If the proxy is already resolved there's nothing to do
600 // (functions and consts may be resolved by the parser).
601 if (proxy->var() != NULL) return;
602
603 // Otherwise, try to resolve the variable.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000604 Variable* invalidated_local = NULL;
605 Variable* var = LookupRecursive(proxy->name(), false, &invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606
607 if (proxy->inside_with()) {
608 // If we are inside a local 'with' statement, all bets are off
609 // and we cannot resolve the proxy to a local variable even if
610 // we found an outer matching variable.
611 // Note that we must do a lookup anyway, because if we find one,
612 // we must mark that variable as potentially accessed from this
613 // inner scope (the property may not be in the 'with' object).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000614 var = NonLocal(proxy->name(), Variable::DYNAMIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000615
616 } else {
617 // We are not inside a local 'with' statement.
618
619 if (var == NULL) {
620 // We did not find the variable. We have a global variable
621 // if we are in the global scope (we know already that we
622 // are outside a 'with' statement) or if there is no way
623 // that the variable might be introduced dynamically (through
624 // a local or outer eval() call, or an outer 'with' statement),
625 // or we don't know about the outer scope (because we are
626 // in an eval scope).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000627 if (is_global_scope() ||
628 !(scope_inside_with_ || outer_scope_is_eval_scope_ ||
629 scope_calls_eval_ || outer_scope_calls_eval_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000630 // We must have a global variable.
631 ASSERT(global_scope != NULL);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000632 var = global_scope->DeclareGlobal(proxy->name());
ager@chromium.org381abbb2009-02-25 13:23:22 +0000633
634 } else if (scope_inside_with_) {
635 // If we are inside a with statement we give up and look up
636 // the variable at runtime.
637 var = NonLocal(proxy->name(), Variable::DYNAMIC);
638
639 } else if (invalidated_local != NULL) {
640 // No with statements are involved and we found a local
641 // variable that might be shadowed by eval introduced
642 // variables.
643 var = NonLocal(proxy->name(), Variable::DYNAMIC_LOCAL);
644 var->set_local_if_not_shadowed(invalidated_local);
645
646 } else if (outer_scope_is_eval_scope_) {
647 // No with statements and we did not find a local and the code
648 // is executed with a call to eval. The context contains
649 // scope information that we can use to determine if the
650 // variable is global if it is not shadowed by eval-introduced
651 // variables.
652 if (context->GlobalIfNotShadowedByEval(proxy->name())) {
653 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
654
655 } else {
656 var = NonLocal(proxy->name(), Variable::DYNAMIC);
657 }
658
659 } else {
660 // No with statements and we did not find a local and the code
661 // is not executed with a call to eval. We know that this
662 // variable is global unless it is shadowed by eval-introduced
663 // variables.
664 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000665 }
666 }
667 }
668
669 proxy->BindTo(var);
670}
671
672
ager@chromium.org381abbb2009-02-25 13:23:22 +0000673void Scope::ResolveVariablesRecursively(Scope* global_scope,
674 Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000675 ASSERT(global_scope == NULL || global_scope->is_global_scope());
676
677 // Resolve unresolved variables for this scope.
678 for (int i = 0; i < unresolved_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000679 ResolveVariable(global_scope, context, unresolved_[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680 }
681
682 // Resolve unresolved variables for inner scopes.
683 for (int i = 0; i < inner_scopes_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000684 inner_scopes_[i]->ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000685 }
686}
687
688
ager@chromium.org381abbb2009-02-25 13:23:22 +0000689bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval,
690 bool outer_scope_is_eval_scope) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000691 if (outer_scope_calls_eval) {
692 outer_scope_calls_eval_ = true;
693 }
694
ager@chromium.org381abbb2009-02-25 13:23:22 +0000695 if (outer_scope_is_eval_scope) {
696 outer_scope_is_eval_scope_ = true;
697 }
698
699 bool calls_eval = scope_calls_eval_ || outer_scope_calls_eval_;
700 bool is_eval = is_eval_scope() || outer_scope_is_eval_scope_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000701 for (int i = 0; i < inner_scopes_.length(); i++) {
702 Scope* inner_scope = inner_scopes_[i];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000703 if (inner_scope->PropagateScopeInfo(calls_eval, is_eval)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000704 inner_scope_calls_eval_ = true;
705 }
706 if (inner_scope->force_eager_compilation_) {
707 force_eager_compilation_ = true;
708 }
709 }
710
711 return scope_calls_eval_ || inner_scope_calls_eval_;
712}
713
714
715bool Scope::MustAllocate(Variable* var) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000716 // Give var a read/write use if there is a chance it might be accessed
717 // via an eval() call. This is only possible if the variable has a
718 // visible name.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000719 if ((var->is_this() || var->name()->length() > 0) &&
720 (var->is_accessed_from_inner_scope_ ||
721 scope_calls_eval_ || inner_scope_calls_eval_ ||
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000722 scope_contains_with_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000723 var->var_uses()->RecordAccess(1);
724 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000725 // Global variables do not need to be allocated.
726 return !var->is_global() && var->var_uses()->is_used();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000727}
728
729
730bool Scope::MustAllocateInContext(Variable* var) {
731 // If var is accessed from an inner scope, or if there is a
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000732 // possibility that it might be accessed from the current or an inner
733 // scope (through an eval() call), it must be allocated in the
734 // context. Exception: temporary variables are not allocated in the
735 // context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000736 return
737 var->mode() != Variable::TEMPORARY &&
738 (var->is_accessed_from_inner_scope_ ||
739 scope_calls_eval_ || inner_scope_calls_eval_ ||
740 scope_contains_with_ || var->is_global());
741}
742
743
744bool Scope::HasArgumentsParameter() {
745 for (int i = 0; i < params_.length(); i++) {
746 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
747 return true;
748 }
749 return false;
750}
751
752
753void Scope::AllocateStackSlot(Variable* var) {
754 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
755}
756
757
758void Scope::AllocateHeapSlot(Variable* var) {
759 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
760}
761
762
763void Scope::AllocateParameterLocals() {
764 ASSERT(is_function_scope());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000765 Variable* arguments = LocalLookup(Factory::arguments_symbol());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
767 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
768 // 'arguments' is used. Unless there is also a parameter called
769 // 'arguments', we must be conservative and access all parameters via
770 // the arguments object: The i'th parameter is rewritten into
771 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
772 // (new) value is always assigned to it via the function
773 // invocation. Then 'arguments' denotes that specific parameter value
774 // and cannot be used to access the parameters, which is why we don't
775 // need to rewrite in that case.
776 //
777 // (*) Instead of having a parameter called 'arguments', we may have an
778 // assignment to 'arguments' in the function body, at some arbitrary
779 // point in time (possibly through an 'eval()' call!). After that
780 // assignment any re-write of parameters would be invalid (was bug
781 // 881452). Thus, we introduce a shadow '.arguments'
782 // variable which also points to the arguments object. For rewrites we
783 // use '.arguments' which remains valid even if we assign to
784 // 'arguments'. To summarize: If we need to rewrite, we allocate an
785 // 'arguments' object dynamically upon function invocation. The compiler
786 // introduces 2 local variables 'arguments' and '.arguments', both of
787 // which originally point to the arguments object that was
788 // allocated. All parameters are rewritten into property accesses via
789 // the '.arguments' variable. Thus, any changes to properties of
790 // 'arguments' are reflected in the variables and vice versa. If the
791 // 'arguments' variable is changed, '.arguments' still points to the
792 // correct arguments object and the rewrites still work.
793
794 // We are using 'arguments'. Tell the code generator that is needs to
795 // allocate the arguments object by setting 'arguments_'.
796 arguments_ = new VariableProxy(Factory::arguments_symbol(), false, false);
797 arguments_->BindTo(arguments);
798
799 // We also need the '.arguments' shadow variable. Declare it and create
800 // and bind the corresponding proxy. It's ok to declare it only now
801 // because it's a local variable that is allocated after the parameters
802 // have been allocated.
803 //
804 // Note: This is "almost" at temporary variable but we cannot use
805 // NewTemporary() because the mode needs to be INTERNAL since this
806 // variable may be allocated in the heap-allocated context (temporaries
807 // are never allocated in the context).
808 Variable* arguments_shadow =
809 new Variable(this, Factory::arguments_shadow_symbol(),
ager@chromium.org3e875802009-06-29 08:26:34 +0000810 Variable::INTERNAL, true, Variable::ARGUMENTS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000811 arguments_shadow_ =
812 new VariableProxy(Factory::arguments_shadow_symbol(), false, false);
813 arguments_shadow_->BindTo(arguments_shadow);
814 temps_.Add(arguments_shadow);
815
816 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
817 for (int i = 0; i < params_.length(); i++) {
818 Variable* var = params_[i];
819 ASSERT(var->scope() == this);
820 if (MustAllocate(var)) {
821 if (MustAllocateInContext(var)) {
822 // It is ok to set this only now, because arguments is a local
823 // variable that is allocated after the parameters have been
824 // allocated.
825 arguments_shadow->is_accessed_from_inner_scope_ = true;
826 }
827 var->rewrite_ =
828 new Property(arguments_shadow_,
829 new Literal(Handle<Object>(Smi::FromInt(i))),
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000830 RelocInfo::kNoPosition,
831 Property::SYNTHETIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000832 arguments_shadow->var_uses()->RecordUses(var->var_uses());
833 }
834 }
835
836 } else {
837 // The arguments object is not used, so we can access parameters directly.
838 // The same parameter may occur multiple times in the parameters_ list.
839 // If it does, and if it is not copied into the context object, it must
840 // receive the highest parameter index for that parameter; thus iteration
841 // order is relevant!
842 for (int i = 0; i < params_.length(); i++) {
843 Variable* var = params_[i];
844 ASSERT(var->scope() == this);
845 if (MustAllocate(var)) {
846 if (MustAllocateInContext(var)) {
847 ASSERT(var->rewrite_ == NULL ||
848 (var->slot() != NULL && var->slot()->type() == Slot::CONTEXT));
849 if (var->rewrite_ == NULL) {
850 // Only set the heap allocation if the parameter has not
851 // been allocated yet.
852 AllocateHeapSlot(var);
853 }
854 } else {
855 ASSERT(var->rewrite_ == NULL ||
856 (var->slot() != NULL &&
857 var->slot()->type() == Slot::PARAMETER));
858 // Set the parameter index always, even if the parameter
859 // was seen before! (We need to access the actual parameter
860 // supplied for the last occurrence of a multiply declared
861 // parameter.)
862 var->rewrite_ = new Slot(var, Slot::PARAMETER, i);
863 }
864 }
865 }
866 }
867}
868
869
870void Scope::AllocateNonParameterLocal(Variable* var) {
871 ASSERT(var->scope() == this);
872 ASSERT(var->rewrite_ == NULL ||
873 (!var->IsVariable(Factory::result_symbol())) ||
874 (var->slot() == NULL || var->slot()->type() != Slot::LOCAL));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000875 if (var->rewrite_ == NULL && MustAllocate(var)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000876 if (MustAllocateInContext(var)) {
877 AllocateHeapSlot(var);
878 } else {
879 AllocateStackSlot(var);
880 }
881 }
882}
883
884
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000885void Scope::AllocateNonParameterLocals() {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000886 // All variables that have no rewrite yet are non-parameter locals.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000887 for (int i = 0; i < temps_.length(); i++) {
888 AllocateNonParameterLocal(temps_[i]);
889 }
890
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000891 for (VariableMap::Entry* p = variables_.Start();
892 p != NULL;
893 p = variables_.Next(p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000894 Variable* var = reinterpret_cast<Variable*>(p->value);
895 AllocateNonParameterLocal(var);
896 }
897
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000898 // For now, function_ must be allocated at the very end. If it gets
899 // allocated in the context, it must be the last slot in the context,
900 // because of the current ScopeInfo implementation (see
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000901 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
902 if (function_ != NULL) {
903 AllocateNonParameterLocal(function_);
904 }
905}
906
907
908void Scope::AllocateVariablesRecursively() {
909 // The number of slots required for variables.
910 num_stack_slots_ = 0;
911 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
912
913 // Allocate variables for inner scopes.
914 for (int i = 0; i < inner_scopes_.length(); i++) {
915 inner_scopes_[i]->AllocateVariablesRecursively();
916 }
917
918 // Allocate variables for this scope.
919 // Parameters must be allocated first, if any.
920 if (is_function_scope()) AllocateParameterLocals();
921 AllocateNonParameterLocals();
922
923 // Allocate context if necessary.
924 bool must_have_local_context = false;
925 if (scope_calls_eval_ || scope_contains_with_) {
926 // The context for the eval() call or 'with' statement in this scope.
927 // Unless we are in the global or an eval scope, we need a local
928 // context even if we didn't statically allocate any locals in it,
929 // and the compiler will access the context variable. If we are
930 // not in an inner scope, the scope is provided from the outside.
931 must_have_local_context = is_function_scope();
932 }
933
934 // If we didn't allocate any locals in the local context, then we only
935 // need the minimal number of slots if we must have a local context.
936 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
937 !must_have_local_context) {
938 num_heap_slots_ = 0;
939 }
940
941 // Allocation done.
942 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
943}
944
945} } // namespace v8::internal