scopes.cc 44.3 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

30 31
#include "scopes.h"

32
#include "accessors.h"
33 34
#include "bootstrapper.h"
#include "compiler.h"
35
#include "messages.h"
36 37
#include "scopeinfo.h"

38 39
#include "allocation-inl.h"

40 41
namespace v8 {
namespace internal {
42 43 44 45 46 47 48 49 50 51 52 53 54

// ----------------------------------------------------------------------------
// 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.

static bool Match(void* key1, void* key2) {
  String* name1 = *reinterpret_cast<String**>(key1);
  String* name2 = *reinterpret_cast<String**>(key2);
55 56
  ASSERT(name1->IsInternalizedString());
  ASSERT(name2->IsInternalizedString());
57 58 59 60
  return name1 == name2;
}


61 62 63
VariableMap::VariableMap(Zone* zone)
    : ZoneHashMap(Match, 8, ZoneAllocationPolicy(zone)),
      zone_(zone) {}
64
VariableMap::~VariableMap() {}
65 66


67 68 69 70 71 72
Variable* VariableMap::Declare(
    Scope* scope,
    Handle<String> name,
    VariableMode mode,
    bool is_valid_lhs,
    Variable::Kind kind,
73 74
    InitializationFlag initialization_flag,
    Interface* interface) {
75 76
  Entry* p = ZoneHashMap::Lookup(name.location(), name->Hash(), true,
                                 ZoneAllocationPolicy(zone()));
77 78 79
  if (p->value == NULL) {
    // The variable has not been declared yet -> insert it.
    ASSERT(p->key == name.location());
80 81 82 83 84 85 86
    p->value = new(zone()) Variable(scope,
                                    name,
                                    mode,
                                    is_valid_lhs,
                                    kind,
                                    initialization_flag,
                                    interface);
87 88 89 90 91
  }
  return reinterpret_cast<Variable*>(p->value);
}


92
Variable* VariableMap::Lookup(Handle<String> name) {
93 94
  Entry* p = ZoneHashMap::Lookup(name.location(), name->Hash(), false,
                                 ZoneAllocationPolicy(NULL));
95 96 97 98 99 100 101 102 103 104 105 106
  if (p != NULL) {
    ASSERT(*reinterpret_cast<String**>(p->key) == *name);
    ASSERT(p->value != NULL);
    return reinterpret_cast<Variable*>(p->value);
  }
  return NULL;
}


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

107
Scope::Scope(Scope* outer_scope, ScopeType type, Zone* zone)
108
    : isolate_(zone->isolate()),
109 110
      inner_scopes_(4, zone),
      variables_(zone),
111
      internals_(4, zone),
112 113 114 115
      temps_(4, zone),
      params_(4, zone),
      unresolved_(16, zone),
      decls_(4, zone),
116 117
      interface_(FLAG_harmony_modules &&
                 (type == MODULE_SCOPE || type == GLOBAL_SCOPE)
118 119 120
                     ? Interface::NewModule(zone) : NULL),
      already_resolved_(false),
      zone_(zone) {
121
  SetDefaults(type, outer_scope, Handle<ScopeInfo>::null());
122 123
  // The outermost scope must be a global scope.
  ASSERT(type == GLOBAL_SCOPE || outer_scope != NULL);
124 125 126 127
  ASSERT(!HasIllegalRedeclaration());
}


128
Scope::Scope(Scope* inner_scope,
129
             ScopeType type,
130 131
             Handle<ScopeInfo> scope_info,
             Zone* zone)
132
    : isolate_(Isolate::Current()),
133 134
      inner_scopes_(4, zone),
      variables_(zone),
135
      internals_(4, zone),
136 137 138 139
      temps_(4, zone),
      params_(4, zone),
      unresolved_(16, zone),
      decls_(4, zone),
140
      interface_(NULL),
141 142
      already_resolved_(true),
      zone_(zone) {
143
  SetDefaults(type, NULL, scope_info);
144 145
  if (!scope_info.is_null()) {
    num_heap_slots_ = scope_info_->ContextLength();
146
  }
147 148 149
  // 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));
150 151 152
  AddInnerScope(inner_scope);
}

153

154
Scope::Scope(Scope* inner_scope, Handle<String> catch_variable_name, Zone* zone)
155
    : isolate_(Isolate::Current()),
156 157
      inner_scopes_(1, zone),
      variables_(zone),
158
      internals_(0, zone),
159 160 161 162
      temps_(0, zone),
      params_(0, zone),
      unresolved_(0, zone),
      decls_(0, zone),
163
      interface_(NULL),
164 165
      already_resolved_(true),
      zone_(zone) {
166
  SetDefaults(CATCH_SCOPE, NULL, Handle<ScopeInfo>::null());
167
  AddInnerScope(inner_scope);
168
  ++num_var_or_const_;
169
  num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
170 171
  Variable* variable = variables_.Declare(this,
                                          catch_variable_name,
172
                                          VAR,
173
                                          true,  // Valid left-hand side.
174 175
                                          Variable::NORMAL,
                                          kCreatedInitialized);
176
  AllocateHeapSlot(variable);
177 178 179
}


180
void Scope::SetDefaults(ScopeType type,
181
                        Scope* outer_scope,
182
                        Handle<ScopeInfo> scope_info) {
183 184
  outer_scope_ = outer_scope;
  type_ = type;
185
  scope_name_ = isolate_->factory()->empty_string();
186 187 188 189 190 191 192 193 194
  dynamics_ = NULL;
  receiver_ = NULL;
  function_ = NULL;
  arguments_ = NULL;
  illegal_redecl_ = NULL;
  scope_inside_with_ = false;
  scope_contains_with_ = false;
  scope_calls_eval_ = false;
  // Inherit the strict mode from the parent scope.
195 196
  language_mode_ = (outer_scope != NULL)
      ? outer_scope->language_mode_ : CLASSIC_MODE;
197
  outer_scope_calls_non_strict_eval_ = false;
198 199
  inner_scope_calls_eval_ = false;
  force_eager_compilation_ = false;
200 201
  force_context_allocation_ = (outer_scope != NULL && !is_function_scope())
      ? outer_scope->has_forced_context_allocation() : false;
202
  num_var_or_const_ = 0;
203 204
  num_stack_slots_ = 0;
  num_heap_slots_ = 0;
205 206
  num_modules_ = 0;
  module_var_ = NULL,
207
  scope_info_ = scope_info;
208 209
  start_position_ = RelocInfo::kNoPosition;
  end_position_ = RelocInfo::kNoPosition;
210 211
  if (!scope_info.is_null()) {
    scope_calls_eval_ = scope_info->CallsEval();
212
    language_mode_ = scope_info->language_mode();
213
  }
214 215 216
}


217 218
Scope* Scope::DeserializeScopeChain(Context* context, Scope* global_scope,
                                    Zone* zone) {
219 220
  // Reconstruct the outer scope chain from a closure's context chain.
  Scope* current_scope = NULL;
221
  Scope* innermost_scope = NULL;
222
  bool contains_with = false;
223
  while (!context->IsNativeContext()) {
224
    if (context->IsWithContext()) {
225 226 227 228
      Scope* with_scope = new(zone) Scope(current_scope,
                                          WITH_SCOPE,
                                          Handle<ScopeInfo>::null(),
                                          zone);
229
      current_scope = with_scope;
230 231 232 233 234
      // 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;
      }
235 236 237 238 239 240
    } else if (context->IsGlobalContext()) {
      ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
      current_scope = new(zone) Scope(current_scope,
                                      GLOBAL_SCOPE,
                                      Handle<ScopeInfo>(scope_info),
                                      zone);
241 242 243 244 245 246
    } else if (context->IsModuleContext()) {
      ScopeInfo* scope_info = ScopeInfo::cast(context->module()->scope_info());
      current_scope = new(zone) Scope(current_scope,
                                      MODULE_SCOPE,
                                      Handle<ScopeInfo>(scope_info),
                                      zone);
247
    } else if (context->IsFunctionContext()) {
248
      ScopeInfo* scope_info = context->closure()->shared()->scope_info();
249 250 251 252
      current_scope = new(zone) Scope(current_scope,
                                      FUNCTION_SCOPE,
                                      Handle<ScopeInfo>(scope_info),
                                      zone);
253
    } else if (context->IsBlockContext()) {
254
      ScopeInfo* scope_info = ScopeInfo::cast(context->extension());
255 256 257 258
      current_scope = new(zone) Scope(current_scope,
                                      BLOCK_SCOPE,
                                      Handle<ScopeInfo>(scope_info),
                                      zone);
259
    } else {
260 261
      ASSERT(context->IsCatchContext());
      String* name = String::cast(context->extension());
262 263
      current_scope = new(zone) Scope(
          current_scope, Handle<String>(name), zone);
264
    }
265 266
    if (contains_with) current_scope->RecordWithStatement();
    if (innermost_scope == NULL) innermost_scope = current_scope;
267

268 269 270 271 272 273
    // 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();
  }
274

275
  global_scope->AddInnerScope(current_scope);
276
  global_scope->PropagateScopeInfo(false);
277
  return (innermost_scope == NULL) ? global_scope : innermost_scope;
278 279
}

280

281 282
bool Scope::Analyze(CompilationInfo* info) {
  ASSERT(info->function() != NULL);
283 284
  Scope* scope = info->function()->scope();
  Scope* top = scope;
285

286 287 288 289 290 291 292
  // Traverse the scope tree up to the first unresolved scope or the global
  // scope and start scope resolution and variable allocation from that scope.
  while (!top->is_global_scope() &&
         !top->outer_scope()->already_resolved()) {
    top = top->outer_scope();
  }

293 294
  // Allocate the variables.
  {
295 296
    AstNodeFactory<AstNullVisitor> ast_node_factory(info->isolate(),
                                                    info->zone());
297
    if (!top->AllocateVariables(info, &ast_node_factory)) return false;
298
  }
299 300

#ifdef DEBUG
301
  if (info->isolate()->bootstrapper()->IsActive()
302 303
          ? FLAG_print_builtin_scopes
          : FLAG_print_scopes) {
304
    scope->Print();
305
  }
306 307 308 309 310

  if (FLAG_harmony_modules && FLAG_print_interfaces && top->is_global_scope()) {
    PrintF("global : ");
    top->interface()->Print();
  }
311 312
#endif

313
  info->SetScope(scope);
314
  return true;
315 316 317
}


318
void Scope::Initialize() {
319
  ASSERT(!already_resolved());
320

321 322
  // Add this scope as a new inner scope of the outer scope.
  if (outer_scope_ != NULL) {
323
    outer_scope_->inner_scopes_.Add(this, zone());
324
    scope_inside_with_ = outer_scope_->scope_inside_with_ || is_with_scope();
325
  } else {
326
    scope_inside_with_ = is_with_scope();
327 328 329 330 331 332 333 334 335 336
  }

  // Declare convenience variables.
  // Declare and allocate receiver (even for the global scope, and even
  // if naccesses_ == 0).
  // NOTE: When loading parameters in the global 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
337
  if (is_declaration_scope()) {
338
    Variable* var =
339
        variables_.Declare(this,
340
                           isolate_->factory()->this_string(),
341
                           VAR,
342
                           false,
343 344
                           Variable::THIS,
                           kCreatedInitialized);
345
    var->AllocateTo(Variable::PARAMETER, -1);
346
    receiver_ = var;
347 348 349
  } else {
    ASSERT(outer_scope() != NULL);
    receiver_ = outer_scope()->receiver();
350
  }
351 352 353

  if (is_function_scope()) {
    // Declare 'arguments' variable which exists in all functions.
354 355
    // Note that it might never be accessed, in which case it won't be
    // allocated during variable allocation.
356
    variables_.Declare(this,
357
                       isolate_->factory()->arguments_string(),
358
                       VAR,
359
                       true,
360 361
                       Variable::ARGUMENTS,
                       kCreatedInitialized);
362 363 364 365
  }
}


366 367
Scope* Scope::FinalizeBlockScope() {
  ASSERT(is_block_scope());
368
  ASSERT(internals_.is_empty());
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  ASSERT(temps_.is_empty());
  ASSERT(params_.is_empty());

  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++) {
389
    outer_scope()->unresolved_.Add(unresolved_[i], zone());
390 391 392 393 394 395
  }

  return NULL;
}


396
Variable* Scope::LocalLookup(Handle<String> name) {
397
  Variable* result = variables_.Lookup(name);
398
  if (result != NULL || scope_info_.is_null()) {
399 400
    return result;
  }
401
  // If we have a serialized scope info, we might find the variable there.
402
  // There should be no local slot with the given name.
403 404
  ASSERT(scope_info_->StackSlotIndex(*name) < 0);

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

    mode = DYNAMIC;
    location = Variable::LOOKUP;
    init_flag = kCreatedInitialized;
418 419
  }

420 421
  Variable* var = variables_.Declare(this, name, mode, true, Variable::NORMAL,
                                     init_flag);
422
  var->AllocateTo(location, index);
423
  return var;
424 425 426
}


427 428
Variable* Scope::LookupFunctionVar(Handle<String> name,
                                   AstNodeFactory<AstNullVisitor>* factory) {
429 430
  if (function_ != NULL && function_->proxy()->name().is_identical_to(name)) {
    return function_->proxy()->var();
431 432 433 434 435
  } else if (!scope_info_.is_null()) {
    // If we are backed by a scope info, try to lookup the variable there.
    VariableMode mode;
    int index = scope_info_->FunctionContextSlotIndex(*name, &mode);
    if (index < 0) return NULL;
436
    Variable* var = new(zone()) Variable(
437 438 439 440 441 442
        this, name, mode, true /* is valid LHS */,
        Variable::NORMAL, kCreatedInitialized);
    VariableProxy* proxy = factory->NewVariableProxy(var);
    VariableDeclaration* declaration =
        factory->NewVariableDeclaration(proxy, mode, this);
    DeclareFunctionVar(declaration);
443 444 445 446 447 448 449 450
    var->AllocateTo(Variable::CONTEXT, index);
    return var;
  } else {
    return NULL;
  }
}


451 452 453 454
Variable* Scope::Lookup(Handle<String> name) {
  for (Scope* scope = this;
       scope != NULL;
       scope = scope->outer_scope()) {
455
    Variable* var = scope->LocalLookup(name);
456 457 458 459 460 461
    if (var != NULL) return var;
  }
  return NULL;
}


462
void Scope::DeclareParameter(Handle<String> name, VariableMode mode) {
463
  ASSERT(!already_resolved());
464
  ASSERT(is_function_scope());
465 466 467
  Variable* var = variables_.Declare(this, name, mode, true, Variable::NORMAL,
                                     kCreatedInitialized);
  params_.Add(var, zone());
468 469 470
}


471 472
Variable* Scope::DeclareLocal(Handle<String> name,
                              VariableMode mode,
473 474
                              InitializationFlag init_flag,
                              Interface* interface) {
475
  ASSERT(!already_resolved());
476 477 478
  // This function handles VAR and CONST modes.  DYNAMIC variables are
  // introduces during variable allocation, INTERNAL variables are allocated
  // explicitly, and TEMPORARY variables are allocated via NewTemporary().
479
  ASSERT(IsDeclaredVariableMode(mode));
480
  ++num_var_or_const_;
481 482
  return variables_.Declare(
      this, name, mode, true, Variable::NORMAL, init_flag, interface);
483 484 485
}


486
Variable* Scope::DeclareDynamicGlobal(Handle<String> name) {
487
  ASSERT(is_global_scope());
488 489 490
  return variables_.Declare(this,
                            name,
                            DYNAMIC_GLOBAL,
491
                            true,
492 493
                            Variable::NORMAL,
                            kCreatedInitialized);
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
}


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


509 510 511 512 513 514 515 516 517 518 519 520 521
Variable* Scope::NewInternal(Handle<String> name) {
  ASSERT(!already_resolved());
  Variable* var = new(zone()) Variable(this,
                                       name,
                                       INTERNAL,
                                       false,
                                       Variable::NORMAL,
                                       kCreatedInitialized);
  internals_.Add(var, zone());
  return var;
}


522
Variable* Scope::NewTemporary(Handle<String> name) {
523
  ASSERT(!already_resolved());
524 525 526 527 528 529 530
  Variable* var = new(zone()) Variable(this,
                                       name,
                                       TEMPORARY,
                                       true,
                                       Variable::NORMAL,
                                       kCreatedInitialized);
  temps_.Add(var, zone());
531
  return var;
532 533 534 535
}


void Scope::AddDeclaration(Declaration* declaration) {
536
  decls_.Add(declaration, zone());
537 538 539 540
}


void Scope::SetIllegalRedeclaration(Expression* expression) {
541
  // Record only the first illegal redeclaration.
542 543 544 545 546 547 548
  if (!HasIllegalRedeclaration()) {
    illegal_redecl_ = expression;
  }
  ASSERT(HasIllegalRedeclaration());
}


549
void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
550 551 552 553 554
  ASSERT(HasIllegalRedeclaration());
  illegal_redecl_->Accept(visitor);
}


555 556 557 558
Declaration* Scope::CheckConflictingVarDeclarations() {
  int length = decls_.length();
  for (int i = 0; i < length; i++) {
    Declaration* decl = decls_[i];
559
    if (decl->mode() != VAR) continue;
560
    Handle<String> name = decl->proxy()->name();
561 562 563 564 565

    // Iterate through all scopes until and including the declaration scope.
    Scope* previous = NULL;
    Scope* current = decl->scope();
    do {
566
      // There is a conflict if there exists a non-VAR binding.
567
      Variable* other_var = current->variables_.Lookup(name);
568
      if (other_var != NULL && other_var->mode() != VAR) {
569 570
        return decl;
      }
571 572 573
      previous = current;
      current = current->outer_scope_;
    } while (!previous->is_declaration_scope());
574 575 576 577 578
  }
  return NULL;
}


579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
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_;
};


594 595 596 597 598
void Scope::CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
                                         ZoneList<Variable*>* context_locals) {
  ASSERT(stack_locals != NULL);
  ASSERT(context_locals != NULL);

599 600 601 602 603 604 605 606 607
  // 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()) {
      ASSERT(var->IsContextSlot());
      context_locals->Add(var, zone());
    }
  }

608 609
  // Collect temporaries which are always allocated on the stack, unless the
  // context as a whole has forced context allocation.
610 611
  for (int i = 0; i < temps_.length(); i++) {
    Variable* var = temps_[i];
612
    if (var->is_used()) {
613 614 615 616 617 618 619
      if (var->IsContextSlot()) {
        ASSERT(has_forced_context_allocation());
        context_locals->Add(var, zone());
      } else {
        ASSERT(var->IsStackLocal());
        stack_locals->Add(var, zone());
      }
620 621
    }
  }
622 623

  // Collect declared local variables.
624
  ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
625 626 627
  for (VariableMap::Entry* p = variables_.Start();
       p != NULL;
       p = variables_.Next(p)) {
628
    Variable* var = reinterpret_cast<Variable*>(p->value);
629
    if (var->is_used()) {
630 631 632 633 634 635 636 637 638 639 640
      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());
641 642 643 644 645
    }
  }
}


646
bool Scope::AllocateVariables(CompilationInfo* info,
647
                              AstNodeFactory<AstNullVisitor>* factory) {
648
  // 1) Propagate scope information.
649
  bool outer_scope_calls_non_strict_eval = false;
650 651 652 653
  if (outer_scope_ != NULL) {
    outer_scope_calls_non_strict_eval =
        outer_scope_->outer_scope_calls_non_strict_eval() |
        outer_scope_->calls_non_strict_eval();
654
  }
655
  PropagateScopeInfo(outer_scope_calls_non_strict_eval);
656

657 658 659 660 661 662 663
  // 2) Allocate module instances.
  if (FLAG_harmony_modules && (is_global_scope() || is_module_scope())) {
    ASSERT(num_modules_ == 0);
    AllocateModulesRecursively(this);
  }

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

666
  // 4) Allocate variables.
667
  AllocateVariablesRecursively();
668 669

  return true;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
}


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


697 698 699
bool Scope::HasLazyCompilableOuterContext() const {
  Scope* outer = outer_scope_;
  if (outer == NULL) return true;
700 701 702
  // 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.
703 704 705 706 707 708 709 710 711
  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;
    if (scope->is_declaration_scope() && scope->num_heap_slots() > 0) {
      found_non_trivial_declarations = true;
    }
  }
  return true;
712 713 714
}


715 716
bool Scope::AllowsLazyCompilation() const {
  return !force_eager_compilation_ && HasLazyCompilableOuterContext();
717 718 719
}


720 721
bool Scope::AllowsLazyCompilationWithoutContext() const {
  return !force_eager_compilation_ && HasTrivialOuterContext();
722 723 724
}


725 726 727 728 729 730 731 732 733 734
int Scope::ContextChainLength(Scope* scope) {
  int n = 0;
  for (Scope* s = this; s != scope; s = s->outer_scope_) {
    ASSERT(s != NULL);  // scope must be in the scope chain
    if (s->num_heap_slots() > 0) n++;
  }
  return n;
}


735 736 737 738 739 740 741 742 743
Scope* Scope::GlobalScope() {
  Scope* scope = this;
  while (!scope->is_global_scope()) {
    scope = scope->outer_scope();
  }
  return scope;
}


744 745
Scope* Scope::DeclarationScope() {
  Scope* scope = this;
746
  while (!scope->is_declaration_scope()) {
747 748 749 750 751 752
    scope = scope->outer_scope();
  }
  return scope;
}


753
Handle<ScopeInfo> Scope::GetScopeInfo() {
754
  if (scope_info_.is_null()) {
755
    scope_info_ = ScopeInfo::Create(this, zone());
756 757 758 759 760
  }
  return scope_info_;
}


761
void Scope::GetNestedScopeChain(
762
    List<Handle<ScopeInfo> >* chain,
763
    int position) {
764
  if (!is_eval_scope()) chain->Add(Handle<ScopeInfo>(GetScopeInfo()));
765 766 767 768 769 770

  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();
    ASSERT(beg_pos >= 0 && end_pos >= 0);
771
    if (beg_pos <= position && position < end_pos) {
772 773 774 775 776 777 778
      scope->GetNestedScopeChain(chain, position);
      return;
    }
  }
}


779
#ifdef DEBUG
780
static const char* Header(ScopeType type) {
781
  switch (type) {
782 783
    case EVAL_SCOPE: return "eval";
    case FUNCTION_SCOPE: return "function";
784
    case MODULE_SCOPE: return "module";
785 786 787 788
    case GLOBAL_SCOPE: return "global";
    case CATCH_SCOPE: return "catch";
    case BLOCK_SCOPE: return "block";
    case WITH_SCOPE: return "with";
789 790 791 792 793 794 795 796 797 798 799 800
  }
  UNREACHABLE();
  return NULL;
}


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


static void PrintName(Handle<String> name) {
801
  SmartArrayPointer<char> s = name->ToCString(DISALLOW_NULLS);
802 803 804 805
  PrintF("%s", *s);
}


806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
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()) {
828 829 830 831
    Indent(indent, Variable::Mode2String(var->mode()));
    PrintF(" ");
    PrintName(var->name());
    PrintF(";  // ");
832
    PrintLocation(var);
833
    if (var->has_forced_context_allocation()) {
834
      if (!var->IsUnallocated()) PrintF(", ");
835
      PrintF("forced context allocation");
836
    }
837 838 839 840 841
    PrintF("\n");
  }
}


842
static void PrintMap(int indent, VariableMap* map) {
843
  for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
844
    Variable* var = reinterpret_cast<Variable*>(p->value);
845
    PrintVar(indent, var);
846 847 848 849
  }
}


850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
void Scope::Print(int n) {
  int n0 = (n > 0 ? n : 0);
  int n1 = n0 + 2;  // indentation

  // Print header.
  Indent(n0, Header(type_));
  if (scope_name_->length() > 0) {
    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(", ");
      PrintName(params_[i]->name());
    }
    PrintF(")");
  }

871
  PrintF(" { // (%d, %d)\n", start_position(), end_position());
872 873 874 875

  // Function name, if any (named function literals, only).
  if (function_ != NULL) {
    Indent(n1, "// (local) function name: ");
876
    PrintName(function_->proxy()->name());
877 878 879 880 881 882 883
    PrintF("\n");
  }

  // Scope info.
  if (HasTrivialOuterContext()) {
    Indent(n1, "// scope has trivial outer context\n");
  }
884 885 886 887 888 889 890 891 892 893
  switch (language_mode()) {
    case CLASSIC_MODE:
      break;
    case STRICT_MODE:
      Indent(n1, "// strict mode scope\n");
      break;
    case EXTENDED_MODE:
      Indent(n1, "// extended mode scope\n");
      break;
  }
894 895 896
  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");
897 898 899
  if (outer_scope_calls_non_strict_eval_) {
    Indent(n1, "// outer scope calls 'eval' in non-strict context\n");
  }
900 901 902 903 904 905 906 907 908
  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.
  Indent(n1, "// function var\n");
  if (function_ != NULL) {
909
    PrintVar(n1, function_->proxy()->var());
910 911 912 913
  }

  Indent(n1, "// temporary vars\n");
  for (int i = 0; i < temps_.length(); i++) {
914
    PrintVar(n1, temps_[i]);
915 916
  }

917 918 919 920 921
  Indent(n1, "// internal vars\n");
  for (int i = 0; i < internals_.length(); i++) {
    PrintVar(n1, internals_[i]);
  }

922
  Indent(n1, "// local vars\n");
923
  PrintMap(n1, &variables_);
924

925
  Indent(n1, "// dynamic vars\n");
926
  if (dynamics_ != NULL) {
927 928 929
    PrintMap(n1, dynamics_->GetMap(DYNAMIC));
    PrintMap(n1, dynamics_->GetMap(DYNAMIC_LOCAL));
    PrintMap(n1, dynamics_->GetMap(DYNAMIC_GLOBAL));
930
  }
931 932 933 934 935 936 937 938 939 940 941 942 943 944

  // 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


945
Variable* Scope::NonLocal(Handle<String> name, VariableMode mode) {
946
  if (dynamics_ == NULL) dynamics_ = new(zone()) DynamicScopePart(zone());
947
  VariableMap* map = dynamics_->GetMap(mode);
948 949 950
  Variable* var = map->Lookup(name);
  if (var == NULL) {
    // Declare a new non-local.
951 952 953 954 955 956 957 958
    InitializationFlag init_flag = (mode == VAR)
        ? kCreatedInitialized : kNeedsInitialization;
    var = map->Declare(NULL,
                       name,
                       mode,
                       true,
                       Variable::NORMAL,
                       init_flag);
959
    // Allocate it by giving it a dynamic lookup.
960
    var->AllocateTo(Variable::LOOKUP, -1);
961 962 963 964 965
  }
  return var;
}


966
Variable* Scope::LookupRecursive(Handle<String> name,
967 968
                                 BindingKind* binding_kind,
                                 AstNodeFactory<AstNullVisitor>* factory) {
969
  ASSERT(binding_kind != NULL);
970
  // Try to find the variable in this scope.
971
  Variable* var = LocalLookup(name);
972

973 974 975
  // 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.)
976
  if (var != NULL) {
977 978
    *binding_kind = BOUND;
    return var;
979
  }
980

981 982 983 984
  // 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;
985
  var = LookupFunctionVar(name, factory);
986
  if (var != NULL) {
987 988
    *binding_kind = BOUND;
  } else if (outer_scope_ != NULL) {
989
    var = outer_scope_->LookupRecursive(name, binding_kind, factory);
990 991 992
    if (*binding_kind == BOUND && (is_function_scope() || is_with_scope())) {
      var->ForceContextAllocation();
    }
993 994
  } else {
    ASSERT(is_global_scope());
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  }

  if (is_with_scope()) {
    // 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).
    *binding_kind = DYNAMIC_LOOKUP;
    return NULL;
  } else if (calls_non_strict_eval()) {
    // A variable binding may have been found in an outer scope, but the current
    // scope makes a non-strict 'eval' call, so the found variable may not be
    // 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;
    }
1016
  }
1017 1018 1019 1020
  return var;
}


1021
bool Scope::ResolveVariable(CompilationInfo* info,
1022 1023
                            VariableProxy* proxy,
                            AstNodeFactory<AstNullVisitor>* factory) {
1024
  ASSERT(info->global_scope()->is_global_scope());
1025 1026 1027

  // If the proxy is already resolved there's nothing to do
  // (functions and consts may be resolved by the parser).
1028
  if (proxy->var() != NULL) return true;
1029 1030

  // Otherwise, try to resolve the variable.
1031
  BindingKind binding_kind;
1032
  Variable* var = LookupRecursive(proxy->name(), &binding_kind, factory);
1033 1034 1035 1036
  switch (binding_kind) {
    case BOUND:
      // We found a variable binding.
      break;
1037

1038
    case BOUND_EVAL_SHADOWED:
1039 1040 1041 1042
      // 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).
1043
      if (var->IsGlobalObjectProperty()) {
1044
        var = NonLocal(proxy->name(), DYNAMIC_GLOBAL);
1045 1046
      } else if (var->is_dynamic()) {
        var = NonLocal(proxy->name(), DYNAMIC);
1047 1048
      } else {
        Variable* invalidated = var;
1049
        var = NonLocal(proxy->name(), DYNAMIC_LOCAL);
1050 1051 1052
        var->set_local_if_not_shadowed(invalidated);
      }
      break;
1053

1054
    case UNBOUND:
1055 1056
      // No binding has been found. Declare a variable on the global object.
      var = info->global_scope()->DeclareDynamicGlobal(proxy->name());
1057
      break;
1058

1059 1060 1061 1062 1063
    case UNBOUND_EVAL_SHADOWED:
      // No binding has been found. But some scope makes a
      // non-strict 'eval' call.
      var = NonLocal(proxy->name(), DYNAMIC_GLOBAL);
      break;
1064

1065 1066 1067 1068
    case DYNAMIC_LOOKUP:
      // The variable could not be resolved statically.
      var = NonLocal(proxy->name(), DYNAMIC);
      break;
1069 1070
  }

1071
  ASSERT(var != NULL);
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
  if (FLAG_harmony_scoping && is_extended_mode() &&
      var->is_const_mode() && proxy->IsLValue()) {
    // Assignment to const. Throw a syntax error.
    MessageLocation location(
        info->script(), proxy->position(), proxy->position());
    Isolate* isolate = Isolate::Current();
    Factory* factory = isolate->factory();
    Handle<JSArray> array = factory->NewJSArray(0);
    Handle<Object> result =
        factory->NewSyntaxError("harmony_const_assign", array);
    isolate->Throw(*result, &location);
    return false;
  }

1087 1088 1089 1090 1091 1092
  if (FLAG_harmony_modules) {
    bool ok;
#ifdef DEBUG
    if (FLAG_print_interface_details)
      PrintF("# Resolve %s:\n", var->name()->ToAsciiArray());
#endif
1093
    proxy->interface()->Unify(var->interface(), zone(), &ok);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
    if (!ok) {
#ifdef DEBUG
      if (FLAG_print_interfaces) {
        PrintF("SCOPES TYPE ERROR\n");
        PrintF("proxy: ");
        proxy->interface()->Print();
        PrintF("var: ");
        var->interface()->Print();
      }
#endif

      // Inconsistent use of module. Throw a syntax error.
      // TODO(rossberg): generate more helpful error message.
1107 1108
      MessageLocation location(
          info->script(), proxy->position(), proxy->position());
1109 1110 1111
      Isolate* isolate = Isolate::Current();
      Factory* factory = isolate->factory();
      Handle<JSArray> array = factory->NewJSArray(1);
rossberg@chromium.org's avatar
rossberg@chromium.org committed
1112
      USE(JSObject::SetElement(array, 0, var->name(), NONE, kStrictMode));
1113 1114 1115 1116 1117 1118 1119
      Handle<Object> result =
          factory->NewSyntaxError("module_type_error", array);
      isolate->Throw(*result, &location);
      return false;
    }
  }

1120 1121
  proxy->BindTo(var);

1122
  return true;
1123 1124 1125
}


1126 1127
bool Scope::ResolveVariablesRecursively(
    CompilationInfo* info,
1128
    AstNodeFactory<AstNullVisitor>* factory) {
1129
  ASSERT(info->global_scope()->is_global_scope());
1130 1131 1132

  // Resolve unresolved variables for this scope.
  for (int i = 0; i < unresolved_.length(); i++) {
1133
    if (!ResolveVariable(info, unresolved_[i], factory)) return false;
1134 1135 1136 1137
  }

  // Resolve unresolved variables for inner scopes.
  for (int i = 0; i < inner_scopes_.length(); i++) {
1138 1139
    if (!inner_scopes_[i]->ResolveVariablesRecursively(info, factory))
      return false;
1140
  }
1141 1142

  return true;
1143 1144 1145
}


1146
bool Scope::PropagateScopeInfo(bool outer_scope_calls_non_strict_eval ) {
1147 1148 1149 1150 1151
  if (outer_scope_calls_non_strict_eval) {
    outer_scope_calls_non_strict_eval_ = true;
  }

  bool calls_non_strict_eval =
1152
      this->calls_non_strict_eval() || outer_scope_calls_non_strict_eval_;
1153 1154
  for (int i = 0; i < inner_scopes_.length(); i++) {
    Scope* inner_scope = inner_scopes_[i];
1155
    if (inner_scope->PropagateScopeInfo(calls_non_strict_eval)) {
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
      inner_scope_calls_eval_ = true;
    }
    if (inner_scope->force_eager_compilation_) {
      force_eager_compilation_ = true;
    }
  }

  return scope_calls_eval_ || inner_scope_calls_eval_;
}


bool Scope::MustAllocate(Variable* var) {
1168 1169 1170
  // 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.
1171
  if ((var->is_this() || var->name()->length() > 0) &&
1172
      (var->has_forced_context_allocation() ||
1173 1174 1175
       scope_calls_eval_ ||
       inner_scope_calls_eval_ ||
       scope_contains_with_ ||
1176
       is_catch_scope() ||
1177
       is_block_scope() ||
1178 1179
       is_module_scope() ||
       is_global_scope())) {
1180
    var->set_is_used(true);
1181
  }
1182
  // Global variables do not need to be allocated.
1183
  return !var->IsGlobalObjectProperty() && var->is_used();
1184 1185 1186 1187
}


bool Scope::MustAllocateInContext(Variable* var) {
1188 1189 1190
  // 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
1191
  // context.
1192
  //
1193 1194 1195 1196 1197
  // 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;
1198
  if (var->mode() == TEMPORARY) return false;
1199
  if (var->mode() == INTERNAL) return true;
1200
  if (is_catch_scope() || is_block_scope() || is_module_scope()) return true;
1201
  if (is_global_scope() && IsLexicalVariableMode(var->mode())) return true;
1202
  return var->has_forced_context_allocation() ||
1203 1204
      scope_calls_eval_ ||
      inner_scope_calls_eval_ ||
1205
      scope_contains_with_;
1206 1207 1208 1209 1210
}


bool Scope::HasArgumentsParameter() {
  for (int i = 0; i < params_.length(); i++) {
1211
    if (params_[i]->name().is_identical_to(
1212
            isolate_->factory()->arguments_string())) {
1213
      return true;
1214
    }
1215 1216 1217 1218 1219 1220
  }
  return false;
}


void Scope::AllocateStackSlot(Variable* var) {
1221
  var->AllocateTo(Variable::LOCAL, num_stack_slots_++);
1222 1223 1224 1225
}


void Scope::AllocateHeapSlot(Variable* var) {
1226
  var->AllocateTo(Variable::CONTEXT, num_heap_slots_++);
1227 1228 1229 1230 1231
}


void Scope::AllocateParameterLocals() {
  ASSERT(is_function_scope());
1232
  Variable* arguments = LocalLookup(isolate_->factory()->arguments_string());
1233
  ASSERT(arguments != NULL);  // functions have 'arguments' declared implicitly
1234

1235
  bool uses_nonstrict_arguments = false;
1236

1237 1238
  if (MustAllocate(arguments) && !HasArgumentsParameter()) {
    // 'arguments' is used. Unless there is also a parameter called
1239 1240 1241 1242 1243 1244 1245
    // '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.
1246 1247 1248

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

1251 1252 1253
    // In strict mode 'arguments' does not alias formal parameters.
    // Therefore in strict mode we allocate parameters as if 'arguments'
    // were not used.
1254
    uses_nonstrict_arguments = is_classic_mode();
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
  }

  // 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];
    ASSERT(var->scope() == this);
    if (uses_nonstrict_arguments) {
1265 1266
      // Force context allocation of the parameter.
      var->ForceContextAllocation();
1267 1268
    }

1269 1270
    if (MustAllocate(var)) {
      if (MustAllocateInContext(var)) {
1271 1272
        ASSERT(var->IsUnallocated() || var->IsContextSlot());
        if (var->IsUnallocated()) {
1273 1274 1275
          AllocateHeapSlot(var);
        }
      } else {
1276 1277 1278
        ASSERT(var->IsUnallocated() || var->IsParameter());
        if (var->IsUnallocated()) {
          var->AllocateTo(Variable::PARAMETER, i);
1279 1280 1281 1282 1283 1284 1285 1286 1287
        }
      }
    }
  }
}


void Scope::AllocateNonParameterLocal(Variable* var) {
  ASSERT(var->scope() == this);
1288
  ASSERT(!var->IsVariable(isolate_->factory()->result_string()) ||
1289 1290
         !var->IsStackLocal());
  if (var->IsUnallocated() && MustAllocate(var)) {
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    if (MustAllocateInContext(var)) {
      AllocateHeapSlot(var);
    } else {
      AllocateStackSlot(var);
    }
  }
}


void Scope::AllocateNonParameterLocals() {
1301
  // All variables that have no rewrite yet are non-parameter locals.
1302 1303 1304 1305
  for (int i = 0; i < temps_.length(); i++) {
    AllocateNonParameterLocal(temps_[i]);
  }

1306 1307 1308
  for (int i = 0; i < internals_.length(); i++) {
    AllocateNonParameterLocal(internals_[i]);
  }
1309

1310
  ZoneList<VarAndOrder> vars(variables_.occupancy(), zone());
1311 1312 1313
  for (VariableMap::Entry* p = variables_.Start();
       p != NULL;
       p = variables_.Next(p)) {
1314
    Variable* var = reinterpret_cast<Variable*>(p->value);
1315 1316 1317 1318 1319 1320
    vars.Add(VarAndOrder(var, p->order), zone());
  }
  vars.Sort(VarAndOrder::Compare);
  int var_count = vars.length();
  for (int i = 0; i < var_count; i++) {
    AllocateNonParameterLocal(vars[i].var());
1321 1322
  }

1323 1324 1325
  // 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
1326 1327
  // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
  if (function_ != NULL) {
1328
    AllocateNonParameterLocal(function_->proxy()->var());
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
  }
}


void Scope::AllocateVariablesRecursively() {
  // Allocate variables for inner scopes.
  for (int i = 0; i < inner_scopes_.length(); i++) {
    inner_scopes_[i]->AllocateVariablesRecursively();
  }

1339 1340
  // If scope is already resolved, we still need to allocate
  // variables in inner scopes which might not had been resolved yet.
1341
  if (already_resolved()) return;
1342 1343 1344 1345
  // The number of slots required for variables.
  num_stack_slots_ = 0;
  num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;

1346 1347 1348 1349 1350
  // Allocate variables for this scope.
  // Parameters must be allocated first, if any.
  if (is_function_scope()) AllocateParameterLocals();
  AllocateNonParameterLocals();

1351 1352 1353
  // 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.
1354 1355
  // Likewise for modules.
  bool must_have_context = is_with_scope() || is_module_scope() ||
1356
      (is_function_scope() && calls_eval());
1357 1358

  // If we didn't allocate any locals in the local context, then we only
1359 1360
  // need the minimal number of slots if we must have a context.
  if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS && !must_have_context) {
1361 1362 1363 1364 1365 1366 1367
    num_heap_slots_ = 0;
  }

  // Allocation done.
  ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
}

1368

1369 1370
void Scope::AllocateModulesRecursively(Scope* host_scope) {
  if (already_resolved()) return;
1371 1372
  if (is_module_scope()) {
    ASSERT(interface_->IsFrozen());
1373
    Handle<String> name = isolate_->factory()->InternalizeOneByteString(
1374
        STATIC_ASCII_VECTOR(".module"));
1375 1376 1377
    ASSERT(module_var_ == NULL);
    module_var_ = host_scope->NewInternal(name);
    ++host_scope->num_modules_;
1378 1379 1380 1381
  }

  for (int i = 0; i < inner_scopes_.length(); i++) {
    Scope* inner_scope = inner_scopes_.at(i);
1382
    inner_scope->AllocateModulesRecursively(host_scope);
1383 1384 1385 1386
  }
}


1387 1388 1389 1390
int Scope::StackLocalCount() const {
  return num_stack_slots() -
      (function_ != NULL && function_->proxy()->var()->IsStackLocal() ? 1 : 0);
}
1391 1392


1393 1394 1395 1396
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);
1397 1398
}

1399
} }  // namespace v8::internal