parser.cc 149 KB
Newer Older
1
// Copyright 2010 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 30 31 32
// 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"

#include "api.h"
#include "ast.h"
#include "bootstrapper.h"
33
#include "codegen.h"
34
#include "compiler.h"
35
#include "func-name-inferrer.h"
36
#include "messages.h"
37
#include "parser.h"
38
#include "platform.h"
39
#include "preparser.h"
40
#include "runtime.h"
41
#include "scopeinfo.h"
42
#include "string-stream.h"
43

44 45 46
#include "ast-inl.h"
#include "jump-target-inl.h"

47 48
namespace v8 {
namespace internal {
49

bak@chromium.org's avatar
bak@chromium.org committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
// PositionStack is used for on-stack allocation of token positions for
// new expressions. Please look at ParseNewExpression.

class PositionStack  {
 public:
  explicit PositionStack(bool* ok) : top_(NULL), ok_(ok) {}
  ~PositionStack() { ASSERT(!*ok_ || is_empty()); }

  class Element  {
   public:
    Element(PositionStack* stack, int value) {
      previous_ = stack->top();
      value_ = value;
      stack->set_top(this);
    }

   private:
    Element* previous() { return previous_; }
    int value() { return value_; }
    friend class PositionStack;
    Element* previous_;
    int value_;
  };

  bool is_empty() { return top_ == NULL; }
  int pop() {
    ASSERT(!is_empty());
    int result = top_->value();
    top_ = top_->previous();
    return result;
  }

 private:
  Element* top() { return top_; }
  void set_top(Element* value) { top_ = value; }
  Element* top_;
  bool* ok_;
};


90
RegExpBuilder::RegExpBuilder()
91 92 93 94
  : pending_empty_(false),
    characters_(NULL),
    terms_(),
    alternatives_()
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
#ifdef DEBUG
  , last_added_(ADD_NONE)
#endif
  {}


void RegExpBuilder::FlushCharacters() {
  pending_empty_ = false;
  if (characters_ != NULL) {
    RegExpTree* atom = new RegExpAtom(characters_->ToConstVector());
    characters_ = NULL;
    text_.Add(atom);
    LAST(ADD_ATOM);
  }
}


void RegExpBuilder::FlushText() {
  FlushCharacters();
  int num_text = text_.length();
  if (num_text == 0) {
    return;
  } else if (num_text == 1) {
    terms_.Add(text_.last());
  } else {
    RegExpText* text = new RegExpText();
    for (int i = 0; i < num_text; i++)
      text_.Get(i)->AppendToText(text);
    terms_.Add(text);
  }
  text_.Clear();
}


void RegExpBuilder::AddCharacter(uc16 c) {
  pending_empty_ = false;
  if (characters_ == NULL) {
    characters_ = new ZoneList<uc16>(4);
  }
  characters_->Add(c);
  LAST(ADD_CHAR);
}


void RegExpBuilder::AddEmpty() {
  pending_empty_ = true;
}


void RegExpBuilder::AddAtom(RegExpTree* term) {
  if (term->IsEmpty()) {
    AddEmpty();
    return;
  }
  if (term->IsTextElement()) {
    FlushCharacters();
    text_.Add(term);
  } else {
    FlushText();
    terms_.Add(term);
  }
  LAST(ADD_ATOM);
}


void RegExpBuilder::AddAssertion(RegExpTree* assert) {
  FlushText();
  terms_.Add(assert);
  LAST(ADD_ASSERT);
}


void RegExpBuilder::NewAlternative() {
  FlushTerms();
}


void RegExpBuilder::FlushTerms() {
  FlushText();
  int num_terms = terms_.length();
  RegExpTree* alternative;
  if (num_terms == 0) {
    alternative = RegExpEmpty::GetInstance();
  } else if (num_terms == 1) {
    alternative = terms_.last();
  } else {
    alternative = new RegExpAlternative(terms_.GetList());
  }
  alternatives_.Add(alternative);
  terms_.Clear();
  LAST(ADD_NONE);
}


RegExpTree* RegExpBuilder::ToRegExp() {
  FlushTerms();
  int num_alternatives = alternatives_.length();
  if (num_alternatives == 0) {
    return RegExpEmpty::GetInstance();
  }
  if (num_alternatives == 1) {
    return alternatives_.last();
  }
  return new RegExpDisjunction(alternatives_.GetList());
}


202 203 204
void RegExpBuilder::AddQuantifierToAtom(int min,
                                        int max,
                                        RegExpQuantifier::Type type) {
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
  if (pending_empty_) {
    pending_empty_ = false;
    return;
  }
  RegExpTree* atom;
  if (characters_ != NULL) {
    ASSERT(last_added_ == ADD_CHAR);
    // Last atom was character.
    Vector<const uc16> char_vector = characters_->ToConstVector();
    int num_chars = char_vector.length();
    if (num_chars > 1) {
      Vector<const uc16> prefix = char_vector.SubVector(0, num_chars - 1);
      text_.Add(new RegExpAtom(prefix));
      char_vector = char_vector.SubVector(num_chars - 1, num_chars);
    }
    characters_ = NULL;
    atom = new RegExpAtom(char_vector);
    FlushText();
  } else if (text_.length() > 0) {
    ASSERT(last_added_ == ADD_ATOM);
    atom = text_.RemoveLast();
    FlushText();
  } else if (terms_.length() > 0) {
    ASSERT(last_added_ == ADD_ATOM);
    atom = terms_.RemoveLast();
230 231
    if (atom->max_match() == 0) {
      // Guaranteed to only match an empty string.
232 233 234 235 236 237 238 239 240 241 242 243
      LAST(ADD_TERM);
      if (min == 0) {
        return;
      }
      terms_.Add(atom);
      return;
    }
  } else {
    // Only call immediately after adding an atom or character!
    UNREACHABLE();
    return;
  }
244
  terms_.Add(new RegExpQuantifier(min, max, type, atom));
245 246 247 248
  LAST(ADD_TERM);
}


249 250 251 252 253 254
// A temporary scope stores information during parsing, just like
// a plain scope.  However, temporary scopes are not kept around
// after parsing or referenced by syntax trees so they can be stack-
// allocated and hence used by the pre-parser.
class TemporaryScope BASE_EMBEDDED {
 public:
255
  explicit TemporaryScope(TemporaryScope** variable);
256 257
  ~TemporaryScope();

258 259 260 261 262 263
  int NextMaterializedLiteralIndex() {
    int next_index =
        materialized_literal_count_ + JSFunction::kLiteralsPrefixSize;
    materialized_literal_count_++;
    return next_index;
  }
264
  int materialized_literal_count() { return materialized_literal_count_; }
265

266 267 268 269 270 271 272 273 274 275 276 277 278 279
  void SetThisPropertyAssignmentInfo(
      bool only_simple_this_property_assignments,
      Handle<FixedArray> this_property_assignments) {
    only_simple_this_property_assignments_ =
        only_simple_this_property_assignments;
    this_property_assignments_ = this_property_assignments;
  }
  bool only_simple_this_property_assignments() {
    return only_simple_this_property_assignments_;
  }
  Handle<FixedArray> this_property_assignments() {
    return this_property_assignments_;
  }

280
  void AddProperty() { expected_property_count_++; }
281
  int expected_property_count() { return expected_property_count_; }
282 283 284 285

  void AddLoop() { loop_count_++; }
  bool ContainsLoops() const { return loop_count_ > 0; }

286
 private:
287 288 289
  // Captures the number of literals that need materialization in the
  // function.  Includes regexp literals, and boilerplate for object
  // and array literals.
290 291 292 293 294
  int materialized_literal_count_;

  // Properties count estimation.
  int expected_property_count_;

295 296
  // Keeps track of assignments to properties of this. Used for
  // optimizing constructors.
297 298 299
  bool only_simple_this_property_assignments_;
  Handle<FixedArray> this_property_assignments_;

300 301 302
  // Captures the number of loops inside the scope.
  int loop_count_;

303
  // Bookkeeping
304
  TemporaryScope** variable_;
305 306 307 308
  TemporaryScope* parent_;
};


309
TemporaryScope::TemporaryScope(TemporaryScope** variable)
310 311
  : materialized_literal_count_(0),
    expected_property_count_(0),
312 313
    only_simple_this_property_assignments_(false),
    this_property_assignments_(Factory::empty_fixed_array()),
314
    loop_count_(0),
315 316 317
    variable_(variable),
    parent_(*variable) {
  *variable = this;
318 319 320 321
}


TemporaryScope::~TemporaryScope() {
322
  *variable_ = parent_;
323 324 325
}


326
Handle<String> Parser::LookupSymbol(int symbol_id,
327
                                    Vector<const char> string) {
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
  // Length of symbol cache is the number of identified symbols.
  // If we are larger than that, or negative, it's not a cached symbol.
  // This might also happen if there is no preparser symbol data, even
  // if there is some preparser data.
  if (static_cast<unsigned>(symbol_id)
      >= static_cast<unsigned>(symbol_cache_.length())) {
    return Factory::LookupSymbol(string);
  }
  return LookupCachedSymbol(symbol_id, string);
}


Handle<String> Parser::LookupCachedSymbol(int symbol_id,
                                          Vector<const char> string) {
  // Make sure the cache is large enough to hold the symbol identifier.
  if (symbol_cache_.length() <= symbol_id) {
    // Increase length to index + 1.
    symbol_cache_.AddBlock(Handle<String>::null(),
                           symbol_id + 1 - symbol_cache_.length());
  }
  Handle<String> result = symbol_cache_.at(symbol_id);
  if (result.is_null()) {
    result = Factory::LookupSymbol(string);
    symbol_cache_.at(symbol_id) = result;
352
    return result;
353
  }
354 355 356
  Counters::total_preparse_symbols_skipped.Increment();
  return result;
}
357 358


359 360 361 362 363 364 365 366 367 368 369
Vector<unsigned> PartialParserRecorder::ExtractData() {
  int function_size = function_store_.size();
  int total_size = ScriptDataImpl::kHeaderSize + function_size;
  Vector<unsigned> data = Vector<unsigned>::New(total_size);
  preamble_[ScriptDataImpl::kFunctionsSizeOffset] = function_size;
  preamble_[ScriptDataImpl::kSymbolCountOffset] = 0;
  memcpy(data.start(), preamble_, sizeof(preamble_));
  int symbol_start = ScriptDataImpl::kHeaderSize + function_size;
  if (function_size > 0) {
    function_store_.WriteTo(data.SubVector(ScriptDataImpl::kHeaderSize,
                                           symbol_start));
370
  }
371 372
  return data;
}
373

374

375 376
void CompleteParserRecorder::LogSymbol(int start, Vector<const char> literal) {
  if (!is_recording_) return;
377

378 379 380 381 382 383 384 385 386
  int hash = vector_hash(literal);
  HashMap::Entry* entry = symbol_table_.Lookup(&literal, hash, true);
  int id = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
  if (id == 0) {
    // Put (symbol_id_ + 1) into entry and increment it.
    id = ++symbol_id_;
    entry->value = reinterpret_cast<void*>(id);
    Vector<Vector<const char> > symbol = symbol_entries_.AddBlock(1, literal);
    entry->key = &symbol[0];
387
  }
388 389
  WriteNumber(id - 1);
}
390

391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
Vector<unsigned> CompleteParserRecorder::ExtractData() {
  int function_size = function_store_.size();
  // Add terminator to symbols, then pad to unsigned size.
  int symbol_size = symbol_store_.size();
  int padding = sizeof(unsigned) - (symbol_size % sizeof(unsigned));
  symbol_store_.AddBlock(padding, ScriptDataImpl::kNumberTerminator);
  symbol_size += padding;
  int total_size = ScriptDataImpl::kHeaderSize + function_size
      + (symbol_size / sizeof(unsigned));
  Vector<unsigned> data = Vector<unsigned>::New(total_size);
  preamble_[ScriptDataImpl::kFunctionsSizeOffset] = function_size;
  preamble_[ScriptDataImpl::kSymbolCountOffset] = symbol_id_;
  memcpy(data.start(), preamble_, sizeof(preamble_));
  int symbol_start = ScriptDataImpl::kHeaderSize + function_size;
  if (function_size > 0) {
    function_store_.WriteTo(data.SubVector(ScriptDataImpl::kHeaderSize,
                                           symbol_start));
409
  }
410 411 412
  if (!has_error()) {
    symbol_store_.WriteTo(
        Vector<byte>::cast(data.SubVector(symbol_start, total_size)));
413
  }
414 415
  return data;
}
416 417


418 419 420
FunctionEntry ScriptDataImpl::GetFunctionEntry(int start) {
  // The current pre-data entry must be a FunctionEntry with the given
  // start position.
421 422 423 424
  if ((function_index_ + FunctionEntry::kSize <= store_.length())
      && (static_cast<int>(store_[function_index_]) == start)) {
    int index = function_index_;
    function_index_ += FunctionEntry::kSize;
425 426
    return FunctionEntry(store_.SubVector(index,
                                          index + FunctionEntry::kSize));
427 428 429 430 431
  }
  return FunctionEntry();
}


432 433
int ScriptDataImpl::GetSymbolIdentifier() {
  return ReadNumber(&symbol_data_);
434 435 436 437 438 439 440
}


bool ScriptDataImpl::SanityCheck() {
  // Check that the header data is valid and doesn't specify
  // point to positions outside the store.
  if (store_.length() < ScriptDataImpl::kHeaderSize) return false;
441 442
  if (magic() != ScriptDataImpl::kMagicNumber) return false;
  if (version() != ScriptDataImpl::kCurrentVersion) return false;
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
  if (has_error()) {
    // Extra sane sanity check for error message encoding.
    if (store_.length() <= kHeaderSize + kMessageTextPos) return false;
    if (Read(kMessageStartPos) > Read(kMessageEndPos)) return false;
    unsigned arg_count = Read(kMessageArgCountPos);
    int pos = kMessageTextPos;
    for (unsigned int i = 0; i <= arg_count; i++) {
      if (store_.length() <= kHeaderSize + pos) return false;
      int length = static_cast<int>(Read(pos));
      if (length < 0) return false;
      pos += 1 + length;
    }
    if (store_.length() < kHeaderSize + pos) return false;
    return true;
  }
  // Check that the space allocated for function entries is sane.
  int functions_size =
      static_cast<int>(store_[ScriptDataImpl::kFunctionsSizeOffset]);
  if (functions_size < 0) return false;
  if (functions_size % FunctionEntry::kSize != 0) return false;
  // Check that the count of symbols is non-negative.
  int symbol_count =
      static_cast<int>(store_[ScriptDataImpl::kSymbolCountOffset]);
  if (symbol_count < 0) return false;
467
  // Check that the total size has room for header and function entries.
468 469 470
  int minimum_size =
      ScriptDataImpl::kHeaderSize + functions_size;
  if (store_.length() < minimum_size) return false;
471 472 473 474
  return true;
}


475

476 477 478 479
PartialParserRecorder::PartialParserRecorder()
    : function_store_(0),
      is_recording_(true),
      pause_count_(0) {
480 481 482
  preamble_[ScriptDataImpl::kMagicOffset] = ScriptDataImpl::kMagicNumber;
  preamble_[ScriptDataImpl::kVersionOffset] = ScriptDataImpl::kCurrentVersion;
  preamble_[ScriptDataImpl::kHasErrorOffset] = false;
483 484
  preamble_[ScriptDataImpl::kFunctionsSizeOffset] = 0;
  preamble_[ScriptDataImpl::kSymbolCountOffset] = 0;
485
  preamble_[ScriptDataImpl::kSizeOffset] = 0;
486
  ASSERT_EQ(6, ScriptDataImpl::kHeaderSize);
487
#ifdef DEBUG
488
  prev_start_ = -1;
489
#endif
490 491 492
}


493 494 495 496 497 498 499 500 501 502
CompleteParserRecorder::CompleteParserRecorder()
    : PartialParserRecorder(),
      symbol_store_(0),
      symbol_entries_(0),
      symbol_table_(vector_compare),
      symbol_id_(0) {
}


void PartialParserRecorder::WriteString(Vector<const char> str) {
503
  function_store_.Add(str.length());
504
  for (int i = 0; i < str.length(); i++) {
505
    function_store_.Add(str[i]);
506
  }
507 508 509
}


510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
void CompleteParserRecorder::WriteNumber(int number) {
  ASSERT(number >= 0);

  int mask = (1 << 28) - 1;
  for (int i = 28; i > 0; i -= 7) {
    if (number > mask) {
      symbol_store_.Add(static_cast<byte>(number >> i) | 0x80u);
      number &= mask;
    }
    mask >>= 7;
  }
  symbol_store_.Add(static_cast<byte>(number));
}



526
const char* ScriptDataImpl::ReadString(unsigned* start, int* chars) {
527 528
  int length = start[0];
  char* result = NewArray<char>(length + 1);
529
  for (int i = 0; i < length; i++) {
530
    result[i] = start[i + 1];
531
  }
532 533 534 535 536 537
  result[length] = '\0';
  if (chars != NULL) *chars = length;
  return result;
}


538
void PartialParserRecorder::LogMessage(Scanner::Location loc,
539 540
                                       const char* message,
                                       Vector<const char*> args) {
541
  if (has_error()) return;
542
  preamble_[ScriptDataImpl::kHasErrorOffset] = true;
543 544 545 546 547 548 549 550
  function_store_.Reset();
  STATIC_ASSERT(ScriptDataImpl::kMessageStartPos == 0);
  function_store_.Add(loc.beg_pos);
  STATIC_ASSERT(ScriptDataImpl::kMessageEndPos == 1);
  function_store_.Add(loc.end_pos);
  STATIC_ASSERT(ScriptDataImpl::kMessageArgCountPos == 2);
  function_store_.Add(args.length());
  STATIC_ASSERT(ScriptDataImpl::kMessageTextPos == 3);
551
  WriteString(CStrVector(message));
552
  for (int i = 0; i < args.length(); i++) {
553
    WriteString(CStrVector(args[i]));
554
  }
555
  is_recording_ = false;
556 557 558 559
}


Scanner::Location ScriptDataImpl::MessageLocation() {
560 561
  int beg_pos = Read(kMessageStartPos);
  int end_pos = Read(kMessageEndPos);
562 563 564 565 566
  return Scanner::Location(beg_pos, end_pos);
}


const char* ScriptDataImpl::BuildMessage() {
567
  unsigned* start = ReadAddress(kMessageTextPos);
568
  return ReadString(start, NULL);
569 570 571 572
}


Vector<const char*> ScriptDataImpl::BuildArgs() {
573
  int arg_count = Read(kMessageArgCountPos);
574
  const char** array = NewArray<const char*>(arg_count);
575 576
  // Position after text found by skipping past length field and
  // length field content words.
577
  int pos = kMessageTextPos + 1 + Read(kMessageTextPos);
578 579
  for (int i = 0; i < arg_count; i++) {
    int count = 0;
580
    array[i] = ReadString(ReadAddress(pos), &count);
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    pos += count + 1;
  }
  return Vector<const char*>(array, arg_count);
}


unsigned ScriptDataImpl::Read(int position) {
  return store_[ScriptDataImpl::kHeaderSize + position];
}


unsigned* ScriptDataImpl::ReadAddress(int position) {
  return &store_[ScriptDataImpl::kHeaderSize + position];
}


597
Scope* Parser::NewScope(Scope* parent, Scope::Type type, bool inside_with) {
598 599 600 601 602 603 604 605 606 607 608 609 610
  Scope* result = new Scope(parent, type);
  result->Initialize(inside_with);
  return result;
}

// ----------------------------------------------------------------------------
// Target is a support class to facilitate manipulation of the
// Parser's target_stack_ (the stack of potential 'break' and
// 'continue' statement targets). Upon construction, a new target is
// added; it is removed upon destruction.

class Target BASE_EMBEDDED {
 public:
611 612 613
  Target(Target** variable, AstNode* node)
      : variable_(variable), node_(node), previous_(*variable) {
    *variable = this;
614 615 616
  }

  ~Target() {
617
    *variable_ = previous_;
618 619
  }

bak@chromium.org's avatar
bak@chromium.org committed
620
  Target* previous() { return previous_; }
621
  AstNode* node() { return node_; }
bak@chromium.org's avatar
bak@chromium.org committed
622

623
 private:
624
  Target** variable_;
625
  AstNode* node_;
bak@chromium.org's avatar
bak@chromium.org committed
626
  Target* previous_;
627 628 629 630 631
};


class TargetScope BASE_EMBEDDED {
 public:
632 633 634
  explicit TargetScope(Target** variable)
      : variable_(variable), previous_(*variable) {
    *variable = NULL;
635 636 637
  }

  ~TargetScope() {
638
    *variable_ = previous_;
639 640 641
  }

 private:
642
  Target** variable_;
bak@chromium.org's avatar
bak@chromium.org committed
643
  Target* previous_;
644 645 646 647 648 649 650 651 652 653
};


// ----------------------------------------------------------------------------
// LexicalScope is a support class to facilitate manipulation of the
// Parser's scope stack. The constructor sets the parser's top scope
// to the incoming scope, and the destructor resets it.

class LexicalScope BASE_EMBEDDED {
 public:
654 655 656 657 658 659 660 661 662
  LexicalScope(Scope** scope_variable,
               int* with_nesting_level_variable,
               Scope* scope)
    : scope_variable_(scope_variable),
      with_nesting_level_variable_(with_nesting_level_variable),
      prev_scope_(*scope_variable),
      prev_level_(*with_nesting_level_variable) {
    *scope_variable = scope;
    *with_nesting_level_variable = 0;
663 664 665
  }

  ~LexicalScope() {
666 667 668
    (*scope_variable_)->Leave();
    *scope_variable_ = prev_scope_;
    *with_nesting_level_variable_ = prev_level_;
669 670 671
  }

 private:
672 673
  Scope** scope_variable_;
  int* with_nesting_level_variable_;
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
  Scope* prev_scope_;
  int prev_level_;
};


// ----------------------------------------------------------------------------
// The CHECK_OK macro is a convenient macro to enforce error
// handling for functions that may fail (by returning !*ok).
//
// CAUTION: This macro appends extra statements after a call,
// thus it must never be used where only a single statement
// is correct (e.g. an if statement branch w/o braces)!

#define CHECK_OK  ok);   \
  if (!*ok) return NULL; \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY

693
#define CHECK_FAILED  /**/);   \
694 695 696 697
  if (failed_) return NULL; \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY
698 699 700 701 702 703 704 705

// ----------------------------------------------------------------------------
// Implementation of Parser

Parser::Parser(Handle<Script> script,
               bool allow_natives_syntax,
               v8::Extension* extension,
               ScriptDataImpl* pre_data)
706 707
    : symbol_cache_(pre_data ? pre_data->symbol_count() : 0),
      script_(script),
708
      scanner_(),
709 710 711 712 713 714
      top_scope_(NULL),
      with_nesting_level_(0),
      temp_scope_(NULL),
      target_stack_(NULL),
      allow_natives_syntax_(allow_natives_syntax),
      extension_(extension),
715
      pre_data_(pre_data),
716
      fni_(NULL) {
717 718 719 720 721
}


FunctionLiteral* Parser::ParseProgram(Handle<String> source,
                                      bool in_global_context) {
722
  CompilationZoneScope zone_scope(DONT_DELETE_ON_EXIT);
723

724
  HistogramTimerScope timer(&Counters::parse);
725
  Counters::total_parse_size.Increment(source->length());
726
  fni_ = new FuncNameInferrer();
727 728

  // Initialize parser state.
729
  source->TryFlatten();
730
  scanner_.Initialize(source, JAVASCRIPT);
731
  ASSERT(target_stack_ == NULL);
732
  if (pre_data_ != NULL) pre_data_->Initialize();
733 734 735 736 737 738 739 740 741

  // Compute the parsing mode.
  mode_ = FLAG_lazy ? PARSE_LAZILY : PARSE_EAGERLY;
  if (allow_natives_syntax_ || extension_ != NULL) mode_ = PARSE_EAGERLY;

  Scope::Type type =
    in_global_context
      ? Scope::GLOBAL_SCOPE
      : Scope::EVAL_SCOPE;
742
  Handle<String> no_name = Factory::empty_symbol();
743 744

  FunctionLiteral* result = NULL;
745
  { Scope* scope = NewScope(top_scope_, type, inside_with());
746 747 748
    LexicalScope lexical_scope(&this->top_scope_, &this->with_nesting_level_,
                               scope);
    TemporaryScope temp_scope(&this->temp_scope_);
749
    ZoneList<Statement*>* body = new ZoneList<Statement*>(16);
750
    bool ok = true;
751
    ParseSourceElements(body, Token::EOS, &ok);
752
    if (ok) {
753
      result = new FunctionLiteral(
754 755
          no_name,
          top_scope_,
756
          body,
757 758 759 760 761 762 763
          temp_scope.materialized_literal_count(),
          temp_scope.expected_property_count(),
          temp_scope.only_simple_this_property_assignments(),
          temp_scope.this_property_assignments(),
          0,
          0,
          source->length(),
764
          false,
765
          temp_scope.ContainsLoops());
766 767 768 769 770 771 772 773 774 775
    } else if (scanner().stack_overflow()) {
      Top::StackOverflow();
    }
  }

  // Make sure the target stack is empty.
  ASSERT(target_stack_ == NULL);

  // If there was a syntax error we have to get rid of the AST
  // and it is not safe to do so before the scope has been deleted.
776
  if (result == NULL) zone_scope.DeleteOnExit();
777 778 779 780
  return result;
}


781
FunctionLiteral* Parser::ParseLazy(Handle<SharedFunctionInfo> info) {
782
  CompilationZoneScope zone_scope(DONT_DELETE_ON_EXIT);
783
  HistogramTimerScope timer(&Counters::parse_lazy);
784
  Handle<String> source(String::cast(script_->source()));
785
  Counters::total_parse_size.Increment(source->length());
786

787
  Handle<String> name(String::cast(info->name()));
788 789 790
  fni_ = new FuncNameInferrer();
  fni_->PushEnclosingName(name);

791
  // Initialize parser state.
792
  source->TryFlatten();
793 794
  scanner_.Initialize(source, info->start_position(), info->end_position(),
                      JAVASCRIPT);
795 796 797 798 799 800 801 802
  ASSERT(target_stack_ == NULL);
  mode_ = PARSE_EAGERLY;

  // Place holder for the result.
  FunctionLiteral* result = NULL;

  {
    // Parse the function literal.
803
    Handle<String> no_name = Factory::empty_symbol();
804
    Scope* scope =
805
        NewScope(top_scope_, Scope::GLOBAL_SCOPE, inside_with());
806 807 808
    LexicalScope lexical_scope(&this->top_scope_, &this->with_nesting_level_,
                               scope);
    TemporaryScope temp_scope(&this->temp_scope_);
809

810 811
    FunctionLiteralType type =
        info->is_expression() ? EXPRESSION : DECLARATION;
812
    bool ok = true;
813
    result = ParseFunctionLiteral(name, RelocInfo::kNoPosition, type, &ok);
814 815 816 817 818 819 820 821 822 823 824 825 826
    // Make sure the results agree.
    ASSERT(ok == (result != NULL));
    // The only errors should be stack overflows.
    ASSERT(ok || scanner_.stack_overflow());
  }

  // Make sure the target stack is empty.
  ASSERT(target_stack_ == NULL);

  // If there was a stack overflow we have to get rid of AST and it is
  // not safe to do before scope has been deleted.
  if (result == NULL) {
    Top::StackOverflow();
827
    zone_scope.DeleteOnExit();
828 829 830 831
  }
  return result;
}

832

833
Handle<String> Parser::GetSymbol(bool* ok) {
834
  int symbol_id = -1;
835
  if (pre_data() != NULL) {
836
    symbol_id = pre_data()->GetSymbolIdentifier();
837
  }
838 839 840 841 842 843 844
  return LookupSymbol(symbol_id, scanner_.literal());
}


void Parser::ReportMessage(const char* type, Vector<const char*> args) {
  Scanner::Location source_location = scanner_.location();
  ReportMessageAt(source_location, type, args);
845 846 847
}


848 849 850
void Parser::ReportMessageAt(Scanner::Location source_location,
                             const char* type,
                             Vector<const char*> args) {
851 852 853 854 855 856 857 858 859 860 861
  MessageLocation location(script_,
                           source_location.beg_pos, source_location.end_pos);
  Handle<JSArray> array = Factory::NewJSArray(args.length());
  for (int i = 0; i < args.length(); i++) {
    SetElement(array, i, Factory::NewStringFromUtf8(CStrVector(args[i])));
  }
  Handle<Object> result = Factory::NewSyntaxError(type, array);
  Top::Throw(*result, &location);
}


862 863 864 865 866 867 868 869 870 871 872 873 874 875
// Base class containing common code for the different finder classes used by
// the parser.
class ParserFinder {
 protected:
  ParserFinder() {}
  static Assignment* AsAssignment(Statement* stat) {
    if (stat == NULL) return NULL;
    ExpressionStatement* exp_stat = stat->AsExpressionStatement();
    if (exp_stat == NULL) return NULL;
    return exp_stat->expression()->AsAssignment();
  }
};


876
// An InitializationBlockFinder finds and marks sequences of statements of the
877
// form expr.a = ...; expr.b = ...; etc.
878
class InitializationBlockFinder : public ParserFinder {
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
 public:
  InitializationBlockFinder()
    : first_in_block_(NULL), last_in_block_(NULL), block_size_(0) {}

  ~InitializationBlockFinder() {
    if (InBlock()) EndBlock();
  }

  void Update(Statement* stat) {
    Assignment* assignment = AsAssignment(stat);
    if (InBlock()) {
      if (BlockContinues(assignment)) {
        UpdateBlock(assignment);
      } else {
        EndBlock();
      }
    }
    if (!InBlock() && (assignment != NULL) &&
        (assignment->op() == Token::ASSIGN)) {
      StartBlock(assignment);
    }
  }

 private:
903 904 905 906 907
  // The minimum number of contiguous assignment that will
  // be treated as an initialization block. Benchmarks show that
  // the overhead exceeds the savings below this limit.
  static const int kMinInitializationBlock = 3;

908 909
  // Returns true if the expressions appear to denote the same object.
  // In the context of initialization blocks, we only consider expressions
910
  // of the form 'expr.x' or expr["x"].
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
  static bool SameObject(Expression* e1, Expression* e2) {
    VariableProxy* v1 = e1->AsVariableProxy();
    VariableProxy* v2 = e2->AsVariableProxy();
    if (v1 != NULL && v2 != NULL) {
      return v1->name()->Equals(*v2->name());
    }
    Property* p1 = e1->AsProperty();
    Property* p2 = e2->AsProperty();
    if ((p1 == NULL) || (p2 == NULL)) return false;
    Literal* key1 = p1->key()->AsLiteral();
    Literal* key2 = p2->key()->AsLiteral();
    if ((key1 == NULL) || (key2 == NULL)) return false;
    if (!key1->handle()->IsString() || !key2->handle()->IsString()) {
      return false;
    }
    String* name1 = String::cast(*key1->handle());
    String* name2 = String::cast(*key2->handle());
    if (!name1->Equals(name2)) return false;
    return SameObject(p1->obj(), p2->obj());
  }

  // Returns true if the expressions appear to denote different properties
  // of the same object.
  static bool PropertyOfSameObject(Expression* e1, Expression* e2) {
    Property* p1 = e1->AsProperty();
    Property* p2 = e2->AsProperty();
    if ((p1 == NULL) || (p2 == NULL)) return false;
    return SameObject(p1->obj(), p2->obj());
  }

  bool BlockContinues(Assignment* assignment) {
    if ((assignment == NULL) || (first_in_block_ == NULL)) return false;
    if (assignment->op() != Token::ASSIGN) return false;
    return PropertyOfSameObject(first_in_block_->target(),
                                assignment->target());
  }

  void StartBlock(Assignment* assignment) {
    first_in_block_ = assignment;
    last_in_block_ = assignment;
    block_size_ = 1;
  }

  void UpdateBlock(Assignment* assignment) {
    last_in_block_ = assignment;
    ++block_size_;
  }

  void EndBlock() {
960
    if (block_size_ >= kMinInitializationBlock) {
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
      first_in_block_->mark_block_start();
      last_in_block_->mark_block_end();
    }
    last_in_block_ = first_in_block_ = NULL;
    block_size_ = 0;
  }

  bool InBlock() { return first_in_block_ != NULL; }

  Assignment* first_in_block_;
  Assignment* last_in_block_;
  int block_size_;

  DISALLOW_COPY_AND_ASSIGN(InitializationBlockFinder);
};


978 979 980 981 982 983
// A ThisNamedPropertyAssigmentFinder finds and marks statements of the form
// this.x = ...;, where x is a named property. It also determines whether a
// function contains only assignments of this type.
class ThisNamedPropertyAssigmentFinder : public ParserFinder {
 public:
  ThisNamedPropertyAssigmentFinder()
984
      : only_simple_this_property_assignments_(true),
985 986 987 988 989
        names_(NULL),
        assigned_arguments_(NULL),
        assigned_constants_(NULL) {}

  void Update(Scope* scope, Statement* stat) {
990 991 992
    // Bail out if function already has property assignment that are
    // not simple this property assignments.
    if (!only_simple_this_property_assignments_) {
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
      return;
    }

    // Check whether this statement is of the form this.x = ...;
    Assignment* assignment = AsAssignment(stat);
    if (IsThisPropertyAssignment(assignment)) {
      HandleThisPropertyAssignment(scope, assignment);
    } else {
      only_simple_this_property_assignments_ = false;
    }
  }

  // Returns whether only statements of the form this.x = y; where y is either a
  // constant or a function argument was encountered.
  bool only_simple_this_property_assignments() {
    return only_simple_this_property_assignments_;
  }

  // Returns a fixed array containing three elements for each assignment of the
  // form this.x = y;
  Handle<FixedArray> GetThisPropertyAssignments() {
    if (names_ == NULL) {
      return Factory::empty_fixed_array();
    }
    ASSERT(names_ != NULL);
    ASSERT(assigned_arguments_ != NULL);
    ASSERT_EQ(names_->length(), assigned_arguments_->length());
    ASSERT_EQ(names_->length(), assigned_constants_->length());
    Handle<FixedArray> assignments =
        Factory::NewFixedArray(names_->length() * 3);
    for (int i = 0; i < names_->length(); i++) {
      assignments->set(i * 3, *names_->at(i));
      assignments->set(i * 3 + 1, Smi::FromInt(assigned_arguments_->at(i)));
      assignments->set(i * 3 + 2, *assigned_constants_->at(i));
    }
    return assignments;
  }

 private:
  bool IsThisPropertyAssignment(Assignment* assignment) {
    if (assignment != NULL) {
      Property* property = assignment->target()->AsProperty();
      return assignment->op() == Token::ASSIGN
             && property != NULL
             && property->obj()->AsVariableProxy() != NULL
             && property->obj()->AsVariableProxy()->is_this();
    }
    return false;
  }

  void HandleThisPropertyAssignment(Scope* scope, Assignment* assignment) {
1044 1045
    // Check that the property assigned to is a named property, which is not
    // __proto__.
1046 1047 1048 1049 1050 1051
    Property* property = assignment->target()->AsProperty();
    ASSERT(property != NULL);
    Literal* literal = property->key()->AsLiteral();
    uint32_t dummy;
    if (literal != NULL &&
        literal->handle()->IsString() &&
1052
        !String::cast(*(literal->handle()))->Equals(Heap::Proto_symbol()) &&
1053 1054 1055 1056 1057 1058 1059 1060 1061
        !String::cast(*(literal->handle()))->AsArrayIndex(&dummy)) {
      Handle<String> key = Handle<String>::cast(literal->handle());

      // Check whether the value assigned is either a constant or matches the
      // name of one of the arguments to the function.
      if (assignment->value()->AsLiteral() != NULL) {
        // Constant assigned.
        Literal* literal = assignment->value()->AsLiteral();
        AssignmentFromConstant(key, literal->handle());
1062
        return;
1063 1064 1065 1066 1067 1068 1069 1070
      } else if (assignment->value()->AsVariableProxy() != NULL) {
        // Variable assigned.
        Handle<String> name =
            assignment->value()->AsVariableProxy()->name();
        // Check whether the variable assigned matches an argument name.
        for (int i = 0; i < scope->num_parameters(); i++) {
          if (*scope->parameter(i)->name() == *name) {
            // Assigned from function argument.
1071 1072
            AssignmentFromParameter(key, i);
            return;
1073 1074 1075 1076
          }
        }
      }
    }
1077 1078 1079
    // It is not a simple "this.x = value;" assignment with a constant
    // or parameter value.
    AssignmentFromSomethingElse();
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  }

  void AssignmentFromParameter(Handle<String> name, int index) {
    EnsureAllocation();
    names_->Add(name);
    assigned_arguments_->Add(index);
    assigned_constants_->Add(Factory::undefined_value());
  }

  void AssignmentFromConstant(Handle<String> name, Handle<Object> value) {
    EnsureAllocation();
    names_->Add(name);
    assigned_arguments_->Add(-1);
    assigned_constants_->Add(value);
  }

1096
  void AssignmentFromSomethingElse() {
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    // The this assignment is not a simple one.
    only_simple_this_property_assignments_ = false;
  }

  void EnsureAllocation() {
    if (names_ == NULL) {
      ASSERT(assigned_arguments_ == NULL);
      ASSERT(assigned_constants_ == NULL);
      names_ = new ZoneStringList(4);
      assigned_arguments_ = new ZoneList<int>(4);
      assigned_constants_ = new ZoneObjectList(4);
    }
  }

  bool only_simple_this_property_assignments_;
  ZoneStringList* names_;
  ZoneList<int>* assigned_arguments_;
  ZoneObjectList* assigned_constants_;
};


1118
void* Parser::ParseSourceElements(ZoneList<Statement*>* processor,
1119 1120 1121 1122 1123 1124 1125 1126 1127
                                  int end_token,
                                  bool* ok) {
  // SourceElements ::
  //   (Statement)* <end_token>

  // Allocate a target stack to use for this set of source
  // elements. This way, all scripts and functions get their own
  // target stack thus avoiding illegal breaks and continues across
  // functions.
1128
  TargetScope scope(&this->target_stack_);
1129 1130

  ASSERT(processor != NULL);
1131
  InitializationBlockFinder block_finder;
1132
  ThisNamedPropertyAssigmentFinder this_property_assignment_finder;
1133 1134
  while (peek() != end_token) {
    Statement* stat = ParseStatement(NULL, CHECK_OK);
1135 1136 1137 1138
    if (stat == NULL || stat->IsEmpty()) continue;
    // We find and mark the initialization blocks on top level code only.
    // This is because the optimization prevents reuse of the map transitions,
    // so it should be used only for code that will only be run once.
1139 1140 1141 1142 1143 1144 1145
    if (top_scope_->is_global_scope()) {
      block_finder.Update(stat);
    }
    // Find and mark all assignments to named properties in this (this.x =)
    if (top_scope_->is_function_scope()) {
      this_property_assignment_finder.Update(top_scope_, stat);
    }
1146
    processor->Add(stat);
1147
  }
1148 1149

  // Propagate the collected information on this property assignments.
1150
  if (top_scope_->is_function_scope()) {
1151
    bool only_simple_this_property_assignments =
1152 1153
        this_property_assignment_finder.only_simple_this_property_assignments()
        && top_scope_->declarations()->length() == 0;
1154
    if (only_simple_this_property_assignments) {
1155
      temp_scope_->SetThisPropertyAssignmentInfo(
1156
          only_simple_this_property_assignments,
1157 1158 1159
          this_property_assignment_finder.GetThisPropertyAssignments());
    }
  }
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  return 0;
}


Statement* Parser::ParseStatement(ZoneStringList* labels, bool* ok) {
  // Statement ::
  //   Block
  //   VariableStatement
  //   EmptyStatement
  //   ExpressionStatement
  //   IfStatement
  //   IterationStatement
  //   ContinueStatement
  //   BreakStatement
  //   ReturnStatement
  //   WithStatement
  //   LabelledStatement
  //   SwitchStatement
  //   ThrowStatement
  //   TryStatement
  //   DebuggerStatement

  // Note: Since labels can only be used by 'break' and 'continue'
  // statements, which themselves are only valid within blocks,
  // iterations or 'switch' statements (i.e., BreakableStatements),
  // labels can be simply ignored in all other cases; except for
1186
  // trivial labeled break statements 'label: break label' which is
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  // parsed into an empty statement.

  // Keep the source position of the statement
  int statement_pos = scanner().peek_location().beg_pos;
  Statement* stmt = NULL;
  switch (peek()) {
    case Token::LBRACE:
      return ParseBlock(labels, ok);

    case Token::CONST:  // fall through
    case Token::VAR:
      stmt = ParseVariableStatement(ok);
      break;

    case Token::SEMICOLON:
      Next();
1203
      return EmptyStatement();
1204 1205 1206 1207 1208 1209

    case Token::IF:
      stmt = ParseIfStatement(labels, ok);
      break;

    case Token::DO:
1210
      stmt = ParseDoWhileStatement(labels, ok);
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
      break;

    case Token::WHILE:
      stmt = ParseWhileStatement(labels, ok);
      break;

    case Token::FOR:
      stmt = ParseForStatement(labels, ok);
      break;

    case Token::CONTINUE:
      stmt = ParseContinueStatement(ok);
      break;

    case Token::BREAK:
      stmt = ParseBreakStatement(labels, ok);
      break;

    case Token::RETURN:
      stmt = ParseReturnStatement(ok);
      break;

    case Token::WITH:
      stmt = ParseWithStatement(labels, ok);
      break;

    case Token::SWITCH:
      stmt = ParseSwitchStatement(labels, ok);
      break;

    case Token::THROW:
      stmt = ParseThrowStatement(ok);
      break;

    case Token::TRY: {
      // NOTE: It is somewhat complicated to have labels on
      // try-statements. When breaking out of a try-finally statement,
      // one must take great care not to treat it as a
      // fall-through. It is much easier just to wrap the entire
      // try-statement in a statement block and put the labels there
1251
      Block* result = new Block(labels, 1, false);
1252
      Target target(&this->target_stack_, result);
1253
      TryStatement* statement = ParseTryStatement(CHECK_OK);
1254 1255 1256
      if (statement) {
        statement->set_statement_pos(statement_pos);
      }
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
      if (result) result->AddStatement(statement);
      return result;
    }

    case Token::FUNCTION:
      return ParseFunctionDeclaration(ok);

    case Token::NATIVE:
      return ParseNativeDeclaration(ok);

    case Token::DEBUGGER:
      stmt = ParseDebuggerStatement(ok);
      break;

    default:
      stmt = ParseExpressionOrLabelledStatement(labels, ok);
  }

  // Store the source position of the statement
  if (stmt != NULL) stmt->set_statement_pos(statement_pos);
  return stmt;
}


1281 1282 1283 1284 1285
VariableProxy* Parser::Declare(Handle<String> name,
                               Variable::Mode mode,
                               FunctionLiteral* fun,
                               bool resolve,
                               bool* ok) {
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  Variable* var = NULL;
  // If we are inside a function, a declaration of a variable
  // is a truly local variable, and the scope of the variable
  // is always the function scope.

  // If a function scope exists, then we can statically declare this
  // variable and also set its mode. In any case, a Declaration node
  // will be added to the scope so that the declaration can be added
  // to the corresponding activation frame at runtime if necessary.
  // For instance declarations inside an eval scope need to be added
  // to the calling function context.
  if (top_scope_->is_function_scope()) {
    // Declare the variable in the function scope.
1299
    var = top_scope_->LocalLookup(name);
1300 1301
    if (var == NULL) {
      // Declare the name.
1302
      var = top_scope_->DeclareLocal(name, mode);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    } else {
      // The name was declared before; check for conflicting
      // re-declarations. If the previous declaration was a const or the
      // current declaration is a const then we have a conflict. There is
      // similar code in runtime.cc in the Declare functions.
      if ((mode == Variable::CONST) || (var->mode() == Variable::CONST)) {
        // We only have vars and consts in declarations.
        ASSERT(var->mode() == Variable::VAR ||
               var->mode() == Variable::CONST);
        const char* type = (var->mode() == Variable::VAR) ? "var" : "const";
        Handle<String> type_string =
            Factory::NewStringFromUtf8(CStrVector(type), TENURED);
        Expression* expression =
            NewThrowTypeError(Factory::redeclaration_symbol(),
                              type_string, name);
        top_scope_->SetIllegalRedeclaration(expression);
      }
    }
  }

  // We add a declaration node for every declaration. The compiler
  // will only generate code if necessary. In particular, declarations
  // for inner local variables that do not represent functions won't
  // result in any generated code.
  //
  // Note that we always add an unresolved proxy even if it's not
  // used, simply because we don't know in this method (w/o extra
  // parameters) if the proxy is needed or not. The proxy will be
  // bound during variable resolution time unless it was pre-bound
  // below.
  //
  // WARNING: This will lead to multiple declaration nodes for the
  // same variable if it is declared several times. This is not a
  // semantic issue as long as we keep the source order, but it may be
  // a performance issue since it may lead to repeated
  // Runtime::DeclareContextSlot() calls.
  VariableProxy* proxy = top_scope_->NewUnresolved(name, inside_with());
1340
  top_scope_->AddDeclaration(new Declaration(proxy, mode, fun));
1341 1342 1343 1344

  // For global const variables we bind the proxy to a variable.
  if (mode == Variable::CONST && top_scope_->is_global_scope()) {
    ASSERT(resolve);  // should be set by all callers
1345
    Variable::Kind kind = Variable::NORMAL;
1346
    var = new Variable(top_scope_, name, Variable::CONST, true, kind);
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
  }

  // If requested and we have a local variable, bind the proxy to the variable
  // at parse-time. This is used for functions (and consts) declared inside
  // statements: the corresponding function (or const) variable must be in the
  // function scope and not a statement-local scope, e.g. as provided with a
  // 'with' statement:
  //
  //   with (obj) {
  //     function f() {}
  //   }
  //
  // which is translated into:
  //
  //   with (obj) {
  //     // in this case this is not: 'var f; f = function () {};'
  //     var f = function () {};
  //   }
  //
  // Note that if 'f' is accessed from inside the 'with' statement, it
  // will be allocated in the context (because we must be able to look
  // it up dynamically) but it will also be accessed statically, i.e.,
  // with a context slot index and a context chain length for this
  // initialization code. Thus, inside the 'with' statement, we need
  // both access to the static and the dynamic context chain; the
  // runtime needs to provide both.
  if (resolve && var != NULL) proxy->BindTo(var);

  return proxy;
}


// Language extension which is only enabled for source files loaded
// through the API's extension mechanism.  A native function
// declaration is resolved by looking up the function through a
// callback provided by the extension.
Statement* Parser::ParseNativeDeclaration(bool* ok) {
  if (extension_ == NULL) {
    ReportUnexpectedToken(Token::NATIVE);
    *ok = false;
    return NULL;
  }

  Expect(Token::NATIVE, CHECK_OK);
  Expect(Token::FUNCTION, CHECK_OK);
  Handle<String> name = ParseIdentifier(CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  bool done = (peek() == Token::RPAREN);
  while (!done) {
    ParseIdentifier(CHECK_OK);
    done = (peek() == Token::RPAREN);
1398 1399 1400
    if (!done) {
      Expect(Token::COMMA, CHECK_OK);
    }
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
  }
  Expect(Token::RPAREN, CHECK_OK);
  Expect(Token::SEMICOLON, CHECK_OK);

  // Make sure that the function containing the native declaration
  // isn't lazily compiled. The extension structures are only
  // accessible while parsing the first time not when reparsing
  // because of lazy compilation.
  top_scope_->ForceEagerCompilation();

  // Compute the function template for the native function.
  v8::Handle<v8::FunctionTemplate> fun_template =
      extension_->GetNativeFunction(v8::Utils::ToLocal(name));
  ASSERT(!fun_template.IsEmpty());

1416
  // Instantiate the function and create a shared function info from it.
1417 1418 1419
  Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
  const int literals = fun->NumberOfLiterals();
  Handle<Code> code = Handle<Code>(fun->shared()->code());
1420
  Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1421 1422 1423
  Handle<SharedFunctionInfo> shared =
      Factory::NewSharedFunctionInfo(name, literals, code,
          Handle<SerializedScopeInfo>(fun->shared()->scope_info()));
1424
  shared->set_construct_stub(*construct_stub);
1425

1426
  // Copy the function data to the shared function info.
1427
  shared->set_function_data(fun->shared()->function_data());
1428
  int parameters = fun->shared()->formal_parameter_count();
1429
  shared->set_formal_parameter_count(parameters);
1430 1431 1432 1433

  // TODO(1240846): It's weird that native function declarations are
  // introduced dynamically when we meet their declarations, whereas
  // other functions are setup when entering the surrounding scope.
1434
  SharedFunctionInfoLiteral* lit = new SharedFunctionInfoLiteral(shared);
1435
  VariableProxy* var = Declare(name, Variable::VAR, NULL, true, CHECK_OK);
1436 1437
  return new ExpressionStatement(
      new Assignment(Token::INIT_VAR, var, lit, RelocInfo::kNoPosition));
1438 1439 1440 1441
}


Statement* Parser::ParseFunctionDeclaration(bool* ok) {
1442 1443
  // FunctionDeclaration ::
  //   'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
1444 1445
  Expect(Token::FUNCTION, CHECK_OK);
  int function_token_position = scanner().location().beg_pos;
1446 1447 1448 1449 1450 1451 1452 1453 1454
  Handle<String> name = ParseIdentifier(CHECK_OK);
  FunctionLiteral* fun = ParseFunctionLiteral(name,
                                              function_token_position,
                                              DECLARATION,
                                              CHECK_OK);
  // Even if we're not at the top-level of the global or a function
  // scope, we treat is as such and introduce the function with it's
  // initial value upon entering the corresponding scope.
  Declare(name, Variable::VAR, fun, true, CHECK_OK);
1455
  return EmptyStatement();
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
}


Block* Parser::ParseBlock(ZoneStringList* labels, bool* ok) {
  // Block ::
  //   '{' Statement* '}'

  // Note that a Block does not introduce a new execution scope!
  // (ECMA-262, 3rd, 12.2)
  //
  // Construct block expecting 16 statements.
1467
  Block* result = new Block(labels, 16, false);
1468
  Target target(&this->target_stack_, result);
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
  Expect(Token::LBRACE, CHECK_OK);
  while (peek() != Token::RBRACE) {
    Statement* stat = ParseStatement(NULL, CHECK_OK);
    if (stat && !stat->IsEmpty()) result->AddStatement(stat);
  }
  Expect(Token::RBRACE, CHECK_OK);
  return result;
}


Block* Parser::ParseVariableStatement(bool* ok) {
  // VariableStatement ::
  //   VariableDeclarations ';'

  Expression* dummy;  // to satisfy the ParseVariableDeclarations() signature
  Block* result = ParseVariableDeclarations(true, &dummy, CHECK_OK);
  ExpectSemicolon(CHECK_OK);
  return result;
}


// If the variable declaration declares exactly one non-const
// variable, then *var is set to that variable. In all other cases,
// *var is untouched; in particular, it is the caller's responsibility
// to initialize it properly. This mechanism is used for the parsing
// of 'for-in' loops.
Block* Parser::ParseVariableDeclarations(bool accept_IN,
                                         Expression** var,
                                         bool* ok) {
  // VariableDeclarations ::
  //   ('var' | 'const') (Identifier ('=' AssignmentExpression)?)+[',']

  Variable::Mode mode = Variable::VAR;
  bool is_const = false;
  if (peek() == Token::VAR) {
    Consume(Token::VAR);
  } else if (peek() == Token::CONST) {
    Consume(Token::CONST);
    mode = Variable::CONST;
    is_const = true;
  } else {
    UNREACHABLE();  // by current callers
  }

  // The scope of a variable/const declared anywhere inside a function
  // is the entire function (ECMA-262, 3rd, 10.1.3, and 12.2). Thus we can
  // transform a source-level variable/const declaration into a (Function)
  // Scope declaration, and rewrite the source-level initialization into an
  // assignment statement. We use a block to collect multiple assignments.
  //
  // We mark the block as initializer block because we don't want the
  // rewriter to add a '.result' assignment to such a block (to get compliant
  // behavior for code such as print(eval('var x = 7')), and for cosmetic
  // reasons when pretty-printing. Also, unless an assignment (initialization)
  // is inside an initializer block, it is ignored.
  //
  // Create new block with one expected declaration.
1526
  Block* block = new Block(NULL, 1, true);
1527 1528 1529
  VariableProxy* last_var = NULL;  // the last variable declared
  int nvars = 0;  // the number of variables declared
  do {
1530 1531
    if (fni_ != NULL) fni_->Enter();

1532 1533 1534
    // Parse variable name.
    if (nvars > 0) Consume(Token::COMMA);
    Handle<String> name = ParseIdentifier(CHECK_OK);
1535
    if (fni_ != NULL) fni_->PushVariableName(name);
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586

    // Declare variable.
    // Note that we *always* must treat the initial value via a separate init
    // assignment for variables and constants because the value must be assigned
    // when the variable is encountered in the source. But the variable/constant
    // is declared (and set to 'undefined') upon entering the function within
    // which the variable or constant is declared. Only function variables have
    // an initial value in the declaration (because they are initialized upon
    // entering the function).
    //
    // If we have a const declaration, in an inner scope, the proxy is always
    // bound to the declared variable (independent of possibly surrounding with
    // statements).
    last_var = Declare(name, mode, NULL,
                       is_const /* always bound for CONST! */,
                       CHECK_OK);
    nvars++;

    // Parse initialization expression if present and/or needed. A
    // declaration of the form:
    //
    //    var v = x;
    //
    // is syntactic sugar for:
    //
    //    var v; v = x;
    //
    // In particular, we need to re-lookup 'v' as it may be a
    // different 'v' than the 'v' in the declaration (if we are inside
    // a 'with' statement that makes a object property with name 'v'
    // visible).
    //
    // However, note that const declarations are different! A const
    // declaration of the form:
    //
    //   const c = x;
    //
    // is *not* syntactic sugar for:
    //
    //   const c; c = x;
    //
    // The "variable" c initialized to x is the same as the declared
    // one - there is no re-lookup (see the last parameter of the
    // Declare() call above).

    Expression* value = NULL;
    int position = -1;
    if (peek() == Token::ASSIGN) {
      Expect(Token::ASSIGN, CHECK_OK);
      position = scanner().location().beg_pos;
      value = ParseAssignmentExpression(accept_IN, CHECK_OK);
1587 1588
      // Don't infer if it is "a = function(){...}();"-like expression.
      if (fni_ != NULL && value->AsCall() == NULL) fni_->Infer();
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    }

    // Make sure that 'const c' actually initializes 'c' to undefined
    // even though it seems like a stupid thing to do.
    if (value == NULL && is_const) {
      value = GetLiteralUndefined();
    }

    // Global variable declarations must be compiled in a specific
    // way. When the script containing the global variable declaration
    // is entered, the global variable must be declared, so that if it
    // doesn't exist (not even in a prototype of the global object) it
    // gets created with an initial undefined value. This is handled
    // by the declarations part of the function representing the
    // top-level global code; see Runtime::DeclareGlobalVariable. If
    // it already exists (in the object or in a prototype), it is
    // *not* touched until the variable declaration statement is
    // executed.
    //
    // Executing the variable declaration statement will always
    // guarantee to give the global object a "local" variable; a
    // variable defined in the global object and not in any
    // prototype. This way, global variable declarations can shadow
    // properties in the prototype chain, but only after the variable
    // declaration statement has been executed. This is important in
    // browsers where the global object (window) has lots of
    // properties defined in prototype objects.

1617
    if (top_scope_->is_global_scope()) {
1618 1619 1620 1621 1622 1623
      // Compute the arguments for the runtime call.
      ZoneList<Expression*>* arguments = new ZoneList<Expression*>(2);
      // Be careful not to assign a value to the global variable if
      // we're in a with. The initialization value should not
      // necessarily be stored in the global object in that case,
      // which is why we need to generate a separate assignment node.
1624
      arguments->Add(new Literal(name));  // we have at least 1 parameter
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
      if (is_const || (value != NULL && !inside_with())) {
        arguments->Add(value);
        value = NULL;  // zap the value to avoid the unnecessary assignment
      }
      // Construct the call to Runtime::DeclareGlobal{Variable,Const}Locally
      // and add it to the initialization statement block. Note that
      // this function does different things depending on if we have
      // 1 or 2 parameters.
      CallRuntime* initialize;
      if (is_const) {
        initialize =
1636
          new CallRuntime(
1637 1638
            Factory::InitializeConstGlobal_symbol(),
            Runtime::FunctionForId(Runtime::kInitializeConstGlobal),
1639
            arguments);
1640 1641
      } else {
        initialize =
1642
          new CallRuntime(
1643 1644
            Factory::InitializeVarGlobal_symbol(),
            Runtime::FunctionForId(Runtime::kInitializeVarGlobal),
1645
            arguments);
1646
      }
1647
      block->AddStatement(new ExpressionStatement(initialize));
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
    }

    // Add an assignment node to the initialization statement block if
    // we still have a pending initialization value. We must distinguish
    // between variables and constants: Variable initializations are simply
    // assignments (with all the consequences if they are inside a 'with'
    // statement - they may change a 'with' object property). Constant
    // initializations always assign to the declared constant which is
    // always at the function scope level. This is only relevant for
    // dynamically looked-up variables and constants (the start context
    // for constant lookups is always the function context, while it is
    // the top context for variables). Sigh...
    if (value != NULL) {
      Token::Value op = (is_const ? Token::INIT_CONST : Token::INIT_VAR);
1662 1663
      Assignment* assignment = new Assignment(op, last_var, value, position);
      if (block) block->AddStatement(new ExpressionStatement(assignment));
1664
    }
1665 1666

    if (fni_ != NULL) fni_->Leave();
1667 1668 1669 1670
  } while (peek() == Token::COMMA);

  if (!is_const && nvars == 1) {
    // We have a single, non-const variable.
1671 1672
    ASSERT(last_var != NULL);
    *var = last_var;
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
  }

  return block;
}


static bool ContainsLabel(ZoneStringList* labels, Handle<String> label) {
  ASSERT(!label.is_null());
  if (labels != NULL)
    for (int i = labels->length(); i-- > 0; )
      if (labels->at(i).is_identical_to(label))
        return true;

  return false;
}


Statement* Parser::ParseExpressionOrLabelledStatement(ZoneStringList* labels,
                                                      bool* ok) {
  // ExpressionStatement | LabelledStatement ::
  //   Expression ';'
  //   Identifier ':' Statement

  Expression* expr = ParseExpression(true, CHECK_OK);
  if (peek() == Token::COLON && expr &&
      expr->AsVariableProxy() != NULL &&
      !expr->AsVariableProxy()->is_this()) {
    VariableProxy* var = expr->AsVariableProxy();
    Handle<String> label = var->name();
    // TODO(1240780): We don't check for redeclaration of labels
    // during preparsing since keeping track of the set of active
    // labels requires nontrivial changes to the way scopes are
    // structured.  However, these are probably changes we want to
    // make later anyway so we should go back and fix this then.
1707 1708 1709 1710 1711 1712 1713
    if (ContainsLabel(labels, label) || TargetStackContainsLabel(label)) {
      SmartPointer<char> c_string = label->ToCString(DISALLOW_NULLS);
      const char* elms[2] = { "Label", *c_string };
      Vector<const char*> args(elms, 2);
      ReportMessage("redeclaration", args);
      *ok = false;
      return NULL;
1714
    }
1715 1716 1717 1718 1719 1720
    if (labels == NULL) labels = new ZoneStringList(4);
    labels->Add(label);
    // Remove the "ghost" variable that turned out to be a label
    // from the top scope. This way, we don't try to resolve it
    // during the scope processing.
    top_scope_->RemoveUnresolved(var);
1721 1722 1723 1724 1725 1726
    Expect(Token::COLON, CHECK_OK);
    return ParseStatement(labels, ok);
  }

  // Parsed expression statement.
  ExpectSemicolon(CHECK_OK);
1727
  return new ExpressionStatement(expr);
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
}


IfStatement* Parser::ParseIfStatement(ZoneStringList* labels, bool* ok) {
  // IfStatement ::
  //   'if' '(' Expression ')' Statement ('else' Statement)?

  Expect(Token::IF, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  Expression* condition = ParseExpression(true, CHECK_OK);
  Expect(Token::RPAREN, CHECK_OK);
  Statement* then_statement = ParseStatement(labels, CHECK_OK);
  Statement* else_statement = NULL;
  if (peek() == Token::ELSE) {
    Next();
    else_statement = ParseStatement(labels, CHECK_OK);
1744 1745
  } else {
    else_statement = EmptyStatement();
1746
  }
1747
  return new IfStatement(condition, then_statement, else_statement);
1748 1749 1750 1751 1752 1753 1754 1755
}


Statement* Parser::ParseContinueStatement(bool* ok) {
  // ContinueStatement ::
  //   'continue' Identifier? ';'

  Expect(Token::CONTINUE, CHECK_OK);
1756
  Handle<String> label = Handle<String>::null();
1757 1758
  Token::Value tok = peek();
  if (!scanner_.has_line_terminator_before_next() &&
1759
      tok != Token::SEMICOLON && tok != Token::RBRACE && tok != Token::EOS) {
1760 1761 1762
    label = ParseIdentifier(CHECK_OK);
  }
  IterationStatement* target = NULL;
1763 1764 1765 1766 1767 1768 1769 1770
  target = LookupContinueTarget(label, CHECK_OK);
  if (target == NULL) {
    // Illegal continue statement.  To be consistent with KJS we delay
    // reporting of the syntax error until runtime.
    Handle<String> error_type = Factory::illegal_continue_symbol();
    if (!label.is_null()) error_type = Factory::unknown_label_symbol();
    Expression* throw_error = NewThrowSyntaxError(error_type, label);
    return new ExpressionStatement(throw_error);
1771 1772
  }
  ExpectSemicolon(CHECK_OK);
1773
  return new ContinueStatement(target);
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
}


Statement* Parser::ParseBreakStatement(ZoneStringList* labels, bool* ok) {
  // BreakStatement ::
  //   'break' Identifier? ';'

  Expect(Token::BREAK, CHECK_OK);
  Handle<String> label;
  Token::Value tok = peek();
  if (!scanner_.has_line_terminator_before_next() &&
1785
      tok != Token::SEMICOLON && tok != Token::RBRACE && tok != Token::EOS) {
1786 1787
    label = ParseIdentifier(CHECK_OK);
  }
1788
  // Parse labeled break statements that target themselves into
1789 1790
  // empty statements, e.g. 'l1: l2: l3: break l2;'
  if (!label.is_null() && ContainsLabel(labels, label)) {
1791
    return EmptyStatement();
1792 1793
  }
  BreakableStatement* target = NULL;
1794 1795 1796 1797 1798 1799 1800 1801
  target = LookupBreakTarget(label, CHECK_OK);
  if (target == NULL) {
    // Illegal break statement.  To be consistent with KJS we delay
    // reporting of the syntax error until runtime.
    Handle<String> error_type = Factory::illegal_break_symbol();
    if (!label.is_null()) error_type = Factory::unknown_label_symbol();
    Expression* throw_error = NewThrowSyntaxError(error_type, label);
    return new ExpressionStatement(throw_error);
1802 1803
  }
  ExpectSemicolon(CHECK_OK);
1804
  return new BreakStatement(target);
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
}


Statement* Parser::ParseReturnStatement(bool* ok) {
  // ReturnStatement ::
  //   'return' Expression? ';'

  // Consume the return token. It is necessary to do the before
  // reporting any errors on it, because of the way errors are
  // reported (underlining).
  Expect(Token::RETURN, CHECK_OK);

  // An ECMAScript program is considered syntactically incorrect if it
  // contains a return statement that is not within the body of a
  // function. See ECMA-262, section 12.9, page 67.
  //
  // To be consistent with KJS we report the syntax error at runtime.
1822
  if (!top_scope_->is_function_scope()) {
1823 1824
    Handle<String> type = Factory::illegal_return_symbol();
    Expression* throw_error = NewThrowSyntaxError(type, Handle<Object>::null());
1825
    return new ExpressionStatement(throw_error);
1826 1827 1828 1829 1830 1831 1832 1833
  }

  Token::Value tok = peek();
  if (scanner_.has_line_terminator_before_next() ||
      tok == Token::SEMICOLON ||
      tok == Token::RBRACE ||
      tok == Token::EOS) {
    ExpectSemicolon(CHECK_OK);
1834
    return new ReturnStatement(GetLiteralUndefined());
1835 1836 1837 1838
  }

  Expression* expr = ParseExpression(true, CHECK_OK);
  ExpectSemicolon(CHECK_OK);
1839
  return new ReturnStatement(expr);
1840 1841 1842
}


1843 1844 1845 1846
Block* Parser::WithHelper(Expression* obj,
                          ZoneStringList* labels,
                          bool is_catch_block,
                          bool* ok) {
1847
  // Parse the statement and collect escaping labels.
1848
  ZoneList<BreakTarget*>* target_list = new ZoneList<BreakTarget*>(0);
1849
  TargetCollector collector(target_list);
1850
  Statement* stat;
1851
  { Target target(&this->target_stack_, &collector);
1852 1853 1854 1855 1856 1857 1858 1859
    with_nesting_level_++;
    top_scope_->RecordWithStatement();
    stat = ParseStatement(labels, CHECK_OK);
    with_nesting_level_--;
  }
  // Create resulting block with two statements.
  // 1: Evaluate the with expression.
  // 2: The try-finally block evaluating the body.
1860
  Block* result = new Block(NULL, 2, false);
1861

1862
  if (result != NULL) {
1863
    result->AddStatement(new WithEnterStatement(obj, is_catch_block));
1864 1865

    // Create body block.
1866
    Block* body = new Block(NULL, 1, false);
1867 1868 1869
    body->AddStatement(stat);

    // Create exit block.
1870 1871
    Block* exit = new Block(NULL, 1, false);
    exit->AddStatement(new WithExitStatement());
1872 1873

    // Return a try-finally statement.
1874
    TryFinallyStatement* wrapper = new TryFinallyStatement(body, exit);
1875
    wrapper->set_escaping_targets(collector.targets());
1876 1877
    result->AddStatement(wrapper);
  }
1878
  return result;
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
}


Statement* Parser::ParseWithStatement(ZoneStringList* labels, bool* ok) {
  // WithStatement ::
  //   'with' '(' Expression ')' Statement

  Expect(Token::WITH, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  Expression* expr = ParseExpression(true, CHECK_OK);
  Expect(Token::RPAREN, CHECK_OK);

1891
  return WithHelper(expr, labels, false, CHECK_OK);
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
}


CaseClause* Parser::ParseCaseClause(bool* default_seen_ptr, bool* ok) {
  // CaseClause ::
  //   'case' Expression ':' Statement*
  //   'default' ':' Statement*

  Expression* label = NULL;  // NULL expression indicates default case
  if (peek() == Token::CASE) {
    Expect(Token::CASE, CHECK_OK);
    label = ParseExpression(true, CHECK_OK);
  } else {
    Expect(Token::DEFAULT, CHECK_OK);
    if (*default_seen_ptr) {
      ReportMessage("multiple_defaults_in_switch",
                    Vector<const char*>::empty());
      *ok = false;
      return NULL;
    }
    *default_seen_ptr = true;
  }
  Expect(Token::COLON, CHECK_OK);

1916
  ZoneList<Statement*>* statements = new ZoneList<Statement*>(5);
1917 1918 1919 1920
  while (peek() != Token::CASE &&
         peek() != Token::DEFAULT &&
         peek() != Token::RBRACE) {
    Statement* stat = ParseStatement(NULL, CHECK_OK);
1921
    statements->Add(stat);
1922 1923
  }

1924
  return new CaseClause(label, statements);
1925 1926 1927 1928 1929 1930 1931 1932
}


SwitchStatement* Parser::ParseSwitchStatement(ZoneStringList* labels,
                                              bool* ok) {
  // SwitchStatement ::
  //   'switch' '(' Expression ')' '{' CaseClause* '}'

1933
  SwitchStatement* statement = new SwitchStatement(labels);
1934
  Target target(&this->target_stack_, statement);
1935 1936 1937 1938 1939 1940 1941

  Expect(Token::SWITCH, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  Expression* tag = ParseExpression(true, CHECK_OK);
  Expect(Token::RPAREN, CHECK_OK);

  bool default_seen = false;
1942
  ZoneList<CaseClause*>* cases = new ZoneList<CaseClause*>(4);
1943 1944 1945
  Expect(Token::LBRACE, CHECK_OK);
  while (peek() != Token::RBRACE) {
    CaseClause* clause = ParseCaseClause(&default_seen, CHECK_OK);
1946
    cases->Add(clause);
1947 1948 1949
  }
  Expect(Token::RBRACE, CHECK_OK);

1950
  if (statement) statement->Initialize(tag, cases);
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
  return statement;
}


Statement* Parser::ParseThrowStatement(bool* ok) {
  // ThrowStatement ::
  //   'throw' Expression ';'

  Expect(Token::THROW, CHECK_OK);
  int pos = scanner().location().beg_pos;
  if (scanner_.has_line_terminator_before_next()) {
    ReportMessage("newline_after_throw", Vector<const char*>::empty());
    *ok = false;
    return NULL;
  }
  Expression* exception = ParseExpression(true, CHECK_OK);
  ExpectSemicolon(CHECK_OK);

1969
  return new ExpressionStatement(new Throw(exception, pos));
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
}


TryStatement* Parser::ParseTryStatement(bool* ok) {
  // TryStatement ::
  //   'try' Block Catch
  //   'try' Block Finally
  //   'try' Block Catch Finally
  //
  // Catch ::
  //   'catch' '(' Identifier ')' Block
  //
  // Finally ::
  //   'finally' Block

  Expect(Token::TRY, CHECK_OK);

1987
  ZoneList<BreakTarget*>* target_list = new ZoneList<BreakTarget*>(0);
1988
  TargetCollector collector(target_list);
1989 1990
  Block* try_block;

1991
  { Target target(&this->target_stack_, &collector);
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
    try_block = ParseBlock(NULL, CHECK_OK);
  }

  Block* catch_block = NULL;
  VariableProxy* catch_var = NULL;
  Block* finally_block = NULL;

  Token::Value tok = peek();
  if (tok != Token::CATCH && tok != Token::FINALLY) {
    ReportMessage("no_catch_or_finally", Vector<const char*>::empty());
    *ok = false;
    return NULL;
  }

  // If we can break out from the catch block and there is a finally block,
2007 2008 2009
  // then we will need to collect jump targets from the catch block. Since
  // we don't know yet if there will be a finally block, we always collect
  // the jump targets.
2010
  ZoneList<BreakTarget*>* catch_target_list = new ZoneList<BreakTarget*>(0);
2011
  TargetCollector catch_collector(catch_target_list);
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
  bool has_catch = false;
  if (tok == Token::CATCH) {
    has_catch = true;
    Consume(Token::CATCH);

    Expect(Token::LPAREN, CHECK_OK);
    Handle<String> name = ParseIdentifier(CHECK_OK);
    Expect(Token::RPAREN, CHECK_OK);

    if (peek() == Token::LBRACE) {
      // Allocate a temporary for holding the finally state while
      // executing the finally block.
      catch_var = top_scope_->NewTemporary(Factory::catch_var_symbol());
2025 2026
      Literal* name_literal = new Literal(name);
      Expression* obj = new CatchExtensionObject(name_literal, catch_var);
2027
      { Target target(&this->target_stack_, &catch_collector);
2028
        catch_block = WithHelper(obj, NULL, true, CHECK_OK);
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
      }
    } else {
      Expect(Token::LBRACE, CHECK_OK);
    }

    tok = peek();
  }

  if (tok == Token::FINALLY || !has_catch) {
    Consume(Token::FINALLY);
    // Declare a variable for holding the finally state while
    // executing the finally block.
    finally_block = ParseBlock(NULL, CHECK_OK);
  }

  // Simplify the AST nodes by converting:
  //   'try { } catch { } finally { }'
  // to:
  //   'try { try { } catch { } } finally { }'

2049
  if (catch_block != NULL && finally_block != NULL) {
2050
    TryCatchStatement* statement =
2051
        new TryCatchStatement(try_block, catch_var, catch_block);
2052
    statement->set_escaping_targets(collector.targets());
2053
    try_block = new Block(NULL, 1, false);
2054 2055 2056 2057 2058
    try_block->AddStatement(statement);
    catch_block = NULL;
  }

  TryStatement* result = NULL;
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
  if (catch_block != NULL) {
    ASSERT(finally_block == NULL);
    result = new TryCatchStatement(try_block, catch_var, catch_block);
    result->set_escaping_targets(collector.targets());
  } else {
    ASSERT(finally_block != NULL);
    result = new TryFinallyStatement(try_block, finally_block);
    // Add the jump targets of the try block and the catch block.
    for (int i = 0; i < collector.targets()->length(); i++) {
      catch_collector.AddTarget(collector.targets()->at(i));
2069
    }
2070
    result->set_escaping_targets(catch_collector.targets());
2071 2072 2073 2074 2075 2076
  }

  return result;
}


2077 2078
DoWhileStatement* Parser::ParseDoWhileStatement(ZoneStringList* labels,
                                                bool* ok) {
2079 2080 2081
  // DoStatement ::
  //   'do' Statement 'while' '(' Expression ')' ';'

2082
  temp_scope_->AddLoop();
2083
  DoWhileStatement* loop = new DoWhileStatement(labels);
2084
  Target target(&this->target_stack_, loop);
2085 2086 2087 2088 2089

  Expect(Token::DO, CHECK_OK);
  Statement* body = ParseStatement(NULL, CHECK_OK);
  Expect(Token::WHILE, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
2090 2091 2092 2093 2094 2095

  if (loop != NULL) {
    int position = scanner().location().beg_pos;
    loop->set_condition_position(position);
  }

2096
  Expression* cond = ParseExpression(true, CHECK_OK);
2097
  if (cond != NULL) cond->set_is_loop_condition(true);
2098 2099 2100 2101 2102 2103 2104 2105
  Expect(Token::RPAREN, CHECK_OK);

  // Allow do-statements to be terminated with and without
  // semi-colons. This allows code such as 'do;while(0)return' to
  // parse, which would not be the case if we had used the
  // ExpectSemicolon() functionality here.
  if (peek() == Token::SEMICOLON) Consume(Token::SEMICOLON);

2106
  if (loop != NULL) loop->Initialize(cond, body);
2107 2108 2109 2110
  return loop;
}


2111
WhileStatement* Parser::ParseWhileStatement(ZoneStringList* labels, bool* ok) {
2112 2113 2114
  // WhileStatement ::
  //   'while' '(' Expression ')' Statement

2115
  temp_scope_->AddLoop();
2116
  WhileStatement* loop = new WhileStatement(labels);
2117
  Target target(&this->target_stack_, loop);
2118 2119 2120 2121

  Expect(Token::WHILE, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  Expression* cond = ParseExpression(true, CHECK_OK);
2122
  if (cond != NULL) cond->set_is_loop_condition(true);
2123 2124 2125
  Expect(Token::RPAREN, CHECK_OK);
  Statement* body = ParseStatement(NULL, CHECK_OK);

2126
  if (loop != NULL) loop->Initialize(cond, body);
2127 2128 2129 2130 2131 2132 2133 2134
  return loop;
}


Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
  // ForStatement ::
  //   'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement

2135
  temp_scope_->AddLoop();
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
  Statement* init = NULL;

  Expect(Token::FOR, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  if (peek() != Token::SEMICOLON) {
    if (peek() == Token::VAR || peek() == Token::CONST) {
      Expression* each = NULL;
      Block* variable_statement =
          ParseVariableDeclarations(false, &each, CHECK_OK);
      if (peek() == Token::IN && each != NULL) {
2146
        ForInStatement* loop = new ForInStatement(labels);
2147
        Target target(&this->target_stack_, loop);
2148 2149 2150 2151 2152 2153

        Expect(Token::IN, CHECK_OK);
        Expression* enumerable = ParseExpression(true, CHECK_OK);
        Expect(Token::RPAREN, CHECK_OK);

        Statement* body = ParseStatement(NULL, CHECK_OK);
2154 2155 2156 2157 2158 2159
        loop->Initialize(each, enumerable, body);
        Block* result = new Block(NULL, 2, false);
        result->AddStatement(variable_statement);
        result->AddStatement(loop);
        // Parsed for-in loop w/ variable/const declaration.
        return result;
2160 2161 2162 2163 2164 2165 2166
      } else {
        init = variable_statement;
      }

    } else {
      Expression* expression = ParseExpression(false, CHECK_OK);
      if (peek() == Token::IN) {
2167 2168 2169 2170
        // Signal a reference error if the expression is an invalid
        // left-hand side expression.  We could report this as a syntax
        // error here but for compatibility with JSC we choose to report
        // the error at runtime.
2171
        if (expression == NULL || !expression->IsValidLeftHandSide()) {
2172 2173
          Handle<String> type = Factory::invalid_lhs_in_for_in_symbol();
          expression = NewThrowReferenceError(type);
2174
        }
2175
        ForInStatement* loop = new ForInStatement(labels);
2176
        Target target(&this->target_stack_, loop);
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187

        Expect(Token::IN, CHECK_OK);
        Expression* enumerable = ParseExpression(true, CHECK_OK);
        Expect(Token::RPAREN, CHECK_OK);

        Statement* body = ParseStatement(NULL, CHECK_OK);
        if (loop) loop->Initialize(expression, enumerable, body);
        // Parsed for-in loop.
        return loop;

      } else {
2188
        init = new ExpressionStatement(expression);
2189 2190 2191 2192 2193
      }
    }
  }

  // Standard 'for' loop
2194
  ForStatement* loop = new ForStatement(labels);
2195
  Target target(&this->target_stack_, loop);
2196 2197 2198 2199 2200 2201 2202

  // Parsed initializer at this point.
  Expect(Token::SEMICOLON, CHECK_OK);

  Expression* cond = NULL;
  if (peek() != Token::SEMICOLON) {
    cond = ParseExpression(true, CHECK_OK);
2203
    if (cond != NULL) cond->set_is_loop_condition(true);
2204 2205 2206 2207 2208 2209
  }
  Expect(Token::SEMICOLON, CHECK_OK);

  Statement* next = NULL;
  if (peek() != Token::RPAREN) {
    Expression* exp = ParseExpression(true, CHECK_OK);
2210
    next = new ExpressionStatement(exp);
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
  }
  Expect(Token::RPAREN, CHECK_OK);

  Statement* body = ParseStatement(NULL, CHECK_OK);
  if (loop) loop->Initialize(init, cond, next, body);
  return loop;
}


// Precedence = 1
Expression* Parser::ParseExpression(bool accept_IN, bool* ok) {
  // Expression ::
  //   AssignmentExpression
  //   Expression ',' AssignmentExpression

  Expression* result = ParseAssignmentExpression(accept_IN, CHECK_OK);
  while (peek() == Token::COMMA) {
    Expect(Token::COMMA, CHECK_OK);
2229
    int position = scanner().location().beg_pos;
2230
    Expression* right = ParseAssignmentExpression(accept_IN, CHECK_OK);
2231
    result = new BinaryOperation(Token::COMMA, result, right, position);
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
  }
  return result;
}


// Precedence = 2
Expression* Parser::ParseAssignmentExpression(bool accept_IN, bool* ok) {
  // AssignmentExpression ::
  //   ConditionalExpression
  //   LeftHandSideExpression AssignmentOperator AssignmentExpression

2243
  if (fni_ != NULL) fni_->Enter();
2244 2245 2246
  Expression* expression = ParseConditionalExpression(accept_IN, CHECK_OK);

  if (!Token::IsAssignmentOp(peek())) {
2247
    if (fni_ != NULL) fni_->Leave();
2248 2249 2250 2251
    // Parsed conditional expression only (no assignment).
    return expression;
  }

2252 2253 2254 2255
  // Signal a reference error if the expression is an invalid left-hand
  // side expression.  We could report this as a syntax error here but
  // for compatibility with JSC we choose to report the error at
  // runtime.
2256
  if (expression == NULL || !expression->IsValidLeftHandSide()) {
2257 2258
    Handle<String> type = Factory::invalid_lhs_in_assignment_symbol();
    expression = NewThrowReferenceError(type);
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
  }

  Token::Value op = Next();  // Get assignment operator.
  int pos = scanner().location().beg_pos;
  Expression* right = ParseAssignmentExpression(accept_IN, CHECK_OK);

  // TODO(1231235): We try to estimate the set of properties set by
  // constructors. We define a new property whenever there is an
  // assignment to a property of 'this'. We should probably only add
  // properties if we haven't seen them before. Otherwise we'll
  // probably overestimate the number of properties.
  Property* property = expression ? expression->AsProperty() : NULL;
  if (op == Token::ASSIGN &&
      property != NULL &&
      property->obj()->AsVariableProxy() != NULL &&
      property->obj()->AsVariableProxy()->is_this()) {
    temp_scope_->AddProperty();
  }

2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
  if (fni_ != NULL) {
    // Check if the right hand side is a call to avoid inferring a
    // name if we're dealing with "a = function(){...}();"-like
    // expression.
    if ((op == Token::INIT_VAR
         || op == Token::INIT_CONST
         || op == Token::ASSIGN)
        && (right->AsCall() == NULL)) {
      fni_->Infer();
    }
    fni_->Leave();
  }

2291
  return new Assignment(op, expression, right, pos);
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
}


// Precedence = 3
Expression* Parser::ParseConditionalExpression(bool accept_IN, bool* ok) {
  // ConditionalExpression ::
  //   LogicalOrExpression
  //   LogicalOrExpression '?' AssignmentExpression ':' AssignmentExpression

  // We start using the binary expression parser for prec >= 4 only!
  Expression* expression = ParseBinaryExpression(4, accept_IN, CHECK_OK);
  if (peek() != Token::CONDITIONAL) return expression;
  Consume(Token::CONDITIONAL);
  // In parsing the first assignment expression in conditional
  // expressions we always accept the 'in' keyword; see ECMA-262,
  // section 11.12, page 58.
2308
  int left_position = scanner().peek_location().beg_pos;
2309 2310
  Expression* left = ParseAssignmentExpression(true, CHECK_OK);
  Expect(Token::COLON, CHECK_OK);
2311
  int right_position = scanner().peek_location().beg_pos;
2312
  Expression* right = ParseAssignmentExpression(accept_IN, CHECK_OK);
2313 2314
  return new Conditional(expression, left, right,
                         left_position, right_position);
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
}


static int Precedence(Token::Value tok, bool accept_IN) {
  if (tok == Token::IN && !accept_IN)
    return 0;  // 0 precedence will terminate binary expression parsing

  return Token::Precedence(tok);
}


// Precedence >= 4
Expression* Parser::ParseBinaryExpression(int prec, bool accept_IN, bool* ok) {
  ASSERT(prec >= 4);
  Expression* x = ParseUnaryExpression(CHECK_OK);
  for (int prec1 = Precedence(peek(), accept_IN); prec1 >= prec; prec1--) {
    // prec1 >= 4
    while (Precedence(peek(), accept_IN) == prec1) {
      Token::Value op = Next();
2334
      int position = scanner().location().beg_pos;
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
      Expression* y = ParseBinaryExpression(prec1 + 1, accept_IN, CHECK_OK);

      // Compute some expressions involving only number literals.
      if (x && x->AsLiteral() && x->AsLiteral()->handle()->IsNumber() &&
          y && y->AsLiteral() && y->AsLiteral()->handle()->IsNumber()) {
        double x_val = x->AsLiteral()->handle()->Number();
        double y_val = y->AsLiteral()->handle()->Number();

        switch (op) {
          case Token::ADD:
            x = NewNumberLiteral(x_val + y_val);
            continue;
          case Token::SUB:
            x = NewNumberLiteral(x_val - y_val);
            continue;
          case Token::MUL:
            x = NewNumberLiteral(x_val * y_val);
            continue;
          case Token::DIV:
            x = NewNumberLiteral(x_val / y_val);
            continue;
          case Token::BIT_OR:
            x = NewNumberLiteral(DoubleToInt32(x_val) | DoubleToInt32(y_val));
            continue;
          case Token::BIT_AND:
            x = NewNumberLiteral(DoubleToInt32(x_val) & DoubleToInt32(y_val));
            continue;
          case Token::BIT_XOR:
            x = NewNumberLiteral(DoubleToInt32(x_val) ^ DoubleToInt32(y_val));
            continue;
          case Token::SHL: {
            int value = DoubleToInt32(x_val) << (DoubleToInt32(y_val) & 0x1f);
            x = NewNumberLiteral(value);
            continue;
          }
          case Token::SHR: {
            uint32_t shift = DoubleToInt32(y_val) & 0x1f;
            uint32_t value = DoubleToUint32(x_val) >> shift;
            x = NewNumberLiteral(value);
            continue;
          }
          case Token::SAR: {
            uint32_t shift = DoubleToInt32(y_val) & 0x1f;
            int value = ArithmeticShiftRight(DoubleToInt32(x_val), shift);
            x = NewNumberLiteral(value);
            continue;
          }
          default:
            break;
        }
      }

2387 2388 2389 2390 2391 2392
      // Convert constant divisions to multiplications for speed.
      if (op == Token::DIV &&
          y && y->AsLiteral() && y->AsLiteral()->handle()->IsNumber()) {
        double y_val = y->AsLiteral()->handle()->Number();
        int64_t y_int = static_cast<int64_t>(y_val);
        // There are rounding issues with this optimization, but they don't
2393 2394 2395 2396 2397 2398 2399 2400 2401
        // apply if the number to be divided with has a reciprocal that can be
        // precisely represented as a floating point number.  This is the case
        // if the number is an integer power of 2.  Negative integer powers of
        // 2 work too, but for -2, -1, 1 and 2 we don't do the strength
        // reduction because the inlined optimistic idiv has a reasonable
        // chance of succeeding by producing a Smi answer with no remainder.
        if (static_cast<double>(y_int) == y_val &&
            (IsPowerOf2(y_int) || IsPowerOf2(-y_int)) &&
            (y_int > 2 || y_int < -2)) {
2402 2403 2404 2405 2406
          y = NewNumberLiteral(1 / y_val);
          op = Token::MUL;
        }
      }

2407 2408
      // For now we distinguish between comparisons and other binary
      // operations.  (We could combine the two and get rid of this
2409
      // code and AST node eventually.)
2410 2411 2412 2413 2414 2415 2416 2417
      if (Token::IsCompareOp(op)) {
        // We have a comparison.
        Token::Value cmp = op;
        switch (op) {
          case Token::NE: cmp = Token::EQ; break;
          case Token::NE_STRICT: cmp = Token::EQ_STRICT; break;
          default: break;
        }
2418
        x = NewCompareNode(cmp, x, y, position);
2419 2420
        if (cmp != op) {
          // The comparison was negated - add a NOT.
2421
          x = new UnaryOperation(Token::NOT, x);
2422 2423 2424 2425
        }

      } else {
        // We have a "normal" binary operation.
2426
        x = new BinaryOperation(op, x, y, position);
2427 2428 2429 2430 2431 2432 2433
      }
    }
  }
  return x;
}


2434 2435
Expression* Parser::NewCompareNode(Token::Value op,
                                   Expression* x,
2436 2437
                                   Expression* y,
                                   int position) {
2438
  ASSERT(op != Token::NE && op != Token::NE_STRICT);
2439
  if (op == Token::EQ || op == Token::EQ_STRICT) {
2440 2441 2442
    bool is_strict = (op == Token::EQ_STRICT);
    Literal* x_literal = x->AsLiteral();
    if (x_literal != NULL && x_literal->IsNull()) {
2443
      return new CompareToNull(is_strict, y);
2444 2445 2446 2447
    }

    Literal* y_literal = y->AsLiteral();
    if (y_literal != NULL && y_literal->IsNull()) {
2448
      return new CompareToNull(is_strict, x);
2449 2450
    }
  }
2451
  return new CompareOperation(op, x, y, position);
2452 2453 2454
}


2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
Expression* Parser::ParseUnaryExpression(bool* ok) {
  // UnaryExpression ::
  //   PostfixExpression
  //   'delete' UnaryExpression
  //   'void' UnaryExpression
  //   'typeof' UnaryExpression
  //   '++' UnaryExpression
  //   '--' UnaryExpression
  //   '+' UnaryExpression
  //   '-' UnaryExpression
  //   '~' UnaryExpression
  //   '!' UnaryExpression

  Token::Value op = peek();
  if (Token::IsUnaryOp(op)) {
    op = Next();
2471
    Expression* expression = ParseUnaryExpression(CHECK_OK);
2472 2473

    // Compute some expressions involving only number literals.
2474 2475 2476
    if (expression != NULL && expression->AsLiteral() &&
        expression->AsLiteral()->handle()->IsNumber()) {
      double value = expression->AsLiteral()->handle()->Number();
2477
      switch (op) {
2478
        case Token::ADD:
2479
          return expression;
2480
        case Token::SUB:
2481
          return NewNumberLiteral(-value);
2482
        case Token::BIT_NOT:
2483
          return NewNumberLiteral(~DoubleToInt32(value));
2484 2485 2486 2487
        default: break;
      }
    }

2488
    return new UnaryOperation(op, expression);
2489 2490 2491

  } else if (Token::IsCountOp(op)) {
    op = Next();
2492 2493 2494 2495 2496 2497 2498 2499
    Expression* expression = ParseUnaryExpression(CHECK_OK);
    // Signal a reference error if the expression is an invalid
    // left-hand side expression.  We could report this as a syntax
    // error here but for compatibility with JSC we choose to report the
    // error at runtime.
    if (expression == NULL || !expression->IsValidLeftHandSide()) {
      Handle<String> type = Factory::invalid_lhs_in_prefix_op_symbol();
      expression = NewThrowReferenceError(type);
2500
    }
2501
    int position = scanner().location().beg_pos;
2502 2503
    IncrementOperation* increment = new IncrementOperation(op, expression);
    return new CountOperation(true /* prefix */, increment, position);
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514

  } else {
    return ParsePostfixExpression(ok);
  }
}


Expression* Parser::ParsePostfixExpression(bool* ok) {
  // PostfixExpression ::
  //   LeftHandSideExpression ('++' | '--')?

2515
  Expression* expression = ParseLeftHandSideExpression(CHECK_OK);
2516
  if (!scanner_.has_line_terminator_before_next() && Token::IsCountOp(peek())) {
2517 2518 2519 2520 2521 2522 2523
    // Signal a reference error if the expression is an invalid
    // left-hand side expression.  We could report this as a syntax
    // error here but for compatibility with JSC we choose to report the
    // error at runtime.
    if (expression == NULL || !expression->IsValidLeftHandSide()) {
      Handle<String> type = Factory::invalid_lhs_in_postfix_op_symbol();
      expression = NewThrowReferenceError(type);
2524 2525
    }
    Token::Value next = Next();
2526
    int position = scanner().location().beg_pos;
2527 2528
    IncrementOperation* increment = new IncrementOperation(next, expression);
    expression = new CountOperation(false /* postfix */, increment, position);
2529
  }
2530
  return expression;
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
}


Expression* Parser::ParseLeftHandSideExpression(bool* ok) {
  // LeftHandSideExpression ::
  //   (NewExpression | MemberExpression) ...

  Expression* result;
  if (peek() == Token::NEW) {
    result = ParseNewExpression(CHECK_OK);
  } else {
    result = ParseMemberExpression(CHECK_OK);
  }

  while (true) {
    switch (peek()) {
      case Token::LBRACK: {
        Consume(Token::LBRACK);
        int pos = scanner().location().beg_pos;
        Expression* index = ParseExpression(true, CHECK_OK);
2551
        result = new Property(result, index, pos);
2552 2553 2554 2555 2556 2557 2558 2559 2560
        Expect(Token::RBRACK, CHECK_OK);
        break;
      }

      case Token::LPAREN: {
        int pos = scanner().location().beg_pos;
        ZoneList<Expression*>* args = ParseArguments(CHECK_OK);

        // Keep track of eval() calls since they disable all local variable
2561 2562 2563 2564 2565 2566 2567
        // optimizations.
        // The calls that need special treatment are the
        // direct (i.e. not aliased) eval calls. These calls are all of the
        // form eval(...) with no explicit receiver object where eval is not
        // declared in the current scope chain. These calls are marked as
        // potentially direct eval calls. Whether they are actually direct calls
        // to eval is determined at run time.
2568 2569 2570 2571 2572 2573
        VariableProxy* callee = result->AsVariableProxy();
        if (callee != NULL && callee->IsVariable(Factory::eval_symbol())) {
          Handle<String> name = callee->name();
          Variable* var = top_scope_->Lookup(name);
          if (var == NULL) {
            top_scope_->RecordEvalCall();
2574 2575
          }
        }
2576
        result = NewCall(result, args, pos);
2577 2578 2579 2580 2581 2582
        break;
      }

      case Token::PERIOD: {
        Consume(Token::PERIOD);
        int pos = scanner().location().beg_pos;
2583
        Handle<String> name = ParseIdentifierName(CHECK_OK);
2584
        result = new Property(result, new Literal(name), pos);
2585
        if (fni_ != NULL) fni_->PushLiteralName(name);
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
        break;
      }

      default:
        return result;
    }
  }
}


bak@chromium.org's avatar
bak@chromium.org committed
2596
Expression* Parser::ParseNewPrefix(PositionStack* stack, bool* ok) {
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
  // NewExpression ::
  //   ('new')+ MemberExpression

  // The grammar for new expressions is pretty warped. The keyword
  // 'new' can either be a part of the new expression (where it isn't
  // followed by an argument list) or a part of the member expression,
  // where it must be followed by an argument list. To accommodate
  // this, we parse the 'new' keywords greedily and keep track of how
  // many we have parsed. This information is then passed on to the
  // member expression parser, which is only allowed to match argument
  // lists as long as it has 'new' prefixes left
bak@chromium.org's avatar
bak@chromium.org committed
2608 2609 2610 2611 2612 2613 2614 2615
  Expect(Token::NEW, CHECK_OK);
  PositionStack::Element pos(stack, scanner().location().beg_pos);

  Expression* result;
  if (peek() == Token::NEW) {
    result = ParseNewPrefix(stack, CHECK_OK);
  } else {
    result = ParseMemberWithNewPrefixesExpression(stack, CHECK_OK);
2616 2617
  }

bak@chromium.org's avatar
bak@chromium.org committed
2618 2619
  if (!stack->is_empty()) {
    int last = stack->pop();
2620
    result = new CallNew(result, new ZoneList<Expression*>(0), last);
2621 2622 2623 2624 2625
  }
  return result;
}


bak@chromium.org's avatar
bak@chromium.org committed
2626 2627 2628 2629 2630 2631
Expression* Parser::ParseNewExpression(bool* ok) {
  PositionStack stack(ok);
  return ParseNewPrefix(&stack, ok);
}


2632
Expression* Parser::ParseMemberExpression(bool* ok) {
bak@chromium.org's avatar
bak@chromium.org committed
2633
  return ParseMemberWithNewPrefixesExpression(NULL, ok);
2634 2635 2636
}


bak@chromium.org's avatar
bak@chromium.org committed
2637 2638
Expression* Parser::ParseMemberWithNewPrefixesExpression(PositionStack* stack,
                                                         bool* ok) {
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
  // MemberExpression ::
  //   (PrimaryExpression | FunctionLiteral)
  //     ('[' Expression ']' | '.' Identifier | Arguments)*

  // Parse the initial primary or function expression.
  Expression* result = NULL;
  if (peek() == Token::FUNCTION) {
    Expect(Token::FUNCTION, CHECK_OK);
    int function_token_position = scanner().location().beg_pos;
    Handle<String> name;
    if (peek() == Token::IDENTIFIER) name = ParseIdentifier(CHECK_OK);
    result = ParseFunctionLiteral(name, function_token_position,
                                  NESTED, CHECK_OK);
  } else {
    result = ParsePrimaryExpression(CHECK_OK);
  }

  while (true) {
    switch (peek()) {
      case Token::LBRACK: {
        Consume(Token::LBRACK);
        int pos = scanner().location().beg_pos;
        Expression* index = ParseExpression(true, CHECK_OK);
2662
        result = new Property(result, index, pos);
2663 2664 2665 2666 2667 2668
        Expect(Token::RBRACK, CHECK_OK);
        break;
      }
      case Token::PERIOD: {
        Consume(Token::PERIOD);
        int pos = scanner().location().beg_pos;
2669
        Handle<String> name = ParseIdentifierName(CHECK_OK);
2670
        result = new Property(result, new Literal(name), pos);
2671
        if (fni_ != NULL) fni_->PushLiteralName(name);
2672 2673 2674
        break;
      }
      case Token::LPAREN: {
bak@chromium.org's avatar
bak@chromium.org committed
2675
        if ((stack == NULL) || stack->is_empty()) return result;
2676 2677
        // Consume one of the new prefixes (already parsed).
        ZoneList<Expression*>* args = ParseArguments(CHECK_OK);
bak@chromium.org's avatar
bak@chromium.org committed
2678
        int last = stack->pop();
2679
        result = new CallNew(result, args, last);
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
        break;
      }
      default:
        return result;
    }
  }
}


DebuggerStatement* Parser::ParseDebuggerStatement(bool* ok) {
  // In ECMA-262 'debugger' is defined as a reserved keyword. In some browser
  // contexts this is used as a statement which invokes the debugger as i a
  // break point is present.
  // DebuggerStatement ::
  //   'debugger' ';'

  Expect(Token::DEBUGGER, CHECK_OK);
  ExpectSemicolon(CHECK_OK);
2698
  return new DebuggerStatement();
2699 2700 2701 2702 2703 2704
}


void Parser::ReportUnexpectedToken(Token::Value token) {
  // We don't report stack overflows here, to avoid increasing the
  // stack depth even further.  Instead we report it after parsing is
2705
  // over, in ParseProgram/ParseJson.
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
  if (token == Token::ILLEGAL && scanner().stack_overflow())
    return;
  // Four of the tokens are treated specially
  switch (token) {
  case Token::EOS:
    return ReportMessage("unexpected_eos", Vector<const char*>::empty());
  case Token::NUMBER:
    return ReportMessage("unexpected_token_number",
                         Vector<const char*>::empty());
  case Token::STRING:
    return ReportMessage("unexpected_token_string",
                         Vector<const char*>::empty());
  case Token::IDENTIFIER:
    return ReportMessage("unexpected_token_identifier",
                         Vector<const char*>::empty());
  default:
    const char* name = Token::String(token);
    ASSERT(name != NULL);
    ReportMessage("unexpected_token", Vector<const char*>(&name, 1));
  }
}


2729 2730 2731 2732 2733 2734 2735 2736 2737
void Parser::ReportInvalidPreparseData(Handle<String> name, bool* ok) {
  SmartPointer<char> name_string = name->ToCString(DISALLOW_NULLS);
  const char* element[1] = { *name_string };
  ReportMessage("invalid_preparser_data",
                Vector<const char*>(element, 1));
  *ok = false;
}


2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
Expression* Parser::ParsePrimaryExpression(bool* ok) {
  // PrimaryExpression ::
  //   'this'
  //   'null'
  //   'true'
  //   'false'
  //   Identifier
  //   Number
  //   String
  //   ArrayLiteral
  //   ObjectLiteral
  //   RegExpLiteral
  //   '(' Expression ')'

  Expression* result = NULL;
  switch (peek()) {
    case Token::THIS: {
      Consume(Token::THIS);
2756 2757
      VariableProxy* recv = top_scope_->receiver();
      result = recv;
2758 2759 2760 2761 2762
      break;
    }

    case Token::NULL_LITERAL:
      Consume(Token::NULL_LITERAL);
2763
      result = new Literal(Factory::null_value());
2764 2765 2766 2767
      break;

    case Token::TRUE_LITERAL:
      Consume(Token::TRUE_LITERAL);
2768
      result = new Literal(Factory::true_value());
2769 2770 2771 2772
      break;

    case Token::FALSE_LITERAL:
      Consume(Token::FALSE_LITERAL);
2773
      result = new Literal(Factory::false_value());
2774 2775 2776 2777
      break;

    case Token::IDENTIFIER: {
      Handle<String> name = ParseIdentifier(CHECK_OK);
2778
      if (fni_ != NULL) fni_->PushVariableName(name);
2779
      result = top_scope_->NewUnresolved(name, inside_with());
2780 2781 2782 2783 2784 2785
      break;
    }

    case Token::NUMBER: {
      Consume(Token::NUMBER);
      double value =
2786
        StringToDouble(scanner_.literal(), ALLOW_HEX | ALLOW_OCTALS);
2787 2788 2789 2790 2791 2792
      result = NewNumberLiteral(value);
      break;
    }

    case Token::STRING: {
      Consume(Token::STRING);
2793
      Handle<String> symbol = GetSymbol(CHECK_OK);
2794
      result = new Literal(symbol);
2795
      if (fni_ != NULL) fni_->PushLiteralName(symbol);
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
      break;
    }

    case Token::ASSIGN_DIV:
      result = ParseRegExpLiteral(true, CHECK_OK);
      break;

    case Token::DIV:
      result = ParseRegExpLiteral(false, CHECK_OK);
      break;

    case Token::LBRACK:
      result = ParseArrayLiteral(CHECK_OK);
      break;

    case Token::LBRACE:
      result = ParseObjectLiteral(CHECK_OK);
      break;

    case Token::LPAREN:
      Consume(Token::LPAREN);
      result = ParseExpression(true, CHECK_OK);
      Expect(Token::RPAREN, CHECK_OK);
      break;

    case Token::MOD:
      if (allow_natives_syntax_ || extension_ != NULL) {
        result = ParseV8Intrinsic(CHECK_OK);
        break;
      }
      // If we're not allowing special syntax we fall-through to the
      // default case.

    default: {
2830
      Token::Value tok = Next();
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
      ReportUnexpectedToken(tok);
      *ok = false;
      return NULL;
    }
  }

  return result;
}


2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
void Parser::BuildArrayLiteralBoilerplateLiterals(ZoneList<Expression*>* values,
                                                  Handle<FixedArray> literals,
                                                  bool* is_simple,
                                                  int* depth) {
  // Fill in the literals.
  // Accumulate output values in local variables.
  bool is_simple_acc = true;
  int depth_acc = 1;
  for (int i = 0; i < values->length(); i++) {
    MaterializedLiteral* m_literal = values->at(i)->AsMaterializedLiteral();
    if (m_literal != NULL && m_literal->depth() >= depth_acc) {
      depth_acc = m_literal->depth() + 1;
    }
    Handle<Object> boilerplate_value = GetBoilerplateValue(values->at(i));
    if (boilerplate_value->IsUndefined()) {
      literals->set_the_hole(i);
      is_simple_acc = false;
    } else {
      literals->set(i, *boilerplate_value);
    }
  }

  *is_simple = is_simple_acc;
  *depth = depth_acc;
}


2868 2869 2870 2871
Expression* Parser::ParseArrayLiteral(bool* ok) {
  // ArrayLiteral ::
  //   '[' Expression? (',' Expression?)* ']'

2872
  ZoneList<Expression*>* values = new ZoneList<Expression*>(4);
2873 2874 2875 2876 2877 2878 2879 2880
  Expect(Token::LBRACK, CHECK_OK);
  while (peek() != Token::RBRACK) {
    Expression* elem;
    if (peek() == Token::COMMA) {
      elem = GetLiteralTheHole();
    } else {
      elem = ParseAssignmentExpression(true, CHECK_OK);
    }
2881
    values->Add(elem);
2882 2883 2884 2885 2886
    if (peek() != Token::RBRACK) {
      Expect(Token::COMMA, CHECK_OK);
    }
  }
  Expect(Token::RBRACK, CHECK_OK);
2887 2888

  // Update the scope information before the pre-parsing bailout.
2889
  int literal_index = temp_scope_->NextMaterializedLiteralIndex();
2890

2891 2892
  // Allocate a fixed array with all the literals.
  Handle<FixedArray> literals =
2893
      Factory::NewFixedArray(values->length(), TENURED);
2894 2895

  // Fill in the literals.
2896 2897
  bool is_simple = true;
  int depth = 1;
2898 2899
  for (int i = 0, n = values->length(); i < n; i++) {
    MaterializedLiteral* m_literal = values->at(i)->AsMaterializedLiteral();
2900 2901 2902
    if (m_literal != NULL && m_literal->depth() + 1 > depth) {
      depth = m_literal->depth() + 1;
    }
2903
    Handle<Object> boilerplate_value = GetBoilerplateValue(values->at(i));
2904
    if (boilerplate_value->IsUndefined()) {
2905
      literals->set_the_hole(i);
2906
      is_simple = false;
2907
    } else {
2908
      literals->set(i, *boilerplate_value);
2909 2910 2911
    }
  }

2912 2913
  // Simple and shallow arrays can be lazily copied, we transform the
  // elements array to a copy-on-write array.
2914
  if (is_simple && depth == 1 && values->length() > 0) {
2915 2916 2917
    literals->set_map(Heap::fixed_cow_array_map());
  }

2918 2919
  return new ArrayLiteral(literals, values,
                          literal_index, is_simple, depth);
2920 2921 2922
}


2923 2924 2925 2926 2927 2928
bool Parser::IsBoilerplateProperty(ObjectLiteral::Property* property) {
  return property != NULL &&
         property->kind() != ObjectLiteral::Property::PROTOTYPE;
}


2929 2930 2931 2932 2933
bool CompileTimeValue::IsCompileTimeValue(Expression* expression) {
  MaterializedLiteral* lit = expression->AsMaterializedLiteral();
  return lit != NULL && lit->is_simple();
}

2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946

bool CompileTimeValue::ArrayLiteralElementNeedsInitialization(
    Expression* value) {
  // If value is a literal the property value is already set in the
  // boilerplate object.
  if (value->AsLiteral() != NULL) return false;
  // If value is a materialized literal the property value is already set
  // in the boilerplate object if it is simple.
  if (CompileTimeValue::IsCompileTimeValue(value)) return false;
  return true;
}


2947 2948 2949 2950 2951 2952
Handle<FixedArray> CompileTimeValue::GetValue(Expression* expression) {
  ASSERT(IsCompileTimeValue(expression));
  Handle<FixedArray> result = Factory::NewFixedArray(2, TENURED);
  ObjectLiteral* object_literal = expression->AsObjectLiteral();
  if (object_literal != NULL) {
    ASSERT(object_literal->is_simple());
2953 2954 2955 2956 2957
    if (object_literal->fast_elements()) {
      result->set(kTypeSlot, Smi::FromInt(OBJECT_LITERAL_FAST_ELEMENTS));
    } else {
      result->set(kTypeSlot, Smi::FromInt(OBJECT_LITERAL_SLOW_ELEMENTS));
    }
2958 2959 2960 2961 2962
    result->set(kElementsSlot, *object_literal->constant_properties());
  } else {
    ArrayLiteral* array_literal = expression->AsArrayLiteral();
    ASSERT(array_literal != NULL && array_literal->is_simple());
    result->set(kTypeSlot, Smi::FromInt(ARRAY_LITERAL));
2963
    result->set(kElementsSlot, *array_literal->constant_elements());
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
  }
  return result;
}


CompileTimeValue::Type CompileTimeValue::GetType(Handle<FixedArray> value) {
  Smi* type_value = Smi::cast(value->get(kTypeSlot));
  return static_cast<Type>(type_value->value());
}


Handle<FixedArray> CompileTimeValue::GetElements(Handle<FixedArray> value) {
  return Handle<FixedArray>(FixedArray::cast(value->get(kElementsSlot)));
}


Handle<Object> Parser::GetBoilerplateValue(Expression* expression) {
  if (expression->AsLiteral() != NULL) {
    return expression->AsLiteral()->handle();
  }
  if (CompileTimeValue::IsCompileTimeValue(expression)) {
    return CompileTimeValue::GetValue(expression);
  }
  return Factory::undefined_value();
2988 2989 2990
}


2991 2992 2993 2994
void Parser::BuildObjectLiteralConstantProperties(
    ZoneList<ObjectLiteral::Property*>* properties,
    Handle<FixedArray> constant_properties,
    bool* is_simple,
2995
    bool* fast_elements,
2996 2997 2998 2999 3000
    int* depth) {
  int position = 0;
  // Accumulate the value in local variables and store it at the end.
  bool is_simple_acc = true;
  int depth_acc = 1;
3001 3002
  uint32_t max_element_index = 0;
  uint32_t elements = 0;
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
  for (int i = 0; i < properties->length(); i++) {
    ObjectLiteral::Property* property = properties->at(i);
    if (!IsBoilerplateProperty(property)) {
      is_simple_acc = false;
      continue;
    }
    MaterializedLiteral* m_literal = property->value()->AsMaterializedLiteral();
    if (m_literal != NULL && m_literal->depth() >= depth_acc) {
      depth_acc = m_literal->depth() + 1;
    }

    // Add CONSTANT and COMPUTED properties to boilerplate. Use undefined
    // value for COMPUTED properties, the real value is filled in at
    // runtime. The enumeration order is maintained.
    Handle<Object> key = property->key()->handle();
    Handle<Object> value = GetBoilerplateValue(property->value());
    is_simple_acc = is_simple_acc && !value->IsUndefined();

3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
    // Keep track of the number of elements in the object literal and
    // the largest element index.  If the largest element index is
    // much larger than the number of elements, creating an object
    // literal with fast elements will be a waste of space.
    uint32_t element_index = 0;
    if (key->IsString()
        && Handle<String>::cast(key)->AsArrayIndex(&element_index)
        && element_index > max_element_index) {
      max_element_index = element_index;
      elements++;
    } else if (key->IsSmi()) {
      int key_value = Smi::cast(*key)->value();
      if (key_value > 0
          && static_cast<uint32_t>(key_value) > max_element_index) {
        max_element_index = key_value;
      }
      elements++;
    }

3040 3041 3042 3043
    // Add name, value pair to the fixed array.
    constant_properties->set(position++, *key);
    constant_properties->set(position++, *value);
  }
3044 3045
  *fast_elements =
      (max_element_index <= 32) || ((2 * elements) >= max_element_index);
3046 3047 3048 3049 3050
  *is_simple = is_simple_acc;
  *depth = depth_acc;
}


3051 3052 3053 3054 3055 3056
ObjectLiteral::Property* Parser::ParseObjectLiteralGetSet(bool is_getter,
                                                          bool* ok) {
  // Special handling of getter and setter syntax:
  // { ... , get foo() { ... }, ... , set foo(v) { ... v ... } , ... }
  // We have already read the "get" or "set" keyword.
  Token::Value next = Next();
3057 3058
  // TODO(820): Allow NUMBER and STRING as well (and handle array indices).
  if (next == Token::IDENTIFIER || Token::IsKeyword(next)) {
3059
    Handle<String> name = GetSymbol(CHECK_OK);
3060 3061 3062 3063 3064 3065
    FunctionLiteral* value =
        ParseFunctionLiteral(name,
                             RelocInfo::kNoPosition,
                             DECLARATION,
                             CHECK_OK);
    ObjectLiteral::Property* property =
3066
        new ObjectLiteral::Property(is_getter, value);
3067 3068 3069 3070 3071 3072 3073 3074 3075
    return property;
  } else {
    ReportUnexpectedToken(next);
    *ok = false;
    return NULL;
  }
}


3076 3077 3078
Expression* Parser::ParseObjectLiteral(bool* ok) {
  // ObjectLiteral ::
  //   '{' (
3079 3080
  //       ((IdentifierName | String | Number) ':' AssignmentExpression)
  //     | (('get' | 'set') (IdentifierName | String | Number) FunctionLiteral)
3081 3082
  //    )*[','] '}'

3083 3084
  ZoneList<ObjectLiteral::Property*>* properties =
      new ZoneList<ObjectLiteral::Property*>(4);
feng@chromium.org's avatar
feng@chromium.org committed
3085
  int number_of_boilerplate_properties = 0;
3086 3087 3088

  Expect(Token::LBRACE, CHECK_OK);
  while (peek() != Token::RBRACE) {
3089 3090
    if (fni_ != NULL) fni_->Enter();

3091
    Literal* key = NULL;
3092 3093
    Token::Value next = peek();
    switch (next) {
3094 3095 3096 3097 3098
      case Token::IDENTIFIER: {
        bool is_getter = false;
        bool is_setter = false;
        Handle<String> id =
            ParseIdentifierOrGetOrSet(&is_getter, &is_setter, CHECK_OK);
3099 3100
        if (fni_ != NULL) fni_->PushLiteralName(id);

3101
        if ((is_getter || is_setter) && peek() != Token::COLON) {
3102
            ObjectLiteral::Property* property =
3103
                ParseObjectLiteralGetSet(is_getter, CHECK_OK);
3104
            if (IsBoilerplateProperty(property)) {
3105
              number_of_boilerplate_properties++;
3106
            }
3107
            properties->Add(property);
3108
            if (peek() != Token::RBRACE) Expect(Token::COMMA, CHECK_OK);
3109 3110 3111 3112 3113

            if (fni_ != NULL) {
              fni_->Infer();
              fni_->Leave();
            }
3114 3115
            continue;  // restart the while
        }
3116 3117
        // Failed to parse as get/set property, so it's just a property
        // called "get" or "set".
3118
        key = new Literal(id);
3119 3120 3121
        break;
      }
      case Token::STRING: {
3122
        Consume(Token::STRING);
3123
        Handle<String> string = GetSymbol(CHECK_OK);
3124
        if (fni_ != NULL) fni_->PushLiteralName(string);
3125
        uint32_t index;
3126
        if (!string.is_null() && string->AsArrayIndex(&index)) {
3127
          key = NewNumberLiteral(index);
3128
          break;
3129
        }
3130
        key = new Literal(string);
3131 3132 3133 3134 3135
        break;
      }
      case Token::NUMBER: {
        Consume(Token::NUMBER);
        double value =
3136
          StringToDouble(scanner_.literal(), ALLOW_HEX | ALLOW_OCTALS);
3137 3138 3139 3140
        key = NewNumberLiteral(value);
        break;
      }
      default:
3141 3142
        if (Token::IsKeyword(next)) {
          Consume(next);
3143
          Handle<String> string = GetSymbol(CHECK_OK);
3144
          key = new Literal(string);
3145 3146 3147 3148 3149 3150 3151
        } else {
          // Unexpected token.
          Token::Value next = Next();
          ReportUnexpectedToken(next);
          *ok = false;
          return NULL;
        }
3152 3153 3154 3155 3156 3157
    }

    Expect(Token::COLON, CHECK_OK);
    Expression* value = ParseAssignmentExpression(true, CHECK_OK);

    ObjectLiteral::Property* property =
3158
        new ObjectLiteral::Property(key, value);
sgjesse's avatar
sgjesse committed
3159

feng@chromium.org's avatar
feng@chromium.org committed
3160
    // Count CONSTANT or COMPUTED properties to maintain the enumeration order.
3161
    if (IsBoilerplateProperty(property)) number_of_boilerplate_properties++;
3162
    properties->Add(property);
3163 3164 3165

    // TODO(1240767): Consider allowing trailing comma.
    if (peek() != Token::RBRACE) Expect(Token::COMMA, CHECK_OK);
3166 3167 3168 3169 3170

    if (fni_ != NULL) {
      fni_->Infer();
      fni_->Leave();
    }
3171 3172 3173 3174 3175
  }
  Expect(Token::RBRACE, CHECK_OK);
  // Computation of literal_index must happen before pre parse bailout.
  int literal_index = temp_scope_->NextMaterializedLiteralIndex();

3176
  Handle<FixedArray> constant_properties =
feng@chromium.org's avatar
feng@chromium.org committed
3177
      Factory::NewFixedArray(number_of_boilerplate_properties * 2, TENURED);
3178

3179
  bool is_simple = true;
3180
  bool fast_elements = true;
3181
  int depth = 1;
3182
  BuildObjectLiteralConstantProperties(properties,
3183 3184
                                       constant_properties,
                                       &is_simple,
3185
                                       &fast_elements,
3186
                                       &depth);
3187
  return new ObjectLiteral(constant_properties,
3188
                           properties,
3189 3190
                           literal_index,
                           is_simple,
3191
                           fast_elements,
3192
                           depth);
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
}


Expression* Parser::ParseRegExpLiteral(bool seen_equal, bool* ok) {
  if (!scanner_.ScanRegExpPattern(seen_equal)) {
    Next();
    ReportMessage("unterminated_regexp", Vector<const char*>::empty());
    *ok = false;
    return NULL;
  }

  int literal_index = temp_scope_->NextMaterializedLiteralIndex();

  Handle<String> js_pattern =
      Factory::NewStringFromUtf8(scanner_.next_literal(), TENURED);
  scanner_.ScanRegExpFlags();
  Handle<String> js_flags =
      Factory::NewStringFromUtf8(scanner_.next_literal(), TENURED);
  Next();

  return new RegExpLiteral(js_pattern, js_flags, literal_index);
}


ZoneList<Expression*>* Parser::ParseArguments(bool* ok) {
  // Arguments ::
  //   '(' (AssignmentExpression)*[','] ')'

3221
  ZoneList<Expression*>* result = new ZoneList<Expression*>(4);
3222 3223 3224 3225
  Expect(Token::LPAREN, CHECK_OK);
  bool done = (peek() == Token::RPAREN);
  while (!done) {
    Expression* argument = ParseAssignmentExpression(true, CHECK_OK);
3226
    result->Add(argument);
3227 3228 3229 3230
    done = (peek() == Token::RPAREN);
    if (!done) Expect(Token::COMMA, CHECK_OK);
  }
  Expect(Token::RPAREN, CHECK_OK);
3231
  return result;
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
}


FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> var_name,
                                              int function_token_position,
                                              FunctionLiteralType type,
                                              bool* ok) {
  // Function ::
  //   '(' FormalParameterList? ')' '{' FunctionBody '}'
  bool is_named = !var_name.is_null();

  // The name associated with this function. If it's a function expression,
  // this is the actual function name, otherwise this is the name of the
  // variable declared and initialized with the function (expression). In
  // that case, we don't have a function name (it's empty).
3247
  Handle<String> name = is_named ? var_name : Factory::empty_symbol();
3248
  // The function name, if any.
3249
  Handle<String> function_name = Factory::empty_symbol();
3250 3251 3252 3253 3254 3255
  if (is_named && (type == EXPRESSION || type == NESTED)) {
    function_name = name;
  }

  int num_parameters = 0;
  // Parse function body.
3256
  { Scope* scope =
3257
        NewScope(top_scope_, Scope::FUNCTION_SCOPE, inside_with());
3258 3259 3260
    LexicalScope lexical_scope(&this->top_scope_, &this->with_nesting_level_,
                               scope);
    TemporaryScope temp_scope(&this->temp_scope_);
3261 3262 3263 3264 3265 3266 3267 3268 3269
    top_scope_->SetScopeName(name);

    //  FormalParameterList ::
    //    '(' (Identifier)*[','] ')'
    Expect(Token::LPAREN, CHECK_OK);
    int start_pos = scanner_.location().beg_pos;
    bool done = (peek() == Token::RPAREN);
    while (!done) {
      Handle<String> param_name = ParseIdentifier(CHECK_OK);
3270 3271 3272
      top_scope_->AddParameter(top_scope_->DeclareLocal(param_name,
                                                        Variable::VAR));
      num_parameters++;
3273 3274 3275 3276 3277 3278
      done = (peek() == Token::RPAREN);
      if (!done) Expect(Token::COMMA, CHECK_OK);
    }
    Expect(Token::RPAREN, CHECK_OK);

    Expect(Token::LBRACE, CHECK_OK);
3279
    ZoneList<Statement*>* body = new ZoneList<Statement*>(8);
3280 3281 3282 3283 3284 3285 3286

    // If we have a named function expression, we add a local variable
    // declaration to the body of the function with the name of the
    // function and let it refer to the function itself (closure).
    // NOTE: We create a proxy and resolve it here so that in the
    // future we can change the AST to only refer to VariableProxies
    // instead of Variables and Proxis as is the case now.
3287
    if (!function_name.is_null() && function_name->length() > 0) {
3288 3289 3290 3291
      Variable* fvar = top_scope_->DeclareFunctionVar(function_name);
      VariableProxy* fproxy =
          top_scope_->NewUnresolved(function_name, inside_with());
      fproxy->BindTo(fvar);
3292 3293 3294 3295
      body->Add(new ExpressionStatement(
                    new Assignment(Token::INIT_CONST, fproxy,
                                   new ThisFunction(),
                                   RelocInfo::kNoPosition)));
3296 3297 3298 3299 3300 3301 3302
    }

    // Determine if the function will be lazily compiled. The mode can
    // only be PARSE_LAZILY if the --lazy flag is true.
    bool is_lazily_compiled =
        mode() == PARSE_LAZILY && top_scope_->HasTrivialOuterContext();

3303
    int function_block_pos = scanner_.location().beg_pos;
3304 3305
    int materialized_literal_count;
    int expected_property_count;
3306
    int end_pos;
3307 3308
    bool only_simple_this_property_assignments;
    Handle<FixedArray> this_property_assignments;
3309
    if (is_lazily_compiled && pre_data() != NULL) {
3310
      FunctionEntry entry = pre_data()->GetFunctionEntry(function_block_pos);
3311 3312 3313
      if (!entry.is_valid()) {
        ReportInvalidPreparseData(name, CHECK_OK);
      }
3314 3315
      end_pos = entry.end_pos();
      if (end_pos <= function_block_pos) {
3316 3317 3318
        // End position greater than end of stream is safe, and hard to check.
        ReportInvalidPreparseData(name, CHECK_OK);
      }
3319
      Counters::total_preparse_skipped.Increment(end_pos - function_block_pos);
3320 3321 3322
      scanner_.SeekForward(end_pos);
      materialized_literal_count = entry.literal_count();
      expected_property_count = entry.property_count();
3323 3324
      only_simple_this_property_assignments = false;
      this_property_assignments = Factory::empty_fixed_array();
3325
      Expect(Token::RBRACE, CHECK_OK);
3326
    } else {
3327 3328
      ParseSourceElements(body, Token::RBRACE, CHECK_OK);

3329 3330
      materialized_literal_count = temp_scope.materialized_literal_count();
      expected_property_count = temp_scope.expected_property_count();
3331 3332 3333
      only_simple_this_property_assignments =
          temp_scope.only_simple_this_property_assignments();
      this_property_assignments = temp_scope.this_property_assignments();
3334

3335 3336
      Expect(Token::RBRACE, CHECK_OK);
      end_pos = scanner_.location().end_pos;
3337 3338
    }

3339
    FunctionLiteral* function_literal =
3340
        new FunctionLiteral(name,
3341
                            top_scope_,
3342
                            body,
3343 3344 3345 3346 3347 3348 3349
                            materialized_literal_count,
                            expected_property_count,
                            only_simple_this_property_assignments,
                            this_property_assignments,
                            num_parameters,
                            start_pos,
                            end_pos,
3350
                            function_name->length() > 0,
3351 3352
                            temp_scope.ContainsLoops());
    function_literal->set_function_token_position(function_token_position);
3353

3354
    if (fni_ != NULL && !is_named) fni_->AddFunction(function_literal);
3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
    return function_literal;
  }
}


Expression* Parser::ParseV8Intrinsic(bool* ok) {
  // CallRuntime ::
  //   '%' Identifier Arguments

  Expect(Token::MOD, CHECK_OK);
  Handle<String> name = ParseIdentifier(CHECK_OK);
  ZoneList<Expression*>* args = ParseArguments(CHECK_OK);
3367 3368

  if (extension_ != NULL) {
3369 3370 3371 3372 3373
    // The extension structures are only accessible while parsing the
    // very first time not when reparsing because of lazy compilation.
    top_scope_->ForceEagerCompilation();
  }

3374
  Runtime::Function* function = Runtime::FunctionForSymbol(name);
3375

3376 3377 3378 3379 3380 3381 3382 3383 3384 3385
  // Check for built-in IS_VAR macro.
  if (function != NULL &&
      function->intrinsic_type == Runtime::RUNTIME &&
      function->function_id == Runtime::kIS_VAR) {
    // %IS_VAR(x) evaluates to x if x is a variable,
    // leads to a parse error otherwise.  Could be implemented as an
    // inline function %_IS_VAR(x) to eliminate this special case.
    if (args->length() == 1 && args->at(0)->AsVariableProxy() != NULL) {
      return args->at(0);
    } else {
3386
      ReportMessage("unable_to_parse", Vector<const char*>::empty());
3387
      *ok = false;
3388 3389 3390 3391
      return NULL;
    }
  }

3392 3393 3394 3395 3396 3397 3398
  // Check that the expected number of arguments are being passed.
  if (function != NULL &&
      function->nargs != -1 &&
      function->nargs != args->length()) {
    ReportMessage("illegal_access", Vector<const char*>::empty());
    *ok = false;
    return NULL;
3399 3400
  }

3401
  // We have a valid intrinsics call or a call to a builtin.
3402
  return new CallRuntime(name, function, args);
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
}


void Parser::Consume(Token::Value token) {
  Token::Value next = Next();
  USE(next);
  USE(token);
  ASSERT(next == token);
}


void Parser::Expect(Token::Value token, bool* ok) {
  Token::Value next = Next();
  if (next == token) return;
  ReportUnexpectedToken(next);
  *ok = false;
}


3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
bool Parser::Check(Token::Value token) {
  Token::Value next = peek();
  if (next == token) {
    Consume(next);
    return true;
  }
  return false;
}


3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
void Parser::ExpectSemicolon(bool* ok) {
  // Check for automatic semicolon insertion according to
  // the rules given in ECMA-262, section 7.9, page 21.
  Token::Value tok = peek();
  if (tok == Token::SEMICOLON) {
    Next();
    return;
  }
  if (scanner_.has_line_terminator_before_next() ||
      tok == Token::RBRACE ||
      tok == Token::EOS) {
    return;
  }
  Expect(Token::SEMICOLON, ok);
}


Literal* Parser::GetLiteralUndefined() {
3450
  return new Literal(Factory::undefined_value());
3451 3452 3453 3454
}


Literal* Parser::GetLiteralTheHole() {
3455
  return new Literal(Factory::the_hole_value());
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466
}


Literal* Parser::GetLiteralNumber(double value) {
  return NewNumberLiteral(value);
}


Handle<String> Parser::ParseIdentifier(bool* ok) {
  Expect(Token::IDENTIFIER, ok);
  if (!*ok) return Handle<String>();
3467
  return GetSymbol(ok);
3468 3469
}

3470 3471 3472 3473 3474 3475 3476 3477

Handle<String> Parser::ParseIdentifierName(bool* ok) {
  Token::Value next = Next();
  if (next != Token::IDENTIFIER && !Token::IsKeyword(next)) {
    ReportUnexpectedToken(next);
    *ok = false;
    return Handle<String>();
  }
3478
  return GetSymbol(ok);
3479 3480 3481
}


3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
// This function reads an identifier and determines whether or not it
// is 'get' or 'set'.  The reason for not using ParseIdentifier and
// checking on the output is that this involves heap allocation which
// we can't do during preparsing.
Handle<String> Parser::ParseIdentifierOrGetOrSet(bool* is_get,
                                                 bool* is_set,
                                                 bool* ok) {
  Expect(Token::IDENTIFIER, ok);
  if (!*ok) return Handle<String>();
  if (scanner_.literal_length() == 3) {
    const char* token = scanner_.literal_string();
    *is_get = strcmp(token, "get") == 0;
    *is_set = !*is_get && strcmp(token, "set") == 0;
  }
3496
  return GetSymbol(ok);
3497 3498 3499 3500 3501 3502 3503 3504
}


// ----------------------------------------------------------------------------
// Parser support


bool Parser::TargetStackContainsLabel(Handle<String> label) {
bak@chromium.org's avatar
bak@chromium.org committed
3505 3506
  for (Target* t = target_stack_; t != NULL; t = t->previous()) {
    BreakableStatement* stat = t->node()->AsBreakableStatement();
3507 3508 3509 3510 3511 3512 3513 3514 3515
    if (stat != NULL && ContainsLabel(stat->labels(), label))
      return true;
  }
  return false;
}


BreakableStatement* Parser::LookupBreakTarget(Handle<String> label, bool* ok) {
  bool anonymous = label.is_null();
bak@chromium.org's avatar
bak@chromium.org committed
3516 3517
  for (Target* t = target_stack_; t != NULL; t = t->previous()) {
    BreakableStatement* stat = t->node()->AsBreakableStatement();
3518 3519 3520
    if (stat == NULL) continue;
    if ((anonymous && stat->is_target_for_anonymous()) ||
        (!anonymous && ContainsLabel(stat->labels(), label))) {
bak@chromium.org's avatar
bak@chromium.org committed
3521
      RegisterTargetUse(stat->break_target(), t->previous());
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
      return stat;
    }
  }
  return NULL;
}


IterationStatement* Parser::LookupContinueTarget(Handle<String> label,
                                                 bool* ok) {
  bool anonymous = label.is_null();
bak@chromium.org's avatar
bak@chromium.org committed
3532 3533
  for (Target* t = target_stack_; t != NULL; t = t->previous()) {
    IterationStatement* stat = t->node()->AsIterationStatement();
3534 3535 3536 3537
    if (stat == NULL) continue;

    ASSERT(stat->is_target_for_anonymous());
    if (anonymous || ContainsLabel(stat->labels(), label)) {
bak@chromium.org's avatar
bak@chromium.org committed
3538
      RegisterTargetUse(stat->continue_target(), t->previous());
3539 3540 3541 3542 3543 3544 3545
      return stat;
    }
  }
  return NULL;
}


bak@chromium.org's avatar
bak@chromium.org committed
3546 3547
void Parser::RegisterTargetUse(BreakTarget* target, Target* stop) {
  // Register that a break target found at the given stop in the
3548 3549
  // target stack has been used from the top of the target stack. Add
  // the break target to any TargetCollectors passed on the stack.
bak@chromium.org's avatar
bak@chromium.org committed
3550 3551
  for (Target* t = target_stack_; t != stop; t = t->previous()) {
    TargetCollector* collector = t->node()->AsTargetCollector();
3552
    if (collector != NULL) collector->AddTarget(target);
3553 3554 3555 3556 3557
  }
}


Literal* Parser::NewNumberLiteral(double number) {
3558
  return new Literal(Factory::NewNumber(number, TENURED));
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595
}


Expression* Parser::NewThrowReferenceError(Handle<String> type) {
  return NewThrowError(Factory::MakeReferenceError_symbol(),
                       type, HandleVector<Object>(NULL, 0));
}


Expression* Parser::NewThrowSyntaxError(Handle<String> type,
                                        Handle<Object> first) {
  int argc = first.is_null() ? 0 : 1;
  Vector< Handle<Object> > arguments = HandleVector<Object>(&first, argc);
  return NewThrowError(Factory::MakeSyntaxError_symbol(), type, arguments);
}


Expression* Parser::NewThrowTypeError(Handle<String> type,
                                      Handle<Object> first,
                                      Handle<Object> second) {
  ASSERT(!first.is_null() && !second.is_null());
  Handle<Object> elements[] = { first, second };
  Vector< Handle<Object> > arguments =
      HandleVector<Object>(elements, ARRAY_SIZE(elements));
  return NewThrowError(Factory::MakeTypeError_symbol(), type, arguments);
}


Expression* Parser::NewThrowError(Handle<String> constructor,
                                  Handle<String> type,
                                  Vector< Handle<Object> > arguments) {
  int argc = arguments.length();
  Handle<JSArray> array = Factory::NewJSArray(argc, TENURED);
  ASSERT(array->IsJSArray() && array->HasFastElements());
  for (int i = 0; i < argc; i++) {
    Handle<Object> element = arguments[i];
    if (!element.is_null()) {
3596 3597
      // We know this doesn't cause a GC here because we allocated the JSArray
      // large enough.
3598
      array->SetFastElement(i, *element)->ToObjectUnchecked();
3599 3600 3601 3602 3603 3604 3605 3606 3607
    }
  }
  ZoneList<Expression*>* args = new ZoneList<Expression*>(2);
  args->Add(new Literal(type));
  args->Add(new Literal(array));
  return new Throw(new CallRuntime(constructor, NULL, args),
                   scanner().location().beg_pos);
}

3608 3609 3610
// ----------------------------------------------------------------------------
// JSON

3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
Handle<Object> JsonParser::ParseJson(Handle<String> source) {
  source->TryFlatten();
  scanner_.Initialize(source, JSON);
  Handle<Object> result = ParseJsonValue();
  if (result.is_null() || scanner_.Next() != Token::EOS) {
    if (scanner_.stack_overflow()) {
      // Scanner failed.
      Top::StackOverflow();
    } else {
      // Parse failed. Scanner's current token is the unexpected token.
      Token::Value token = scanner_.current_token();

      const char* message;
      const char* name_opt = NULL;

      switch (token) {
        case Token::EOS:
          message = "unexpected_eos";
          break;
        case Token::NUMBER:
          message = "unexpected_token_number";
          break;
        case Token::STRING:
          message = "unexpected_token_string";
          break;
        case Token::IDENTIFIER:
          message = "unexpected_token_identifier";
          break;
        default:
          message = "unexpected_token";
          name_opt = Token::String(token);
          ASSERT(name_opt != NULL);
          break;
      }

      Scanner::Location source_location = scanner_.location();
      MessageLocation location(Factory::NewScript(source),
                               source_location.beg_pos,
                               source_location.end_pos);
      int argc = (name_opt == NULL) ? 0 : 1;
      Handle<JSArray> array = Factory::NewJSArray(argc);
      if (name_opt != NULL) {
        SetElement(array,
                   0,
                   Factory::NewStringFromUtf8(CStrVector(name_opt)));
      }
      Handle<Object> result = Factory::NewSyntaxError(message, array);
      Top::Throw(*result, &location);
      return Handle<Object>::null();
    }
  }
3662 3663 3664 3665
  return result;
}


3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
Handle<String> JsonParser::GetString() {
  int literal_length = scanner_.literal_length();
  if (literal_length == 0) {
    return Factory::empty_string();
  }
  const char* literal_string = scanner_.literal_string();
  Vector<const char> literal(literal_string, literal_length);
  return Factory::NewStringFromUtf8(literal);
}


3677
// Parse any JSON value.
3678 3679
Handle<Object> JsonParser::ParseJsonValue() {
  Token::Value token = scanner_.Next();
3680 3681
  switch (token) {
    case Token::STRING: {
3682
      return GetString();
3683 3684
    }
    case Token::NUMBER: {
3685
      double value = StringToDouble(scanner_.literal(),
3686 3687
                                    NO_FLAGS,  // Hex, octal or trailing junk.
                                    OS::nan_value());
3688
      return Factory::NewNumber(value);
3689 3690
    }
    case Token::FALSE_LITERAL:
3691
      return Factory::false_value();
3692
    case Token::TRUE_LITERAL:
3693
      return Factory::true_value();
3694
    case Token::NULL_LITERAL:
3695 3696 3697 3698 3699
      return Factory::null_value();
    case Token::LBRACE:
      return ParseJsonObject();
    case Token::LBRACK:
      return ParseJsonArray();
3700
    default:
3701
      return ReportUnexpectedToken();
3702 3703 3704 3705 3706
  }
}


// Parse a JSON object. Scanner must be right after '{' token.
3707 3708 3709 3710 3711 3712 3713
Handle<Object> JsonParser::ParseJsonObject() {
  Handle<JSFunction> object_constructor(
      Top::global_context()->object_function());
  Handle<JSObject> json_object = Factory::NewJSObject(object_constructor);
  if (scanner_.peek() == Token::RBRACE) {
    scanner_.Next();
  } else {
3714
    do {
3715 3716 3717 3718 3719 3720 3721 3722 3723
      if (scanner_.Next() != Token::STRING) {
        return ReportUnexpectedToken();
      }
      Handle<String> key = GetString();
      if (scanner_.Next() != Token::COLON) {
        return ReportUnexpectedToken();
      }
      Handle<Object> value = ParseJsonValue();
      if (value.is_null()) return Handle<Object>::null();
3724 3725
      uint32_t index;
      if (key->AsArrayIndex(&index)) {
3726
        SetElement(json_object, index, value);
3727
      } else {
3728
        SetProperty(json_object, key, value, NONE);
3729
      }
3730 3731 3732 3733
    } while (scanner_.Next() == Token::COMMA);
    if (scanner_.current_token() != Token::RBRACE) {
      return ReportUnexpectedToken();
    }
3734
  }
3735
  return json_object;
3736 3737 3738 3739
}


// Parse a JSON array. Scanner must be right after '[' token.
3740 3741 3742
Handle<Object> JsonParser::ParseJsonArray() {
  ZoneScope zone_scope(DELETE_ON_EXIT);
  ZoneList<Handle<Object> > elements(4);
3743

3744 3745 3746 3747
  Token::Value token = scanner_.peek();
  if (token == Token::RBRACK) {
    scanner_.Next();
  } else {
3748
    do {
3749 3750 3751 3752 3753 3754 3755 3756
      Handle<Object> element = ParseJsonValue();
      if (element.is_null()) return Handle<Object>::null();
      elements.Add(element);
      token = scanner_.Next();
    } while (token == Token::COMMA);
    if (token != Token::RBRACK) {
      return ReportUnexpectedToken();
    }
3757 3758
  }

3759 3760 3761
  // Allocate a fixed array with all the elements.
  Handle<FixedArray> fast_elements =
      Factory::NewFixedArray(elements.length());
3762

3763 3764 3765
  for (int i = 0, n = elements.length(); i < n; i++) {
    fast_elements->set(i, *elements[i]);
  }
3766

3767
  return Factory::NewJSArrayWithElements(fast_elements);
3768 3769
}

3770 3771 3772 3773 3774 3775
// ----------------------------------------------------------------------------
// Regular expressions


RegExpParser::RegExpParser(FlatStringReader* in,
                           Handle<String>* error,
3776
                           bool multiline)
3777 3778 3779 3780 3781 3782
  : error_(error),
    captures_(NULL),
    in_(in),
    current_(kEndMarker),
    next_pos_(0),
    capture_count_(0),
3783
    has_more_(true),
3784
    multiline_(multiline),
3785
    simple_(false),
3786
    contains_anchor_(false),
3787
    is_scanned_for_captures_(false),
3788
    failed_(false) {
3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
  Advance(1);
}


uc32 RegExpParser::Next() {
  if (has_next()) {
    return in()->Get(next_pos_);
  } else {
    return kEndMarker;
  }
}


void RegExpParser::Advance() {
  if (next_pos_ < in()->length()) {
3804 3805 3806 3807 3808 3809 3810 3811 3812
    StackLimitCheck check;
    if (check.HasOverflowed()) {
      ReportError(CStrVector(Top::kStackOverflowMessage));
    } else if (Zone::excess_allocation()) {
      ReportError(CStrVector("Regular expression too large"));
    } else {
      current_ = in()->Get(next_pos_);
      next_pos_++;
    }
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
  } else {
    current_ = kEndMarker;
    has_more_ = false;
  }
}


void RegExpParser::Reset(int pos) {
  next_pos_ = pos;
  Advance();
}


void RegExpParser::Advance(int dist) {
  for (int i = 0; i < dist; i++)
    Advance();
}


3832 3833
bool RegExpParser::simple() {
  return simple_;
3834 3835
}

3836 3837
RegExpTree* RegExpParser::ReportError(Vector<const char> message) {
  failed_ = true;
3838
  *error_ = Factory::NewStringFromAscii(message, NOT_TENURED);
3839 3840 3841
  // Zip to the end to make sure the no more input is read.
  current_ = kEndMarker;
  next_pos_ = in()->length();
3842 3843 3844 3845 3846 3847
  return NULL;
}


// Pattern ::
//   Disjunction
3848 3849
RegExpTree* RegExpParser::ParsePattern() {
  RegExpTree* result = ParseDisjunction(CHECK_FAILED);
3850
  ASSERT(!has_more());
3851 3852 3853 3854 3855
  // If the result of parsing is a literal string atom, and it has the
  // same length as the input, then the atom is identical to the input.
  if (result->IsAtom() && result->AsAtom()->length() == in()->length()) {
    simple_ = true;
  }
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
  return result;
}


// Disjunction ::
//   Alternative
//   Alternative | Disjunction
// Alternative ::
//   [empty]
//   Term Alternative
// Term ::
//   Assertion
//   Atom
//   Atom Quantifier
3870
RegExpTree* RegExpParser::ParseDisjunction() {
3871 3872 3873 3874 3875
  // Used to store current state while parsing subexpressions.
  RegExpParserState initial_state(NULL, INITIAL, 0);
  RegExpParserState* stored_state = &initial_state;
  // Cache the builder in a local variable for quick access.
  RegExpBuilder* builder = initial_state.builder();
3876 3877 3878
  while (true) {
    switch (current()) {
    case kEndMarker:
3879 3880 3881 3882 3883 3884 3885 3886 3887
      if (stored_state->IsSubexpression()) {
        // Inside a parenthesized group when hitting end of input.
        ReportError(CStrVector("Unterminated group") CHECK_FAILED);
      }
      ASSERT_EQ(INITIAL, stored_state->group_type());
      // Parsing completed successfully.
      return builder->ToRegExp();
    case ')': {
      if (!stored_state->IsSubexpression()) {
3888
        ReportError(CStrVector("Unmatched ')'") CHECK_FAILED);
3889 3890 3891
      }
      ASSERT_NE(INITIAL, stored_state->group_type());

3892
      Advance();
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
      // End disjunction parsing and convert builder content to new single
      // regexp atom.
      RegExpTree* body = builder->ToRegExp();

      int end_capture_index = captures_started();

      int capture_index = stored_state->capture_index();
      SubexpressionType type = stored_state->group_type();

      // Restore previous state.
      stored_state = stored_state->previous_state();
      builder = stored_state->builder();

      // Build result of subexpression.
      if (type == CAPTURE) {
        RegExpCapture* capture = new RegExpCapture(body, capture_index);
        captures_->at(capture_index - 1) = capture;
        body = capture;
      } else if (type != GROUPING) {
        ASSERT(type == POSITIVE_LOOKAHEAD || type == NEGATIVE_LOOKAHEAD);
        bool is_positive = (type == POSITIVE_LOOKAHEAD);
        body = new RegExpLookahead(body,
                                   is_positive,
                                   end_capture_index - capture_index,
                                   capture_index);
3918
      }
3919 3920 3921 3922 3923 3924
      builder->AddAtom(body);
      break;
    }
    case '|': {
      Advance();
      builder->NewAlternative();
3925 3926 3927 3928 3929
      continue;
    }
    case '*':
    case '+':
    case '?':
3930
      return ReportError(CStrVector("Nothing to repeat"));
3931 3932
    case '^': {
      Advance();
3933
      if (multiline_) {
3934
        builder->AddAssertion(
3935 3936
            new RegExpAssertion(RegExpAssertion::START_OF_LINE));
      } else {
3937
        builder->AddAssertion(
3938 3939 3940
            new RegExpAssertion(RegExpAssertion::START_OF_INPUT));
        set_contains_anchor();
      }
3941 3942 3943 3944 3945
      continue;
    }
    case '$': {
      Advance();
      RegExpAssertion::Type type =
3946 3947
          multiline_ ? RegExpAssertion::END_OF_LINE :
                       RegExpAssertion::END_OF_INPUT;
3948
      builder->AddAssertion(new RegExpAssertion(type));
3949 3950 3951 3952 3953 3954 3955 3956
      continue;
    }
    case '.': {
      Advance();
      // everything except \x0a, \x0d, \u2028 and \u2029
      ZoneList<CharacterRange>* ranges = new ZoneList<CharacterRange>(2);
      CharacterRange::AddClassEscape('.', ranges);
      RegExpTree* atom = new RegExpCharacterClass(ranges, false);
3957
      builder->AddAtom(atom);
3958 3959 3960
      break;
    }
    case '(': {
3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992
      SubexpressionType type = CAPTURE;
      Advance();
      if (current() == '?') {
        switch (Next()) {
          case ':':
            type = GROUPING;
            break;
          case '=':
            type = POSITIVE_LOOKAHEAD;
            break;
          case '!':
            type = NEGATIVE_LOOKAHEAD;
            break;
          default:
            ReportError(CStrVector("Invalid group") CHECK_FAILED);
            break;
        }
        Advance(2);
      } else {
        if (captures_ == NULL) {
          captures_ = new ZoneList<RegExpCapture*>(2);
        }
        if (captures_started() >= kMaxCaptures) {
          ReportError(CStrVector("Too many captures") CHECK_FAILED);
        }
        captures_->Add(NULL);
      }
      // Store current state and begin new disjunction parsing.
      stored_state = new RegExpParserState(stored_state,
                                           type,
                                           captures_started());
      builder = stored_state->builder();
3993 3994 3995
      break;
    }
    case '[': {
3996
      RegExpTree* atom = ParseCharacterClass(CHECK_FAILED);
3997
      builder->AddAtom(atom);
3998 3999 4000 4001 4002 4003 4004
      break;
    }
    // Atom ::
    //   \ AtomEscape
    case '\\':
      switch (Next()) {
      case kEndMarker:
4005
        return ReportError(CStrVector("\\ at end of pattern"));
4006 4007
      case 'b':
        Advance(2);
4008
        builder->AddAssertion(
4009 4010 4011 4012
            new RegExpAssertion(RegExpAssertion::BOUNDARY));
        continue;
      case 'B':
        Advance(2);
4013
        builder->AddAssertion(
4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
            new RegExpAssertion(RegExpAssertion::NON_BOUNDARY));
        continue;
        // AtomEscape ::
        //   CharacterClassEscape
        //
        // CharacterClassEscape :: one of
        //   d D s S w W
      case 'd': case 'D': case 's': case 'S': case 'w': case 'W': {
        uc32 c = Next();
        Advance(2);
        ZoneList<CharacterRange>* ranges = new ZoneList<CharacterRange>(2);
        CharacterRange::AddClassEscape(c, ranges);
        RegExpTree* atom = new RegExpCharacterClass(ranges, false);
4027
        builder->AddAtom(atom);
4028
        break;
4029 4030 4031 4032 4033
      }
      case '1': case '2': case '3': case '4': case '5': case '6':
      case '7': case '8': case '9': {
        int index = 0;
        if (ParseBackReferenceIndex(&index)) {
4034 4035 4036 4037 4038 4039
          RegExpCapture* capture = NULL;
          if (captures_ != NULL && index <= captures_->length()) {
            capture = captures_->at(index - 1);
          }
          if (capture == NULL) {
            builder->AddEmpty();
4040
            break;
4041 4042
          }
          RegExpTree* atom = new RegExpBackReference(capture);
4043
          builder->AddAtom(atom);
4044
          break;
4045 4046 4047 4048
        }
        uc32 first_digit = Next();
        if (first_digit == '8' || first_digit == '9') {
          // Treat as identity escape
4049
          builder->AddCharacter(first_digit);
4050 4051 4052 4053 4054 4055 4056 4057
          Advance(2);
          break;
        }
      }
      // FALLTHROUGH
      case '0': {
        Advance();
        uc32 octal = ParseOctalLiteral();
4058
        builder->AddCharacter(octal);
4059 4060 4061 4062 4063 4064
        break;
      }
      // ControlEscape :: one of
      //   f n r t v
      case 'f':
        Advance(2);
4065
        builder->AddCharacter('\f');
4066 4067 4068
        break;
      case 'n':
        Advance(2);
4069
        builder->AddCharacter('\n');
4070 4071 4072
        break;
      case 'r':
        Advance(2);
4073
        builder->AddCharacter('\r');
4074 4075 4076
        break;
      case 't':
        Advance(2);
4077
        builder->AddCharacter('\t');
4078 4079 4080
        break;
      case 'v':
        Advance(2);
4081
        builder->AddCharacter('\v');
4082 4083 4084
        break;
      case 'c': {
        Advance(2);
4085
        uc32 control = ParseControlLetterEscape();
4086
        builder->AddCharacter(control);
4087 4088 4089 4090 4091 4092
        break;
      }
      case 'x': {
        Advance(2);
        uc32 value;
        if (ParseHexEscape(2, &value)) {
4093
          builder->AddCharacter(value);
4094
        } else {
4095
          builder->AddCharacter('x');
4096 4097 4098 4099 4100 4101 4102
        }
        break;
      }
      case 'u': {
        Advance(2);
        uc32 value;
        if (ParseHexEscape(4, &value)) {
4103
          builder->AddCharacter(value);
4104
        } else {
4105
          builder->AddCharacter('u');
4106 4107 4108 4109 4110
        }
        break;
      }
      default:
        // Identity escape.
4111
        builder->AddCharacter(Next());
4112 4113 4114 4115 4116 4117 4118
        Advance(2);
        break;
      }
      break;
    case '{': {
      int dummy;
      if (ParseIntervalQuantifier(&dummy, &dummy)) {
4119
        ReportError(CStrVector("Nothing to repeat") CHECK_FAILED);
4120 4121 4122 4123
      }
      // fallthrough
    }
    default:
4124
      builder->AddCharacter(current());
4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
      Advance();
      break;
    }  // end switch(current())

    int min;
    int max;
    switch (current()) {
    // QuantifierPrefix ::
    //   *
    //   +
    //   ?
    //   {
    case '*':
      min = 0;
4139
      max = RegExpTree::kInfinity;
4140 4141 4142 4143
      Advance();
      break;
    case '+':
      min = 1;
4144
      max = RegExpTree::kInfinity;
4145 4146 4147 4148 4149 4150 4151 4152 4153
      Advance();
      break;
    case '?':
      min = 0;
      max = 1;
      Advance();
      break;
    case '{':
      if (ParseIntervalQuantifier(&min, &max)) {
4154 4155 4156 4157
        if (max < min) {
          ReportError(CStrVector("numbers out of order in {} quantifier.")
                      CHECK_FAILED);
        }
4158 4159 4160 4161 4162 4163 4164
        break;
      } else {
        continue;
      }
    default:
      continue;
    }
4165
    RegExpQuantifier::Type type = RegExpQuantifier::GREEDY;
4166
    if (current() == '?') {
4167 4168 4169 4170 4171
      type = RegExpQuantifier::NON_GREEDY;
      Advance();
    } else if (FLAG_regexp_possessive_quantifier && current() == '+') {
      // FLAG_regexp_possessive_quantifier is a debug-only flag.
      type = RegExpQuantifier::POSSESSIVE;
4172 4173
      Advance();
    }
4174
    builder->AddQuantifierToAtom(min, max, type);
4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224
  }
}

class SourceCharacter {
 public:
  static bool Is(uc32 c) {
    switch (c) {
      // case ']': case '}':
      // In spidermonkey and jsc these are treated as source characters
      // so we do too.
      case '^': case '$': case '\\': case '.': case '*': case '+':
      case '?': case '(': case ')': case '[': case '{': case '|':
      case RegExpParser::kEndMarker:
        return false;
      default:
        return true;
    }
  }
};


static unibrow::Predicate<SourceCharacter> source_character;


static inline bool IsSourceCharacter(uc32 c) {
  return source_character.get(c);
}

#ifdef DEBUG
// Currently only used in an ASSERT.
static bool IsSpecialClassEscape(uc32 c) {
  switch (c) {
    case 'd': case 'D':
    case 's': case 'S':
    case 'w': case 'W':
      return true;
    default:
      return false;
  }
}
#endif


// In order to know whether an escape is a backreference or not we have to scan
// the entire regexp and find the number of capturing parentheses.  However we
// don't want to scan the regexp twice unless it is necessary.  This mini-parser
// is called when needed.  It can see the difference between capturing and
// noncapturing parentheses and can skip character classes and backslash-escaped
// characters.
void RegExpParser::ScanForCaptures() {
4225 4226 4227
  // Start with captures started previous to current position
  int capture_count = captures_started();
  // Add count of captures after this position.
4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
  int n;
  while ((n = current()) != kEndMarker) {
    Advance();
    switch (n) {
      case '\\':
        Advance();
        break;
      case '[': {
        int c;
        while ((c = current()) != kEndMarker) {
          Advance();
          if (c == '\\') {
            Advance();
          } else {
            if (c == ']') break;
          }
        }
        break;
      }
      case '(':
4248
        if (current() != '?') capture_count++;
4249 4250 4251
        break;
    }
  }
4252
  capture_count_ = capture_count;
4253 4254 4255 4256 4257 4258 4259
  is_scanned_for_captures_ = true;
}


bool RegExpParser::ParseBackReferenceIndex(int* index_out) {
  ASSERT_EQ('\\', current());
  ASSERT('1' <= Next() && Next() <= '9');
4260 4261
  // Try to parse a decimal literal that is no greater than the total number
  // of left capturing parentheses in the input.
4262 4263 4264 4265 4266 4267 4268
  int start = position();
  int value = Next() - '0';
  Advance(2);
  while (true) {
    uc32 c = current();
    if (IsDecimalDigit(c)) {
      value = 10 * value + (c - '0');
4269 4270 4271 4272
      if (value > kMaxCaptures) {
        Reset(start);
        return false;
      }
4273 4274 4275 4276 4277
      Advance();
    } else {
      break;
    }
  }
4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
  if (value > captures_started()) {
    if (!is_scanned_for_captures_) {
      int saved_position = position();
      ScanForCaptures();
      Reset(saved_position);
    }
    if (value > capture_count_) {
      Reset(start);
      return false;
    }
  }
4289 4290 4291 4292 4293 4294 4295 4296 4297
  *index_out = value;
  return true;
}


// QuantifierPrefix ::
//   { DecimalDigits }
//   { DecimalDigits , }
//   { DecimalDigits , DecimalDigits }
4298 4299 4300
//
// Returns true if parsing succeeds, and set the min_out and max_out
// values. Values are truncated to RegExpTree::kInfinity if they overflow.
4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
bool RegExpParser::ParseIntervalQuantifier(int* min_out, int* max_out) {
  ASSERT_EQ(current(), '{');
  int start = position();
  Advance();
  int min = 0;
  if (!IsDecimalDigit(current())) {
    Reset(start);
    return false;
  }
  while (IsDecimalDigit(current())) {
4311 4312 4313
    int next = current() - '0';
    if (min > (RegExpTree::kInfinity - next) / 10) {
      // Overflow. Skip past remaining decimal digits and return -1.
4314 4315 4316
      do {
        Advance();
      } while (IsDecimalDigit(current()));
4317 4318 4319 4320
      min = RegExpTree::kInfinity;
      break;
    }
    min = 10 * min + next;
4321 4322 4323 4324 4325 4326 4327 4328 4329
    Advance();
  }
  int max = 0;
  if (current() == '}') {
    max = min;
    Advance();
  } else if (current() == ',') {
    Advance();
    if (current() == '}') {
4330
      max = RegExpTree::kInfinity;
4331 4332 4333
      Advance();
    } else {
      while (IsDecimalDigit(current())) {
4334 4335
        int next = current() - '0';
        if (max > (RegExpTree::kInfinity - next) / 10) {
4336 4337 4338 4339
          do {
            Advance();
          } while (IsDecimalDigit(current()));
          max = RegExpTree::kInfinity;
4340 4341 4342
          break;
        }
        max = 10 * max + next;
4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363
        Advance();
      }
      if (current() != '}') {
        Reset(start);
        return false;
      }
      Advance();
    }
  } else {
    Reset(start);
    return false;
  }
  *min_out = min;
  *max_out = max;
  return true;
}


// Upper and lower case letters differ by one bit.
STATIC_CHECK(('a' ^ 'A') == 0x20);

4364
uc32 RegExpParser::ParseControlLetterEscape() {
4365 4366
  if (!has_more())
    return 'c';
4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
  uc32 letter = current() & ~(0x20);  // Collapse upper and lower case letters.
  if (letter < 'A' || 'Z' < letter) {
    // Non-spec error-correction: "\c" followed by non-control letter is
    // interpreted as an IdentityEscape of 'c'.
    return 'c';
  }
  Advance();
  return letter & 0x1f;  // Remainder modulo 32, per specification.
}


uc32 RegExpParser::ParseOctalLiteral() {
  ASSERT('0' <= current() && current() <= '7');
  // For compatibility with some other browsers (not all), we parse
  // up to three octal digits with a value below 256.
  uc32 value = current() - '0';
  Advance();
  if ('0' <= current() && current() <= '7') {
    value = value * 8 + current() - '0';
    Advance();
    if (value < 32 && '0' <= current() && current() <= '7') {
      value = value * 8 + current() - '0';
      Advance();
    }
  }
  return value;
}


bool RegExpParser::ParseHexEscape(int length, uc32 *value) {
  int start = position();
  uc32 val = 0;
  bool done = false;
  for (int i = 0; !done; i++) {
    uc32 c = current();
    int d = HexValue(c);
    if (d < 0) {
      Reset(start);
      return false;
    }
    val = val * 16 + d;
    Advance();
    if (i == length - 1) {
      done = true;
    }
  }
  *value = val;
  return true;
}


4418
uc32 RegExpParser::ParseClassCharacterEscape() {
4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
  ASSERT(current() == '\\');
  ASSERT(has_next() && !IsSpecialClassEscape(Next()));
  Advance();
  switch (current()) {
    case 'b':
      Advance();
      return '\b';
    // ControlEscape :: one of
    //   f n r t v
    case 'f':
      Advance();
      return '\f';
    case 'n':
      Advance();
      return '\n';
    case 'r':
      Advance();
      return '\r';
    case 't':
      Advance();
      return '\t';
    case 'v':
      Advance();
      return '\v';
    case 'c':
4444
      Advance();
4445
      return ParseControlLetterEscape();
4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484
    case '0': case '1': case '2': case '3': case '4': case '5':
    case '6': case '7':
      // For compatibility, we interpret a decimal escape that isn't
      // a back reference (and therefore either \0 or not valid according
      // to the specification) as a 1..3 digit octal character code.
      return ParseOctalLiteral();
    case 'x': {
      Advance();
      uc32 value;
      if (ParseHexEscape(2, &value)) {
        return value;
      }
      // If \x is not followed by a two-digit hexadecimal, treat it
      // as an identity escape.
      return 'x';
    }
    case 'u': {
      Advance();
      uc32 value;
      if (ParseHexEscape(4, &value)) {
        return value;
      }
      // If \u is not followed by a four-digit hexadecimal, treat it
      // as an identity escape.
      return 'u';
    }
    default: {
      // Extended identity escape. We accept any character that hasn't
      // been matched by a more specific case, not just the subset required
      // by the ECMAScript specification.
      uc32 result = current();
      Advance();
      return result;
    }
  }
  return 0;
}


4485
CharacterRange RegExpParser::ParseClassAtom(uc16* char_class) {
4486
  ASSERT_EQ(0, *char_class);
4487 4488 4489 4490
  uc32 first = current();
  if (first == '\\') {
    switch (Next()) {
      case 'w': case 'W': case 'd': case 'D': case 's': case 'S': {
4491
        *char_class = Next();
4492
        Advance(2);
4493
        return CharacterRange::Singleton(0);  // Return dummy value.
4494
      }
4495
      case kEndMarker:
4496
        return ReportError(CStrVector("\\ at end of pattern"));
4497
      default:
4498
        uc32 c = ParseClassCharacterEscape(CHECK_FAILED);
4499 4500 4501 4502 4503 4504 4505 4506 4507
        return CharacterRange::Singleton(c);
    }
  } else {
    Advance();
    return CharacterRange::Singleton(first);
  }
}


4508
RegExpTree* RegExpParser::ParseCharacterClass() {
4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
  static const char* kUnterminated = "Unterminated character class";
  static const char* kRangeOutOfOrder = "Range out of order in character class";

  ASSERT_EQ(current(), '[');
  Advance();
  bool is_negated = false;
  if (current() == '^') {
    is_negated = true;
    Advance();
  }
  ZoneList<CharacterRange>* ranges = new ZoneList<CharacterRange>(2);
  while (has_more() && current() != ']') {
4521
    uc16 char_class = 0;
4522
    CharacterRange first = ParseClassAtom(&char_class CHECK_FAILED);
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537
    if (char_class) {
      CharacterRange::AddClassEscape(char_class, ranges);
      continue;
    }
    if (current() == '-') {
      Advance();
      if (current() == kEndMarker) {
        // If we reach the end we break out of the loop and let the
        // following code report an error.
        break;
      } else if (current() == ']') {
        ranges->Add(first);
        ranges->Add(CharacterRange::Singleton('-'));
        break;
      }
4538
      CharacterRange next = ParseClassAtom(&char_class CHECK_FAILED);
4539
      if (char_class) {
4540
        ranges->Add(first);
4541 4542 4543
        ranges->Add(CharacterRange::Singleton('-'));
        CharacterRange::AddClassEscape(char_class, ranges);
        continue;
4544
      }
4545
      if (first.from() > next.to()) {
4546
        return ReportError(CStrVector(kRangeOutOfOrder) CHECK_FAILED);
4547 4548 4549 4550
      }
      ranges->Add(CharacterRange::Range(first.from(), next.to()));
    } else {
      ranges->Add(first);
4551 4552 4553
    }
  }
  if (!has_more()) {
4554
    return ReportError(CStrVector(kUnterminated) CHECK_FAILED);
4555 4556 4557
  }
  Advance();
  if (ranges->length() == 0) {
4558
    ranges->Add(CharacterRange::Everything());
4559 4560 4561 4562 4563 4564
    is_negated = !is_negated;
  }
  return new RegExpCharacterClass(ranges, is_negated);
}


4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575
// ----------------------------------------------------------------------------
// The Parser interface.

ParserMessage::~ParserMessage() {
  for (int i = 0; i < args().length(); i++)
    DeleteArray(args()[i]);
  DeleteArray(args().start());
}


ScriptDataImpl::~ScriptDataImpl() {
4576
  if (owns_store_) store_.Dispose();
4577 4578 4579 4580
}


int ScriptDataImpl::Length() {
4581
  return store_.length() * sizeof(unsigned);
4582 4583 4584
}


4585 4586
const char* ScriptDataImpl::Data() {
  return reinterpret_cast<const char*>(store_.start());
4587 4588 4589
}


4590 4591 4592 4593 4594
bool ScriptDataImpl::HasError() {
  return has_error();
}


4595
void ScriptDataImpl::Initialize() {
4596
  // Prepares state for use.
4597
  if (store_.length() >= kHeaderSize) {
4598
    function_index_ = kHeaderSize;
4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637
    int symbol_data_offset = kHeaderSize + store_[kFunctionsSizeOffset];
    if (store_.length() > symbol_data_offset) {
      symbol_data_ = reinterpret_cast<byte*>(&store_[symbol_data_offset]);
    } else {
      // Partial preparse causes no symbol information.
      symbol_data_ = reinterpret_cast<byte*>(&store_[0] + store_.length());
    }
    symbol_data_end_ = reinterpret_cast<byte*>(&store_[0] + store_.length());
  }
}


int ScriptDataImpl::ReadNumber(byte** source) {
  // Reads a number from symbol_data_ in base 128. The most significant
  // bit marks that there are more digits.
  // If the first byte is 0x80 (kNumberTerminator), it would normally
  // represent a leading zero. Since that is useless, and therefore won't
  // appear as the first digit of any actual value, it is used to
  // mark the end of the input stream.
  byte* data = *source;
  if (data >= symbol_data_end_) return -1;
  byte input = *data;
  if (input == kNumberTerminator) {
    // End of stream marker.
    return -1;
  }
  int result = input & 0x7f;
  data++;
  while ((input & 0x80u) != 0) {
    if (data >= symbol_data_end_) return -1;
    input = *data;
    result = (result << 7) | (input & 0x7f);
    data++;
  }
  *source = data;
  return result;
}


4638 4639 4640 4641 4642 4643
// Preparse, but only collect data that is immediately useful,
// even if the preparser data is only used once.
ScriptDataImpl* ParserApi::PartialPreParse(Handle<String> source,
                                           unibrow::CharacterStream* stream,
                                           v8::Extension* extension) {
  Handle<Script> no_script;
4644 4645 4646 4647 4648 4649
  bool allow_lazy = FLAG_lazy && (extension == NULL);
  if (!allow_lazy) {
    // Partial preparsing is only about lazily compiled functions.
    // If we don't allow lazy compilation, the log data will be empty.
    return NULL;
  }
4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665
  preparser::PreParser<Scanner, PartialParserRecorder> parser;
  Scanner scanner;
  scanner.Initialize(source, stream, JAVASCRIPT);
  PartialParserRecorder recorder;
  if (!parser.PreParseProgram(&scanner, &recorder, allow_lazy)) {
    Top::StackOverflow();
    return NULL;
  }

  // Extract the accumulated data from the recorder as a single
  // contiguous vector that we are responsible for disposing.
  Vector<unsigned> store = recorder.ExtractData();
  return new ScriptDataImpl(store);
}


4666 4667 4668
ScriptDataImpl* ParserApi::PreParse(Handle<String> source,
                                    unibrow::CharacterStream* stream,
                                    v8::Extension* extension) {
4669
  Handle<Script> no_script;
4670 4671 4672 4673 4674 4675 4676 4677 4678
  preparser::PreParser<Scanner, CompleteParserRecorder> parser;
  Scanner scanner;
  scanner.Initialize(source, stream, JAVASCRIPT);
  bool allow_lazy = FLAG_lazy && (extension == NULL);
  CompleteParserRecorder recorder;
  if (!parser.PreParseProgram(&scanner, &recorder, allow_lazy)) {
    Top::StackOverflow();
    return NULL;
  }
4679 4680
  // Extract the accumulated data from the recorder as a single
  // contiguous vector that we are responsible for disposing.
4681
  Vector<unsigned> store = recorder.ExtractData();
4682 4683 4684 4685
  return new ScriptDataImpl(store);
}


4686 4687 4688
bool RegExpParser::ParseRegExp(FlatStringReader* input,
                               bool multiline,
                               RegExpCompileData* result) {
4689
  ASSERT(result != NULL);
4690
  RegExpParser parser(input, &result->error, multiline);
4691
  RegExpTree* tree = parser.ParsePattern();
4692
  if (parser.failed()) {
4693
    ASSERT(tree == NULL);
4694 4695
    ASSERT(!result->error.is_null());
  } else {
4696
    ASSERT(tree != NULL);
4697
    ASSERT(result->error.is_null());
4698 4699 4700
    result->tree = tree;
    int capture_count = parser.captures_started();
    result->simple = tree->IsAtom() && parser.simple() && capture_count == 0;
4701
    result->contains_anchor = parser.contains_anchor();
4702
    result->capture_count = capture_count;
4703
  }
4704
  return !parser.failed();
4705 4706 4707
}


4708
bool ParserApi::Parse(CompilationInfo* info) {
4709 4710 4711 4712
  ASSERT(info->function() == NULL);
  FunctionLiteral* result = NULL;
  Handle<Script> script = info->script();
  if (info->is_lazy()) {
4713
    Parser parser(script, true, NULL, NULL);
4714
    result = parser.ParseLazy(info->shared_info());
4715
  } else {
4716 4717 4718
    bool allow_natives_syntax =
        FLAG_allow_natives_syntax || Bootstrapper::IsActive();
    ScriptDataImpl* pre_data = info->pre_parse_data();
4719
    Parser parser(script, allow_natives_syntax, info->extension(), pre_data);
4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732
    if (pre_data != NULL && pre_data->has_error()) {
      Scanner::Location loc = pre_data->MessageLocation();
      const char* message = pre_data->BuildMessage();
      Vector<const char*> args = pre_data->BuildArgs();
      parser.ReportMessageAt(loc, message, args);
      DeleteArray(message);
      for (int i = 0; i < args.length(); i++) {
        DeleteArray(args[i]);
      }
      DeleteArray(args.start());
      ASSERT(Top::has_pending_exception());
    } else {
      Handle<String> source = Handle<String>(String::cast(script->source()));
4733
      result = parser.ParseProgram(source, info->is_global());
4734
    }
4735
  }
4736

4737 4738
  info->SetFunction(result);
  return (result != NULL);
4739 4740 4741
}

} }  // namespace v8::internal