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 template<class Visitor> 130 Variable* DeclareFunctionVar(Handle<String> name, 131 VariableMode mode, 132 AstNodeFactory<Visitor>* factory) { 133 ASSERT(is_function_scope() && function_ == NULL); 134 Variable* function_var = new Variable( 135 this, name, mode, true, Variable::NORMAL, kCreatedInitialized); 136 function_ = factory->NewVariableProxy(function_var); 137 return function_var; 138 } 139 140 // Declare a parameter in this scope. When there are duplicated 141 // parameters the rightmost one 'wins'. However, the implementation 142 // expects all parameters to be declared and from left to right. 143 void DeclareParameter(Handle<String> name, VariableMode mode); 144 145 // Declare a local variable in this scope. If the variable has been 146 // declared before, the previously declared variable is returned. 147 Variable* DeclareLocal(Handle<String> name, 148 VariableMode mode, 149 InitializationFlag init_flag, 150 Interface* interface = Interface::NewValue()); 151 152 // Declare an implicit global variable in this scope which must be a 153 // global scope. The variable was introduced (possibly from an inner 154 // scope) by a reference to an unresolved variable with no intervening 155 // with statements or eval calls. 156 Variable* DeclareGlobal(Handle<String> name); 157 158 // Create a new unresolved variable. 159 template<class Visitor> 160 VariableProxy* NewUnresolved(AstNodeFactory<Visitor>* factory, 161 Handle<String> name, 162 int position = RelocInfo::kNoPosition, 163 Interface* interface = Interface::NewValue()) { 164 // Note that we must not share the unresolved variables with 165 // the same name because they may be removed selectively via 166 // RemoveUnresolved(). 167 ASSERT(!already_resolved()); 168 VariableProxy* proxy = 169 factory->NewVariableProxy(name, false, position, interface); 170 unresolved_.Add(proxy); 171 return proxy; 172 } 173 174 // Remove a unresolved variable. During parsing, an unresolved variable 175 // may have been added optimistically, but then only the variable name 176 // was used (typically for labels). If the variable was not declared, the 177 // addition introduced a new unresolved variable which may end up being 178 // allocated globally as a "ghost" variable. RemoveUnresolved removes 179 // such a variable again if it was added; otherwise this is a no-op. 180 void RemoveUnresolved(VariableProxy* var); 181 182 // Creates a new temporary variable in this scope. The name is only used 183 // for printing and cannot be used to find the variable. In particular, 184 // the only way to get hold of the temporary is by keeping the Variable* 185 // around. 186 Variable* NewTemporary(Handle<String> name); 187 188 // Adds the specific declaration node to the list of declarations in 189 // this scope. The declarations are processed as part of entering 190 // the scope; see codegen.cc:ProcessDeclarations. 191 void AddDeclaration(Declaration* declaration); 192 193 // --------------------------------------------------------------------------- 194 // Illegal redeclaration support. 195 196 // Set an expression node that will be executed when the scope is 197 // entered. We only keep track of one illegal redeclaration node per 198 // scope - the first one - so if you try to set it multiple times 199 // the additional requests will be silently ignored. 200 void SetIllegalRedeclaration(Expression* expression); 201 202 // Visit the illegal redeclaration expression. Do not call if the 203 // scope doesn't have an illegal redeclaration node. 204 void VisitIllegalRedeclaration(AstVisitor* visitor); 205 206 // Check if the scope has (at least) one illegal redeclaration. 207 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; } 208 209 // For harmony block scoping mode: Check if the scope has conflicting var 210 // declarations, i.e. a var declaration that has been hoisted from a nested 211 // scope over a let binding of the same name. 212 Declaration* CheckConflictingVarDeclarations(); 213 214 // For harmony block scoping mode: Check if the scope has variable proxies 215 // that are used as lvalues and point to const variables. Assumes that scopes 216 // have been analyzed and variables been resolved. 217 VariableProxy* CheckAssignmentToConst(); 218 219 // --------------------------------------------------------------------------- 220 // Scope-specific info. 221 222 // Inform the scope that the corresponding code contains a with statement. 223 void RecordWithStatement() { scope_contains_with_ = true; } 224 225 // Inform the scope that the corresponding code contains an eval call. 226 void RecordEvalCall() { if (!is_global_scope()) scope_calls_eval_ = true; } 227 228 // Set the strict mode flag (unless disabled by a global flag). 229 void SetLanguageMode(LanguageMode language_mode) { 230 language_mode_ = language_mode; 231 } 232 233 // Position in the source where this scope begins and ends. 234 // 235 // * For the scope of a with statement 236 // with (obj) stmt 237 // start position: start position of first token of 'stmt' 238 // end position: end position of last token of 'stmt' 239 // * For the scope of a block 240 // { stmts } 241 // start position: start position of '{' 242 // end position: end position of '}' 243 // * For the scope of a function literal or decalaration 244 // function fun(a,b) { stmts } 245 // start position: start position of '(' 246 // end position: end position of '}' 247 // * For the scope of a catch block 248 // try { stms } catch(e) { stmts } 249 // start position: start position of '(' 250 // end position: end position of ')' 251 // * For the scope of a for-statement 252 // for (let x ...) stmt 253 // start position: start position of '(' 254 // end position: end position of last token of 'stmt' 255 int start_position() const { return start_position_; } 256 void set_start_position(int statement_pos) { 257 start_position_ = statement_pos; 258 } 259 int end_position() const { return end_position_; } 260 void set_end_position(int statement_pos) { 261 end_position_ = statement_pos; 262 } 263 264 // --------------------------------------------------------------------------- 265 // Predicates. 266 267 // Specific scope types. 268 bool is_eval_scope() const { return type_ == EVAL_SCOPE; } 269 bool is_function_scope() const { return type_ == FUNCTION_SCOPE; } 270 bool is_module_scope() const { return type_ == MODULE_SCOPE; } 271 bool is_global_scope() const { return type_ == GLOBAL_SCOPE; } 272 bool is_catch_scope() const { return type_ == CATCH_SCOPE; } 273 bool is_block_scope() const { return type_ == BLOCK_SCOPE; } 274 bool is_with_scope() const { return type_ == WITH_SCOPE; } 275 bool is_declaration_scope() const { 276 return is_eval_scope() || is_function_scope() || is_global_scope(); 277 } 278 bool is_classic_mode() const { 279 return language_mode() == CLASSIC_MODE; 280 } 281 bool is_extended_mode() const { 282 return language_mode() == EXTENDED_MODE; 283 } 284 bool is_strict_or_extended_eval_scope() const { 285 return is_eval_scope() && !is_classic_mode(); 286 } 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 variable corresponding the 'this' value. 312 Variable* receiver() { return receiver_; } 313 314 // The variable holding the function literal for named function 315 // literals, or NULL. 316 // Only valid for function scopes. 317 VariableProxy* function() const { 318 ASSERT(is_function_scope()); 319 return function_; 320 } 321 322 // Parameters. The left-most parameter has index 0. 323 // Only valid for function scopes. 324 Variable* parameter(int index) const { 325 ASSERT(is_function_scope()); 326 return params_[index]; 327 } 328 329 int num_parameters() const { return params_.length(); } 330 331 // The local variable 'arguments' if we need to allocate it; NULL otherwise. 332 Variable* arguments() const { return arguments_; } 333 334 // Declarations list. 335 ZoneList<Declaration*>* declarations() { return &decls_; } 336 337 // Inner scope list. 338 ZoneList<Scope*>* inner_scopes() { return &inner_scopes_; } 339 340 // The scope immediately surrounding this scope, or NULL. 341 Scope* outer_scope() const { return outer_scope_; } 342 343 // The interface as inferred so far; only for module scopes. 344 Interface* interface() const { return interface_; } 345 346 // --------------------------------------------------------------------------- 347 // Variable allocation. 348 349 // Collect stack and context allocated local variables in this scope. Note 350 // that the function variable - if present - is not collected and should be 351 // handled separately. 352 void CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals, 353 ZoneList<Variable*>* context_locals); 354 355 // Current number of var or const locals. 356 int num_var_or_const() { return num_var_or_const_; } 357 358 // Result of variable allocation. 359 int num_stack_slots() const { return num_stack_slots_; } 360 int num_heap_slots() const { return num_heap_slots_; } 361 362 int StackLocalCount() const; 363 int ContextLocalCount() const; 364 365 // Make sure this scope and all outer scopes are eagerly compiled. 366 void ForceEagerCompilation() { force_eager_compilation_ = true; } 367 368 // Determine if we can use lazy compilation for this scope. 369 bool AllowsLazyCompilation() const; 370 371 // True if we can lazily recompile functions with this scope. 372 bool AllowsLazyRecompilation() const; 373 374 // True if the outer context of this scope is always the global context. 375 bool HasTrivialOuterContext() const; 376 377 // True if this scope is inside a with scope and all declaration scopes 378 // between them have empty contexts. Such declaration scopes become 379 // invisible during scope info deserialization. 380 bool TrivialDeclarationScopesBeforeWithScope() const; 381 382 // The number of contexts between this and scope; zero if this == scope. 383 int ContextChainLength(Scope* scope); 384 385 // Find the first function, global, or eval scope. This is the scope 386 // where var declarations will be hoisted to in the implementation. 387 Scope* DeclarationScope(); 388 389 Handle<ScopeInfo> GetScopeInfo(); 390 391 // Get the chain of nested scopes within this scope for the source statement 392 // position. The scopes will be added to the list from the outermost scope to 393 // the innermost scope. Only nested block, catch or with scopes are tracked 394 // and will be returned, but no inner function scopes. 395 void GetNestedScopeChain(List<Handle<ScopeInfo> >* chain, 396 int statement_position); 397 398 // --------------------------------------------------------------------------- 399 // Strict mode support. 400 bool IsDeclared(Handle<String> name) { 401 // During formal parameter list parsing the scope only contains 402 // two variables inserted at initialization: "this" and "arguments". 403 // "this" is an invalid parameter name and "arguments" is invalid parameter 404 // name in strict mode. Therefore looking up with the map which includes 405 // "this" and "arguments" in addition to all formal parameters is safe. 406 return variables_.Lookup(name) != NULL; 407 } 408 409 // --------------------------------------------------------------------------- 410 // Debugging. 411 412 #ifdef DEBUG 413 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively 414 #endif 415 416 // --------------------------------------------------------------------------- 417 // Implementation. 418 protected: 419 friend class ParserFactory; 420 421 Isolate* const isolate_; 422 423 // Scope tree. 424 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL 425 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes 426 427 // The scope type. 428 ScopeType type_; 429 430 // Debugging support. 431 Handle<String> scope_name_; 432 433 // The variables declared in this scope: 434 // 435 // All user-declared variables (incl. parameters). For global scopes 436 // variables may be implicitly 'declared' by being used (possibly in 437 // an inner scope) with no intervening with statements or eval calls. 438 VariableMap variables_; 439 // Compiler-allocated (user-invisible) temporaries. 440 ZoneList<Variable*> temps_; 441 // Parameter list in source order. 442 ZoneList<Variable*> params_; 443 // Variables that must be looked up dynamically. 444 DynamicScopePart* dynamics_; 445 // Unresolved variables referred to from this scope. 446 ZoneList<VariableProxy*> unresolved_; 447 // Declarations. 448 ZoneList<Declaration*> decls_; 449 // Convenience variable. 450 Variable* receiver_; 451 // Function variable, if any; function scopes only. 452 VariableProxy* function_; 453 // Convenience variable; function scopes only. 454 Variable* arguments_; 455 // Interface; module scopes only. 456 Interface* interface_; 457 458 // Illegal redeclaration. 459 Expression* illegal_redecl_; 460 461 // Scope-specific information computed during parsing. 462 // 463 // This scope is inside a 'with' of some outer scope. 464 bool scope_inside_with_; 465 // This scope contains a 'with' statement. 466 bool scope_contains_with_; 467 // This scope or a nested catch scope or with scope contain an 'eval' call. At 468 // the 'eval' call site this scope is the declaration scope. 469 bool scope_calls_eval_; 470 // The language mode of this scope. 471 LanguageMode language_mode_; 472 // Source positions. 473 int start_position_; 474 int end_position_; 475 476 // Computed via PropagateScopeInfo. 477 bool outer_scope_calls_non_strict_eval_; 478 bool inner_scope_calls_eval_; 479 bool force_eager_compilation_; 480 481 // True if it doesn't need scope resolution (e.g., if the scope was 482 // constructed based on a serialized scope info or a catch context). 483 bool already_resolved_; 484 485 // Computed as variables are declared. 486 int num_var_or_const_; 487 488 // Computed via AllocateVariables; function, block and catch scopes only. 489 int num_stack_slots_; 490 int num_heap_slots_; 491 492 // Serialized scope info support. 493 Handle<ScopeInfo> scope_info_; 494 bool already_resolved() { return already_resolved_; } 495 496 // Create a non-local variable with a given name. 497 // These variables are looked up dynamically at runtime. 498 Variable* NonLocal(Handle<String> name, VariableMode mode); 499 500 // Variable resolution. 501 // Possible results of a recursive variable lookup telling if and how a 502 // variable is bound. These are returned in the output parameter *binding_kind 503 // of the LookupRecursive function. 504 enum BindingKind { 505 // The variable reference could be statically resolved to a variable binding 506 // which is returned. There is no 'with' statement between the reference and 507 // the binding and no scope between the reference scope (inclusive) and 508 // binding scope (exclusive) makes a non-strict 'eval' call. 509 BOUND, 510 511 // The variable reference could be statically resolved to a variable binding 512 // which is returned. There is no 'with' statement between the reference and 513 // the binding, but some scope between the reference scope (inclusive) and 514 // binding scope (exclusive) makes a non-strict 'eval' call, that might 515 // possibly introduce variable bindings shadowing the found one. Thus the 516 // found variable binding is just a guess. 517 BOUND_EVAL_SHADOWED, 518 519 // The variable reference could not be statically resolved to any binding 520 // and thus should be considered referencing a global variable. NULL is 521 // returned. The variable reference is not inside any 'with' statement and 522 // no scope between the reference scope (inclusive) and global scope 523 // (exclusive) makes a non-strict 'eval' call. 524 UNBOUND, 525 526 // The variable reference could not be statically resolved to any binding 527 // NULL is returned. The variable reference is not inside any 'with' 528 // statement, but some scope between the reference scope (inclusive) and 529 // global scope (exclusive) makes a non-strict 'eval' call, that might 530 // possibly introduce a variable binding. Thus the reference should be 531 // considered referencing a global variable unless it is shadowed by an 532 // 'eval' introduced binding. 533 UNBOUND_EVAL_SHADOWED, 534 535 // The variable could not be statically resolved and needs to be looked up 536 // dynamically. NULL is returned. There are two possible reasons: 537 // * A 'with' statement has been encountered and there is no variable 538 // binding for the name between the variable reference and the 'with'. 539 // The variable potentially references a property of the 'with' object. 540 // * The code is being executed as part of a call to 'eval' and the calling 541 // context chain contains either a variable binding for the name or it 542 // contains a 'with' context. 543 DYNAMIC_LOOKUP 544 }; 545 546 // Lookup a variable reference given by name recursively starting with this 547 // scope. If the code is executed because of a call to 'eval', the context 548 // parameter should be set to the calling context of 'eval'. 549 Variable* LookupRecursive(Handle<String> name, 550 BindingKind* binding_kind, 551 AstNodeFactory<AstNullVisitor>* factory); 552 MUST_USE_RESULT 553 bool ResolveVariable(CompilationInfo* info, 554 VariableProxy* proxy, 555 AstNodeFactory<AstNullVisitor>* factory); 556 MUST_USE_RESULT 557 bool ResolveVariablesRecursively(CompilationInfo* info, 558 AstNodeFactory<AstNullVisitor>* factory); 559 560 // Scope analysis. 561 bool PropagateScopeInfo(bool outer_scope_calls_non_strict_eval); 562 bool HasTrivialContext() const; 563 564 // Predicates. 565 bool MustAllocate(Variable* var); 566 bool MustAllocateInContext(Variable* var); 567 bool HasArgumentsParameter(); 568 569 // Variable allocation. 570 void AllocateStackSlot(Variable* var); 571 void AllocateHeapSlot(Variable* var); 572 void AllocateParameterLocals(); 573 void AllocateNonParameterLocal(Variable* var); 574 void AllocateNonParameterLocals(); 575 void AllocateVariablesRecursively(); 576 577 // Resolve and fill in the allocation information for all variables 578 // in this scopes. Must be called *after* all scopes have been 579 // processed (parsed) to ensure that unresolved variables can be 580 // resolved properly. 581 // 582 // In the case of code compiled and run using 'eval', the context 583 // parameter is the context in which eval was called. In all other 584 // cases the context parameter is an empty handle. 585 MUST_USE_RESULT 586 bool AllocateVariables(CompilationInfo* info, 587 AstNodeFactory<AstNullVisitor>* factory); 588 589 private: 590 // Construct a scope based on the scope info. 591 Scope(Scope* inner_scope, ScopeType type, Handle<ScopeInfo> scope_info); 592 593 // Construct a catch scope with a binding for the name. 594 Scope(Scope* inner_scope, Handle<String> catch_variable_name); 595 596 void AddInnerScope(Scope* inner_scope) { 597 if (inner_scope != NULL) { 598 inner_scopes_.Add(inner_scope); 599 inner_scope->outer_scope_ = this; 600 } 601 } 602 603 void SetDefaults(ScopeType type, 604 Scope* outer_scope, 605 Handle<ScopeInfo> scope_info); 606 }; 607 608 } } // namespace v8::internal 609 610 #endif // V8_SCOPES_H_ 611