Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / v8 / src / scopes.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_SCOPES_H_
6 #define V8_SCOPES_H_
7
8 #include "src/ast.h"
9 #include "src/zone.h"
10
11 namespace v8 {
12 namespace internal {
13
14 class CompilationInfo;
15
16
17 // A hash map to support fast variable declaration and lookup.
18 class VariableMap: public ZoneHashMap {
19  public:
20   explicit VariableMap(Zone* zone);
21
22   virtual ~VariableMap();
23
24   Variable* Declare(Scope* scope, const AstRawString* name, VariableMode mode,
25                     bool is_valid_lhs, Variable::Kind kind,
26                     InitializationFlag initialization_flag,
27                     MaybeAssignedFlag maybe_assigned_flag = kNotAssigned,
28                     Interface* interface = Interface::NewValue());
29
30   Variable* Lookup(const AstRawString* name);
31
32   Zone* zone() const { return zone_; }
33
34  private:
35   Zone* zone_;
36 };
37
38
39 // The dynamic scope part holds hash maps for the variables that will
40 // be looked up dynamically from within eval and with scopes. The objects
41 // are allocated on-demand from Scope::NonLocal to avoid wasting memory
42 // and setup time for scopes that don't need them.
43 class DynamicScopePart : public ZoneObject {
44  public:
45   explicit DynamicScopePart(Zone* zone) {
46     for (int i = 0; i < 3; i++)
47       maps_[i] = new(zone->New(sizeof(VariableMap))) VariableMap(zone);
48   }
49
50   VariableMap* GetMap(VariableMode mode) {
51     int index = mode - DYNAMIC;
52     DCHECK(index >= 0 && index < 3);
53     return maps_[index];
54   }
55
56  private:
57   VariableMap *maps_[3];
58 };
59
60
61 // Global invariants after AST construction: Each reference (i.e. identifier)
62 // to a JavaScript variable (including global properties) is represented by a
63 // VariableProxy node. Immediately after AST construction and before variable
64 // allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
65 // corresponding variable (though some are bound during parse time). Variable
66 // allocation binds each unresolved VariableProxy to one Variable and assigns
67 // a location. Note that many VariableProxy nodes may refer to the same Java-
68 // Script variable.
69
70 class Scope: public ZoneObject {
71  public:
72   // ---------------------------------------------------------------------------
73   // Construction
74
75   Scope(Scope* outer_scope, ScopeType scope_type,
76         AstValueFactory* value_factory, Zone* zone);
77
78   // Compute top scope and allocate variables. For lazy compilation the top
79   // scope only contains the single lazily compiled function, so this
80   // doesn't re-allocate variables repeatedly.
81   static bool Analyze(CompilationInfo* info);
82
83   static Scope* DeserializeScopeChain(Context* context, Scope* global_scope,
84                                       Zone* zone);
85
86   // The scope name is only used for printing/debugging.
87   void SetScopeName(const AstRawString* scope_name) {
88     scope_name_ = scope_name;
89   }
90
91   void Initialize();
92
93   // Checks if the block scope is redundant, i.e. it does not contain any
94   // block scoped declarations. In that case it is removed from the scope
95   // tree and its children are reparented.
96   Scope* FinalizeBlockScope();
97
98   Zone* zone() const { return zone_; }
99
100   // ---------------------------------------------------------------------------
101   // Declarations
102
103   // Lookup a variable in this scope. Returns the variable or NULL if not found.
104   Variable* LookupLocal(const AstRawString* name);
105
106   // This lookup corresponds to a lookup in the "intermediate" scope sitting
107   // between this scope and the outer scope. (ECMA-262, 3rd., requires that
108   // the name of named function literal is kept in an intermediate scope
109   // in between this scope and the next outer scope.)
110   Variable* LookupFunctionVar(const AstRawString* name,
111                               AstNodeFactory<AstNullVisitor>* factory);
112
113   // Lookup a variable in this scope or outer scopes.
114   // Returns the variable or NULL if not found.
115   Variable* Lookup(const AstRawString* name);
116
117   // Declare the function variable for a function literal. This variable
118   // is in an intermediate scope between this function scope and the the
119   // outer scope. Only possible for function scopes; at most one variable.
120   void DeclareFunctionVar(VariableDeclaration* declaration) {
121     DCHECK(is_function_scope());
122     function_ = declaration;
123   }
124
125   // Declare a parameter in this scope.  When there are duplicated
126   // parameters the rightmost one 'wins'.  However, the implementation
127   // expects all parameters to be declared and from left to right.
128   Variable* DeclareParameter(const AstRawString* name, VariableMode mode);
129
130   // Declare a local variable in this scope. If the variable has been
131   // declared before, the previously declared variable is returned.
132   Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
133                          InitializationFlag init_flag,
134                          MaybeAssignedFlag maybe_assigned_flag = kNotAssigned,
135                          Interface* interface = Interface::NewValue());
136
137   // Declare an implicit global variable in this scope which must be a
138   // global scope.  The variable was introduced (possibly from an inner
139   // scope) by a reference to an unresolved variable with no intervening
140   // with statements or eval calls.
141   Variable* DeclareDynamicGlobal(const AstRawString* name);
142
143   // Create a new unresolved variable.
144   template<class Visitor>
145   VariableProxy* NewUnresolved(AstNodeFactory<Visitor>* factory,
146                                const AstRawString* name,
147                                Interface* interface = Interface::NewValue(),
148                                int position = RelocInfo::kNoPosition) {
149     // Note that we must not share the unresolved variables with
150     // the same name because they may be removed selectively via
151     // RemoveUnresolved().
152     DCHECK(!already_resolved());
153     VariableProxy* proxy =
154         factory->NewVariableProxy(name, false, interface, position);
155     unresolved_.Add(proxy, zone_);
156     return proxy;
157   }
158
159   // Remove a unresolved variable. During parsing, an unresolved variable
160   // may have been added optimistically, but then only the variable name
161   // was used (typically for labels). If the variable was not declared, the
162   // addition introduced a new unresolved variable which may end up being
163   // allocated globally as a "ghost" variable. RemoveUnresolved removes
164   // such a variable again if it was added; otherwise this is a no-op.
165   void RemoveUnresolved(VariableProxy* var);
166
167   // Creates a new internal variable in this scope.  The name is only used
168   // for printing and cannot be used to find the variable.  In particular,
169   // the only way to get hold of the temporary is by keeping the Variable*
170   // around.
171   Variable* NewInternal(const AstRawString* name);
172
173   // Creates a new temporary variable in this scope.  The name is only used
174   // for printing and cannot be used to find the variable.  In particular,
175   // the only way to get hold of the temporary is by keeping the Variable*
176   // around.  The name should not clash with a legitimate variable names.
177   Variable* NewTemporary(const AstRawString* name);
178
179   // Adds the specific declaration node to the list of declarations in
180   // this scope. The declarations are processed as part of entering
181   // the scope; see codegen.cc:ProcessDeclarations.
182   void AddDeclaration(Declaration* declaration);
183
184   // ---------------------------------------------------------------------------
185   // Illegal redeclaration support.
186
187   // Set an expression node that will be executed when the scope is
188   // entered. We only keep track of one illegal redeclaration node per
189   // scope - the first one - so if you try to set it multiple times
190   // the additional requests will be silently ignored.
191   void SetIllegalRedeclaration(Expression* expression);
192
193   // Visit the illegal redeclaration expression. Do not call if the
194   // scope doesn't have an illegal redeclaration node.
195   void VisitIllegalRedeclaration(AstVisitor* visitor);
196
197   // Check if the scope has (at least) one illegal redeclaration.
198   bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
199
200   // For harmony block scoping mode: Check if the scope has conflicting var
201   // declarations, i.e. a var declaration that has been hoisted from a nested
202   // scope over a let binding of the same name.
203   Declaration* CheckConflictingVarDeclarations();
204
205   // ---------------------------------------------------------------------------
206   // Scope-specific info.
207
208   // Inform the scope that the corresponding code contains a with statement.
209   void RecordWithStatement() { scope_contains_with_ = true; }
210
211   // Inform the scope that the corresponding code contains an eval call.
212   void RecordEvalCall() { if (!is_global_scope()) scope_calls_eval_ = true; }
213
214   // Set the strict mode flag (unless disabled by a global flag).
215   void SetStrictMode(StrictMode strict_mode) { strict_mode_ = strict_mode; }
216
217   // Position in the source where this scope begins and ends.
218   //
219   // * For the scope of a with statement
220   //     with (obj) stmt
221   //   start position: start position of first token of 'stmt'
222   //   end position: end position of last token of 'stmt'
223   // * For the scope of a block
224   //     { stmts }
225   //   start position: start position of '{'
226   //   end position: end position of '}'
227   // * For the scope of a function literal or decalaration
228   //     function fun(a,b) { stmts }
229   //   start position: start position of '('
230   //   end position: end position of '}'
231   // * For the scope of a catch block
232   //     try { stms } catch(e) { stmts }
233   //   start position: start position of '('
234   //   end position: end position of ')'
235   // * For the scope of a for-statement
236   //     for (let x ...) stmt
237   //   start position: start position of '('
238   //   end position: end position of last token of 'stmt'
239   int start_position() const { return start_position_; }
240   void set_start_position(int statement_pos) {
241     start_position_ = statement_pos;
242   }
243   int end_position() const { return end_position_; }
244   void set_end_position(int statement_pos) {
245     end_position_ = statement_pos;
246   }
247
248   // In some cases we want to force context allocation for a whole scope.
249   void ForceContextAllocation() {
250     DCHECK(!already_resolved());
251     force_context_allocation_ = true;
252   }
253   bool has_forced_context_allocation() const {
254     return force_context_allocation_;
255   }
256
257   // ---------------------------------------------------------------------------
258   // Predicates.
259
260   // Specific scope types.
261   bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
262   bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
263   bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
264   bool is_global_scope() const { return scope_type_ == GLOBAL_SCOPE; }
265   bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
266   bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
267   bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
268   bool is_declaration_scope() const {
269     return is_eval_scope() || is_function_scope() ||
270         is_module_scope() || is_global_scope();
271   }
272   bool is_strict_eval_scope() const {
273     return is_eval_scope() && strict_mode_ == STRICT;
274   }
275
276   // Information about which scopes calls eval.
277   bool calls_eval() const { return scope_calls_eval_; }
278   bool calls_sloppy_eval() {
279     return scope_calls_eval_ && strict_mode_ == SLOPPY;
280   }
281   bool outer_scope_calls_sloppy_eval() const {
282     return outer_scope_calls_sloppy_eval_;
283   }
284
285   // Is this scope inside a with statement.
286   bool inside_with() const { return scope_inside_with_; }
287   // Does this scope contain a with statement.
288   bool contains_with() const { return scope_contains_with_; }
289
290   // ---------------------------------------------------------------------------
291   // Accessors.
292
293   // The type of this scope.
294   ScopeType scope_type() const { return scope_type_; }
295
296   // The language mode of this scope.
297   StrictMode strict_mode() const { return strict_mode_; }
298
299   // The variable corresponding the 'this' value.
300   Variable* receiver() { return receiver_; }
301
302   // The variable holding the function literal for named function
303   // literals, or NULL.  Only valid for function scopes.
304   VariableDeclaration* function() const {
305     DCHECK(is_function_scope());
306     return function_;
307   }
308
309   // Parameters. The left-most parameter has index 0.
310   // Only valid for function scopes.
311   Variable* parameter(int index) const {
312     DCHECK(is_function_scope());
313     return params_[index];
314   }
315
316   int num_parameters() const { return params_.length(); }
317
318   // The local variable 'arguments' if we need to allocate it; NULL otherwise.
319   Variable* arguments() const { return arguments_; }
320
321   // Declarations list.
322   ZoneList<Declaration*>* declarations() { return &decls_; }
323
324   // Inner scope list.
325   ZoneList<Scope*>* inner_scopes() { return &inner_scopes_; }
326
327   // The scope immediately surrounding this scope, or NULL.
328   Scope* outer_scope() const { return outer_scope_; }
329
330   // The interface as inferred so far; only for module scopes.
331   Interface* interface() const { return interface_; }
332
333   // ---------------------------------------------------------------------------
334   // Variable allocation.
335
336   // Collect stack and context allocated local variables in this scope. Note
337   // that the function variable - if present - is not collected and should be
338   // handled separately.
339   void CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
340                                     ZoneList<Variable*>* context_locals);
341
342   // Current number of var or const locals.
343   int num_var_or_const() { return num_var_or_const_; }
344
345   // Result of variable allocation.
346   int num_stack_slots() const { return num_stack_slots_; }
347   int num_heap_slots() const { return num_heap_slots_; }
348
349   int StackLocalCount() const;
350   int ContextLocalCount() const;
351
352   // For global scopes, the number of module literals (including nested ones).
353   int num_modules() const { return num_modules_; }
354
355   // For module scopes, the host scope's internal variable binding this module.
356   Variable* module_var() const { return module_var_; }
357
358   // Make sure this scope and all outer scopes are eagerly compiled.
359   void ForceEagerCompilation()  { force_eager_compilation_ = true; }
360
361   // Determine if we can use lazy compilation for this scope.
362   bool AllowsLazyCompilation() const;
363
364   // Determine if we can use lazy compilation for this scope without a context.
365   bool AllowsLazyCompilationWithoutContext() const;
366
367   // True if the outer context of this scope is always the native context.
368   bool HasTrivialOuterContext() const;
369
370   // True if the outer context allows lazy compilation of this scope.
371   bool HasLazyCompilableOuterContext() const;
372
373   // The number of contexts between this and scope; zero if this == scope.
374   int ContextChainLength(Scope* scope);
375
376   // Find the innermost global scope.
377   Scope* GlobalScope();
378
379   // Find the first function, global, or eval scope.  This is the scope
380   // where var declarations will be hoisted to in the implementation.
381   Scope* DeclarationScope();
382
383   Handle<ScopeInfo> GetScopeInfo();
384
385   // Get the chain of nested scopes within this scope for the source statement
386   // position. The scopes will be added to the list from the outermost scope to
387   // the innermost scope. Only nested block, catch or with scopes are tracked
388   // and will be returned, but no inner function scopes.
389   void GetNestedScopeChain(List<Handle<ScopeInfo> >* chain,
390                            int statement_position);
391
392   // ---------------------------------------------------------------------------
393   // Strict mode support.
394   bool IsDeclared(const AstRawString* name) {
395     // During formal parameter list parsing the scope only contains
396     // two variables inserted at initialization: "this" and "arguments".
397     // "this" is an invalid parameter name and "arguments" is invalid parameter
398     // name in strict mode. Therefore looking up with the map which includes
399     // "this" and "arguments" in addition to all formal parameters is safe.
400     return variables_.Lookup(name) != NULL;
401   }
402
403   // ---------------------------------------------------------------------------
404   // Debugging.
405
406 #ifdef DEBUG
407   void Print(int n = 0);  // n = indentation; n < 0 => don't print recursively
408 #endif
409
410   // ---------------------------------------------------------------------------
411   // Implementation.
412  protected:
413   friend class ParserFactory;
414
415   Isolate* const isolate_;
416
417   // Scope tree.
418   Scope* outer_scope_;  // the immediately enclosing outer scope, or NULL
419   ZoneList<Scope*> inner_scopes_;  // the immediately enclosed inner scopes
420
421   // The scope type.
422   ScopeType scope_type_;
423
424   // Debugging support.
425   const AstRawString* scope_name_;
426
427   // The variables declared in this scope:
428   //
429   // All user-declared variables (incl. parameters).  For global scopes
430   // variables may be implicitly 'declared' by being used (possibly in
431   // an inner scope) with no intervening with statements or eval calls.
432   VariableMap variables_;
433   // Compiler-allocated (user-invisible) internals.
434   ZoneList<Variable*> internals_;
435   // Compiler-allocated (user-invisible) temporaries.
436   ZoneList<Variable*> temps_;
437   // Parameter list in source order.
438   ZoneList<Variable*> params_;
439   // Variables that must be looked up dynamically.
440   DynamicScopePart* dynamics_;
441   // Unresolved variables referred to from this scope.
442   ZoneList<VariableProxy*> unresolved_;
443   // Declarations.
444   ZoneList<Declaration*> decls_;
445   // Convenience variable.
446   Variable* receiver_;
447   // Function variable, if any; function scopes only.
448   VariableDeclaration* function_;
449   // Convenience variable; function scopes only.
450   Variable* arguments_;
451   // Interface; module scopes only.
452   Interface* interface_;
453
454   // Illegal redeclaration.
455   Expression* illegal_redecl_;
456
457   // Scope-specific information computed during parsing.
458   //
459   // This scope is inside a 'with' of some outer scope.
460   bool scope_inside_with_;
461   // This scope contains a 'with' statement.
462   bool scope_contains_with_;
463   // This scope or a nested catch scope or with scope contain an 'eval' call. At
464   // the 'eval' call site this scope is the declaration scope.
465   bool scope_calls_eval_;
466   // The strict mode of this scope.
467   StrictMode strict_mode_;
468   // Source positions.
469   int start_position_;
470   int end_position_;
471
472   // Computed via PropagateScopeInfo.
473   bool outer_scope_calls_sloppy_eval_;
474   bool inner_scope_calls_eval_;
475   bool force_eager_compilation_;
476   bool force_context_allocation_;
477
478   // True if it doesn't need scope resolution (e.g., if the scope was
479   // constructed based on a serialized scope info or a catch context).
480   bool already_resolved_;
481
482   // Computed as variables are declared.
483   int num_var_or_const_;
484
485   // Computed via AllocateVariables; function, block and catch scopes only.
486   int num_stack_slots_;
487   int num_heap_slots_;
488
489   // The number of modules (including nested ones).
490   int num_modules_;
491
492   // For module scopes, the host scope's internal variable binding this module.
493   Variable* module_var_;
494
495   // Serialized scope info support.
496   Handle<ScopeInfo> scope_info_;
497   bool already_resolved() { return already_resolved_; }
498
499   // Create a non-local variable with a given name.
500   // These variables are looked up dynamically at runtime.
501   Variable* NonLocal(const AstRawString* name, VariableMode mode);
502
503   // Variable resolution.
504   // Possible results of a recursive variable lookup telling if and how a
505   // variable is bound. These are returned in the output parameter *binding_kind
506   // of the LookupRecursive function.
507   enum BindingKind {
508     // The variable reference could be statically resolved to a variable binding
509     // which is returned. There is no 'with' statement between the reference and
510     // the binding and no scope between the reference scope (inclusive) and
511     // binding scope (exclusive) makes a sloppy 'eval' call.
512     BOUND,
513
514     // The variable reference could be statically resolved to a variable binding
515     // which is returned. There is no 'with' statement between the reference and
516     // the binding, but some scope between the reference scope (inclusive) and
517     // binding scope (exclusive) makes a sloppy 'eval' call, that might
518     // possibly introduce variable bindings shadowing the found one. Thus the
519     // found variable binding is just a guess.
520     BOUND_EVAL_SHADOWED,
521
522     // The variable reference could not be statically resolved to any binding
523     // and thus should be considered referencing a global variable. NULL is
524     // returned. The variable reference is not inside any 'with' statement and
525     // no scope between the reference scope (inclusive) and global scope
526     // (exclusive) makes a sloppy 'eval' call.
527     UNBOUND,
528
529     // The variable reference could not be statically resolved to any binding
530     // NULL is returned. The variable reference is not inside any 'with'
531     // statement, but some scope between the reference scope (inclusive) and
532     // global scope (exclusive) makes a sloppy 'eval' call, that might
533     // possibly introduce a variable binding. Thus the reference should be
534     // considered referencing a global variable unless it is shadowed by an
535     // 'eval' introduced binding.
536     UNBOUND_EVAL_SHADOWED,
537
538     // The variable could not be statically resolved and needs to be looked up
539     // dynamically. NULL is returned. There are two possible reasons:
540     // * A 'with' statement has been encountered and there is no variable
541     //   binding for the name between the variable reference and the 'with'.
542     //   The variable potentially references a property of the 'with' object.
543     // * The code is being executed as part of a call to 'eval' and the calling
544     //   context chain contains either a variable binding for the name or it
545     //   contains a 'with' context.
546     DYNAMIC_LOOKUP
547   };
548
549   // Lookup a variable reference given by name recursively starting with this
550   // scope. If the code is executed because of a call to 'eval', the context
551   // parameter should be set to the calling context of 'eval'.
552   Variable* LookupRecursive(VariableProxy* proxy,
553                             BindingKind* binding_kind,
554                             AstNodeFactory<AstNullVisitor>* factory);
555   MUST_USE_RESULT
556   bool ResolveVariable(CompilationInfo* info,
557                        VariableProxy* proxy,
558                        AstNodeFactory<AstNullVisitor>* factory);
559   MUST_USE_RESULT
560   bool ResolveVariablesRecursively(CompilationInfo* info,
561                                    AstNodeFactory<AstNullVisitor>* factory);
562
563   // Scope analysis.
564   void PropagateScopeInfo(bool outer_scope_calls_sloppy_eval);
565   bool HasTrivialContext() const;
566
567   // Predicates.
568   bool MustAllocate(Variable* var);
569   bool MustAllocateInContext(Variable* var);
570   bool HasArgumentsParameter();
571
572   // Variable allocation.
573   void AllocateStackSlot(Variable* var);
574   void AllocateHeapSlot(Variable* var);
575   void AllocateParameterLocals();
576   void AllocateNonParameterLocal(Variable* var);
577   void AllocateNonParameterLocals();
578   void AllocateVariablesRecursively();
579   void AllocateModulesRecursively(Scope* host_scope);
580
581   // Resolve and fill in the allocation information for all variables
582   // in this scopes. Must be called *after* all scopes have been
583   // processed (parsed) to ensure that unresolved variables can be
584   // resolved properly.
585   //
586   // In the case of code compiled and run using 'eval', the context
587   // parameter is the context in which eval was called.  In all other
588   // cases the context parameter is an empty handle.
589   MUST_USE_RESULT
590   bool AllocateVariables(CompilationInfo* info,
591                          AstNodeFactory<AstNullVisitor>* factory);
592
593  private:
594   // Construct a scope based on the scope info.
595   Scope(Scope* inner_scope, ScopeType type, Handle<ScopeInfo> scope_info,
596         AstValueFactory* value_factory, Zone* zone);
597
598   // Construct a catch scope with a binding for the name.
599   Scope(Scope* inner_scope,
600         const AstRawString* catch_variable_name,
601         AstValueFactory* value_factory, Zone* zone);
602
603   void AddInnerScope(Scope* inner_scope) {
604     if (inner_scope != NULL) {
605       inner_scopes_.Add(inner_scope, zone_);
606       inner_scope->outer_scope_ = this;
607     }
608   }
609
610   void SetDefaults(ScopeType type,
611                    Scope* outer_scope,
612                    Handle<ScopeInfo> scope_info);
613
614   AstValueFactory* ast_value_factory_;
615   Zone* zone_;
616 };
617
618 } }  // namespace v8::internal
619
620 #endif  // V8_SCOPES_H_