blob: 18db0cdd26ba1a950b282e8f6e4f669c37e393ab [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.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100152 virtual VariableProxy* NewUnresolved(Handle<String> name,
153 bool inside_with,
154 int position = RelocInfo::kNoPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +0000155
156 // Remove a unresolved variable. During parsing, an unresolved variable
157 // may have been added optimistically, but then only the variable name
158 // was used (typically for labels). If the variable was not declared, the
159 // addition introduced a new unresolved variable which may end up being
160 // allocated globally as a "ghost" variable. RemoveUnresolved removes
161 // such a variable again if it was added; otherwise this is a no-op.
162 void RemoveUnresolved(VariableProxy* var);
163
Ben Murdochb0fe1622011-05-05 13:52:32 +0100164 // Creates a new temporary variable in this scope. The name is only used
165 // for printing and cannot be used to find the variable. In particular,
166 // the only way to get hold of the temporary is by keeping the Variable*
167 // around.
168 virtual Variable* NewTemporary(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000169
170 // Adds the specific declaration node to the list of declarations in
171 // this scope. The declarations are processed as part of entering
172 // the scope; see codegen.cc:ProcessDeclarations.
173 void AddDeclaration(Declaration* declaration);
174
175 // ---------------------------------------------------------------------------
176 // Illegal redeclaration support.
177
178 // Set an expression node that will be executed when the scope is
179 // entered. We only keep track of one illegal redeclaration node per
180 // scope - the first one - so if you try to set it multiple times
181 // the additional requests will be silently ignored.
182 void SetIllegalRedeclaration(Expression* expression);
183
184 // Visit the illegal redeclaration expression. Do not call if the
185 // scope doesn't have an illegal redeclaration node.
186 void VisitIllegalRedeclaration(AstVisitor* visitor);
187
188 // Check if the scope has (at least) one illegal redeclaration.
189 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
190
191
192 // ---------------------------------------------------------------------------
193 // Scope-specific info.
194
195 // Inform the scope that the corresponding code contains a with statement.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100196 void RecordWithStatement() { scope_contains_with_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000197
198 // Inform the scope that the corresponding code contains an eval call.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100199 void RecordEvalCall() { scope_calls_eval_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000200
Steve Block44f0eee2011-05-26 01:26:41 +0100201 // Enable strict mode for the scope (unless disabled by a global flag).
202 void EnableStrictMode() {
203 strict_mode_ = FLAG_strict_mode;
204 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000205
206 // ---------------------------------------------------------------------------
207 // Predicates.
208
209 // Specific scope types.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100210 bool is_eval_scope() const { return type_ == EVAL_SCOPE; }
211 bool is_function_scope() const { return type_ == FUNCTION_SCOPE; }
212 bool is_global_scope() const { return type_ == GLOBAL_SCOPE; }
Steve Block44f0eee2011-05-26 01:26:41 +0100213 bool is_strict_mode() const { return strict_mode_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000214
215 // Information about which scopes calls eval.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100216 bool calls_eval() const { return scope_calls_eval_; }
217 bool outer_scope_calls_eval() const { return outer_scope_calls_eval_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000218
219 // Is this scope inside a with statement.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100220 bool inside_with() const { return scope_inside_with_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000221 // Does this scope contain a with statement.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100222 bool contains_with() const { return scope_contains_with_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000223
224 // The scope immediately surrounding this scope, or NULL.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100225 Scope* outer_scope() const { return outer_scope_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000226
227 // ---------------------------------------------------------------------------
228 // Accessors.
229
Leon Clarkee46be812010-01-19 14:06:41 +0000230 // A new variable proxy corresponding to the (function) receiver.
231 VariableProxy* receiver() const {
232 VariableProxy* proxy =
Steve Block44f0eee2011-05-26 01:26:41 +0100233 new VariableProxy(FACTORY->this_symbol(), true, false);
Leon Clarkee46be812010-01-19 14:06:41 +0000234 proxy->BindTo(receiver_);
235 return proxy;
236 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000237
238 // The variable holding the function literal for named function
239 // literals, or NULL.
240 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100241 Variable* function() const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000242 ASSERT(is_function_scope());
243 return function_;
244 }
245
246 // Parameters. The left-most parameter has index 0.
247 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100248 Variable* parameter(int index) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000249 ASSERT(is_function_scope());
250 return params_[index];
251 }
252
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100253 int num_parameters() const { return params_.length(); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000254
255 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
256 // If arguments() exist, arguments_shadow() exists, too.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100257 Variable* arguments() const { return arguments_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000258
259 // The '.arguments' shadow variable if we need to allocate it; NULL otherwise.
260 // If arguments_shadow() exist, arguments() exists, too.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100261 Variable* arguments_shadow() const { return arguments_shadow_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000262
263 // Declarations list.
264 ZoneList<Declaration*>* declarations() { return &decls_; }
265
266
267
268 // ---------------------------------------------------------------------------
269 // Variable allocation.
270
271 // Collect all used locals in this scope.
272 template<class Allocator>
273 void CollectUsedVariables(List<Variable*, Allocator>* locals);
274
275 // Resolve and fill in the allocation information for all variables
276 // in this scopes. Must be called *after* all scopes have been
277 // processed (parsed) to ensure that unresolved variables can be
278 // resolved properly.
279 //
280 // In the case of code compiled and run using 'eval', the context
281 // parameter is the context in which eval was called. In all other
282 // cases the context parameter is an empty handle.
283 void AllocateVariables(Handle<Context> context);
284
285 // Result of variable allocation.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100286 int num_stack_slots() const { return num_stack_slots_; }
287 int num_heap_slots() const { return num_heap_slots_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000288
289 // Make sure this scope and all outer scopes are eagerly compiled.
290 void ForceEagerCompilation() { force_eager_compilation_ = true; }
291
292 // Determine if we can use lazy compilation for this scope.
293 bool AllowsLazyCompilation() const;
294
295 // True if the outer context of this scope is always the global context.
Ben Murdochf87a2032010-10-22 12:50:53 +0100296 virtual bool HasTrivialOuterContext() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000297
298 // The number of contexts between this and scope; zero if this == scope.
299 int ContextChainLength(Scope* scope);
300
Steve Blocka7e24c12009-10-30 11:49:00 +0000301 // ---------------------------------------------------------------------------
Steve Block1e0659c2011-05-24 12:43:12 +0100302 // Strict mode support.
303 bool IsDeclared(Handle<String> name) {
304 // During formal parameter list parsing the scope only contains
305 // two variables inserted at initialization: "this" and "arguments".
306 // "this" is an invalid parameter name and "arguments" is invalid parameter
307 // name in strict mode. Therefore looking up with the map which includes
308 // "this" and "arguments" in addition to all formal parameters is safe.
309 return variables_.Lookup(name) != NULL;
310 }
311
312 // ---------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000313 // Debugging.
314
315#ifdef DEBUG
316 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
317#endif
318
319 // ---------------------------------------------------------------------------
320 // Implementation.
321 protected:
322 friend class ParserFactory;
323
324 explicit Scope(Type type);
325
326 // Scope tree.
327 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
328 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes
329
330 // The scope type.
331 Type type_;
332
333 // Debugging support.
334 Handle<String> scope_name_;
335
336 // The variables declared in this scope:
337 //
338 // All user-declared variables (incl. parameters). For global scopes
339 // variables may be implicitly 'declared' by being used (possibly in
340 // an inner scope) with no intervening with statements or eval calls.
341 VariableMap variables_;
342 // Compiler-allocated (user-invisible) temporaries.
343 ZoneList<Variable*> temps_;
344 // Parameter list in source order.
345 ZoneList<Variable*> params_;
346 // Variables that must be looked up dynamically.
347 DynamicScopePart* dynamics_;
348 // Unresolved variables referred to from this scope.
349 ZoneList<VariableProxy*> unresolved_;
350 // Declarations.
351 ZoneList<Declaration*> decls_;
352 // Convenience variable.
Leon Clarkee46be812010-01-19 14:06:41 +0000353 Variable* receiver_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000354 // Function variable, if any; function scopes only.
355 Variable* function_;
356 // Convenience variable; function scopes only.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100357 Variable* arguments_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000358 // Convenience variable; function scopes only.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100359 Variable* arguments_shadow_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000360
361 // Illegal redeclaration.
362 Expression* illegal_redecl_;
363
364 // Scope-specific information.
365 bool scope_inside_with_; // this scope is inside a 'with' of some outer scope
366 bool scope_contains_with_; // this scope contains a 'with' statement
367 bool scope_calls_eval_; // this scope contains an 'eval' call
Steve Block44f0eee2011-05-26 01:26:41 +0100368 bool strict_mode_; // this scope is a strict mode scope
Steve Blocka7e24c12009-10-30 11:49:00 +0000369
370 // Computed via PropagateScopeInfo.
371 bool outer_scope_calls_eval_;
372 bool inner_scope_calls_eval_;
373 bool outer_scope_is_eval_scope_;
374 bool force_eager_compilation_;
375
376 // Computed via AllocateVariables; function scopes only.
377 int num_stack_slots_;
378 int num_heap_slots_;
379
Ben Murdochb8e0da22011-05-16 14:20:40 +0100380 // Serialized scopes support.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100381 Handle<SerializedScopeInfo> scope_info_;
382 bool resolved() { return !scope_info_.is_null(); }
Ben Murdochb8e0da22011-05-16 14:20:40 +0100383
Steve Blocka7e24c12009-10-30 11:49:00 +0000384 // Create a non-local variable with a given name.
385 // These variables are looked up dynamically at runtime.
386 Variable* NonLocal(Handle<String> name, Variable::Mode mode);
387
388 // Variable resolution.
389 Variable* LookupRecursive(Handle<String> name,
390 bool inner_lookup,
391 Variable** invalidated_local);
392 void ResolveVariable(Scope* global_scope,
393 Handle<Context> context,
394 VariableProxy* proxy);
395 void ResolveVariablesRecursively(Scope* global_scope,
396 Handle<Context> context);
397
398 // Scope analysis.
399 bool PropagateScopeInfo(bool outer_scope_calls_eval,
400 bool outer_scope_is_eval_scope);
401 bool HasTrivialContext() const;
402
403 // Predicates.
404 bool MustAllocate(Variable* var);
405 bool MustAllocateInContext(Variable* var);
406 bool HasArgumentsParameter();
407
408 // Variable allocation.
409 void AllocateStackSlot(Variable* var);
410 void AllocateHeapSlot(Variable* var);
411 void AllocateParameterLocals();
412 void AllocateNonParameterLocal(Variable* var);
413 void AllocateNonParameterLocals();
414 void AllocateVariablesRecursively();
Ben Murdochb8e0da22011-05-16 14:20:40 +0100415
416 private:
Ben Murdoch8b112d22011-06-08 16:22:53 +0100417 Scope(Scope* inner_scope, Handle<SerializedScopeInfo> scope_info);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100418
Steve Block44f0eee2011-05-26 01:26:41 +0100419 void AddInnerScope(Scope* inner_scope) {
420 if (inner_scope != NULL) {
421 inner_scopes_.Add(inner_scope);
422 inner_scope->outer_scope_ = this;
423 }
424 }
425
Ben Murdochb8e0da22011-05-16 14:20:40 +0100426 void SetDefaults(Type type,
427 Scope* outer_scope,
Ben Murdoch8b112d22011-06-08 16:22:53 +0100428 Handle<SerializedScopeInfo> scope_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000429};
430
431
Ben Murdochf87a2032010-10-22 12:50:53 +0100432// Scope used during pre-parsing.
Steve Blocka7e24c12009-10-30 11:49:00 +0000433class DummyScope : public Scope {
434 public:
Ben Murdochf87a2032010-10-22 12:50:53 +0100435 DummyScope()
436 : Scope(GLOBAL_SCOPE),
437 nesting_level_(1), // Allows us to Leave the initial scope.
438 inside_with_level_(kNotInsideWith) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000439 outer_scope_ = this;
Ben Murdochf87a2032010-10-22 12:50:53 +0100440 scope_inside_with_ = false;
441 }
442
443 virtual void Initialize(bool inside_with) {
444 nesting_level_++;
445 if (inside_with && inside_with_level_ == kNotInsideWith) {
446 inside_with_level_ = nesting_level_;
447 }
448 ASSERT(inside_with_level_ <= nesting_level_);
449 }
450
451 virtual void Leave() {
452 nesting_level_--;
453 ASSERT(nesting_level_ >= 0);
454 if (nesting_level_ < inside_with_level_) {
455 inside_with_level_ = kNotInsideWith;
456 }
457 ASSERT(inside_with_level_ <= nesting_level_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000458 }
459
460 virtual Variable* Lookup(Handle<String> name) { return NULL; }
Ben Murdochf87a2032010-10-22 12:50:53 +0100461
Ben Murdoch8b112d22011-06-08 16:22:53 +0100462 virtual VariableProxy* NewUnresolved(Handle<String> name,
463 bool inside_with,
464 int position = RelocInfo::kNoPosition) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000465 return NULL;
466 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100467
Ben Murdochb0fe1622011-05-05 13:52:32 +0100468 virtual Variable* NewTemporary(Handle<String> name) { return NULL; }
Ben Murdochf87a2032010-10-22 12:50:53 +0100469
470 virtual bool HasTrivialOuterContext() const {
471 return (nesting_level_ == 0 || inside_with_level_ <= 0);
472 }
473
474 private:
475 static const int kNotInsideWith = -1;
476 // Number of surrounding scopes of the current scope.
477 int nesting_level_;
478 // Nesting level of outermost scope that is contained in a with statement,
479 // or kNotInsideWith if there are no with's around the current scope.
480 int inside_with_level_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000481};
482
483
484} } // namespace v8::internal
485
486#endif // V8_SCOPES_H_