blob: c2c41799b93fdb94590bff2eb7e01a8d7016d700 [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.
Ben Murdoch69a99ed2011-11-30 16:03:39 +000096 CATCH_SCOPE, // The scope introduced by catch.
97 BLOCK_SCOPE // The scope introduced by a new block.
Steve Block053d10c2011-06-13 19:13:29 +010098 };
99
Steve Blocka7e24c12009-10-30 11:49:00 +0000100 Scope(Scope* outer_scope, Type type);
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 Murdoch3fb3ca82011-12-02 17:19:32 +0000113 void Initialize(bool inside_with);
Steve Blocka7e24c12009-10-30 11:49:00 +0000114
115 // ---------------------------------------------------------------------------
116 // Declarations
117
118 // Lookup a variable in this scope. Returns the variable or NULL if not found.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000119 Variable* LocalLookup(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000120
121 // Lookup a variable in this scope or outer scopes.
122 // Returns the variable or NULL if not found.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000123 Variable* Lookup(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000124
125 // Declare the function variable for a function literal. This variable
126 // is in an intermediate scope between this function scope and the the
127 // outer scope. Only possible for function scopes; at most one variable.
128 Variable* DeclareFunctionVar(Handle<String> name);
129
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000130 // Declare a parameter in this scope. When there are duplicated
131 // parameters the rightmost one 'wins'. However, the implementation
132 // expects all parameters to be declared and from left to right.
133 void DeclareParameter(Handle<String> name);
134
Steve Blocka7e24c12009-10-30 11:49:00 +0000135 // Declare a local variable in this scope. If the variable has been
136 // declared before, the previously declared variable is returned.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000137 Variable* DeclareLocal(Handle<String> name, Variable::Mode mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000138
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
Steve Blocka7e24c12009-10-30 11:49:00 +0000145 // Create a new unresolved variable.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000146 VariableProxy* NewUnresolved(Handle<String> name,
147 bool inside_with,
148 int position = RelocInfo::kNoPosition);
Steve Blocka7e24c12009-10-30 11:49:00 +0000149
150 // Remove a unresolved variable. During parsing, an unresolved variable
151 // may have been added optimistically, but then only the variable name
152 // was used (typically for labels). If the variable was not declared, the
153 // addition introduced a new unresolved variable which may end up being
154 // allocated globally as a "ghost" variable. RemoveUnresolved removes
155 // such a variable again if it was added; otherwise this is a no-op.
156 void RemoveUnresolved(VariableProxy* var);
157
Ben Murdochb0fe1622011-05-05 13:52:32 +0100158 // Creates a new temporary variable in this scope. The name is only used
159 // for printing and cannot be used to find the variable. In particular,
160 // the only way to get hold of the temporary is by keeping the Variable*
161 // around.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000162 Variable* NewTemporary(Handle<String> name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000163
164 // Adds the specific declaration node to the list of declarations in
165 // this scope. The declarations are processed as part of entering
166 // the scope; see codegen.cc:ProcessDeclarations.
167 void AddDeclaration(Declaration* declaration);
168
169 // ---------------------------------------------------------------------------
170 // Illegal redeclaration support.
171
172 // Set an expression node that will be executed when the scope is
173 // entered. We only keep track of one illegal redeclaration node per
174 // scope - the first one - so if you try to set it multiple times
175 // the additional requests will be silently ignored.
176 void SetIllegalRedeclaration(Expression* expression);
177
178 // Visit the illegal redeclaration expression. Do not call if the
179 // scope doesn't have an illegal redeclaration node.
180 void VisitIllegalRedeclaration(AstVisitor* visitor);
181
182 // Check if the scope has (at least) one illegal redeclaration.
183 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
184
185
186 // ---------------------------------------------------------------------------
187 // Scope-specific info.
188
189 // Inform the scope that the corresponding code contains a with statement.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100190 void RecordWithStatement() { scope_contains_with_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000191
192 // Inform the scope that the corresponding code contains an eval call.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100193 void RecordEvalCall() { scope_calls_eval_ = true; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000194
Steve Block44f0eee2011-05-26 01:26:41 +0100195 // Enable strict mode for the scope (unless disabled by a global flag).
196 void EnableStrictMode() {
197 strict_mode_ = FLAG_strict_mode;
198 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000199
200 // ---------------------------------------------------------------------------
201 // Predicates.
202
203 // Specific scope types.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100204 bool is_eval_scope() const { return type_ == EVAL_SCOPE; }
205 bool is_function_scope() const { return type_ == FUNCTION_SCOPE; }
206 bool is_global_scope() const { return type_ == GLOBAL_SCOPE; }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000207 bool is_catch_scope() const { return type_ == CATCH_SCOPE; }
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000208 bool is_block_scope() const { return type_ == BLOCK_SCOPE; }
Steve Block44f0eee2011-05-26 01:26:41 +0100209 bool is_strict_mode() const { return strict_mode_; }
Ben Murdoch257744e2011-11-30 15:57:28 +0000210 bool is_strict_mode_eval_scope() const {
211 return is_eval_scope() && is_strict_mode();
212 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000213
214 // Information about which scopes calls eval.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100215 bool calls_eval() const { return scope_calls_eval_; }
216 bool outer_scope_calls_eval() const { return outer_scope_calls_eval_; }
Ben Murdoch257744e2011-11-30 15:57:28 +0000217 bool outer_scope_calls_non_strict_eval() const {
218 return outer_scope_calls_non_strict_eval_;
219 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000220
221 // Is this scope inside a with statement.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100222 bool inside_with() const { return scope_inside_with_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000223 // Does this scope contain a with statement.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100224 bool contains_with() const { return scope_contains_with_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000225
226 // The scope immediately surrounding this scope, or NULL.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100227 Scope* outer_scope() const { return outer_scope_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000228
229 // ---------------------------------------------------------------------------
230 // Accessors.
231
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000232 // The variable corresponding the 'this' value.
233 Variable* receiver() { return receiver_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000234
235 // The variable holding the function literal for named function
236 // literals, or NULL.
237 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100238 Variable* function() const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000239 ASSERT(is_function_scope());
240 return function_;
241 }
242
243 // Parameters. The left-most parameter has index 0.
244 // Only valid for function scopes.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100245 Variable* parameter(int index) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000246 ASSERT(is_function_scope());
247 return params_[index];
248 }
249
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100250 int num_parameters() const { return params_.length(); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000251
252 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100253 Variable* arguments() const { return arguments_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000254
Steve Blocka7e24c12009-10-30 11:49:00 +0000255 // Declarations list.
256 ZoneList<Declaration*>* declarations() { return &decls_; }
257
258
Steve Blocka7e24c12009-10-30 11:49:00 +0000259 // ---------------------------------------------------------------------------
260 // Variable allocation.
261
262 // Collect all used locals in this scope.
263 template<class Allocator>
264 void CollectUsedVariables(List<Variable*, Allocator>* locals);
265
266 // Resolve and fill in the allocation information for all variables
267 // in this scopes. Must be called *after* all scopes have been
268 // processed (parsed) to ensure that unresolved variables can be
269 // resolved properly.
270 //
271 // In the case of code compiled and run using 'eval', the context
272 // parameter is the context in which eval was called. In all other
273 // cases the context parameter is an empty handle.
274 void AllocateVariables(Handle<Context> context);
275
Steve Block053d10c2011-06-13 19:13:29 +0100276 // Current number of var or const locals.
277 int num_var_or_const() { return num_var_or_const_; }
278
Steve Blocka7e24c12009-10-30 11:49:00 +0000279 // Result of variable allocation.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100280 int num_stack_slots() const { return num_stack_slots_; }
281 int num_heap_slots() const { return num_heap_slots_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000282
283 // Make sure this scope and all outer scopes are eagerly compiled.
284 void ForceEagerCompilation() { force_eager_compilation_ = true; }
285
286 // Determine if we can use lazy compilation for this scope.
287 bool AllowsLazyCompilation() const;
288
289 // True if the outer context of this scope is always the global context.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000290 bool HasTrivialOuterContext() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000291
292 // The number of contexts between this and scope; zero if this == scope.
293 int ContextChainLength(Scope* scope);
294
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000295 // Find the first function, global, or eval scope. This is the scope
296 // where var declarations will be hoisted to in the implementation.
297 Scope* DeclarationScope();
298
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000299 Handle<SerializedScopeInfo> GetSerializedScopeInfo();
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
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000326 Isolate* const isolate_;
327
Steve Blocka7e24c12009-10-30 11:49:00 +0000328 // Scope tree.
329 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
330 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes
331
332 // The scope type.
333 Type type_;
334
335 // Debugging support.
336 Handle<String> scope_name_;
337
338 // The variables declared in this scope:
339 //
340 // All user-declared variables (incl. parameters). For global scopes
341 // variables may be implicitly 'declared' by being used (possibly in
342 // an inner scope) with no intervening with statements or eval calls.
343 VariableMap variables_;
344 // Compiler-allocated (user-invisible) temporaries.
345 ZoneList<Variable*> temps_;
346 // Parameter list in source order.
347 ZoneList<Variable*> params_;
348 // Variables that must be looked up dynamically.
349 DynamicScopePart* dynamics_;
350 // Unresolved variables referred to from this scope.
351 ZoneList<VariableProxy*> unresolved_;
352 // Declarations.
353 ZoneList<Declaration*> decls_;
354 // Convenience variable.
Leon Clarkee46be812010-01-19 14:06:41 +0000355 Variable* receiver_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000356 // Function variable, if any; function scopes only.
357 Variable* function_;
358 // Convenience variable; function scopes only.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100359 Variable* arguments_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000360
361 // Illegal redeclaration.
362 Expression* illegal_redecl_;
363
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000364 // Scope-specific information computed during parsing.
365 //
366 // This scope is inside a 'with' of some outer scope.
367 bool scope_inside_with_;
368 // This scope contains a 'with' statement.
369 bool scope_contains_with_;
370 // This scope or a nested catch scope or with scope contain an 'eval' call. At
371 // the 'eval' call site this scope is the declaration scope.
372 bool scope_calls_eval_;
373 // This scope is a strict mode scope.
374 bool strict_mode_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000375
376 // Computed via PropagateScopeInfo.
377 bool outer_scope_calls_eval_;
Ben Murdoch257744e2011-11-30 15:57:28 +0000378 bool outer_scope_calls_non_strict_eval_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000379 bool inner_scope_calls_eval_;
380 bool outer_scope_is_eval_scope_;
381 bool force_eager_compilation_;
382
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000383 // True if it doesn't need scope resolution (e.g., if the scope was
384 // constructed based on a serialized scope info or a catch context).
385 bool already_resolved_;
386
Steve Block053d10c2011-06-13 19:13:29 +0100387 // Computed as variables are declared.
388 int num_var_or_const_;
389
Steve Blocka7e24c12009-10-30 11:49:00 +0000390 // Computed via AllocateVariables; function scopes only.
391 int num_stack_slots_;
392 int num_heap_slots_;
393
Ben Murdochb8e0da22011-05-16 14:20:40 +0100394 // Serialized scopes support.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100395 Handle<SerializedScopeInfo> scope_info_;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000396 bool already_resolved() { return already_resolved_; }
Ben Murdochb8e0da22011-05-16 14:20:40 +0100397
Steve Blocka7e24c12009-10-30 11:49:00 +0000398 // Create a non-local variable with a given name.
399 // These variables are looked up dynamically at runtime.
400 Variable* NonLocal(Handle<String> name, Variable::Mode mode);
401
402 // Variable resolution.
403 Variable* LookupRecursive(Handle<String> name,
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000404 bool from_inner_function,
Steve Blocka7e24c12009-10-30 11:49:00 +0000405 Variable** invalidated_local);
406 void ResolveVariable(Scope* global_scope,
407 Handle<Context> context,
408 VariableProxy* proxy);
409 void ResolveVariablesRecursively(Scope* global_scope,
410 Handle<Context> context);
411
412 // Scope analysis.
413 bool PropagateScopeInfo(bool outer_scope_calls_eval,
Ben Murdoch257744e2011-11-30 15:57:28 +0000414 bool outer_scope_calls_non_strict_eval,
Steve Blocka7e24c12009-10-30 11:49:00 +0000415 bool outer_scope_is_eval_scope);
416 bool HasTrivialContext() const;
417
418 // Predicates.
419 bool MustAllocate(Variable* var);
420 bool MustAllocateInContext(Variable* var);
421 bool HasArgumentsParameter();
422
423 // Variable allocation.
424 void AllocateStackSlot(Variable* var);
425 void AllocateHeapSlot(Variable* var);
426 void AllocateParameterLocals();
427 void AllocateNonParameterLocal(Variable* var);
428 void AllocateNonParameterLocals();
429 void AllocateVariablesRecursively();
Ben Murdochb8e0da22011-05-16 14:20:40 +0100430
431 private:
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000432 // Construct a function or block scope based on the scope info.
433 Scope(Scope* inner_scope, Type type, Handle<SerializedScopeInfo> scope_info);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100434
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000435 // Construct a catch scope with a binding for the name.
436 Scope(Scope* inner_scope, Handle<String> catch_variable_name);
437
438 inline Slot* NewSlot(Variable* var, Slot::Type type, int index) {
439 return new(isolate_->zone()) Slot(isolate_, var, type, index);
440 }
441
Steve Block44f0eee2011-05-26 01:26:41 +0100442 void AddInnerScope(Scope* inner_scope) {
443 if (inner_scope != NULL) {
444 inner_scopes_.Add(inner_scope);
445 inner_scope->outer_scope_ = this;
446 }
447 }
448
Ben Murdochb8e0da22011-05-16 14:20:40 +0100449 void SetDefaults(Type type,
450 Scope* outer_scope,
Ben Murdoch8b112d22011-06-08 16:22:53 +0100451 Handle<SerializedScopeInfo> scope_info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000452};
453
Steve Blocka7e24c12009-10-30 11:49:00 +0000454} } // namespace v8::internal
455
456#endif // V8_SCOPES_H_