scopes.h 55.5 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_AST_SCOPES_H_
#define V8_AST_SCOPES_H_
7

8
#include <numeric>
9

10
#include "src/ast/ast.h"
11
#include "src/base/compiler-specific.h"
lpy's avatar
lpy committed
12
#include "src/base/hashmap.h"
13
#include "src/base/threaded-list.h"
14
#include "src/common/globals.h"
15 16
#include "src/objects/function-kind.h"
#include "src/objects/objects.h"
17
#include "src/utils/pointer-with-payload.h"
18
#include "src/utils/utils.h"
19
#include "src/zone/zone-hashmap.h"
20
#include "src/zone/zone.h"
21

22 23
namespace v8 {
namespace internal {
24

25 26 27 28
class AstNodeFactory;
class AstValueFactory;
class AstRawString;
class Declaration;
29
class ParseInfo;
30
class Parser;
31
class PreparseDataBuilder;
32
class SloppyBlockFunctionStatement;
33
class Statement;
34
class StringSet;
35
class VariableProxy;
36

37 38
using UnresolvedList =
    base::ThreadedList<VariableProxy, VariableProxy::UnresolvedNext>;
39

40
// A hash map to support fast variable declaration and lookup.
41
class VariableMap : public ZoneHashMap {
42
 public:
43
  explicit VariableMap(Zone* zone);
44 45 46 47 48 49 50 51 52
  VariableMap(const VariableMap& other, Zone* zone);

  VariableMap(VariableMap&& other) V8_NOEXCEPT : ZoneHashMap(std::move(other)) {
  }

  VariableMap& operator=(VariableMap&& other) V8_NOEXCEPT {
    static_cast<ZoneHashMap&>(*this) = std::move(other);
    return *this;
  }
53

54 55 56
  Variable* Declare(Zone* zone, Scope* scope, const AstRawString* name,
                    VariableMode mode, VariableKind kind,
                    InitializationFlag initialization_flag,
57
                    MaybeAssignedFlag maybe_assigned_flag,
58
                    IsStaticFlag is_static_flag, bool* was_added);
59

60
  V8_EXPORT_PRIVATE Variable* Lookup(const AstRawString* name);
61
  void Remove(Variable* var);
62
  void Add(Variable* var);
63 64

  Zone* zone() const { return allocator().zone(); }
65 66
};

67 68 69 70 71 72 73
class Scope;

template <>
struct PointerWithPayloadTraits<Scope> {
  static constexpr int value = 1;
};

74 75 76 77 78 79 80 81 82
// Global invariants after AST construction: Each reference (i.e. identifier)
// to a JavaScript variable (including global properties) is represented by a
// VariableProxy node. Immediately after AST construction and before variable
// allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
// corresponding variable (though some are bound during parse time). Variable
// allocation binds each unresolved VariableProxy to one Variable and assigns
// a location. Note that many VariableProxy nodes may refer to the same Java-
// Script variable.

83 84 85 86
// JS environments are represented in the parser using Scope, DeclarationScope
// and ModuleScope. DeclarationScope is used for any scope that hosts 'var'
// declarations. This includes script, module, eval, varblock, and function
// scope. ModuleScope further specializes DeclarationScope.
87
class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
88 89 90 91
 public:
  // ---------------------------------------------------------------------------
  // Construction

92 93 94 95 96 97 98 99 100 101 102
  Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type);

#ifdef DEBUG
  // The scope name is only used for printing/debugging.
  void SetScopeName(const AstRawString* scope_name) {
    scope_name_ = scope_name;
  }
#endif

  DeclarationScope* AsDeclarationScope();
  const DeclarationScope* AsDeclarationScope() const;
103 104
  ModuleScope* AsModuleScope();
  const ModuleScope* AsModuleScope() const;
105 106
  ClassScope* AsClassScope();
  const ClassScope* AsClassScope() const;
107

108
  class Snapshot final {
109
   public:
110 111 112
    Snapshot()
        : outer_scope_and_calls_eval_(nullptr, false),
          top_unresolved_(),
113 114 115
          top_local_() {
      DCHECK(IsCleared());
    }
116
    inline explicit Snapshot(Scope* scope);
117

118 119 120 121
    // Disallow copy and move.
    Snapshot(const Snapshot&) = delete;
    Snapshot(Snapshot&&) = delete;

122
    ~Snapshot() {
123 124 125 126 127
      // If we're still active, there was no arrow function. In that case outer
      // calls eval if it already called eval before this snapshot started, or
      // if the code during the snapshot called eval.
      if (!IsCleared() && outer_scope_and_calls_eval_.GetPayload()) {
        RestoreEvalFlag();
128 129
      }
    }
130

131
    void RestoreEvalFlag() {
132 133 134 135
      if (outer_scope_and_calls_eval_.GetPayload()) {
        // This recreates both calls_eval and sloppy_eval_can_extend_vars.
        outer_scope_and_calls_eval_.GetPointer()->RecordEvalCall();
      }
136 137 138 139 140 141
    }

    void Reparent(DeclarationScope* new_parent);
    bool IsCleared() const {
      return outer_scope_and_calls_eval_.GetPointer() == nullptr;
    }
142

143 144 145 146 147 148 149 150 151 152
    void Clear() {
      outer_scope_and_calls_eval_.SetPointer(nullptr);
#ifdef DEBUG
      outer_scope_and_calls_eval_.SetPayload(false);
      top_inner_scope_ = nullptr;
      top_local_ = base::ThreadedList<Variable>::Iterator();
      top_unresolved_ = UnresolvedList::Iterator();
#endif
    }

153
   private:
154 155 156 157
    // During tracking calls_eval caches whether the outer scope called eval.
    // Upon move assignment we store whether the new inner scope calls eval into
    // the move target calls_eval bit, and restore calls eval on the outer
    // scope.
158
    PointerWithPayload<Scope, bool, 1> outer_scope_and_calls_eval_;
159
    Scope* top_inner_scope_;
160
    UnresolvedList::Iterator top_unresolved_;
161
    base::ThreadedList<Variable>::Iterator top_local_;
162 163
  };

164
  enum class DeserializationMode { kIncludingVariables, kScopesOnly };
165

166
  static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone,
167
                                      ScopeInfo scope_info,
168
                                      DeclarationScope* script_scope,
169 170
                                      AstValueFactory* ast_value_factory,
                                      DeserializationMode deserialization_mode);
171

172 173 174 175 176
  // Checks if the block scope is redundant, i.e. it does not contain any
  // block scoped declarations. In that case it is removed from the scope
  // tree and its children are reparented.
  Scope* FinalizeBlockScope();

177
  // Inserts outer_scope into this scope's scope chain (and removes this
178
  // from the current outer_scope_'s inner scope list).
179 180 181
  // Assumes outer_scope_ is non-null.
  void ReplaceOuterScope(Scope* outer_scope);

182
  Zone* zone() const { return variables_.zone(); }
183

184
  void SetMustUsePreparseData() {
185 186 187 188 189
    if (must_use_preparsed_scope_data_) {
      return;
    }
    must_use_preparsed_scope_data_ = true;
    if (outer_scope_) {
190
      outer_scope_->SetMustUsePreparseData();
191 192 193 194 195 196 197
    }
  }

  bool must_use_preparsed_scope_data() const {
    return must_use_preparsed_scope_data_;
  }

198 199 200
  // ---------------------------------------------------------------------------
  // Declarations

201 202
  // Lookup a variable in this scope. Returns the variable or nullptr if not
  // found.
203
  Variable* LookupLocal(const AstRawString* name) {
204 205
    DCHECK(scope_info_.is_null());
    return variables_.Lookup(name);
206 207
  }

208
  Variable* LookupInScopeInfo(const AstRawString* name, Scope* cache);
209

210
  // Declare a local variable in this scope. If the variable has been
211
  // declared before, the previously declared variable is returned.
212
  Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
213
                         VariableKind kind, bool* was_added,
214
                         InitializationFlag init_flag = kCreatedInitialized);
215

216 217
  Variable* DeclareVariable(Declaration* declaration, const AstRawString* name,
                            int pos, VariableMode mode, VariableKind kind,
218 219 220
                            InitializationFlag init, bool* was_added,
                            bool* sloppy_mode_block_scope_function_redefinition,
                            bool* ok);
marja's avatar
marja committed
221

222 223 224 225
  // Returns nullptr if there was a declaration conflict.
  Variable* DeclareVariableName(const AstRawString* name, VariableMode mode,
                                bool* was_added,
                                VariableKind kind = NORMAL_VARIABLE);
226
  Variable* DeclareCatchVariableName(const AstRawString* name);
227

228
  // Declarations list.
229
  base::ThreadedList<Declaration>* declarations() { return &decls_; }
230

231
  base::ThreadedList<Variable>* locals() { return &locals_; }
232

233
  // Create a new unresolved variable.
234
  VariableProxy* NewUnresolved(AstNodeFactory* factory,
235
                               const AstRawString* name, int start_pos,
236 237 238 239 240 241 242
                               VariableKind kind = NORMAL_VARIABLE) {
    // Note that we must not share the unresolved variables with
    // the same name because they may be removed selectively via
    // RemoveUnresolved().
    DCHECK(!already_resolved_);
    DCHECK_EQ(factory->zone(), zone());
    VariableProxy* proxy = factory->NewVariableProxy(name, kind, start_pos);
243
    AddUnresolved(proxy);
244 245
    return proxy;
  }
246

247
  void AddUnresolved(VariableProxy* proxy);
248

249 250 251
  // Removes an unresolved variable from the list so it can be readded to
  // another list. This is used to reparent parameter initializers that contain
  // sloppy eval.
252
  bool RemoveUnresolved(VariableProxy* var);
253

254 255 256 257 258 259 260 261 262
  // Deletes an unresolved variable. The variable proxy cannot be reused for
  // another list later. During parsing, an unresolved variable may have been
  // added optimistically, but then only the variable name was used (typically
  // for labels and arrow function parameters). If the variable was not
  // declared, the addition introduced a new unresolved variable which may end
  // up being allocated globally as a "ghost" variable. DeleteUnresolved removes
  // such a variable again if it was added; otherwise this is a no-op.
  void DeleteUnresolved(VariableProxy* var);

263 264 265 266 267
  // Creates a new temporary variable in this scope's TemporaryScope.  The
  // name is only used for printing and cannot be used to find the variable.
  // In particular, the only way to get hold of the temporary is by keeping the
  // Variable* around.  The name should not clash with a legitimate variable
  // names.
268
  // TODO(verwaest): Move to DeclarationScope?
269
  Variable* NewTemporary(const AstRawString* name);
270

271 272 273 274 275 276 277
  // Find variable with (variable->mode() <= |mode_limit|) that was declared in
  // |scope|. This is used to catch patterns like `try{}catch(e){let e;}` and
  // function([e]) { let e }, which are errors even though the two 'e's are each
  // time declared in different scopes. Returns the first duplicate variable
  // name if there is one, nullptr otherwise.
  const AstRawString* FindVariableDeclaredIn(Scope* scope,
                                             VariableMode mode_limit);
278

279 280 281
  // ---------------------------------------------------------------------------
  // Scope-specific info.

282
  // Inform the scope and outer scopes that the corresponding code contains an
283
  // eval call.
284
  inline void RecordEvalCall();
285 286

  void RecordInnerScopeEvalCall() {
287
    inner_scope_calls_eval_ = true;
288
    for (Scope* scope = outer_scope(); scope != nullptr;
289
         scope = scope->outer_scope()) {
290
      if (scope->inner_scope_calls_eval_) return;
291 292 293
      scope->inner_scope_calls_eval_ = true;
    }
  }
294

295 296
  // Set the language mode flag (unless disabled by a global flag).
  void SetLanguageMode(LanguageMode language_mode) {
297
    DCHECK(!is_module_scope() || is_strict(language_mode));
298
    set_language_mode(language_mode);
299
  }
300

301 302 303 304 305 306 307 308 309 310 311
  // Inform the scope that the scope may execute declarations nonlinearly.
  // Currently, the only nonlinear scope is a switch statement. The name is
  // more general in case something else comes up with similar control flow,
  // for example the ability to break out of something which does not have
  // its own lexical scope.
  // The bit does not need to be stored on the ScopeInfo because none of
  // the three compilers will perform hole check elimination on a variable
  // located in VariableLocation::CONTEXT. So, direct eval and closures
  // will not expose holes.
  void SetNonlinear() { scope_nonlinear_ = true; }

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  // Position in the source where this scope begins and ends.
  //
  // * For the scope of a with statement
  //     with (obj) stmt
  //   start position: start position of first token of 'stmt'
  //   end position: end position of last token of 'stmt'
  // * For the scope of a block
  //     { stmts }
  //   start position: start position of '{'
  //   end position: end position of '}'
  // * For the scope of a function literal or decalaration
  //     function fun(a,b) { stmts }
  //   start position: start position of '('
  //   end position: end position of '}'
  // * For the scope of a catch block
  //     try { stms } catch(e) { stmts }
  //   start position: start position of '('
  //   end position: end position of ')'
  // * For the scope of a for-statement
  //     for (let x ...) stmt
  //   start position: start position of '('
  //   end position: end position of last token of 'stmt'
334 335 336 337
  // * For the scope of a switch statement
  //     switch (tag) { cases }
  //   start position: start position of '{'
  //   end position: end position of '}'
338 339 340 341 342
  int start_position() const { return start_position_; }
  void set_start_position(int statement_pos) {
    start_position_ = statement_pos;
  }
  int end_position() const { return end_position_; }
343
  void set_end_position(int statement_pos) { end_position_ = statement_pos; }
344

345 346 347 348
  // Scopes created for desugaring are hidden. I.e. not visible to the debugger.
  bool is_hidden() const { return is_hidden_; }
  void set_is_hidden() { is_hidden_ = true; }

349 350 351 352 353 354 355
  void ForceContextAllocationForParameters() {
    DCHECK(!already_resolved_);
    force_context_allocation_for_parameters_ = true;
  }
  bool has_forced_context_allocation_for_parameters() const {
    return force_context_allocation_for_parameters_;
  }
356

357 358 359 360
  // ---------------------------------------------------------------------------
  // Predicates.

  // Specific scope types.
361
  bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
362
  bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
363
  bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
364
  bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
365
  bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
366 367 368
  bool is_block_scope() const {
    return scope_type_ == BLOCK_SCOPE || scope_type_ == CLASS_SCOPE;
  }
369
  bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
370
  bool is_declaration_scope() const { return is_declaration_scope_; }
371
  bool is_class_scope() const { return scope_type_ == CLASS_SCOPE; }
372

373
  bool inner_scope_calls_eval() const { return inner_scope_calls_eval_; }
374 375 376
  bool private_name_lookup_skips_outer_class() const {
    return private_name_lookup_skips_outer_class_;
  }
377
  bool IsAsmModule() const;
378 379 380
  // Returns true if this scope or any inner scopes that might be eagerly
  // compiled are asm modules.
  bool ContainsAsmModule() const;
381 382
  // Does this scope have the potential to execute declarations non-linearly?
  bool is_nonlinear() const { return scope_nonlinear_; }
383 384 385 386 387 388 389 390 391 392 393 394 395
  // Returns if we need to force a context because the current scope is stricter
  // than the outerscope. We need this to properly track the language mode using
  // the context. This is required in ICs where we lookup the language mode
  // from the context.
  bool ForceContextForLanguageMode() const {
    // For function scopes we need not force a context since the language mode
    // can be obtained from the closure. Script scopes always have a context.
    if (scope_type_ == FUNCTION_SCOPE || scope_type_ == SCRIPT_SCOPE) {
      return false;
    }
    DCHECK_NOT_NULL(outer_scope_);
    return (language_mode() > outer_scope_->language_mode());
  }
396

397
  // Whether this needs to be represented by a runtime context.
398
  bool NeedsContext() const {
399
    // Catch scopes always have heap slots.
400 401
    DCHECK_IMPLIES(is_catch_scope(), num_heap_slots() > 0);
    DCHECK_IMPLIES(is_with_scope(), num_heap_slots() > 0);
402
    DCHECK_IMPLIES(ForceContextForLanguageMode(), num_heap_slots() > 0);
403
    return num_heap_slots() > 0;
404
  }
405

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  // Use Scope::ForEach for depth first traversal of scopes.
  // Before:
  // void Scope::VisitRecursively() {
  //   DoSomething();
  //   for (Scope* s = inner_scope_; s != nullptr; s = s->sibling_) {
  //     if (s->ShouldContinue()) continue;
  //     s->VisitRecursively();
  //   }
  // }
  //
  // After:
  // void Scope::VisitIteratively() {
  //   this->ForEach([](Scope* s) {
  //      s->DoSomething();
  //      return s->ShouldContinue() ? kContinue : kDescend;
  //   });
  // }
  template <typename FunctionType>
  V8_INLINE void ForEach(FunctionType callback);
  enum Iteration {
    // Continue the iteration on the same level, do not recurse/descent into
    // inner scopes.
    kContinue,
    // Recurse/descend into inner scopes.
    kDescend
  };

433 434 435
  // Check is this scope is an outer scope of the given scope.
  bool IsOuterScopeOf(Scope* other) const;

436 437 438
  // ---------------------------------------------------------------------------
  // Accessors.

439
  // The type of this scope.
440
  ScopeType scope_type() const { return scope_type_; }
441

442
  // The language mode of this scope.
443 444 445
  LanguageMode language_mode() const {
    return is_strict_ ? LanguageMode::kStrict : LanguageMode::kSloppy;
  }
446

447 448 449 450 451
  // inner_scope() and sibling() together implement the inner scope list of a
  // scope. Inner scope points to the an inner scope of the function, and
  // "sibling" points to a next inner scope of the outer scope of this scope.
  Scope* inner_scope() const { return inner_scope_; }
  Scope* sibling() const { return sibling_; }
452

453
  // The scope immediately surrounding this scope, or nullptr.
454 455
  Scope* outer_scope() const { return outer_scope_; }

456
  Variable* catch_variable() const {
457
    DCHECK(is_catch_scope());
458
    DCHECK_EQ(1, num_var());
459
    return static_cast<Variable*>(variables_.Start()->value);
460 461
  }

462 463
  bool ShouldBanArguments();

464 465 466 467
  // ---------------------------------------------------------------------------
  // Variable allocation.

  // Result of variable allocation.
468 469
  int num_stack_slots() const { return num_stack_slots_; }
  int num_heap_slots() const { return num_heap_slots_; }
470

471
  bool HasContextExtensionSlot() const {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    switch (scope_type_) {
      case MODULE_SCOPE:
      case WITH_SCOPE:  // DebugEvaluateContext as well
        return true;
      default:
        DCHECK_IMPLIES(sloppy_eval_can_extend_vars_,
                       scope_type_ == FUNCTION_SCOPE ||
                           scope_type_ == EVAL_SCOPE ||
                           scope_type_ == BLOCK_SCOPE);
        DCHECK_IMPLIES(sloppy_eval_can_extend_vars_, is_declaration_scope());
        return sloppy_eval_can_extend_vars_;
    }
    UNREACHABLE();
  }
  int ContextHeaderLength() const {
487 488
    return HasContextExtensionSlot() ? Context::MIN_CONTEXT_EXTENDED_SLOTS
                                     : Context::MIN_CONTEXT_SLOTS;
489 490
  }

491 492
  int ContextLocalCount() const;

493 494
  // Determine if we can parse a function literal in this scope lazily without
  // caring about the unresolved variables within.
495
  bool AllowsLazyParsingWithoutUnresolvedVariables(const Scope* outer) const;
496

497
  // The number of contexts between this and scope; zero if this == scope.
498 499 500
  int ContextChainLength(Scope* scope) const;

  // The number of contexts between this and the outermost context that has a
501
  // sloppy eval call. One if this->sloppy_eval_can_extend_vars().
502
  int ContextChainLengthUntilOutermostSloppyEval() const;
503

504 505
  // Find the first function, script, eval or (declaration) block scope. This is
  // the scope where var declarations will be hoisted to in the implementation.
506
  DeclarationScope* GetDeclarationScope();
507

508 509 510 511 512 513 514 515
  // Find the first function, script, or (declaration) block scope.
  // This is the scope where var declarations will be hoisted to in the
  // implementation, including vars in direct sloppy eval calls.
  //
  // TODO(leszeks): Check how often we skip eval scopes in GetDeclarationScope,
  // and possibly merge this with GetDeclarationScope.
  DeclarationScope* GetNonEvalDeclarationScope();

516
  // Find the first non-block declaration scope. This should be either a script,
517 518 519 520 521
  // function, or eval scope. Same as DeclarationScope(), but skips declaration
  // "block" scopes. Used for differentiating associated function objects (i.e.,
  // the scope for which a function prologue allocates a context) or declaring
  // temporaries.
  DeclarationScope* GetClosureScope();
522
  const DeclarationScope* GetClosureScope() const;
523

524 525
  // Find the first (non-arrow) function or script scope.  This is where
  // 'this' is bound, and what determines the function kind.
526
  DeclarationScope* GetReceiverScope();
527

Simon Zünd's avatar
Simon Zünd committed
528 529
  DeclarationScope* GetScriptScope();

530 531 532
  // Find the innermost outer scope that needs a context.
  Scope* GetOuterScopeWithContext();

533 534
  bool HasThisReference() const;

535
  // Analyze() must have been called once to create the ScopeInfo.
536
  Handle<ScopeInfo> scope_info() const {
537 538 539 540
    DCHECK(!scope_info_.is_null());
    return scope_info_;
  }

541 542
  int num_var() const { return variables_.occupancy(); }

543 544 545 546 547
  // ---------------------------------------------------------------------------
  // Debugging.

#ifdef DEBUG
  void Print(int n = 0);  // n = indentation; n < 0 => don't print recursively
548 549 550

  // Check that the scope has positions assigned.
  void CheckScopePositions();
551 552 553

  // Check that all Scopes in the scope tree use the same Zone.
  void CheckZones();
554 555
#endif

556 557
  // Retrieve `IsSimpleParameterList` of current or outer function.
  bool HasSimpleParameters();
558
  void set_is_debug_evaluate_scope() { is_debug_evaluate_scope_ = true; }
559
  bool is_debug_evaluate_scope() const { return is_debug_evaluate_scope_; }
560
  bool IsSkippableFunctionScope();
Simon Zünd's avatar
Simon Zünd committed
561
  void set_is_repl_mode_scope() { is_repl_mode_scope_ = true; }
562 563 564 565
  bool is_repl_mode_scope() const {
    DCHECK_IMPLIES(is_repl_mode_scope_, is_script_scope());
    return is_repl_mode_scope_;
  }
566 567 568 569 570 571
  void set_deserialized_scope_uses_external_cache() {
    deserialized_scope_uses_external_cache_ = true;
  }
  bool deserialized_scope_uses_external_cache() const {
    return deserialized_scope_uses_external_cache_;
  }
572

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  bool RemoveInnerScope(Scope* inner_scope) {
    DCHECK_NOT_NULL(inner_scope);
    if (inner_scope == inner_scope_) {
      inner_scope_ = inner_scope_->sibling_;
      return true;
    }
    for (Scope* scope = inner_scope_; scope != nullptr;
         scope = scope->sibling_) {
      if (scope->sibling_ == inner_scope) {
        scope->sibling_ = scope->sibling_->sibling_;
        return true;
      }
    }
    return false;
  }

589
  Variable* LookupInScopeOrScopeInfo(const AstRawString* name, Scope* cache) {
590 591
    Variable* var = variables_.Lookup(name);
    if (var != nullptr || scope_info_.is_null()) return var;
592
    return LookupInScopeInfo(name, cache);
593 594
  }

595 596
  Variable* LookupForTesting(const AstRawString* name) {
    for (Scope* scope = this; scope != nullptr; scope = scope->outer_scope()) {
597
      Variable* var = scope->LookupInScopeOrScopeInfo(name, scope);
598 599 600 601 602
      if (var != nullptr) return var;
    }
    return nullptr;
  }

603
 protected:
604
  explicit Scope(Zone* zone);
605

606
  void set_language_mode(LanguageMode language_mode) {
607
    is_strict_ = is_strict(language_mode);
608 609
  }

610
 private:
611 612 613
  Variable* Declare(Zone* zone, const AstRawString* name, VariableMode mode,
                    VariableKind kind, InitializationFlag initialization_flag,
                    MaybeAssignedFlag maybe_assigned_flag, bool* was_added) {
614 615 616 617
    // Static variables can only be declared using ClassScope methods.
    Variable* result = variables_.Declare(
        zone, this, name, mode, kind, initialization_flag, maybe_assigned_flag,
        IsStaticFlag::kNotStatic, was_added);
618 619
    if (*was_added) locals_.Add(result);
    return result;
620
  }
621 622 623 624 625

  // This method should only be invoked on scopes created during parsing (i.e.,
  // not deserialized from a context). Also, since NeedsContext() is only
  // returning a valid result after variables are resolved, NeedsScopeInfo()
  // should also be invoked after resolution.
626
  bool NeedsScopeInfo() const;
627

628 629
  Variable* NewTemporary(const AstRawString* name,
                         MaybeAssignedFlag maybe_assigned);
630 631

  // Walk the scope chain to find DeclarationScopes; call
632
  // SavePreparseDataForDeclarationScope for each.
633
  void SavePreparseData(Parser* parser);
634

635 636
  // Create a non-local variable with a given name.
  // These variables are looked up dynamically at runtime.
637
  Variable* NonLocal(const AstRawString* name, VariableMode mode);
638

639 640 641 642 643
  enum ScopeLookupMode {
    kParsedScope,
    kDeserializedScope,
  };

644
  // Variable resolution.
645 646 647 648
  // Lookup a variable reference given by name starting with this scope, and
  // stopping when reaching the outer_scope_end scope. If the code is executed
  // because of a call to 'eval', the context parameter should be set to the
  // calling context of 'eval'.
649
  template <ScopeLookupMode mode>
650
  static Variable* Lookup(VariableProxy* proxy, Scope* scope,
651
                          Scope* outer_scope_end, Scope* cache_scope = nullptr,
652
                          bool force_context_allocation = false);
653
  static Variable* LookupWith(VariableProxy* proxy, Scope* scope,
654
                              Scope* outer_scope_end, Scope* cache_scope,
655
                              bool force_context_allocation);
656
  static Variable* LookupSloppyEval(VariableProxy* proxy, Scope* scope,
657
                                    Scope* outer_scope_end, Scope* cache_scope,
658
                                    bool force_context_allocation);
659
  static void ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
660
                                       Scope* end);
661 662 663
  void ResolveTo(VariableProxy* proxy, Variable* var);
  void ResolveVariable(VariableProxy* proxy);
  V8_WARN_UNUSED_RESULT bool ResolveVariablesRecursively(Scope* end);
664

verwaest's avatar
verwaest committed
665 666
  // Finds free variables of this scope. This mutates the unresolved variables
  // list along the way, so full resolution cannot be done afterwards.
667 668
  void AnalyzePartially(DeclarationScope* max_outer_scope,
                        AstNodeFactory* ast_node_factory,
669 670
                        UnresolvedList* new_unresolved_list,
                        bool maybe_in_arrowhead);
671
  void CollectNonLocals(DeclarationScope* max_outer_scope, Isolate* isolate,
672
                        Handle<StringSet>* non_locals);
673

674 675 676 677 678 679
  // Predicates.
  bool MustAllocate(Variable* var);
  bool MustAllocateInContext(Variable* var);

  // Variable allocation.
  void AllocateStackSlot(Variable* var);
680
  V8_INLINE void AllocateHeapSlot(Variable* var);
681 682
  void AllocateNonParameterLocal(Variable* var);
  void AllocateDeclaredGlobal(Variable* var);
683
  V8_INLINE void AllocateNonParameterLocalsAndDeclaredGlobals();
684
  void AllocateVariablesRecursively();
685

686 687 688
  template <typename LocalIsolate>
  void AllocateScopeInfosRecursively(LocalIsolate* isolate,
                                     MaybeHandle<ScopeInfo> outer_scope);
689

690 691
  void AllocateDebuggerScopeInfos(Isolate* isolate,
                                  MaybeHandle<ScopeInfo> outer_scope);
692

693
  // Construct a scope based on the scope info.
694
  Scope(Zone* zone, ScopeType type, Handle<ScopeInfo> scope_info);
695

696
  // Construct a catch scope with a binding for the name.
697
  Scope(Zone* zone, const AstRawString* catch_variable_name,
698
        MaybeAssignedFlag maybe_assigned, Handle<ScopeInfo> scope_info);
699

700
  void AddInnerScope(Scope* inner_scope) {
701 702 703
    inner_scope->sibling_ = inner_scope_;
    inner_scope_ = inner_scope;
    inner_scope->outer_scope_ = this;
704 705
  }

706
  void SetDefaults();
707

708 709
  void set_scope_info(Handle<ScopeInfo> scope_info);

710
  friend class DeclarationScope;
711
  friend class ClassScope;
712
  friend class ScopeTestHelper;
713
  friend Zone;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735

  // Scope tree.
  Scope* outer_scope_;  // the immediately enclosing outer scope, or nullptr
  Scope* inner_scope_;  // an inner scope of this scope
  Scope* sibling_;  // a sibling inner scope of the outer scope of this scope.

  // The variables declared in this scope:
  //
  // All user-declared variables (incl. parameters).  For script scopes
  // variables may be implicitly 'declared' by being used (possibly in
  // an inner scope) with no intervening with statements or eval calls.
  VariableMap variables_;
  // In case of non-scopeinfo-backed scopes, this contains the variables of the
  // map above in order of addition.
  base::ThreadedList<Variable> locals_;
  // Unresolved variables referred to from this scope. The proxies themselves
  // form a linked list of all unresolved proxies.
  UnresolvedList unresolved_list_;
  // Declarations.
  base::ThreadedList<Declaration> decls_;

  // Serialized scope info support.
736
  Handle<ScopeInfo> scope_info_;
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
// Debugging support.
#ifdef DEBUG
  const AstRawString* scope_name_;

  // True if it doesn't need scope resolution (e.g., if the scope was
  // constructed based on a serialized scope info or a catch context).
  bool already_resolved_;
  // True if this scope may contain objects from a temp zone that needs to be
  // fixed up.
  bool needs_migration_;
#endif

  // Source positions.
  int start_position_;
  int end_position_;

  // Computed via AllocateVariables.
  int num_stack_slots_;
  int num_heap_slots_;

  // The scope type.
  const ScopeType scope_type_;

  // Scope-specific information computed during parsing.
  //
  // The language mode of this scope.
  STATIC_ASSERT(LanguageModeSize == 2);
  bool is_strict_ : 1;
765 766 767 768 769
  // This scope contains an 'eval' call.
  bool calls_eval_ : 1;
  // The context associated with this scope can be extended by a sloppy eval
  // called inside of it.
  bool sloppy_eval_can_extend_vars_ : 1;
770 771 772
  // This scope's declarations might not be executed in order (e.g., switch).
  bool scope_nonlinear_ : 1;
  bool is_hidden_ : 1;
773 774
  // Temporary workaround that allows masking of 'this' in debug-evaluate
  // scopes.
775 776 777 778 779 780 781 782 783
  bool is_debug_evaluate_scope_ : 1;

  // True if one of the inner scopes or the scope itself calls eval.
  bool inner_scope_calls_eval_ : 1;
  bool force_context_allocation_for_parameters_ : 1;

  // True if it holds 'var' declarations.
  bool is_declaration_scope_ : 1;

784 785 786 787 788
  // True if the outer scope is a class scope and should be skipped when
  // resolving private names, i.e. if the scope is in a class heritage
  // expression.
  bool private_name_lookup_skips_outer_class_ : 1;

789
  bool must_use_preparsed_scope_data_ : 1;
Simon Zünd's avatar
Simon Zünd committed
790 791 792 793

  // True if this is a script scope that originated from
  // DebugEvaluate::GlobalREPL().
  bool is_repl_mode_scope_ : 1;
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

  // True if this is a deserialized scope which caches its lookups on another
  // Scope's variable map. This will be true for every scope above the first
  // non-eval declaration scope above the compilation entry point, e.g. for
  //
  //     function f() {
  //       let g; // prevent sloppy block function hoisting.
  //       with({}) {
  //         function g() {
  //           try { throw 0; }
  //           catch { eval("f"); }
  //         }
  //         g();
  //       }
  //     }
  //
  // the compilation of the eval will have the "with" scope as the first scope
  // with this flag enabled.
  bool deserialized_scope_uses_external_cache_ : 1;
813 814
};

815
class V8_EXPORT_PRIVATE DeclarationScope : public Scope {
816 817
 public:
  DeclarationScope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
818
                   FunctionKind function_kind = kNormalFunction);
819
  DeclarationScope(Zone* zone, ScopeType scope_type,
820
                   Handle<ScopeInfo> scope_info);
821
  // Creates a script scope.
822 823
  DeclarationScope(Zone* zone, AstValueFactory* ast_value_factory,
                   REPLMode repl_mode = REPLMode::kNo);
824 825 826 827 828 829 830

  FunctionKind function_kind() const { return function_kind_; }

  bool is_arrow_scope() const {
    return is_function_scope() && IsArrowFunction(function_kind_);
  }

831
  // Inform the scope that the corresponding code uses "super".
832
  void RecordSuperPropertyUsage() {
833 834 835
    DCHECK(IsConciseMethod(function_kind()) ||
           IsAccessorFunction(function_kind()) ||
           IsClassConstructor(function_kind()));
836 837
    scope_uses_super_property_ = true;
  }
838

839
  // Does this scope access "super" property (super.foo).
840 841
  bool NeedsHomeObject() const {
    return scope_uses_super_property_ ||
842 843 844
           (inner_scope_calls_eval_ && (IsConciseMethod(function_kind()) ||
                                        IsAccessorFunction(function_kind()) ||
                                        IsClassConstructor(function_kind())));
845 846
  }

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
  // Inform the scope and outer scopes that the corresponding code contains an
  // eval call.
  void RecordDeclarationScopeEvalCall() {
    calls_eval_ = true;

    // If this isn't a sloppy eval, we don't care about it.
    if (language_mode() != LanguageMode::kSloppy) return;

    // Sloppy eval in script scopes can only introduce global variables anyway,
    // so we don't care that it calls sloppy eval.
    if (is_script_scope()) return;

    // Sloppy eval in a eval scope can only introduce variables into the outer
    // (non-eval) declaration scope, not into this eval scope.
    if (is_eval_scope()) {
#ifdef DEBUG
      // One of three things must be true:
      //   1. The outer non-eval declaration scope should already be marked as
      //      being extendable by sloppy eval, by the current sloppy eval rather
      //      than the inner one,
      //   2. The outer non-eval declaration scope is a script scope and thus
      //      isn't extendable anyway, or
      //   3. This is a debug evaluate and all bets are off.
      DeclarationScope* outer_decl_scope = outer_scope()->GetDeclarationScope();
      while (outer_decl_scope->is_eval_scope()) {
        outer_decl_scope = outer_decl_scope->GetDeclarationScope();
      }
      if (outer_decl_scope->is_debug_evaluate_scope()) {
        // Don't check anything.
        // TODO(9662): Figure out where variables declared by an eval inside a
        // debug-evaluate actually go.
      } else if (!outer_decl_scope->is_script_scope()) {
        DCHECK(outer_decl_scope->sloppy_eval_can_extend_vars_);
      }
#endif

      return;
    }

    sloppy_eval_can_extend_vars_ = true;
887
    num_heap_slots_ = Context::MIN_CONTEXT_EXTENDED_SLOTS;
888 889 890 891
  }

  bool sloppy_eval_can_extend_vars() const {
    return sloppy_eval_can_extend_vars_;
892 893
  }

894 895
  bool was_lazily_parsed() const { return was_lazily_parsed_; }

896 897
  Variable* LookupInModule(const AstRawString* name) {
    DCHECK(is_module_scope());
898
    Variable* var = variables_.Lookup(name);
899 900 901 902
    DCHECK_NOT_NULL(var);
    return var;
  }

903 904
  void DeserializeReceiver(AstValueFactory* ast_value_factory);

905 906 907 908 909 910
#ifdef DEBUG
  void set_is_being_lazily_parsed(bool is_being_lazily_parsed) {
    is_being_lazily_parsed_ = is_being_lazily_parsed;
  }
  bool is_being_lazily_parsed() const { return is_being_lazily_parsed_; }
#endif
911

912 913 914 915
  void set_zone(Zone* zone) {
#ifdef DEBUG
    needs_migration_ = true;
#endif
916 917
    // Migrate variables_' backing store to new zone.
    variables_ = VariableMap(variables_, zone);
918
  }
919

920 921 922 923 924 925
  // ---------------------------------------------------------------------------
  // Illegal redeclaration support.

  // Check if the scope has conflicting var
  // declarations, i.e. a var declaration that has been hoisted from a nested
  // scope over a let binding of the same name.
926 927
  Declaration* CheckConflictingVarDeclarations(
      bool* allowed_catch_binding_var_redeclaration);
928 929 930 931 932 933

  void set_has_checked_syntax(bool has_checked_syntax) {
    has_checked_syntax_ = has_checked_syntax;
  }
  bool has_checked_syntax() const { return has_checked_syntax_; }

934 935 936 937
  bool ShouldEagerCompile() const {
    return force_eager_compilation_ || should_eager_compile_;
  }

938 939
  void set_should_eager_compile();

940 941 942 943 944 945
  void SetScriptScopeInfo(Handle<ScopeInfo> scope_info) {
    DCHECK(is_script_scope());
    DCHECK(scope_info_.is_null());
    scope_info_ = scope_info;
  }

946 947
  bool is_asm_module() const { return is_asm_module_; }
  void set_is_asm_module();
948

949
  bool should_ban_arguments() const {
950
    return IsClassMembersInitializerFunction(function_kind());
951 952
  }

953 954 955 956 957
  void set_is_async_module() {
    DCHECK(IsModule(function_kind_));
    function_kind_ = kAsyncModule;
  }

958
  void DeclareThis(AstValueFactory* ast_value_factory);
959
  void DeclareArguments(AstValueFactory* ast_value_factory);
960 961 962 963 964
  void DeclareDefaultFunctionVariables(AstValueFactory* ast_value_factory);

  // Declare the function variable for a function literal. This variable
  // is in an intermediate scope between this function scope and the the
  // outer scope. Only possible for function scopes; at most one variable.
965 966 967 968 969
  //
  // This function needs to be called after all other variables have been
  // declared in the scope. It will add a variable for {name} to {variables_};
  // either the function variable itself, or a non-local in case the function
  // calls sloppy eval.
970 971
  Variable* DeclareFunctionVar(const AstRawString* name,
                               Scope* cache = nullptr);
972

973 974 975 976
  // Declare some special internal variables which must be accessible to
  // Ignition without ScopeInfo.
  Variable* DeclareGeneratorObjectVar(const AstRawString* name);

977 978 979 980
  // Declare a parameter in this scope.  When there are duplicated
  // parameters the rightmost one 'wins'.  However, the implementation
  // expects all parameters to be declared and from left to right.
  Variable* DeclareParameter(const AstRawString* name, VariableMode mode,
981
                             bool is_optional, bool is_rest,
982
                             AstValueFactory* ast_value_factory, int position);
983

984 985
  // Makes sure that num_parameters_ and has_rest is correct for the preparser.
  void RecordParameter(bool is_rest);
986

987 988 989 990
  // Declare an implicit global variable in this scope which must be a
  // script scope.  The variable was introduced (possibly from an inner
  // scope) by a reference to an unresolved variable with no intervening
  // with statements or eval calls.
991
  Variable* DeclareDynamicGlobal(const AstRawString* name,
992
                                 VariableKind variable_kind, Scope* cache);
993 994 995

  // The variable corresponding to the 'this' value.
  Variable* receiver() {
996
    DCHECK(has_this_declaration() || is_script_scope());
997 998 999 1000
    DCHECK_NOT_NULL(receiver_);
    return receiver_;
  }

1001
  bool has_this_declaration() const { return has_this_declaration_; }
1002 1003 1004 1005 1006

  // The variable corresponding to the 'new.target' value.
  Variable* new_target_var() { return new_target_; }

  // The variable holding the function literal for named function
1007
  // literals, or nullptr.  Only valid for function scopes.
1008
  Variable* function_var() const { return function_; }
1009

1010 1011
  // The variable holding the JSGeneratorObject for generator, async
  // and async generator functions, and modules. Only valid for
1012
  // function, module and REPL mode script scopes.
1013
  Variable* generator_object_var() const {
1014
    DCHECK(is_function_scope() || is_module_scope() || is_repl_mode_scope());
1015 1016 1017
    return GetRareVariable(RareVariable::kGeneratorObject);
  }

1018
  // Parameters. The left-most parameter has index 0.
1019
  // Only valid for function and module scopes.
1020
  Variable* parameter(int index) const {
1021
    DCHECK(is_function_scope() || is_module_scope());
1022
    DCHECK(!is_being_lazily_parsed_);
1023 1024 1025
    return params_[index];
  }

1026 1027 1028 1029 1030
  // Returns the number of formal parameters, excluding a possible rest
  // parameter.  Examples:
  //   function foo(a, b) {}         ==> 2
  //   function foo(a, b, ...c) {}   ==> 2
  //   function foo(a, b, c = 1) {}  ==> 3
1031
  int num_parameters() const { return num_parameters_; }
1032

1033
  // The function's rest parameter (nullptr if there is none).
1034
  Variable* rest_parameter() const {
1035
    return has_rest_ ? params_[params_.length() - 1] : nullptr;
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
  }

  bool has_simple_parameters() const { return has_simple_parameters_; }

  // TODO(caitp): manage this state in a better way. PreParser must be able to
  // communicate that the scope is non-simple, without allocating any parameters
  // as the Parser does. This is necessary to ensure that TC39's proposed early
  // error can be reported consistently regardless of whether lazily parsed or
  // not.
  void SetHasNonSimpleParameters() {
    DCHECK(is_function_scope());
    has_simple_parameters_ = false;
  }

1050 1051 1052 1053 1054 1055 1056 1057 1058
  void MakeParametersNonSimple() {
    SetHasNonSimpleParameters();
    for (ZoneHashMap::Entry* p = variables_.Start(); p != nullptr;
         p = variables_.Next(p)) {
      Variable* var = reinterpret_cast<Variable*>(p->value);
      if (var->is_parameter()) var->MakeParameterNonSimple();
    }
  }

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  // Returns whether the arguments object aliases formal parameters.
  CreateArgumentsType GetArgumentsType() const {
    DCHECK(is_function_scope());
    DCHECK(!is_arrow_scope());
    DCHECK_NOT_NULL(arguments_);
    return is_sloppy(language_mode()) && has_simple_parameters()
               ? CreateArgumentsType::kMappedArguments
               : CreateArgumentsType::kUnmappedArguments;
  }

1069 1070
  // The local variable 'arguments' if we need to allocate it; nullptr
  // otherwise.
1071
  Variable* arguments() const {
1072
    DCHECK_IMPLIES(is_arrow_scope(), arguments_ == nullptr);
1073 1074 1075 1076
    return arguments_;
  }

  Variable* this_function_var() const {
1077 1078
    Variable* this_function = GetRareVariable(RareVariable::kThisFunction);

1079
    // This is only used in derived constructors atm.
1080
    DCHECK(this_function == nullptr ||
1081 1082 1083
           (is_function_scope() && (IsClassConstructor(function_kind()) ||
                                    IsConciseMethod(function_kind()) ||
                                    IsAccessorFunction(function_kind()))));
1084
    return this_function;
1085 1086
  }

1087 1088
  // Adds a local variable in this scope's locals list. This is for adjusting
  // the scope of temporaries and do-expression vars when desugaring parameter
1089
  // initializers.
1090
  void AddLocal(Variable* var);
1091

1092
  void DeclareSloppyBlockFunction(
1093
      SloppyBlockFunctionStatement* sloppy_block_function);
verwaest's avatar
verwaest committed
1094

1095
  // Go through sloppy_block_functions_ and hoist those (into this scope)
1096
  // which should be hoisted.
1097
  void HoistSloppyBlockFunctions(AstNodeFactory* factory);
1098

1099 1100 1101
  // Compute top scope and allocate variables. For lazy compilation the top
  // scope only contains the single lazily compiled function, so this
  // doesn't re-allocate variables repeatedly.
1102
  //
1103
  // Returns false if private names can not be resolved and
1104 1105
  // ParseInfo's pending_error_handler will be populated with an
  // error. Otherwise, returns true.
1106
  V8_WARN_UNUSED_RESULT
1107
  static bool Analyze(ParseInfo* info);
1108 1109

  // To be called during parsing. Do just enough scope analysis that we can
1110 1111 1112 1113
  // discard the Scope contents for lazily compiled functions. In particular,
  // this records variables which cannot be resolved inside the Scope (we don't
  // yet know what they will resolve to since the outer Scopes are incomplete)
  // and recreates them with the correct Zone with ast_node_factory.
1114 1115
  void AnalyzePartially(Parser* parser, AstNodeFactory* ast_node_factory,
                        bool maybe_in_arrowhead);
1116

1117 1118
  // Allocate ScopeInfos for top scope and any inner scopes that need them.
  // Does nothing if ScopeInfo is already allocated.
1119
  template <typename LocalIsolate>
1120
  V8_EXPORT_PRIVATE static void AllocateScopeInfos(ParseInfo* info,
1121
                                                   LocalIsolate* isolate);
1122

1123
  Handle<StringSet> CollectNonLocals(Isolate* isolate,
verwaest's avatar
verwaest committed
1124 1125
                                     Handle<StringSet> non_locals);

1126 1127 1128 1129 1130 1131
  // Determine if we can use lazy compilation for this scope.
  bool AllowsLazyCompilation() const;

  // Make sure this closure and all outer closures are eagerly compiled.
  void ForceEagerCompilation() {
    DCHECK_EQ(this, GetClosureScope());
1132 1133
    DeclarationScope* s;
    for (s = this; !s->is_script_scope();
1134 1135 1136
         s = s->outer_scope()->GetClosureScope()) {
      s->force_eager_compilation_ = true;
    }
1137
    s->force_eager_compilation_ = true;
1138 1139
  }

1140 1141 1142 1143
#ifdef DEBUG
  void PrintParameters();
#endif

1144 1145 1146
  V8_INLINE void AllocateLocals();
  V8_INLINE void AllocateParameterLocals();
  V8_INLINE void AllocateReceiver();
1147

1148
  void ResetAfterPreparsing(AstValueFactory* ast_value_factory, bool aborted);
1149

1150 1151 1152 1153 1154
  bool is_skipped_function() const { return is_skipped_function_; }
  void set_is_skipped_function(bool is_skipped_function) {
    is_skipped_function_ = is_skipped_function;
  }

1155 1156 1157 1158 1159 1160 1161 1162
  bool has_inferred_function_name() const {
    return has_inferred_function_name_;
  }
  void set_has_inferred_function_name(bool value) {
    DCHECK(is_function_scope());
    has_inferred_function_name_ = value;
  }

1163 1164
  // Save data describing the context allocation of the variables in this scope
  // and its subscopes (except scopes at the laziness boundary). The data is
1165
  // saved in produced_preparse_data_.
1166
  void SavePreparseDataForDeclarationScope(Parser* parser);
1167

1168 1169
  void set_preparse_data_builder(PreparseDataBuilder* preparse_data_builder) {
    preparse_data_builder_ = preparse_data_builder;
1170 1171
  }

1172 1173
  PreparseDataBuilder* preparse_data_builder() const {
    return preparse_data_builder_;
1174 1175
  }

1176 1177
  void set_has_this_reference() { has_this_reference_ = true; }
  bool has_this_reference() const { return has_this_reference_; }
1178 1179 1180
  void UsesThis() {
    set_has_this_reference();
    GetReceiverScope()->receiver()->ForceContextAllocation();
1181 1182
  }

1183 1184 1185 1186 1187
  bool needs_private_name_context_chain_recalc() const {
    return needs_private_name_context_chain_recalc_;
  }
  void RecordNeedsPrivateNameContextChainRecalc();

Simon Zünd's avatar
Simon Zünd committed
1188 1189 1190 1191
  // Re-writes the {VariableLocation} of top-level 'let' bindings from CONTEXT
  // to REPL_GLOBAL. Should only be called on REPL scripts.
  void RewriteReplGlobalVariables();

1192
 private:
1193
  V8_INLINE void AllocateParameter(Variable* var, int index);
1194

1195 1196 1197 1198 1199 1200 1201 1202
  // Resolve and fill in the allocation information for all variables
  // in this scopes. Must be called *after* all scopes have been
  // processed (parsed) to ensure that unresolved variables can be
  // resolved properly.
  //
  // In the case of code compiled and run using 'eval', the context
  // parameter is the context in which eval was called.  In all other
  // cases the context parameter is an empty handle.
1203
  //
1204
  // Returns false if private names can not be resolved.
1205
  bool AllocateVariables(ParseInfo* info);
1206

1207 1208
  void SetDefaults();

1209 1210 1211 1212 1213 1214
  // Recalculate the private name context chain from the existing skip bit in
  // preparation for AllocateScopeInfos. Because the private name scope is
  // implemented with a skip bit for scopes in heritage position, that bit may
  // need to be recomputed due scopes that do not need contexts.
  void RecalcPrivateNameContextChain();

1215
  bool has_simple_parameters_ : 1;
1216
  // This scope contains an "use asm" annotation.
1217
  bool is_asm_module_ : 1;
1218
  bool force_eager_compilation_ : 1;
1219 1220
  // This function scope has a rest parameter.
  bool has_rest_ : 1;
1221 1222
  // This scope has a parameter called "arguments".
  bool has_arguments_parameter_ : 1;
1223 1224
  // This scope uses "super" property ('super.foo').
  bool scope_uses_super_property_ : 1;
1225
  bool should_eager_compile_ : 1;
1226 1227 1228 1229 1230
  // Set to true after we have finished lazy parsing the scope.
  bool was_lazily_parsed_ : 1;
#if DEBUG
  bool is_being_lazily_parsed_ : 1;
#endif
1231
  bool is_skipped_function_ : 1;
1232
  bool has_inferred_function_name_ : 1;
1233
  bool has_checked_syntax_ : 1;
1234 1235
  bool has_this_reference_ : 1;
  bool has_this_declaration_ : 1;
1236
  bool needs_private_name_context_chain_recalc_ : 1;
1237

1238
  // If the scope is a function scope, this is the function kind.
1239
  FunctionKind function_kind_;
1240

1241 1242
  int num_parameters_ = 0;

1243
  // Parameter list in source order.
1244
  ZonePtrList<Variable> params_;
1245
  // Map of function names to lists of functions defined in sloppy blocks
1246
  base::ThreadedList<SloppyBlockFunctionStatement> sloppy_block_functions_;
1247 1248 1249
  // Convenience variable.
  Variable* receiver_;
  // Function variable, if any; function scopes only.
1250
  Variable* function_;
1251 1252 1253 1254
  // new.target variable, function scopes only.
  Variable* new_target_;
  // Convenience variable; function scopes only.
  Variable* arguments_;
1255

1256
  // For producing the scope allocation data during preparsing.
1257
  PreparseDataBuilder* preparse_data_builder_;
1258

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  struct RareData : public ZoneObject {
    // Convenience variable; Subclass constructor only
    Variable* this_function = nullptr;

    // Generator object, if any; generator function scopes and module scopes
    // only.
    Variable* generator_object = nullptr;
  };

  enum class RareVariable {
    kThisFunction = offsetof(RareData, this_function),
    kGeneratorObject = offsetof(RareData, generator_object),
  };

  V8_INLINE RareData* EnsureRareData() {
    if (rare_data_ == nullptr) {
1275
      rare_data_ = zone()->New<RareData>();
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    }
    return rare_data_;
  }

  V8_INLINE Variable* GetRareVariable(RareVariable id) const {
    if (rare_data_ == nullptr) return nullptr;
    return *reinterpret_cast<Variable**>(
        reinterpret_cast<uint8_t*>(rare_data_) + static_cast<ptrdiff_t>(id));
  }

  // Set `var` to null if it's non-null and Predicate (Variable*) -> bool
  // returns true.
  template <typename Predicate>
  V8_INLINE void NullifyRareVariableIf(RareVariable id, Predicate predicate) {
    if (V8_LIKELY(rare_data_ == nullptr)) return;
    Variable** var = reinterpret_cast<Variable**>(
        reinterpret_cast<uint8_t*>(rare_data_) + static_cast<ptrdiff_t>(id));
    if (*var && predicate(*var)) *var = nullptr;
  }

  RareData* rare_data_ = nullptr;
1297 1298
};

1299 1300 1301 1302 1303 1304
void Scope::RecordEvalCall() {
  calls_eval_ = true;
  GetDeclarationScope()->RecordDeclarationScopeEvalCall();
  RecordInnerScopeEvalCall();
}

1305
Scope::Snapshot::Snapshot(Scope* scope)
1306
    : outer_scope_and_calls_eval_(scope, scope->calls_eval_),
1307
      top_inner_scope_(scope->inner_scope_),
1308
      top_unresolved_(scope->unresolved_list_.end()),
1309 1310
      top_local_(scope->GetClosureScope()->locals_.end()) {
  // Reset in order to record eval calls during this Snapshot's lifetime.
1311 1312 1313
  outer_scope_and_calls_eval_.GetPointer()->calls_eval_ = false;
  outer_scope_and_calls_eval_.GetPointer()->sloppy_eval_can_extend_vars_ =
      false;
1314 1315
}

1316 1317
class ModuleScope final : public DeclarationScope {
 public:
1318
  ModuleScope(DeclarationScope* script_scope, AstValueFactory* avfactory);
1319

1320
  // Deserialization. Does not restore the module descriptor.
1321
  ModuleScope(Isolate* isolate, Handle<ScopeInfo> scope_info,
1322
              AstValueFactory* avfactory);
1323

1324
  // Returns nullptr in a deserialized scope.
1325
  SourceTextModuleDescriptor* module() const { return module_descriptor_; }
1326

1327 1328 1329
  // Set MODULE as VariableLocation for all variables that will live in a
  // module's export table.
  void AllocateModuleVariables();
1330 1331

 private:
1332
  SourceTextModuleDescriptor* const module_descriptor_;
1333 1334
};

1335 1336
class V8_EXPORT_PRIVATE ClassScope : public Scope {
 public:
1337
  ClassScope(Zone* zone, Scope* outer_scope, bool is_anonymous);
1338
  // Deserialization.
1339
  ClassScope(Isolate* isolate, Zone* zone, AstValueFactory* ast_value_factory,
1340
             Handle<ScopeInfo> scope_info);
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
  struct HeritageParsingScope {
    explicit HeritageParsingScope(ClassScope* class_scope)
        : class_scope_(class_scope) {
      class_scope_->SetIsParsingHeritage(true);
    }
    ~HeritageParsingScope() { class_scope_->SetIsParsingHeritage(false); }

   private:
    ClassScope* class_scope_;
  };

1353 1354
  // Declare a private name in the private name map and add it to the
  // local variables of this scope.
1355
  Variable* DeclarePrivateName(const AstRawString* name, VariableMode mode,
1356
                               IsStaticFlag is_static_flag, bool* was_added);
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385

  // Try resolving all unresolved private names found in the current scope.
  // Called from DeclarationScope::AllocateVariables() when reparsing a
  // method to generate code or when eval() is called to access private names.
  // If there are any private names that cannot be resolved, returns false.
  V8_WARN_UNUSED_RESULT bool ResolvePrivateNames(ParseInfo* info);

  // Called after the entire class literal is parsed.
  // - If we are certain a private name cannot be resolve, return that
  //   variable proxy.
  // - If we find the private name in the scope chain, return nullptr.
  //   If the name is found in the current class scope, resolve it
  //   immediately.
  // - If we are not sure if the private name can be resolved or not yet,
  //   return nullptr.
  VariableProxy* ResolvePrivateNamesPartially();

  // Get the current tail of unresolved private names to be used to
  // reset the tail.
  UnresolvedList::Iterator GetUnresolvedPrivateNameTail();

  // Reset the tail of unresolved private names, discard everything
  // between the tail passed into this method and the current tail.
  void ResetUnresolvedPrivateNameTail(UnresolvedList::Iterator tail);

  // Migrate private names added between the tail passed into this method
  // and the current tail.
  void MigrateUnresolvedPrivateNameTail(AstNodeFactory* ast_node_factory,
                                        UnresolvedList::Iterator tail);
1386
  Variable* DeclareBrandVariable(AstValueFactory* ast_value_factory,
1387
                                 IsStaticFlag is_static_flag,
1388
                                 int class_token_pos);
1389 1390 1391 1392

  Variable* DeclareClassVariable(AstValueFactory* ast_value_factory,
                                 const AstRawString* name, int class_token_pos);

1393
  Variable* brand() {
1394 1395 1396
    return GetRareData() == nullptr ? nullptr : GetRareData()->brand;
  }

1397 1398
  Variable* class_variable() { return class_variable_; }

1399 1400
  V8_INLINE bool IsParsingHeritage() {
    return rare_data_and_is_parsing_heritage_.GetPayload();
1401
  }
1402

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
  // Only maintained when the scope is parsed, not when the scope is
  // deserialized.
  bool has_static_private_methods() const {
    return has_static_private_methods_;
  }

  // Returns whether the index of class variable of this class scope should be
  // recorded in the ScopeInfo.
  // If any inner scope accesses static private names directly, the class
  // variable will be forced to be context-allocated.
  // The inner scope may also calls eval which may results in access to
  // static private names.
  // Only maintained when the scope is parsed.
  bool should_save_class_variable_index() const {
    return should_save_class_variable_index_ ||
           has_explicit_static_private_methods_access_ ||
           (has_static_private_methods_ && inner_scope_calls_eval_);
  }

  // Only maintained when the scope is parsed.
  bool is_anonymous_class() const { return is_anonymous_class_; }

  // Overriden during reparsing
  void set_should_save_class_variable_index() {
    should_save_class_variable_index_ = true;
  }

1430 1431
 private:
  friend class Scope;
1432 1433
  friend class PrivateNameScopeIterator;

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
  // Find the private name declared in the private name map first,
  // if it cannot be found there, try scope info if there is any.
  // Returns nullptr if it cannot be found.
  Variable* LookupPrivateName(VariableProxy* proxy);
  // Lookup a private name from the local private name map of the current
  // scope.
  Variable* LookupLocalPrivateName(const AstRawString* name);
  // Lookup a private name from the scope info of the current scope.
  Variable* LookupPrivateNameInScopeInfo(const AstRawString* name);

  struct RareData : public ZoneObject {
    explicit RareData(Zone* zone) : private_name_map(zone) {}
    UnresolvedList unresolved_private_names;
    VariableMap private_name_map;
1448
    Variable* brand = nullptr;
1449 1450
  };

1451 1452 1453
  V8_INLINE RareData* GetRareData() {
    return rare_data_and_is_parsing_heritage_.GetPointer();
  }
1454
  V8_INLINE RareData* EnsureRareData() {
1455
    if (GetRareData() == nullptr) {
1456
      rare_data_and_is_parsing_heritage_.SetPointer(
1457
          zone()->New<RareData>(zone()));
1458
    }
1459 1460 1461 1462
    return GetRareData();
  }
  V8_INLINE void SetIsParsingHeritage(bool v) {
    rare_data_and_is_parsing_heritage_.SetPayload(v);
1463 1464
  }

1465
  PointerWithPayload<RareData, bool, 1> rare_data_and_is_parsing_heritage_;
1466 1467 1468 1469 1470 1471 1472 1473 1474
  Variable* class_variable_ = nullptr;
  // These are only maintained when the scope is parsed, not when the
  // scope is deserialized.
  bool has_static_private_methods_ = false;
  bool has_explicit_static_private_methods_access_ = false;
  bool is_anonymous_class_ = false;
  // This is only maintained during reparsing, restored from the
  // preparsed data.
  bool should_save_class_variable_index_ = false;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
};

// Iterate over the private name scope chain. The iteration proceeds from the
// innermost private name scope outwards.
class PrivateNameScopeIterator {
 public:
  explicit PrivateNameScopeIterator(Scope* start);

  bool Done() const { return current_scope_ == nullptr; }
  void Next();

  // Add an unresolved private name to the current scope.
  void AddUnresolvedPrivateName(VariableProxy* proxy);

  ClassScope* GetScope() const {
    DCHECK(!Done());
    return current_scope_->AsClassScope();
  }

 private:
  bool skipped_any_scopes_ = false;
  Scope* start_scope_;
  Scope* current_scope_;
1498 1499
};

1500 1501
}  // namespace internal
}  // namespace v8
1502

1503
#endif  // V8_AST_SCOPES_H_