blob: 24622b4b46bcadda8248afd34aea2c20c8eafef3 [file] [log] [blame]
Ben Murdochf87a2032010-10-22 12:50:53 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +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#ifndef V8_SCOPES_H_
29#define V8_SCOPES_H_
30
31#include "ast.h"
32#include "hashmap.h"
33
34namespace v8 {
35namespace internal {
36
Ben Murdochf87a2032010-10-22 12:50:53 +010037class CompilationInfo;
38
Steve Blocka7e24c12009-10-30 11:49:00 +000039
40// A hash map to support fast variable declaration and lookup.
41class VariableMap: public HashMap {
42 public:
43 VariableMap();
44
45 // Dummy constructor. This constructor doesn't set up the map
46 // properly so don't use it unless you have a good reason.
47 explicit VariableMap(bool gotta_love_static_overloading);
48
49 virtual ~VariableMap();
50
51 Variable* Declare(Scope* scope,
52 Handle<String> name,
53 Variable::Mode mode,
54 bool is_valid_lhs,
55 Variable::Kind kind);
56
57 Variable* Lookup(Handle<String> name);
58};
59
60
61// The dynamic scope part holds hash maps for the variables that will
62// be looked up dynamically from within eval and with scopes. The objects
63// are allocated on-demand from Scope::NonLocal to avoid wasting memory
64// and setup time for scopes that don't need them.
65class DynamicScopePart : public ZoneObject {
66 public:
67 VariableMap* GetMap(Variable::Mode mode) {
68 int index = mode - Variable::DYNAMIC;
69 ASSERT(index >= 0 && index < 3);
70 return &maps_[index];
71 }
72
73 private:
74 VariableMap maps_[3];
75};
76
77
78// Global invariants after AST construction: Each reference (i.e. identifier)
79// to a JavaScript variable (including global properties) is represented by a
80// VariableProxy node. Immediately after AST construction and before variable
81// allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
82// corresponding variable (though some are bound during parse time). Variable
83// allocation binds each unresolved VariableProxy to one Variable and assigns
84// a location. Note that many VariableProxy nodes may refer to the same Java-
85// Script variable.
86
87class Scope: public ZoneObject {
88 public:
89 // ---------------------------------------------------------------------------
90 // Construction
91
92 enum Type {
93 EVAL_SCOPE, // the top-level scope for an 'eval' source
94 FUNCTION_SCOPE, // the top-level scope for a function
95 GLOBAL_SCOPE // the top-level scope for a program or a top-level eval
96 };
97
98 Scope(Scope* outer_scope, Type type);
99
100 virtual ~Scope() { }
101
Ben Murdochf87a2032010-10-22 12:50:53 +0100102 // Compute top scope and allocate variables. For lazy compilation the top
103 // scope only contains the single lazily compiled function, so this
104 // doesn't re-allocate variables repeatedly.
105 static bool Analyze(CompilationInfo* info);
106
Steve Block44f0eee2011-05-26 01:26:41 +0100107 static Scope* DeserializeScopeChain(CompilationInfo* info,
108 Scope* innermost_scope);
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110 // The scope name is only used for printing/debugging.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100111 void SetScopeName(Handle<String> scope_name) { scope_name_ = scope_name; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000112
Ben Murdochf87a2032010-10-22 12:50:53 +0100113 virtual void Initialize(bool inside_with);
Steve Blocka7e24c12009-10-30 11:49:00 +0000114
Ben Murdochf87a2032010-10-22 12:50:53 +0100115 // Called just before leaving a scope.
116 virtual void Leave() {
117 // No cleanup or fixup necessary.
118 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000119
120 // ---------------------------------------------------------------------------
121 // Declarations
122
123 // Lookup a variable in this scope. Returns the variable or NULL if not found.
124 virtual Variable* LocalLookup(Handle<String> name);
125
126 // Lookup a variable in this scope or outer scopes.
127 // Returns the variable or NULL if not found.
128 virtual Variable* Lookup(Handle<String> name);
129
130 // Declare the function variable for a function literal. This variable
131 // is in an intermediate scope between this function scope and the the
132 // outer scope. Only possible for function scopes; at most one variable.
133 Variable* DeclareFunctionVar(Handle<String> name);
134
135 // Declare a local variable in this scope. If the variable has been
136 // declared before, the previously declared variable is returned.
137 virtual Variable* DeclareLocal(Handle<String> name, Variable::Mode mode);
138
139 // Declare an implicit global variable in this scope which must be a
140 // global scope. The variable was introduced (possibly from an inner
141 // scope) by a reference to an unresolved variable with no intervening
142 // with statements or eval calls.
143 Variable* DeclareGlobal(Handle<String> name);
144
145 // Add a parameter to the parameter list. The parameter must have been
146 // declared via Declare. The same parameter may occur more than once in
147 // the parameter list; they must be added in source order, from left to
148 // right.
149 void AddParameter(Variable* var);
150
151 // Create a new unresolved variable.
152 virtual VariableProxy* NewUnresolved(Handle<String> name, bool inside_with);
153
154 // Remove a unresolved variable. During parsing, an unresolved variable
155 // may have been added optimistically, but then only the variable name
156 // was used (typically for labels). If the variable was not declared, the
157 // addition introduced a new unresolved variable which may end up being
158 // allocated globally as a "ghost" variable. RemoveUnresolved removes
159 // such a variable again if it was added; otherwise this is a no-op.
160 void RemoveUnresolved(VariableProxy* var);
161
Ben Murdochb0fe1622011-05-05 13:52:32 +0100162 // Creates a new temporary variable in this scope. The name is only used
163 // for printing and cannot be used to find the variable. In particular,
164 // the only way to get hold of the temporary is by keeping the Variable*
165 // around.
166 virtual Variable* NewTemporary(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000167
168 // Adds the specific declaration node to the list of declarations in
169 // this scope. The declarations are processed as part of entering
170 // the scope; see codegen.cc:ProcessDeclarations.
171 void AddDeclaration(Declaration* declaration);
172
173 // ---------------------------------------------------------------------------
174 // Illegal redeclaration support.
175
176 // Set an expression node that will be executed when the scope is
177 // entered. We only keep track of one illegal redeclaration node per
178 // scope - the first one - so if you try to set it multiple times
179 // the additional requests will be silently ignored.
180 void SetIllegalRedeclaration(Expression* expression);
181
182 // Visit the illegal redeclaration expression. Do not call if the
183 // scope doesn't have an illegal redeclaration node.
184 void VisitIllegalRedeclaration(AstVisitor* visitor);
185
186 // Check if the scope has (at least) one illegal redeclaration.
187 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
188
189
190 // ---------------------------------------------------------------------------
191 // Scope-specific info.
192
193 // Inform the scope that the corresponding code contains a with statement.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100194 void RecordWithStatement() { scope_contains_with_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000195
196 // Inform the scope that the corresponding code contains an eval call.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100197 void RecordEvalCall() { scope_calls_eval_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000198
Steve Block44f0eee2011-05-26 01:26:41 +0100199 // Enable strict mode for the scope (unless disabled by a global flag).
200 void EnableStrictMode() {
201 strict_mode_ = FLAG_strict_mode;
202 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000203
204 // ---------------------------------------------------------------------------
205 // Predicates.
206
207 // Specific scope types.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100208 bool is_eval_scope() const { return type_ == EVAL_SCOPE; }
209 bool is_function_scope() const { return type_ == FUNCTION_SCOPE; }
210 bool is_global_scope() const { return type_ == GLOBAL_SCOPE; }
Steve Block44f0eee2011-05-26 01:26:41 +0100211 bool is_strict_mode() const { return strict_mode_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000212
213 // Information about which scopes calls eval.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100214 bool calls_eval() const { return scope_calls_eval_; }
215 bool outer_scope_calls_eval() const { return outer_scope_calls_eval_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000216
217 // Is this scope inside a with statement.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100218 bool inside_with() const { return scope_inside_with_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000219 // Does this scope contain a with statement.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100220 bool contains_with() const { return scope_contains_with_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000221
222 // The scope immediately surrounding this scope, or NULL.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100223 Scope* outer_scope() const { return outer_scope_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000224
225 // ---------------------------------------------------------------------------
226 // Accessors.
227
Leon Clarkee46be812010-01-19 14:06:41 +0000228 // A new variable proxy corresponding to the (function) receiver.
229 VariableProxy* receiver() const {
230 VariableProxy* proxy =
Steve Block44f0eee2011-05-26 01:26:41 +0100231 new VariableProxy(FACTORY->this_symbol(), true, false);
Leon Clarkee46be812010-01-19 14:06:41 +0000232 proxy->BindTo(receiver_);
233 return proxy;
234 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000235
236 // The variable holding the function literal for named function
237 // literals, or NULL.
238 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100239 Variable* function() const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000240 ASSERT(is_function_scope());
241 return function_;
242 }
243
244 // Parameters. The left-most parameter has index 0.
245 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100246 Variable* parameter(int index) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000247 ASSERT(is_function_scope());
248 return params_[index];
249 }
250
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100251 int num_parameters() const { return params_.length(); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000252
253 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
254 // If arguments() exist, arguments_shadow() exists, too.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100255 Variable* arguments() const { return arguments_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000256
257 // The '.arguments' shadow variable if we need to allocate it; NULL otherwise.
258 // If arguments_shadow() exist, arguments() exists, too.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100259 Variable* arguments_shadow() const { return arguments_shadow_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000260
261 // Declarations list.
262 ZoneList<Declaration*>* declarations() { return &decls_; }
263
264
265
266 // ---------------------------------------------------------------------------
267 // Variable allocation.
268
269 // Collect all used locals in this scope.
270 template<class Allocator>
271 void CollectUsedVariables(List<Variable*, Allocator>* locals);
272
273 // Resolve and fill in the allocation information for all variables
274 // in this scopes. Must be called *after* all scopes have been
275 // processed (parsed) to ensure that unresolved variables can be
276 // resolved properly.
277 //
278 // In the case of code compiled and run using 'eval', the context
279 // parameter is the context in which eval was called. In all other
280 // cases the context parameter is an empty handle.
281 void AllocateVariables(Handle<Context> context);
282
283 // Result of variable allocation.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100284 int num_stack_slots() const { return num_stack_slots_; }
285 int num_heap_slots() const { return num_heap_slots_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000286
287 // Make sure this scope and all outer scopes are eagerly compiled.
288 void ForceEagerCompilation() { force_eager_compilation_ = true; }
289
290 // Determine if we can use lazy compilation for this scope.
291 bool AllowsLazyCompilation() const;
292
293 // True if the outer context of this scope is always the global context.
Ben Murdochf87a2032010-10-22 12:50:53 +0100294 virtual bool HasTrivialOuterContext() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000295
296 // The number of contexts between this and scope; zero if this == scope.
297 int ContextChainLength(Scope* scope);
298
Steve Blocka7e24c12009-10-30 11:49:00 +0000299 // ---------------------------------------------------------------------------
Steve Block1e0659c2011-05-24 12:43:12 +0100300 // Strict mode support.
301 bool IsDeclared(Handle<String> name) {
302 // During formal parameter list parsing the scope only contains
303 // two variables inserted at initialization: "this" and "arguments".
304 // "this" is an invalid parameter name and "arguments" is invalid parameter
305 // name in strict mode. Therefore looking up with the map which includes
306 // "this" and "arguments" in addition to all formal parameters is safe.
307 return variables_.Lookup(name) != NULL;
308 }
309
310 // ---------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000311 // Debugging.
312
313#ifdef DEBUG
314 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
315#endif
316
317 // ---------------------------------------------------------------------------
318 // Implementation.
319 protected:
320 friend class ParserFactory;
321
322 explicit Scope(Type type);
323
324 // Scope tree.
325 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
326 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes
327
328 // The scope type.
329 Type type_;
330
331 // Debugging support.
332 Handle<String> scope_name_;
333
334 // The variables declared in this scope:
335 //
336 // All user-declared variables (incl. parameters). For global scopes
337 // variables may be implicitly 'declared' by being used (possibly in
338 // an inner scope) with no intervening with statements or eval calls.
339 VariableMap variables_;
340 // Compiler-allocated (user-invisible) temporaries.
341 ZoneList<Variable*> temps_;
342 // Parameter list in source order.
343 ZoneList<Variable*> params_;
344 // Variables that must be looked up dynamically.
345 DynamicScopePart* dynamics_;
346 // Unresolved variables referred to from this scope.
347 ZoneList<VariableProxy*> unresolved_;
348 // Declarations.
349 ZoneList<Declaration*> decls_;
350 // Convenience variable.
Leon Clarkee46be812010-01-19 14:06:41 +0000351 Variable* receiver_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000352 // Function variable, if any; function scopes only.
353 Variable* function_;
354 // Convenience variable; function scopes only.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100355 Variable* arguments_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000356 // Convenience variable; function scopes only.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100357 Variable* arguments_shadow_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000358
359 // Illegal redeclaration.
360 Expression* illegal_redecl_;
361
362 // Scope-specific information.
363 bool scope_inside_with_; // this scope is inside a 'with' of some outer scope
364 bool scope_contains_with_; // this scope contains a 'with' statement
365 bool scope_calls_eval_; // this scope contains an 'eval' call
Steve Block44f0eee2011-05-26 01:26:41 +0100366 bool strict_mode_; // this scope is a strict mode scope
Steve Blocka7e24c12009-10-30 11:49:00 +0000367
368 // Computed via PropagateScopeInfo.
369 bool outer_scope_calls_eval_;
370 bool inner_scope_calls_eval_;
371 bool outer_scope_is_eval_scope_;
372 bool force_eager_compilation_;
373
374 // Computed via AllocateVariables; function scopes only.
375 int num_stack_slots_;
376 int num_heap_slots_;
377
Ben Murdochb8e0da22011-05-16 14:20:40 +0100378 // Serialized scopes support.
379 SerializedScopeInfo* scope_info_;
380 bool resolved() { return scope_info_ != NULL; }
381
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 // Create a non-local variable with a given name.
383 // These variables are looked up dynamically at runtime.
384 Variable* NonLocal(Handle<String> name, Variable::Mode mode);
385
386 // Variable resolution.
387 Variable* LookupRecursive(Handle<String> name,
388 bool inner_lookup,
389 Variable** invalidated_local);
390 void ResolveVariable(Scope* global_scope,
391 Handle<Context> context,
392 VariableProxy* proxy);
393 void ResolveVariablesRecursively(Scope* global_scope,
394 Handle<Context> context);
395
396 // Scope analysis.
397 bool PropagateScopeInfo(bool outer_scope_calls_eval,
398 bool outer_scope_is_eval_scope);
399 bool HasTrivialContext() const;
400
401 // Predicates.
402 bool MustAllocate(Variable* var);
403 bool MustAllocateInContext(Variable* var);
404 bool HasArgumentsParameter();
405
406 // Variable allocation.
407 void AllocateStackSlot(Variable* var);
408 void AllocateHeapSlot(Variable* var);
409 void AllocateParameterLocals();
410 void AllocateNonParameterLocal(Variable* var);
411 void AllocateNonParameterLocals();
412 void AllocateVariablesRecursively();
Ben Murdochb8e0da22011-05-16 14:20:40 +0100413
414 private:
415 Scope(Scope* inner_scope, SerializedScopeInfo* scope_info);
416
Steve Block44f0eee2011-05-26 01:26:41 +0100417 void AddInnerScope(Scope* inner_scope) {
418 if (inner_scope != NULL) {
419 inner_scopes_.Add(inner_scope);
420 inner_scope->outer_scope_ = this;
421 }
422 }
423
Ben Murdochb8e0da22011-05-16 14:20:40 +0100424 void SetDefaults(Type type,
425 Scope* outer_scope,
426 SerializedScopeInfo* scope_info) {
427 outer_scope_ = outer_scope;
428 type_ = type;
Steve Block44f0eee2011-05-26 01:26:41 +0100429 scope_name_ = FACTORY->empty_symbol();
Ben Murdochb8e0da22011-05-16 14:20:40 +0100430 dynamics_ = NULL;
431 receiver_ = NULL;
432 function_ = NULL;
433 arguments_ = NULL;
434 arguments_shadow_ = NULL;
435 illegal_redecl_ = NULL;
436 scope_inside_with_ = false;
437 scope_contains_with_ = false;
438 scope_calls_eval_ = false;
Steve Block44f0eee2011-05-26 01:26:41 +0100439 // Inherit the strict mode from the parent scope.
440 strict_mode_ = (outer_scope != NULL) && outer_scope->strict_mode_;
Ben Murdochb8e0da22011-05-16 14:20:40 +0100441 outer_scope_calls_eval_ = false;
442 inner_scope_calls_eval_ = false;
443 outer_scope_is_eval_scope_ = false;
444 force_eager_compilation_ = false;
445 num_stack_slots_ = 0;
446 num_heap_slots_ = 0;
447 scope_info_ = scope_info;
448 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000449};
450
451
Ben Murdochf87a2032010-10-22 12:50:53 +0100452// Scope used during pre-parsing.
Steve Blocka7e24c12009-10-30 11:49:00 +0000453class DummyScope : public Scope {
454 public:
Ben Murdochf87a2032010-10-22 12:50:53 +0100455 DummyScope()
456 : Scope(GLOBAL_SCOPE),
457 nesting_level_(1), // Allows us to Leave the initial scope.
458 inside_with_level_(kNotInsideWith) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000459 outer_scope_ = this;
Ben Murdochf87a2032010-10-22 12:50:53 +0100460 scope_inside_with_ = false;
461 }
462
463 virtual void Initialize(bool inside_with) {
464 nesting_level_++;
465 if (inside_with && inside_with_level_ == kNotInsideWith) {
466 inside_with_level_ = nesting_level_;
467 }
468 ASSERT(inside_with_level_ <= nesting_level_);
469 }
470
471 virtual void Leave() {
472 nesting_level_--;
473 ASSERT(nesting_level_ >= 0);
474 if (nesting_level_ < inside_with_level_) {
475 inside_with_level_ = kNotInsideWith;
476 }
477 ASSERT(inside_with_level_ <= nesting_level_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000478 }
479
480 virtual Variable* Lookup(Handle<String> name) { return NULL; }
Ben Murdochf87a2032010-10-22 12:50:53 +0100481
Steve Blocka7e24c12009-10-30 11:49:00 +0000482 virtual VariableProxy* NewUnresolved(Handle<String> name, bool inside_with) {
483 return NULL;
484 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100485
Ben Murdochb0fe1622011-05-05 13:52:32 +0100486 virtual Variable* NewTemporary(Handle<String> name) { return NULL; }
Ben Murdochf87a2032010-10-22 12:50:53 +0100487
488 virtual bool HasTrivialOuterContext() const {
489 return (nesting_level_ == 0 || inside_with_level_ <= 0);
490 }
491
492 private:
493 static const int kNotInsideWith = -1;
494 // Number of surrounding scopes of the current scope.
495 int nesting_level_;
496 // Nesting level of outermost scope that is contained in a with statement,
497 // or kNotInsideWith if there are no with's around the current scope.
498 int inside_with_level_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000499};
500
501
502} } // namespace v8::internal
503
504#endif // V8_SCOPES_H_