V8 API Reference, 7.2.502.16 (for Deno 0.2.4)
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_AST_SCOPES_H_
6 #define V8_AST_SCOPES_H_
7 
8 #include "src/ast/ast.h"
9 #include "src/base/compiler-specific.h"
10 #include "src/base/hashmap.h"
11 #include "src/globals.h"
12 #include "src/objects.h"
13 #include "src/pointer-with-payload.h"
14 #include "src/zone/zone.h"
15 
16 namespace v8 {
17 namespace internal {
18 
19 class AstNodeFactory;
20 class AstValueFactory;
21 class AstRawString;
22 class Declaration;
23 class ParseInfo;
24 class PreParsedScopeDataBuilder;
25 class SloppyBlockFunctionStatement;
26 class Statement;
27 class StringSet;
28 class VariableProxy;
29 
30 // A hash map to support fast variable declaration and lookup.
31 class VariableMap: public ZoneHashMap {
32  public:
33  explicit VariableMap(Zone* zone);
34 
35  Variable* Declare(
36  Zone* zone, Scope* scope, const AstRawString* name, VariableMode mode,
37  VariableKind kind = NORMAL_VARIABLE,
38  InitializationFlag initialization_flag = kCreatedInitialized,
39  MaybeAssignedFlag maybe_assigned_flag = kNotAssigned,
40  base::ThreadedList<Variable>* variable_list = nullptr);
41 
42  // Records that "name" exists (if not recorded yet) but doesn't create a
43  // Variable. Useful for preparsing.
44  Variable* DeclareName(Zone* zone, const AstRawString* name,
45  VariableMode mode);
46 
47  Variable* Lookup(const AstRawString* name);
48  void Remove(Variable* var);
49  void Add(Zone* zone, Variable* var);
50 };
51 
52 
53 // Sloppy block-scoped function declarations to var-bind
55  public:
56  class Delegate : public ZoneObject {
57  public:
58  Delegate(Scope* scope, SloppyBlockFunctionStatement* statement, int index)
59  : scope_(scope), statement_(statement), next_(nullptr), index_(index) {}
60  void set_statement(Statement* statement);
61  void set_next(Delegate* next) { next_ = next; }
62  Delegate* next() const { return next_; }
63  Scope* scope() const { return scope_; }
64  int index() const { return index_; }
65 
66  private:
67  Scope* scope_;
68  SloppyBlockFunctionStatement* statement_;
69  Delegate* next_;
70  int index_;
71  };
72 
73  explicit SloppyBlockFunctionMap(Zone* zone);
74  void Declare(Zone* zone, const AstRawString* name, Scope* scope,
75  SloppyBlockFunctionStatement* statement);
76 
77  private:
78  int count_;
79 };
80 
81 class Scope;
82 
83 template <>
85  static constexpr int value = 1;
86 };
87 
88 // Global invariants after AST construction: Each reference (i.e. identifier)
89 // to a JavaScript variable (including global properties) is represented by a
90 // VariableProxy node. Immediately after AST construction and before variable
91 // allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
92 // corresponding variable (though some are bound during parse time). Variable
93 // allocation binds each unresolved VariableProxy to one Variable and assigns
94 // a location. Note that many VariableProxy nodes may refer to the same Java-
95 // Script variable.
96 
97 // JS environments are represented in the parser using Scope, DeclarationScope
98 // and ModuleScope. DeclarationScope is used for any scope that hosts 'var'
99 // declarations. This includes script, module, eval, varblock, and function
100 // scope. ModuleScope further specializes DeclarationScope.
101 class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
102  public:
103  // ---------------------------------------------------------------------------
104  // Construction
105 
106  Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type);
107 
108 #ifdef DEBUG
109  // The scope name is only used for printing/debugging.
110  void SetScopeName(const AstRawString* scope_name) {
111  scope_name_ = scope_name;
112  }
113 #endif
114 
117 
118  // TODO(verwaest): Is this needed on Scope?
119  int num_parameters() const;
120 
121  DeclarationScope* AsDeclarationScope();
122  const DeclarationScope* AsDeclarationScope() const;
123  ModuleScope* AsModuleScope();
124  const ModuleScope* AsModuleScope() const;
125 
126  class Snapshot final {
127  public:
128  Snapshot()
129  : outer_scope_and_calls_eval_(nullptr, false),
130  top_unresolved_(),
131  top_local_() {}
132  inline explicit Snapshot(Scope* scope);
133 
134  ~Snapshot() {
135  // If we're still active, there was no arrow function. In that case outer
136  // calls eval if it already called eval before this snapshot started, or
137  // if the code during the snapshot called eval.
138  if (!IsCleared() && outer_scope_and_calls_eval_.GetPayload()) {
139  RestoreEvalFlag();
140  }
141  }
142 
143  void RestoreEvalFlag() {
144  outer_scope_and_calls_eval_->scope_calls_eval_ =
145  outer_scope_and_calls_eval_.GetPayload();
146  }
147 
148  Snapshot& operator=(Snapshot&& source) V8_NOEXCEPT {
149  outer_scope_and_calls_eval_.SetPointer(
150  source.outer_scope_and_calls_eval_.GetPointer());
151  outer_scope_and_calls_eval_.SetPayload(
152  outer_scope_and_calls_eval_->scope_calls_eval_);
153  top_inner_scope_ = source.top_inner_scope_;
154  top_unresolved_ = source.top_unresolved_;
155  top_local_ = source.top_local_;
156 
157  // We are in the arrow function case. The calls eval we may have recorded
158  // is intended for the inner scope and we should simply restore the
159  // original "calls eval" flag of the outer scope.
160  source.RestoreEvalFlag();
161  source.Clear();
162 
163  return *this;
164  }
165 
166  void Reparent(DeclarationScope* new_parent);
167  bool IsCleared() const {
168  return outer_scope_and_calls_eval_.GetPointer() == nullptr;
169  }
170 
171  private:
172  void Clear() {
173  outer_scope_and_calls_eval_.SetPointer(nullptr);
174 #ifdef DEBUG
175  outer_scope_and_calls_eval_.SetPayload(false);
176  top_inner_scope_ = nullptr;
178  top_unresolved_ = UnresolvedList::Iterator();
179 #endif
180  }
181 
182  // During tracking calls_eval caches whether the outer scope called eval.
183  // Upon move assignment we store whether the new inner scope calls eval into
184  // the move target calls_eval bit, and restore calls eval on the outer
185  // scope.
186  PointerWithPayload<Scope, bool, 1> outer_scope_and_calls_eval_;
187  Scope* top_inner_scope_;
188  UnresolvedList::Iterator top_unresolved_;
190 
191  // Disallow copy and move.
192  Snapshot(const Snapshot&) = delete;
193  Snapshot(Snapshot&&) = delete;
194  };
195 
196  enum class DeserializationMode { kIncludingVariables, kScopesOnly };
197 
198  static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone,
199  ScopeInfo scope_info,
200  DeclarationScope* script_scope,
201  AstValueFactory* ast_value_factory,
202  DeserializationMode deserialization_mode);
203 
204  // Checks if the block scope is redundant, i.e. it does not contain any
205  // block scoped declarations. In that case it is removed from the scope
206  // tree and its children are reparented.
207  Scope* FinalizeBlockScope();
208 
209  bool HasBeenRemoved() const;
210 
211  // Find the first scope that hasn't been removed.
212  Scope* GetUnremovedScope();
213 
214  // Inserts outer_scope into this scope's scope chain (and removes this
215  // from the current outer_scope_'s inner scope list).
216  // Assumes outer_scope_ is non-null.
217  void ReplaceOuterScope(Scope* outer_scope);
218 
219  Zone* zone() const { return zone_; }
220 
221  void SetMustUsePreParsedScopeData() {
222  if (must_use_preparsed_scope_data_) {
223  return;
224  }
225  must_use_preparsed_scope_data_ = true;
226  if (outer_scope_) {
227  outer_scope_->SetMustUsePreParsedScopeData();
228  }
229  }
230 
231  bool must_use_preparsed_scope_data() const {
232  return must_use_preparsed_scope_data_;
233  }
234 
235  // ---------------------------------------------------------------------------
236  // Declarations
237 
238  // Lookup a variable in this scope. Returns the variable or nullptr if not
239  // found.
240  Variable* LookupLocal(const AstRawString* name) {
241  DCHECK(scope_info_.is_null());
242  return variables_.Lookup(name);
243  }
244 
245  Variable* LookupInScopeInfo(const AstRawString* name, Scope* cache);
246 
247  // Declare a local variable in this scope. If the variable has been
248  // declared before, the previously declared variable is returned.
249  Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
250  InitializationFlag init_flag = kCreatedInitialized);
251 
252  Variable* DeclareVariable(Declaration* declaration, VariableMode mode,
253  InitializationFlag init,
254  bool* sloppy_mode_block_scope_function_redefinition,
255  bool* ok);
256 
257  // The return value is meaningful only if FLAG_preparser_scope_analysis is on.
258  Variable* DeclareVariableName(const AstRawString* name, VariableMode mode);
259  void DeclareCatchVariableName(const AstRawString* name);
260 
261  // Declarations list.
262  base::ThreadedList<Declaration>* declarations() { return &decls_; }
263 
264  base::ThreadedList<Variable>* locals() { return &locals_; }
265 
266  // Create a new unresolved variable.
267  VariableProxy* NewUnresolved(AstNodeFactory* factory,
268  const AstRawString* name,
269  int start_pos = kNoSourcePosition,
270  VariableKind kind = NORMAL_VARIABLE) {
271  // Note that we must not share the unresolved variables with
272  // the same name because they may be removed selectively via
273  // RemoveUnresolved().
274  DCHECK(!already_resolved_);
275  DCHECK_EQ(factory->zone(), zone());
276  VariableProxy* proxy = factory->NewVariableProxy(name, kind, start_pos);
277  AddUnresolved(proxy);
278  return proxy;
279  }
280 
281  void AddUnresolved(VariableProxy* proxy);
282 
283  // Removes an unresolved variable from the list so it can be readded to
284  // another list. This is used to reparent parameter initializers that contain
285  // sloppy eval.
286  bool RemoveUnresolved(VariableProxy* var);
287 
288  // Deletes an unresolved variable. The variable proxy cannot be reused for
289  // another list later. During parsing, an unresolved variable may have been
290  // added optimistically, but then only the variable name was used (typically
291  // for labels and arrow function parameters). If the variable was not
292  // declared, the addition introduced a new unresolved variable which may end
293  // up being allocated globally as a "ghost" variable. DeleteUnresolved removes
294  // such a variable again if it was added; otherwise this is a no-op.
295  void DeleteUnresolved(VariableProxy* var);
296 
297  // Creates a new temporary variable in this scope's TemporaryScope. The
298  // name is only used for printing and cannot be used to find the variable.
299  // In particular, the only way to get hold of the temporary is by keeping the
300  // Variable* around. The name should not clash with a legitimate variable
301  // names.
302  // TODO(verwaest): Move to DeclarationScope?
303  Variable* NewTemporary(const AstRawString* name);
304 
305  // ---------------------------------------------------------------------------
306  // Illegal redeclaration support.
307 
308  // Check if the scope has conflicting var
309  // declarations, i.e. a var declaration that has been hoisted from a nested
310  // scope over a let binding of the same name.
311  Declaration* CheckConflictingVarDeclarations();
312 
313  // Check if the scope has a conflicting lexical declaration that has a name in
314  // the given list. This is used to catch patterns like
315  // `try{}catch(e){let e;}`,
316  // which is an error even though the two 'e's are declared in different
317  // scopes.
318  Declaration* CheckLexDeclarationsConflictingWith(
319  const ZonePtrList<const AstRawString>& names);
320 
321  // ---------------------------------------------------------------------------
322  // Scope-specific info.
323 
324  // Inform the scope and outer scopes that the corresponding code contains an
325  // eval call.
326  void RecordEvalCall() {
327  scope_calls_eval_ = true;
328  }
329 
330  void RecordInnerScopeEvalCall() {
331  inner_scope_calls_eval_ = true;
332  for (Scope* scope = outer_scope(); scope != nullptr;
333  scope = scope->outer_scope()) {
334  if (scope->inner_scope_calls_eval_) {
335  return;
336  }
337  scope->inner_scope_calls_eval_ = true;
338  }
339  }
340 
341  // Set the language mode flag (unless disabled by a global flag).
342  void SetLanguageMode(LanguageMode language_mode) {
343  DCHECK(!is_module_scope() || is_strict(language_mode));
344  set_language_mode(language_mode);
345  }
346 
347  // Inform the scope that the scope may execute declarations nonlinearly.
348  // Currently, the only nonlinear scope is a switch statement. The name is
349  // more general in case something else comes up with similar control flow,
350  // for example the ability to break out of something which does not have
351  // its own lexical scope.
352  // The bit does not need to be stored on the ScopeInfo because none of
353  // the three compilers will perform hole check elimination on a variable
354  // located in VariableLocation::CONTEXT. So, direct eval and closures
355  // will not expose holes.
356  void SetNonlinear() { scope_nonlinear_ = true; }
357 
358  // Position in the source where this scope begins and ends.
359  //
360  // * For the scope of a with statement
361  // with (obj) stmt
362  // start position: start position of first token of 'stmt'
363  // end position: end position of last token of 'stmt'
364  // * For the scope of a block
365  // { stmts }
366  // start position: start position of '{'
367  // end position: end position of '}'
368  // * For the scope of a function literal or decalaration
369  // function fun(a,b) { stmts }
370  // start position: start position of '('
371  // end position: end position of '}'
372  // * For the scope of a catch block
373  // try { stms } catch(e) { stmts }
374  // start position: start position of '('
375  // end position: end position of ')'
376  // * For the scope of a for-statement
377  // for (let x ...) stmt
378  // start position: start position of '('
379  // end position: end position of last token of 'stmt'
380  // * For the scope of a switch statement
381  // switch (tag) { cases }
382  // start position: start position of '{'
383  // end position: end position of '}'
384  int start_position() const { return start_position_; }
385  void set_start_position(int statement_pos) {
386  start_position_ = statement_pos;
387  }
388  int end_position() const { return end_position_; }
389  void set_end_position(int statement_pos) {
390  end_position_ = statement_pos;
391  }
392 
393  // Scopes created for desugaring are hidden. I.e. not visible to the debugger.
394  bool is_hidden() const { return is_hidden_; }
395  void set_is_hidden() { is_hidden_ = true; }
396 
397  void ForceContextAllocationForParameters() {
398  DCHECK(!already_resolved_);
399  force_context_allocation_for_parameters_ = true;
400  }
401  bool has_forced_context_allocation_for_parameters() const {
402  return force_context_allocation_for_parameters_;
403  }
404 
405  // ---------------------------------------------------------------------------
406  // Predicates.
407 
408  // Specific scope types.
409  bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
410  bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
411  bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
412  bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
413  bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
414  bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
415  bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
416  bool is_declaration_scope() const { return is_declaration_scope_; }
417 
418  bool inner_scope_calls_eval() const { return inner_scope_calls_eval_; }
419  bool IsAsmModule() const;
420  // Returns true if this scope or any inner scopes that might be eagerly
421  // compiled are asm modules.
422  bool ContainsAsmModule() const;
423  // Does this scope have the potential to execute declarations non-linearly?
424  bool is_nonlinear() const { return scope_nonlinear_; }
425 
426  // Whether this needs to be represented by a runtime context.
427  bool NeedsContext() const {
428  // Catch scopes always have heap slots.
429  DCHECK_IMPLIES(is_catch_scope(), num_heap_slots() > 0);
430  DCHECK_IMPLIES(is_with_scope(), num_heap_slots() > 0);
431  return num_heap_slots() > 0;
432  }
433 
434  // ---------------------------------------------------------------------------
435  // Accessors.
436 
437  // The type of this scope.
438  ScopeType scope_type() const { return scope_type_; }
439 
440  // The language mode of this scope.
441  LanguageMode language_mode() const {
442  return is_strict_ ? LanguageMode::kStrict : LanguageMode::kSloppy;
443  }
444 
445  // inner_scope() and sibling() together implement the inner scope list of a
446  // scope. Inner scope points to the an inner scope of the function, and
447  // "sibling" points to a next inner scope of the outer scope of this scope.
448  Scope* inner_scope() const { return inner_scope_; }
449  Scope* sibling() const { return sibling_; }
450 
451  // The scope immediately surrounding this scope, or nullptr.
452  Scope* outer_scope() const { return outer_scope_; }
453 
454  Variable* catch_variable() const {
455  DCHECK(is_catch_scope());
456  DCHECK_EQ(1, num_var());
457  return static_cast<Variable*>(variables_.Start()->value);
458  }
459 
460  bool ShouldBanArguments();
461 
462  // ---------------------------------------------------------------------------
463  // Variable allocation.
464 
465  // Result of variable allocation.
466  int num_stack_slots() const { return num_stack_slots_; }
467  int num_heap_slots() const { return num_heap_slots_; }
468 
469  int StackLocalCount() const;
470  int ContextLocalCount() const;
471 
472  // Determine if we can parse a function literal in this scope lazily without
473  // caring about the unresolved variables within.
474  bool AllowsLazyParsingWithoutUnresolvedVariables(const Scope* outer) const;
475 
476  // The number of contexts between this and scope; zero if this == scope.
477  int ContextChainLength(Scope* scope) const;
478 
479  // The number of contexts between this and the outermost context that has a
480  // sloppy eval call. One if this->calls_sloppy_eval().
481  int ContextChainLengthUntilOutermostSloppyEval() const;
482 
483  // Find the first function, script, eval or (declaration) block scope. This is
484  // the scope where var declarations will be hoisted to in the implementation.
485  DeclarationScope* GetDeclarationScope();
486 
487  // Find the first non-block declaration scope. This should be either a script,
488  // function, or eval scope. Same as DeclarationScope(), but skips declaration
489  // "block" scopes. Used for differentiating associated function objects (i.e.,
490  // the scope for which a function prologue allocates a context) or declaring
491  // temporaries.
492  DeclarationScope* GetClosureScope();
493  const DeclarationScope* GetClosureScope() const;
494 
495  // Find the first (non-arrow) function or script scope. This is where
496  // 'this' is bound, and what determines the function kind.
497  DeclarationScope* GetReceiverScope();
498 
499  // Find the innermost outer scope that needs a context.
500  Scope* GetOuterScopeWithContext();
501 
502  // Analyze() must have been called once to create the ScopeInfo.
503  Handle<ScopeInfo> scope_info() const {
504  DCHECK(!scope_info_.is_null());
505  return scope_info_;
506  }
507 
508  int num_var() const { return variables_.occupancy(); }
509 
510  // ---------------------------------------------------------------------------
511  // Debugging.
512 
513 #ifdef DEBUG
514  void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
515 
516  // Check that the scope has positions assigned.
517  void CheckScopePositions();
518 
519  // Check that all Scopes in the scope tree use the same Zone.
520  void CheckZones();
521 #endif
522 
523  // Retrieve `IsSimpleParameterList` of current or outer function.
524  bool HasSimpleParameters();
525  void set_is_debug_evaluate_scope() { is_debug_evaluate_scope_ = true; }
526  bool is_debug_evaluate_scope() const { return is_debug_evaluate_scope_; }
527 
528  bool RemoveInnerScope(Scope* inner_scope) {
529  DCHECK_NOT_NULL(inner_scope);
530  if (inner_scope == inner_scope_) {
531  inner_scope_ = inner_scope_->sibling_;
532  return true;
533  }
534  for (Scope* scope = inner_scope_; scope != nullptr;
535  scope = scope->sibling_) {
536  if (scope->sibling_ == inner_scope) {
537  scope->sibling_ = scope->sibling_->sibling_;
538  return true;
539  }
540  }
541  return false;
542  }
543 
544  Variable* LookupInScopeOrScopeInfo(const AstRawString* name) {
545  Variable* var = variables_.Lookup(name);
546  if (var != nullptr || scope_info_.is_null()) return var;
547  return LookupInScopeInfo(name, this);
548  }
549 
550  Variable* LookupForTesting(const AstRawString* name) {
551  for (Scope* scope = this; scope != nullptr; scope = scope->outer_scope()) {
552  Variable* var = scope->LookupInScopeOrScopeInfo(name);
553  if (var != nullptr) return var;
554  }
555  return nullptr;
556  }
557 
558  static void* const kDummyPreParserVariable;
559  static void* const kDummyPreParserLexicalVariable;
560 
561  protected:
562  explicit Scope(Zone* zone);
563 
564  void set_language_mode(LanguageMode language_mode) {
565  is_strict_ = is_strict(language_mode);
566  }
567 
568  private:
569  Variable* Declare(
570  Zone* zone, const AstRawString* name, VariableMode mode,
571  VariableKind kind = NORMAL_VARIABLE,
572  InitializationFlag initialization_flag = kCreatedInitialized,
573  MaybeAssignedFlag maybe_assigned_flag = kNotAssigned) {
574  return variables_.Declare(zone, this, name, mode, kind, initialization_flag,
575  maybe_assigned_flag, &locals_);
576  }
577 
578  // This method should only be invoked on scopes created during parsing (i.e.,
579  // not deserialized from a context). Also, since NeedsContext() is only
580  // returning a valid result after variables are resolved, NeedsScopeInfo()
581  // should also be invoked after resolution.
582  bool NeedsScopeInfo() const;
583 
584  Variable* NewTemporary(const AstRawString* name,
585  MaybeAssignedFlag maybe_assigned);
586 
587  // Walk the scope chain to find DeclarationScopes; call
588  // SavePreParsedScopeDataForDeclarationScope for each.
589  void SavePreParsedScopeData();
590 
591  Zone* zone_;
592 
593  // Scope tree.
594  Scope* outer_scope_; // the immediately enclosing outer scope, or nullptr
595  Scope* inner_scope_; // an inner scope of this scope
596  Scope* sibling_; // a sibling inner scope of the outer scope of this scope.
597 
598  // The variables declared in this scope:
599  //
600  // All user-declared variables (incl. parameters). For script scopes
601  // variables may be implicitly 'declared' by being used (possibly in
602  // an inner scope) with no intervening with statements or eval calls.
603  VariableMap variables_;
604  // In case of non-scopeinfo-backed scopes, this contains the variables of the
605  // map above in order of addition.
606  base::ThreadedList<Variable> locals_;
607  // Unresolved variables referred to from this scope. The proxies themselves
608  // form a linked list of all unresolved proxies.
609  UnresolvedList unresolved_list_;
610  // Declarations.
611  base::ThreadedList<Declaration> decls_;
612 
613  // Serialized scope info support.
614  Handle<ScopeInfo> scope_info_;
615 // Debugging support.
616 #ifdef DEBUG
617  const AstRawString* scope_name_;
618 
619  // True if it doesn't need scope resolution (e.g., if the scope was
620  // constructed based on a serialized scope info or a catch context).
621  bool already_resolved_;
622  // True if this scope may contain objects from a temp zone that needs to be
623  // fixed up.
624  bool needs_migration_;
625 #endif
626 
627  // Source positions.
628  int start_position_;
629  int end_position_;
630 
631  // Computed via AllocateVariables.
632  int num_stack_slots_;
633  int num_heap_slots_;
634 
635  // The scope type.
636  const ScopeType scope_type_;
637 
638  // Scope-specific information computed during parsing.
639  //
640  // The language mode of this scope.
641  STATIC_ASSERT(LanguageModeSize == 2);
642  bool is_strict_ : 1;
643  // This scope or a nested catch scope or with scope contain an 'eval' call. At
644  // the 'eval' call site this scope is the declaration scope.
645  bool scope_calls_eval_ : 1;
646  // This scope's declarations might not be executed in order (e.g., switch).
647  bool scope_nonlinear_ : 1;
648  bool is_hidden_ : 1;
649  // Temporary workaround that allows masking of 'this' in debug-evalute scopes.
650  bool is_debug_evaluate_scope_ : 1;
651 
652  // True if one of the inner scopes or the scope itself calls eval.
653  bool inner_scope_calls_eval_ : 1;
654  bool force_context_allocation_ : 1;
655  bool force_context_allocation_for_parameters_ : 1;
656 
657  // True if it holds 'var' declarations.
658  bool is_declaration_scope_ : 1;
659 
660  bool must_use_preparsed_scope_data_ : 1;
661 
662  // Create a non-local variable with a given name.
663  // These variables are looked up dynamically at runtime.
664  Variable* NonLocal(const AstRawString* name, VariableMode mode);
665 
666  enum ScopeLookupMode {
667  kParsedScope,
668  kDeserializedScope,
669  };
670 
671  // Variable resolution.
672  // Lookup a variable reference given by name starting with this scope, and
673  // stopping when reaching the outer_scope_end scope. If the code is executed
674  // because of a call to 'eval', the context parameter should be set to the
675  // calling context of 'eval'.
676  template <ScopeLookupMode mode>
677  static Variable* Lookup(VariableProxy* proxy, Scope* scope,
678  Scope* outer_scope_end, Scope* entry_point = nullptr,
679  bool force_context_allocation = false);
680  static Variable* LookupWith(VariableProxy* proxy, Scope* scope,
681  Scope* outer_scope_end, Scope* entry_point,
682  bool force_context_allocation);
683  static Variable* LookupSloppyEval(VariableProxy* proxy, Scope* scope,
684  Scope* outer_scope_end, Scope* entry_point,
685  bool force_context_allocation);
686  void ResolveTo(ParseInfo* info, VariableProxy* proxy, Variable* var);
687  V8_WARN_UNUSED_RESULT bool ResolveVariable(ParseInfo* info,
688  VariableProxy* proxy);
689  V8_WARN_UNUSED_RESULT bool ResolveVariablesRecursively(ParseInfo* info);
690 
691  // Finds free variables of this scope. This mutates the unresolved variables
692  // list along the way, so full resolution cannot be done afterwards.
693  void AnalyzePartially(DeclarationScope* max_outer_scope,
694  AstNodeFactory* ast_node_factory,
695  UnresolvedList* new_unresolved_list);
696  void CollectNonLocals(DeclarationScope* max_outer_scope, Isolate* isolate,
697  ParseInfo* info, Handle<StringSet>* non_locals);
698 
699  // Predicates.
700  bool MustAllocate(Variable* var);
701  bool MustAllocateInContext(Variable* var);
702 
703  // Variable allocation.
704  void AllocateStackSlot(Variable* var);
705  void AllocateHeapSlot(Variable* var);
706  void AllocateNonParameterLocal(Variable* var);
707  void AllocateDeclaredGlobal(Variable* var);
708  void AllocateNonParameterLocalsAndDeclaredGlobals();
709  void AllocateVariablesRecursively();
710 
711  void AllocateScopeInfosRecursively(Isolate* isolate,
712  MaybeHandle<ScopeInfo> outer_scope);
713  void AllocateDebuggerScopeInfos(Isolate* isolate,
714  MaybeHandle<ScopeInfo> outer_scope);
715 
716  // Construct a scope based on the scope info.
717  Scope(Zone* zone, ScopeType type, Handle<ScopeInfo> scope_info);
718 
719  // Construct a catch scope with a binding for the name.
720  Scope(Zone* zone, const AstRawString* catch_variable_name,
721  MaybeAssignedFlag maybe_assigned, Handle<ScopeInfo> scope_info);
722 
723  void AddInnerScope(Scope* inner_scope) {
724  inner_scope->sibling_ = inner_scope_;
725  inner_scope_ = inner_scope;
726  inner_scope->outer_scope_ = this;
727  }
728 
729  void SetDefaults();
730 
731  friend class DeclarationScope;
732  friend class ScopeTestHelper;
733 };
734 
735 class V8_EXPORT_PRIVATE DeclarationScope : public Scope {
736  public:
737  DeclarationScope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
738  FunctionKind function_kind = kNormalFunction);
739  DeclarationScope(Zone* zone, ScopeType scope_type,
740  Handle<ScopeInfo> scope_info);
741  // Creates a script scope.
742  DeclarationScope(Zone* zone, AstValueFactory* ast_value_factory);
743 
744  bool IsDeclaredParameter(const AstRawString* name);
745 
746  FunctionKind function_kind() const { return function_kind_; }
747 
748  bool is_arrow_scope() const {
749  return is_function_scope() && IsArrowFunction(function_kind_);
750  }
751 
752  // Inform the scope that the corresponding code uses "super".
753  void RecordSuperPropertyUsage() {
754  DCHECK(IsConciseMethod(function_kind()) ||
755  IsAccessorFunction(function_kind()) ||
756  IsClassConstructor(function_kind()));
757  scope_uses_super_property_ = true;
758  }
759 
760  // Does this scope access "super" property (super.foo).
761  bool NeedsHomeObject() const {
762  return scope_uses_super_property_ ||
763  (inner_scope_calls_eval_ && (IsConciseMethod(function_kind()) ||
764  IsAccessorFunction(function_kind()) ||
765  IsClassConstructor(function_kind())));
766  }
767 
768  bool calls_sloppy_eval() const {
769  return scope_calls_eval_ && is_sloppy(language_mode());
770  }
771 
772  bool was_lazily_parsed() const { return was_lazily_parsed_; }
773 
774  Variable* LookupInModule(const AstRawString* name) {
775  DCHECK(is_module_scope());
776  Variable* var = variables_.Lookup(name);
777  DCHECK_NOT_NULL(var);
778  return var;
779  }
780 
781 #ifdef DEBUG
782  void set_is_being_lazily_parsed(bool is_being_lazily_parsed) {
783  is_being_lazily_parsed_ = is_being_lazily_parsed;
784  }
785  bool is_being_lazily_parsed() const { return is_being_lazily_parsed_; }
786 #endif
787  void set_zone(Zone* zone) {
788 #ifdef DEBUG
789  needs_migration_ = true;
790 #endif
791  zone_ = zone;
792  }
793 
794  bool ShouldEagerCompile() const;
795  void set_should_eager_compile();
796 
797  void SetScriptScopeInfo(Handle<ScopeInfo> scope_info) {
798  DCHECK(is_script_scope());
799  DCHECK(scope_info_.is_null());
800  scope_info_ = scope_info;
801  }
802 
803  bool asm_module() const { return asm_module_; }
804  void set_asm_module();
805 
806  bool should_ban_arguments() const {
807  return IsClassMembersInitializerFunction(function_kind());
808  }
809 
810  void DeclareThis(AstValueFactory* ast_value_factory);
811  void DeclareArguments(AstValueFactory* ast_value_factory);
812  void DeclareDefaultFunctionVariables(AstValueFactory* ast_value_factory);
813 
814  // Declare the function variable for a function literal. This variable
815  // is in an intermediate scope between this function scope and the the
816  // outer scope. Only possible for function scopes; at most one variable.
817  //
818  // This function needs to be called after all other variables have been
819  // declared in the scope. It will add a variable for {name} to {variables_};
820  // either the function variable itself, or a non-local in case the function
821  // calls sloppy eval.
822  Variable* DeclareFunctionVar(const AstRawString* name,
823  Scope* cache = nullptr);
824 
825  // Declare some special internal variables which must be accessible to
826  // Ignition without ScopeInfo.
827  Variable* DeclareGeneratorObjectVar(const AstRawString* name);
828 
829  // Declare a parameter in this scope. When there are duplicated
830  // parameters the rightmost one 'wins'. However, the implementation
831  // expects all parameters to be declared and from left to right.
832  Variable* DeclareParameter(const AstRawString* name, VariableMode mode,
833  bool is_optional, bool is_rest,
834  AstValueFactory* ast_value_factory, int position);
835 
836  // Declares that a parameter with the name exists. Creates a Variable and
837  // returns it if FLAG_preparser_scope_analysis is on.
838  Variable* DeclareParameterName(const AstRawString* name, bool is_rest,
839  AstValueFactory* ast_value_factory,
840  bool declare_local, bool add_parameter);
841 
842  // Declare an implicit global variable in this scope which must be a
843  // script scope. The variable was introduced (possibly from an inner
844  // scope) by a reference to an unresolved variable with no intervening
845  // with statements or eval calls.
846  Variable* DeclareDynamicGlobal(const AstRawString* name,
847  VariableKind variable_kind, Scope* cache);
848 
849  // The variable corresponding to the 'this' value.
850  Variable* receiver() {
851  DCHECK(has_this_declaration());
852  DCHECK_NOT_NULL(receiver_);
853  return receiver_;
854  }
855 
856  // TODO(wingo): Add a GLOBAL_SCOPE scope type which will lexically allocate
857  // "this" (and no other variable) on the native context. Script scopes then
858  // will not have a "this" declaration.
859  bool has_this_declaration() const {
860  return (is_function_scope() && !is_arrow_scope()) || is_module_scope();
861  }
862 
863  // The variable corresponding to the 'new.target' value.
864  Variable* new_target_var() { return new_target_; }
865 
866  // The variable holding the function literal for named function
867  // literals, or nullptr. Only valid for function scopes.
868  Variable* function_var() const { return function_; }
869 
870  // The variable holding the JSGeneratorObject for generator, async
871  // and async generator functions, and modules. Only valid for
872  // function and module scopes.
873  Variable* generator_object_var() const {
874  DCHECK(is_function_scope() || is_module_scope());
875  return GetRareVariable(RareVariable::kGeneratorObject);
876  }
877 
878  // Parameters. The left-most parameter has index 0.
879  // Only valid for function and module scopes.
880  Variable* parameter(int index) const {
881  DCHECK(is_function_scope() || is_module_scope());
882  return params_[index];
883  }
884 
885  // Returns the number of formal parameters, excluding a possible rest
886  // parameter. Examples:
887  // function foo(a, b) {} ==> 2
888  // function foo(a, b, ...c) {} ==> 2
889  // function foo(a, b, c = 1) {} ==> 3
890  int num_parameters() const {
891  return has_rest_ ? params_.length() - 1 : params_.length();
892  }
893 
894  // The function's rest parameter (nullptr if there is none).
895  Variable* rest_parameter() const {
896  return has_rest_ ? params_[params_.length() - 1] : nullptr;
897  }
898 
899  bool has_simple_parameters() const { return has_simple_parameters_; }
900 
901  // TODO(caitp): manage this state in a better way. PreParser must be able to
902  // communicate that the scope is non-simple, without allocating any parameters
903  // as the Parser does. This is necessary to ensure that TC39's proposed early
904  // error can be reported consistently regardless of whether lazily parsed or
905  // not.
906  void SetHasNonSimpleParameters() {
907  DCHECK(is_function_scope());
908  has_simple_parameters_ = false;
909  }
910 
911  // Returns whether the arguments object aliases formal parameters.
912  CreateArgumentsType GetArgumentsType() const {
913  DCHECK(is_function_scope());
914  DCHECK(!is_arrow_scope());
915  DCHECK_NOT_NULL(arguments_);
916  return is_sloppy(language_mode()) && has_simple_parameters()
917  ? CreateArgumentsType::kMappedArguments
918  : CreateArgumentsType::kUnmappedArguments;
919  }
920 
921  // The local variable 'arguments' if we need to allocate it; nullptr
922  // otherwise.
923  Variable* arguments() const {
924  DCHECK_IMPLIES(is_arrow_scope(), arguments_ == nullptr);
925  return arguments_;
926  }
927 
928  Variable* this_function_var() const {
929  Variable* this_function = GetRareVariable(RareVariable::kThisFunction);
930 
931  // This is only used in derived constructors atm.
932  DCHECK(this_function == nullptr ||
933  (is_function_scope() && (IsClassConstructor(function_kind()) ||
934  IsConciseMethod(function_kind()) ||
935  IsAccessorFunction(function_kind()))));
936  return this_function;
937  }
938 
939  // Adds a local variable in this scope's locals list. This is for adjusting
940  // the scope of temporaries and do-expression vars when desugaring parameter
941  // initializers.
942  void AddLocal(Variable* var);
943 
944  void DeclareSloppyBlockFunction(
945  const AstRawString* name, Scope* scope,
946  SloppyBlockFunctionStatement* statement = nullptr);
947 
948  // Go through sloppy_block_function_map_ and hoist those (into this scope)
949  // which should be hoisted.
950  void HoistSloppyBlockFunctions(AstNodeFactory* factory);
951 
952  SloppyBlockFunctionMap* sloppy_block_function_map() {
953  return sloppy_block_function_map_;
954  }
955 
956  // Replaces the outer scope with the outer_scope_info in |info| if there is
957  // one.
958  void AttachOuterScopeInfo(ParseInfo* info, Isolate* isolate);
959 
960  // Compute top scope and allocate variables. For lazy compilation the top
961  // scope only contains the single lazily compiled function, so this
962  // doesn't re-allocate variables repeatedly.
963  //
964  // Returns false if private names can not be resolved and
965  // ParseInfo's pending_error_handler will be populated with an
966  // error. Otherwise, returns true.
967  V8_WARN_UNUSED_RESULT
968  static bool Analyze(ParseInfo* info);
969 
970  // To be called during parsing. Do just enough scope analysis that we can
971  // discard the Scope contents for lazily compiled functions. In particular,
972  // this records variables which cannot be resolved inside the Scope (we don't
973  // yet know what they will resolve to since the outer Scopes are incomplete)
974  // and recreates them with the correct Zone with ast_node_factory.
975  void AnalyzePartially(AstNodeFactory* ast_node_factory);
976 
977  // Allocate ScopeInfos for top scope and any inner scopes that need them.
978  // Does nothing if ScopeInfo is already allocated.
979  static void AllocateScopeInfos(ParseInfo* info, Isolate* isolate);
980 
981  Handle<StringSet> CollectNonLocals(Isolate* isolate, ParseInfo* info,
982  Handle<StringSet> non_locals);
983 
984  // Determine if we can use lazy compilation for this scope.
985  bool AllowsLazyCompilation() const;
986 
987  // Make sure this closure and all outer closures are eagerly compiled.
988  void ForceEagerCompilation() {
989  DCHECK_EQ(this, GetClosureScope());
990  DeclarationScope* s;
991  for (s = this; !s->is_script_scope();
992  s = s->outer_scope()->GetClosureScope()) {
993  s->force_eager_compilation_ = true;
994  }
995  s->force_eager_compilation_ = true;
996  }
997 
998 #ifdef DEBUG
999  void PrintParameters();
1000 #endif
1001 
1002  void AllocateLocals();
1003  void AllocateParameterLocals();
1004  void AllocateReceiver();
1005 
1006  void ResetAfterPreparsing(AstValueFactory* ast_value_factory, bool aborted);
1007 
1008  bool is_skipped_function() const { return is_skipped_function_; }
1009  void set_is_skipped_function(bool is_skipped_function) {
1010  is_skipped_function_ = is_skipped_function;
1011  }
1012 
1013  bool has_inferred_function_name() const {
1014  return has_inferred_function_name_;
1015  }
1016  void set_has_inferred_function_name(bool value) {
1017  DCHECK(is_function_scope());
1018  has_inferred_function_name_ = value;
1019  }
1020 
1021  // Save data describing the context allocation of the variables in this scope
1022  // and its subscopes (except scopes at the laziness boundary). The data is
1023  // saved in produced_preparsed_scope_data_.
1024  void SavePreParsedScopeDataForDeclarationScope();
1025 
1026  void set_preparsed_scope_data_builder(
1027  PreParsedScopeDataBuilder* preparsed_scope_data_builder) {
1028  preparsed_scope_data_builder_ = preparsed_scope_data_builder;
1029  }
1030 
1031  PreParsedScopeDataBuilder* preparsed_scope_data_builder() const {
1032  return preparsed_scope_data_builder_;
1033  }
1034 
1035  private:
1036  void AllocateParameter(Variable* var, int index);
1037 
1038  // Resolve and fill in the allocation information for all variables
1039  // in this scopes. Must be called *after* all scopes have been
1040  // processed (parsed) to ensure that unresolved variables can be
1041  // resolved properly.
1042  //
1043  // In the case of code compiled and run using 'eval', the context
1044  // parameter is the context in which eval was called. In all other
1045  // cases the context parameter is an empty handle.
1046  //
1047  // Returns false if private names can not be resolved.
1048  bool AllocateVariables(ParseInfo* info);
1049 
1050  void SetDefaults();
1051 
1052  bool has_simple_parameters_ : 1;
1053  // This scope contains an "use asm" annotation.
1054  bool asm_module_ : 1;
1055  bool force_eager_compilation_ : 1;
1056  // This function scope has a rest parameter.
1057  bool has_rest_ : 1;
1058  // This scope has a parameter called "arguments".
1059  bool has_arguments_parameter_ : 1;
1060  // This scope uses "super" property ('super.foo').
1061  bool scope_uses_super_property_ : 1;
1062  bool should_eager_compile_ : 1;
1063  // Set to true after we have finished lazy parsing the scope.
1064  bool was_lazily_parsed_ : 1;
1065 #if DEBUG
1066  bool is_being_lazily_parsed_ : 1;
1067 #endif
1068  bool is_skipped_function_ : 1;
1069  bool has_inferred_function_name_ : 1;
1070 
1071  // If the scope is a function scope, this is the function kind.
1072  const FunctionKind function_kind_;
1073 
1074  // Parameter list in source order.
1075  ZonePtrList<Variable> params_;
1076  // Map of function names to lists of functions defined in sloppy blocks
1077  SloppyBlockFunctionMap* sloppy_block_function_map_;
1078  // Convenience variable.
1079  Variable* receiver_;
1080  // Function variable, if any; function scopes only.
1081  Variable* function_;
1082  // new.target variable, function scopes only.
1083  Variable* new_target_;
1084  // Convenience variable; function scopes only.
1085  Variable* arguments_;
1086 
1087  // For producing the scope allocation data during preparsing.
1088  PreParsedScopeDataBuilder* preparsed_scope_data_builder_;
1089 
1090  struct RareData : public ZoneObject {
1091  // Convenience variable; Subclass constructor only
1092  Variable* this_function = nullptr;
1093 
1094  // Generator object, if any; generator function scopes and module scopes
1095  // only.
1096  Variable* generator_object = nullptr;
1097  };
1098 
1099  enum class RareVariable {
1100  kThisFunction = offsetof(RareData, this_function),
1101  kGeneratorObject = offsetof(RareData, generator_object),
1102  };
1103 
1104  V8_INLINE RareData* EnsureRareData() {
1105  if (rare_data_ == nullptr) {
1106  rare_data_ = new (zone_) RareData;
1107  }
1108  return rare_data_;
1109  }
1110 
1111  V8_INLINE Variable* GetRareVariable(RareVariable id) const {
1112  if (rare_data_ == nullptr) return nullptr;
1113  return *reinterpret_cast<Variable**>(
1114  reinterpret_cast<uint8_t*>(rare_data_) + static_cast<ptrdiff_t>(id));
1115  }
1116 
1117  // Set `var` to null if it's non-null and Predicate (Variable*) -> bool
1118  // returns true.
1119  template <typename Predicate>
1120  V8_INLINE void NullifyRareVariableIf(RareVariable id, Predicate predicate) {
1121  if (V8_LIKELY(rare_data_ == nullptr)) return;
1122  Variable** var = reinterpret_cast<Variable**>(
1123  reinterpret_cast<uint8_t*>(rare_data_) + static_cast<ptrdiff_t>(id));
1124  if (*var && predicate(*var)) *var = nullptr;
1125  }
1126 
1127  RareData* rare_data_ = nullptr;
1128 };
1129 
1130 Scope::Snapshot::Snapshot(Scope* scope)
1131  : outer_scope_and_calls_eval_(scope, scope->scope_calls_eval_),
1132  top_inner_scope_(scope->inner_scope_),
1133  top_unresolved_(scope->unresolved_list_.end()),
1134  top_local_(scope->GetClosureScope()->locals_.end()) {
1135  // Reset in order to record eval calls during this Snapshot's lifetime.
1136  outer_scope_and_calls_eval_.GetPointer()->scope_calls_eval_ = false;
1137 }
1138 
1139 class ModuleScope final : public DeclarationScope {
1140  public:
1141  ModuleScope(DeclarationScope* script_scope,
1142  AstValueFactory* ast_value_factory);
1143 
1144  // Deserialization.
1145  // The generated ModuleDescriptor does not preserve all information. In
1146  // particular, its module_requests map will be empty because we no longer need
1147  // the map after parsing.
1148  ModuleScope(Isolate* isolate, Handle<ScopeInfo> scope_info,
1149  AstValueFactory* ast_value_factory);
1150 
1151  ModuleDescriptor* module() const {
1152  DCHECK_NOT_NULL(module_descriptor_);
1153  return module_descriptor_;
1154  }
1155 
1156  // Set MODULE as VariableLocation for all variables that will live in a
1157  // module's export table.
1158  void AllocateModuleVariables();
1159 
1160  private:
1161  ModuleDescriptor* module_descriptor_;
1162 };
1163 
1164 } // namespace internal
1165 } // namespace v8
1166 
1167 #endif // V8_AST_SCOPES_H_
Definition: libplatform.h:13