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