blob: e76fb50598c3a6267576a30a8970a626938e970c [file] [log] [blame]
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001// Copyright 2011 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 {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000093 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 CATCH_SCOPE // The scope introduced by catch.
Steve Block053d10c2011-06-13 19:13:29 +010097 };
98
Steve Blocka7e24c12009-10-30 11:49:00 +000099 Scope(Scope* outer_scope, Type type);
100
Ben Murdochf87a2032010-10-22 12:50:53 +0100101 // Compute top scope and allocate variables. For lazy compilation the top
102 // scope only contains the single lazily compiled function, so this
103 // doesn't re-allocate variables repeatedly.
104 static bool Analyze(CompilationInfo* info);
105
Steve Block44f0eee2011-05-26 01:26:41 +0100106 static Scope* DeserializeScopeChain(CompilationInfo* info,
107 Scope* innermost_scope);
108
Steve Blocka7e24c12009-10-30 11:49:00 +0000109 // The scope name is only used for printing/debugging.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100110 void SetScopeName(Handle<String> scope_name) { scope_name_ = scope_name; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000111
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000112 void Initialize(bool inside_with);
Steve Blocka7e24c12009-10-30 11:49:00 +0000113
114 // ---------------------------------------------------------------------------
115 // Declarations
116
117 // Lookup a variable in this scope. Returns the variable or NULL if not found.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000118 Variable* LocalLookup(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000119
120 // Lookup a variable in this scope or outer scopes.
121 // Returns the variable or NULL if not found.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000122 Variable* Lookup(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000123
124 // Declare the function variable for a function literal. This variable
125 // is in an intermediate scope between this function scope and the the
126 // outer scope. Only possible for function scopes; at most one variable.
127 Variable* DeclareFunctionVar(Handle<String> name);
128
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000129 // Declare a parameter in this scope. When there are duplicated
130 // parameters the rightmost one 'wins'. However, the implementation
131 // expects all parameters to be declared and from left to right.
132 void DeclareParameter(Handle<String> name);
133
Steve Blocka7e24c12009-10-30 11:49:00 +0000134 // Declare a local variable in this scope. If the variable has been
135 // declared before, the previously declared variable is returned.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000136 Variable* DeclareLocal(Handle<String> name, Variable::Mode mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000137
138 // Declare an implicit global variable in this scope which must be a
139 // global scope. The variable was introduced (possibly from an inner
140 // scope) by a reference to an unresolved variable with no intervening
141 // with statements or eval calls.
142 Variable* DeclareGlobal(Handle<String> name);
143
Steve Blocka7e24c12009-10-30 11:49:00 +0000144 // Create a new unresolved variable.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000145 VariableProxy* NewUnresolved(Handle<String> name,
146 bool inside_with,
147 int position = RelocInfo::kNoPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +0000148
149 // Remove a unresolved variable. During parsing, an unresolved variable
150 // may have been added optimistically, but then only the variable name
151 // was used (typically for labels). If the variable was not declared, the
152 // addition introduced a new unresolved variable which may end up being
153 // allocated globally as a "ghost" variable. RemoveUnresolved removes
154 // such a variable again if it was added; otherwise this is a no-op.
155 void RemoveUnresolved(VariableProxy* var);
156
Ben Murdochb0fe1622011-05-05 13:52:32 +0100157 // Creates a new temporary variable in this scope. The name is only used
158 // for printing and cannot be used to find the variable. In particular,
159 // the only way to get hold of the temporary is by keeping the Variable*
160 // around.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000161 Variable* NewTemporary(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000162
163 // Adds the specific declaration node to the list of declarations in
164 // this scope. The declarations are processed as part of entering
165 // the scope; see codegen.cc:ProcessDeclarations.
166 void AddDeclaration(Declaration* declaration);
167
168 // ---------------------------------------------------------------------------
169 // Illegal redeclaration support.
170
171 // Set an expression node that will be executed when the scope is
172 // entered. We only keep track of one illegal redeclaration node per
173 // scope - the first one - so if you try to set it multiple times
174 // the additional requests will be silently ignored.
175 void SetIllegalRedeclaration(Expression* expression);
176
177 // Visit the illegal redeclaration expression. Do not call if the
178 // scope doesn't have an illegal redeclaration node.
179 void VisitIllegalRedeclaration(AstVisitor* visitor);
180
181 // Check if the scope has (at least) one illegal redeclaration.
182 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
183
184
185 // ---------------------------------------------------------------------------
186 // Scope-specific info.
187
188 // Inform the scope that the corresponding code contains a with statement.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100189 void RecordWithStatement() { scope_contains_with_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000190
191 // Inform the scope that the corresponding code contains an eval call.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100192 void RecordEvalCall() { scope_calls_eval_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000193
Steve Block44f0eee2011-05-26 01:26:41 +0100194 // Enable strict mode for the scope (unless disabled by a global flag).
195 void EnableStrictMode() {
196 strict_mode_ = FLAG_strict_mode;
197 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000198
199 // ---------------------------------------------------------------------------
200 // Predicates.
201
202 // Specific scope types.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100203 bool is_eval_scope() const { return type_ == EVAL_SCOPE; }
204 bool is_function_scope() const { return type_ == FUNCTION_SCOPE; }
205 bool is_global_scope() const { return type_ == GLOBAL_SCOPE; }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000206 bool is_catch_scope() const { return type_ == CATCH_SCOPE; }
Steve Block44f0eee2011-05-26 01:26:41 +0100207 bool is_strict_mode() const { return strict_mode_; }
Ben Murdoch257744e2011-11-30 15:57:28 +0000208 bool is_strict_mode_eval_scope() const {
209 return is_eval_scope() && is_strict_mode();
210 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000211
212 // Information about which scopes calls eval.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100213 bool calls_eval() const { return scope_calls_eval_; }
214 bool outer_scope_calls_eval() const { return outer_scope_calls_eval_; }
Ben Murdoch257744e2011-11-30 15:57:28 +0000215 bool outer_scope_calls_non_strict_eval() const {
216 return outer_scope_calls_non_strict_eval_;
217 }
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
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000230 // The variable corresponding the 'this' value.
231 Variable* receiver() { return receiver_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000232
233 // The variable holding the function literal for named function
234 // literals, or NULL.
235 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100236 Variable* function() const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000237 ASSERT(is_function_scope());
238 return function_;
239 }
240
241 // Parameters. The left-most parameter has index 0.
242 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100243 Variable* parameter(int index) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000244 ASSERT(is_function_scope());
245 return params_[index];
246 }
247
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100248 int num_parameters() const { return params_.length(); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000249
250 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100251 Variable* arguments() const { return arguments_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000252
Steve Blocka7e24c12009-10-30 11:49:00 +0000253 // Declarations list.
254 ZoneList<Declaration*>* declarations() { return &decls_; }
255
256
Steve Blocka7e24c12009-10-30 11:49:00 +0000257 // ---------------------------------------------------------------------------
258 // Variable allocation.
259
260 // Collect all used locals in this scope.
261 template<class Allocator>
262 void CollectUsedVariables(List<Variable*, Allocator>* locals);
263
264 // Resolve and fill in the allocation information for all variables
265 // in this scopes. Must be called *after* all scopes have been
266 // processed (parsed) to ensure that unresolved variables can be
267 // resolved properly.
268 //
269 // In the case of code compiled and run using 'eval', the context
270 // parameter is the context in which eval was called. In all other
271 // cases the context parameter is an empty handle.
272 void AllocateVariables(Handle<Context> context);
273
Steve Block053d10c2011-06-13 19:13:29 +0100274 // Current number of var or const locals.
275 int num_var_or_const() { return num_var_or_const_; }
276
Steve Blocka7e24c12009-10-30 11:49:00 +0000277 // Result of variable allocation.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100278 int num_stack_slots() const { return num_stack_slots_; }
279 int num_heap_slots() const { return num_heap_slots_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000280
281 // Make sure this scope and all outer scopes are eagerly compiled.
282 void ForceEagerCompilation() { force_eager_compilation_ = true; }
283
284 // Determine if we can use lazy compilation for this scope.
285 bool AllowsLazyCompilation() const;
286
287 // True if the outer context of this scope is always the global context.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000288 bool HasTrivialOuterContext() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000289
290 // The number of contexts between this and scope; zero if this == scope.
291 int ContextChainLength(Scope* scope);
292
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000293 // Find the first function, global, or eval scope. This is the scope
294 // where var declarations will be hoisted to in the implementation.
295 Scope* DeclarationScope();
296
Steve Blocka7e24c12009-10-30 11:49:00 +0000297 // ---------------------------------------------------------------------------
Steve Block1e0659c2011-05-24 12:43:12 +0100298 // Strict mode support.
299 bool IsDeclared(Handle<String> name) {
300 // During formal parameter list parsing the scope only contains
301 // two variables inserted at initialization: "this" and "arguments".
302 // "this" is an invalid parameter name and "arguments" is invalid parameter
303 // name in strict mode. Therefore looking up with the map which includes
304 // "this" and "arguments" in addition to all formal parameters is safe.
305 return variables_.Lookup(name) != NULL;
306 }
307
308 // ---------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000309 // Debugging.
310
311#ifdef DEBUG
312 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
313#endif
314
315 // ---------------------------------------------------------------------------
316 // Implementation.
317 protected:
318 friend class ParserFactory;
319
320 explicit Scope(Type type);
321
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000322 Isolate* const isolate_;
323
Steve Blocka7e24c12009-10-30 11:49:00 +0000324 // 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
357 // Illegal redeclaration.
358 Expression* illegal_redecl_;
359
360 // Scope-specific information.
361 bool scope_inside_with_; // this scope is inside a 'with' of some outer scope
362 bool scope_contains_with_; // this scope contains a 'with' statement
363 bool scope_calls_eval_; // this scope contains an 'eval' call
Steve Block44f0eee2011-05-26 01:26:41 +0100364 bool strict_mode_; // this scope is a strict mode scope
Steve Blocka7e24c12009-10-30 11:49:00 +0000365
366 // Computed via PropagateScopeInfo.
367 bool outer_scope_calls_eval_;
Ben Murdoch257744e2011-11-30 15:57:28 +0000368 bool outer_scope_calls_non_strict_eval_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000369 bool inner_scope_calls_eval_;
370 bool outer_scope_is_eval_scope_;
371 bool force_eager_compilation_;
372
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000373 // True if it doesn't need scope resolution (e.g., if the scope was
374 // constructed based on a serialized scope info or a catch context).
375 bool already_resolved_;
376
Steve Block053d10c2011-06-13 19:13:29 +0100377 // Computed as variables are declared.
378 int num_var_or_const_;
379
Steve Blocka7e24c12009-10-30 11:49:00 +0000380 // Computed via AllocateVariables; function scopes only.
381 int num_stack_slots_;
382 int num_heap_slots_;
383
Ben Murdochb8e0da22011-05-16 14:20:40 +0100384 // Serialized scopes support.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100385 Handle<SerializedScopeInfo> scope_info_;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000386 bool already_resolved() { return already_resolved_; }
Ben Murdochb8e0da22011-05-16 14:20:40 +0100387
Steve Blocka7e24c12009-10-30 11:49:00 +0000388 // Create a non-local variable with a given name.
389 // These variables are looked up dynamically at runtime.
390 Variable* NonLocal(Handle<String> name, Variable::Mode mode);
391
392 // Variable resolution.
393 Variable* LookupRecursive(Handle<String> name,
394 bool inner_lookup,
395 Variable** invalidated_local);
396 void ResolveVariable(Scope* global_scope,
397 Handle<Context> context,
398 VariableProxy* proxy);
399 void ResolveVariablesRecursively(Scope* global_scope,
400 Handle<Context> context);
401
402 // Scope analysis.
403 bool PropagateScopeInfo(bool outer_scope_calls_eval,
Ben Murdoch257744e2011-11-30 15:57:28 +0000404 bool outer_scope_calls_non_strict_eval,
Steve Blocka7e24c12009-10-30 11:49:00 +0000405 bool outer_scope_is_eval_scope);
406 bool HasTrivialContext() const;
407
408 // Predicates.
409 bool MustAllocate(Variable* var);
410 bool MustAllocateInContext(Variable* var);
411 bool HasArgumentsParameter();
412
413 // Variable allocation.
414 void AllocateStackSlot(Variable* var);
415 void AllocateHeapSlot(Variable* var);
416 void AllocateParameterLocals();
417 void AllocateNonParameterLocal(Variable* var);
418 void AllocateNonParameterLocals();
419 void AllocateVariablesRecursively();
Ben Murdochb8e0da22011-05-16 14:20:40 +0100420
421 private:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000422 // Construct a function scope based on the scope info.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100423 Scope(Scope* inner_scope, Handle<SerializedScopeInfo> scope_info);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100424
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000425 // Construct a catch scope with a binding for the name.
426 Scope(Scope* inner_scope, Handle<String> catch_variable_name);
427
428 inline Slot* NewSlot(Variable* var, Slot::Type type, int index) {
429 return new(isolate_->zone()) Slot(isolate_, var, type, index);
430 }
431
Steve Block44f0eee2011-05-26 01:26:41 +0100432 void AddInnerScope(Scope* inner_scope) {
433 if (inner_scope != NULL) {
434 inner_scopes_.Add(inner_scope);
435 inner_scope->outer_scope_ = this;
436 }
437 }
438
Ben Murdochb8e0da22011-05-16 14:20:40 +0100439 void SetDefaults(Type type,
440 Scope* outer_scope,
Ben Murdoch8b112d22011-06-08 16:22:53 +0100441 Handle<SerializedScopeInfo> scope_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000442};
443
Steve Blocka7e24c12009-10-30 11:49:00 +0000444} } // namespace v8::internal
445
446#endif // V8_SCOPES_H_