scopes.cc 52.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
#include "src/v8.h"
6

7 8 9
#include "src/accessors.h"
#include "src/bootstrapper.h"
#include "src/messages.h"
10
#include "src/parser.h"
11
#include "src/scopeinfo.h"
12
#include "src/scopes.h"
13

14 15
namespace v8 {
namespace internal {
16 17 18 19 20 21 22 23 24 25

// ----------------------------------------------------------------------------
// Implementation of LocalsMap
//
// Note: We are storing the handle locations as key values in the hash map.
//       When inserting a new variable via Declare(), we rely on the fact that
//       the handle location remains alive for the duration of that variable
//       use. Because a Variable holding a handle with the same location exists
//       this is ensured.

26
VariableMap::VariableMap(Zone* zone)
27
    : ZoneHashMap(ZoneHashMap::PointersMatch, 8, ZoneAllocationPolicy(zone)),
28
      zone_(zone) {}
29
VariableMap::~VariableMap() {}
30 31


32
Variable* VariableMap::Declare(Scope* scope, const AstRawString* name,
33
                               VariableMode mode, Variable::Kind kind,
34
                               InitializationFlag initialization_flag,
35 36
                               MaybeAssignedFlag maybe_assigned_flag,
                               int declaration_group_start) {
37 38 39
  // AstRawStrings are unambiguous, i.e., the same string is always represented
  // by the same AstRawString*.
  // FIXME(marja): fix the type of Lookup.
40 41 42
  Entry* p =
      ZoneHashMap::LookupOrInsert(const_cast<AstRawString*>(name), name->hash(),
                                  ZoneAllocationPolicy(zone()));
43 44
  if (p->value == NULL) {
    // The variable has not been declared yet -> insert it.
45
    DCHECK(p->key == name);
46 47
    if (kind == Variable::CLASS) {
      p->value = new (zone())
48
          ClassVariable(scope, name, mode, initialization_flag,
49 50 51 52 53
                        maybe_assigned_flag, declaration_group_start);
    } else {
      p->value = new (zone()) Variable(
          scope, name, mode, kind, initialization_flag, maybe_assigned_flag);
    }
54 55 56 57 58
  }
  return reinterpret_cast<Variable*>(p->value);
}


59
Variable* VariableMap::Lookup(const AstRawString* name) {
60
  Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->hash());
61
  if (p != NULL) {
62 63
    DCHECK(reinterpret_cast<const AstRawString*>(p->key) == name);
    DCHECK(p->value != NULL);
64 65 66 67 68 69 70 71 72
    return reinterpret_cast<Variable*>(p->value);
  }
  return NULL;
}


// ----------------------------------------------------------------------------
// Implementation of Scope

73
Scope::Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
74
             AstValueFactory* ast_value_factory, FunctionKind function_kind)
75
    : inner_scopes_(4, zone),
76
      variables_(zone),
77
      internals_(4, zone),
78 79 80 81
      temps_(4, zone),
      params_(4, zone),
      unresolved_(16, zone),
      decls_(4, zone),
82 83
      module_descriptor_(
          scope_type == MODULE_SCOPE ? ModuleDescriptor::New(zone) : NULL),
84
      already_resolved_(false),
85
      ast_value_factory_(ast_value_factory),
86 87
      zone_(zone),
      class_declaration_group_start_(-1) {
88 89
  SetDefaults(scope_type, outer_scope, Handle<ScopeInfo>::null(),
              function_kind);
90 91
  // The outermost scope must be a script scope.
  DCHECK(scope_type == SCRIPT_SCOPE || outer_scope != NULL);
92
  DCHECK(!HasIllegalRedeclaration());
93 94 95
}


96 97 98
Scope::Scope(Zone* zone, Scope* inner_scope, ScopeType scope_type,
             Handle<ScopeInfo> scope_info, AstValueFactory* value_factory)
    : inner_scopes_(4, zone),
99
      variables_(zone),
100
      internals_(4, zone),
101 102 103 104
      temps_(4, zone),
      params_(4, zone),
      unresolved_(16, zone),
      decls_(4, zone),
105
      module_descriptor_(NULL),
106
      already_resolved_(true),
107
      ast_value_factory_(value_factory),
108 109
      zone_(zone),
      class_declaration_group_start_(-1) {
110
  SetDefaults(scope_type, NULL, scope_info);
111 112
  if (!scope_info.is_null()) {
    num_heap_slots_ = scope_info_->ContextLength();
113
  }
114 115 116
  // Ensure at least MIN_CONTEXT_SLOTS to indicate a materialized context.
  num_heap_slots_ = Max(num_heap_slots_,
                        static_cast<int>(Context::MIN_CONTEXT_SLOTS));
117 118 119
  AddInnerScope(inner_scope);
}

120

121
Scope::Scope(Zone* zone, Scope* inner_scope,
122 123
             const AstRawString* catch_variable_name,
             AstValueFactory* value_factory)
124
    : inner_scopes_(1, zone),
125
      variables_(zone),
126
      internals_(0, zone),
127 128 129 130
      temps_(0, zone),
      params_(0, zone),
      unresolved_(0, zone),
      decls_(0, zone),
131
      module_descriptor_(NULL),
132
      already_resolved_(true),
133
      ast_value_factory_(value_factory),
134 135
      zone_(zone),
      class_declaration_group_start_(-1) {
136
  SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
137
  AddInnerScope(inner_scope);
138
  ++num_var_or_const_;
139
  num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
140 141
  Variable* variable = variables_.Declare(this,
                                          catch_variable_name,
142
                                          VAR,
143 144
                                          Variable::NORMAL,
                                          kCreatedInitialized);
145
  AllocateHeapSlot(variable);
146 147 148
}


149 150 151
void Scope::SetDefaults(ScopeType scope_type, Scope* outer_scope,
                        Handle<ScopeInfo> scope_info,
                        FunctionKind function_kind) {
152
  outer_scope_ = outer_scope;
153
  scope_type_ = scope_type;
154 155
  function_kind_ = function_kind;
  block_scope_is_class_scope_ = false;
156
  scope_name_ = ast_value_factory_->empty_string();
157 158
  dynamics_ = NULL;
  receiver_ = NULL;
159
  new_target_ = nullptr;
160 161 162 163 164 165
  function_ = NULL;
  arguments_ = NULL;
  illegal_redecl_ = NULL;
  scope_inside_with_ = false;
  scope_contains_with_ = false;
  scope_calls_eval_ = false;
166
  scope_uses_arguments_ = false;
167
  scope_uses_super_property_ = false;
168
  scope_uses_this_ = false;
169 170
  asm_module_ = false;
  asm_function_ = outer_scope != NULL && outer_scope->asm_module_;
rossberg's avatar
rossberg committed
171
  // Inherit the language mode from the parent scope.
172
  language_mode_ = outer_scope != NULL ? outer_scope->language_mode_ : SLOPPY;
173
  outer_scope_calls_sloppy_eval_ = false;
174
  inner_scope_calls_eval_ = false;
175
  inner_scope_uses_arguments_ = false;
176
  inner_scope_uses_this_ = false;
177
  inner_scope_uses_super_property_ = false;
178
  force_eager_compilation_ = false;
179 180
  force_context_allocation_ = (outer_scope != NULL && !is_function_scope())
      ? outer_scope->has_forced_context_allocation() : false;
181
  num_var_or_const_ = 0;
182 183
  num_stack_slots_ = 0;
  num_heap_slots_ = 0;
184 185
  num_modules_ = 0;
  module_var_ = NULL,
186 187
  rest_parameter_ = NULL;
  rest_index_ = -1;
188
  scope_info_ = scope_info;
189 190
  start_position_ = RelocInfo::kNoPosition;
  end_position_ = RelocInfo::kNoPosition;
191 192
  if (!scope_info.is_null()) {
    scope_calls_eval_ = scope_info->CallsEval();
193
    language_mode_ = scope_info->language_mode();
194 195
    block_scope_is_class_scope_ = scope_info->block_scope_is_class_scope();
    function_kind_ = scope_info->function_kind();
196
  }
197 198 199
}


200 201
Scope* Scope::DeserializeScopeChain(Isolate* isolate, Zone* zone,
                                    Context* context, Scope* script_scope) {
202 203
  // Reconstruct the outer scope chain from a closure's context chain.
  Scope* current_scope = NULL;
204
  Scope* innermost_scope = NULL;
205
  bool contains_with = false;
206
  while (!context->IsNativeContext()) {
207
    if (context->IsWithContext()) {
208
      Scope* with_scope = new (zone)
209 210
          Scope(zone, current_scope, WITH_SCOPE, Handle<ScopeInfo>::null(),
                script_scope->ast_value_factory_);
211
      current_scope = with_scope;
212 213 214 215 216
      // All the inner scopes are inside a with.
      contains_with = true;
      for (Scope* s = innermost_scope; s != NULL; s = s->outer_scope()) {
        s->scope_inside_with_ = true;
      }
217
    } else if (context->IsScriptContext()) {
218
      ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
219 220 221
      current_scope = new (zone) Scope(zone, current_scope, SCRIPT_SCOPE,
                                       Handle<ScopeInfo>(scope_info),
                                       script_scope->ast_value_factory_);
222 223
    } else if (context->IsModuleContext()) {
      ScopeInfo* scope_info = ScopeInfo::cast(context->module()->scope_info());
224 225 226
      current_scope = new (zone) Scope(zone, current_scope, MODULE_SCOPE,
                                       Handle<ScopeInfo>(scope_info),
                                       script_scope->ast_value_factory_);
227
    } else if (context->IsFunctionContext()) {
228
      ScopeInfo* scope_info = context->closure()->shared()->scope_info();
229 230 231
      current_scope = new (zone) Scope(zone, current_scope, FUNCTION_SCOPE,
                                       Handle<ScopeInfo>(scope_info),
                                       script_scope->ast_value_factory_);
232 233
      if (scope_info->IsAsmFunction()) current_scope->asm_function_ = true;
      if (scope_info->IsAsmModule()) current_scope->asm_module_ = true;
234
    } else if (context->IsBlockContext()) {
235
      ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
236 237 238
      current_scope = new (zone)
          Scope(zone, current_scope, BLOCK_SCOPE, Handle<ScopeInfo>(scope_info),
                script_scope->ast_value_factory_);
239
    } else {
240
      DCHECK(context->IsCatchContext());
241
      String* name = String::cast(context->extension());
242
      current_scope = new (zone) Scope(
243
          zone, current_scope,
244
          script_scope->ast_value_factory_->GetString(Handle<String>(name)),
245
          script_scope->ast_value_factory_);
246
    }
247
    if (contains_with) current_scope->RecordWithStatement();
248
    if (innermost_scope == NULL) innermost_scope = current_scope;
249

250 251 252 253 254 255
    // Forget about a with when we move to a context for a different function.
    if (context->previous()->closure() != context->closure()) {
      contains_with = false;
    }
    context = context->previous();
  }
256

257 258 259
  script_scope->AddInnerScope(current_scope);
  script_scope->PropagateScopeInfo(false);
  return (innermost_scope == NULL) ? script_scope : innermost_scope;
260 261
}

262

263
bool Scope::Analyze(ParseInfo* info) {
264
  DCHECK(info->function() != NULL);
265
  DCHECK(info->scope() == NULL);
266 267
  Scope* scope = info->function()->scope();
  Scope* top = scope;
268

269 270
  // Traverse the scope tree up to the first unresolved scope or the global
  // scope and start scope resolution and variable allocation from that scope.
271
  while (!top->is_script_scope() &&
272 273 274 275
         !top->outer_scope()->already_resolved()) {
    top = top->outer_scope();
  }

276 277
  // Allocate the variables.
  {
278
    AstNodeFactory ast_node_factory(info->ast_value_factory());
279 280 281 282 283 284
    if (!top->AllocateVariables(info, &ast_node_factory)) {
      DCHECK(top->pending_error_handler_.has_pending_error());
      top->pending_error_handler_.ThrowPendingError(info->isolate(),
                                                    info->script());
      return false;
    }
285
  }
286 287

#ifdef DEBUG
288
  if (info->isolate()->bootstrapper()->IsActive()
289 290
          ? FLAG_print_builtin_scopes
          : FLAG_print_scopes) {
291
    scope->Print();
292 293 294
  }
#endif

295
  info->set_scope(scope);
296
  return true;
297 298 299
}


300 301
void Scope::Initialize() {
  bool subclass_constructor = IsSubclassConstructor(function_kind_);
302
  DCHECK(!already_resolved());
303

304 305
  // Add this scope as a new inner scope of the outer scope.
  if (outer_scope_ != NULL) {
306
    outer_scope_->inner_scopes_.Add(this, zone());
307
    scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
308
  } else {
309
    scope_inside_with_ = is_with_scope();
310 311
  }

312 313 314 315 316 317 318 319
  // Declare convenience variables.
  // Declare and allocate receiver (even for the script scope, and even
  // if naccesses_ == 0).
  // NOTE: When loading parameters in the script scope, we must take
  // care not to access them as properties of the global object, but
  // instead load them directly from the stack. Currently, the only
  // such parameter is 'this' which is passed on the stack when
  // invoking scripts
320
  if (is_declaration_scope()) {
321
    DCHECK(!subclass_constructor || is_function_scope());
322 323 324 325 326 327
    Variable* var = variables_.Declare(
        this, ast_value_factory_->this_string(),
        subclass_constructor ? CONST : VAR, Variable::THIS,
        subclass_constructor ? kNeedsInitialization : kCreatedInitialized);
    var->AllocateTo(Variable::PARAMETER, -1);
    receiver_ = var;
328 329

    if (subclass_constructor) {
330 331 332
      new_target_ =
          variables_.Declare(this, ast_value_factory_->new_target_string(),
                             CONST, Variable::NEW_TARGET, kCreatedInitialized);
333 334 335
      new_target_->AllocateTo(Variable::PARAMETER, -2);
      new_target_->set_is_used();
    }
336 337 338
  } else {
    DCHECK(outer_scope() != NULL);
    receiver_ = outer_scope()->receiver();
339
  }
340

341 342
  if (is_function_scope() && !is_arrow_scope()) {
    // Declare 'arguments' variable which exists in all non arrow functions.
343 344
    // Note that it might never be accessed, in which case it won't be
    // allocated during variable allocation.
345
    variables_.Declare(this,
346
                       ast_value_factory_->arguments_string(),
347
                       VAR,
348 349
                       Variable::ARGUMENTS,
                       kCreatedInitialized);
350 351 352 353
  }
}


354
Scope* Scope::FinalizeBlockScope() {
355 356 357 358
  DCHECK(is_block_scope());
  DCHECK(internals_.is_empty());
  DCHECK(temps_.is_empty());
  DCHECK(params_.is_empty());
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

  if (num_var_or_const() > 0) return this;

  // Remove this scope from outer scope.
  for (int i = 0; i < outer_scope_->inner_scopes_.length(); i++) {
    if (outer_scope_->inner_scopes_[i] == this) {
      outer_scope_->inner_scopes_.Remove(i);
      break;
    }
  }

  // Reparent inner scopes.
  for (int i = 0; i < inner_scopes_.length(); i++) {
    outer_scope()->AddInnerScope(inner_scopes_[i]);
  }

  // Move unresolved variables
  for (int i = 0; i < unresolved_.length(); i++) {
377
    outer_scope()->unresolved_.Add(unresolved_[i], zone());
378 379
  }

380
  // Propagate usage flags to outer scope.
381
  if (uses_arguments()) outer_scope_->RecordArgumentsUsage();
382
  if (uses_super_property()) outer_scope_->RecordSuperPropertyUsage();
383
  if (uses_this()) outer_scope_->RecordThisUsage();
384
  if (scope_calls_eval_) outer_scope_->RecordEvalCall();
385

386 387 388 389
  return NULL;
}


390
Variable* Scope::LookupLocal(const AstRawString* name) {
391
  Variable* result = variables_.Lookup(name);
392
  if (result != NULL || scope_info_.is_null()) {
393 394
    return result;
  }
395
  Handle<String> name_handle = name->string();
396 397 398
  // The Scope is backed up by ScopeInfo. This means it cannot operate in a
  // heap-independent mode, and all strings must be internalized immediately. So
  // it's ok to get the Handle<String> here.
399
  // If we have a serialized scope info, we might find the variable there.
400
  // There should be no local slot with the given name.
401
  DCHECK(scope_info_->StackSlotIndex(*name_handle) < 0 || is_block_scope());
402

403
  // Check context slot lookup.
404
  VariableMode mode;
405
  Variable::Location location = Variable::CONTEXT;
406
  InitializationFlag init_flag;
407 408 409
  MaybeAssignedFlag maybe_assigned_flag;
  int index = ScopeInfo::ContextSlotIndex(scope_info_, name_handle, &mode,
                                          &init_flag, &maybe_assigned_flag);
410 411
  if (index < 0) {
    // Check parameters.
412
    index = scope_info_->ParameterIndex(*name_handle);
413
    if (index < 0) return NULL;
414 415 416 417

    mode = DYNAMIC;
    location = Variable::LOOKUP;
    init_flag = kCreatedInitialized;
418 419 420 421
    // Be conservative and flag parameters as maybe assigned. Better information
    // would require ScopeInfo to serialize the maybe_assigned bit also for
    // parameters.
    maybe_assigned_flag = kMaybeAssigned;
422 423
  }

424
  // TODO(marja, rossberg): Declare variables of the right Kind.
425
  Variable* var = variables_.Declare(this, name, mode, Variable::NORMAL,
426
                                     init_flag, maybe_assigned_flag);
427
  var->AllocateTo(location, index);
428
  return var;
429 430 431
}


432
Variable* Scope::LookupFunctionVar(const AstRawString* name,
433
                                   AstNodeFactory* factory) {
434
  if (function_ != NULL && function_->proxy()->raw_name() == name) {
435
    return function_->proxy()->var();
436 437 438
  } else if (!scope_info_.is_null()) {
    // If we are backed by a scope info, try to lookup the variable there.
    VariableMode mode;
439
    int index = scope_info_->FunctionContextSlotIndex(*(name->string()), &mode);
440
    if (index < 0) return NULL;
441 442
    Variable* var = new (zone())
        Variable(this, name, mode, Variable::NORMAL, kCreatedInitialized);
443
    VariableProxy* proxy = factory->NewVariableProxy(var);
444 445
    VariableDeclaration* declaration = factory->NewVariableDeclaration(
        proxy, mode, this, RelocInfo::kNoPosition);
446
    DeclareFunctionVar(declaration);
447 448 449 450 451 452 453 454
    var->AllocateTo(Variable::CONTEXT, index);
    return var;
  } else {
    return NULL;
  }
}


455
Variable* Scope::Lookup(const AstRawString* name) {
456 457 458
  for (Scope* scope = this;
       scope != NULL;
       scope = scope->outer_scope()) {
459
    Variable* var = scope->LookupLocal(name);
460 461 462 463 464 465
    if (var != NULL) return var;
  }
  return NULL;
}


466
Variable* Scope::DeclareParameter(const AstRawString* name, VariableMode mode,
467
                                  bool is_rest, bool* is_duplicate) {
468 469
  DCHECK(!already_resolved());
  DCHECK(is_function_scope());
470
  Variable* var = variables_.Declare(this, name, mode, Variable::NORMAL,
471
                                     kCreatedInitialized);
472 473 474 475 476
  if (is_rest) {
    DCHECK_NULL(rest_parameter_);
    rest_parameter_ = var;
    rest_index_ = num_parameters();
  }
477 478
  // TODO(wingo): Avoid O(n^2) check.
  *is_duplicate = IsDeclaredParameter(name);
479
  params_.Add(var, zone());
480
  return var;
481 482 483
}


484
Variable* Scope::DeclareLocal(const AstRawString* name, VariableMode mode,
485
                              InitializationFlag init_flag, Variable::Kind kind,
486 487
                              MaybeAssignedFlag maybe_assigned_flag,
                              int declaration_group_start) {
488
  DCHECK(!already_resolved());
489
  // This function handles VAR, LET, and CONST modes.  DYNAMIC variables are
490 491
  // introduces during variable allocation, INTERNAL variables are allocated
  // explicitly, and TEMPORARY variables are allocated via NewTemporary().
492
  DCHECK(IsDeclaredVariableMode(mode));
493
  ++num_var_or_const_;
494
  return variables_.Declare(this, name, mode, kind, init_flag,
495
                            maybe_assigned_flag, declaration_group_start);
496 497 498
}


499
Variable* Scope::DeclareDynamicGlobal(const AstRawString* name) {
500
  DCHECK(is_script_scope());
501 502 503 504 505
  return variables_.Declare(this,
                            name,
                            DYNAMIC_GLOBAL,
                            Variable::NORMAL,
                            kCreatedInitialized);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
}


void Scope::RemoveUnresolved(VariableProxy* var) {
  // Most likely (always?) any variable we want to remove
  // was just added before, so we search backwards.
  for (int i = unresolved_.length(); i-- > 0;) {
    if (unresolved_[i] == var) {
      unresolved_.Remove(i);
      return;
    }
  }
}


521
Variable* Scope::NewInternal(const AstRawString* name) {
522
  DCHECK(!already_resolved());
523 524 525 526 527 528 529 530 531 532
  Variable* var = new(zone()) Variable(this,
                                       name,
                                       INTERNAL,
                                       Variable::NORMAL,
                                       kCreatedInitialized);
  internals_.Add(var, zone());
  return var;
}


533
Variable* Scope::NewTemporary(const AstRawString* name) {
534
  DCHECK(!already_resolved());
535 536 537 538 539 540
  Variable* var = new(zone()) Variable(this,
                                       name,
                                       TEMPORARY,
                                       Variable::NORMAL,
                                       kCreatedInitialized);
  temps_.Add(var, zone());
541
  return var;
542 543 544 545
}


void Scope::AddDeclaration(Declaration* declaration) {
546
  decls_.Add(declaration, zone());
547 548 549 550
}


void Scope::SetIllegalRedeclaration(Expression* expression) {
551
  // Record only the first illegal redeclaration.
552 553 554
  if (!HasIllegalRedeclaration()) {
    illegal_redecl_ = expression;
  }
555
  DCHECK(HasIllegalRedeclaration());
556 557 558
}


559
void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
560
  DCHECK(HasIllegalRedeclaration());
561 562 563 564
  illegal_redecl_->Accept(visitor);
}


565 566 567 568
Declaration* Scope::CheckConflictingVarDeclarations() {
  int length = decls_.length();
  for (int i = 0; i < length; i++) {
    Declaration* decl = decls_[i];
569
    if (decl->mode() != VAR) continue;
570
    const AstRawString* name = decl->proxy()->raw_name();
571 572 573 574 575

    // Iterate through all scopes until and including the declaration scope.
    Scope* previous = NULL;
    Scope* current = decl->scope();
    do {
576
      // There is a conflict if there exists a non-VAR binding.
577
      Variable* other_var = current->variables_.Lookup(name);
578
      if (other_var != NULL && other_var->mode() != VAR) {
579 580
        return decl;
      }
581 582 583
      previous = current;
      current = current->outer_scope_;
    } while (!previous->is_declaration_scope());
584 585 586 587 588
  }
  return NULL;
}


589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
class VarAndOrder {
 public:
  VarAndOrder(Variable* var, int order) : var_(var), order_(order) { }
  Variable* var() const { return var_; }
  int order() const { return order_; }
  static int Compare(const VarAndOrder* a, const VarAndOrder* b) {
    return a->order_ - b->order_;
  }

 private:
  Variable* var_;
  int order_;
};


604 605 606
void Scope::CollectStackAndContextLocals(
    ZoneList<Variable*>* stack_locals, ZoneList<Variable*>* context_locals,
    ZoneList<Variable*>* strong_mode_free_variables) {
607 608
  DCHECK(stack_locals != NULL);
  DCHECK(context_locals != NULL);
609

610 611 612 613
  // Collect internals which are always allocated on the heap.
  for (int i = 0; i < internals_.length(); i++) {
    Variable* var = internals_[i];
    if (var->is_used()) {
614
      DCHECK(var->IsContextSlot());
615 616 617 618
      context_locals->Add(var, zone());
    }
  }

619 620
  // Collect temporaries which are always allocated on the stack, unless the
  // context as a whole has forced context allocation.
621 622
  for (int i = 0; i < temps_.length(); i++) {
    Variable* var = temps_[i];
623
    if (var->is_used()) {
624
      if (var->IsContextSlot()) {
625
        DCHECK(has_forced_context_allocation());
626 627
        context_locals->Add(var, zone());
      } else {
628
        DCHECK(var->IsStackLocal());
629 630
        stack_locals->Add(var, zone());
      }
631 632
    }
  }
633 634

  // Collect declared local variables.
635
  ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
636 637 638
  for (VariableMap::Entry* p = variables_.Start();
       p != NULL;
       p = variables_.Next(p)) {
639
    Variable* var = reinterpret_cast<Variable*>(p->value);
640 641 642 643 644
    if (strong_mode_free_variables && var->has_strong_mode_reference() &&
        var->mode() == DYNAMIC_GLOBAL) {
      strong_mode_free_variables->Add(var, zone());
    }

645
    if (var->is_used()) {
646 647 648 649 650 651 652 653 654 655 656
      vars.Add(VarAndOrder(var, p->order), zone());
    }
  }
  vars.Sort(VarAndOrder::Compare);
  int var_count = vars.length();
  for (int i = 0; i < var_count; i++) {
    Variable* var = vars[i].var();
    if (var->IsStackLocal()) {
      stack_locals->Add(var, zone());
    } else if (var->IsContextSlot()) {
      context_locals->Add(var, zone());
657 658 659 660 661
    }
  }
}


662
bool Scope::AllocateVariables(ParseInfo* info, AstNodeFactory* factory) {
663
  // 1) Propagate scope information.
664
  bool outer_scope_calls_sloppy_eval = false;
665
  if (outer_scope_ != NULL) {
666 667 668
    outer_scope_calls_sloppy_eval =
        outer_scope_->outer_scope_calls_sloppy_eval() |
        outer_scope_->calls_sloppy_eval();
669
  }
670
  PropagateScopeInfo(outer_scope_calls_sloppy_eval);
671

672
  // 2) Allocate module instances.
673
  if (FLAG_harmony_modules && is_script_scope()) {
674
    DCHECK(num_modules_ == 0);
675
    AllocateModules();
676 677 678
  }

  // 3) Resolve variables.
679
  if (!ResolveVariablesRecursively(info, factory)) return false;
680

681
  // 4) Allocate variables.
682
  AllocateVariablesRecursively(info->isolate());
683 684

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


bool Scope::HasTrivialContext() const {
  // A function scope has a trivial context if it always is the global
  // context. We iteratively scan out the context chain to see if
  // there is anything that makes this scope non-trivial; otherwise we
  // return true.
  for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
    if (scope->is_eval_scope()) return false;
    if (scope->scope_inside_with_) return false;
    if (scope->num_heap_slots_ > 0) return false;
  }
  return true;
}


bool Scope::HasTrivialOuterContext() const {
  Scope* outer = outer_scope_;
  if (outer == NULL) return true;
  // Note that the outer context may be trivial in general, but the current
  // scope may be inside a 'with' statement in which case the outer context
  // for this scope is not trivial.
  return !scope_inside_with_ && outer->HasTrivialContext();
}


712 713 714
bool Scope::HasLazyCompilableOuterContext() const {
  Scope* outer = outer_scope_;
  if (outer == NULL) return true;
715 716 717
  // We have to prevent lazy compilation if this scope is inside a with scope
  // and all declaration scopes between them have empty contexts. Such
  // declaration scopes may become invisible during scope info deserialization.
718 719 720 721
  outer = outer->DeclarationScope();
  bool found_non_trivial_declarations = false;
  for (const Scope* scope = outer; scope != NULL; scope = scope->outer_scope_) {
    if (scope->is_with_scope() && !found_non_trivial_declarations) return false;
722
    if (scope->is_block_scope() && !scope->decls_.is_empty()) return false;
723 724 725 726 727
    if (scope->is_declaration_scope() && scope->num_heap_slots() > 0) {
      found_non_trivial_declarations = true;
    }
  }
  return true;
728 729 730
}


731 732
bool Scope::AllowsLazyCompilation() const {
  return !force_eager_compilation_ && HasLazyCompilableOuterContext();
733 734 735
}


736 737
bool Scope::AllowsLazyCompilationWithoutContext() const {
  return !force_eager_compilation_ && HasTrivialOuterContext();
738 739 740
}


741 742 743
int Scope::ContextChainLength(Scope* scope) {
  int n = 0;
  for (Scope* s = this; s != scope; s = s->outer_scope_) {
744
    DCHECK(s != NULL);  // scope must be in the scope chain
745
    if (s->is_with_scope() || s->num_heap_slots() > 0) n++;
746
    // Catch and module scopes always have heap slots.
747 748
    DCHECK(!s->is_catch_scope() || s->num_heap_slots() > 0);
    DCHECK(!s->is_module_scope() || s->num_heap_slots() > 0);
749 750 751 752 753
  }
  return n;
}


754
Scope* Scope::ScriptScope() {
755
  Scope* scope = this;
756
  while (!scope->is_script_scope()) {
757 758 759 760 761 762
    scope = scope->outer_scope();
  }
  return scope;
}


763 764
Scope* Scope::DeclarationScope() {
  Scope* scope = this;
765
  while (!scope->is_declaration_scope()) {
766 767 768 769 770 771
    scope = scope->outer_scope();
  }
  return scope;
}


772
Handle<ScopeInfo> Scope::GetScopeInfo(Isolate* isolate) {
773
  if (scope_info_.is_null()) {
774
    scope_info_ = ScopeInfo::Create(isolate, zone(), this);
775 776 777 778 779
  }
  return scope_info_;
}


780 781 782
void Scope::GetNestedScopeChain(Isolate* isolate,
                                List<Handle<ScopeInfo> >* chain, int position) {
  if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo(isolate)));
783 784 785 786 787

  for (int i = 0; i < inner_scopes_.length(); i++) {
    Scope* scope = inner_scopes_[i];
    int beg_pos = scope->start_position();
    int end_pos = scope->end_position();
788
    DCHECK(beg_pos >= 0 && end_pos >= 0);
789
    if (beg_pos <= position && position < end_pos) {
790
      scope->GetNestedScopeChain(isolate, chain, position);
791 792 793 794 795 796
      return;
    }
  }
}


797 798 799 800 801 802 803 804 805 806 807 808 809 810
void Scope::ReportMessage(int start_position, int end_position,
                          const char* message, const AstRawString* arg) {
  // Propagate the error to the topmost scope targeted by this scope analysis
  // phase.
  Scope* top = this;
  while (!top->is_script_scope() && !top->outer_scope()->already_resolved()) {
    top = top->outer_scope();
  }

  top->pending_error_handler_.ReportMessageAt(start_position, end_position,
                                              message, arg, kReferenceError);
}


811
#ifdef DEBUG
812 813
static const char* Header(ScopeType scope_type) {
  switch (scope_type) {
814 815
    case EVAL_SCOPE: return "eval";
    case FUNCTION_SCOPE: return "function";
816
    case MODULE_SCOPE: return "module";
817
    case SCRIPT_SCOPE: return "global";
818 819 820
    case CATCH_SCOPE: return "catch";
    case BLOCK_SCOPE: return "block";
    case WITH_SCOPE: return "with";
821
    case ARROW_SCOPE: return "arrow";
822 823 824 825 826 827 828 829 830 831 832
  }
  UNREACHABLE();
  return NULL;
}


static void Indent(int n, const char* str) {
  PrintF("%*s%s", n, "", str);
}


833 834
static void PrintName(const AstRawString* name) {
  PrintF("%.*s", name->length(), name->raw_data());
835 836 837
}


838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
static void PrintLocation(Variable* var) {
  switch (var->location()) {
    case Variable::UNALLOCATED:
      break;
    case Variable::PARAMETER:
      PrintF("parameter[%d]", var->index());
      break;
    case Variable::LOCAL:
      PrintF("local[%d]", var->index());
      break;
    case Variable::CONTEXT:
      PrintF("context[%d]", var->index());
      break;
    case Variable::LOOKUP:
      PrintF("lookup");
      break;
  }
}


static void PrintVar(int indent, Variable* var) {
  if (var->is_used() || !var->IsUnallocated()) {
860 861
    Indent(indent, Variable::Mode2String(var->mode()));
    PrintF(" ");
862
    PrintName(var->raw_name());
863
    PrintF(";  // ");
864
    PrintLocation(var);
865
    bool comma = !var->IsUnallocated();
866
    if (var->has_forced_context_allocation()) {
867
      if (comma) PrintF(", ");
868
      PrintF("forced context allocation");
869 870
      comma = true;
    }
871
    if (var->maybe_assigned() == kMaybeAssigned) {
872 873
      if (comma) PrintF(", ");
      PrintF("maybe assigned");
874
    }
875 876 877 878 879
    PrintF("\n");
  }
}


880
static void PrintMap(int indent, VariableMap* map) {
881
  for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
882
    Variable* var = reinterpret_cast<Variable*>(p->value);
883
    PrintVar(indent, var);
884 885 886 887
  }
}


888 889 890 891 892
void Scope::Print(int n) {
  int n0 = (n > 0 ? n : 0);
  int n1 = n0 + 2;  // indentation

  // Print header.
893
  Indent(n0, Header(scope_type_));
894
  if (!scope_name_->IsEmpty()) {
895 896 897 898 899 900 901 902 903
    PrintF(" ");
    PrintName(scope_name_);
  }

  // Print parameters, if any.
  if (is_function_scope()) {
    PrintF(" (");
    for (int i = 0; i < params_.length(); i++) {
      if (i > 0) PrintF(", ");
904
      PrintName(params_[i]->raw_name());
905 906 907 908
    }
    PrintF(")");
  }

909
  PrintF(" { // (%d, %d)\n", start_position(), end_position());
910 911 912 913

  // Function name, if any (named function literals, only).
  if (function_ != NULL) {
    Indent(n1, "// (local) function name: ");
914
    PrintName(function_->proxy()->raw_name());
915 916 917 918 919 920 921
    PrintF("\n");
  }

  // Scope info.
  if (HasTrivialOuterContext()) {
    Indent(n1, "// scope has trivial outer context\n");
  }
rossberg's avatar
rossberg committed
922 923 924
  if (is_strong(language_mode())) {
    Indent(n1, "// strong mode scope\n");
  } else if (is_strict(language_mode())) {
925
    Indent(n1, "// strict mode scope\n");
926
  }
927 928 929
  if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
  if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
  if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
930
  if (scope_uses_arguments_) Indent(n1, "// scope uses 'arguments'\n");
931 932
  if (scope_uses_super_property_)
    Indent(n1, "// scope uses 'super' property\n");
933
  if (scope_uses_this_) Indent(n1, "// scope uses 'this'\n");
934 935 936
  if (inner_scope_uses_arguments_) {
    Indent(n1, "// inner scope uses 'arguments'\n");
  }
937 938
  if (inner_scope_uses_super_property_)
    Indent(n1, "// inner scope uses 'super' property\n");
939
  if (inner_scope_uses_this_) Indent(n1, "// inner scope uses 'this'\n");
940 941
  if (outer_scope_calls_sloppy_eval_) {
    Indent(n1, "// outer scope calls 'eval' in sloppy context\n");
942
  }
943 944 945 946 947 948 949 950
  if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
  if (num_stack_slots_ > 0) { Indent(n1, "// ");
  PrintF("%d stack slots\n", num_stack_slots_); }
  if (num_heap_slots_ > 0) { Indent(n1, "// ");
  PrintF("%d heap slots\n", num_heap_slots_); }

  // Print locals.
  if (function_ != NULL) {
951
    Indent(n1, "// function var:\n");
952
    PrintVar(n1, function_->proxy()->var());
953 954
  }

955 956 957 958 959
  if (temps_.length() > 0) {
    Indent(n1, "// temporary vars:\n");
    for (int i = 0; i < temps_.length(); i++) {
      PrintVar(n1, temps_[i]);
    }
960 961
  }

962 963 964 965 966
  if (internals_.length() > 0) {
    Indent(n1, "// internal vars:\n");
    for (int i = 0; i < internals_.length(); i++) {
      PrintVar(n1, internals_[i]);
    }
967 968
  }

969 970 971 972
  if (variables_.Start() != NULL) {
    Indent(n1, "// local vars:\n");
    PrintMap(n1, &variables_);
  }
973

974
  if (dynamics_ != NULL) {
975
    Indent(n1, "// dynamic vars:\n");
976 977 978
    PrintMap(n1, dynamics_->GetMap(DYNAMIC));
    PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
    PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
979
  }
980 981 982 983 984 985 986 987 988 989 990 991 992 993

  // Print inner scopes (disable by providing negative n).
  if (n >= 0) {
    for (int i = 0; i < inner_scopes_.length(); i++) {
      PrintF("\n");
      inner_scopes_[i]->Print(n1);
    }
  }

  Indent(n0, "}\n");
}
#endif  // DEBUG


994 995
Variable* Scope::NonLocal(const AstRawString* name, VariableMode mode) {
  if (dynamics_ == NULL) dynamics_ = new (zone()) DynamicScopePart(zone());
996
  VariableMap* map = dynamics_->GetMap(mode);
997 998 999
  Variable* var = map->Lookup(name);
  if (var == NULL) {
    // Declare a new non-local.
1000 1001 1002 1003 1004 1005 1006
    InitializationFlag init_flag = (mode == VAR)
        ? kCreatedInitialized : kNeedsInitialization;
    var = map->Declare(NULL,
                       name,
                       mode,
                       Variable::NORMAL,
                       init_flag);
1007
    // Allocate it by giving it a dynamic lookup.
1008
    var->AllocateTo(Variable::LOOKUP, -1);
1009 1010 1011 1012 1013
  }
  return var;
}


1014
Variable* Scope::LookupRecursive(VariableProxy* proxy,
1015
                                 BindingKind* binding_kind,
1016
                                 AstNodeFactory* factory) {
1017
  DCHECK(binding_kind != NULL);
1018 1019 1020 1021 1022 1023 1024
  if (already_resolved() && is_with_scope()) {
    // Short-cut: if the scope is deserialized from a scope info, variable
    // allocation is already fixed.  We can simply return with dynamic lookup.
    *binding_kind = DYNAMIC_LOOKUP;
    return NULL;
  }

1025
  // Try to find the variable in this scope.
1026
  Variable* var = LookupLocal(proxy->raw_name());
1027

1028 1029 1030
  // We found a variable and we are done. (Even if there is an 'eval' in
  // this scope which introduces the same variable again, the resulting
  // variable remains the same.)
1031
  if (var != NULL) {
1032 1033
    *binding_kind = BOUND;
    return var;
1034
  }
1035

1036 1037 1038 1039
  // We did not find a variable locally. Check against the function variable,
  // if any. We can do this for all scopes, since the function variable is
  // only present - if at all - for function scopes.
  *binding_kind = UNBOUND;
1040
  var = LookupFunctionVar(proxy->raw_name(), factory);
1041
  if (var != NULL) {
1042 1043
    *binding_kind = BOUND;
  } else if (outer_scope_ != NULL) {
1044
    var = outer_scope_->LookupRecursive(proxy, binding_kind, factory);
1045 1046 1047
    if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
      var->ForceContextAllocation();
    }
1048
  } else {
1049
    DCHECK(is_script_scope());
1050 1051
  }

1052
  if (is_with_scope()) {
1053
    DCHECK(!already_resolved());
1054 1055 1056 1057 1058 1059
    // The current scope is a with scope, so the variable binding can not be
    // statically resolved. However, note that it was necessary to do a lookup
    // in the outer scope anyway, because if a binding exists in an outer scope,
    // the associated variable has to be marked as potentially being accessed
    // from inside of an inner with scope (the property may not be in the 'with'
    // object).
1060
    if (var != NULL && proxy->is_assigned()) var->set_maybe_assigned();
1061 1062
    *binding_kind = DYNAMIC_LOOKUP;
    return NULL;
1063
  } else if (calls_sloppy_eval()) {
1064
    // A variable binding may have been found in an outer scope, but the current
1065
    // scope makes a sloppy 'eval' call, so the found variable may not be
1066 1067 1068 1069 1070 1071 1072
    // the correct one (the 'eval' may introduce a binding with the same name).
    // In that case, change the lookup result to reflect this situation.
    if (*binding_kind == BOUND) {
      *binding_kind = BOUND_EVAL_SHADOWED;
    } else if (*binding_kind == UNBOUND) {
      *binding_kind = UNBOUND_EVAL_SHADOWED;
    }
1073
  }
1074 1075 1076 1077
  return var;
}


1078
bool Scope::ResolveVariable(ParseInfo* info, VariableProxy* proxy,
1079
                            AstNodeFactory* factory) {
1080
  DCHECK(info->script_scope()->is_script_scope());
1081 1082 1083

  // If the proxy is already resolved there's nothing to do
  // (functions and consts may be resolved by the parser).
1084
  if (proxy->is_resolved()) return true;
1085 1086

  // Otherwise, try to resolve the variable.
1087
  BindingKind binding_kind;
1088
  Variable* var = LookupRecursive(proxy, &binding_kind, factory);
1089 1090 1091
  switch (binding_kind) {
    case BOUND:
      // We found a variable binding.
1092
      if (is_strong(language_mode())) {
1093
        if (!CheckStrongModeDeclaration(proxy, var)) return false;
1094
      }
1095
      break;
1096

1097
    case BOUND_EVAL_SHADOWED:
1098 1099 1100 1101
      // We either found a variable binding that might be shadowed by eval  or
      // gave up on it (e.g. by encountering a local with the same in the outer
      // scope which was not promoted to a context, this can happen if we use
      // debugger to evaluate arbitrary expressions at a break point).
1102
      if (var->IsGlobalObjectProperty()) {
1103
        var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1104
      } else if (var->is_dynamic()) {
1105
        var = NonLocal(proxy->raw_name(), DYNAMIC);
1106 1107
      } else {
        Variable* invalidated = var;
1108
        var = NonLocal(proxy->raw_name(), DYNAMIC_LOCAL);
1109 1110 1111
        var->set_local_if_not_shadowed(invalidated);
      }
      break;
1112

1113
    case UNBOUND:
1114
      // No binding has been found. Declare a variable on the global object.
1115
      var = info->script_scope()->DeclareDynamicGlobal(proxy->raw_name());
1116
      break;
1117

1118
    case UNBOUND_EVAL_SHADOWED:
1119
      // No binding has been found. But some scope makes a sloppy 'eval' call.
1120
      var = NonLocal(proxy->raw_name(), DYNAMIC_GLOBAL);
1121
      break;
1122

1123 1124
    case DYNAMIC_LOOKUP:
      // The variable could not be resolved statically.
1125
      var = NonLocal(proxy->raw_name(), DYNAMIC);
1126
      break;
1127 1128
  }

1129
  DCHECK(var != NULL);
1130
  if (proxy->is_assigned()) var->set_maybe_assigned();
1131

1132 1133 1134 1135 1136 1137
  if (is_strong(language_mode())) {
    // Record that the variable is referred to from strong mode. Also, record
    // the position.
    var->RecordStrongModeReference(proxy->position(), proxy->end_position());
  }

1138 1139
  proxy->BindTo(var);

1140
  return true;
1141 1142 1143
}


1144 1145 1146 1147 1148
bool Scope::CheckStrongModeDeclaration(VariableProxy* proxy, Variable* var) {
  // Check for declaration-after use (for variables) in strong mode. Note that
  // we can only do this in the case where we have seen the declaration. And we
  // always allow referencing functions (for now).

1149 1150 1151 1152 1153
  // This might happen during lazy compilation; we don't keep track of
  // initializer positions for variables stored in ScopeInfo, so we cannot check
  // bindings against them. TODO(marja, rossberg): remove this hack.
  if (var->initializer_position() == RelocInfo::kNoPosition) return true;

1154 1155 1156 1157 1158 1159 1160 1161
  // Allow referencing the class name from methods of that class, even though
  // the initializer position for class names is only after the body.
  Scope* scope = this;
  while (scope) {
    if (scope->ClassVariableForMethod() == var) return true;
    scope = scope->outer_scope();
  }

1162
  // Allow references from methods to classes declared later, if we detect no
1163 1164 1165 1166 1167 1168 1169 1170
  // problematic dependency cycles. Note that we can be inside multiple methods
  // at the same time, and it's enough if we find one where the reference is
  // allowed.
  if (var->is_class() &&
      var->AsClassVariable()->declaration_group_start() >= 0) {
    for (scope = this; scope && scope != var->scope();
         scope = scope->outer_scope()) {
      ClassVariable* class_var = scope->ClassVariableForMethod();
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
      // A method is referring to some other class, possibly declared
      // later. Referring to a class declared earlier is always OK and covered
      // by the code outside this if. Here we only need to allow special cases
      // for referring to a class which is declared later.

      // Referring to a class C declared later is OK under the following
      // circumstances:

      // 1. The class declarations are in a consecutive group with no other
      // declarations or statements in between, and

      // 2. There is no dependency cycle where the first edge is an
      // initialization time dependency (computed property name or extends
      // clause) from C to something that depends on this class directly or
      // transitively.
      if (class_var &&
          class_var->declaration_group_start() ==
              var->AsClassVariable()->declaration_group_start()) {
        return true;
1190
      }
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

      // TODO(marja,rossberg): implement the dependency cycle detection. Here we
      // undershoot the target and allow referring to any class in the same
      // consectuive declaration group.

      // The cycle detection can work roughly like this: 1) detect init-time
      // references here (they are free variables which are inside the class
      // scope but not inside a method scope - no parser changes needed to
      // detect them) 2) if we encounter an init-time reference here, allow it,
      // but record it for a later dependency cycle check 3) also record
      // non-init-time references here 4) after scope analysis is done, analyse
      // the dependency cycles: an illegal cycle is one starting with an
      // init-time reference and leading back to the starting point with either
      // non-init-time and init-time references.
1205
    }
1206 1207
  }

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  // If both the use and the declaration are inside an eval scope (possibly
  // indirectly), or one of them is, we need to check whether they are inside
  // the same eval scope or different ones.

  // TODO(marja,rossberg): Detect errors across different evals (depends on the
  // future of eval in strong mode).
  const Scope* eval_for_use = NearestOuterEvalScope();
  const Scope* eval_for_declaration = var->scope()->NearestOuterEvalScope();

  if (proxy->position() != RelocInfo::kNoPosition &&
      proxy->position() < var->initializer_position() && !var->is_function() &&
      eval_for_use == eval_for_declaration) {
    DCHECK(proxy->end_position() != RelocInfo::kNoPosition);
    ReportMessage(proxy->position(), proxy->end_position(),
                  "strong_use_before_declaration", proxy->raw_name());
    return false;
  }
  return true;
}


1229 1230 1231 1232 1233
ClassVariable* Scope::ClassVariableForMethod() const {
  // TODO(marja, rossberg): This fails to find a class variable in the following
  // cases:
  // let A = class { ... }
  // It needs to be investigated whether this causes any practical problems.
1234
  if (!is_function_scope()) return nullptr;
1235
  if (IsInObjectLiteral(function_kind_)) return nullptr;
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
  if (!IsConciseMethod(function_kind_) && !IsConstructor(function_kind_) &&
      !IsAccessorFunction(function_kind_)) {
    return nullptr;
  }
  DCHECK_NOT_NULL(outer_scope_);
  DCHECK(outer_scope_->is_class_scope());
  // The class scope contains at most one variable, the class name.
  DCHECK(outer_scope_->variables_.occupancy() <= 1);
  if (outer_scope_->variables_.occupancy() == 0) return nullptr;
  VariableMap::Entry* p = outer_scope_->variables_.Start();
1246 1247 1248
  Variable* var = reinterpret_cast<Variable*>(p->value);
  if (!var->is_class()) return nullptr;
  return var->AsClassVariable();
1249 1250 1251
}


1252
bool Scope::ResolveVariablesRecursively(ParseInfo* info,
1253
                                        AstNodeFactory* factory) {
1254
  DCHECK(info->script_scope()->is_script_scope());
1255 1256 1257

  // Resolve unresolved variables for this scope.
  for (int i = 0; i < unresolved_.length(); i++) {
1258
    if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1259 1260 1261 1262
  }

  // Resolve unresolved variables for inner scopes.
  for (int i = 0; i < inner_scopes_.length(); i++) {
1263 1264
    if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
      return false;
1265
  }
1266 1267

  return true;
1268 1269 1270
}


1271
void Scope::PropagateScopeInfo(bool outer_scope_calls_sloppy_eval ) {
1272 1273
  if (outer_scope_calls_sloppy_eval) {
    outer_scope_calls_sloppy_eval_ = true;
1274 1275
  }

1276 1277
  bool calls_sloppy_eval =
      this->calls_sloppy_eval() || outer_scope_calls_sloppy_eval_;
1278
  for (int i = 0; i < inner_scopes_.length(); i++) {
1279 1280 1281
    Scope* inner = inner_scopes_[i];
    inner->PropagateScopeInfo(calls_sloppy_eval);
    if (inner->scope_calls_eval_ || inner->inner_scope_calls_eval_) {
1282 1283
      inner_scope_calls_eval_ = true;
    }
1284
    // If the inner scope is an arrow function, propagate the flags tracking
1285
    // usage of arguments/super/this, but do not propagate them out from normal
1286 1287
    // functions.
    if (!inner->is_function_scope() || inner->is_arrow_scope()) {
1288 1289 1290
      if (inner->scope_uses_arguments_ || inner->inner_scope_uses_arguments_) {
        inner_scope_uses_arguments_ = true;
      }
1291 1292 1293 1294
      if (inner->scope_uses_super_property_ ||
          inner->inner_scope_uses_super_property_) {
        inner_scope_uses_super_property_ = true;
      }
1295 1296 1297
      if (inner->scope_uses_this_ || inner->inner_scope_uses_this_) {
        inner_scope_uses_this_ = true;
      }
1298
    }
1299
    if (inner->force_eager_compilation_) {
1300 1301
      force_eager_compilation_ = true;
    }
1302 1303 1304
    if (asm_module_ && inner->scope_type() == FUNCTION_SCOPE) {
      inner->asm_function_ = true;
    }
1305 1306 1307 1308 1309
  }
}


bool Scope::MustAllocate(Variable* var) {
1310 1311 1312
  // Give var a read/write use if there is a chance it might be accessed
  // via an eval() call.  This is only possible if the variable has a
  // visible name.
1313 1314 1315 1316
  if ((var->is_this() || var->is_new_target() || !var->raw_name()->IsEmpty()) &&
      (var->has_forced_context_allocation() || scope_calls_eval_ ||
       inner_scope_calls_eval_ || scope_contains_with_ || is_catch_scope() ||
       is_block_scope() || is_module_scope() || is_script_scope())) {
1317 1318
    var->set_is_used();
    if (scope_calls_eval_ || inner_scope_calls_eval_) var->set_maybe_assigned();
1319
  }
1320
  // Global variables do not need to be allocated.
1321
  return !var->IsGlobalObjectProperty() && var->is_used();
1322 1323 1324 1325
}


bool Scope::MustAllocateInContext(Variable* var) {
1326 1327 1328
  // If var is accessed from an inner scope, or if there is a possibility
  // that it might be accessed from the current or an inner scope (through
  // an eval() call or a runtime with lookup), it must be allocated in the
1329
  // context.
1330
  //
1331 1332 1333 1334 1335
  // Exceptions: If the scope as a whole has forced context allocation, all
  // variables will have context allocation, even temporaries.  Otherwise
  // temporary variables are always stack-allocated.  Catch-bound variables are
  // always context-allocated.
  if (has_forced_context_allocation()) return true;
1336
  if (var->mode() == TEMPORARY) return false;
1337
  if (var->mode() == INTERNAL) return true;
1338
  if (is_catch_scope() || is_module_scope()) return true;
1339
  if (is_script_scope() && IsLexicalVariableMode(var->mode())) return true;
1340
  return var->has_forced_context_allocation() ||
1341 1342
      scope_calls_eval_ ||
      inner_scope_calls_eval_ ||
1343
      scope_contains_with_;
1344 1345 1346
}


1347
bool Scope::HasArgumentsParameter(Isolate* isolate) {
1348
  for (int i = 0; i < params_.length(); i++) {
1349
    if (params_[i]->name().is_identical_to(
1350
            isolate->factory()->arguments_string())) {
1351
      return true;
1352
    }
1353 1354 1355 1356 1357 1358
  }
  return false;
}


void Scope::AllocateStackSlot(Variable* var) {
1359 1360 1361 1362 1363
  if (is_block_scope()) {
    DeclarationScope()->AllocateStackSlot(var);
  } else {
    var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
  }
1364 1365 1366 1367
}


void Scope::AllocateHeapSlot(Variable* var) {
1368
  var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1369 1370 1371
}


1372
void Scope::AllocateParameterLocals(Isolate* isolate) {
1373
  DCHECK(is_function_scope());
1374
  Variable* arguments = LookupLocal(ast_value_factory_->arguments_string());
1375 1376
  // Functions have 'arguments' declared implicitly in all non arrow functions.
  DCHECK(arguments != nullptr || is_arrow_scope());
1377

1378
  bool uses_sloppy_arguments = false;
1379

1380 1381
  if (arguments != nullptr && MustAllocate(arguments) &&
      !HasArgumentsParameter(isolate)) {
1382
    // 'arguments' is used. Unless there is also a parameter called
1383 1384 1385 1386 1387 1388 1389
    // 'arguments', we must be conservative and allocate all parameters to
    // the context assuming they will be captured by the arguments object.
    // If we have a parameter named 'arguments', a (new) value is always
    // assigned to it via the function invocation. Then 'arguments' denotes
    // that specific parameter value and cannot be used to access the
    // parameters, which is why we don't need to allocate an arguments
    // object in that case.
1390 1391 1392

    // We are using 'arguments'. Tell the code generator that is needs to
    // allocate the arguments object by setting 'arguments_'.
1393
    arguments_ = arguments;
1394

1395 1396 1397
    // In strict mode 'arguments' does not alias formal parameters.
    // Therefore in strict mode we allocate parameters as if 'arguments'
    // were not used.
1398
    uses_sloppy_arguments = is_sloppy(language_mode());
1399 1400
  }

1401 1402 1403 1404
  if (rest_parameter_ && !MustAllocate(rest_parameter_)) {
    rest_parameter_ = NULL;
  }

1405 1406 1407 1408 1409 1410
  // The same parameter may occur multiple times in the parameters_ list.
  // If it does, and if it is not copied into the context object, it must
  // receive the highest parameter index for that parameter; thus iteration
  // order is relevant!
  for (int i = params_.length() - 1; i >= 0; --i) {
    Variable* var = params_[i];
1411 1412
    if (var == rest_parameter_) continue;

1413
    DCHECK(var->scope() == this);
1414
    if (uses_sloppy_arguments || has_forced_context_allocation()) {
1415 1416
      // Force context allocation of the parameter.
      var->ForceContextAllocation();
1417 1418
    }

1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    if (MustAllocate(var)) {
      if (MustAllocateInContext(var)) {
        DCHECK(var->IsUnallocated() || var->IsContextSlot());
        if (var->IsUnallocated()) {
          AllocateHeapSlot(var);
        }
      } else {
        DCHECK(var->IsUnallocated() || var->IsParameter());
        if (var->IsUnallocated()) {
          var->AllocateTo(Variable::PARAMETER, i);
        }
1430 1431 1432 1433 1434 1435
      }
    }
  }
}


1436
void Scope::AllocateNonParameterLocal(Isolate* isolate, Variable* var) {
1437
  DCHECK(var->scope() == this);
1438
  DCHECK(!var->IsVariable(isolate->factory()->dot_result_string()) ||
1439 1440
         !var->IsStackLocal());
  if (var->IsUnallocated() && MustAllocate(var)) {
1441 1442 1443 1444 1445 1446 1447 1448 1449
    if (MustAllocateInContext(var)) {
      AllocateHeapSlot(var);
    } else {
      AllocateStackSlot(var);
    }
  }
}


1450
void Scope::AllocateNonParameterLocals(Isolate* isolate) {
1451
  // All variables that have no rewrite yet are non-parameter locals.
1452
  for (int i = 0; i < temps_.length(); i++) {
1453
    AllocateNonParameterLocal(isolate, temps_[i]);
1454 1455
  }

1456
  for (int i = 0; i < internals_.length(); i++) {
1457
    AllocateNonParameterLocal(isolate, internals_[i]);
1458
  }
1459

1460
  ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
1461 1462 1463
  for (VariableMap::Entry* p = variables_.Start();
       p != NULL;
       p = variables_.Next(p)) {
1464
    Variable* var = reinterpret_cast<Variable*>(p->value);
1465 1466 1467 1468 1469
    vars.Add(VarAndOrder(var, p->order), zone());
  }
  vars.Sort(VarAndOrder::Compare);
  int var_count = vars.length();
  for (int i = 0; i < var_count; i++) {
1470
    AllocateNonParameterLocal(isolate, vars[i].var());
1471 1472
  }

1473 1474 1475
  // For now, function_ must be allocated at the very end.  If it gets
  // allocated in the context, it must be the last slot in the context,
  // because of the current ScopeInfo implementation (see
1476 1477
  // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
  if (function_ != NULL) {
1478
    AllocateNonParameterLocal(isolate, function_->proxy()->var());
1479
  }
1480 1481

  if (rest_parameter_) {
1482
    AllocateNonParameterLocal(isolate, rest_parameter_);
1483
  }
1484 1485 1486
}


1487
void Scope::AllocateVariablesRecursively(Isolate* isolate) {
1488 1489 1490
  if (!already_resolved()) {
    num_stack_slots_ = 0;
  }
1491 1492
  // Allocate variables for inner scopes.
  for (int i = 0; i < inner_scopes_.length(); i++) {
1493
    inner_scopes_[i]->AllocateVariablesRecursively(isolate);
1494 1495
  }

1496 1497
  // If scope is already resolved, we still need to allocate
  // variables in inner scopes which might not had been resolved yet.
1498
  if (already_resolved()) return;
1499 1500 1501
  // The number of slots required for variables.
  num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;

1502 1503
  // Allocate variables for this scope.
  // Parameters must be allocated first, if any.
1504 1505
  if (is_function_scope()) AllocateParameterLocals(isolate);
  AllocateNonParameterLocals(isolate);
1506

1507 1508 1509
  // Force allocation of a context for this scope if necessary. For a 'with'
  // scope and for a function scope that makes an 'eval' call we need a context,
  // even if no local variables were statically allocated in the scope.
1510 1511
  // Likewise for modules.
  bool must_have_context = is_with_scope() || is_module_scope() ||
1512
                           (is_function_scope() && calls_sloppy_eval());
1513 1514

  // If we didn't allocate any locals in the local context, then we only
1515 1516
  // need the minimal number of slots if we must have a context.
  if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1517 1518 1519 1520
    num_heap_slots_ = 0;
  }

  // Allocation done.
1521
  DCHECK(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1522 1523
}

1524

1525 1526 1527
void Scope::AllocateModules() {
  DCHECK(is_script_scope());
  DCHECK(!already_resolved());
1528
  for (int i = 0; i < inner_scopes_.length(); i++) {
1529 1530 1531 1532 1533 1534 1535 1536
    Scope* scope = inner_scopes_.at(i);
    if (scope->is_module_scope()) {
      DCHECK(!scope->already_resolved());
      DCHECK(scope->module_descriptor_->IsFrozen());
      DCHECK_NULL(scope->module_var_);
      scope->module_var_ = NewInternal(ast_value_factory_->dot_module_string());
      ++num_modules_;
    }
1537 1538 1539 1540
  }
}


1541 1542 1543 1544
int Scope::StackLocalCount() const {
  return num_stack_slots() -
      (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
}
1545 1546


1547 1548 1549 1550
int Scope::ContextLocalCount() const {
  if (num_heap_slots() == 0) return 0;
  return num_heap_slots() - Context::MIN_CONTEXT_SLOTS -
      (function_ != NULL && function_->proxy()->var()->IsContextSlot() ? 1 : 0);
1551
}
1552
} }  // namespace v8::internal