scopes.h 53.1 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
#include "src/ast/ast.h"
10
#include "src/base/compiler-specific.h"
lpy's avatar
lpy committed
11
#include "src/base/hashmap.h"
12
#include "src/base/threaded-list.h"
13
#include "src/common/globals.h"
14 15
#include "src/objects/function-kind.h"
#include "src/objects/objects.h"
16
#include "src/utils/pointer-with-payload.h"
17
#include "src/utils/utils.h"
18
#include "src/zone/zone.h"
19

20 21
namespace v8 {
namespace internal {
22

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

35 36
using UnresolvedList =
    base::ThreadedList<VariableProxy, VariableProxy::UnresolvedNext>;
37

38
// A hash map to support fast variable declaration and lookup.
39
class VariableMap : public ZoneHashMap {
40
 public:
41
  explicit VariableMap(Zone* zone);
42

43 44 45
  Variable* Declare(Zone* zone, Scope* scope, const AstRawString* name,
                    VariableMode mode, VariableKind kind,
                    InitializationFlag initialization_flag,
46
                    MaybeAssignedFlag maybe_assigned_flag,
47
                    IsStaticFlag is_static_flag, bool* was_added);
48

49
  V8_EXPORT_PRIVATE Variable* Lookup(const AstRawString* name);
50
  void Remove(Variable* var);
51
  void Add(Zone* zone, Variable* var);
52 53
};

54 55 56 57 58 59 60
class Scope;

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

61 62 63 64 65 66 67 68 69
// 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.

70 71 72 73
// 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.
74
class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
75 76 77 78
 public:
  // ---------------------------------------------------------------------------
  // Construction

79 80 81 82 83 84 85 86 87 88 89
  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;
90 91
  ModuleScope* AsModuleScope();
  const ModuleScope* AsModuleScope() const;
92 93
  ClassScope* AsClassScope();
  const ClassScope* AsClassScope() const;
94

95
  class Snapshot final {
96
   public:
97 98 99
    Snapshot()
        : outer_scope_and_calls_eval_(nullptr, false),
          top_unresolved_(),
100 101 102
          top_local_() {
      DCHECK(IsCleared());
    }
103
    inline explicit Snapshot(Scope* scope);
104

105
    ~Snapshot() {
106 107 108 109 110
      // 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();
111 112
      }
    }
113

114
    void RestoreEvalFlag() {
115 116 117 118
      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();
      }
119 120 121 122 123 124
    }

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

126 127 128 129 130 131 132 133 134 135
    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
    }

136
   private:
137 138 139 140
    // 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.
141
    PointerWithPayload<Scope, bool, 1> outer_scope_and_calls_eval_;
142
    Scope* top_inner_scope_;
143
    UnresolvedList::Iterator top_unresolved_;
144
    base::ThreadedList<Variable>::Iterator top_local_;
145 146 147 148

    // Disallow copy and move.
    Snapshot(const Snapshot&) = delete;
    Snapshot(Snapshot&&) = delete;
149 150
  };

151
  enum class DeserializationMode { kIncludingVariables, kScopesOnly };
152

153
  static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone,
154
                                      ScopeInfo scope_info,
155
                                      DeclarationScope* script_scope,
156 157
                                      AstValueFactory* ast_value_factory,
                                      DeserializationMode deserialization_mode);
158

159 160 161 162 163
  // 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();

164
  // Inserts outer_scope into this scope's scope chain (and removes this
165
  // from the current outer_scope_'s inner scope list).
166 167 168
  // Assumes outer_scope_ is non-null.
  void ReplaceOuterScope(Scope* outer_scope);

verwaest's avatar
verwaest committed
169
  Zone* zone() const { return zone_; }
170

171
  void SetMustUsePreparseData() {
172 173 174 175 176
    if (must_use_preparsed_scope_data_) {
      return;
    }
    must_use_preparsed_scope_data_ = true;
    if (outer_scope_) {
177
      outer_scope_->SetMustUsePreparseData();
178 179 180 181 182 183 184
    }
  }

  bool must_use_preparsed_scope_data() const {
    return must_use_preparsed_scope_data_;
  }

185 186 187
  // ---------------------------------------------------------------------------
  // Declarations

188 189
  // Lookup a variable in this scope. Returns the variable or nullptr if not
  // found.
190
  Variable* LookupLocal(const AstRawString* name) {
191 192
    DCHECK(scope_info_.is_null());
    return variables_.Lookup(name);
193 194
  }

195
  Variable* LookupInScopeInfo(const AstRawString* name, Scope* cache);
196

197
  // Declare a local variable in this scope. If the variable has been
198
  // declared before, the previously declared variable is returned.
199
  Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
200
                         VariableKind kind, bool* was_added,
201
                         InitializationFlag init_flag = kCreatedInitialized);
202

203 204
  Variable* DeclareVariable(Declaration* declaration, const AstRawString* name,
                            int pos, VariableMode mode, VariableKind kind,
205 206 207
                            InitializationFlag init, bool* was_added,
                            bool* sloppy_mode_block_scope_function_redefinition,
                            bool* ok);
marja's avatar
marja committed
208

209 210 211 212
  // Returns nullptr if there was a declaration conflict.
  Variable* DeclareVariableName(const AstRawString* name, VariableMode mode,
                                bool* was_added,
                                VariableKind kind = NORMAL_VARIABLE);
213
  Variable* DeclareCatchVariableName(const AstRawString* name);
214

215
  // Declarations list.
216
  base::ThreadedList<Declaration>* declarations() { return &decls_; }
217

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

220
  // Create a new unresolved variable.
221
  VariableProxy* NewUnresolved(AstNodeFactory* factory,
222
                               const AstRawString* name, int start_pos,
223 224 225 226 227 228 229
                               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);
230
    AddUnresolved(proxy);
231 232
    return proxy;
  }
233

234
  void AddUnresolved(VariableProxy* proxy);
235

236 237 238
  // 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.
239
  bool RemoveUnresolved(VariableProxy* var);
240

241 242 243 244 245 246 247 248 249
  // 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);

250 251 252 253 254
  // 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.
255
  // TODO(verwaest): Move to DeclarationScope?
256
  Variable* NewTemporary(const AstRawString* name);
257

258 259 260 261 262 263 264
  // 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);
265

266 267 268
  // ---------------------------------------------------------------------------
  // Scope-specific info.

269
  // Inform the scope and outer scopes that the corresponding code contains an
270
  // eval call.
271
  inline void RecordEvalCall();
272 273

  void RecordInnerScopeEvalCall() {
274
    inner_scope_calls_eval_ = true;
275
    for (Scope* scope = outer_scope(); scope != nullptr;
276
         scope = scope->outer_scope()) {
277
      if (scope->inner_scope_calls_eval_) return;
278 279 280
      scope->inner_scope_calls_eval_ = true;
    }
  }
281

282 283
  // Set the language mode flag (unless disabled by a global flag).
  void SetLanguageMode(LanguageMode language_mode) {
284
    DCHECK(!is_module_scope() || is_strict(language_mode));
285
    set_language_mode(language_mode);
286
  }
287

288 289 290 291 292 293 294 295 296 297 298
  // 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; }

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  // 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'
321 322 323 324
  // * For the scope of a switch statement
  //     switch (tag) { cases }
  //   start position: start position of '{'
  //   end position: end position of '}'
325 326 327 328 329 330 331 332 333
  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_; }
  void set_end_position(int statement_pos) {
    end_position_ = statement_pos;
  }

334 335 336 337
  // 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; }

338 339 340 341 342 343 344
  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_;
  }
345

346 347 348 349
  // ---------------------------------------------------------------------------
  // Predicates.

  // Specific scope types.
350
  bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
351
  bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
352
  bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
353
  bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
354
  bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
355 356 357
  bool is_block_scope() const {
    return scope_type_ == BLOCK_SCOPE || scope_type_ == CLASS_SCOPE;
  }
358
  bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
359
  bool is_declaration_scope() const { return is_declaration_scope_; }
360
  bool is_class_scope() const { return scope_type_ == CLASS_SCOPE; }
361

362
  bool inner_scope_calls_eval() const { return inner_scope_calls_eval_; }
363 364 365
  bool private_name_lookup_skips_outer_class() const {
    return private_name_lookup_skips_outer_class_;
  }
366
  bool IsAsmModule() const;
367 368 369
  // Returns true if this scope or any inner scopes that might be eagerly
  // compiled are asm modules.
  bool ContainsAsmModule() const;
370 371
  // Does this scope have the potential to execute declarations non-linearly?
  bool is_nonlinear() const { return scope_nonlinear_; }
372 373 374 375 376 377 378 379 380 381 382 383 384
  // 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());
  }
385

386
  // Whether this needs to be represented by a runtime context.
387
  bool NeedsContext() const {
388
    // Catch scopes always have heap slots.
389 390
    DCHECK_IMPLIES(is_catch_scope(), num_heap_slots() > 0);
    DCHECK_IMPLIES(is_with_scope(), num_heap_slots() > 0);
391
    DCHECK_IMPLIES(ForceContextForLanguageMode(), num_heap_slots() > 0);
392
    return num_heap_slots() > 0;
393
  }
394

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  // 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
  };

422 423 424
  // ---------------------------------------------------------------------------
  // Accessors.

425
  // The type of this scope.
426
  ScopeType scope_type() const { return scope_type_; }
427

428
  // The language mode of this scope.
429 430 431
  LanguageMode language_mode() const {
    return is_strict_ ? LanguageMode::kStrict : LanguageMode::kSloppy;
  }
432

433 434 435 436 437
  // 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_; }
438

439
  // The scope immediately surrounding this scope, or nullptr.
440 441
  Scope* outer_scope() const { return outer_scope_; }

442
  Variable* catch_variable() const {
443
    DCHECK(is_catch_scope());
444
    DCHECK_EQ(1, num_var());
445
    return static_cast<Variable*>(variables_.Start()->value);
446 447
  }

448 449
  bool ShouldBanArguments();

450 451 452 453
  // ---------------------------------------------------------------------------
  // Variable allocation.

  // Result of variable allocation.
454 455
  int num_stack_slots() const { return num_stack_slots_; }
  int num_heap_slots() const { return num_heap_slots_; }
456

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  bool HasContextExtension() const {
    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 {
    return HasContextExtension() ? Context::MIN_CONTEXT_EXTENDED_SLOTS
                                 : Context::MIN_CONTEXT_SLOTS;
  }

477 478
  int ContextLocalCount() const;

479 480
  // Determine if we can parse a function literal in this scope lazily without
  // caring about the unresolved variables within.
481
  bool AllowsLazyParsingWithoutUnresolvedVariables(const Scope* outer) const;
482

483
  // The number of contexts between this and scope; zero if this == scope.
484 485 486
  int ContextChainLength(Scope* scope) const;

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

490 491
  // Find the first function, script, eval or (declaration) block scope. This is
  // the scope where var declarations will be hoisted to in the implementation.
492
  DeclarationScope* GetDeclarationScope();
493

494
  // Find the first non-block declaration scope. This should be either a script,
495 496 497 498 499
  // 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();
500
  const DeclarationScope* GetClosureScope() const;
501

502 503
  // Find the first (non-arrow) function or script scope.  This is where
  // 'this' is bound, and what determines the function kind.
504
  DeclarationScope* GetReceiverScope();
505

506 507 508
  // Find the innermost outer scope that needs a context.
  Scope* GetOuterScopeWithContext();

509 510
  bool HasThisReference() const;

511
  // Analyze() must have been called once to create the ScopeInfo.
512
  Handle<ScopeInfo> scope_info() const {
513 514 515 516
    DCHECK(!scope_info_.is_null());
    return scope_info_;
  }

517 518
  int num_var() const { return variables_.occupancy(); }

519 520 521 522 523
  // ---------------------------------------------------------------------------
  // Debugging.

#ifdef DEBUG
  void Print(int n = 0);  // n = indentation; n < 0 => don't print recursively
524 525 526

  // Check that the scope has positions assigned.
  void CheckScopePositions();
527 528 529

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

532 533
  // Retrieve `IsSimpleParameterList` of current or outer function.
  bool HasSimpleParameters();
534
  void set_is_debug_evaluate_scope() { is_debug_evaluate_scope_ = true; }
535
  bool is_debug_evaluate_scope() const { return is_debug_evaluate_scope_; }
536
  bool IsSkippableFunctionScope();
537

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
  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;
  }

554 555 556 557 558 559
  Variable* LookupInScopeOrScopeInfo(const AstRawString* name) {
    Variable* var = variables_.Lookup(name);
    if (var != nullptr || scope_info_.is_null()) return var;
    return LookupInScopeInfo(name, this);
  }

560 561
  Variable* LookupForTesting(const AstRawString* name) {
    for (Scope* scope = this; scope != nullptr; scope = scope->outer_scope()) {
562
      Variable* var = scope->LookupInScopeOrScopeInfo(name);
563 564 565 566 567
      if (var != nullptr) return var;
    }
    return nullptr;
  }

568
 protected:
569
  explicit Scope(Zone* zone);
570

571
  void set_language_mode(LanguageMode language_mode) {
572
    is_strict_ = is_strict(language_mode);
573 574
  }

575
 private:
576 577 578
  Variable* Declare(Zone* zone, const AstRawString* name, VariableMode mode,
                    VariableKind kind, InitializationFlag initialization_flag,
                    MaybeAssignedFlag maybe_assigned_flag, bool* was_added) {
579 580 581 582
    // 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);
583 584
    if (*was_added) locals_.Add(result);
    return result;
585
  }
586 587 588 589 590

  // 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.
591
  bool NeedsScopeInfo() const;
592

593 594
  Variable* NewTemporary(const AstRawString* name,
                         MaybeAssignedFlag maybe_assigned);
595 596

  // Walk the scope chain to find DeclarationScopes; call
597
  // SavePreparseDataForDeclarationScope for each.
598
  void SavePreparseData(Parser* parser);
599

600 601
  // Create a non-local variable with a given name.
  // These variables are looked up dynamically at runtime.
602
  Variable* NonLocal(const AstRawString* name, VariableMode mode);
603

604 605 606 607 608
  enum ScopeLookupMode {
    kParsedScope,
    kDeserializedScope,
  };

609
  // Variable resolution.
610 611 612 613
  // 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'.
614
  template <ScopeLookupMode mode>
615
  static Variable* Lookup(VariableProxy* proxy, Scope* scope,
616
                          Scope* outer_scope_end, Scope* entry_point = nullptr,
617
                          bool force_context_allocation = false);
618
  static Variable* LookupWith(VariableProxy* proxy, Scope* scope,
619
                              Scope* outer_scope_end, Scope* entry_point,
620
                              bool force_context_allocation);
621
  static Variable* LookupSloppyEval(VariableProxy* proxy, Scope* scope,
622
                                    Scope* outer_scope_end, Scope* entry_point,
623
                                    bool force_context_allocation);
624
  static void ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
625
                                       Scope* end);
626
  void ResolveTo(ParseInfo* info, VariableProxy* proxy, Variable* var);
627
  void ResolveVariable(ParseInfo* info, VariableProxy* proxy);
628
  V8_WARN_UNUSED_RESULT bool ResolveVariablesRecursively(ParseInfo* info);
629

verwaest's avatar
verwaest committed
630 631
  // Finds free variables of this scope. This mutates the unresolved variables
  // list along the way, so full resolution cannot be done afterwards.
632 633
  void AnalyzePartially(DeclarationScope* max_outer_scope,
                        AstNodeFactory* ast_node_factory,
634 635
                        UnresolvedList* new_unresolved_list,
                        bool maybe_in_arrowhead);
636 637
  void CollectNonLocals(DeclarationScope* max_outer_scope, Isolate* isolate,
                        ParseInfo* info, Handle<StringSet>* non_locals);
638

639 640 641 642 643 644
  // Predicates.
  bool MustAllocate(Variable* var);
  bool MustAllocateInContext(Variable* var);

  // Variable allocation.
  void AllocateStackSlot(Variable* var);
645
  V8_INLINE void AllocateHeapSlot(Variable* var);
646 647
  void AllocateNonParameterLocal(Variable* var);
  void AllocateDeclaredGlobal(Variable* var);
648
  V8_INLINE void AllocateNonParameterLocalsAndDeclaredGlobals();
649
  void AllocateVariablesRecursively();
650

651
  void AllocateScopeInfosRecursively(Isolate* isolate,
jochen's avatar
jochen committed
652
                                     MaybeHandle<ScopeInfo> outer_scope);
653

654 655
  void AllocateDebuggerScopeInfos(Isolate* isolate,
                                  MaybeHandle<ScopeInfo> outer_scope);
656

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

660
  // Construct a catch scope with a binding for the name.
661
  Scope(Zone* zone, const AstRawString* catch_variable_name,
662
        MaybeAssignedFlag maybe_assigned, Handle<ScopeInfo> scope_info);
663

664
  void AddInnerScope(Scope* inner_scope) {
665 666 667
    inner_scope->sibling_ = inner_scope_;
    inner_scope_ = inner_scope;
    inner_scope->outer_scope_ = this;
668 669
  }

670
  void SetDefaults();
671

672
  friend class DeclarationScope;
673
  friend class ClassScope;
674
  friend class ScopeTestHelper;
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

  Zone* zone_;

  // 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.
  Handle<ScopeInfo> scope_info_;
// 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;
728 729 730 731 732
  // 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;
733 734 735
  // This scope's declarations might not be executed in order (e.g., switch).
  bool scope_nonlinear_ : 1;
  bool is_hidden_ : 1;
736 737
  // Temporary workaround that allows masking of 'this' in debug-evaluate
  // scopes.
738 739 740 741 742 743 744 745 746
  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;

747 748 749 750 751
  // 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;

752
  bool must_use_preparsed_scope_data_ : 1;
753 754
};

755
class V8_EXPORT_PRIVATE DeclarationScope : public Scope {
756 757
 public:
  DeclarationScope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
758
                   FunctionKind function_kind = kNormalFunction);
759
  DeclarationScope(Zone* zone, ScopeType scope_type,
760
                   Handle<ScopeInfo> scope_info);
761
  // Creates a script scope.
762
  DeclarationScope(Zone* zone, AstValueFactory* ast_value_factory);
763 764 765 766 767 768 769

  FunctionKind function_kind() const { return function_kind_; }

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

770
  // Inform the scope that the corresponding code uses "super".
771
  void RecordSuperPropertyUsage() {
772 773 774
    DCHECK(IsConciseMethod(function_kind()) ||
           IsAccessorFunction(function_kind()) ||
           IsClassConstructor(function_kind()));
775 776
    scope_uses_super_property_ = true;
  }
777

778
  // Does this scope access "super" property (super.foo).
779 780
  bool NeedsHomeObject() const {
    return scope_uses_super_property_ ||
781 782 783
           (inner_scope_calls_eval_ && (IsConciseMethod(function_kind()) ||
                                        IsAccessorFunction(function_kind()) ||
                                        IsClassConstructor(function_kind())));
784 785
  }

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  // 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;
826
    num_heap_slots_ = Context::MIN_CONTEXT_EXTENDED_SLOTS;
827 828 829 830
  }

  bool sloppy_eval_can_extend_vars() const {
    return sloppy_eval_can_extend_vars_;
831 832
  }

833 834
  bool was_lazily_parsed() const { return was_lazily_parsed_; }

835 836
  Variable* LookupInModule(const AstRawString* name) {
    DCHECK(is_module_scope());
837
    Variable* var = variables_.Lookup(name);
838 839 840 841
    DCHECK_NOT_NULL(var);
    return var;
  }

842 843
  void DeserializeReceiver(AstValueFactory* ast_value_factory);

844 845 846 847 848 849
#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
850 851 852 853 854 855
  void set_zone(Zone* zone) {
#ifdef DEBUG
    needs_migration_ = true;
#endif
    zone_ = zone;
  }
856

857 858 859 860 861 862 863 864 865 866 867 868 869
  // ---------------------------------------------------------------------------
  // 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.
  Declaration* CheckConflictingVarDeclarations();

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

870 871 872 873
  bool ShouldEagerCompile() const {
    return force_eager_compilation_ || should_eager_compile_;
  }

874 875
  void set_should_eager_compile();

876 877 878 879 880 881
  void SetScriptScopeInfo(Handle<ScopeInfo> scope_info) {
    DCHECK(is_script_scope());
    DCHECK(scope_info_.is_null());
    scope_info_ = scope_info;
  }

882 883
  bool is_asm_module() const { return is_asm_module_; }
  void set_is_asm_module();
884

885
  bool should_ban_arguments() const {
886
    return IsClassMembersInitializerFunction(function_kind());
887 888
  }

889 890 891 892 893
  void set_is_async_module() {
    DCHECK(IsModule(function_kind_));
    function_kind_ = kAsyncModule;
  }

894
  void DeclareThis(AstValueFactory* ast_value_factory);
895
  void DeclareArguments(AstValueFactory* ast_value_factory);
896 897 898 899 900
  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.
901 902 903 904 905
  //
  // 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.
906 907
  Variable* DeclareFunctionVar(const AstRawString* name,
                               Scope* cache = nullptr);
908

909 910 911 912
  // Declare some special internal variables which must be accessible to
  // Ignition without ScopeInfo.
  Variable* DeclareGeneratorObjectVar(const AstRawString* name);

913 914 915 916
  // 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,
917
                             bool is_optional, bool is_rest,
918
                             AstValueFactory* ast_value_factory, int position);
919

920 921
  // Makes sure that num_parameters_ and has_rest is correct for the preparser.
  void RecordParameter(bool is_rest);
922

923 924 925 926
  // 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.
927
  Variable* DeclareDynamicGlobal(const AstRawString* name,
928
                                 VariableKind variable_kind, Scope* cache);
929 930 931

  // The variable corresponding to the 'this' value.
  Variable* receiver() {
932
    DCHECK(has_this_declaration() || is_script_scope());
933 934 935 936
    DCHECK_NOT_NULL(receiver_);
    return receiver_;
  }

937
  bool has_this_declaration() const { return has_this_declaration_; }
938 939 940 941 942

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

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

946 947 948
  // The variable holding the JSGeneratorObject for generator, async
  // and async generator functions, and modules. Only valid for
  // function and module scopes.
949 950 951 952 953
  Variable* generator_object_var() const {
    DCHECK(is_function_scope() || is_module_scope());
    return GetRareVariable(RareVariable::kGeneratorObject);
  }

954
  // Parameters. The left-most parameter has index 0.
955
  // Only valid for function and module scopes.
956
  Variable* parameter(int index) const {
957
    DCHECK(is_function_scope() || is_module_scope());
958
    DCHECK(!is_being_lazily_parsed_);
959 960 961
    return params_[index];
  }

962 963 964 965 966
  // 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
967
  int num_parameters() const { return num_parameters_; }
968

969
  // The function's rest parameter (nullptr if there is none).
970
  Variable* rest_parameter() const {
971
    return has_rest_ ? params_[params_.length() - 1] : nullptr;
972 973 974 975 976 977 978 979 980 981 982 983 984 985
  }

  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;
  }

986 987 988 989 990 991 992 993 994
  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();
    }
  }

995 996 997 998 999 1000 1001 1002 1003 1004
  // 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;
  }

1005 1006
  // The local variable 'arguments' if we need to allocate it; nullptr
  // otherwise.
1007
  Variable* arguments() const {
1008
    DCHECK_IMPLIES(is_arrow_scope(), arguments_ == nullptr);
1009 1010 1011 1012
    return arguments_;
  }

  Variable* this_function_var() const {
1013 1014
    Variable* this_function = GetRareVariable(RareVariable::kThisFunction);

1015
    // This is only used in derived constructors atm.
1016
    DCHECK(this_function == nullptr ||
1017 1018 1019
           (is_function_scope() && (IsClassConstructor(function_kind()) ||
                                    IsConciseMethod(function_kind()) ||
                                    IsAccessorFunction(function_kind()))));
1020
    return this_function;
1021 1022
  }

1023 1024
  // 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
1025
  // initializers.
1026
  void AddLocal(Variable* var);
1027

1028
  void DeclareSloppyBlockFunction(
1029
      SloppyBlockFunctionStatement* sloppy_block_function);
verwaest's avatar
verwaest committed
1030

1031
  // Go through sloppy_block_functions_ and hoist those (into this scope)
1032
  // which should be hoisted.
1033
  void HoistSloppyBlockFunctions(AstNodeFactory* factory);
1034

1035 1036 1037
  // 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.
1038
  //
1039
  // Returns false if private names can not be resolved and
1040 1041
  // ParseInfo's pending_error_handler will be populated with an
  // error. Otherwise, returns true.
1042
  V8_WARN_UNUSED_RESULT
1043
  static bool Analyze(ParseInfo* info);
1044 1045

  // To be called during parsing. Do just enough scope analysis that we can
1046 1047 1048 1049
  // 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.
1050 1051
  void AnalyzePartially(Parser* parser, AstNodeFactory* ast_node_factory,
                        bool maybe_in_arrowhead);
1052

1053 1054
  // Allocate ScopeInfos for top scope and any inner scopes that need them.
  // Does nothing if ScopeInfo is already allocated.
1055
  static void AllocateScopeInfos(ParseInfo* info, Isolate* isolate);
1056

1057
  Handle<StringSet> CollectNonLocals(Isolate* isolate, ParseInfo* info,
verwaest's avatar
verwaest committed
1058 1059
                                     Handle<StringSet> non_locals);

1060 1061 1062 1063 1064 1065
  // 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());
1066 1067
    DeclarationScope* s;
    for (s = this; !s->is_script_scope();
1068 1069 1070
         s = s->outer_scope()->GetClosureScope()) {
      s->force_eager_compilation_ = true;
    }
1071
    s->force_eager_compilation_ = true;
1072 1073
  }

1074 1075 1076 1077
#ifdef DEBUG
  void PrintParameters();
#endif

1078 1079 1080
  V8_INLINE void AllocateLocals();
  V8_INLINE void AllocateParameterLocals();
  V8_INLINE void AllocateReceiver();
1081

1082
  void ResetAfterPreparsing(AstValueFactory* ast_value_factory, bool aborted);
1083

1084 1085 1086 1087 1088
  bool is_skipped_function() const { return is_skipped_function_; }
  void set_is_skipped_function(bool is_skipped_function) {
    is_skipped_function_ = is_skipped_function;
  }

1089 1090 1091 1092 1093 1094 1095 1096
  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;
  }

1097 1098
  // Save data describing the context allocation of the variables in this scope
  // and its subscopes (except scopes at the laziness boundary). The data is
1099
  // saved in produced_preparse_data_.
1100
  void SavePreparseDataForDeclarationScope(Parser* parser);
1101

1102 1103
  void set_preparse_data_builder(PreparseDataBuilder* preparse_data_builder) {
    preparse_data_builder_ = preparse_data_builder;
1104 1105
  }

1106 1107
  PreparseDataBuilder* preparse_data_builder() const {
    return preparse_data_builder_;
1108 1109
  }

1110 1111
  void set_has_this_reference() { has_this_reference_ = true; }
  bool has_this_reference() const { return has_this_reference_; }
1112 1113 1114

  bool can_elide_this_hole_checks() const {
    return can_elide_this_hole_checks_;
1115 1116
  }

1117 1118
  void set_can_elide_this_hole_checks() { can_elide_this_hole_checks_ = true; }

1119 1120 1121 1122 1123
  bool needs_private_name_context_chain_recalc() const {
    return needs_private_name_context_chain_recalc_;
  }
  void RecordNeedsPrivateNameContextChainRecalc();

1124
 private:
1125
  V8_INLINE void AllocateParameter(Variable* var, int index);
1126

1127 1128 1129 1130 1131 1132 1133 1134
  // 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.
1135
  //
1136
  // Returns false if private names can not be resolved.
1137
  bool AllocateVariables(ParseInfo* info);
1138

1139 1140
  void SetDefaults();

1141 1142 1143 1144 1145 1146
  // 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();

1147
  bool has_simple_parameters_ : 1;
1148
  // This scope contains an "use asm" annotation.
1149
  bool is_asm_module_ : 1;
1150
  bool force_eager_compilation_ : 1;
1151 1152
  // This function scope has a rest parameter.
  bool has_rest_ : 1;
1153 1154
  // This scope has a parameter called "arguments".
  bool has_arguments_parameter_ : 1;
1155 1156
  // This scope uses "super" property ('super.foo').
  bool scope_uses_super_property_ : 1;
1157
  bool should_eager_compile_ : 1;
1158 1159 1160 1161 1162
  // 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
1163
  bool is_skipped_function_ : 1;
1164
  bool has_inferred_function_name_ : 1;
1165
  bool has_checked_syntax_ : 1;
1166 1167
  bool has_this_reference_ : 1;
  bool has_this_declaration_ : 1;
1168
  bool can_elide_this_hole_checks_ : 1;
1169
  bool needs_private_name_context_chain_recalc_ : 1;
1170

1171
  // If the scope is a function scope, this is the function kind.
1172
  FunctionKind function_kind_;
1173

1174 1175
  int num_parameters_ = 0;

1176
  // Parameter list in source order.
1177
  ZonePtrList<Variable> params_;
1178
  // Map of function names to lists of functions defined in sloppy blocks
1179
  base::ThreadedList<SloppyBlockFunctionStatement> sloppy_block_functions_;
1180 1181 1182
  // Convenience variable.
  Variable* receiver_;
  // Function variable, if any; function scopes only.
1183
  Variable* function_;
1184 1185 1186 1187
  // new.target variable, function scopes only.
  Variable* new_target_;
  // Convenience variable; function scopes only.
  Variable* arguments_;
1188

1189
  // For producing the scope allocation data during preparsing.
1190
  PreparseDataBuilder* preparse_data_builder_;
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
  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) {
      rare_data_ = new (zone_) RareData;
    }
    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;
1230 1231
};

1232 1233 1234 1235 1236 1237
void Scope::RecordEvalCall() {
  calls_eval_ = true;
  GetDeclarationScope()->RecordDeclarationScopeEvalCall();
  RecordInnerScopeEvalCall();
}

1238
Scope::Snapshot::Snapshot(Scope* scope)
1239
    : outer_scope_and_calls_eval_(scope, scope->calls_eval_),
1240
      top_inner_scope_(scope->inner_scope_),
1241
      top_unresolved_(scope->unresolved_list_.end()),
1242 1243
      top_local_(scope->GetClosureScope()->locals_.end()) {
  // Reset in order to record eval calls during this Snapshot's lifetime.
1244 1245 1246
  outer_scope_and_calls_eval_.GetPointer()->calls_eval_ = false;
  outer_scope_and_calls_eval_.GetPointer()->sloppy_eval_can_extend_vars_ =
      false;
1247 1248
}

1249 1250
class ModuleScope final : public DeclarationScope {
 public:
1251
  ModuleScope(DeclarationScope* script_scope, AstValueFactory* avfactory);
1252

1253
  // Deserialization. Does not restore the module descriptor.
1254
  ModuleScope(Isolate* isolate, Handle<ScopeInfo> scope_info,
1255
              AstValueFactory* avfactory);
1256

1257
  // Returns nullptr in a deserialized scope.
1258
  SourceTextModuleDescriptor* module() const { return module_descriptor_; }
1259

1260 1261 1262
  // Set MODULE as VariableLocation for all variables that will live in a
  // module's export table.
  void AllocateModuleVariables();
1263 1264

 private:
1265
  SourceTextModuleDescriptor* const module_descriptor_;
1266 1267
};

1268 1269
class V8_EXPORT_PRIVATE ClassScope : public Scope {
 public:
1270
  ClassScope(Zone* zone, Scope* outer_scope, bool is_anonymous);
1271
  // Deserialization.
1272
  ClassScope(Isolate* isolate, Zone* zone, AstValueFactory* ast_value_factory,
1273
             Handle<ScopeInfo> scope_info);
1274

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
  struct HeritageParsingScope {
    explicit HeritageParsingScope(ClassScope* class_scope)
        : class_scope_(class_scope) {
      class_scope_->SetIsParsingHeritage(true);
    }
    ~HeritageParsingScope() { class_scope_->SetIsParsingHeritage(false); }

   private:
    ClassScope* class_scope_;
  };

1286 1287
  // Declare a private name in the private name map and add it to the
  // local variables of this scope.
1288
  Variable* DeclarePrivateName(const AstRawString* name, VariableMode mode,
1289
                               IsStaticFlag is_static_flag, bool* was_added);
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318

  // 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);
1319
  Variable* DeclareBrandVariable(AstValueFactory* ast_value_factory,
1320
                                 IsStaticFlag is_static_flag,
1321
                                 int class_token_pos);
1322 1323 1324 1325

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

1326
  Variable* brand() {
1327 1328 1329
    return GetRareData() == nullptr ? nullptr : GetRareData()->brand;
  }

1330 1331
  Variable* class_variable() { return class_variable_; }

1332 1333
  V8_INLINE bool IsParsingHeritage() {
    return rare_data_and_is_parsing_heritage_.GetPayload();
1334
  }
1335

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  // 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;
  }

1363 1364
 private:
  friend class Scope;
1365 1366
  friend class PrivateNameScopeIterator;

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  // 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;
1381
    Variable* brand = nullptr;
1382 1383
  };

1384 1385 1386
  V8_INLINE RareData* GetRareData() {
    return rare_data_and_is_parsing_heritage_.GetPointer();
  }
1387
  V8_INLINE RareData* EnsureRareData() {
1388 1389 1390
    if (GetRareData() == nullptr) {
      rare_data_and_is_parsing_heritage_.SetPointer(new (zone_)
                                                        RareData(zone_));
1391
    }
1392 1393 1394 1395
    return GetRareData();
  }
  V8_INLINE void SetIsParsingHeritage(bool v) {
    rare_data_and_is_parsing_heritage_.SetPayload(v);
1396 1397
  }

1398
  PointerWithPayload<RareData, bool, 1> rare_data_and_is_parsing_heritage_;
1399 1400 1401 1402 1403 1404 1405 1406 1407
  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;
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
};

// 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_;
1431 1432
};

1433 1434
}  // namespace internal
}  // namespace v8
1435

1436
#endif  // V8_AST_SCOPES_H_