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

5
#include "src/parser.h"
6

7 8
#include "src/api.h"
#include "src/ast.h"
9
#include "src/ast-literal-reindexer.h"
10
#include "src/bailout-reason.h"
11
#include "src/base/platform/platform.h"
12 13 14 15 16 17
#include "src/bootstrapper.h"
#include "src/char-predicates-inl.h"
#include "src/codegen.h"
#include "src/compiler.h"
#include "src/messages.h"
#include "src/preparser.h"
18
#include "src/runtime/runtime.h"
19 20 21
#include "src/scanner-character-streams.h"
#include "src/scopeinfo.h"
#include "src/string-stream.h"
22

23 24
namespace v8 {
namespace internal {
25

26 27 28 29 30 31 32 33 34 35 36 37
ScriptData::ScriptData(const byte* data, int length)
    : owns_data_(false), rejected_(false), data_(data), length_(length) {
  if (!IsAligned(reinterpret_cast<intptr_t>(data), kPointerAlignment)) {
    byte* copy = NewArray<byte>(length);
    DCHECK(IsAligned(reinterpret_cast<intptr_t>(copy), kPointerAlignment));
    CopyBytes(copy, data, length);
    data_ = copy;
    AcquireDataOwnership();
  }
}


38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
ParseInfo::ParseInfo(Zone* zone)
    : zone_(zone),
      flags_(0),
      source_stream_(nullptr),
      source_stream_encoding_(ScriptCompiler::StreamedSource::ONE_BYTE),
      extension_(nullptr),
      compile_options_(ScriptCompiler::kNoCompileOptions),
      script_scope_(nullptr),
      unicode_cache_(nullptr),
      stack_limit_(0),
      hash_seed_(0),
      cached_data_(nullptr),
      ast_value_factory_(nullptr),
      literal_(nullptr),
      scope_(nullptr) {}


ParseInfo::ParseInfo(Zone* zone, Handle<JSFunction> function)
    : ParseInfo(zone, Handle<SharedFunctionInfo>(function->shared())) {
57 58 59 60 61
  set_closure(function);
  set_context(Handle<Context>(function->context()));
}


62 63
ParseInfo::ParseInfo(Zone* zone, Handle<SharedFunctionInfo> shared)
    : ParseInfo(zone) {
64 65 66 67 68 69 70 71 72 73 74
  isolate_ = shared->GetIsolate();

  set_lazy();
  set_hash_seed(isolate_->heap()->HashSeed());
  set_stack_limit(isolate_->stack_guard()->real_climit());
  set_unicode_cache(isolate_->unicode_cache());
  set_language_mode(shared->language_mode());
  set_shared_info(shared);

  Handle<Script> script(Script::cast(shared->script()));
  set_script(script);
75
  if (!script.is_null() && script->type() == Script::TYPE_NATIVE) {
76 77 78 79 80
    set_native();
  }
}


81
ParseInfo::ParseInfo(Zone* zone, Handle<Script> script) : ParseInfo(zone) {
82 83 84 85 86 87 88
  isolate_ = script->GetIsolate();

  set_hash_seed(isolate_->heap()->HashSeed());
  set_stack_limit(isolate_->stack_guard()->real_climit());
  set_unicode_cache(isolate_->unicode_cache());
  set_script(script);

89
  if (script->type() == Script::TYPE_NATIVE) {
90 91 92 93 94
    set_native();
  }
}


95 96
RegExpBuilder::RegExpBuilder(Zone* zone)
    : zone_(zone),
97 98 99 100
      pending_empty_(false),
      characters_(NULL),
      terms_(),
      alternatives_()
101
#ifdef DEBUG
102
    , last_added_(ADD_NONE)
103 104 105 106 107 108 109
#endif
  {}


void RegExpBuilder::FlushCharacters() {
  pending_empty_ = false;
  if (characters_ != NULL) {
110
    RegExpTree* atom = new(zone()) RegExpAtom(characters_->ToConstVector());
111
    characters_ = NULL;
112
    text_.Add(atom, zone());
113 114 115 116 117 118 119 120 121 122 123
    LAST(ADD_ATOM);
  }
}


void RegExpBuilder::FlushText() {
  FlushCharacters();
  int num_text = text_.length();
  if (num_text == 0) {
    return;
  } else if (num_text == 1) {
124
    terms_.Add(text_.last(), zone());
125
  } else {
126
    RegExpText* text = new(zone()) RegExpText(zone());
127
    for (int i = 0; i < num_text; i++)
128 129
      text_.Get(i)->AppendToText(text, zone());
    terms_.Add(text, zone());
130 131 132 133 134 135 136 137
  }
  text_.Clear();
}


void RegExpBuilder::AddCharacter(uc16 c) {
  pending_empty_ = false;
  if (characters_ == NULL) {
138
    characters_ = new(zone()) ZoneList<uc16>(4, zone());
139
  }
140
  characters_->Add(c, zone());
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  LAST(ADD_CHAR);
}


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


void RegExpBuilder::AddAtom(RegExpTree* term) {
  if (term->IsEmpty()) {
    AddEmpty();
    return;
  }
  if (term->IsTextElement()) {
    FlushCharacters();
157
    text_.Add(term, zone());
158 159
  } else {
    FlushText();
160
    terms_.Add(term, zone());
161 162 163 164 165 166 167
  }
  LAST(ADD_ATOM);
}


void RegExpBuilder::AddAssertion(RegExpTree* assert) {
  FlushText();
168
  terms_.Add(assert, zone());
169 170 171 172 173 174 175 176 177 178 179 180 181 182
  LAST(ADD_ASSERT);
}


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


void RegExpBuilder::FlushTerms() {
  FlushText();
  int num_terms = terms_.length();
  RegExpTree* alternative;
  if (num_terms == 0) {
183
    alternative = new (zone()) RegExpEmpty();
184 185 186
  } else if (num_terms == 1) {
    alternative = terms_.last();
  } else {
187
    alternative = new(zone()) RegExpAlternative(terms_.GetList(zone()));
188
  }
189
  alternatives_.Add(alternative, zone());
190 191 192 193 194 195 196 197
  terms_.Clear();
  LAST(ADD_NONE);
}


RegExpTree* RegExpBuilder::ToRegExp() {
  FlushTerms();
  int num_alternatives = alternatives_.length();
198 199
  if (num_alternatives == 0) return new (zone()) RegExpEmpty();
  if (num_alternatives == 1) return alternatives_.last();
200
  return new(zone()) RegExpDisjunction(alternatives_.GetList(zone()));
201 202 203
}


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


251
FunctionEntry ParseData::GetFunctionEntry(int start) {
252 253
  // The current pre-data entry must be a FunctionEntry with the given
  // start position.
254 255
  if ((function_index_ + FunctionEntry::kSize <= Length()) &&
      (static_cast<int>(Data()[function_index_]) == start)) {
256 257
    int index = function_index_;
    function_index_ += FunctionEntry::kSize;
258 259
    Vector<unsigned> subvector(&(Data()[index]), FunctionEntry::kSize);
    return FunctionEntry(subvector);
260 261 262 263 264
  }
  return FunctionEntry();
}


265 266 267 268 269
int ParseData::FunctionCount() {
  int functions_size = FunctionsSize();
  if (functions_size < 0) return 0;
  if (functions_size % FunctionEntry::kSize != 0) return 0;
  return functions_size / FunctionEntry::kSize;
270 271 272
}


273
bool ParseData::IsSane() {
274
  if (!IsAligned(script_data_->length(), sizeof(unsigned))) return false;
275 276
  // Check that the header data is valid and doesn't specify
  // point to positions outside the store.
277 278 279 280 281
  int data_length = Length();
  if (data_length < PreparseDataConstants::kHeaderSize) return false;
  if (Magic() != PreparseDataConstants::kMagicNumber) return false;
  if (Version() != PreparseDataConstants::kCurrentVersion) return false;
  if (HasError()) return false;
282
  // Check that the space allocated for function entries is sane.
283
  int functions_size = FunctionsSize();
284 285
  if (functions_size < 0) return false;
  if (functions_size % FunctionEntry::kSize != 0) return false;
286
  // Check that the total size has room for header and function entries.
287
  int minimum_size =
288
      PreparseDataConstants::kHeaderSize + functions_size;
289
  if (data_length < minimum_size) return false;
290 291 292 293
  return true;
}


294 295 296 297 298
void ParseData::Initialize() {
  // Prepares state for use.
  int data_length = Length();
  if (data_length >= PreparseDataConstants::kHeaderSize) {
    function_index_ = PreparseDataConstants::kHeaderSize;
299
  }
300 301 302
}


303 304
bool ParseData::HasError() {
  return Data()[PreparseDataConstants::kHasErrorOffset];
305 306 307
}


308 309
unsigned ParseData::Magic() {
  return Data()[PreparseDataConstants::kMagicOffset];
310 311 312
}


313 314
unsigned ParseData::Version() {
  return Data()[PreparseDataConstants::kVersionOffset];
315 316 317
}


318 319
int ParseData::FunctionsSize() {
  return static_cast<int>(Data()[PreparseDataConstants::kFunctionsSizeOffset]);
320 321 322
}


323
void Parser::SetCachedData(ParseInfo* info) {
324
  if (compile_options_ == ScriptCompiler::kNoCompileOptions) {
325 326
    cached_parse_data_ = NULL;
  } else {
327 328 329
    DCHECK(info->cached_data() != NULL);
    if (compile_options_ == ScriptCompiler::kConsumeParserCache) {
      cached_parse_data_ = ParseData::FromCachedData(*info->cached_data());
330 331
    }
  }
332 333 334
}


335
FunctionLiteral* Parser::DefaultConstructor(bool call_super, Scope* scope,
336 337
                                            int pos, int end_pos,
                                            LanguageMode language_mode) {
338 339 340 341 342
  int materialized_literal_count = -1;
  int expected_property_count = -1;
  int parameter_count = 0;
  const AstRawString* name = ast_value_factory()->empty_string();

343

344 345
  FunctionKind kind = call_super ? FunctionKind::kDefaultSubclassConstructor
                                 : FunctionKind::kDefaultBaseConstructor;
346
  Scope* function_scope = NewScope(scope, FUNCTION_SCOPE, kind);
347
  function_scope->SetLanguageMode(
348
      static_cast<LanguageMode>(language_mode | STRICT));
349 350 351 352 353 354
  // Set start and end position to the same value
  function_scope->set_start_position(pos);
  function_scope->set_end_position(pos);
  ZoneList<Statement*>* body = NULL;

  {
355
    AstNodeFactory function_factory(ast_value_factory());
356
    FunctionState function_state(&function_state_, &scope_, function_scope,
357
                                 kind, &function_factory);
358

359 360
    body = new (zone()) ZoneList<Statement*>(call_super ? 2 : 1, zone());
    AddAssertIsConstruct(body, pos);
361
    if (call_super) {
362
      // %_DefaultConstructorCallSuper(new.target, %GetPrototype(<this-fun>))
363
      ZoneList<Expression*>* args =
364 365 366 367 368 369 370 371
          new (zone()) ZoneList<Expression*>(2, zone());
      VariableProxy* new_target_proxy = scope_->NewUnresolved(
          factory(), ast_value_factory()->new_target_string(), Variable::NORMAL,
          pos);
      args->Add(new_target_proxy, zone());
      VariableProxy* this_function_proxy = scope_->NewUnresolved(
          factory(), ast_value_factory()->this_function_string(),
          Variable::NORMAL, pos);
372 373 374 375 376 377
      ZoneList<Expression*>* tmp =
          new (zone()) ZoneList<Expression*>(1, zone());
      tmp->Add(this_function_proxy, zone());
      Expression* get_prototype =
          factory()->NewCallRuntime(Runtime::kGetPrototype, tmp, pos);
      args->Add(get_prototype, zone());
378
      CallRuntime* call = factory()->NewCallRuntime(
379
          Runtime::kInlineDefaultConstructorCallSuper, args, pos);
380
      body->Add(factory()->NewReturnStatement(call, pos), zone());
381 382 383 384 385 386 387 388
    }

    materialized_literal_count = function_state.materialized_literal_count();
    expected_property_count = function_state.expected_property_count();
  }

  FunctionLiteral* function_literal = factory()->NewFunctionLiteral(
      name, ast_value_factory(), function_scope, body,
389 390
      materialized_literal_count, expected_property_count, parameter_count,
      FunctionLiteral::kNoDuplicateParameters,
391
      FunctionLiteral::ANONYMOUS_EXPRESSION, FunctionLiteral::kIsFunction,
392
      FunctionLiteral::kShouldLazyCompile, kind, pos);
393 394 395 396 397

  return function_literal;
}


398 399 400 401 402 403 404 405
// ----------------------------------------------------------------------------
// 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:
406 407
  Target(Target** variable, BreakableStatement* statement)
      : variable_(variable), statement_(statement), previous_(*variable) {
408
    *variable = this;
409 410 411
  }

  ~Target() {
412
    *variable_ = previous_;
413 414
  }

bak@chromium.org's avatar
bak@chromium.org committed
415
  Target* previous() { return previous_; }
416
  BreakableStatement* statement() { return statement_; }
bak@chromium.org's avatar
bak@chromium.org committed
417

418
 private:
419
  Target** variable_;
420
  BreakableStatement* statement_;
bak@chromium.org's avatar
bak@chromium.org committed
421
  Target* previous_;
422 423 424 425 426
};


class TargetScope BASE_EMBEDDED {
 public:
427 428 429
  explicit TargetScope(Target** variable)
      : variable_(variable), previous_(*variable) {
    *variable = NULL;
430 431 432
  }

  ~TargetScope() {
433
    *variable_ = previous_;
434 435 436
  }

 private:
437
  Target** variable_;
bak@chromium.org's avatar
bak@chromium.org committed
438
  Target* previous_;
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
};


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

456
#define CHECK_FAILED  /**/);   \
457 458 459 460
  if (failed_) return NULL; \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY
461 462 463 464

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

rossberg's avatar
rossberg committed
465 466 467 468 469 470 471 472 473 474
bool ParserTraits::IsEval(const AstRawString* identifier) const {
  return identifier == parser_->ast_value_factory()->eval_string();
}


bool ParserTraits::IsArguments(const AstRawString* identifier) const {
  return identifier == parser_->ast_value_factory()->arguments_string();
}


475
bool ParserTraits::IsEvalOrArguments(const AstRawString* identifier) const {
rossberg's avatar
rossberg committed
476
  return IsEval(identifier) || IsArguments(identifier);
477 478
}

479 480 481
bool ParserTraits::IsUndefined(const AstRawString* identifier) const {
  return identifier == parser_->ast_value_factory()->undefined_string();
}
482

arv@chromium.org's avatar
arv@chromium.org committed
483 484 485 486 487 488 489 490 491 492
bool ParserTraits::IsPrototype(const AstRawString* identifier) const {
  return identifier == parser_->ast_value_factory()->prototype_string();
}


bool ParserTraits::IsConstructor(const AstRawString* identifier) const {
  return identifier == parser_->ast_value_factory()->constructor_string();
}


493
bool ParserTraits::IsThisProperty(Expression* expression) {
494
  DCHECK(expression != NULL);
495
  Property* property = expression->AsProperty();
arv's avatar
arv committed
496 497
  return property != NULL && property->obj()->IsVariableProxy() &&
         property->obj()->AsVariableProxy()->is_this();
498 499 500
}


501 502 503 504 505 506
bool ParserTraits::IsIdentifier(Expression* expression) {
  VariableProxy* operand = expression->AsVariableProxy();
  return operand != NULL && !operand->is_this();
}


507 508 509
void ParserTraits::PushPropertyName(FuncNameInferrer* fni,
                                    Expression* expression) {
  if (expression->IsPropertyName()) {
510
    fni->PushLiteralName(expression->AsLiteral()->AsRawPropertyName());
511 512
  } else {
    fni->PushLiteralName(
513
        parser_->ast_value_factory()->anonymous_function_string());
514 515 516 517
  }
}


518 519
void ParserTraits::CheckAssigningFunctionLiteralToProperty(Expression* left,
                                                           Expression* right) {
520
  DCHECK(left != NULL);
arv's avatar
arv committed
521
  if (left->IsProperty() && right->IsFunctionLiteral()) {
522 523 524 525 526
    right->AsFunctionLiteral()->set_pretenure();
  }
}


527 528 529 530
void ParserTraits::CheckPossibleEvalCall(Expression* expression,
                                         Scope* scope) {
  VariableProxy* callee = expression->AsVariableProxy();
  if (callee != NULL &&
531
      callee->raw_name() == parser_->ast_value_factory()->eval_string()) {
532
    scope->DeclarationScope()->RecordEvalCall();
533
    scope->RecordEvalCall();
534 535 536 537
  }
}


538 539 540 541
Expression* ParserTraits::MarkExpressionAsAssigned(Expression* expression) {
  VariableProxy* proxy =
      expression != NULL ? expression->AsVariableProxy() : NULL;
  if (proxy != NULL) proxy->set_is_assigned();
542 543 544 545
  return expression;
}


546 547
bool ParserTraits::ShortcutNumericLiteralBinaryExpression(
    Expression** x, Expression* y, Token::Value op, int pos,
548
    AstNodeFactory* factory) {
549 550 551 552
  if ((*x)->AsLiteral() && (*x)->AsLiteral()->raw_value()->IsNumber() &&
      y->AsLiteral() && y->AsLiteral()->raw_value()->IsNumber()) {
    double x_val = (*x)->AsLiteral()->raw_value()->AsNumber();
    double y_val = y->AsLiteral()->raw_value()->AsNumber();
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    switch (op) {
      case Token::ADD:
        *x = factory->NewNumberLiteral(x_val + y_val, pos);
        return true;
      case Token::SUB:
        *x = factory->NewNumberLiteral(x_val - y_val, pos);
        return true;
      case Token::MUL:
        *x = factory->NewNumberLiteral(x_val * y_val, pos);
        return true;
      case Token::DIV:
        *x = factory->NewNumberLiteral(x_val / y_val, pos);
        return true;
      case Token::BIT_OR: {
        int value = DoubleToInt32(x_val) | DoubleToInt32(y_val);
        *x = factory->NewNumberLiteral(value, pos);
        return true;
      }
      case Token::BIT_AND: {
        int value = DoubleToInt32(x_val) & DoubleToInt32(y_val);
        *x = factory->NewNumberLiteral(value, pos);
        return true;
      }
      case Token::BIT_XOR: {
        int value = DoubleToInt32(x_val) ^ DoubleToInt32(y_val);
        *x = factory->NewNumberLiteral(value, pos);
        return true;
      }
      case Token::SHL: {
        int value = DoubleToInt32(x_val) << (DoubleToInt32(y_val) & 0x1f);
        *x = factory->NewNumberLiteral(value, pos);
        return true;
      }
      case Token::SHR: {
        uint32_t shift = DoubleToInt32(y_val) & 0x1f;
        uint32_t value = DoubleToUint32(x_val) >> shift;
        *x = factory->NewNumberLiteral(value, pos);
        return true;
      }
      case Token::SAR: {
        uint32_t shift = DoubleToInt32(y_val) & 0x1f;
        int value = ArithmeticShiftRight(DoubleToInt32(x_val), shift);
        *x = factory->NewNumberLiteral(value, pos);
        return true;
      }
      default:
        break;
    }
  }
  return false;
}


606 607 608
Expression* ParserTraits::BuildUnaryExpression(Expression* expression,
                                               Token::Value op, int pos,
                                               AstNodeFactory* factory) {
609
  DCHECK(expression != NULL);
610
  if (expression->IsLiteral()) {
611
    const AstValue* literal = expression->AsLiteral()->raw_value();
612 613 614
    if (op == Token::NOT) {
      // Convert the literal to a boolean condition and negate it.
      bool condition = literal->BooleanValue();
615
      return factory->NewBooleanLiteral(!condition, pos);
616 617
    } else if (literal->IsNumber()) {
      // Compute some expressions involving only number literals.
618
      double value = literal->AsNumber();
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
      switch (op) {
        case Token::ADD:
          return expression;
        case Token::SUB:
          return factory->NewNumberLiteral(-value, pos);
        case Token::BIT_NOT:
          return factory->NewNumberLiteral(~DoubleToInt32(value), pos);
        default:
          break;
      }
    }
  }
  // Desugar '+foo' => 'foo*1'
  if (op == Token::ADD) {
    return factory->NewBinaryOperation(
634
        Token::MUL, expression, factory->NewNumberLiteral(1, pos, true), pos);
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  }
  // The same idea for '-foo' => 'foo*(-1)'.
  if (op == Token::SUB) {
    return factory->NewBinaryOperation(
        Token::MUL, expression, factory->NewNumberLiteral(-1, pos), pos);
  }
  // ...and one more time for '~foo' => 'foo^(~0)'.
  if (op == Token::BIT_NOT) {
    return factory->NewBinaryOperation(
        Token::BIT_XOR, expression, factory->NewNumberLiteral(~0, pos), pos);
  }
  return factory->NewUnaryOperation(op, expression, pos);
}


650 651
Expression* ParserTraits::NewThrowReferenceError(
    MessageTemplate::Template message, int pos) {
652 653
  return NewThrowError(Runtime::kNewReferenceError, message,
                       parser_->ast_value_factory()->empty_string(), pos);
654 655 656
}


657 658 659
Expression* ParserTraits::NewThrowSyntaxError(MessageTemplate::Template message,
                                              const AstRawString* arg,
                                              int pos) {
660
  return NewThrowError(Runtime::kNewSyntaxError, message, arg, pos);
661 662 663
}


664 665
Expression* ParserTraits::NewThrowTypeError(MessageTemplate::Template message,
                                            const AstRawString* arg, int pos) {
666
  return NewThrowError(Runtime::kNewTypeError, message, arg, pos);
667 668 669
}


670
Expression* ParserTraits::NewThrowError(Runtime::FunctionId id,
671 672
                                        MessageTemplate::Template message,
                                        const AstRawString* arg, int pos) {
673
  Zone* zone = parser_->zone();
674
  ZoneList<Expression*>* args = new (zone) ZoneList<Expression*>(2, zone);
675
  args->Add(parser_->factory()->NewSmiLiteral(message, pos), zone);
676
  args->Add(parser_->factory()->NewStringLiteral(arg, pos), zone);
677 678
  CallRuntime* call_constructor =
      parser_->factory()->NewCallRuntime(id, args, pos);
679 680 681 682
  return parser_->factory()->NewThrow(call_constructor, pos);
}


683
void ParserTraits::ReportMessageAt(Scanner::Location source_location,
684 685
                                   MessageTemplate::Template message,
                                   const char* arg, ParseErrorType error_type) {
686 687 688 689 690 691
  if (parser_->stack_overflow()) {
    // Suppress the error message (syntax error or such) in the presence of a
    // stack overflow. The isolate allows only one pending exception at at time
    // and we want to report the stack overflow later.
    return;
  }
692 693 694
  parser_->pending_error_handler_.ReportMessageAt(source_location.beg_pos,
                                                  source_location.end_pos,
                                                  message, arg, error_type);
695 696 697
}


698 699
void ParserTraits::ReportMessage(MessageTemplate::Template message,
                                 const char* arg, ParseErrorType error_type) {
700
  Scanner::Location source_location = parser_->scanner()->location();
701
  ReportMessageAt(source_location, message, arg, error_type);
702 703 704
}


705 706
void ParserTraits::ReportMessage(MessageTemplate::Template message,
                                 const AstRawString* arg,
707
                                 ParseErrorType error_type) {
708
  Scanner::Location source_location = parser_->scanner()->location();
709
  ReportMessageAt(source_location, message, arg, error_type);
710 711 712 713
}


void ParserTraits::ReportMessageAt(Scanner::Location source_location,
714 715
                                   MessageTemplate::Template message,
                                   const AstRawString* arg,
716
                                   ParseErrorType error_type) {
717 718 719 720 721 722
  if (parser_->stack_overflow()) {
    // Suppress the error message (syntax error or such) in the presence of a
    // stack overflow. The isolate allows only one pending exception at at time
    // and we want to report the stack overflow later.
    return;
  }
723 724 725
  parser_->pending_error_handler_.ReportMessageAt(source_location.beg_pos,
                                                  source_location.end_pos,
                                                  message, arg, error_type);
726 727 728
}


729 730
const AstRawString* ParserTraits::GetSymbol(Scanner* scanner) {
  const AstRawString* result =
731
      parser_->scanner()->CurrentSymbol(parser_->ast_value_factory());
732
  DCHECK(result != NULL);
733
  return result;
734 735
}

736

737 738 739 740
const AstRawString* ParserTraits::GetNumberAsSymbol(Scanner* scanner) {
  double double_value = parser_->scanner()->DoubleValue();
  char array[100];
  const char* string =
741
      DoubleToCString(double_value, Vector<char>(array, arraysize(array)));
742
  return parser_->ast_value_factory()->GetOneByteString(string);
743 744 745
}


746
const AstRawString* ParserTraits::GetNextSymbol(Scanner* scanner) {
747
  return parser_->scanner()->NextSymbol(parser_->ast_value_factory());
748 749 750
}


751 752
Expression* ParserTraits::ThisExpression(Scope* scope, AstNodeFactory* factory,
                                         int pos) {
753 754 755
  return scope->NewUnresolved(factory,
                              parser_->ast_value_factory()->this_string(),
                              Variable::THIS, pos, pos + 4);
756 757
}

758

759 760 761
Expression* ParserTraits::SuperPropertyReference(Scope* scope,
                                                 AstNodeFactory* factory,
                                                 int pos) {
762 763 764
  // this_function[home_object_symbol]
  VariableProxy* this_function_proxy = scope->NewUnresolved(
      factory, parser_->ast_value_factory()->this_function_string(),
765
      Variable::NORMAL, pos);
766 767 768 769
  Expression* home_object_symbol_literal =
      factory->NewSymbolLiteral("home_object_symbol", RelocInfo::kNoPosition);
  Expression* home_object = factory->NewProperty(
      this_function_proxy, home_object_symbol_literal, pos);
770
  return factory->NewSuperPropertyReference(
771
      ThisExpression(scope, factory, pos)->AsVariableProxy(), home_object, pos);
772
}
773

774

775 776 777 778 779 780 781 782 783 784 785 786 787 788
Expression* ParserTraits::SuperCallReference(Scope* scope,
                                             AstNodeFactory* factory, int pos) {
  VariableProxy* new_target_proxy = scope->NewUnresolved(
      factory, parser_->ast_value_factory()->new_target_string(),
      Variable::NORMAL, pos);
  VariableProxy* this_function_proxy = scope->NewUnresolved(
      factory, parser_->ast_value_factory()->this_function_string(),
      Variable::NORMAL, pos);
  return factory->NewSuperCallReference(
      ThisExpression(scope, factory, pos)->AsVariableProxy(), new_target_proxy,
      this_function_proxy, pos);
}


789 790 791 792
Expression* ParserTraits::NewTargetExpression(Scope* scope,
                                              AstNodeFactory* factory,
                                              int pos) {
  static const int kNewTargetStringLength = 10;
793
  auto proxy = scope->NewUnresolved(
794 795
      factory, parser_->ast_value_factory()->new_target_string(),
      Variable::NORMAL, pos, pos + kNewTargetStringLength);
796 797
  proxy->set_is_new_target();
  return proxy;
798 799 800
}


801
Expression* ParserTraits::DefaultConstructor(bool call_super, Scope* scope,
802 803 804
                                             int pos, int end_pos,
                                             LanguageMode mode) {
  return parser_->DefaultConstructor(call_super, scope, pos, end_pos, mode);
805 806 807
}


808 809 810
Literal* ParserTraits::ExpressionFromLiteral(Token::Value token, int pos,
                                             Scanner* scanner,
                                             AstNodeFactory* factory) {
811 812
  switch (token) {
    case Token::NULL_LITERAL:
813
      return factory->NewNullLiteral(pos);
814
    case Token::TRUE_LITERAL:
815
      return factory->NewBooleanLiteral(true, pos);
816
    case Token::FALSE_LITERAL:
817
      return factory->NewBooleanLiteral(false, pos);
verwaest's avatar
verwaest committed
818 819 820 821
    case Token::SMI: {
      int value = scanner->smi_value();
      return factory->NewSmiLiteral(value, pos);
    }
822
    case Token::NUMBER: {
823
      bool has_dot = scanner->ContainsDot();
824
      double value = scanner->DoubleValue();
825
      return factory->NewNumberLiteral(value, pos, has_dot);
826 827
    }
    default:
828
      DCHECK(false);
829 830 831 832 833
  }
  return NULL;
}


834
Expression* ParserTraits::ExpressionFromIdentifier(const AstRawString* name,
835 836 837
                                                   int start_position,
                                                   int end_position,
                                                   Scope* scope,
838
                                                   AstNodeFactory* factory) {
839
  if (parser_->fni_ != NULL) parser_->fni_->PushVariableName(name);
840 841
  return scope->NewUnresolved(factory, name, Variable::NORMAL, start_position,
                              end_position);
842 843 844
}


845 846
Expression* ParserTraits::ExpressionFromString(int pos, Scanner* scanner,
                                               AstNodeFactory* factory) {
847
  const AstRawString* symbol = GetSymbol(scanner);
848
  if (parser_->fni_ != NULL) parser_->fni_->PushLiteralName(symbol);
849
  return factory->NewStringLiteral(symbol, pos);
850 851 852
}


853 854
Expression* ParserTraits::GetIterator(Expression* iterable,
                                      AstNodeFactory* factory) {
855
  Expression* iterator_symbol_literal =
856
      factory->NewSymbolLiteral("iterator_symbol", RelocInfo::kNoPosition);
857 858 859 860 861 862 863 864 865
  int pos = iterable->position();
  Expression* prop =
      factory->NewProperty(iterable, iterator_symbol_literal, pos);
  Zone* zone = parser_->zone();
  ZoneList<Expression*>* args = new (zone) ZoneList<Expression*>(0, zone);
  return factory->NewCall(prop, args, pos);
}


866 867
Literal* ParserTraits::GetLiteralTheHole(int position,
                                         AstNodeFactory* factory) {
868
  return factory->NewTheHoleLiteral(RelocInfo::kNoPosition);
869 870 871 872 873 874 875 876
}


Expression* ParserTraits::ParseV8Intrinsic(bool* ok) {
  return parser_->ParseV8Intrinsic(ok);
}


877
FunctionLiteral* ParserTraits::ParseFunctionLiteral(
878
    const AstRawString* name, Scanner::Location function_name_location,
879
    FunctionNameValidity function_name_validity, FunctionKind kind,
880
    int function_token_position, FunctionLiteral::FunctionType type,
881 882
    FunctionLiteral::ArityRestriction arity_restriction,
    LanguageMode language_mode, bool* ok) {
883
  return parser_->ParseFunctionLiteral(
884
      name, function_name_location, function_name_validity, kind,
885
      function_token_position, type, arity_restriction, language_mode, ok);
886 887 888
}


889 890 891 892 893 894 895 896
ClassLiteral* ParserTraits::ParseClassLiteral(
    const AstRawString* name, Scanner::Location class_name_location,
    bool name_is_strict_reserved, int pos, bool* ok) {
  return parser_->ParseClassLiteral(name, class_name_location,
                                    name_is_strict_reserved, pos, ok);
}


897 898
Parser::Parser(ParseInfo* info)
    : ParserBase<ParserTraits>(info->zone(), &scanner_, info->stack_limit(),
899 900
                               info->extension(), info->ast_value_factory(),
                               NULL, this),
901
      scanner_(info->unicode_cache()),
902
      reusable_preparser_(NULL),
903
      original_scope_(NULL),
904
      target_stack_(NULL),
905
      compile_options_(info->compile_options()),
906
      cached_parse_data_(NULL),
907
      total_preparse_skipped_(0),
908 909
      pre_parse_timer_(NULL),
      parsing_on_main_thread_(true) {
910
  // Even though we were passed ParseInfo, we should not store it in
911
  // Parser - this makes sure that Isolate is not accidentally accessed via
912
  // ParseInfo during background parsing.
913
  DCHECK(!info->script().is_null() || info->source_stream() != NULL);
914
  set_allow_lazy(info->allow_lazy_parsing());
915 916
  set_allow_natives(FLAG_allow_natives_syntax || info->is_native());
  set_allow_harmony_sloppy(FLAG_harmony_sloppy);
917
  set_allow_harmony_sloppy_function(FLAG_harmony_sloppy_function);
918
  set_allow_harmony_sloppy_let(FLAG_harmony_sloppy_let);
919
  set_allow_harmony_rest_parameters(FLAG_harmony_rest_parameters);
920
  set_allow_harmony_default_parameters(FLAG_harmony_default_parameters);
neis's avatar
neis committed
921
  set_allow_harmony_spread_calls(FLAG_harmony_spread_calls);
dslomov's avatar
dslomov committed
922
  set_allow_harmony_destructuring(FLAG_harmony_destructuring);
arv's avatar
arv committed
923
  set_allow_harmony_spread_arrays(FLAG_harmony_spread_arrays);
924
  set_allow_harmony_new_target(FLAG_harmony_new_target);
marja's avatar
marja committed
925
  set_allow_strong_mode(FLAG_strong_mode);
926
  set_allow_legacy_const(FLAG_legacy_const);
927 928 929 930
  for (int feature = 0; feature < v8::Isolate::kUseCounterFeatureCount;
       ++feature) {
    use_counts_[feature] = 0;
  }
931 932
  if (info->ast_value_factory() == NULL) {
    // info takes ownership of AstValueFactory.
933 934
    info->set_ast_value_factory(new AstValueFactory(zone(), info->hash_seed()));
    info->set_ast_value_factory_owned();
935
    ast_value_factory_ = info->ast_value_factory();
936
  }
937 938 939
}


940
FunctionLiteral* Parser::ParseProgram(Isolate* isolate, ParseInfo* info) {
941 942
  // TODO(bmeurer): We temporarily need to pass allow_nesting = true here,
  // see comment for HistogramTimerScope class.
943

944 945 946 947 948 949 950
  // It's OK to use the Isolate & counters here, since this function is only
  // called in the main thread.
  DCHECK(parsing_on_main_thread_);

  HistogramTimerScope timer_scope(isolate->counters()->parse(), true);
  Handle<String> source(String::cast(info->script()->source()));
  isolate->counters()->total_parse_size()->Increment(source->length());
951
  base::ElapsedTimer timer;
952 953 954
  if (FLAG_trace_parse) {
    timer.Start();
  }
955
  fni_ = new (zone()) FuncNameInferrer(ast_value_factory(), zone());
956 957

  // Initialize parser state.
958
  CompleteParserRecorder recorder;
959

960
  if (produce_cached_parse_data()) {
961
    log_ = &recorder;
962
  } else if (consume_cached_parse_data()) {
963
    cached_parse_data_->Initialize();
964 965
  }

966
  source = String::Flatten(source);
967
  FunctionLiteral* result;
968

969 970 971 972
  if (source->IsExternalTwoByteString()) {
    // Notice that the stream is destroyed at the end of the branch block.
    // The last line of the blocks can't be moved outside, even though they're
    // identical calls.
973
    ExternalTwoByteStringUtf16CharacterStream stream(
974
        Handle<ExternalTwoByteString>::cast(source), 0, source->length());
975
    scanner_.Initialize(&stream);
wingo's avatar
wingo committed
976
    result = DoParseProgram(info);
977
  } else {
978
    GenericStringUtf16CharacterStream stream(source, 0, source->length());
979
    scanner_.Initialize(&stream);
wingo's avatar
wingo committed
980
    result = DoParseProgram(info);
981
  }
wingo's avatar
wingo committed
982 983
  if (result != NULL) {
    DCHECK_EQ(scanner_.peek_location().beg_pos, source->length());
984
  }
985
  HandleSourceURLComments(isolate, info->script());
986 987

  if (FLAG_trace_parse && result != NULL) {
988
    double ms = timer.Elapsed().InMillisecondsF();
989
    if (info->is_eval()) {
990
      PrintF("[parsing eval");
991 992
    } else if (info->script()->name()->IsString()) {
      String* name = String::cast(info->script()->name());
rmcilroy's avatar
rmcilroy committed
993
      base::SmartArrayPointer<char> name_chars = name->ToCString();
994
      PrintF("[parsing script: %s", name_chars.get());
995 996 997 998 999
    } else {
      PrintF("[parsing script");
    }
    PrintF(" - took %0.3f ms]\n", ms);
  }
1000
  if (produce_cached_parse_data()) {
1001
    if (result != NULL) *info->cached_data() = recorder.GetScriptData();
1002 1003
    log_ = NULL;
  }
1004
  return result;
1005 1006 1007
}


wingo's avatar
wingo committed
1008
FunctionLiteral* Parser::DoParseProgram(ParseInfo* info) {
1009 1010
  // Note that this function can be called from the main thread or from a
  // background thread. We should not access anything Isolate / heap dependent
1011
  // via ParseInfo, and also not pass it forward.
1012 1013
  DCHECK(scope_ == NULL);
  DCHECK(target_stack_ == NULL);
1014

1015 1016 1017
  Mode parsing_mode = FLAG_lazy && allow_lazy() ? PARSE_LAZILY : PARSE_EAGERLY;
  if (allow_natives() || extension_ != NULL) parsing_mode = PARSE_EAGERLY;

1018
  FunctionLiteral* result = NULL;
1019
  {
1020
    // TODO(wingo): Add an outer SCRIPT_SCOPE corresponding to the native
1021
    // context, which will have the "this" binding for script scopes.
wingo's avatar
wingo committed
1022 1023
    Scope* scope = NewScope(scope_, SCRIPT_SCOPE);
    info->set_script_scope(scope);
1024
    if (!info->context().is_null() && !info->context()->IsNativeContext()) {
wingo's avatar
wingo committed
1025 1026
      scope = Scope::DeserializeScopeChain(info->isolate(), zone(),
                                           *info->context(), scope);
1027 1028 1029
      // The Scope is backed up by ScopeInfo (which is in the V8 heap); this
      // means the Parser cannot operate independent of the V8 heap. Tell the
      // string table to internalize strings and values right after they're
1030 1031 1032
      // created. This kind of parsing can only be done in the main thread.
      DCHECK(parsing_on_main_thread_);
      ast_value_factory()->Internalize(info->isolate());
1033
    }
wingo's avatar
wingo committed
1034
    original_scope_ = scope;
1035
    if (info->is_eval()) {
1036
      if (!scope->is_script_scope() || is_strict(info->language_mode())) {
1037
        parsing_mode = PARSE_EAGERLY;
1038
      }
1039
      scope = NewScope(scope, EVAL_SCOPE);
1040
    } else if (info->is_module()) {
wingo's avatar
wingo committed
1041
      scope = NewScope(scope, MODULE_SCOPE);
1042
    }
wingo's avatar
wingo committed
1043 1044

    scope->set_start_position(0);
1045

1046 1047
    // Enter 'scope' with the given parsing mode.
    ParsingModeScope parsing_mode_scope(this, parsing_mode);
1048
    AstNodeFactory function_factory(ast_value_factory());
wingo's avatar
wingo committed
1049
    FunctionState function_state(&function_state_, &scope_, scope,
1050
                                 kNormalFunction, &function_factory);
1051

1052
    scope_->SetLanguageMode(info->language_mode());
1053
    ZoneList<Statement*>* body = new(zone()) ZoneList<Statement*>(16, zone());
1054
    bool ok = true;
1055
    int beg_pos = scanner()->location().beg_pos;
1056
    if (info->is_module()) {
1057
      ParseModuleItemList(body, &ok);
1058
    } else {
1059
      ParseStatementList(body, Token::EOS, &ok);
1060
    }
1061

wingo's avatar
wingo committed
1062 1063 1064 1065
    // The parser will peek but not consume EOS.  Our scope logically goes all
    // the way to the EOS, though.
    scope->set_end_position(scanner()->peek_location().beg_pos);

1066
    if (ok && is_strict(language_mode())) {
1067
      CheckStrictOctalLiteral(beg_pos, scanner()->location().end_pos, &ok);
1068
    }
1069 1070 1071 1072 1073 1074 1075
    if (ok && is_sloppy(language_mode()) && allow_harmony_sloppy_function()) {
      // TODO(littledan): Function bindings on the global object that modify
      // pre-existing bindings should be made writable, enumerable and
      // nonconfigurable if possible, whereas this code will leave attributes
      // unchanged if the property already exists.
      InsertSloppyBlockFunctionVarBindings(scope, &ok);
    }
1076
    if (ok && (is_strict(language_mode()) || allow_harmony_sloppy())) {
1077
      CheckConflictingVarDeclarations(scope_, &ok);
1078 1079
    }

1080 1081 1082 1083 1084
    if (ok && info->parse_restriction() == ONLY_SINGLE_FUNCTION_LITERAL) {
      if (body->length() != 1 ||
          !body->at(0)->IsExpressionStatement() ||
          !body->at(0)->AsExpressionStatement()->
              expression()->IsFunctionLiteral()) {
1085
        ReportMessage(MessageTemplate::kSingleFunctionLiteral);
1086 1087 1088 1089
        ok = false;
      }
    }

1090
    if (ok) {
1091
      result = factory()->NewFunctionLiteral(
1092 1093
          ast_value_factory()->empty_string(), ast_value_factory(), scope_,
          body, function_state.materialized_literal_count(),
1094
          function_state.expected_property_count(), 0,
1095
          FunctionLiteral::kNoDuplicateParameters,
1096
          FunctionLiteral::ANONYMOUS_EXPRESSION, FunctionLiteral::kGlobalOrEval,
1097 1098
          FunctionLiteral::kShouldLazyCompile, FunctionKind::kNormalFunction,
          0);
1099 1100 1101 1102
    }
  }

  // Make sure the target stack is empty.
1103
  DCHECK(target_stack_ == NULL);
1104 1105 1106 1107

  return result;
}

1108

1109
FunctionLiteral* Parser::ParseLazy(Isolate* isolate, ParseInfo* info) {
1110 1111 1112
  // It's OK to use the Isolate & counters here, since this function is only
  // called in the main thread.
  DCHECK(parsing_on_main_thread_);
1113
  HistogramTimerScope timer_scope(isolate->counters()->parse_lazy());
1114
  Handle<String> source(String::cast(info->script()->source()));
1115
  isolate->counters()->total_parse_size()->Increment(source->length());
1116
  base::ElapsedTimer timer;
1117 1118 1119
  if (FLAG_trace_parse) {
    timer.Start();
  }
1120
  Handle<SharedFunctionInfo> shared_info = info->shared_info();
1121

1122
  // Initialize parser state.
1123
  source = String::Flatten(source);
1124
  FunctionLiteral* result;
1125
  if (source->IsExternalTwoByteString()) {
1126
    ExternalTwoByteStringUtf16CharacterStream stream(
1127
        Handle<ExternalTwoByteString>::cast(source),
1128 1129
        shared_info->start_position(),
        shared_info->end_position());
1130
    result = ParseLazy(isolate, info, &stream);
1131
  } else {
1132 1133 1134
    GenericStringUtf16CharacterStream stream(source,
                                             shared_info->start_position(),
                                             shared_info->end_position());
1135
    result = ParseLazy(isolate, info, &stream);
1136
  }
1137 1138

  if (FLAG_trace_parse && result != NULL) {
1139
    double ms = timer.Elapsed().InMillisecondsF();
rmcilroy's avatar
rmcilroy committed
1140 1141
    base::SmartArrayPointer<char> name_chars =
        result->debug_name()->ToCString();
1142
    PrintF("[parsing function: %s - took %0.3f ms]\n", name_chars.get(), ms);
1143 1144
  }
  return result;
1145 1146 1147
}


1148
FunctionLiteral* Parser::ParseLazy(Isolate* isolate, ParseInfo* info,
1149 1150
                                   Utf16CharacterStream* source) {
  Handle<SharedFunctionInfo> shared_info = info->shared_info();
1151
  scanner_.Initialize(source);
1152 1153
  DCHECK(scope_ == NULL);
  DCHECK(target_stack_ == NULL);
1154

1155
  Handle<String> name(String::cast(shared_info->name()));
1156 1157 1158
  DCHECK(ast_value_factory());
  fni_ = new (zone()) FuncNameInferrer(ast_value_factory(), zone());
  const AstRawString* raw_name = ast_value_factory()->GetString(name);
1159
  fni_->PushEnclosingName(raw_name);
1160

1161
  ParsingModeScope parsing_mode(this, PARSE_EAGERLY);
1162 1163 1164 1165 1166 1167

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

  {
    // Parse the function literal.
1168
    Scope* scope = NewScope(scope_, SCRIPT_SCOPE);
1169
    info->set_script_scope(scope);
1170 1171 1172 1173
    if (!info->closure().is_null()) {
      // Ok to use Isolate here, since lazy function parsing is only done in the
      // main thread.
      DCHECK(parsing_on_main_thread_);
1174
      scope = Scope::DeserializeScopeChain(isolate, zone(),
1175
                                           info->closure()->context(), scope);
1176
    }
1177
    original_scope_ = scope;
1178
    AstNodeFactory function_factory(ast_value_factory());
1179
    FunctionState function_state(&function_state_, &scope_, scope,
1180
                                 shared_info->kind(), &function_factory);
1181
    DCHECK(is_sloppy(scope->language_mode()) ||
1182 1183
           is_strict(info->language_mode()));
    DCHECK(info->language_mode() == shared_info->language_mode());
1184
    FunctionLiteral::FunctionType function_type = shared_info->is_expression()
1185 1186 1187 1188
        ? (shared_info->is_anonymous()
              ? FunctionLiteral::ANONYMOUS_EXPRESSION
              : FunctionLiteral::NAMED_EXPRESSION)
        : FunctionLiteral::DECLARATION;
1189
    bool ok = true;
1190 1191

    if (shared_info->is_arrow()) {
1192 1193
      Scope* scope =
          NewScope(scope_, ARROW_SCOPE, FunctionKind::kArrowFunction);
1194
      scope->SetLanguageMode(shared_info->language_mode());
1195
      scope->set_start_position(shared_info->start_position());
1196
      ExpressionClassifier formals_classifier;
1197
      ParserFormalParameters formals(scope);
1198
      Checkpoint checkpoint(this);
1199 1200 1201 1202 1203 1204 1205
      {
        // Parsing patterns as variable reference expression creates
        // NewUnresolved references in current scope. Entrer arrow function
        // scope for formal parameter parsing.
        BlockState block_state(&scope_, scope);
        if (Check(Token::LPAREN)) {
          // '(' StrictFormalParameters ')'
1206
          ParseFormalParameterList(&formals, &formals_classifier, &ok);
1207 1208 1209
          if (ok) ok = Check(Token::RPAREN);
        } else {
          // BindingIdentifier
1210
          ParseFormalParameter(&formals, &formals_classifier, &ok);
1211
          if (ok) {
1212 1213
            DeclareFormalParameter(formals.scope, formals.at(0),
                                   &formals_classifier);
1214
          }
1215
        }
1216 1217
      }

1218
      if (ok) {
1219
        checkpoint.Restore(&formals.materialized_literals_count);
1220
        Expression* expression =
1221
            ParseArrowFunctionLiteral(formals, formals_classifier, &ok);
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        if (ok) {
          // Scanning must end at the same position that was recorded
          // previously. If not, parsing has been interrupted due to a stack
          // overflow, at which point the partially parsed arrow function
          // concise body happens to be a valid expression. This is a problem
          // only for arrow functions with single expression bodies, since there
          // is no end token such as "}" for normal functions.
          if (scanner()->location().end_pos == shared_info->end_position()) {
            // The pre-parser saw an arrow function here, so the full parser
            // must produce a FunctionLiteral.
            DCHECK(expression->IsFunctionLiteral());
            result = expression->AsFunctionLiteral();
          } else {
            ok = false;
          }
1237 1238
        }
      }
1239
    } else if (shared_info->is_default_constructor()) {
1240
      result = DefaultConstructor(IsSubclassConstructor(shared_info->kind()),
1241
                                  scope, shared_info->start_position(),
1242 1243
                                  shared_info->end_position(),
                                  shared_info->language_mode());
1244
    } else {
1245 1246 1247 1248
      result = ParseFunctionLiteral(
          raw_name, Scanner::Location::invalid(), kSkipFunctionNameCheck,
          shared_info->kind(), RelocInfo::kNoPosition, function_type,
          FunctionLiteral::NORMAL_ARITY, shared_info->language_mode(), &ok);
1249
    }
1250
    // Make sure the results agree.
1251
    DCHECK(ok == (result != NULL));
1252 1253 1254
  }

  // Make sure the target stack is empty.
1255
  DCHECK(target_stack_ == NULL);
1256

1257
  if (result != NULL) {
1258
    Handle<String> inferred_name(shared_info->inferred_name());
1259
    result->set_inferred_name(inferred_name);
1260 1261 1262 1263
  }
  return result;
}

1264

1265
void* Parser::ParseStatementList(ZoneList<Statement*>* body, int end_token,
1266
                                 bool* ok) {
1267 1268
  // StatementList ::
  //   (StatementListItem)* <end_token>
1269 1270 1271 1272 1273

  // 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.
1274
  TargetScope scope(&this->target_stack_);
1275

1276
  DCHECK(body != NULL);
1277 1278
  bool directive_prologue = true;     // Parsing directive prologue.

1279
  while (peek() != end_token) {
1280 1281 1282 1283
    if (directive_prologue && peek() != Token::STRING) {
      directive_prologue = false;
    }

1284
    Scanner::Location token_loc = scanner()->peek_location();
1285 1286
    Scanner::Location old_this_loc = function_state_->this_location();
    Scanner::Location old_super_loc = function_state_->super_location();
1287
    Statement* stat = ParseStatementListItem(CHECK_OK);
1288

1289 1290
    if (is_strong(language_mode()) && scope_->is_function_scope() &&
        IsClassConstructor(function_state_->kind())) {
1291 1292 1293 1294
      Scanner::Location this_loc = function_state_->this_location();
      Scanner::Location super_loc = function_state_->super_location();
      if (this_loc.beg_pos != old_this_loc.beg_pos &&
          this_loc.beg_pos != token_loc.beg_pos) {
1295
        ReportMessageAt(this_loc, MessageTemplate::kStrongConstructorThis);
1296 1297 1298 1299 1300
        *ok = false;
        return nullptr;
      }
      if (super_loc.beg_pos != old_super_loc.beg_pos &&
          super_loc.beg_pos != token_loc.beg_pos) {
1301
        ReportMessageAt(super_loc, MessageTemplate::kStrongConstructorSuper);
1302 1303 1304
        *ok = false;
        return nullptr;
      }
1305 1306
    }

1307 1308 1309 1310 1311 1312 1313
    if (stat == NULL || stat->IsEmpty()) {
      directive_prologue = false;   // End of directive prologue.
      continue;
    }

    if (directive_prologue) {
      // A shot at a directive.
1314 1315
      ExpressionStatement* e_stat;
      Literal* literal;
1316 1317 1318
      // Still processing directive prologue?
      if ((e_stat = stat->AsExpressionStatement()) != NULL &&
          (literal = e_stat->expression()->AsLiteral()) != NULL &&
1319
          literal->raw_value()->IsString()) {
marja's avatar
marja committed
1320 1321 1322
        // Check "use strict" directive (ES5 14.1), "use asm" directive, and
        // "use strong" directive (experimental).
        bool use_strict_found =
1323
            literal->raw_value()->AsString() ==
1324
                ast_value_factory()->use_strict_string() &&
1325
            token_loc.end_pos - token_loc.beg_pos ==
marja's avatar
marja committed
1326 1327 1328 1329 1330 1331 1332 1333
                ast_value_factory()->use_strict_string()->length() + 2;
        bool use_strong_found =
            allow_strong_mode() &&
            literal->raw_value()->AsString() ==
                ast_value_factory()->use_strong_string() &&
            token_loc.end_pos - token_loc.beg_pos ==
                ast_value_factory()->use_strong_string()->length() + 2;
        if (use_strict_found || use_strong_found) {
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
          // Strong mode implies strict mode. If there are several "use strict"
          // / "use strong" directives, do the strict mode changes only once.
          if (is_sloppy(scope_->language_mode())) {
            scope_->SetLanguageMode(
                static_cast<LanguageMode>(scope_->language_mode() | STRICT));
          }

          if (use_strong_found) {
            scope_->SetLanguageMode(
                static_cast<LanguageMode>(scope_->language_mode() | STRONG));
1344
            if (IsClassConstructor(function_state_->kind())) {
1345 1346 1347 1348 1349 1350 1351 1352
              // "use strong" cannot occur in a class constructor body, to avoid
              // unintuitive strong class object semantics.
              ParserTraits::ReportMessageAt(
                  token_loc, MessageTemplate::kStrongConstructorDirective);
              *ok = false;
              return nullptr;
            }
          }
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
          if (!scope_->HasSimpleParameters()) {
            // TC39 deemed "use strict" directives to be an error when occurring
            // in the body of a function with non-simple parameter list, on
            // 29/7/2015. https://goo.gl/ueA7Ln
            //
            // In V8, this also applies to "use strong " directives.
            const AstRawString* string = literal->raw_value()->AsString();
            ParserTraits::ReportMessageAt(
                token_loc, MessageTemplate::kIllegalLanguageModeDirective,
                string);
            *ok = false;
            return nullptr;
          }
1366 1367 1368
          // Because declarations in strict eval code don't leak into the scope
          // of the eval call, it is likely that functions declared in strict
          // eval code will be used within the eval code, so lazy parsing is
1369
          // probably not a win.
1370
          if (scope_->is_eval_scope()) mode_ = PARSE_EAGERLY;
1371
        } else if (literal->raw_value()->AsString() ==
1372
                       ast_value_factory()->use_asm_string() &&
1373
                   token_loc.end_pos - token_loc.beg_pos ==
1374
                       ast_value_factory()->use_asm_string()->length() + 2) {
1375 1376 1377
          // Store the usage count; The actual use counter on the isolate is
          // incremented after parsing is done.
          ++use_counts_[v8::Isolate::kUseAsm];
1378
          scope_->SetAsmModule();
1379 1380 1381 1382 1383 1384 1385
        }
      } else {
        // End of the directive prologue.
        directive_prologue = false;
      }
    }

1386
    body->Add(stat, zone());
1387
  }
1388

1389 1390 1391 1392
  return 0;
}


1393 1394 1395
Statement* Parser::ParseStatementListItem(bool* ok) {
  // (Ecma 262 6th Edition, 13.1):
  // StatementListItem:
1396
  //    Statement
1397
  //    Declaration
1398

1399 1400 1401 1402 1403 1404
  if (peek() != Token::CLASS) {
    // No more classes follow; reset the start position for the consecutive
    // class declaration group.
    scope_->set_class_declaration_group_start(-1);
  }

1405 1406
  switch (peek()) {
    case Token::FUNCTION:
1407
      return ParseFunctionDeclaration(NULL, ok);
arv@chromium.org's avatar
arv@chromium.org committed
1408
    case Token::CLASS:
1409 1410 1411 1412
      if (scope_->class_declaration_group_start() < 0) {
        scope_->set_class_declaration_group_start(
            scanner()->peek_location().beg_pos);
      }
arv@chromium.org's avatar
arv@chromium.org committed
1413
      return ParseClassDeclaration(NULL, ok);
1414
    case Token::CONST:
1415 1416 1417 1418
      if (allow_const()) {
        return ParseVariableStatement(kStatementListItem, NULL, ok);
      }
      break;
1419 1420
    case Token::VAR:
      return ParseVariableStatement(kStatementListItem, NULL, ok);
1421
    case Token::LET:
littledan's avatar
littledan committed
1422
      if (IsNextLetKeyword()) {
1423
        return ParseVariableStatement(kStatementListItem, NULL, ok);
1424
      }
1425
      break;
1426
    default:
1427
      break;
1428
  }
1429
  return ParseStatement(NULL, ok);
1430 1431 1432
}


1433 1434 1435 1436 1437 1438
Statement* Parser::ParseModuleItem(bool* ok) {
  // (Ecma 262 6th Edition, 15.2):
  // ModuleItem :
  //    ImportDeclaration
  //    ExportDeclaration
  //    StatementListItem
1439 1440

  switch (peek()) {
1441 1442 1443 1444 1445 1446
    case Token::IMPORT:
      return ParseImportDeclaration(ok);
    case Token::EXPORT:
      return ParseExportDeclaration(ok);
    default:
      return ParseStatementListItem(ok);
1447 1448 1449 1450
  }
}


1451
void* Parser::ParseModuleItemList(ZoneList<Statement*>* body, bool* ok) {
1452 1453 1454 1455 1456 1457
  // (Ecma 262 6th Edition, 15.2):
  // Module :
  //    ModuleBody?
  //
  // ModuleBody :
  //    ModuleItem*
1458

1459 1460
  DCHECK(scope_->is_module_scope());
  scope_->SetLanguageMode(
1461
      static_cast<LanguageMode>(scope_->language_mode() | STRICT));
1462

1463 1464 1465 1466
  while (peek() != Token::EOS) {
    Statement* stat = ParseModuleItem(CHECK_OK);
    if (stat && !stat->IsEmpty()) {
      body->Add(stat, zone());
1467 1468 1469
    }
  }

1470
  // Check that all exports are bound.
1471
  ModuleDescriptor* descriptor = scope_->module();
1472 1473
  for (ModuleDescriptor::Iterator it = descriptor->iterator(); !it.done();
       it.Advance()) {
1474
    if (scope_->LookupLocal(it.local_name()) == NULL) {
1475 1476 1477
      // TODO(adamk): Pass both local_name and export_name once ParserTraits
      // supports multiple arg error messages.
      // Also try to report this at a better location.
1478 1479
      ParserTraits::ReportMessage(MessageTemplate::kModuleExportUndefined,
                                  it.local_name());
1480 1481 1482 1483 1484
      *ok = false;
      return NULL;
    }
  }

1485 1486
  scope_->module()->Freeze();
  return NULL;
1487 1488 1489
}


1490
const AstRawString* Parser::ParseModuleSpecifier(bool* ok) {
1491 1492
  // ModuleSpecifier :
  //    StringLiteral
1493 1494

  Expect(Token::STRING, CHECK_OK);
1495
  return GetSymbol(scanner());
1496 1497 1498
}


1499 1500 1501
void* Parser::ParseExportClause(ZoneList<const AstRawString*>* export_names,
                                ZoneList<Scanner::Location>* export_locations,
                                ZoneList<const AstRawString*>* local_names,
1502 1503
                                Scanner::Location* reserved_loc, bool* ok) {
  // ExportClause :
1504
  //   '{' '}'
1505 1506
  //   '{' ExportsList '}'
  //   '{' ExportsList ',' '}'
1507
  //
1508 1509 1510
  // ExportsList :
  //   ExportSpecifier
  //   ExportsList ',' ExportSpecifier
1511
  //
1512
  // ExportSpecifier :
1513 1514 1515 1516 1517
  //   IdentifierName
  //   IdentifierName 'as' IdentifierName

  Expect(Token::LBRACE, CHECK_OK);

1518 1519 1520 1521 1522 1523 1524 1525
  Token::Value name_tok;
  while ((name_tok = peek()) != Token::RBRACE) {
    // Keep track of the first reserved word encountered in case our
    // caller needs to report an error.
    if (!reserved_loc->IsValid() &&
        !Token::IsIdentifier(name_tok, STRICT, false)) {
      *reserved_loc = scanner()->location();
    }
1526
    const AstRawString* local_name = ParseIdentifierName(CHECK_OK);
1527 1528 1529 1530
    const AstRawString* export_name = NULL;
    if (CheckContextualKeyword(CStrVector("as"))) {
      export_name = ParseIdentifierName(CHECK_OK);
    }
1531 1532 1533 1534 1535 1536
    if (export_name == NULL) {
      export_name = local_name;
    }
    export_names->Add(export_name, zone());
    local_names->Add(local_name, zone());
    export_locations->Add(scanner()->location(), zone());
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    if (peek() == Token::RBRACE) break;
    Expect(Token::COMMA, CHECK_OK);
  }

  Expect(Token::RBRACE, CHECK_OK);

  return 0;
}


1547
ZoneList<ImportDeclaration*>* Parser::ParseNamedImports(int pos, bool* ok) {
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
  // NamedImports :
  //   '{' '}'
  //   '{' ImportsList '}'
  //   '{' ImportsList ',' '}'
  //
  // ImportsList :
  //   ImportSpecifier
  //   ImportsList ',' ImportSpecifier
  //
  // ImportSpecifier :
  //   BindingIdentifier
  //   IdentifierName 'as' BindingIdentifier

  Expect(Token::LBRACE, CHECK_OK);

1563 1564
  ZoneList<ImportDeclaration*>* result =
      new (zone()) ZoneList<ImportDeclaration*>(1, zone());
1565 1566 1567
  while (peek() != Token::RBRACE) {
    const AstRawString* import_name = ParseIdentifierName(CHECK_OK);
    const AstRawString* local_name = import_name;
1568 1569
    // In the presence of 'as', the left-side of the 'as' can
    // be any IdentifierName. But without 'as', it must be a valid
1570
    // BindingIdentifier.
1571
    if (CheckContextualKeyword(CStrVector("as"))) {
1572 1573 1574
      local_name = ParseIdentifierName(CHECK_OK);
    }
    if (!Token::IsIdentifier(scanner()->current_token(), STRICT, false)) {
1575
      *ok = false;
1576
      ReportMessage(MessageTemplate::kUnexpectedReserved);
1577
      return NULL;
1578
    } else if (IsEvalOrArguments(local_name)) {
1579
      *ok = false;
1580
      ReportMessage(MessageTemplate::kStrictEvalArguments);
1581
      return NULL;
1582 1583
    } else if (is_strong(language_mode()) && IsUndefined(local_name)) {
      *ok = false;
1584
      ReportMessage(MessageTemplate::kStrongUndefined);
1585
      return NULL;
1586
    }
1587 1588 1589
    VariableProxy* proxy = NewUnresolved(local_name, IMPORT);
    ImportDeclaration* declaration =
        factory()->NewImportDeclaration(proxy, import_name, NULL, scope_, pos);
1590
    Declare(declaration, DeclarationDescriptor::NORMAL, true, CHECK_OK);
1591
    result->Add(declaration, zone());
1592 1593 1594 1595 1596 1597
    if (peek() == Token::RBRACE) break;
    Expect(Token::COMMA, CHECK_OK);
  }

  Expect(Token::RBRACE, CHECK_OK);

1598
  return result;
1599 1600 1601
}


1602
Statement* Parser::ParseImportDeclaration(bool* ok) {
1603 1604 1605
  // ImportDeclaration :
  //   'import' ImportClause 'from' ModuleSpecifier ';'
  //   'import' ModuleSpecifier ';'
1606
  //
1607 1608 1609 1610 1611 1612 1613 1614 1615
  // ImportClause :
  //   NameSpaceImport
  //   NamedImports
  //   ImportedDefaultBinding
  //   ImportedDefaultBinding ',' NameSpaceImport
  //   ImportedDefaultBinding ',' NamedImports
  //
  // NameSpaceImport :
  //   '*' 'as' ImportedBinding
1616

1617
  int pos = peek_position();
1618
  Expect(Token::IMPORT, CHECK_OK);
1619 1620 1621 1622 1623

  Token::Value tok = peek();

  // 'import' ModuleSpecifier ';'
  if (tok == Token::STRING) {
1624
    const AstRawString* module_specifier = ParseModuleSpecifier(CHECK_OK);
1625
    scope_->module()->AddModuleRequest(module_specifier, zone());
1626 1627 1628 1629 1630
    ExpectSemicolon(CHECK_OK);
    return factory()->NewEmptyStatement(pos);
  }

  // Parse ImportedDefaultBinding if present.
1631
  ImportDeclaration* import_default_declaration = NULL;
1632
  if (tok != Token::MUL && tok != Token::LBRACE) {
1633
    const AstRawString* local_name =
1634
        ParseIdentifier(kDontAllowRestrictedIdentifiers, CHECK_OK);
1635 1636 1637
    VariableProxy* proxy = NewUnresolved(local_name, IMPORT);
    import_default_declaration = factory()->NewImportDeclaration(
        proxy, ast_value_factory()->default_string(), NULL, scope_, pos);
1638 1639
    Declare(import_default_declaration, DeclarationDescriptor::NORMAL, true,
            CHECK_OK);
1640 1641 1642
  }

  const AstRawString* module_instance_binding = NULL;
1643
  ZoneList<ImportDeclaration*>* named_declarations = NULL;
1644
  if (import_default_declaration == NULL || Check(Token::COMMA)) {
1645 1646 1647 1648 1649
    switch (peek()) {
      case Token::MUL: {
        Consume(Token::MUL);
        ExpectContextualKeyword(CStrVector("as"), CHECK_OK);
        module_instance_binding =
1650
            ParseIdentifier(kDontAllowRestrictedIdentifiers, CHECK_OK);
1651
        // TODO(ES6): Add an appropriate declaration.
1652 1653
        break;
      }
1654

1655
      case Token::LBRACE:
1656
        named_declarations = ParseNamedImports(pos, CHECK_OK);
1657 1658 1659 1660 1661 1662 1663
        break;

      default:
        *ok = false;
        ReportUnexpectedToken(scanner()->current_token());
        return NULL;
    }
1664 1665
  }

1666
  ExpectContextualKeyword(CStrVector("from"), CHECK_OK);
1667
  const AstRawString* module_specifier = ParseModuleSpecifier(CHECK_OK);
1668 1669
  scope_->module()->AddModuleRequest(module_specifier, zone());

1670
  if (module_instance_binding != NULL) {
1671
    // TODO(ES6): Set the module specifier for the module namespace binding.
1672 1673
  }

1674 1675
  if (import_default_declaration != NULL) {
    import_default_declaration->set_module_specifier(module_specifier);
1676
  }
1677

1678 1679 1680 1681
  if (named_declarations != NULL) {
    for (int i = 0; i < named_declarations->length(); ++i) {
      named_declarations->at(i)->set_module_specifier(module_specifier);
    }
1682 1683
  }

1684
  ExpectSemicolon(CHECK_OK);
1685
  return factory()->NewEmptyStatement(pos);
1686 1687 1688
}


1689 1690 1691 1692 1693 1694
Statement* Parser::ParseExportDefault(bool* ok) {
  //  Supports the following productions, starting after the 'default' token:
  //    'export' 'default' FunctionDeclaration
  //    'export' 'default' ClassDeclaration
  //    'export' 'default' AssignmentExpression[In] ';'

1695 1696 1697 1698
  Expect(Token::DEFAULT, CHECK_OK);
  Scanner::Location default_loc = scanner()->location();

  ZoneList<const AstRawString*> names(1, zone());
1699 1700 1701 1702
  Statement* result = NULL;
  switch (peek()) {
    case Token::FUNCTION:
      // TODO(ES6): Support parsing anonymous function declarations here.
1703
      result = ParseFunctionDeclaration(&names, CHECK_OK);
1704 1705 1706 1707
      break;

    case Token::CLASS:
      // TODO(ES6): Support parsing anonymous class declarations here.
1708
      result = ParseClassDeclaration(&names, CHECK_OK);
1709 1710 1711 1712
      break;

    default: {
      int pos = peek_position();
1713 1714
      ExpressionClassifier classifier;
      Expression* expr = ParseAssignmentExpression(true, &classifier, CHECK_OK);
1715
      ValidateExpression(&classifier, CHECK_OK);
1716

1717 1718 1719 1720 1721 1722
      ExpectSemicolon(CHECK_OK);
      result = factory()->NewExpressionStatement(expr, pos);
      break;
    }
  }

1723 1724 1725 1726 1727 1728
  const AstRawString* default_string = ast_value_factory()->default_string();

  DCHECK_LE(names.length(), 1);
  if (names.length() == 1) {
    scope_->module()->AddLocalExport(default_string, names.first(), zone(), ok);
    if (!*ok) {
1729 1730
      ParserTraits::ReportMessageAt(
          default_loc, MessageTemplate::kDuplicateExport, default_string);
1731 1732 1733 1734 1735 1736
      return NULL;
    }
  } else {
    // TODO(ES6): Assign result to a const binding with the name "*default*"
    // and add an export entry with "*default*" as the local name.
  }
1737 1738 1739 1740 1741

  return result;
}


1742 1743
Statement* Parser::ParseExportDeclaration(bool* ok) {
  // ExportDeclaration:
1744 1745 1746 1747 1748
  //    'export' '*' 'from' ModuleSpecifier ';'
  //    'export' ExportClause ('from' ModuleSpecifier)? ';'
  //    'export' VariableStatement
  //    'export' Declaration
  //    'export' 'default' ... (handled in ParseExportDefault)
1749

1750
  int pos = peek_position();
1751 1752 1753
  Expect(Token::EXPORT, CHECK_OK);

  Statement* result = NULL;
1754
  ZoneList<const AstRawString*> names(1, zone());
1755
  switch (peek()) {
1756 1757 1758 1759 1760 1761
    case Token::DEFAULT:
      return ParseExportDefault(ok);

    case Token::MUL: {
      Consume(Token::MUL);
      ExpectContextualKeyword(CStrVector("from"), CHECK_OK);
1762
      const AstRawString* module_specifier = ParseModuleSpecifier(CHECK_OK);
1763
      scope_->module()->AddModuleRequest(module_specifier, zone());
1764
      // TODO(ES6): scope_->module()->AddStarExport(...)
1765
      ExpectSemicolon(CHECK_OK);
1766
      return factory()->NewEmptyStatement(pos);
1767 1768
    }

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
    case Token::LBRACE: {
      // There are two cases here:
      //
      // 'export' ExportClause ';'
      // and
      // 'export' ExportClause FromClause ';'
      //
      // In the first case, the exported identifiers in ExportClause must
      // not be reserved words, while in the latter they may be. We
      // pass in a location that gets filled with the first reserved word
      // encountered, and then throw a SyntaxError if we are in the
      // non-FromClause case.
      Scanner::Location reserved_loc = Scanner::Location::invalid();
1782 1783 1784 1785 1786
      ZoneList<const AstRawString*> export_names(1, zone());
      ZoneList<Scanner::Location> export_locations(1, zone());
      ZoneList<const AstRawString*> local_names(1, zone());
      ParseExportClause(&export_names, &export_locations, &local_names,
                        &reserved_loc, CHECK_OK);
1787
      const AstRawString* indirect_export_module_specifier = NULL;
1788
      if (CheckContextualKeyword(CStrVector("from"))) {
1789
        indirect_export_module_specifier = ParseModuleSpecifier(CHECK_OK);
1790 1791 1792
      } else if (reserved_loc.IsValid()) {
        // No FromClause, so reserved words are invalid in ExportClause.
        *ok = false;
1793
        ReportMessageAt(reserved_loc, MessageTemplate::kUnexpectedReserved);
1794
        return NULL;
1795 1796
      }
      ExpectSemicolon(CHECK_OK);
1797 1798 1799 1800 1801 1802 1803 1804 1805
      const int length = export_names.length();
      DCHECK_EQ(length, local_names.length());
      DCHECK_EQ(length, export_locations.length());
      if (indirect_export_module_specifier == NULL) {
        for (int i = 0; i < length; ++i) {
          scope_->module()->AddLocalExport(export_names[i], local_names[i],
                                           zone(), ok);
          if (!*ok) {
            ParserTraits::ReportMessageAt(export_locations[i],
1806 1807
                                          MessageTemplate::kDuplicateExport,
                                          export_names[i]);
1808 1809 1810 1811
            return NULL;
          }
        }
      } else {
1812 1813
        scope_->module()->AddModuleRequest(indirect_export_module_specifier,
                                           zone());
1814 1815 1816 1817 1818
        for (int i = 0; i < length; ++i) {
          // TODO(ES6): scope_->module()->AddIndirectExport(...);(
        }
      }
      return factory()->NewEmptyStatement(pos);
1819
    }
1820

1821 1822 1823 1824
    case Token::FUNCTION:
      result = ParseFunctionDeclaration(&names, CHECK_OK);
      break;

arv@chromium.org's avatar
arv@chromium.org committed
1825 1826 1827 1828
    case Token::CLASS:
      result = ParseClassDeclaration(&names, CHECK_OK);
      break;

1829 1830 1831
    case Token::VAR:
    case Token::LET:
    case Token::CONST:
1832
      result = ParseVariableStatement(kStatementListItem, &names, CHECK_OK);
1833 1834 1835 1836
      break;

    default:
      *ok = false;
1837
      ReportUnexpectedToken(scanner()->current_token());
1838 1839 1840
      return NULL;
  }

1841 1842
  // Extract declared names into export declarations.
  ModuleDescriptor* descriptor = scope_->module();
1843
  for (int i = 0; i < names.length(); ++i) {
1844 1845 1846
    descriptor->AddLocalExport(names[i], names[i], zone(), ok);
    if (!*ok) {
      // TODO(adamk): Possibly report this error at the right place.
1847
      ParserTraits::ReportMessage(MessageTemplate::kDuplicateExport, names[i]);
1848
      return NULL;
1849
    }
1850 1851
  }

1852
  DCHECK_NOT_NULL(result);
1853
  return result;
1854 1855 1856
}


1857 1858
Statement* Parser::ParseStatement(ZoneList<const AstRawString*>* labels,
                                  bool* ok) {
1859
  // Statement ::
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
  //   EmptyStatement
  //   ...

  if (peek() == Token::SEMICOLON) {
    Next();
    return factory()->NewEmptyStatement(RelocInfo::kNoPosition);
  }
  return ParseSubStatement(labels, ok);
}


Statement* Parser::ParseSubStatement(ZoneList<const AstRawString*>* labels,
                                     bool* ok) {
  // Statement ::
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
  //   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
1894
  // trivial labeled break statements 'label: break label' which is
1895 1896 1897 1898 1899 1900
  // parsed into an empty statement.
  switch (peek()) {
    case Token::LBRACE:
      return ParseBlock(labels, ok);

    case Token::SEMICOLON:
1901
      if (is_strong(language_mode())) {
1902 1903
        ReportMessageAt(scanner()->peek_location(),
                        MessageTemplate::kStrongEmpty);
1904 1905 1906
        *ok = false;
        return NULL;
      }
1907
      Next();
1908
      return factory()->NewEmptyStatement(RelocInfo::kNoPosition);
1909 1910

    case Token::IF:
1911
      return ParseIfStatement(labels, ok);
1912 1913

    case Token::DO:
1914
      return ParseDoWhileStatement(labels, ok);
1915 1916

    case Token::WHILE:
1917
      return ParseWhileStatement(labels, ok);
1918 1919

    case Token::FOR:
1920
      return ParseForStatement(labels, ok);
1921 1922 1923 1924

    case Token::CONTINUE:
    case Token::BREAK:
    case Token::RETURN:
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
    case Token::THROW:
    case Token::TRY: {
      // These statements must have their labels preserved in an enclosing
      // block
      if (labels == NULL) {
        return ParseStatementAsUnlabelled(labels, ok);
      } else {
        Block* result =
            factory()->NewBlock(labels, 1, false, RelocInfo::kNoPosition);
        Target target(&this->target_stack_, result);
        Statement* statement = ParseStatementAsUnlabelled(labels, CHECK_OK);
neis's avatar
neis committed
1936
        if (result) result->statements()->Add(statement, zone());
1937 1938 1939
        return result;
      }
    }
1940 1941

    case Token::WITH:
1942
      return ParseWithStatement(labels, ok);
1943 1944

    case Token::SWITCH:
1945
      return ParseSwitchStatement(labels, ok);
1946

1947
    case Token::FUNCTION: {
1948 1949 1950 1951 1952 1953 1954
      // FunctionDeclaration is only allowed in the context of SourceElements
      // (Ecma 262 5th Edition, clause 14):
      // SourceElement:
      //    Statement
      //    FunctionDeclaration
      // Common language extension is to allow function declaration in place
      // of any statement. This language extension is disabled in strict mode.
1955 1956 1957 1958
      //
      // In Harmony mode, this case also handles the extension:
      // Statement:
      //    GeneratorDeclaration
1959
      if (is_strict(language_mode())) {
1960 1961
        ReportMessageAt(scanner()->peek_location(),
                        MessageTemplate::kStrictFunction);
1962 1963 1964
        *ok = false;
        return NULL;
      }
1965
      return ParseFunctionDeclaration(NULL, ok);
1966
    }
1967 1968

    case Token::DEBUGGER:
1969
      return ParseDebuggerStatement(ok);
1970

1971 1972 1973
    case Token::VAR:
      return ParseVariableStatement(kStatement, NULL, ok);

1974 1975 1976 1977
    case Token::CONST:
      // In ES6 CONST is not allowed as a Statement, only as a
      // LexicalDeclaration, however we continue to allow it in sloppy mode for
      // backwards compatibility.
1978
      if (is_sloppy(language_mode()) && allow_legacy_const()) {
1979 1980
        return ParseVariableStatement(kStatement, NULL, ok);
      }
1981 1982

    // Fall through.
1983
    default:
1984
      return ParseExpressionOrLabelledStatement(labels, ok);
1985 1986 1987
  }
}

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
Statement* Parser::ParseStatementAsUnlabelled(
    ZoneList<const AstRawString*>* labels, bool* ok) {
  switch (peek()) {
    case Token::CONTINUE:
      return ParseContinueStatement(ok);

    case Token::BREAK:
      return ParseBreakStatement(labels, ok);

    case Token::RETURN:
      return ParseReturnStatement(ok);

    case Token::THROW:
      return ParseThrowStatement(ok);

    case Token::TRY:
      return ParseTryStatement(ok);

    default:
      UNREACHABLE();
      return NULL;
  }
}

2012

2013
VariableProxy* Parser::NewUnresolved(const AstRawString* name,
2014
                                     VariableMode mode) {
2015 2016 2017
  // If we are inside a function, a declaration of a var/const variable is a
  // truly local variable, and the scope of the variable is always the function
  // scope.
2018 2019
  // Let/const variables in harmony mode are always added to the immediately
  // enclosing scope.
2020 2021 2022
  return DeclarationScope(mode)->NewUnresolved(
      factory(), name, Variable::NORMAL, scanner()->location().beg_pos,
      scanner()->location().end_pos);
2023 2024 2025
}


2026 2027
Variable* Parser::Declare(Declaration* declaration,
                          DeclarationDescriptor::Kind declaration_kind,
2028
                          bool resolve, bool* ok, Scope* scope) {
2029
  VariableProxy* proxy = declaration->proxy();
2030
  DCHECK(proxy->raw_name() != NULL);
2031
  const AstRawString* name = proxy->raw_name();
2032
  VariableMode mode = declaration->mode();
2033 2034 2035
  if (scope == nullptr) scope = scope_;
  Scope* declaration_scope =
      IsLexicalVariableMode(mode) ? scope : scope->DeclarationScope();
2036
  Variable* var = NULL;
2037

2038
  // If a suitable scope exists, then we can statically declare this
2039 2040 2041
  // 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.
2042 2043 2044 2045
  // For instance, var declarations inside a sloppy eval scope need
  // to be added to the calling function context. Similarly, strict
  // mode eval scope and lexical eval bindings do not leak variable
  // declarations to the caller's scope so we declare all locals, too.
2046
  if (declaration_scope->is_function_scope() ||
2047
      declaration_scope->is_block_scope() ||
2048
      declaration_scope->is_module_scope() ||
2049 2050 2051 2052
      declaration_scope->is_script_scope() ||
      (declaration_scope->is_eval_scope() &&
       (is_strict(declaration_scope->language_mode()) ||
        IsLexicalVariableMode(mode)))) {
2053
    // Declare the variable in the declaration scope.
2054
    var = declaration_scope->LookupLocal(name);
2055 2056
    if (var == NULL) {
      // Declare the name.
2057
      Variable::Kind kind = Variable::NORMAL;
2058
      int declaration_group_start = -1;
2059 2060 2061 2062 2063
      if (declaration->IsFunctionDeclaration()) {
        kind = Variable::FUNCTION;
      } else if (declaration->IsVariableDeclaration() &&
                 declaration->AsVariableDeclaration()->is_class_declaration()) {
        kind = Variable::CLASS;
2064 2065
        declaration_group_start =
            declaration->AsVariableDeclaration()->declaration_group_start();
2066
      }
2067
      var = declaration_scope->DeclareLocal(
2068 2069
          name, mode, declaration->initialization(), kind, kNotAssigned,
          declaration_group_start);
2070 2071 2072 2073
    } else if (IsLexicalVariableMode(mode) ||
               IsLexicalVariableMode(var->mode()) ||
               ((mode == CONST_LEGACY || var->mode() == CONST_LEGACY) &&
                !declaration_scope->is_script_scope())) {
2074 2075
      // The name was declared in this scope before; check for conflicting
      // re-declarations. We have a conflict if either of the declarations is
2076
      // not a var (in script scope, we also have to ignore legacy const for
2077
      // compatibility). There is similar code in runtime.cc in the Declare
2078
      // functions. The function CheckConflictingVarDeclarations checks for
2079 2080
      // var and let bindings from different scopes whereas this is a check for
      // conflicting declarations within the same scope. This check also covers
2081
      // the special case
2082 2083 2084 2085 2086
      //
      // function () { let x; { var x; } }
      //
      // because the var declaration is hoisted to the function scope where 'x'
      // is already bound.
2087
      DCHECK(IsDeclaredVariableMode(var->mode()));
2088
      if (is_strict(language_mode()) || allow_harmony_sloppy()) {
2089
        // In harmony we treat re-declarations as early errors. See
2090
        // ES5 16 for a definition of early errors.
2091 2092 2093
        if (declaration_kind == DeclarationDescriptor::NORMAL) {
          ParserTraits::ReportMessage(MessageTemplate::kVarRedeclaration, name);
        } else {
2094
          ParserTraits::ReportMessage(MessageTemplate::kParamDupe);
2095
        }
2096
        *ok = false;
2097
        return nullptr;
2098
      }
2099
      Expression* expression = NewThrowSyntaxError(
2100
          MessageTemplate::kVarRedeclaration, name, declaration->position());
2101
      declaration_scope->SetIllegalRedeclaration(expression);
2102 2103
    } else if (mode == VAR) {
      var->set_maybe_assigned();
2104
    }
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
  } else if (declaration_scope->is_eval_scope() &&
             is_sloppy(declaration_scope->language_mode()) &&
             !IsLexicalVariableMode(mode)) {
    // In a var binding in a sloppy direct eval, pollute the enclosing scope
    // with this new binding by doing the following:
    // The proxy is bound to a lookup variable to force a dynamic declaration
    // using the DeclareLookupSlot runtime function.
    Variable::Kind kind = Variable::NORMAL;
    // TODO(sigurds) figure out if kNotAssigned is OK here
    var = new (zone()) Variable(declaration_scope, name, mode, kind,
                                declaration->initialization(), kNotAssigned);
    var->AllocateTo(VariableLocation::LOOKUP, -1);
    resolve = true;
2118 2119
  }

2120

2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
  // 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
2136
  // RuntimeHidden_DeclareLookupSlot calls.
2137
  declaration_scope->AddDeclaration(declaration);
2138

2139
  if (mode == CONST_LEGACY && declaration_scope->is_script_scope()) {
2140
    // For global const variables we bind the proxy to a variable.
2141
    DCHECK(resolve);  // should be set by all callers
2142
    Variable::Kind kind = Variable::NORMAL;
2143
    var = new (zone()) Variable(declaration_scope, name, mode, kind,
2144
                                kNeedsInitialization, kNotAssigned);
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
  }

  // 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.
2171 2172 2173
  if (resolve && var != NULL) {
    proxy->BindTo(var);
  }
2174
  return var;
2175 2176 2177 2178 2179 2180 2181 2182
}


// 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) {
2183
  int pos = peek_position();
2184
  Expect(Token::FUNCTION, CHECK_OK);
2185
  // Allow "eval" or "arguments" for backward compatibility.
2186 2187
  const AstRawString* name =
      ParseIdentifier(kAllowRestrictedIdentifiers, CHECK_OK);
2188 2189 2190
  Expect(Token::LPAREN, CHECK_OK);
  bool done = (peek() == Token::RPAREN);
  while (!done) {
2191
    ParseIdentifier(kAllowRestrictedIdentifiers, CHECK_OK);
2192
    done = (peek() == Token::RPAREN);
2193 2194 2195
    if (!done) {
      Expect(Token::COMMA, CHECK_OK);
    }
2196 2197 2198 2199 2200 2201 2202 2203
  }
  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.
2204
  DeclarationScope(VAR)->ForceEagerCompilation();
2205 2206 2207

  // TODO(1240846): It's weird that native function declarations are
  // introduced dynamically when we meet their declarations, whereas
2208
  // other functions are set up when entering the surrounding scope.
2209
  VariableProxy* proxy = NewUnresolved(name, VAR);
2210
  Declaration* declaration =
2211
      factory()->NewVariableDeclaration(proxy, VAR, scope_, pos);
2212
  Declare(declaration, DeclarationDescriptor::NORMAL, true, CHECK_OK);
2213 2214
  NativeFunctionLiteral* lit = factory()->NewNativeFunctionLiteral(
      name, extension_, RelocInfo::kNoPosition);
2215 2216
  return factory()->NewExpressionStatement(
      factory()->NewAssignment(
2217 2218
          Token::INIT_VAR, proxy, lit, RelocInfo::kNoPosition),
      pos);
2219 2220 2221
}


2222 2223
Statement* Parser::ParseFunctionDeclaration(
    ZoneList<const AstRawString*>* names, bool* ok) {
2224 2225
  // FunctionDeclaration ::
  //   'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
2226 2227 2228
  // GeneratorDeclaration ::
  //   'function' '*' Identifier '(' FormalParameterListopt ')'
  //      '{' FunctionBody '}'
2229
  Expect(Token::FUNCTION, CHECK_OK);
2230
  int pos = position();
wingo@igalia.com's avatar
wingo@igalia.com committed
2231
  bool is_generator = Check(Token::MUL);
2232
  bool is_strict_reserved = false;
2233
  const AstRawString* name = ParseIdentifierOrStrictReservedWord(
2234
      &is_strict_reserved, CHECK_OK);
2235 2236 2237 2238 2239

  if (fni_ != NULL) {
    fni_->Enter();
    fni_->PushEnclosingName(name);
  }
2240 2241 2242 2243 2244 2245 2246 2247
  FunctionLiteral* fun = ParseFunctionLiteral(
      name, scanner()->location(),
      is_strict_reserved ? kFunctionNameIsStrictReserved
                         : kFunctionNameValidityUnknown,
      is_generator ? FunctionKind::kGeneratorFunction
                   : FunctionKind::kNormalFunction,
      pos, FunctionLiteral::DECLARATION, FunctionLiteral::NORMAL_ARITY,
      language_mode(), CHECK_OK);
2248 2249
  if (fni_ != NULL) fni_->Leave();

2250
  // Even if we're not at the top-level of the global or a function
2251
  // scope, we treat it as such and introduce the function with its
2252
  // initial value upon entering the corresponding scope.
2253 2254
  // In ES6, a function behaves as a lexical binding, except in
  // a script scope, or the initial scope of eval or another function.
2255
  VariableMode mode =
2256 2257
      is_strong(language_mode())
          ? CONST
2258 2259 2260 2261
          : (is_strict(language_mode()) || allow_harmony_sloppy_function()) &&
                    !scope_->is_declaration_scope()
                ? LET
                : VAR;
2262
  VariableProxy* proxy = NewUnresolved(name, mode);
2263
  Declaration* declaration =
2264
      factory()->NewFunctionDeclaration(proxy, mode, fun, scope_, pos);
2265
  Declare(declaration, DeclarationDescriptor::NORMAL, true, CHECK_OK);
2266
  if (names) names->Add(name, zone());
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
  EmptyStatement* empty = factory()->NewEmptyStatement(RelocInfo::kNoPosition);
  if (is_sloppy(language_mode()) && allow_harmony_sloppy_function() &&
      !scope_->is_declaration_scope()) {
    SloppyBlockFunctionStatement* delegate =
        factory()->NewSloppyBlockFunctionStatement(empty, scope_);
    scope_->DeclarationScope()->sloppy_block_function_map()->Declare(name,
                                                                     delegate);
    return delegate;
  }
  return empty;
2277 2278 2279
}


arv@chromium.org's avatar
arv@chromium.org committed
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
Statement* Parser::ParseClassDeclaration(ZoneList<const AstRawString*>* names,
                                         bool* ok) {
  // ClassDeclaration ::
  //   'class' Identifier ('extends' LeftHandExpression)? '{' ClassBody '}'
  //
  // A ClassDeclaration
  //
  //   class C { ... }
  //
  // has the same semantics as:
  //
  //   let C = class C { ... };
  //
  // so rewrite it as such.

  Expect(Token::CLASS, CHECK_OK);
2296
  if (!allow_harmony_sloppy() && is_sloppy(language_mode())) {
2297
    ReportMessage(MessageTemplate::kSloppyLexical);
2298 2299 2300 2301
    *ok = false;
    return NULL;
  }

arv@chromium.org's avatar
arv@chromium.org committed
2302 2303 2304 2305
  int pos = position();
  bool is_strict_reserved = false;
  const AstRawString* name =
      ParseIdentifierOrStrictReservedWord(&is_strict_reserved, CHECK_OK);
2306 2307
  ClassLiteral* value = ParseClassLiteral(name, scanner()->location(),
                                          is_strict_reserved, pos, CHECK_OK);
arv@chromium.org's avatar
arv@chromium.org committed
2308

2309 2310
  VariableMode mode = is_strong(language_mode()) ? CONST : LET;
  VariableProxy* proxy = NewUnresolved(name, mode);
2311 2312
  const bool is_class_declaration = true;
  Declaration* declaration = factory()->NewVariableDeclaration(
2313 2314
      proxy, mode, scope_, pos, is_class_declaration,
      scope_->class_declaration_group_start());
2315 2316
  Variable* outer_class_variable =
      Declare(declaration, DeclarationDescriptor::NORMAL, true, CHECK_OK);
2317
  proxy->var()->set_initializer_position(position());
2318 2319 2320 2321
  // This is needed because a class ("class Name { }") creates two bindings (one
  // in the outer scope, and one in the class scope). The method is a function
  // scope inside the inner scope (class scope). The consecutive class
  // declarations are in the outer scope.
2322 2323 2324 2325 2326 2327 2328 2329 2330
  if (value->class_variable_proxy() && value->class_variable_proxy()->var() &&
      outer_class_variable->is_class()) {
    // In some cases, the outer variable is not detected as a class variable;
    // this happens e.g., for lazy methods. They are excluded from strong mode
    // checks for now. TODO(marja, rossberg): re-create variables with the
    // correct Kind and remove this hack.
    value->class_variable_proxy()
        ->var()
        ->AsClassVariable()
2331 2332
        ->set_declaration_group_start(
            outer_class_variable->AsClassVariable()->declaration_group_start());
2333
  }
arv@chromium.org's avatar
arv@chromium.org committed
2334

2335 2336
  Token::Value init_op =
      is_strong(language_mode()) ? Token::INIT_CONST : Token::INIT_LET;
arv@chromium.org's avatar
arv@chromium.org committed
2337
  Assignment* assignment = factory()->NewAssignment(init_op, proxy, value, pos);
2338 2339
  Statement* assignment_statement =
      factory()->NewExpressionStatement(assignment, RelocInfo::kNoPosition);
arv@chromium.org's avatar
arv@chromium.org committed
2340
  if (names) names->Add(name, zone());
2341
  return assignment_statement;
arv@chromium.org's avatar
arv@chromium.org committed
2342 2343 2344
}


2345
Block* Parser::ParseBlock(ZoneList<const AstRawString*>* labels, bool* ok) {
2346
  if (is_strict(language_mode()) || allow_harmony_sloppy()) {
2347 2348
    return ParseScopedBlock(labels, ok);
  }
2349

2350 2351 2352 2353 2354 2355 2356
  // Block ::
  //   '{' Statement* '}'

  // Note that a Block does not introduce a new execution scope!
  // (ECMA-262, 3rd, 12.2)
  //
  // Construct block expecting 16 statements.
2357 2358
  Block* result =
      factory()->NewBlock(labels, 16, false, RelocInfo::kNoPosition);
2359
  Target target(&this->target_stack_, result);
2360 2361 2362
  Expect(Token::LBRACE, CHECK_OK);
  while (peek() != Token::RBRACE) {
    Statement* stat = ParseStatement(NULL, CHECK_OK);
2363
    if (stat && !stat->IsEmpty()) {
neis's avatar
neis committed
2364
      result->statements()->Add(stat, zone());
2365
    }
2366 2367 2368 2369 2370 2371
  }
  Expect(Token::RBRACE, CHECK_OK);
  return result;
}


2372 2373
Block* Parser::ParseScopedBlock(ZoneList<const AstRawString*>* labels,
                                bool* ok) {
2374
  // The harmony mode uses block elements instead of statements.
2375 2376
  //
  // Block ::
2377
  //   '{' StatementList '}'
2378

2379
  // Construct block expecting 16 statements.
2380 2381
  Block* body =
      factory()->NewBlock(labels, 16, false, RelocInfo::kNoPosition);
2382
  Scope* block_scope = NewScope(scope_, BLOCK_SCOPE);
2383 2384 2385

  // Parse the statements and collect escaping labels.
  Expect(Token::LBRACE, CHECK_OK);
2386
  block_scope->set_start_position(scanner()->location().beg_pos);
2387
  { BlockState block_state(&scope_, block_scope);
2388
    Target target(&this->target_stack_, body);
2389 2390

    while (peek() != Token::RBRACE) {
2391
      Statement* stat = ParseStatementListItem(CHECK_OK);
2392
      if (stat && !stat->IsEmpty()) {
neis's avatar
neis committed
2393
        body->statements()->Add(stat, zone());
2394 2395 2396 2397
      }
    }
  }
  Expect(Token::RBRACE, CHECK_OK);
2398
  block_scope->set_end_position(scanner()->location().end_pos);
2399
  block_scope = block_scope->FinalizeBlockScope();
2400
  body->set_scope(block_scope);
2401
  return body;
2402 2403 2404
}


2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
const AstRawString* Parser::DeclarationParsingResult::SingleName() const {
  if (declarations.length() != 1) return nullptr;
  const Declaration& declaration = declarations.at(0);
  if (declaration.pattern->IsVariableProxy()) {
    return declaration.pattern->AsVariableProxy()->raw_name();
  }
  return nullptr;
}


Block* Parser::DeclarationParsingResult::BuildInitializationBlock(
    ZoneList<const AstRawString*>* names, bool* ok) {
2417 2418
  Block* result = descriptor.parser->factory()->NewBlock(
      NULL, 1, true, descriptor.declaration_pos);
2419 2420 2421 2422 2423 2424 2425 2426
  for (auto declaration : declarations) {
    PatternRewriter::DeclareAndInitializeVariables(
        result, &descriptor, &declaration, names, CHECK_OK);
  }
  return result;
}


2427
Block* Parser::ParseVariableStatement(VariableDeclarationContext var_context,
2428
                                      ZoneList<const AstRawString*>* names,
2429
                                      bool* ok) {
2430 2431 2432
  // VariableStatement ::
  //   VariableDeclarations ';'

2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
  // The scope of a var/const declared variable anywhere inside a function
  // is the entire function (ECMA-262, 3rd, 10.1.3, and 12.2). Thus we can
  // transform a source-level var/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.

  DeclarationParsingResult parsing_result;
  ParseVariableDeclarations(var_context, &parsing_result, CHECK_OK);
2447
  ExpectSemicolon(CHECK_OK);
2448 2449

  Block* result = parsing_result.BuildInitializationBlock(names, CHECK_OK);
2450 2451 2452
  return result;
}

2453

2454 2455 2456
void Parser::ParseVariableDeclarations(VariableDeclarationContext var_context,
                                       DeclarationParsingResult* parsing_result,
                                       bool* ok) {
2457
  // VariableDeclarations ::
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
  //   ('var' | 'const' | 'let') (Identifier ('=' AssignmentExpression)?)+[',']
  //
  // The ES6 Draft Rev3 specifies the following grammar for const declarations
  //
  // ConstDeclaration ::
  //   const ConstBinding (',' ConstBinding)* ';'
  // ConstBinding ::
  //   Identifier '=' AssignmentExpression
  //
  // TODO(ES6):
  // ConstBinding ::
  //   BindingPattern '=' AssignmentExpression
2470

2471
  parsing_result->descriptor.parser = this;
2472
  parsing_result->descriptor.declaration_kind = DeclarationDescriptor::NORMAL;
2473 2474
  parsing_result->descriptor.declaration_pos = peek_position();
  parsing_result->descriptor.initialization_pos = peek_position();
2475
  parsing_result->descriptor.mode = VAR;
2476 2477 2478 2479
  // True if the binding needs initialization. 'let' and 'const' declared
  // bindings are created uninitialized by their declaration nodes and
  // need initialization. 'var' declared bindings are always initialized
  // immediately by their declaration nodes.
2480 2481 2482
  parsing_result->descriptor.needs_init = false;
  parsing_result->descriptor.is_const = false;
  parsing_result->descriptor.init_op = Token::INIT_VAR;
2483
  if (peek() == Token::VAR) {
marja's avatar
marja committed
2484 2485
    if (is_strong(language_mode())) {
      Scanner::Location location = scanner()->peek_location();
2486
      ReportMessageAt(location, MessageTemplate::kStrongVar);
marja's avatar
marja committed
2487
      *ok = false;
2488
      return;
marja's avatar
marja committed
2489
    }
2490
    Consume(Token::VAR);
2491
  } else if (peek() == Token::CONST && allow_const()) {
2492
    Consume(Token::CONST);
2493
    if (is_sloppy(language_mode()) && allow_legacy_const()) {
2494 2495
      parsing_result->descriptor.mode = CONST_LEGACY;
      parsing_result->descriptor.init_op = Token::INIT_CONST_LEGACY;
2496
      ++use_counts_[v8::Isolate::kLegacyConst];
2497
    } else {
2498
      DCHECK(is_strict(language_mode()) || allow_harmony_sloppy());
2499
      DCHECK(var_context != kStatement);
2500 2501
      parsing_result->descriptor.mode = CONST;
      parsing_result->descriptor.init_op = Token::INIT_CONST;
2502
    }
2503 2504
    parsing_result->descriptor.is_const = true;
    parsing_result->descriptor.needs_init = true;
2505
  } else if (peek() == Token::LET && allow_let()) {
2506
    Consume(Token::LET);
2507
    DCHECK(var_context != kStatement);
2508 2509 2510
    parsing_result->descriptor.mode = LET;
    parsing_result->descriptor.needs_init = true;
    parsing_result->descriptor.init_op = Token::INIT_LET;
2511 2512 2513 2514
  } else {
    UNREACHABLE();  // by current callers
  }

2515 2516 2517
  parsing_result->descriptor.declaration_scope =
      DeclarationScope(parsing_result->descriptor.mode);
  parsing_result->descriptor.scope = scope_;
2518
  parsing_result->descriptor.hoist_scope = nullptr;
2519

2520

2521
  bool first_declaration = true;
2522
  int bindings_start = peek_position();
2523
  bool is_for_iteration_variable;
2524
  do {
2525 2526
    if (fni_ != NULL) fni_->Enter();

2527 2528
    // Parse name.
    if (!first_declaration) Consume(Token::COMMA);
2529

2530
    Expression* pattern;
2531 2532 2533
    {
      ExpressionClassifier pattern_classifier;
      Token::Value next = peek();
2534 2535 2536 2537 2538
      pattern = ParsePrimaryExpression(&pattern_classifier, ok);
      if (!*ok) return;
      ValidateBindingPattern(&pattern_classifier, ok);
      if (!*ok) return;
      if (!allow_harmony_destructuring() && !pattern->IsVariableProxy()) {
2539 2540
        ReportUnexpectedToken(next);
        *ok = false;
2541
        return;
2542 2543 2544
      }
    }

2545
    Scanner::Location variable_loc = scanner()->location();
2546 2547 2548 2549 2550
    const AstRawString* single_name =
        pattern->IsVariableProxy() ? pattern->AsVariableProxy()->raw_name()
                                   : nullptr;
    if (single_name != nullptr) {
      if (fni_ != NULL) fni_->PushVariableName(single_name);
2551 2552
    }

2553 2554 2555
    is_for_iteration_variable =
        var_context == kForStatement &&
        (peek() == Token::IN || PeekContextualKeyword(CStrVector("of")));
2556 2557
    if (is_for_iteration_variable && parsing_result->descriptor.mode == CONST) {
      parsing_result->descriptor.needs_init = false;
2558 2559
    }

2560
    Expression* value = NULL;
2561
    // Harmony consts have non-optional initializers.
2562 2563 2564 2565 2566
    int initializer_position = RelocInfo::kNoPosition;
    if (peek() == Token::ASSIGN || (parsing_result->descriptor.mode == CONST &&
                                    !is_for_iteration_variable)) {
      Expect(Token::ASSIGN, ok);
      if (!*ok) return;
2567 2568
      ExpressionClassifier classifier;
      value = ParseAssignmentExpression(var_context != kForStatement,
2569 2570 2571 2572
                                        &classifier, ok);
      if (!*ok) return;
      ValidateExpression(&classifier, ok);
      if (!*ok) return;
2573 2574
      variable_loc.end_pos = scanner()->location().end_pos;

2575 2576
      if (!parsing_result->first_initializer_loc.IsValid()) {
        parsing_result->first_initializer_loc = variable_loc;
2577 2578
      }

2579
      // Don't infer if it is "a = function(){...}();"-like expression.
2580 2581 2582 2583 2584 2585 2586
      if (single_name) {
        if (fni_ != NULL && value->AsCall() == NULL &&
            value->AsCallNew() == NULL) {
          fni_->Infer();
        } else {
          fni_->RemoveLastFunction();
        }
2587
      }
2588
      // End position of the initializer is after the assignment expression.
2589
      initializer_position = scanner()->location().end_pos;
2590 2591
    } else {
      // End position of the initializer is after the variable.
2592
      initializer_position = position();
2593 2594
    }

2595
    // Make sure that 'const x' and 'let x' initialize 'x' to undefined.
2596
    if (value == NULL && parsing_result->descriptor.needs_init) {
2597
      value = GetLiteralUndefined(position());
2598 2599
    }

2600
    if (single_name && fni_ != NULL) fni_->Leave();
2601 2602 2603
    parsing_result->declarations.Add(DeclarationParsingResult::Declaration(
        pattern, initializer_position, value));
    first_declaration = false;
2604 2605
  } while (peek() == Token::COMMA);

2606 2607
  parsing_result->bindings_loc =
      Scanner::Location(bindings_start, scanner()->location().end_pos);
2608 2609 2610
}


2611 2612
static bool ContainsLabel(ZoneList<const AstRawString*>* labels,
                          const AstRawString* label) {
2613
  DCHECK(label != NULL);
2614 2615
  if (labels != NULL) {
    for (int i = labels->length(); i-- > 0; ) {
2616
      if (labels->at(i) == label) {
2617
        return true;
2618 2619 2620
      }
    }
  }
2621 2622 2623 2624
  return false;
}


2625 2626
Statement* Parser::ParseExpressionOrLabelledStatement(
    ZoneList<const AstRawString*>* labels, bool* ok) {
2627 2628 2629
  // ExpressionStatement | LabelledStatement ::
  //   Expression ';'
  //   Identifier ':' Statement
2630 2631 2632 2633
  //
  // ExpressionStatement[Yield] :
  //   [lookahead ∉ {{, function, class, let [}] Expression[In, ?Yield] ;

2634 2635
  int pos = peek_position();

2636 2637 2638 2639 2640 2641 2642 2643 2644
  switch (peek()) {
    case Token::FUNCTION:
    case Token::LBRACE:
      UNREACHABLE();  // Always handled by the callers.
    case Token::CLASS:
      ReportUnexpectedToken(Next());
      *ok = false;
      return nullptr;

2645
    case Token::THIS:
2646 2647
      if (!FLAG_strong_this) break;
      // Fall through.
2648 2649
    case Token::SUPER:
      if (is_strong(language_mode()) &&
2650
          IsClassConstructor(function_state_->kind())) {
2651 2652
        bool is_this = peek() == Token::THIS;
        Expression* expr;
2653
        ExpressionClassifier classifier;
2654
        if (is_this) {
2655
          expr = ParseStrongInitializationExpression(&classifier, CHECK_OK);
2656
        } else {
2657
          expr = ParseStrongSuperCallExpression(&classifier, CHECK_OK);
2658
        }
2659
        ValidateExpression(&classifier, CHECK_OK);
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
        switch (peek()) {
          case Token::SEMICOLON:
            Consume(Token::SEMICOLON);
            break;
          case Token::RBRACE:
          case Token::EOS:
            break;
          default:
            if (!scanner()->HasAnyLineTerminatorBeforeNext()) {
              ReportMessageAt(function_state_->this_location(),
2670 2671 2672
                              is_this
                                  ? MessageTemplate::kStrongConstructorThis
                                  : MessageTemplate::kStrongConstructorSuper);
2673 2674 2675 2676 2677 2678 2679 2680
              *ok = false;
              return nullptr;
            }
        }
        return factory()->NewExpressionStatement(expr, pos);
      }
      break;

2681 2682 2683 2684
    default:
      break;
  }

2685
  bool starts_with_idenfifier = peek_any_identifier();
2686
  Expression* expr = ParseExpression(true, CHECK_OK);
2687
  if (peek() == Token::COLON && starts_with_idenfifier && expr != NULL &&
2688 2689
      expr->AsVariableProxy() != NULL &&
      !expr->AsVariableProxy()->is_this()) {
2690 2691
    // Expression is a single identifier, and not, e.g., a parenthesized
    // identifier.
2692
    VariableProxy* var = expr->AsVariableProxy();
2693
    const AstRawString* label = var->raw_name();
2694 2695 2696 2697 2698
    // 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.
2699
    if (ContainsLabel(labels, label) || TargetStackContainsLabel(label)) {
2700
      ParserTraits::ReportMessage(MessageTemplate::kLabelRedeclaration, label);
2701 2702
      *ok = false;
      return NULL;
2703
    }
2704
    if (labels == NULL) {
2705
      labels = new(zone()) ZoneList<const AstRawString*>(4, zone());
2706 2707
    }
    labels->Add(label, zone());
2708 2709 2710
    // 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.
2711
    scope_->RemoveUnresolved(var);
2712 2713 2714 2715
    Expect(Token::COLON, CHECK_OK);
    return ParseStatement(labels, ok);
  }

2716 2717 2718
  // If we have an extension, we allow a native function declaration.
  // A native function declaration starts with "native function" with
  // no line-terminator between the two words.
2719 2720
  if (extension_ != NULL && peek() == Token::FUNCTION &&
      !scanner()->HasAnyLineTerminatorBeforeNext() && expr != NULL &&
2721
      expr->AsVariableProxy() != NULL &&
2722
      expr->AsVariableProxy()->raw_name() ==
2723
          ast_value_factory()->native_string() &&
2724
      !scanner()->literal_contains_escapes()) {
2725 2726 2727
    return ParseNativeDeclaration(ok);
  }

2728 2729
  // Parsed expression statement, followed by semicolon.
  // Detect attempts at 'let' declarations in sloppy mode.
2730 2731
  if (!allow_harmony_sloppy_let() && peek() == Token::IDENTIFIER &&
      expr->AsVariableProxy() != NULL &&
2732 2733
      expr->AsVariableProxy()->raw_name() ==
          ast_value_factory()->let_string()) {
2734
    ReportMessage(MessageTemplate::kSloppyLexical, NULL);
2735 2736
    *ok = false;
    return NULL;
2737
  }
2738
  ExpectSemicolon(CHECK_OK);
2739
  return factory()->NewExpressionStatement(expr, pos);
2740 2741 2742
}


2743 2744
IfStatement* Parser::ParseIfStatement(ZoneList<const AstRawString*>* labels,
                                      bool* ok) {
2745 2746 2747
  // IfStatement ::
  //   'if' '(' Expression ')' Statement ('else' Statement)?

2748
  int pos = peek_position();
2749 2750 2751 2752
  Expect(Token::IF, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  Expression* condition = ParseExpression(true, CHECK_OK);
  Expect(Token::RPAREN, CHECK_OK);
2753
  Statement* then_statement = ParseSubStatement(labels, CHECK_OK);
2754 2755 2756
  Statement* else_statement = NULL;
  if (peek() == Token::ELSE) {
    Next();
2757
    else_statement = ParseSubStatement(labels, CHECK_OK);
2758
  } else {
2759
    else_statement = factory()->NewEmptyStatement(RelocInfo::kNoPosition);
2760
  }
2761 2762
  return factory()->NewIfStatement(
      condition, then_statement, else_statement, pos);
2763 2764 2765 2766 2767 2768 2769
}


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

2770
  int pos = peek_position();
2771
  Expect(Token::CONTINUE, CHECK_OK);
2772
  const AstRawString* label = NULL;
2773
  Token::Value tok = peek();
2774
  if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
2775
      tok != Token::SEMICOLON && tok != Token::RBRACE && tok != Token::EOS) {
2776
    // ECMA allows "eval" or "arguments" as labels even in strict mode.
2777
    label = ParseIdentifier(kAllowRestrictedIdentifiers, CHECK_OK);
2778
  }
2779
  IterationStatement* target = LookupContinueTarget(label, CHECK_OK);
2780
  if (target == NULL) {
2781
    // Illegal continue statement.
2782
    MessageTemplate::Template message = MessageTemplate::kIllegalContinue;
2783
    if (label != NULL) {
2784
      message = MessageTemplate::kUnknownLabel;
2785
    }
2786
    ParserTraits::ReportMessage(message, label);
2787 2788
    *ok = false;
    return NULL;
2789 2790
  }
  ExpectSemicolon(CHECK_OK);
2791
  return factory()->NewContinueStatement(target, pos);
2792 2793 2794
}


2795 2796
Statement* Parser::ParseBreakStatement(ZoneList<const AstRawString*>* labels,
                                       bool* ok) {
2797 2798 2799
  // BreakStatement ::
  //   'break' Identifier? ';'

2800
  int pos = peek_position();
2801
  Expect(Token::BREAK, CHECK_OK);
2802
  const AstRawString* label = NULL;
2803
  Token::Value tok = peek();
2804
  if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
2805
      tok != Token::SEMICOLON && tok != Token::RBRACE && tok != Token::EOS) {
2806
    // ECMA allows "eval" or "arguments" as labels even in strict mode.
2807
    label = ParseIdentifier(kAllowRestrictedIdentifiers, CHECK_OK);
2808
  }
2809
  // Parse labeled break statements that target themselves into
2810
  // empty statements, e.g. 'l1: l2: l3: break l2;'
2811
  if (label != NULL && ContainsLabel(labels, label)) {
2812
    ExpectSemicolon(CHECK_OK);
2813
    return factory()->NewEmptyStatement(pos);
2814 2815
  }
  BreakableStatement* target = NULL;
2816 2817
  target = LookupBreakTarget(label, CHECK_OK);
  if (target == NULL) {
2818
    // Illegal break statement.
2819
    MessageTemplate::Template message = MessageTemplate::kIllegalBreak;
2820
    if (label != NULL) {
2821
      message = MessageTemplate::kUnknownLabel;
2822
    }
2823
    ParserTraits::ReportMessage(message, label);
2824 2825
    *ok = false;
    return NULL;
2826 2827
  }
  ExpectSemicolon(CHECK_OK);
2828
  return factory()->NewBreakStatement(target, pos);
2829 2830 2831 2832 2833 2834 2835
}


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

2836
  // Consume the return token. It is necessary to do that before
2837 2838 2839
  // reporting any errors on it, because of the way errors are
  // reported (underlining).
  Expect(Token::RETURN, CHECK_OK);
2840
  Scanner::Location loc = scanner()->location();
2841
  function_state_->set_return_location(loc);
2842

2843 2844
  Token::Value tok = peek();
  Statement* result;
2845
  Expression* return_value;
2846
  if (scanner()->HasAnyLineTerminatorBeforeNext() ||
2847 2848 2849
      tok == Token::SEMICOLON ||
      tok == Token::RBRACE ||
      tok == Token::EOS) {
2850
    if (IsSubclassConstructor(function_state_->kind())) {
2851 2852 2853 2854
      return_value = ThisExpression(scope_, factory(), loc.beg_pos);
    } else {
      return_value = GetLiteralUndefined(position());
    }
2855
  } else {
2856
    if (is_strong(language_mode()) &&
2857
        IsClassConstructor(function_state_->kind())) {
2858 2859
      int pos = peek_position();
      ReportMessageAt(Scanner::Location(pos, pos + 1),
2860
                      MessageTemplate::kStrongConstructorReturnValue);
2861 2862 2863
      *ok = false;
      return NULL;
    }
2864 2865

    int pos = peek_position();
2866
    return_value = ParseExpression(true, CHECK_OK);
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877

    if (IsSubclassConstructor(function_state_->kind())) {
      // For subclass constructors we need to return this in case of undefined
      // and throw an exception in case of a non object.
      //
      //   return expr;
      //
      // Is rewritten as:
      //
      //   return (temp = expr) === undefined ? this :
      //       %_IsSpecObject(temp) ? temp : throw new TypeError(...);
2878
      Variable* temp = scope_->NewTemporary(
2879 2880 2881 2882 2883
          ast_value_factory()->empty_string());
      Assignment* assign = factory()->NewAssignment(
          Token::ASSIGN, factory()->NewVariableProxy(temp), return_value, pos);

      Expression* throw_expression =
2884
          NewThrowTypeError(MessageTemplate::kDerivedConstructorReturn,
2885 2886 2887 2888 2889 2890 2891
                            ast_value_factory()->empty_string(), pos);

      // %_IsSpecObject(temp)
      ZoneList<Expression*>* is_spec_object_args =
          new (zone()) ZoneList<Expression*>(1, zone());
      is_spec_object_args->Add(factory()->NewVariableProxy(temp), zone());
      Expression* is_spec_object_call = factory()->NewCallRuntime(
2892
          Runtime::kInlineIsSpecObject, is_spec_object_args, pos);
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908

      // %_IsSpecObject(temp) ? temp : throw_expression
      Expression* is_object_conditional = factory()->NewConditional(
          is_spec_object_call, factory()->NewVariableProxy(temp),
          throw_expression, pos);

      // temp === undefined
      Expression* is_undefined = factory()->NewCompareOperation(
          Token::EQ_STRICT, assign,
          factory()->NewUndefinedLiteral(RelocInfo::kNoPosition), pos);

      // is_undefined ? this : is_object_conditional
      return_value = factory()->NewConditional(
          is_undefined, ThisExpression(scope_, factory(), pos),
          is_object_conditional, pos);
    }
2909 2910
  }
  ExpectSemicolon(CHECK_OK);
2911

2912 2913
  if (is_generator()) {
    Expression* generator = factory()->NewVariableProxy(
2914
        function_state_->generator_object_variable());
2915
    Expression* yield = factory()->NewYield(
2916
        generator, return_value, Yield::kFinal, loc.beg_pos);
2917
    result = factory()->NewExpressionStatement(yield, loc.beg_pos);
2918
  } else {
2919
    result = factory()->NewReturnStatement(return_value, loc.beg_pos);
2920 2921
  }

2922
  Scope* decl_scope = scope_->DeclarationScope();
2923
  if (decl_scope->is_script_scope() || decl_scope->is_eval_scope()) {
2924
    ReportMessageAt(loc, MessageTemplate::kIllegalReturn);
2925 2926
    *ok = false;
    return NULL;
2927
  }
2928
  return result;
2929 2930 2931
}


2932 2933
Statement* Parser::ParseWithStatement(ZoneList<const AstRawString*>* labels,
                                      bool* ok) {
2934 2935 2936 2937
  // WithStatement ::
  //   'with' '(' Expression ')' Statement

  Expect(Token::WITH, CHECK_OK);
2938
  int pos = position();
2939

2940
  if (is_strict(language_mode())) {
2941
    ReportMessage(MessageTemplate::kStrictWith);
2942 2943 2944 2945
    *ok = false;
    return NULL;
  }

2946 2947 2948 2949
  Expect(Token::LPAREN, CHECK_OK);
  Expression* expr = ParseExpression(true, CHECK_OK);
  Expect(Token::RPAREN, CHECK_OK);

2950 2951
  scope_->DeclarationScope()->RecordWithStatement();
  Scope* with_scope = NewScope(scope_, WITH_SCOPE);
2952
  Statement* stmt;
2953
  { BlockState block_state(&scope_, with_scope);
2954
    with_scope->set_start_position(scanner()->peek_location().beg_pos);
2955
    stmt = ParseSubStatement(labels, CHECK_OK);
2956
    with_scope->set_end_position(scanner()->location().end_pos);
2957
  }
2958
  return factory()->NewWithStatement(with_scope, expr, stmt, pos);
2959 2960 2961 2962 2963
}


CaseClause* Parser::ParseCaseClause(bool* default_seen_ptr, bool* ok) {
  // CaseClause ::
2964 2965
  //   'case' Expression ':' StatementList
  //   'default' ':' StatementList
2966 2967 2968 2969 2970 2971 2972 2973

  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) {
2974
      ReportMessage(MessageTemplate::kMultipleDefaultsInSwitch);
2975 2976 2977 2978 2979 2980
      *ok = false;
      return NULL;
    }
    *default_seen_ptr = true;
  }
  Expect(Token::COLON, CHECK_OK);
2981
  int pos = position();
2982 2983
  ZoneList<Statement*>* statements =
      new(zone()) ZoneList<Statement*>(5, zone());
2984
  Statement* stat = NULL;
2985 2986 2987
  while (peek() != Token::CASE &&
         peek() != Token::DEFAULT &&
         peek() != Token::RBRACE) {
2988
    stat = ParseStatementListItem(CHECK_OK);
2989
    statements->Add(stat, zone());
2990
  }
2991 2992
  if (is_strong(language_mode()) && stat != NULL && !stat->IsJump() &&
      peek() != Token::RBRACE) {
2993 2994
    ReportMessageAt(scanner()->location(),
                    MessageTemplate::kStrongSwitchFallthrough);
2995 2996 2997
    *ok = false;
    return NULL;
  }
2998
  return factory()->NewCaseClause(label, statements, pos);
2999 3000 3001
}


3002 3003
Statement* Parser::ParseSwitchStatement(ZoneList<const AstRawString*>* labels,
                                        bool* ok) {
3004 3005
  // SwitchStatement ::
  //   'switch' '(' Expression ')' '{' CaseClause* '}'
3006 3007 3008 3009 3010 3011 3012 3013 3014
  // In order to get the CaseClauses to execute in their own lexical scope,
  // but without requiring downstream code to have special scope handling
  // code for switch statements, desugar into blocks as follows:
  // {  // To group the statements--harmless to evaluate Expression in scope
  //   .tag_variable = Expression;
  //   {  // To give CaseClauses a scope
  //     switch (.tag_variable) { CaseClause* }
  //   }
  // }
3015

3016
  Block* switch_block =
3017
      factory()->NewBlock(NULL, 2, false, RelocInfo::kNoPosition);
3018
  int switch_pos = peek_position();
3019 3020 3021 3022 3023 3024

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

3025 3026 3027 3028 3029 3030 3031
  Variable* tag_variable =
      scope_->NewTemporary(ast_value_factory()->dot_switch_tag_string());
  Assignment* tag_assign = factory()->NewAssignment(
      Token::ASSIGN, factory()->NewVariableProxy(tag_variable), tag,
      tag->position());
  Statement* tag_statement =
      factory()->NewExpressionStatement(tag_assign, RelocInfo::kNoPosition);
neis's avatar
neis committed
3032
  switch_block->statements()->Add(tag_statement, zone());
3033

3034 3035 3036
  // make statement: undefined;
  // This is needed so the tag isn't returned as the value, in case the switch
  // statements don't have a value.
neis's avatar
neis committed
3037
  switch_block->statements()->Add(
3038 3039 3040 3041 3042
      factory()->NewExpressionStatement(
          factory()->NewUndefinedLiteral(RelocInfo::kNoPosition),
          RelocInfo::kNoPosition),
      zone());

3043
  Block* cases_block =
3044
      factory()->NewBlock(NULL, 1, false, RelocInfo::kNoPosition);
3045
  Scope* cases_scope = NewScope(scope_, BLOCK_SCOPE);
3046
  cases_scope->SetNonlinear();
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066

  SwitchStatement* switch_statement =
      factory()->NewSwitchStatement(labels, switch_pos);

  cases_scope->set_start_position(scanner()->location().beg_pos);
  {
    BlockState cases_block_state(&scope_, cases_scope);
    Target target(&this->target_stack_, switch_statement);

    Expression* tag_read = factory()->NewVariableProxy(tag_variable);

    bool default_seen = false;
    ZoneList<CaseClause*>* cases =
        new (zone()) ZoneList<CaseClause*>(4, zone());
    Expect(Token::LBRACE, CHECK_OK);
    while (peek() != Token::RBRACE) {
      CaseClause* clause = ParseCaseClause(&default_seen, CHECK_OK);
      cases->Add(clause, zone());
    }
    switch_statement->Initialize(tag_read, cases);
neis's avatar
neis committed
3067
    cases_block->statements()->Add(switch_statement, zone());
3068 3069 3070
  }
  Expect(Token::RBRACE, CHECK_OK);

3071 3072 3073 3074
  cases_scope->set_end_position(scanner()->location().end_pos);
  cases_scope = cases_scope->FinalizeBlockScope();
  cases_block->set_scope(cases_scope);

neis's avatar
neis committed
3075
  switch_block->statements()->Add(cases_block, zone());
3076 3077

  return switch_block;
3078 3079 3080 3081 3082 3083 3084 3085
}


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

  Expect(Token::THROW, CHECK_OK);
3086
  int pos = position();
3087
  if (scanner()->HasAnyLineTerminatorBeforeNext()) {
3088
    ReportMessage(MessageTemplate::kNewlineAfterThrow);
3089 3090 3091 3092 3093 3094
    *ok = false;
    return NULL;
  }
  Expression* exception = ParseExpression(true, CHECK_OK);
  ExpectSemicolon(CHECK_OK);

3095 3096
  return factory()->NewExpressionStatement(
      factory()->NewThrow(exception, pos), pos);
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112
}


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);
3113
  int pos = position();
3114

3115
  Block* try_block = ParseBlock(NULL, CHECK_OK);
3116 3117 3118

  Token::Value tok = peek();
  if (tok != Token::CATCH && tok != Token::FINALLY) {
3119
    ReportMessage(MessageTemplate::kNoCatchOrFinally);
3120 3121 3122 3123
    *ok = false;
    return NULL;
  }

3124 3125
  Scope* catch_scope = NULL;
  Variable* catch_variable = NULL;
3126
  Block* catch_block = NULL;
3127
  const AstRawString* name = NULL;
3128 3129 3130 3131
  if (tok == Token::CATCH) {
    Consume(Token::CATCH);

    Expect(Token::LPAREN, CHECK_OK);
3132
    catch_scope = NewScope(scope_, CATCH_SCOPE);
3133
    catch_scope->set_start_position(scanner()->location().beg_pos);
3134
    name = ParseIdentifier(kDontAllowRestrictedIdentifiers, CHECK_OK);
3135

3136 3137
    Expect(Token::RPAREN, CHECK_OK);

3138 3139
    catch_variable = catch_scope->DeclareLocal(name, VAR, kCreatedInitialized,
                                               Variable::NORMAL);
3140
    BlockState block_state(&scope_, catch_scope);
3141 3142
    catch_block = ParseBlock(NULL, CHECK_OK);

3143
    catch_scope->set_end_position(scanner()->location().end_pos);
3144 3145 3146
    tok = peek();
  }

3147
  Block* finally_block = NULL;
3148
  DCHECK(tok == Token::FINALLY || catch_block != NULL);
3149
  if (tok == Token::FINALLY) {
3150 3151 3152 3153 3154
    Consume(Token::FINALLY);
    finally_block = ParseBlock(NULL, CHECK_OK);
  }

  // Simplify the AST nodes by converting:
3155
  //   'try B0 catch B1 finally B2'
3156
  // to:
3157
  //   'try { try B0 catch B1 } finally B2'
3158

3159
  if (catch_block != NULL && finally_block != NULL) {
3160
    // If we have both, create an inner try/catch.
3161
    DCHECK(catch_scope != NULL && catch_variable != NULL);
3162 3163 3164
    TryCatchStatement* statement =
        factory()->NewTryCatchStatement(try_block, catch_scope, catch_variable,
                                        catch_block, RelocInfo::kNoPosition);
3165
    try_block = factory()->NewBlock(NULL, 1, false, RelocInfo::kNoPosition);
neis's avatar
neis committed
3166
    try_block->statements()->Add(statement, zone());
3167
    catch_block = NULL;  // Clear to indicate it's been handled.
3168 3169 3170
  }

  TryStatement* result = NULL;
3171
  if (catch_block != NULL) {
3172 3173
    DCHECK(finally_block == NULL);
    DCHECK(catch_scope != NULL && catch_variable != NULL);
3174 3175
    result = factory()->NewTryCatchStatement(try_block, catch_scope,
                                             catch_variable, catch_block, pos);
3176
  } else {
3177
    DCHECK(finally_block != NULL);
3178
    result = factory()->NewTryFinallyStatement(try_block, finally_block, pos);
3179 3180 3181 3182 3183 3184
  }

  return result;
}


3185 3186
DoWhileStatement* Parser::ParseDoWhileStatement(
    ZoneList<const AstRawString*>* labels, bool* ok) {
3187 3188 3189
  // DoStatement ::
  //   'do' Statement 'while' '(' Expression ')' ';'

3190 3191
  DoWhileStatement* loop =
      factory()->NewDoWhileStatement(labels, peek_position());
3192
  Target target(&this->target_stack_, loop);
3193 3194

  Expect(Token::DO, CHECK_OK);
3195
  Statement* body = ParseSubStatement(NULL, CHECK_OK);
3196 3197
  Expect(Token::WHILE, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
3198

3199 3200 3201 3202 3203 3204 3205 3206 3207
  Expression* cond = ParseExpression(true, CHECK_OK);
  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);

3208
  if (loop != NULL) loop->Initialize(cond, body);
3209 3210 3211 3212
  return loop;
}


3213 3214
WhileStatement* Parser::ParseWhileStatement(
    ZoneList<const AstRawString*>* labels, bool* ok) {
3215 3216 3217
  // WhileStatement ::
  //   'while' '(' Expression ')' Statement

3218
  WhileStatement* loop = factory()->NewWhileStatement(labels, peek_position());
3219
  Target target(&this->target_stack_, loop);
3220 3221 3222 3223 3224

  Expect(Token::WHILE, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  Expression* cond = ParseExpression(true, CHECK_OK);
  Expect(Token::RPAREN, CHECK_OK);
3225
  Statement* body = ParseSubStatement(NULL, CHECK_OK);
3226

3227
  if (loop != NULL) loop->Initialize(cond, body);
3228 3229 3230 3231
  return loop;
}


3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252
// !%_IsSpecObject(result = iterator.next()) &&
//     %ThrowIteratorResultNotAnObject(result)
Expression* Parser::BuildIteratorNextResult(Expression* iterator,
                                            Variable* result, int pos) {
  Expression* next_literal = factory()->NewStringLiteral(
      ast_value_factory()->next_string(), RelocInfo::kNoPosition);
  Expression* next_property =
      factory()->NewProperty(iterator, next_literal, RelocInfo::kNoPosition);
  ZoneList<Expression*>* next_arguments =
      new (zone()) ZoneList<Expression*>(0, zone());
  Expression* next_call =
      factory()->NewCall(next_property, next_arguments, pos);
  Expression* result_proxy = factory()->NewVariableProxy(result);
  Expression* left =
      factory()->NewAssignment(Token::ASSIGN, result_proxy, next_call, pos);

  // %_IsSpecObject(...)
  ZoneList<Expression*>* is_spec_object_args =
      new (zone()) ZoneList<Expression*>(1, zone());
  is_spec_object_args->Add(left, zone());
  Expression* is_spec_object_call = factory()->NewCallRuntime(
3253
      Runtime::kInlineIsSpecObject, is_spec_object_args, pos);
3254 3255 3256 3257 3258 3259 3260

  // %ThrowIteratorResultNotAnObject(result)
  Expression* result_proxy_again = factory()->NewVariableProxy(result);
  ZoneList<Expression*>* throw_arguments =
      new (zone()) ZoneList<Expression*>(1, zone());
  throw_arguments->Add(result_proxy_again, zone());
  Expression* throw_call = factory()->NewCallRuntime(
3261
      Runtime::kThrowIteratorResultNotAnObject, throw_arguments, pos);
3262 3263 3264 3265 3266 3267 3268 3269

  return factory()->NewBinaryOperation(
      Token::AND,
      factory()->NewUnaryOperation(Token::NOT, is_spec_object_call, pos),
      throw_call, pos);
}


3270 3271 3272 3273 3274 3275 3276
void Parser::InitializeForEachStatement(ForEachStatement* stmt,
                                        Expression* each,
                                        Expression* subject,
                                        Statement* body) {
  ForOfStatement* for_of = stmt->AsForOfStatement();

  if (for_of != NULL) {
3277
    Variable* iterator = scope_->NewTemporary(
3278
        ast_value_factory()->dot_iterator_string());
3279
    Variable* result = scope_->NewTemporary(
3280
        ast_value_factory()->dot_result_string());
3281 3282 3283 3284 3285 3286

    Expression* assign_iterator;
    Expression* next_result;
    Expression* result_done;
    Expression* assign_each;

3287
    // iterator = subject[Symbol.iterator]()
3288 3289
    assign_iterator = factory()->NewAssignment(
        Token::ASSIGN, factory()->NewVariableProxy(iterator),
3290
        GetIterator(subject, factory()), subject->position());
3291

3292 3293
    // !%_IsSpecObject(result = iterator.next()) &&
    //     %ThrowIteratorResultNotAnObject(result)
3294
    {
3295
      // result = iterator.next()
3296
      Expression* iterator_proxy = factory()->NewVariableProxy(iterator);
3297 3298
      next_result =
          BuildIteratorNextResult(iterator_proxy, result, subject->position());
3299 3300 3301 3302
    }

    // result.done
    {
3303
      Expression* done_literal = factory()->NewStringLiteral(
3304
          ast_value_factory()->done_string(), RelocInfo::kNoPosition);
3305 3306 3307 3308 3309 3310 3311
      Expression* result_proxy = factory()->NewVariableProxy(result);
      result_done = factory()->NewProperty(
          result_proxy, done_literal, RelocInfo::kNoPosition);
    }

    // each = result.value
    {
3312
      Expression* value_literal = factory()->NewStringLiteral(
3313
          ast_value_factory()->value_string(), RelocInfo::kNoPosition);
3314 3315 3316
      Expression* result_proxy = factory()->NewVariableProxy(result);
      Expression* result_value = factory()->NewProperty(
          result_proxy, value_literal, RelocInfo::kNoPosition);
3317
      assign_each = factory()->NewAssignment(Token::ASSIGN, each, result_value,
3318
                                             RelocInfo::kNoPosition);
3319 3320 3321
    }

    for_of->Initialize(each, subject, body,
3322 3323 3324 3325
                       assign_iterator,
                       next_result,
                       result_done,
                       assign_each);
3326 3327 3328 3329 3330 3331
  } else {
    stmt->Initialize(each, subject, body);
  }
}


rossberg's avatar
rossberg committed
3332 3333
Statement* Parser::DesugarLexicalBindingsInForStatement(
    Scope* inner_scope, bool is_const, ZoneList<const AstRawString*>* names,
3334 3335
    ForStatement* loop, Statement* init, Expression* cond, Statement* next,
    Statement* body, bool* ok) {
3336 3337 3338 3339 3340 3341 3342
  // ES6 13.6.3.4 specifies that on each loop iteration the let variables are
  // copied into a new environment. After copying, the "next" statement of the
  // loop is executed to update the loop variables. The loop condition is
  // checked and the loop body is executed.
  //
  // We rewrite a for statement of the form
  //
rossberg's avatar
rossberg committed
3343
  //  labels: for (let/const x = i; cond; next) body
3344 3345 3346 3347
  //
  // into
  //
  //  {
rossberg's avatar
rossberg committed
3348
  //    let/const x = i;
3349 3350
  //    temp_x = x;
  //    first = 1;
3351
  //    undefined;
3352
  //    outer: for (;;) {
3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
  //      { // This block's only function is to ensure that the statements it
  //        // contains do not affect the normal completion value. This is
  //        // accomplished by setting its ignore_completion_value bit.
  //        // No new lexical scope is introduced, so lexically scoped variables
  //        // declared here will be scoped to the outer for loop.
  //        let/const x = temp_x;
  //        if (first == 1) {
  //          first = 0;
  //        } else {
  //          next;
  //        }
  //        flag = 1;
3365 3366
  //      }
  //      labels: for (; flag == 1; flag = 0, temp_x = x) {
3367
  //        if (cond) {
3368
  //          body
3369
  //        } else {
3370
  //          break outer;
3371
  //        }
3372 3373 3374 3375 3376
  //      }
  //      if (flag == 1) {
  //        break;
  //      }
  //    }
3377 3378
  //  }

3379
  DCHECK(names->length() > 0);
3380 3381 3382 3383 3384
  Scope* for_scope = scope_;
  ZoneList<Variable*> temps(names->length(), zone());

  Block* outer_block = factory()->NewBlock(NULL, names->length() + 3, false,
                                           RelocInfo::kNoPosition);
3385

rossberg's avatar
rossberg committed
3386
  // Add statement: let/const x = i.
neis's avatar
neis committed
3387
  outer_block->statements()->Add(init, zone());
3388

3389
  const AstRawString* temp_name = ast_value_factory()->dot_for_string();
3390

rossberg's avatar
rossberg committed
3391
  // For each lexical variable x:
3392 3393
  //   make statement: temp_x = x.
  for (int i = 0; i < names->length(); i++) {
3394
    VariableProxy* proxy = NewUnresolved(names->at(i), LET);
3395
    Variable* temp = scope_->NewTemporary(temp_name);
3396 3397 3398 3399 3400
    VariableProxy* temp_proxy = factory()->NewVariableProxy(temp);
    Assignment* assignment = factory()->NewAssignment(
        Token::ASSIGN, temp_proxy, proxy, RelocInfo::kNoPosition);
    Statement* assignment_statement = factory()->NewExpressionStatement(
        assignment, RelocInfo::kNoPosition);
neis's avatar
neis committed
3401
    outer_block->statements()->Add(assignment_statement, zone());
3402 3403 3404
    temps.Add(temp, zone());
  }

3405 3406 3407
  Variable* first = NULL;
  // Make statement: first = 1.
  if (next) {
3408
    first = scope_->NewTemporary(temp_name);
3409
    VariableProxy* first_proxy = factory()->NewVariableProxy(first);
3410
    Expression* const1 = factory()->NewSmiLiteral(1, RelocInfo::kNoPosition);
3411
    Assignment* assignment = factory()->NewAssignment(
3412 3413 3414
        Token::ASSIGN, first_proxy, const1, RelocInfo::kNoPosition);
    Statement* assignment_statement =
        factory()->NewExpressionStatement(assignment, RelocInfo::kNoPosition);
neis's avatar
neis committed
3415
    outer_block->statements()->Add(assignment_statement, zone());
3416 3417
  }

3418
  // make statement: undefined;
neis's avatar
neis committed
3419
  outer_block->statements()->Add(
3420 3421 3422 3423 3424
      factory()->NewExpressionStatement(
          factory()->NewUndefinedLiteral(RelocInfo::kNoPosition),
          RelocInfo::kNoPosition),
      zone());

3425 3426 3427 3428 3429 3430 3431
  // Make statement: outer: for (;;)
  // Note that we don't actually create the label, or set this loop up as an
  // explicit break target, instead handing it directly to those nodes that
  // need to know about it. This should be safe because we don't run any code
  // in this function that looks up break targets.
  ForStatement* outer_loop =
      factory()->NewForStatement(NULL, RelocInfo::kNoPosition);
neis's avatar
neis committed
3432
  outer_block->statements()->Add(outer_loop, zone());
3433

3434 3435 3436
  outer_block->set_scope(for_scope);
  scope_ = inner_scope;

3437 3438 3439 3440
  Block* inner_block =
      factory()->NewBlock(NULL, 3, false, RelocInfo::kNoPosition);
  Block* ignore_completion_block = factory()->NewBlock(
      NULL, names->length() + 2, true, RelocInfo::kNoPosition);
3441 3442
  ZoneList<Variable*> inner_vars(names->length(), zone());
  // For each let variable x:
rossberg's avatar
rossberg committed
3443 3444
  //    make statement: let/const x = temp_x.
  VariableMode mode = is_const ? CONST : LET;
3445
  for (int i = 0; i < names->length(); i++) {
rossberg's avatar
rossberg committed
3446
    VariableProxy* proxy = NewUnresolved(names->at(i), mode);
3447
    Declaration* declaration = factory()->NewVariableDeclaration(
rossberg's avatar
rossberg committed
3448
        proxy, mode, scope_, RelocInfo::kNoPosition);
3449
    Declare(declaration, DeclarationDescriptor::NORMAL, true, CHECK_OK);
3450 3451
    inner_vars.Add(declaration->proxy()->var(), zone());
    VariableProxy* temp_proxy = factory()->NewVariableProxy(temps.at(i));
3452 3453 3454
    Assignment* assignment =
        factory()->NewAssignment(is_const ? Token::INIT_CONST : Token::INIT_LET,
                                 proxy, temp_proxy, RelocInfo::kNoPosition);
3455 3456
    Statement* assignment_statement =
        factory()->NewExpressionStatement(assignment, RelocInfo::kNoPosition);
3457
    DCHECK(init->position() != RelocInfo::kNoPosition);
3458
    proxy->var()->set_initializer_position(init->position());
neis's avatar
neis committed
3459
    ignore_completion_block->statements()->Add(assignment_statement, zone());
3460 3461
  }

3462
  // Make statement: if (first == 1) { first = 0; } else { next; }
3463
  if (next) {
3464
    DCHECK(first);
3465
    Expression* compare = NULL;
3466
    // Make compare expression: first == 1.
3467
    {
3468
      Expression* const1 = factory()->NewSmiLiteral(1, RelocInfo::kNoPosition);
3469
      VariableProxy* first_proxy = factory()->NewVariableProxy(first);
3470 3471
      compare = factory()->NewCompareOperation(Token::EQ, first_proxy, const1,
                                               RelocInfo::kNoPosition);
3472
    }
3473 3474
    Statement* clear_first = NULL;
    // Make statement: first = 0.
3475
    {
3476
      VariableProxy* first_proxy = factory()->NewVariableProxy(first);
3477
      Expression* const0 = factory()->NewSmiLiteral(0, RelocInfo::kNoPosition);
3478
      Assignment* assignment = factory()->NewAssignment(
3479 3480 3481
          Token::ASSIGN, first_proxy, const0, RelocInfo::kNoPosition);
      clear_first =
          factory()->NewExpressionStatement(assignment, RelocInfo::kNoPosition);
3482
    }
3483 3484
    Statement* clear_first_or_next = factory()->NewIfStatement(
        compare, clear_first, next, RelocInfo::kNoPosition);
neis's avatar
neis committed
3485
    ignore_completion_block->statements()->Add(clear_first_or_next, zone());
3486 3487
  }

3488
  Variable* flag = scope_->NewTemporary(temp_name);
3489 3490 3491 3492 3493 3494 3495 3496
  // Make statement: flag = 1.
  {
    VariableProxy* flag_proxy = factory()->NewVariableProxy(flag);
    Expression* const1 = factory()->NewSmiLiteral(1, RelocInfo::kNoPosition);
    Assignment* assignment = factory()->NewAssignment(
        Token::ASSIGN, flag_proxy, const1, RelocInfo::kNoPosition);
    Statement* assignment_statement =
        factory()->NewExpressionStatement(assignment, RelocInfo::kNoPosition);
neis's avatar
neis committed
3497
    ignore_completion_block->statements()->Add(assignment_statement, zone());
3498
  }
neis's avatar
neis committed
3499
  inner_block->statements()->Add(ignore_completion_block, zone());
3500 3501 3502 3503 3504
  // Make cond expression for main loop: flag == 1.
  Expression* flag_cond = NULL;
  {
    Expression* const1 = factory()->NewSmiLiteral(1, RelocInfo::kNoPosition);
    VariableProxy* flag_proxy = factory()->NewVariableProxy(flag);
3505 3506
    flag_cond = factory()->NewCompareOperation(Token::EQ, flag_proxy, const1,
                                               RelocInfo::kNoPosition);
3507 3508
  }

3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
  // Create chain of expressions "flag = 0, temp_x = x, ..."
  Statement* compound_next_statement = NULL;
  {
    Expression* compound_next = NULL;
    // Make expression: flag = 0.
    {
      VariableProxy* flag_proxy = factory()->NewVariableProxy(flag);
      Expression* const0 = factory()->NewSmiLiteral(0, RelocInfo::kNoPosition);
      compound_next = factory()->NewAssignment(Token::ASSIGN, flag_proxy,
                                               const0, RelocInfo::kNoPosition);
    }
3520

3521
    // Make the comma-separated list of temp_x = x assignments.
3522
    int inner_var_proxy_pos = scanner()->location().beg_pos;
3523 3524
    for (int i = 0; i < names->length(); i++) {
      VariableProxy* temp_proxy = factory()->NewVariableProxy(temps.at(i));
3525 3526
      VariableProxy* proxy =
          factory()->NewVariableProxy(inner_vars.at(i), inner_var_proxy_pos);
3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
      Assignment* assignment = factory()->NewAssignment(
          Token::ASSIGN, temp_proxy, proxy, RelocInfo::kNoPosition);
      compound_next = factory()->NewBinaryOperation(
          Token::COMMA, compound_next, assignment, RelocInfo::kNoPosition);
    }

    compound_next_statement = factory()->NewExpressionStatement(
        compound_next, RelocInfo::kNoPosition);
  }

  // Make statement: if (cond) { body; } else { break outer; }
  Statement* body_or_stop = body;
3539
  if (cond) {
3540 3541 3542 3543
    Statement* stop =
        factory()->NewBreakStatement(outer_loop, RelocInfo::kNoPosition);
    body_or_stop =
        factory()->NewIfStatement(cond, body, stop, cond->position());
3544 3545
  }

3546
  // Make statement: labels: for (; flag == 1; flag = 0, temp_x = x)
3547
  // Note that we re-use the original loop node, which retains its labels
3548 3549 3550
  // and ensures that any break or continue statements in body point to
  // the right place.
  loop->Initialize(NULL, flag_cond, compound_next_statement, body_or_stop);
neis's avatar
neis committed
3551
  inner_block->statements()->Add(loop, zone());
3552

3553 3554 3555 3556 3557 3558 3559
  // Make statement: if (flag == 1) { break; }
  {
    Expression* compare = NULL;
    // Make compare expresion: flag == 1.
    {
      Expression* const1 = factory()->NewSmiLiteral(1, RelocInfo::kNoPosition);
      VariableProxy* flag_proxy = factory()->NewVariableProxy(flag);
3560 3561
      compare = factory()->NewCompareOperation(Token::EQ, flag_proxy, const1,
                                               RelocInfo::kNoPosition);
3562 3563 3564 3565 3566 3567
    }
    Statement* stop =
        factory()->NewBreakStatement(outer_loop, RelocInfo::kNoPosition);
    Statement* empty = factory()->NewEmptyStatement(RelocInfo::kNoPosition);
    Statement* if_flag_break =
        factory()->NewIfStatement(compare, stop, empty, RelocInfo::kNoPosition);
neis's avatar
neis committed
3568
    inner_block->statements()->Add(if_flag_break, zone());
3569 3570 3571 3572 3573 3574
  }

  inner_scope->set_end_position(scanner()->location().end_pos);
  inner_block->set_scope(inner_scope);
  scope_ = for_scope;

3575
  outer_loop->Initialize(NULL, NULL, NULL, inner_block);
3576 3577 3578 3579
  return outer_block;
}


3580 3581
Statement* Parser::ParseForStatement(ZoneList<const AstRawString*>* labels,
                                     bool* ok) {
3582 3583 3584
  // ForStatement ::
  //   'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement

3585
  int stmt_pos = peek_position();
rossberg's avatar
rossberg committed
3586
  bool is_const = false;
3587
  Statement* init = NULL;
rossberg's avatar
rossberg committed
3588
  ZoneList<const AstRawString*> lexical_bindings(1, zone());
3589

3590
  // Create an in-between scope for let-bound iteration variables.
3591 3592 3593
  Scope* saved_scope = scope_;
  Scope* for_scope = NewScope(scope_, BLOCK_SCOPE);
  scope_ = for_scope;
3594 3595
  Expect(Token::FOR, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
3596
  for_scope->set_start_position(scanner()->location().beg_pos);
3597
  bool is_let_identifier_expression = false;
3598
  DeclarationParsingResult parsing_result;
3599
  if (peek() != Token::SEMICOLON) {
3600
    if (peek() == Token::VAR || (peek() == Token::CONST && allow_const()) ||
littledan's avatar
littledan committed
3601
        (peek() == Token::LET && IsNextLetKeyword())) {
3602
      ParseVariableDeclarations(kForStatement, &parsing_result, CHECK_OK);
3603
      is_const = parsing_result.descriptor.mode == CONST;
3604 3605

      int num_decl = parsing_result.declarations.length();
3606
      bool accept_IN = num_decl >= 1;
3607
      bool accept_OF = true;
3608
      ForEachStatement::VisitMode mode;
3609 3610
      int each_beg_pos = scanner()->location().beg_pos;
      int each_end_pos = scanner()->location().end_pos;
3611

3612
      if (accept_IN && CheckInOrOf(accept_OF, &mode, ok)) {
rossberg's avatar
rossberg committed
3613
        if (!*ok) return nullptr;
3614 3615 3616
        if (num_decl != 1) {
          const char* loop_type =
              mode == ForEachStatement::ITERATE ? "for-of" : "for-in";
3617 3618 3619
          ParserTraits::ReportMessageAt(
              parsing_result.bindings_loc,
              MessageTemplate::kForInOfLoopMultiBindings, loop_type);
3620 3621 3622
          *ok = false;
          return nullptr;
        }
3623
        if (parsing_result.first_initializer_loc.IsValid() &&
littledan's avatar
littledan committed
3624 3625
            (is_strict(language_mode()) || mode == ForEachStatement::ITERATE ||
             IsLexicalVariableMode(parsing_result.descriptor.mode))) {
3626
          if (mode == ForEachStatement::ITERATE) {
3627
            ReportMessageAt(parsing_result.first_initializer_loc,
3628
                            MessageTemplate::kForOfLoopInitializer);
3629 3630
          } else {
            // TODO(caitp): This should be an error in sloppy mode too.
3631
            ReportMessageAt(parsing_result.first_initializer_loc,
3632
                            MessageTemplate::kForInLoopInitializer);
3633 3634 3635 3636
          }
          *ok = false;
          return nullptr;
        }
3637

3638 3639 3640 3641
        DCHECK(parsing_result.declarations.length() == 1);
        Block* init_block = nullptr;

        // special case for legacy for (var/const x =.... in)
3642
        if (!IsLexicalVariableMode(parsing_result.descriptor.mode) &&
3643 3644 3645 3646 3647 3648
            parsing_result.declarations[0].initializer != nullptr) {
          VariableProxy* single_var = scope_->NewUnresolved(
              factory(), parsing_result.SingleName(), Variable::NORMAL,
              each_beg_pos, each_end_pos);
          init_block = factory()->NewBlock(
              nullptr, 2, true, parsing_result.descriptor.declaration_pos);
neis's avatar
neis committed
3649
          init_block->statements()->Add(
3650 3651 3652 3653 3654 3655 3656
              factory()->NewExpressionStatement(
                  factory()->NewAssignment(
                      Token::ASSIGN, single_var,
                      parsing_result.declarations[0].initializer,
                      RelocInfo::kNoPosition),
                  RelocInfo::kNoPosition),
              zone());
3657
        }
3658 3659

        // Rewrite a for-in/of statement of the form
3660
        //
3661
        //   for (let/const/var x in/of e) b
3662 3663 3664
        //
        // into
        //
3665 3666 3667 3668 3669 3670 3671 3672
        //   {
        //     <let x' be a temporary variable>
        //     for (x' in/of e) {
        //       let/const/var x;
        //       x = x';
        //       b;
        //     }
        //     let x;  // for TDZ
3673 3674
        //   }

3675
        Variable* temp = scope_->NewTemporary(
3676
            ast_value_factory()->dot_for_string());
3677
        ForEachStatement* loop =
3678
            factory()->NewForEachStatement(mode, labels, stmt_pos);
3679 3680 3681
        Target target(&this->target_stack_, loop);

        Expression* enumerable = ParseExpression(true, CHECK_OK);
3682

3683 3684
        Expect(Token::RPAREN, CHECK_OK);

3685 3686 3687 3688
        Scope* body_scope = NewScope(scope_, BLOCK_SCOPE);
        body_scope->set_start_position(scanner()->location().beg_pos);
        scope_ = body_scope;

3689
        Statement* body = ParseSubStatement(NULL, CHECK_OK);
3690

3691 3692
        Block* body_block =
            factory()->NewBlock(NULL, 3, false, RelocInfo::kNoPosition);
3693

3694 3695
        auto each_initialization_block =
            factory()->NewBlock(nullptr, 1, true, RelocInfo::kNoPosition);
3696 3697 3698 3699
        {
          DCHECK(parsing_result.declarations.length() == 1);
          DeclarationParsingResult::Declaration decl =
              parsing_result.declarations[0];
3700 3701
          auto descriptor = parsing_result.descriptor;
          descriptor.declaration_pos = RelocInfo::kNoPosition;
3702
          descriptor.initialization_pos = RelocInfo::kNoPosition;
3703 3704
          decl.initializer = factory()->NewVariableProxy(temp);

3705
          PatternRewriter::DeclareAndInitializeVariables(
3706 3707 3708 3709
              each_initialization_block, &descriptor, &decl,
              IsLexicalVariableMode(descriptor.mode) ? &lexical_bindings
                                                     : nullptr,
              CHECK_OK);
3710 3711
        }

neis's avatar
neis committed
3712 3713
        body_block->statements()->Add(each_initialization_block, zone());
        body_block->statements()->Add(body, zone());
3714 3715
        VariableProxy* temp_proxy =
            factory()->NewVariableProxy(temp, each_beg_pos, each_end_pos);
3716
        InitializeForEachStatement(loop, temp_proxy, enumerable, body_block);
3717 3718 3719 3720 3721 3722 3723 3724
        scope_ = for_scope;
        body_scope->set_end_position(scanner()->location().end_pos);
        body_scope = body_scope->FinalizeBlockScope();
        if (body_scope != nullptr) {
          body_block->set_scope(body_scope);
        }

        // Create a TDZ for any lexically-bound names.
3725
        if (IsLexicalVariableMode(parsing_result.descriptor.mode)) {
3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
          DCHECK_NULL(init_block);

          init_block =
              factory()->NewBlock(nullptr, 1, false, RelocInfo::kNoPosition);

          for (int i = 0; i < lexical_bindings.length(); ++i) {
            // TODO(adamk): This needs to be some sort of special
            // INTERNAL variable that's invisible to the debugger
            // but visible to everything else.
            VariableProxy* tdz_proxy = NewUnresolved(lexical_bindings[i], LET);
            Declaration* tdz_decl = factory()->NewVariableDeclaration(
                tdz_proxy, LET, scope_, RelocInfo::kNoPosition);
            Variable* tdz_var = Declare(tdz_decl, DeclarationDescriptor::NORMAL,
                                        true, CHECK_OK);
            tdz_var->set_initializer_position(position());
          }
        }

3744
        scope_ = saved_scope;
3745
        for_scope->set_end_position(scanner()->location().end_pos);
3746
        for_scope = for_scope->FinalizeBlockScope();
3747 3748
        // Parsed for-in loop w/ variable declarations.
        if (init_block != nullptr) {
neis's avatar
neis committed
3749
          init_block->statements()->Add(loop, zone());
3750 3751 3752
          if (for_scope != nullptr) {
            init_block->set_scope(for_scope);
          }
3753 3754
          return init_block;
        } else {
3755
          DCHECK_NULL(for_scope);
3756 3757
          return loop;
        }
3758
      } else {
3759 3760 3761 3762 3763
        init = parsing_result.BuildInitializationBlock(
            IsLexicalVariableMode(parsing_result.descriptor.mode)
                ? &lexical_bindings
                : nullptr,
            CHECK_OK);
3764
      }
3765
    } else {
3766
      int lhs_beg_pos = peek_position();
3767
      Expression* expression = ParseExpression(false, CHECK_OK);
3768
      int lhs_end_pos = scanner()->location().end_pos;
3769
      ForEachStatement::VisitMode mode;
3770
      bool accept_OF = expression->IsVariableProxy();
3771
      is_let_identifier_expression =
3772 3773 3774
          expression->IsVariableProxy() &&
          expression->AsVariableProxy()->raw_name() ==
              ast_value_factory()->let_string();
3775

rossberg's avatar
rossberg committed
3776 3777
      if (CheckInOrOf(accept_OF, &mode, ok)) {
        if (!*ok) return nullptr;
3778
        expression = this->CheckAndRewriteReferenceExpression(
3779
            expression, lhs_beg_pos, lhs_end_pos,
3780
            MessageTemplate::kInvalidLhsInFor, kSyntaxError, CHECK_OK);
3781

3782
        ForEachStatement* loop =
3783
            factory()->NewForEachStatement(mode, labels, stmt_pos);
3784
        Target target(&this->target_stack_, loop);
3785 3786 3787 3788

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

3789
        Statement* body = ParseSubStatement(NULL, CHECK_OK);
3790
        InitializeForEachStatement(loop, expression, enumerable, body);
3791
        scope_ = saved_scope;
3792
        for_scope->set_end_position(scanner()->location().end_pos);
3793
        for_scope = for_scope->FinalizeBlockScope();
3794
        DCHECK(for_scope == NULL);
3795 3796 3797 3798
        // Parsed for-in loop.
        return loop;

      } else {
3799
        init = factory()->NewExpressionStatement(expression, lhs_beg_pos);
3800 3801 3802 3803 3804
      }
    }
  }

  // Standard 'for' loop
3805
  ForStatement* loop = factory()->NewForStatement(labels, stmt_pos);
3806
  Target target(&this->target_stack_, loop);
3807 3808

  // Parsed initializer at this point.
3809
  // Detect attempts at 'let' declarations in sloppy mode.
3810 3811
  if (!allow_harmony_sloppy_let() && peek() == Token::IDENTIFIER &&
      is_sloppy(language_mode()) && is_let_identifier_expression) {
3812
    ReportMessage(MessageTemplate::kSloppyLexical, NULL);
3813 3814 3815
    *ok = false;
    return NULL;
  }
3816 3817
  Expect(Token::SEMICOLON, CHECK_OK);

3818 3819 3820
  // If there are let bindings, then condition and the next statement of the
  // for loop must be parsed in a new scope.
  Scope* inner_scope = NULL;
rossberg's avatar
rossberg committed
3821
  if (lexical_bindings.length() > 0) {
3822 3823 3824 3825 3826
    inner_scope = NewScope(for_scope, BLOCK_SCOPE);
    inner_scope->set_start_position(scanner()->location().beg_pos);
    scope_ = inner_scope;
  }

3827 3828 3829 3830 3831 3832 3833 3834 3835
  Expression* cond = NULL;
  if (peek() != Token::SEMICOLON) {
    cond = ParseExpression(true, CHECK_OK);
  }
  Expect(Token::SEMICOLON, CHECK_OK);

  Statement* next = NULL;
  if (peek() != Token::RPAREN) {
    Expression* exp = ParseExpression(true, CHECK_OK);
3836
    next = factory()->NewExpressionStatement(exp, exp->position());
3837 3838 3839
  }
  Expect(Token::RPAREN, CHECK_OK);

3840
  Statement* body = ParseSubStatement(NULL, CHECK_OK);
3841 3842

  Statement* result = NULL;
rossberg's avatar
rossberg committed
3843
  if (lexical_bindings.length() > 0) {
3844
    scope_ = for_scope;
rossberg's avatar
rossberg committed
3845 3846 3847
    result = DesugarLexicalBindingsInForStatement(
                 inner_scope, is_const, &lexical_bindings, loop, init, cond,
                 next, body, CHECK_OK);
3848 3849
    scope_ = saved_scope;
    for_scope->set_end_position(scanner()->location().end_pos);
3850
  } else {
3851 3852
    scope_ = saved_scope;
    for_scope->set_end_position(scanner()->location().end_pos);
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863
    for_scope = for_scope->FinalizeBlockScope();
    if (for_scope) {
      // Rewrite a for statement of the form
      //   for (const x = i; c; n) b
      //
      // into
      //
      //   {
      //     const x = i;
      //     for (; c; n) b
      //   }
3864
      DCHECK(init != NULL);
3865 3866
      Block* block =
          factory()->NewBlock(NULL, 2, false, RelocInfo::kNoPosition);
neis's avatar
neis committed
3867 3868
      block->statements()->Add(init, zone());
      block->statements()->Add(loop, zone());
3869 3870 3871 3872 3873 3874 3875
      block->set_scope(for_scope);
      loop->Initialize(NULL, cond, next, body);
      result = block;
    } else {
      loop->Initialize(init, cond, next, body);
      result = loop;
    }
3876
  }
3877
  return result;
3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
}


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

3888
  int pos = peek_position();
3889 3890
  Expect(Token::DEBUGGER, CHECK_OK);
  ExpectSemicolon(CHECK_OK);
3891
  return factory()->NewDebuggerStatement(pos);
3892 3893 3894
}


3895
bool CompileTimeValue::IsCompileTimeValue(Expression* expression) {
3896
  if (expression->IsLiteral()) return true;
3897 3898 3899 3900
  MaterializedLiteral* lit = expression->AsMaterializedLiteral();
  return lit != NULL && lit->is_simple();
}

3901

3902 3903 3904
Handle<FixedArray> CompileTimeValue::GetValue(Isolate* isolate,
                                              Expression* expression) {
  Factory* factory = isolate->factory();
3905
  DCHECK(IsCompileTimeValue(expression));
3906
  Handle<FixedArray> result = factory->NewFixedArray(2, TENURED);
3907 3908
  ObjectLiteral* object_literal = expression->AsObjectLiteral();
  if (object_literal != NULL) {
3909
    DCHECK(object_literal->is_simple());
3910
    if (object_literal->fast_elements()) {
3911
      result->set(kLiteralTypeSlot, Smi::FromInt(OBJECT_LITERAL_FAST_ELEMENTS));
3912
    } else {
3913
      result->set(kLiteralTypeSlot, Smi::FromInt(OBJECT_LITERAL_SLOW_ELEMENTS));
3914
    }
3915 3916 3917
    result->set(kElementsSlot, *object_literal->constant_properties());
  } else {
    ArrayLiteral* array_literal = expression->AsArrayLiteral();
3918
    DCHECK(array_literal != NULL && array_literal->is_simple());
3919
    result->set(kLiteralTypeSlot, Smi::FromInt(ARRAY_LITERAL));
3920
    result->set(kElementsSlot, *array_literal->constant_elements());
3921 3922 3923 3924 3925
  }
  return result;
}


3926 3927 3928 3929
CompileTimeValue::LiteralType CompileTimeValue::GetLiteralType(
    Handle<FixedArray> value) {
  Smi* literal_type = Smi::cast(value->get(kLiteralTypeSlot));
  return static_cast<LiteralType>(literal_type->value());
3930 3931 3932 3933 3934 3935 3936 3937
}


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


3938
void ParserTraits::ParseArrowFunctionFormalParameters(
3939
    ParserFormalParameters* parameters, Expression* expr,
3940
    const Scanner::Location& params_loc, bool* ok) {
3941
  if (parameters->Arity() >= Code::kMaxArguments) {
3942
    ReportMessageAt(params_loc, MessageTemplate::kMalformedArrowFunParamList);
3943 3944 3945
    *ok = false;
    return;
  }
3946

3947
  // ArrowFunctionFormals ::
3948 3949 3950 3951 3952 3953
  //    Binary(Token::COMMA, NonTailArrowFunctionFormals, Tail)
  //    Tail
  // NonTailArrowFunctionFormals ::
  //    Binary(Token::COMMA, NonTailArrowFunctionFormals, VariableProxy)
  //    VariableProxy
  // Tail ::
3954
  //    VariableProxy
3955
  //    Spread(VariableProxy)
3956 3957 3958 3959 3960 3961
  //
  // As we need to visit the parameters in left-to-right order, we recurse on
  // the left-hand side of comma expressions.
  //
  if (expr->IsBinaryOperation()) {
    BinaryOperation* binop = expr->AsBinaryOperation();
3962 3963 3964
    // The classifier has already run, so we know that the expression is a valid
    // arrow function formals production.
    DCHECK_EQ(binop->op(), Token::COMMA);
3965 3966
    Expression* left = binop->left();
    Expression* right = binop->right();
3967
    ParseArrowFunctionFormalParameters(parameters, left, params_loc, ok);
3968 3969 3970 3971
    if (!*ok) return;
    // LHS of comma expression should be unparenthesized.
    expr = right;
  }
3972

3973
  // Only the right-most expression may be a rest parameter.
3974
  DCHECK(!parameters->has_rest);
3975

3976
  bool is_rest = expr->IsSpread();
3977 3978 3979
  if (is_rest) {
    expr = expr->AsSpread()->expression();
    parameters->has_rest = true;
3980 3981 3982
    parameters->rest_array_literal_index =
        parser_->function_state_->NextMaterializedLiteralIndex();
    ++parameters->materialized_literals_count;
3983 3984 3985 3986
  }
  if (parameters->is_simple) {
    parameters->is_simple = !is_rest && expr->IsVariableProxy();
  }
3987

3988
  Expression* initializer = nullptr;
3989 3990 3991 3992 3993 3994 3995
  if (expr->IsVariableProxy()) {
    // When the formal parameter was originally seen, it was parsed as a
    // VariableProxy and recorded as unresolved in the scope.  Here we undo that
    // parse-time side-effect for parameters that are single-names (not
    // patterns; for patterns that happens uniformly in
    // PatternRewriter::VisitVariableProxy).
    parser_->scope_->RemoveUnresolved(expr->AsVariableProxy());
3996 3997 3998 3999 4000 4001
  } else if (expr->IsAssignment()) {
    Assignment* assignment = expr->AsAssignment();
    DCHECK(parser_->allow_harmony_default_parameters());
    DCHECK(!assignment->is_compound());
    initializer = assignment->value();
    expr = assignment->target();
4002 4003 4004
  }

  AddFormalParameter(parameters, expr, initializer, is_rest);
4005 4006 4007 4008 4009 4010 4011
}


void ParserTraits::ParseArrowFunctionFormalParameterList(
    ParserFormalParameters* parameters, Expression* expr,
    const Scanner::Location& params_loc,
    Scanner::Location* duplicate_loc, bool* ok) {
4012 4013
  if (expr->IsEmptyParentheses()) return;

4014
  ParseArrowFunctionFormalParameters(parameters, expr, params_loc, ok);
4015 4016
  if (!*ok) return;

4017 4018 4019 4020
  ExpressionClassifier classifier;
  if (!parameters->is_simple) {
    classifier.RecordNonSimpleParameter();
  }
4021 4022
  for (int i = 0; i < parameters->Arity(); ++i) {
    auto parameter = parameters->at(i);
4023
    DeclareFormalParameter(parameters->scope, parameter, &classifier);
4024 4025 4026
    if (!duplicate_loc->IsValid()) {
      *duplicate_loc = classifier.duplicate_formal_parameter_error().location;
    }
4027
  }
4028
  DCHECK_EQ(parameters->is_simple, parameters->scope->has_simple_parameters());
4029 4030 4031
}


4032
void ParserTraits::ReindexLiterals(const ParserFormalParameters& parameters) {
4033 4034 4035
  if (parser_->function_state_->materialized_literal_count() > 0) {
    AstLiteralReindexer reindexer;

4036
    for (const auto p : parameters.params) {
4037 4038
      if (p.pattern != nullptr) reindexer.Reindex(p.pattern);
    }
4039 4040 4041 4042 4043

    if (parameters.has_rest) {
      parameters.rest_array_literal_index = reindexer.NextIndex();
    }

4044 4045 4046 4047 4048 4049
    DCHECK(reindexer.count() <=
           parser_->function_state_->materialized_literal_count());
  }
}


4050
FunctionLiteral* Parser::ParseFunctionLiteral(
4051
    const AstRawString* function_name, Scanner::Location function_name_location,
4052 4053
    FunctionNameValidity function_name_validity, FunctionKind kind,
    int function_token_pos, FunctionLiteral::FunctionType function_type,
4054 4055
    FunctionLiteral::ArityRestriction arity_restriction,
    LanguageMode language_mode, bool* ok) {
4056 4057
  // Function ::
  //   '(' FormalParameterList? ')' '{' FunctionBody '}'
4058 4059 4060 4061 4062 4063
  //
  // Getter ::
  //   '(' ')' '{' FunctionBody '}'
  //
  // Setter ::
  //   '(' PropertySetParameterList ')' '{' FunctionBody '}'
4064

4065 4066 4067
  int pos = function_token_pos == RelocInfo::kNoPosition
      ? peek_position() : function_token_pos;

4068 4069
  bool is_generator = IsGeneratorFunction(kind);

4070 4071 4072
  // Anonymous functions were passed either the empty symbol or a null
  // handle as the function name.  Remember if we were passed a non-empty
  // handle to decide whether to invoke function name inference.
4073
  bool should_infer_name = function_name == NULL;
4074 4075 4076

  // We want a non-null handle as the function name.
  if (should_infer_name) {
4077
    function_name = ast_value_factory()->empty_string();
4078 4079
  }

4080 4081 4082
  // Function declarations are function scoped in normal mode, so they are
  // hoisted. In harmony block scoping mode they are block scoped, so they
  // are not hoisted.
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106
  //
  // One tricky case are function declarations in a local sloppy-mode eval:
  // their declaration is hoisted, but they still see the local scope. E.g.,
  //
  // function() {
  //   var x = 0
  //   try { throw 1 } catch (x) { eval("function g() { return x }") }
  //   return g()
  // }
  //
  // needs to return 1. To distinguish such cases, we need to detect
  // (1) whether a function stems from a sloppy eval, and
  // (2) whether it actually hoists across the eval.
  // Unfortunately, we do not represent sloppy eval scopes, so we do not have
  // either information available directly, especially not when lazily compiling
  // a function like 'g'. We hence rely on the following invariants:
  // - (1) is the case iff the innermost scope of the deserialized scope chain
  //   under which we compile is _not_ a declaration scope. This holds because
  //   in all normal cases, function declarations are fully hoisted to a
  //   declaration scope and compiled relative to that.
  // - (2) is the case iff the current declaration scope is still the original
  //   one relative to the deserialized scope chain. Otherwise we must be
  //   compiling a function in an inner declaration scope in the eval, e.g. a
  //   nested function, and hoisting works normally relative to that.
4107
  Scope* declaration_scope = scope_->DeclarationScope();
4108
  Scope* original_declaration_scope = original_scope_->DeclarationScope();
4109
  Scope* scope = function_type == FunctionLiteral::DECLARATION &&
littledan's avatar
littledan committed
4110 4111
                         is_sloppy(language_mode) &&
                         !allow_harmony_sloppy_function() &&
4112 4113 4114 4115
                         (original_scope_ == original_declaration_scope ||
                          declaration_scope != original_declaration_scope)
                     ? NewScope(declaration_scope, FUNCTION_SCOPE, kind)
                     : NewScope(scope_, FUNCTION_SCOPE, kind);
4116
  scope->SetLanguageMode(language_mode);
4117
  ZoneList<Statement*>* body = NULL;
4118
  int arity = -1;
4119 4120
  int materialized_literal_count = -1;
  int expected_property_count = -1;
4121 4122
  DuplicateFinder duplicate_finder(scanner()->unicode_cache());
  ExpressionClassifier formals_classifier(&duplicate_finder);
4123 4124 4125
  FunctionLiteral::EagerCompileHint eager_compile_hint =
      parenthesized_function_ ? FunctionLiteral::kShouldEagerCompile
                              : FunctionLiteral::kShouldLazyCompile;
4126
  bool should_be_used_once_hint = false;
4127
  // Parse function.
4128
  {
4129
    AstNodeFactory function_factory(ast_value_factory());
4130
    FunctionState function_state(&function_state_, &scope_, scope, kind,
4131
                                 &function_factory);
4132
    scope_->SetScopeName(function_name);
4133 4134 4135 4136 4137

    if (is_generator) {
      // For generators, allocating variables in contexts is currently a win
      // because it minimizes the work needed to suspend and resume an
      // activation.
4138
      scope_->ForceContextAllocation();
4139 4140 4141

      // Calling a generator returns a generator object.  That object is stored
      // in a temporary variable, a definition that is used by "yield"
4142
      // expressions. This also marks the FunctionState as a generator.
4143
      Variable* temp = scope_->NewTemporary(
4144
          ast_value_factory()->dot_generator_object_string());
4145 4146
      function_state.set_generator_object_variable(temp);
    }
4147

4148
    Expect(Token::LPAREN, CHECK_OK);
4149 4150
    int start_position = scanner()->location().beg_pos;
    scope_->set_start_position(start_position);
4151
    ParserFormalParameters formals(scope);
4152
    ParseFormalParameterList(&formals, &formals_classifier, CHECK_OK);
4153
    arity = formals.Arity();
4154
    Expect(Token::RPAREN, CHECK_OK);
4155 4156
    int formals_end_position = scanner()->location().end_pos;

4157 4158
    CheckArityRestrictions(arity, arity_restriction,
                           formals.has_rest, start_position,
4159
                           formals_end_position, CHECK_OK);
4160 4161
    Expect(Token::LBRACE, CHECK_OK);

4162 4163 4164 4165 4166
    // Determine if the function can be parsed lazily. Lazy parsing is different
    // from lazy compilation; we need to parse more eagerly than we compile.

    // We can only parse lazily if we also compile lazily. The heuristics for
    // lazy compilation are:
4167 4168
    // - It must not have been prohibited by the caller to Parse (some callers
    //   need a full AST).
4169
    // - The outer scope must allow lazy compilation of inner functions.
4170 4171 4172 4173 4174 4175
    // - The function mustn't be a function expression with an open parenthesis
    //   before; we consider that a hint that the function will be called
    //   immediately, and it would be a waste of time to make it lazily
    //   compiled.
    // These are all things we can know at this point, without looking at the
    // function itself.
4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194

    // In addition, we need to distinguish between these cases:
    // (function foo() {
    //   bar = function() { return 1; }
    //  })();
    // and
    // (function foo() {
    //   var a = 1;
    //   bar = function() { return a; }
    //  })();

    // Now foo will be parsed eagerly and compiled eagerly (optimization: assume
    // parenthesis before the function means that it will be called
    // immediately). The inner function *must* be parsed eagerly to resolve the
    // possible reference to the variable in foo's scope. However, it's possible
    // that it will be compiled lazily.

    // To make this additional case work, both Parser and PreParser implement a
    // logic where only top-level functions will be parsed lazily.
4195 4196 4197
    bool is_lazily_parsed = mode() == PARSE_LAZILY &&
                            scope_->AllowsLazyParsing() &&
                            !parenthesized_function_;
4198
    parenthesized_function_ = false;  // The bit was set for this function only.
4199

4200 4201 4202 4203 4204 4205
    // Eager or lazy parse?
    // If is_lazily_parsed, we'll parse lazy. If we can set a bookmark, we'll
    // pass it to SkipLazyFunctionBody, which may use it to abort lazy
    // parsing if it suspect that wasn't a good idea. If so, or if we didn't
    // try to lazy parse in the first place, we'll have to parse eagerly.
    Scanner::BookmarkScope bookmark(scanner());
4206
    if (is_lazily_parsed) {
4207 4208
      Scanner::BookmarkScope* maybe_bookmark =
          bookmark.Set() ? &bookmark : nullptr;
4209
      SkipLazyFunctionBody(&materialized_literal_count,
4210 4211 4212
                           &expected_property_count, /*CHECK_OK*/ ok,
                           maybe_bookmark);

4213 4214
      materialized_literal_count += formals.materialized_literals_count +
                                    function_state.materialized_literal_count();
4215

4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
      if (bookmark.HasBeenReset()) {
        // Trigger eager (re-)parsing, just below this block.
        is_lazily_parsed = false;

        // This is probably an initialization function. Inform the compiler it
        // should also eager-compile this function, and that we expect it to be
        // used once.
        eager_compile_hint = FunctionLiteral::kShouldEagerCompile;
        should_be_used_once_hint = true;
      }
    }
    if (!is_lazily_parsed) {
4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240
      // Determine whether the function body can be discarded after parsing.
      // The preconditions are:
      // - Lazy compilation has to be enabled.
      // - Neither V8 natives nor native function declarations can be allowed,
      //   since parsing one would retroactively force the function to be
      //   eagerly compiled.
      // - The invoker of this parser can't depend on the AST being eagerly
      //   built (either because the function is about to be compiled, or
      //   because the AST is going to be inspected for some reason).
      // - Because of the above, we can't be attempting to parse a
      //   FunctionExpression; even without enclosing parentheses it might be
      //   immediately invoked.
      // - The function literal shouldn't be hinted to eagerly compile.
4241
      bool use_temp_zone =
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253
          FLAG_lazy && !allow_natives() && extension_ == NULL && allow_lazy() &&
          function_type == FunctionLiteral::DECLARATION &&
          eager_compile_hint != FunctionLiteral::kShouldEagerCompile;
      // Open a new BodyScope, which sets our AstNodeFactory to allocate in the
      // new temporary zone if the preconditions are satisfied, and ensures that
      // the previous zone is always restored after parsing the body.
      // For the purpose of scope analysis, some ZoneObjects allocated by the
      // factory must persist after the function body is thrown away and
      // temp_zone is deallocated. These objects are instead allocated in a
      // parser-persistent zone (see parser_zone_ in AstNodeFactory).
      {
        Zone temp_zone;
4254
        AstNodeFactory::BodyScope inner(factory(), &temp_zone, use_temp_zone);
4255 4256 4257 4258

        body = ParseEagerFunctionBody(function_name, pos, formals, kind,
                                      function_type, CHECK_OK);
      }
4259 4260
      materialized_literal_count = function_state.materialized_literal_count();
      expected_property_count = function_state.expected_property_count();
4261
      if (use_temp_zone) {
4262 4263 4264 4265
        // If the preconditions are correct the function body should never be
        // accessed, but do this anyway for better behaviour if they're wrong.
        body = NULL;
      }
4266
    }
4267

4268 4269 4270 4271 4272 4273 4274 4275 4276 4277
    // Parsing the body may change the language mode in our scope.
    language_mode = scope->language_mode();

    if (is_strong(language_mode) && IsSubclassConstructor(kind)) {
      if (!function_state.super_location().IsValid()) {
        ReportMessageAt(function_name_location,
                        MessageTemplate::kStrongSuperCallMissing,
                        kReferenceError);
        *ok = false;
        return nullptr;
4278
      }
4279 4280
    }

4281 4282
    // Validate name and parameter names. We can do this only after parsing the
    // function, since the function can declare itself strict.
4283
    CheckFunctionName(language_mode, function_name, function_name_validity,
4284
                      function_name_location, CHECK_OK);
4285
    const bool allow_duplicate_parameters =
4286
        is_sloppy(language_mode) && formals.is_simple && !IsConciseMethod(kind);
4287
    ValidateFormalParameters(&formals_classifier, language_mode,
4288
                             allow_duplicate_parameters, CHECK_OK);
4289

4290
    if (is_strict(language_mode)) {
4291 4292
      CheckStrictOctalLiteral(scope->start_position(), scope->end_position(),
                              CHECK_OK);
4293
    }
4294 4295 4296
    if (is_sloppy(language_mode) && allow_harmony_sloppy_function()) {
      InsertSloppyBlockFunctionVarBindings(scope, CHECK_OK);
    }
4297
    if (is_strict(language_mode) || allow_harmony_sloppy()) {
4298 4299
      CheckConflictingVarDeclarations(scope, CHECK_OK);
    }
4300 4301
  }

4302 4303
  bool has_duplicate_parameters =
      !formals_classifier.is_valid_formal_parameter_list_without_duplicates();
4304
  FunctionLiteral::ParameterFlag duplicate_parameters =
4305 4306
      has_duplicate_parameters ? FunctionLiteral::kHasDuplicateParameters
                               : FunctionLiteral::kNoDuplicateParameters;
4307

4308
  FunctionLiteral* function_literal = factory()->NewFunctionLiteral(
4309
      function_name, ast_value_factory(), scope, body,
4310
      materialized_literal_count, expected_property_count, arity,
4311 4312
      duplicate_parameters, function_type, FunctionLiteral::kIsFunction,
      eager_compile_hint, kind, pos);
4313
  function_literal->set_function_token_position(function_token_pos);
4314 4315
  if (should_be_used_once_hint)
    function_literal->set_should_be_used_once_hint();
4316

4317
  if (fni_ != NULL && should_infer_name) fni_->AddFunction(function_literal);
4318
  return function_literal;
4319 4320 4321
}


4322
void Parser::SkipLazyFunctionBody(int* materialized_literal_count,
4323 4324 4325
                                  int* expected_property_count, bool* ok,
                                  Scanner::BookmarkScope* bookmark) {
  DCHECK_IMPLIES(bookmark, bookmark->HasBeenSet());
4326
  if (produce_cached_parse_data()) CHECK(log_);
4327

4328
  int function_block_pos = position();
4329
  if (consume_cached_parse_data() && !cached_parse_data_->rejected()) {
4330 4331 4332
    // If we have cached data, we use it to skip parsing the function body. The
    // data contains the information we need to construct the lazy function.
    FunctionEntry entry =
4333
        cached_parse_data_->GetFunctionEntry(function_block_pos);
4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
    // Check that cached data is valid. If not, mark it as invalid (the embedder
    // handles it). Note that end position greater than end of stream is safe,
    // and hard to check.
    if (entry.is_valid() && entry.end_pos() > function_block_pos) {
      scanner()->SeekForward(entry.end_pos() - 1);

      scope_->set_end_position(entry.end_pos());
      Expect(Token::RBRACE, ok);
      if (!*ok) {
        return;
      }
      total_preparse_skipped_ += scope_->end_position() - function_block_pos;
      *materialized_literal_count = entry.literal_count();
      *expected_property_count = entry.property_count();
4348
      scope_->SetLanguageMode(entry.language_mode());
4349
      if (entry.uses_super_property()) scope_->RecordSuperPropertyUsage();
4350
      if (entry.calls_eval()) scope_->RecordEvalCall();
4351 4352
      return;
    }
4353 4354 4355 4356 4357 4358
    cached_parse_data_->Reject();
  }
  // With no cached data, we partially parse the function, without building an
  // AST. This gathers the data needed to build a lazy function.
  SingletonLogger logger;
  PreParser::PreParseResult result =
4359 4360 4361 4362
      ParseLazyFunctionBodyWithPreParser(&logger, bookmark);
  if (bookmark && bookmark->HasBeenReset()) {
    return;  // Return immediately if pre-parser devided to abort parsing.
  }
4363 4364 4365 4366 4367 4368 4369 4370 4371
  if (result == PreParser::kPreParseStackOverflow) {
    // Propagate stack overflow.
    set_stack_overflow();
    *ok = false;
    return;
  }
  if (logger.has_error()) {
    ParserTraits::ReportMessageAt(
        Scanner::Location(logger.start(), logger.end()), logger.message(),
4372
        logger.argument_opt(), logger.error_type());
4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383
    *ok = false;
    return;
  }
  scope_->set_end_position(logger.end());
  Expect(Token::RBRACE, ok);
  if (!*ok) {
    return;
  }
  total_preparse_skipped_ += scope_->end_position() - function_block_pos;
  *materialized_literal_count = logger.literals();
  *expected_property_count = logger.properties();
4384
  scope_->SetLanguageMode(logger.language_mode());
4385
  if (logger.uses_super_property()) {
4386 4387
    scope_->RecordSuperPropertyUsage();
  }
4388 4389 4390
  if (logger.calls_eval()) {
    scope_->RecordEvalCall();
  }
4391 4392 4393 4394 4395
  if (produce_cached_parse_data()) {
    DCHECK(log_);
    // Position right after terminal '}'.
    int body_end = scanner()->location().end_pos;
    log_->LogFunction(function_block_pos, body_end, *materialized_literal_count,
4396
                      *expected_property_count, scope_->language_mode(),
4397
                      scope_->uses_super_property(), scope_->calls_eval());
4398 4399 4400 4401
  }
}


4402 4403 4404 4405
void Parser::AddAssertIsConstruct(ZoneList<Statement*>* body, int pos) {
  ZoneList<Expression*>* arguments =
      new (zone()) ZoneList<Expression*>(0, zone());
  CallRuntime* construct_check = factory()->NewCallRuntime(
4406
      Runtime::kInlineIsConstructCall, arguments, pos);
4407
  CallRuntime* non_callable_error = factory()->NewCallRuntime(
4408
      Runtime::kThrowConstructorNonCallableError, arguments, pos);
4409 4410 4411 4412 4413 4414 4415 4416
  IfStatement* if_statement = factory()->NewIfStatement(
      factory()->NewUnaryOperation(Token::NOT, construct_check, pos),
      factory()->NewReturnStatement(non_callable_error, pos),
      factory()->NewEmptyStatement(pos), pos);
  body->Add(if_statement, zone());
}


4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442
Statement* Parser::BuildAssertIsCoercible(Variable* var) {
  // if (var === null || var === undefined)
  //     throw /* type error kNonCoercible) */;

  Expression* condition = factory()->NewBinaryOperation(
      Token::OR, factory()->NewCompareOperation(
                     Token::EQ_STRICT, factory()->NewVariableProxy(var),
                     factory()->NewUndefinedLiteral(RelocInfo::kNoPosition),
                     RelocInfo::kNoPosition),
      factory()->NewCompareOperation(
          Token::EQ_STRICT, factory()->NewVariableProxy(var),
          factory()->NewNullLiteral(RelocInfo::kNoPosition),
          RelocInfo::kNoPosition),
      RelocInfo::kNoPosition);
  Expression* throw_type_error = this->NewThrowTypeError(
      MessageTemplate::kNonCoercible, ast_value_factory()->empty_string(),
      RelocInfo::kNoPosition);
  IfStatement* if_statement = factory()->NewIfStatement(
      condition, factory()->NewExpressionStatement(throw_type_error,
                                                   RelocInfo::kNoPosition),
      factory()->NewEmptyStatement(RelocInfo::kNoPosition),
      RelocInfo::kNoPosition);
  return if_statement;
}


4443
Block* Parser::BuildParameterInitializationBlock(
4444
    const ParserFormalParameters& parameters, bool* ok) {
4445
  DCHECK(!parameters.is_simple);
4446
  DCHECK(scope_->is_function_scope());
4447 4448
  Block* init_block =
      factory()->NewBlock(NULL, 1, true, RelocInfo::kNoPosition);
4449 4450
  for (int i = 0; i < parameters.params.length(); ++i) {
    auto parameter = parameters.params[i];
4451 4452 4453 4454 4455
    DeclarationDescriptor descriptor;
    descriptor.declaration_kind = DeclarationDescriptor::PARAMETER;
    descriptor.parser = this;
    descriptor.declaration_scope = scope_;
    descriptor.scope = scope_;
4456
    descriptor.hoist_scope = nullptr;
4457 4458 4459 4460 4461 4462
    descriptor.mode = LET;
    descriptor.is_const = false;
    descriptor.needs_init = true;
    descriptor.declaration_pos = parameter.pattern->position();
    descriptor.initialization_pos = parameter.pattern->position();
    descriptor.init_op = Token::INIT_LET;
4463 4464 4465 4466
    Expression* initial_value =
        factory()->NewVariableProxy(parameters.scope->parameter(i));
    if (parameter.initializer != nullptr) {
      // IS_UNDEFINED($param) ? initializer : $param
4467
      DCHECK(!parameter.is_rest);
4468 4469 4470 4471 4472 4473 4474 4475 4476
      auto condition = factory()->NewCompareOperation(
          Token::EQ_STRICT,
          factory()->NewVariableProxy(parameters.scope->parameter(i)),
          factory()->NewUndefinedLiteral(RelocInfo::kNoPosition),
          RelocInfo::kNoPosition);
      initial_value = factory()->NewConditional(
          condition, parameter.initializer, initial_value,
          RelocInfo::kNoPosition);
      descriptor.initialization_pos = parameter.initializer->position();
4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546
    } else if (parameter.is_rest) {
      // $rest = [];
      // for (var $argument_index = $rest_index;
      //      $argument_index < %_ArgumentsLength();
      //      ++$argument_index) {
      //   %AppendElement($rest, %_Arguments($argument_index));
      // }
      // let <param> = $rest;
      DCHECK(parameter.pattern->IsVariableProxy());
      DCHECK_EQ(i, parameters.params.length() - 1);

      int pos = parameter.pattern->position();
      Variable* temp_var = parameters.scope->parameter(i);
      auto empty_values = new (zone()) ZoneList<Expression*>(0, zone());
      auto empty_array = factory()->NewArrayLiteral(
          empty_values, parameters.rest_array_literal_index,
          is_strong(language_mode()), RelocInfo::kNoPosition);

      auto init_array = factory()->NewAssignment(
          Token::INIT_VAR, factory()->NewVariableProxy(temp_var), empty_array,
          RelocInfo::kNoPosition);

      auto loop = factory()->NewForStatement(NULL, RelocInfo::kNoPosition);

      auto argument_index =
          parameters.scope->NewTemporary(ast_value_factory()->empty_string());
      auto init = factory()->NewExpressionStatement(
          factory()->NewAssignment(
              Token::INIT_VAR, factory()->NewVariableProxy(argument_index),
              factory()->NewSmiLiteral(i, RelocInfo::kNoPosition),
              RelocInfo::kNoPosition),
          RelocInfo::kNoPosition);

      auto empty_arguments = new (zone()) ZoneList<Expression*>(0, zone());

      // $arguments_index < arguments.length
      auto cond = factory()->NewCompareOperation(
          Token::LT, factory()->NewVariableProxy(argument_index),
          factory()->NewCallRuntime(Runtime::kInlineArgumentsLength,
                                    empty_arguments, RelocInfo::kNoPosition),
          RelocInfo::kNoPosition);

      // ++argument_index
      auto next = factory()->NewExpressionStatement(
          factory()->NewCountOperation(
              Token::INC, true, factory()->NewVariableProxy(argument_index),
              RelocInfo::kNoPosition),
          RelocInfo::kNoPosition);

      // %_Arguments($arguments_index)
      auto arguments_args = new (zone()) ZoneList<Expression*>(1, zone());
      arguments_args->Add(factory()->NewVariableProxy(argument_index), zone());

      // %AppendElement($rest, %_Arguments($arguments_index))
      auto append_element_args = new (zone()) ZoneList<Expression*>(2, zone());

      append_element_args->Add(factory()->NewVariableProxy(temp_var), zone());
      append_element_args->Add(
          factory()->NewCallRuntime(Runtime::kInlineArguments, arguments_args,
                                    RelocInfo::kNoPosition),
          zone());

      auto body = factory()->NewExpressionStatement(
          factory()->NewCallRuntime(Runtime::kAppendElement,
                                    append_element_args,
                                    RelocInfo::kNoPosition),
          RelocInfo::kNoPosition);

      loop->Initialize(init, cond, next, body);

neis's avatar
neis committed
4547
      init_block->statements()->Add(
4548 4549 4550
          factory()->NewExpressionStatement(init_array, RelocInfo::kNoPosition),
          zone());

neis's avatar
neis committed
4551
      init_block->statements()->Add(loop, zone());
4552 4553

      descriptor.initialization_pos = pos;
4554
    }
4555 4556 4557

    Scope* param_scope = scope_;
    Block* param_block = init_block;
4558
    if (!parameter.is_simple() && scope_->calls_sloppy_eval()) {
4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576
      param_scope = NewScope(scope_, BLOCK_SCOPE);
      param_scope->set_is_declaration_scope();
      param_scope->set_start_position(parameter.pattern->position());
      param_scope->set_end_position(RelocInfo::kNoPosition);
      param_scope->RecordEvalCall();
      param_block = factory()->NewBlock(NULL, 8, true, RelocInfo::kNoPosition);
      param_block->set_scope(param_scope);
      descriptor.hoist_scope = scope_;
    }

    {
      BlockState block_state(&scope_, param_scope);
      DeclarationParsingResult::Declaration decl(
          parameter.pattern, parameter.pattern->position(), initial_value);
      PatternRewriter::DeclareAndInitializeVariables(param_block, &descriptor,
                                                     &decl, nullptr, CHECK_OK);
    }

4577
    if (!parameter.is_simple() && scope_->calls_sloppy_eval()) {
4578 4579 4580 4581
      param_scope = param_scope->FinalizeBlockScope();
      if (param_scope != nullptr) {
        CheckConflictingVarDeclarations(param_scope, CHECK_OK);
      }
neis's avatar
neis committed
4582
      init_block->statements()->Add(param_block, zone());
4583
    }
4584 4585 4586 4587 4588
  }
  return init_block;
}


4589
ZoneList<Statement*>* Parser::ParseEagerFunctionBody(
4590
    const AstRawString* function_name, int pos,
4591 4592
    const ParserFormalParameters& parameters, FunctionKind kind,
    FunctionLiteral::FunctionType function_type, bool* ok) {
4593 4594 4595
  // Everything inside an eagerly parsed function will be parsed eagerly
  // (see comment above).
  ParsingModeScope parsing_mode(this, PARSE_EAGERLY);
4596
  ZoneList<Statement*>* result = new(zone()) ZoneList<Statement*>(8, zone());
4597

4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
  static const int kFunctionNameAssignmentIndex = 0;
  if (function_type == FunctionLiteral::NAMED_EXPRESSION) {
    DCHECK(function_name != NULL);
    // 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).
    // Not having parsed the function body, the language mode may still change,
    // so we reserve a spot and create the actual const assignment later.
    DCHECK_EQ(kFunctionNameAssignmentIndex, result->length());
    result->Add(NULL, zone());
  }
4609 4610 4611

  // For concise constructors, check that they are constructed,
  // not called.
4612
  if (IsClassConstructor(kind)) {
4613
    AddAssertIsConstruct(result, pos);
4614 4615
  }

4616
  ZoneList<Statement*>* body = result;
4617
  Scope* inner_scope = scope_;
4618
  Block* inner_block = nullptr;
4619
  if (!parameters.is_simple) {
4620 4621 4622
    inner_scope = NewScope(scope_, BLOCK_SCOPE);
    inner_scope->set_is_declaration_scope();
    inner_scope->set_start_position(scanner()->location().beg_pos);
4623 4624 4625
    inner_block = factory()->NewBlock(NULL, 8, true, RelocInfo::kNoPosition);
    inner_block->set_scope(inner_scope);
    body = inner_block->statements();
4626 4627
  }

4628
  {
4629
    BlockState block_state(&scope_, inner_scope);
4630

4631 4632 4633 4634 4635
    // For generators, allocate and yield an iterator on function entry.
    if (IsGeneratorFunction(kind)) {
      ZoneList<Expression*>* arguments =
          new(zone()) ZoneList<Expression*>(0, zone());
      CallRuntime* allocation = factory()->NewCallRuntime(
4636
          Runtime::kCreateJSGeneratorObject, arguments, pos);
4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647
      VariableProxy* init_proxy = factory()->NewVariableProxy(
          function_state_->generator_object_variable());
      Assignment* assignment = factory()->NewAssignment(
          Token::INIT_VAR, init_proxy, allocation, RelocInfo::kNoPosition);
      VariableProxy* get_proxy = factory()->NewVariableProxy(
          function_state_->generator_object_variable());
      Yield* yield = factory()->NewYield(
          get_proxy, assignment, Yield::kInitial, RelocInfo::kNoPosition);
      body->Add(factory()->NewExpressionStatement(
          yield, RelocInfo::kNoPosition), zone());
    }
4648

4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660
    ParseStatementList(body, Token::RBRACE, CHECK_OK);

    if (IsGeneratorFunction(kind)) {
      VariableProxy* get_proxy = factory()->NewVariableProxy(
          function_state_->generator_object_variable());
      Expression* undefined =
          factory()->NewUndefinedLiteral(RelocInfo::kNoPosition);
      Yield* yield = factory()->NewYield(get_proxy, undefined, Yield::kFinal,
                                         RelocInfo::kNoPosition);
      body->Add(factory()->NewExpressionStatement(
          yield, RelocInfo::kNoPosition), zone());
    }
4661

4662 4663 4664 4665 4666 4667 4668
    if (IsSubclassConstructor(kind)) {
      body->Add(
          factory()->NewReturnStatement(
              this->ThisExpression(scope_, factory(), RelocInfo::kNoPosition),
              RelocInfo::kNoPosition),
              zone());
    }
4669 4670
  }

4671 4672
  Expect(Token::RBRACE, CHECK_OK);
  scope_->set_end_position(scanner()->location().end_pos);
4673

4674
  if (!parameters.is_simple) {
4675 4676 4677
    DCHECK_NOT_NULL(inner_scope);
    DCHECK_EQ(body, inner_block->statements());
    scope_->SetLanguageMode(inner_scope->language_mode());
4678
    Block* init_block = BuildParameterInitializationBlock(parameters, CHECK_OK);
4679 4680
    DCHECK_NOT_NULL(init_block);

4681 4682
    inner_scope->set_end_position(scanner()->location().end_pos);
    inner_scope = inner_scope->FinalizeBlockScope();
4683 4684
    if (inner_scope != nullptr) {
      CheckConflictingVarDeclarations(inner_scope, CHECK_OK);
4685
      InsertShadowingVarBindingInitializers(inner_block);
4686
    }
4687 4688 4689

    result->Add(init_block, zone());
    result->Add(inner_block, zone());
4690
  }
4691

4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722
  if (function_type == FunctionLiteral::NAMED_EXPRESSION) {
    // Now that we know the language mode, we can create the const assignment
    // in the previously reserved spot.
    // 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 Proxies as is the case now.
    Token::Value fvar_init_op = Token::INIT_CONST_LEGACY;
    bool use_strict_const = is_strict(scope_->language_mode()) ||
                            (!allow_legacy_const() && allow_harmony_sloppy());
    if (use_strict_const) {
      fvar_init_op = Token::INIT_CONST;
    }
    VariableMode fvar_mode = use_strict_const ? CONST : CONST_LEGACY;
    Variable* fvar = new (zone())
        Variable(scope_, function_name, fvar_mode, Variable::NORMAL,
                 kCreatedInitialized, kNotAssigned);
    VariableProxy* proxy = factory()->NewVariableProxy(fvar);
    VariableDeclaration* fvar_declaration = factory()->NewVariableDeclaration(
        proxy, fvar_mode, scope_, RelocInfo::kNoPosition);
    scope_->DeclareFunctionVar(fvar_declaration);

    VariableProxy* fproxy = scope_->NewUnresolved(factory(), function_name);
    fproxy->BindTo(fvar);
    result->Set(kFunctionNameAssignmentIndex,
                factory()->NewExpressionStatement(
                    factory()->NewAssignment(fvar_init_op, fproxy,
                                             factory()->NewThisFunction(pos),
                                             RelocInfo::kNoPosition),
                    RelocInfo::kNoPosition));
  }

4723
  return result;
4724 4725 4726 4727
}


PreParser::PreParseResult Parser::ParseLazyFunctionBodyWithPreParser(
4728
    SingletonLogger* logger, Scanner::BookmarkScope* bookmark) {
4729 4730 4731 4732 4733
  // This function may be called on a background thread too; record only the
  // main thread preparse times.
  if (pre_parse_timer_ != NULL) {
    pre_parse_timer_->Start();
  }
4734
  DCHECK_EQ(Token::LBRACE, scanner()->current_token());
4735 4736

  if (reusable_preparser_ == NULL) {
4737 4738
    reusable_preparser_ = new PreParser(zone(), &scanner_, ast_value_factory(),
                                        NULL, stack_limit_);
4739
    reusable_preparser_->set_allow_lazy(true);
4740 4741 4742
#define SET_ALLOW(name) reusable_preparser_->set_allow_##name(allow_##name());
    SET_ALLOW(natives);
    SET_ALLOW(harmony_sloppy);
4743
    SET_ALLOW(harmony_sloppy_let);
4744
    SET_ALLOW(harmony_rest_parameters);
4745
    SET_ALLOW(harmony_default_parameters);
neis's avatar
neis committed
4746
    SET_ALLOW(harmony_spread_calls);
4747 4748 4749 4750 4751
    SET_ALLOW(harmony_destructuring);
    SET_ALLOW(harmony_spread_arrays);
    SET_ALLOW(harmony_new_target);
    SET_ALLOW(strong_mode);
#undef SET_ALLOW
4752
  }
4753
  PreParser::PreParseResult result = reusable_preparser_->PreParseLazyFunction(
4754 4755
      language_mode(), function_state_->kind(), scope_->has_simple_parameters(),
      logger, bookmark);
4756 4757 4758
  if (pre_parse_timer_ != NULL) {
    pre_parse_timer_->Stop();
  }
4759 4760 4761 4762
  return result;
}


4763 4764 4765 4766 4767 4768
ClassLiteral* Parser::ParseClassLiteral(const AstRawString* name,
                                        Scanner::Location class_name_location,
                                        bool name_is_strict_reserved, int pos,
                                        bool* ok) {
  // All parts of a ClassDeclaration and ClassExpression are strict code.
  if (name_is_strict_reserved) {
4769 4770
    ReportMessageAt(class_name_location,
                    MessageTemplate::kUnexpectedStrictReserved);
4771 4772 4773 4774
    *ok = false;
    return NULL;
  }
  if (IsEvalOrArguments(name)) {
4775
    ReportMessageAt(class_name_location, MessageTemplate::kStrictEvalArguments);
4776 4777 4778
    *ok = false;
    return NULL;
  }
4779
  if (is_strong(language_mode()) && IsUndefined(name)) {
4780
    ReportMessageAt(class_name_location, MessageTemplate::kStrongUndefined);
4781 4782 4783
    *ok = false;
    return NULL;
  }
4784 4785 4786

  Scope* block_scope = NewScope(scope_, BLOCK_SCOPE);
  BlockState block_state(&scope_, block_scope);
4787
  scope_->SetLanguageMode(
4788
      static_cast<LanguageMode>(scope_->language_mode() | STRICT));
4789 4790 4791 4792
  scope_->SetScopeName(name);

  VariableProxy* proxy = NULL;
  if (name != NULL) {
4793
    proxy = NewUnresolved(name, CONST);
4794 4795 4796 4797
    const bool is_class_declaration = true;
    Declaration* declaration = factory()->NewVariableDeclaration(
        proxy, CONST, block_scope, pos, is_class_declaration,
        scope_->class_declaration_group_start());
4798
    Declare(declaration, DeclarationDescriptor::NORMAL, true, CHECK_OK);
4799 4800 4801 4802 4803
  }

  Expression* extends = NULL;
  if (Check(Token::EXTENDS)) {
    block_scope->set_start_position(scanner()->location().end_pos);
4804 4805
    ExpressionClassifier classifier;
    extends = ParseLeftHandSideExpression(&classifier, CHECK_OK);
4806
    ValidateExpression(&classifier, CHECK_OK);
4807 4808 4809 4810
  } else {
    block_scope->set_start_position(scanner()->location().end_pos);
  }

4811 4812

  ClassLiteralChecker checker(this);
4813
  ZoneList<ObjectLiteral::Property*>* properties = NewPropertyList(4, zone());
4814
  FunctionLiteral* constructor = NULL;
4815 4816 4817
  bool has_seen_constructor = false;

  Expect(Token::LBRACE, CHECK_OK);
4818

4819
  const bool has_extends = extends != nullptr;
4820 4821 4822 4823 4824
  while (peek() != Token::RBRACE) {
    if (Check(Token::SEMICOLON)) continue;
    if (fni_ != NULL) fni_->Enter();
    const bool in_class = true;
    const bool is_static = false;
arv's avatar
arv committed
4825 4826
    bool is_computed_name = false;  // Classes do not care about computed
                                    // property names here.
4827
    ExpressionClassifier classifier;
4828
    ObjectLiteral::Property* property = ParsePropertyDefinition(
4829
        &checker, in_class, has_extends, is_static, &is_computed_name,
4830
        &has_seen_constructor, &classifier, CHECK_OK);
4831
    ValidateExpression(&classifier, CHECK_OK);
4832 4833

    if (has_seen_constructor && constructor == NULL) {
4834 4835
      constructor = GetPropertyValue(property)->AsFunctionLiteral();
      DCHECK_NOT_NULL(constructor);
4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849
    } else {
      properties->Add(property, zone());
    }

    if (fni_ != NULL) {
      fni_->Infer();
      fni_->Leave();
    }
  }

  Expect(Token::RBRACE, CHECK_OK);
  int end_pos = scanner()->location().end_pos;

  if (constructor == NULL) {
4850 4851
    constructor = DefaultConstructor(extends != NULL, block_scope, pos, end_pos,
                                     block_scope->language_mode());
4852 4853 4854 4855 4856 4857
  }

  block_scope->set_end_position(end_pos);

  if (name != NULL) {
    DCHECK_NOT_NULL(proxy);
4858
    proxy->var()->set_initializer_position(end_pos);
4859 4860 4861 4862
  } else {
    // Unnamed classes should not have scopes (the scope will be empty).
    DCHECK_EQ(block_scope->num_var_or_const(), 0);
    block_scope = nullptr;
4863 4864 4865 4866 4867 4868 4869
  }

  return factory()->NewClassLiteral(name, block_scope, proxy, extends,
                                    constructor, properties, pos, end_pos);
}


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

4874
  int pos = peek_position();
4875
  Expect(Token::MOD, CHECK_OK);
4876
  // Allow "eval" or "arguments" for backward compatibility.
4877 4878
  const AstRawString* name = ParseIdentifier(kAllowRestrictedIdentifiers,
                                             CHECK_OK);
4879
  Scanner::Location spread_pos;
4880 4881 4882
  ExpressionClassifier classifier;
  ZoneList<Expression*>* args =
      ParseArguments(&spread_pos, &classifier, CHECK_OK);
4883
  ValidateExpression(&classifier, CHECK_OK);
4884 4885

  DCHECK(!spread_pos.IsValid());
4886 4887

  if (extension_ != NULL) {
4888 4889
    // The extension structures are only accessible while parsing the
    // very first time not when reparsing because of lazy compilation.
4890
    scope_->DeclarationScope()->ForceEagerCompilation();
4891 4892
  }

4893
  const Runtime::Function* function = Runtime::FunctionForName(name->string());
4894

4895
  if (function != NULL) {
4896 4897 4898
    // Check for possible name clash.
    DCHECK_EQ(Context::kNotFound,
              Context::IntrinsicIndexForName(name->string()));
4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916
    // Check for built-in IS_VAR macro.
    if (function->function_id == Runtime::kIS_VAR) {
      DCHECK_EQ(Runtime::RUNTIME, function->intrinsic_type);
      // %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 {
        ReportMessage(MessageTemplate::kNotIsvar);
        *ok = false;
        return NULL;
      }
    }

    // Check that the expected number of arguments are being passed.
    if (function->nargs != -1 && function->nargs != args->length()) {
      ReportMessage(MessageTemplate::kIllegalAccess);
4917
      *ok = false;
4918 4919 4920
      return NULL;
    }

4921
    return factory()->NewCallRuntime(function, args, pos);
4922 4923
  }

4924 4925 4926 4927
  int context_index = Context::IntrinsicIndexForName(name->string());

  // Check that the function is defined.
  if (context_index == Context::kNotFound) {
4928
    ParserTraits::ReportMessage(MessageTemplate::kNotDefined, name);
4929 4930
    *ok = false;
    return NULL;
4931 4932
  }

4933
  return factory()->NewCallRuntime(context_index, args, pos);
4934 4935 4936
}


4937
Literal* Parser::GetLiteralUndefined(int position) {
4938
  return factory()->NewUndefinedLiteral(position);
4939 4940 4941
}


4942 4943 4944
void Parser::CheckConflictingVarDeclarations(Scope* scope, bool* ok) {
  Declaration* decl = scope->CheckConflictingVarDeclarations();
  if (decl != NULL) {
4945
    // In ES6, conflicting variable bindings are early errors.
4946
    const AstRawString* name = decl->proxy()->raw_name();
4947 4948 4949 4950
    int position = decl->proxy()->position();
    Scanner::Location location = position == RelocInfo::kNoPosition
        ? Scanner::Location::invalid()
        : Scanner::Location(position, position + 1);
4951 4952
    ParserTraits::ReportMessageAt(location, MessageTemplate::kVarRedeclaration,
                                  name);
4953 4954 4955 4956 4957
    *ok = false;
  }
}


4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982
void Parser::InsertShadowingVarBindingInitializers(Block* inner_block) {
  // For each var-binding that shadows a parameter, insert an assignment
  // initializing the variable with the parameter.
  Scope* inner_scope = inner_block->scope();
  DCHECK(inner_scope->is_declaration_scope());
  Scope* function_scope = inner_scope->outer_scope();
  DCHECK(function_scope->is_function_scope());
  ZoneList<Declaration*>* decls = inner_scope->declarations();
  for (int i = 0; i < decls->length(); ++i) {
    Declaration* decl = decls->at(i);
    if (decl->mode() != VAR || !decl->IsVariableDeclaration()) continue;
    const AstRawString* name = decl->proxy()->raw_name();
    Variable* parameter = function_scope->LookupLocal(name);
    if (parameter == nullptr) continue;
    VariableProxy* to = inner_scope->NewUnresolved(factory(), name);
    VariableProxy* from = factory()->NewVariableProxy(parameter);
    Expression* assignment = factory()->NewAssignment(
        Token::ASSIGN, to, from, RelocInfo::kNoPosition);
    Statement* statement = factory()->NewExpressionStatement(
        assignment, RelocInfo::kNoPosition);
    inner_block->statements()->InsertAt(0, statement, zone());
  }
}


4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017
void Parser::InsertSloppyBlockFunctionVarBindings(Scope* scope, bool* ok) {
  // For each variable which is used as a function declaration in a sloppy
  // block,
  DCHECK(scope->is_declaration_scope());
  SloppyBlockFunctionMap* map = scope->sloppy_block_function_map();
  for (ZoneHashMap::Entry* p = map->Start(); p != nullptr; p = map->Next(p)) {
    AstRawString* name = static_cast<AstRawString*>(p->key);
    // If the variable wouldn't conflict with a lexical declaration,
    Variable* var = scope->LookupLocal(name);
    if (var == nullptr || !IsLexicalVariableMode(var->mode())) {
      // Declare a var-style binding for the function in the outer scope
      VariableProxy* proxy = scope->NewUnresolved(factory(), name);
      Declaration* declaration = factory()->NewVariableDeclaration(
          proxy, VAR, scope, RelocInfo::kNoPosition);
      Declare(declaration, DeclarationDescriptor::NORMAL, true, ok, scope);
      DCHECK(ok);  // Based on the preceding check, this should not fail
      if (!ok) return;

      // Write in assignments to var for each block-scoped function declaration
      auto delegates = static_cast<SloppyBlockFunctionMap::Vector*>(p->value);
      for (SloppyBlockFunctionStatement* delegate : *delegates) {
        // Read from the local lexical scope and write to the function scope
        VariableProxy* to = scope->NewUnresolved(factory(), name);
        VariableProxy* from = delegate->scope()->NewUnresolved(factory(), name);
        Expression* assignment = factory()->NewAssignment(
            Token::ASSIGN, to, from, RelocInfo::kNoPosition);
        Statement* statement = factory()->NewExpressionStatement(
            assignment, RelocInfo::kNoPosition);
        delegate->set_statement(statement);
      }
    }
  }
}


5018 5019 5020
// ----------------------------------------------------------------------------
// Parser support

5021
bool Parser::TargetStackContainsLabel(const AstRawString* label) {
bak@chromium.org's avatar
bak@chromium.org committed
5022
  for (Target* t = target_stack_; t != NULL; t = t->previous()) {
5023
    if (ContainsLabel(t->statement()->labels(), label)) return true;
5024 5025 5026 5027 5028
  }
  return false;
}


5029 5030 5031
BreakableStatement* Parser::LookupBreakTarget(const AstRawString* label,
                                              bool* ok) {
  bool anonymous = label == NULL;
bak@chromium.org's avatar
bak@chromium.org committed
5032
  for (Target* t = target_stack_; t != NULL; t = t->previous()) {
5033
    BreakableStatement* stat = t->statement();
5034 5035 5036 5037 5038 5039 5040 5041 5042
    if ((anonymous && stat->is_target_for_anonymous()) ||
        (!anonymous && ContainsLabel(stat->labels(), label))) {
      return stat;
    }
  }
  return NULL;
}


5043
IterationStatement* Parser::LookupContinueTarget(const AstRawString* label,
5044
                                                 bool* ok) {
5045
  bool anonymous = label == NULL;
bak@chromium.org's avatar
bak@chromium.org committed
5046
  for (Target* t = target_stack_; t != NULL; t = t->previous()) {
5047
    IterationStatement* stat = t->statement()->AsIterationStatement();
5048 5049
    if (stat == NULL) continue;

5050
    DCHECK(stat->is_target_for_anonymous());
5051 5052 5053 5054 5055 5056 5057 5058
    if (anonymous || ContainsLabel(stat->labels(), label)) {
      return stat;
    }
  }
  return NULL;
}


5059
void Parser::HandleSourceURLComments(Isolate* isolate, Handle<Script> script) {
5060
  if (scanner_.source_url()->length() > 0) {
5061 5062
    Handle<String> source_url = scanner_.source_url()->Internalize(isolate);
    script->set_source_url(*source_url);
5063 5064
  }
  if (scanner_.source_mapping_url()->length() > 0) {
5065
    Handle<String> source_mapping_url =
5066 5067
        scanner_.source_mapping_url()->Internalize(isolate);
    script->set_source_mapping_url(*source_mapping_url);
5068 5069 5070 5071
  }
}


5072
void Parser::Internalize(Isolate* isolate, Handle<Script> script, bool error) {
5073
  // Internalize strings.
5074
  ast_value_factory()->Internalize(isolate);
5075 5076

  // Error processing.
5077
  if (error) {
5078
    if (stack_overflow()) {
5079
      isolate->StackOverflow();
5080
    } else {
5081 5082
      DCHECK(pending_error_handler_.has_pending_error());
      pending_error_handler_.ThrowPendingError(isolate, script);
5083 5084 5085 5086
    }
  }

  // Move statistics to Isolate.
5087 5088 5089
  for (int feature = 0; feature < v8::Isolate::kUseCounterFeatureCount;
       ++feature) {
    for (int i = 0; i < use_counts_[feature]; ++i) {
5090
      isolate->CountUsage(v8::Isolate::UseCounterFeature(feature));
5091 5092
    }
  }
5093
  isolate->counters()->total_preparse_skipped()->Increment(
5094
      total_preparse_skipped_);
5095 5096 5097
}


5098 5099 5100 5101
// ----------------------------------------------------------------------------
// Regular expressions


5102
RegExpParser::RegExpParser(FlatStringReader* in, Handle<String>* error,
5103 5104 5105
                           bool multiline, bool unicode, Isolate* isolate,
                           Zone* zone)
    : isolate_(isolate),
5106
      zone_(zone),
5107 5108 5109 5110 5111 5112 5113 5114
      error_(error),
      captures_(NULL),
      in_(in),
      current_(kEndMarker),
      next_pos_(0),
      capture_count_(0),
      has_more_(true),
      multiline_(multiline),
5115
      unicode_(unicode),
5116 5117 5118 5119
      simple_(false),
      contains_anchor_(false),
      is_scanned_for_captures_(false),
      failed_(false) {
5120
  Advance();
5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134
}


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


void RegExpParser::Advance() {
  if (next_pos_ < in()->length()) {
5135
    StackLimitCheck check(isolate());
5136
    if (check.HasOverflowed()) {
5137
      ReportError(CStrVector(Isolate::kStackOverflowMessage));
5138
    } else if (zone()->excess_allocation()) {
5139 5140 5141 5142 5143
      ReportError(CStrVector("Regular expression too large"));
    } else {
      current_ = in()->Get(next_pos_);
      next_pos_++;
    }
5144 5145
  } else {
    current_ = kEndMarker;
5146 5147 5148
    // Advance so that position() points to 1-after-the-last-character. This is
    // important so that Reset() to this position works correctly.
    next_pos_ = in()->length() + 1;
5149 5150 5151 5152 5153 5154 5155
    has_more_ = false;
  }
}


void RegExpParser::Reset(int pos) {
  next_pos_ = pos;
5156
  has_more_ = (pos < in()->length());
5157 5158 5159 5160 5161
  Advance();
}


void RegExpParser::Advance(int dist) {
5162 5163
  next_pos_ += dist - 1;
  Advance();
5164 5165 5166
}


5167 5168
bool RegExpParser::simple() {
  return simple_;
5169 5170
}

5171

5172 5173 5174 5175 5176 5177 5178
bool RegExpParser::IsSyntaxCharacter(uc32 c) {
  return c == '^' || c == '$' || c == '\\' || c == '.' || c == '*' ||
         c == '+' || c == '?' || c == '(' || c == ')' || c == '[' || c == ']' ||
         c == '{' || c == '}' || c == '|';
}


5179 5180
RegExpTree* RegExpParser::ReportError(Vector<const char> message) {
  failed_ = true;
5181
  *error_ = isolate()->factory()->NewStringFromAscii(message).ToHandleChecked();
5182 5183 5184
  // Zip to the end to make sure the no more input is read.
  current_ = kEndMarker;
  next_pos_ = in()->length();
5185 5186 5187 5188 5189 5190
  return NULL;
}


// Pattern ::
//   Disjunction
5191 5192
RegExpTree* RegExpParser::ParsePattern() {
  RegExpTree* result = ParseDisjunction(CHECK_FAILED);
5193
  DCHECK(!has_more());
5194 5195 5196 5197 5198
  // 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;
  }
5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212
  return result;
}


// Disjunction ::
//   Alternative
//   Alternative | Disjunction
// Alternative ::
//   [empty]
//   Term Alternative
// Term ::
//   Assertion
//   Atom
//   Atom Quantifier
5213
RegExpTree* RegExpParser::ParseDisjunction() {
5214
  // Used to store current state while parsing subexpressions.
5215
  RegExpParserState initial_state(NULL, INITIAL, 0, zone());
5216 5217 5218
  RegExpParserState* stored_state = &initial_state;
  // Cache the builder in a local variable for quick access.
  RegExpBuilder* builder = initial_state.builder();
5219 5220 5221
  while (true) {
    switch (current()) {
    case kEndMarker:
5222 5223 5224 5225
      if (stored_state->IsSubexpression()) {
        // Inside a parenthesized group when hitting end of input.
        ReportError(CStrVector("Unterminated group") CHECK_FAILED);
      }
5226
      DCHECK_EQ(INITIAL, stored_state->group_type());
5227 5228 5229 5230
      // Parsing completed successfully.
      return builder->ToRegExp();
    case ')': {
      if (!stored_state->IsSubexpression()) {
5231
        ReportError(CStrVector("Unmatched ')'") CHECK_FAILED);
5232
      }
5233
      DCHECK_NE(INITIAL, stored_state->group_type());
5234

5235
      Advance();
5236 5237 5238 5239 5240 5241 5242
      // 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();
5243
      SubexpressionType group_type = stored_state->group_type();
5244 5245 5246 5247 5248 5249

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

      // Build result of subexpression.
5250
      if (group_type == CAPTURE) {
5251
        RegExpCapture* capture = new(zone()) RegExpCapture(body, capture_index);
5252 5253
        captures_->at(capture_index - 1) = capture;
        body = capture;
5254
      } else if (group_type != GROUPING) {
5255
        DCHECK(group_type == POSITIVE_LOOKAHEAD ||
5256 5257
               group_type == NEGATIVE_LOOKAHEAD);
        bool is_positive = (group_type == POSITIVE_LOOKAHEAD);
5258
        body = new(zone()) RegExpLookahead(body,
5259 5260 5261
                                   is_positive,
                                   end_capture_index - capture_index,
                                   capture_index);
5262
      }
5263
      builder->AddAtom(body);
5264 5265
      // For compatability with JSC and ES3, we allow quantifiers after
      // lookaheads, and break in all cases.
5266 5267 5268 5269 5270
      break;
    }
    case '|': {
      Advance();
      builder->NewAlternative();
5271 5272 5273 5274 5275
      continue;
    }
    case '*':
    case '+':
    case '?':
5276
      return ReportError(CStrVector("Nothing to repeat"));
5277 5278
    case '^': {
      Advance();
5279
      if (multiline_) {
5280
        builder->AddAssertion(
5281
            new(zone()) RegExpAssertion(RegExpAssertion::START_OF_LINE));
5282
      } else {
5283
        builder->AddAssertion(
5284
            new(zone()) RegExpAssertion(RegExpAssertion::START_OF_INPUT));
5285 5286
        set_contains_anchor();
      }
5287 5288 5289 5290
      continue;
    }
    case '$': {
      Advance();
5291
      RegExpAssertion::AssertionType assertion_type =
5292 5293
          multiline_ ? RegExpAssertion::END_OF_LINE :
                       RegExpAssertion::END_OF_INPUT;
5294
      builder->AddAssertion(new(zone()) RegExpAssertion(assertion_type));
5295 5296 5297 5298 5299
      continue;
    }
    case '.': {
      Advance();
      // everything except \x0a, \x0d, \u2028 and \u2029
5300
      ZoneList<CharacterRange>* ranges =
5301 5302
          new(zone()) ZoneList<CharacterRange>(2, zone());
      CharacterRange::AddClassEscape('.', ranges, zone());
5303
      RegExpTree* atom = new(zone()) RegExpCharacterClass(ranges, false);
5304
      builder->AddAtom(atom);
5305 5306 5307
      break;
    }
    case '(': {
5308
      SubexpressionType subexpr_type = CAPTURE;
5309 5310 5311 5312
      Advance();
      if (current() == '?') {
        switch (Next()) {
          case ':':
5313
            subexpr_type = GROUPING;
5314 5315
            break;
          case '=':
5316
            subexpr_type = POSITIVE_LOOKAHEAD;
5317 5318
            break;
          case '!':
5319
            subexpr_type = NEGATIVE_LOOKAHEAD;
5320 5321 5322 5323 5324 5325 5326 5327
            break;
          default:
            ReportError(CStrVector("Invalid group") CHECK_FAILED);
            break;
        }
        Advance(2);
      } else {
        if (captures_ == NULL) {
5328
          captures_ = new(zone()) ZoneList<RegExpCapture*>(2, zone());
5329 5330 5331 5332
        }
        if (captures_started() >= kMaxCaptures) {
          ReportError(CStrVector("Too many captures") CHECK_FAILED);
        }
5333
        captures_->Add(NULL, zone());
5334 5335
      }
      // Store current state and begin new disjunction parsing.
5336
      stored_state = new(zone()) RegExpParserState(stored_state, subexpr_type,
5337
                                                   captures_started(), zone());
5338
      builder = stored_state->builder();
5339
      continue;
5340 5341
    }
    case '[': {
5342
      RegExpTree* atom = ParseCharacterClass(CHECK_FAILED);
5343
      builder->AddAtom(atom);
5344 5345 5346 5347 5348 5349 5350
      break;
    }
    // Atom ::
    //   \ AtomEscape
    case '\\':
      switch (Next()) {
      case kEndMarker:
5351
        return ReportError(CStrVector("\\ at end of pattern"));
5352 5353
      case 'b':
        Advance(2);
5354
        builder->AddAssertion(
5355
            new(zone()) RegExpAssertion(RegExpAssertion::BOUNDARY));
5356 5357 5358
        continue;
      case 'B':
        Advance(2);
5359
        builder->AddAssertion(
5360
            new(zone()) RegExpAssertion(RegExpAssertion::NON_BOUNDARY));
5361
        continue;
5362 5363 5364 5365 5366
      // AtomEscape ::
      //   CharacterClassEscape
      //
      // CharacterClassEscape :: one of
      //   d D s S w W
5367 5368 5369
      case 'd': case 'D': case 's': case 'S': case 'w': case 'W': {
        uc32 c = Next();
        Advance(2);
5370
        ZoneList<CharacterRange>* ranges =
5371 5372
            new(zone()) ZoneList<CharacterRange>(2, zone());
        CharacterRange::AddClassEscape(c, ranges, zone());
5373
        RegExpTree* atom = new(zone()) RegExpCharacterClass(ranges, false);
5374
        builder->AddAtom(atom);
5375
        break;
5376 5377 5378 5379 5380
      }
      case '1': case '2': case '3': case '4': case '5': case '6':
      case '7': case '8': case '9': {
        int index = 0;
        if (ParseBackReferenceIndex(&index)) {
5381 5382 5383 5384 5385 5386
          RegExpCapture* capture = NULL;
          if (captures_ != NULL && index <= captures_->length()) {
            capture = captures_->at(index - 1);
          }
          if (capture == NULL) {
            builder->AddEmpty();
5387
            break;
5388
          }
5389
          RegExpTree* atom = new(zone()) RegExpBackReference(capture);
5390
          builder->AddAtom(atom);
5391
          break;
5392 5393 5394
        }
        uc32 first_digit = Next();
        if (first_digit == '8' || first_digit == '9') {
5395 5396 5397
          // If the 'u' flag is present, only syntax characters can be escaped,
          // no other identity escapes are allowed. If the 'u' flag is not
          // present, all identity escapes are allowed.
5398
          if (!FLAG_harmony_unicode_regexps || !unicode_) {
5399 5400 5401 5402 5403
            builder->AddCharacter(first_digit);
            Advance(2);
          } else {
            return ReportError(CStrVector("Invalid escape"));
          }
5404 5405 5406 5407 5408 5409 5410
          break;
        }
      }
      // FALLTHROUGH
      case '0': {
        Advance();
        uc32 octal = ParseOctalLiteral();
5411
        builder->AddCharacter(octal);
5412 5413 5414 5415 5416 5417
        break;
      }
      // ControlEscape :: one of
      //   f n r t v
      case 'f':
        Advance(2);
5418
        builder->AddCharacter('\f');
5419 5420 5421
        break;
      case 'n':
        Advance(2);
5422
        builder->AddCharacter('\n');
5423 5424 5425
        break;
      case 'r':
        Advance(2);
5426
        builder->AddCharacter('\r');
5427 5428 5429
        break;
      case 't':
        Advance(2);
5430
        builder->AddCharacter('\t');
5431 5432 5433
        break;
      case 'v':
        Advance(2);
5434
        builder->AddCharacter('\v');
5435 5436
        break;
      case 'c': {
5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451
        Advance();
        uc32 controlLetter = Next();
        // Special case if it is an ASCII letter.
        // Convert lower case letters to uppercase.
        uc32 letter = controlLetter & ~('a' ^ 'A');
        if (letter < 'A' || 'Z' < letter) {
          // controlLetter is not in range 'A'-'Z' or 'a'-'z'.
          // This is outside the specification. We match JSC in
          // reading the backslash as a literal character instead
          // of as starting an escape.
          builder->AddCharacter('\\');
        } else {
          Advance(2);
          builder->AddCharacter(controlLetter & 0x1f);
        }
5452 5453 5454 5455 5456 5457
        break;
      }
      case 'x': {
        Advance(2);
        uc32 value;
        if (ParseHexEscape(2, &value)) {
5458
          builder->AddCharacter(value);
5459
        } else if (!FLAG_harmony_unicode_regexps || !unicode_) {
5460
          builder->AddCharacter('x');
5461 5462 5463 5464
        } else {
          // If the 'u' flag is present, invalid escapes are not treated as
          // identity escapes.
          return ReportError(CStrVector("Invalid escape"));
5465 5466 5467 5468 5469 5470
        }
        break;
      }
      case 'u': {
        Advance(2);
        uc32 value;
5471
        if (ParseUnicodeEscape(&value)) {
5472
          builder->AddCharacter(value);
5473
        } else if (!FLAG_harmony_unicode_regexps || !unicode_) {
5474
          builder->AddCharacter('u');
5475 5476 5477 5478
        } else {
          // If the 'u' flag is present, invalid escapes are not treated as
          // identity escapes.
          return ReportError(CStrVector("Invalid unicode escape"));
5479 5480 5481 5482
        }
        break;
      }
      default:
5483 5484 5485 5486
        Advance();
        // If the 'u' flag is present, only syntax characters can be escaped, no
        // other identity escapes are allowed. If the 'u' flag is not present,
        // all identity escapes are allowed.
5487
        if (!FLAG_harmony_unicode_regexps || !unicode_ ||
5488 5489 5490 5491 5492 5493
            IsSyntaxCharacter(current())) {
          builder->AddCharacter(current());
          Advance();
        } else {
          return ReportError(CStrVector("Invalid escape"));
        }
5494 5495 5496 5497 5498 5499
        break;
      }
      break;
    case '{': {
      int dummy;
      if (ParseIntervalQuantifier(&dummy, &dummy)) {
5500
        ReportError(CStrVector("Nothing to repeat") CHECK_FAILED);
5501 5502 5503 5504
      }
      // fallthrough
    }
    default:
5505
      builder->AddCharacter(current());
5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519
      Advance();
      break;
    }  // end switch(current())

    int min;
    int max;
    switch (current()) {
    // QuantifierPrefix ::
    //   *
    //   +
    //   ?
    //   {
    case '*':
      min = 0;
5520
      max = RegExpTree::kInfinity;
5521 5522 5523 5524
      Advance();
      break;
    case '+':
      min = 1;
5525
      max = RegExpTree::kInfinity;
5526 5527 5528 5529 5530 5531 5532 5533 5534
      Advance();
      break;
    case '?':
      min = 0;
      max = 1;
      Advance();
      break;
    case '{':
      if (ParseIntervalQuantifier(&min, &max)) {
5535 5536 5537 5538
        if (max < min) {
          ReportError(CStrVector("numbers out of order in {} quantifier.")
                      CHECK_FAILED);
        }
5539 5540 5541 5542 5543 5544 5545
        break;
      } else {
        continue;
      }
    default:
      continue;
    }
5546
    RegExpQuantifier::QuantifierType quantifier_type = RegExpQuantifier::GREEDY;
5547
    if (current() == '?') {
5548
      quantifier_type = RegExpQuantifier::NON_GREEDY;
5549 5550 5551
      Advance();
    } else if (FLAG_regexp_possessive_quantifier && current() == '+') {
      // FLAG_regexp_possessive_quantifier is a debug-only flag.
5552
      quantifier_type = RegExpQuantifier::POSSESSIVE;
5553 5554
      Advance();
    }
5555
    builder->AddQuantifierToAtom(min, max, quantifier_type);
5556 5557 5558 5559 5560
  }
}


#ifdef DEBUG
5561
// Currently only used in an DCHECK.
5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581
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() {
5582 5583 5584
  // Start with captures started previous to current position
  int capture_count = captures_started();
  // Add count of captures after this position.
5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604
  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 '(':
5605
        if (current() != '?') capture_count++;
5606 5607 5608
        break;
    }
  }
5609
  capture_count_ = capture_count;
5610 5611 5612 5613 5614
  is_scanned_for_captures_ = true;
}


bool RegExpParser::ParseBackReferenceIndex(int* index_out) {
5615 5616
  DCHECK_EQ('\\', current());
  DCHECK('1' <= Next() && Next() <= '9');
5617 5618
  // Try to parse a decimal literal that is no greater than the total number
  // of left capturing parentheses in the input.
5619 5620 5621 5622 5623 5624 5625
  int start = position();
  int value = Next() - '0';
  Advance(2);
  while (true) {
    uc32 c = current();
    if (IsDecimalDigit(c)) {
      value = 10 * value + (c - '0');
5626 5627 5628 5629
      if (value > kMaxCaptures) {
        Reset(start);
        return false;
      }
5630 5631 5632 5633 5634
      Advance();
    } else {
      break;
    }
  }
5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645
  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;
    }
  }
5646 5647 5648 5649 5650 5651 5652 5653 5654
  *index_out = value;
  return true;
}


// QuantifierPrefix ::
//   { DecimalDigits }
//   { DecimalDigits , }
//   { DecimalDigits , DecimalDigits }
5655 5656 5657
//
// Returns true if parsing succeeds, and set the min_out and max_out
// values. Values are truncated to RegExpTree::kInfinity if they overflow.
5658
bool RegExpParser::ParseIntervalQuantifier(int* min_out, int* max_out) {
5659
  DCHECK_EQ(current(), '{');
5660 5661 5662 5663 5664 5665 5666 5667
  int start = position();
  Advance();
  int min = 0;
  if (!IsDecimalDigit(current())) {
    Reset(start);
    return false;
  }
  while (IsDecimalDigit(current())) {
5668 5669 5670
    int next = current() - '0';
    if (min > (RegExpTree::kInfinity - next) / 10) {
      // Overflow. Skip past remaining decimal digits and return -1.
5671 5672 5673
      do {
        Advance();
      } while (IsDecimalDigit(current()));
5674 5675 5676 5677
      min = RegExpTree::kInfinity;
      break;
    }
    min = 10 * min + next;
5678 5679 5680 5681 5682 5683 5684 5685 5686
    Advance();
  }
  int max = 0;
  if (current() == '}') {
    max = min;
    Advance();
  } else if (current() == ',') {
    Advance();
    if (current() == '}') {
5687
      max = RegExpTree::kInfinity;
5688 5689 5690
      Advance();
    } else {
      while (IsDecimalDigit(current())) {
5691 5692
        int next = current() - '0';
        if (max > (RegExpTree::kInfinity - next) / 10) {
5693 5694 5695 5696
          do {
            Advance();
          } while (IsDecimalDigit(current()));
          max = RegExpTree::kInfinity;
5697 5698 5699
          break;
        }
        max = 10 * max + next;
5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718
        Advance();
      }
      if (current() != '}') {
        Reset(start);
        return false;
      }
      Advance();
    }
  } else {
    Reset(start);
    return false;
  }
  *min_out = min;
  *max_out = max;
  return true;
}


uc32 RegExpParser::ParseOctalLiteral() {
5719
  DCHECK(('0' <= current() && current() <= '7') || current() == kEndMarker);
5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735
  // 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;
}


5736
bool RegExpParser::ParseHexEscape(int length, uc32* value) {
5737 5738
  int start = position();
  uc32 val = 0;
5739
  for (int i = 0; i < length; ++i) {
5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753
    uc32 c = current();
    int d = HexValue(c);
    if (d < 0) {
      Reset(start);
      return false;
    }
    val = val * 16 + d;
    Advance();
  }
  *value = val;
  return true;
}


5754 5755 5756 5757
bool RegExpParser::ParseUnicodeEscape(uc32* value) {
  // Accept both \uxxxx and \u{xxxxxx} (if harmony unicode escapes are
  // allowed). In the latter case, the number of hex digits between { } is
  // arbitrary. \ and u have already been read.
5758
  if (current() == '{' && FLAG_harmony_unicode_regexps && unicode_) {
5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793
    int start = position();
    Advance();
    if (ParseUnlimitedLengthHexNumber(0x10ffff, value)) {
      if (current() == '}') {
        Advance();
        return true;
      }
    }
    Reset(start);
    return false;
  }
  // \u but no {, or \u{...} escapes not allowed.
  return ParseHexEscape(4, value);
}


bool RegExpParser::ParseUnlimitedLengthHexNumber(int max_value, uc32* value) {
  uc32 x = 0;
  int d = HexValue(current());
  if (d < 0) {
    return false;
  }
  while (d >= 0) {
    x = x * 16 + d;
    if (x > max_value) {
      return false;
    }
    Advance();
    d = HexValue(current());
  }
  *value = x;
  return true;
}


5794
uc32 RegExpParser::ParseClassCharacterEscape() {
5795 5796
  DCHECK(current() == '\\');
  DCHECK(has_next() && !IsSpecialClassEscape(Next()));
5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818
  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';
5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835
    case 'c': {
      uc32 controlLetter = Next();
      uc32 letter = controlLetter & ~('A' ^ 'a');
      // For compatibility with JSC, inside a character class
      // we also accept digits and underscore as control characters.
      if ((controlLetter >= '0' && controlLetter <= '9') ||
          controlLetter == '_' ||
          (letter >= 'A' && letter <= 'Z')) {
        Advance(2);
        // Control letters mapped to ASCII control characters in the range
        // 0x00-0x1f.
        return controlLetter & 0x1f;
      }
      // We match JSC in reading the backslash as a literal
      // character instead of as starting an escape.
      return '\\';
    }
5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847
    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;
      }
5848
      if (!FLAG_harmony_unicode_regexps || !unicode_) {
5849 5850 5851 5852 5853 5854 5855 5856
        // If \x is not followed by a two-digit hexadecimal, treat it
        // as an identity escape.
        return 'x';
      }
      // If the 'u' flag is present, invalid escapes are not treated as
      // identity escapes.
      ReportError(CStrVector("Invalid escape"));
      return 0;
5857 5858 5859 5860
    }
    case 'u': {
      Advance();
      uc32 value;
5861
      if (ParseUnicodeEscape(&value)) {
5862 5863
        return value;
      }
5864
      if (!FLAG_harmony_unicode_regexps || !unicode_) {
5865 5866 5867 5868 5869 5870
        return 'u';
      }
      // If the 'u' flag is present, invalid escapes are not treated as
      // identity escapes.
      ReportError(CStrVector("Invalid unicode escape"));
      return 0;
5871 5872 5873
    }
    default: {
      uc32 result = current();
5874 5875 5876
      // If the 'u' flag is present, only syntax characters can be escaped, no
      // other identity escapes are allowed. If the 'u' flag is not present, all
      // identity escapes are allowed.
5877 5878
      if (!FLAG_harmony_unicode_regexps || !unicode_ ||
          IsSyntaxCharacter(result)) {
5879 5880 5881 5882 5883
        Advance();
        return result;
      }
      ReportError(CStrVector("Invalid escape"));
      return 0;
5884 5885 5886 5887 5888 5889
    }
  }
  return 0;
}


5890
CharacterRange RegExpParser::ParseClassAtom(uc16* char_class) {
5891
  DCHECK_EQ(0, *char_class);
5892 5893 5894 5895
  uc32 first = current();
  if (first == '\\') {
    switch (Next()) {
      case 'w': case 'W': case 'd': case 'D': case 's': case 'S': {
5896
        *char_class = Next();
5897
        Advance(2);
5898
        return CharacterRange::Singleton(0);  // Return dummy value.
5899
      }
5900
      case kEndMarker:
5901
        return ReportError(CStrVector("\\ at end of pattern"));
5902
      default:
5903
        uc32 c = ParseClassCharacterEscape(CHECK_FAILED);
5904 5905 5906 5907 5908 5909 5910 5911 5912
        return CharacterRange::Singleton(c);
    }
  } else {
    Advance();
    return CharacterRange::Singleton(first);
  }
}


5913 5914 5915 5916 5917 5918 5919
static const uc16 kNoCharClass = 0;

// Adds range or pre-defined character class to character ranges.
// If char_class is not kInvalidClass, it's interpreted as a class
// escape (i.e., 's' means whitespace, from '\s').
static inline void AddRangeOrEscape(ZoneList<CharacterRange>* ranges,
                                    uc16 char_class,
5920 5921
                                    CharacterRange range,
                                    Zone* zone) {
5922
  if (char_class != kNoCharClass) {
5923
    CharacterRange::AddClassEscape(char_class, ranges, zone);
5924
  } else {
5925
    ranges->Add(range, zone);
5926 5927 5928 5929
  }
}


5930
RegExpTree* RegExpParser::ParseCharacterClass() {
5931 5932 5933
  static const char* kUnterminated = "Unterminated character class";
  static const char* kRangeOutOfOrder = "Range out of order in character class";

5934
  DCHECK_EQ(current(), '[');
5935 5936 5937 5938 5939 5940
  Advance();
  bool is_negated = false;
  if (current() == '^') {
    is_negated = true;
    Advance();
  }
5941 5942
  ZoneList<CharacterRange>* ranges =
      new(zone()) ZoneList<CharacterRange>(2, zone());
5943
  while (has_more() && current() != ']') {
5944
    uc16 char_class = kNoCharClass;
5945
    CharacterRange first = ParseClassAtom(&char_class CHECK_FAILED);
5946 5947 5948 5949 5950 5951 5952
    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() == ']') {
5953 5954
        AddRangeOrEscape(ranges, char_class, first, zone());
        ranges->Add(CharacterRange::Singleton('-'), zone());
5955 5956
        break;
      }
5957 5958 5959 5960
      uc16 char_class_2 = kNoCharClass;
      CharacterRange next = ParseClassAtom(&char_class_2 CHECK_FAILED);
      if (char_class != kNoCharClass || char_class_2 != kNoCharClass) {
        // Either end is an escaped character class. Treat the '-' verbatim.
5961 5962 5963
        AddRangeOrEscape(ranges, char_class, first, zone());
        ranges->Add(CharacterRange::Singleton('-'), zone());
        AddRangeOrEscape(ranges, char_class_2, next, zone());
5964
        continue;
5965
      }
5966
      if (first.from() > next.to()) {
5967
        return ReportError(CStrVector(kRangeOutOfOrder) CHECK_FAILED);
5968
      }
5969
      ranges->Add(CharacterRange::Range(first.from(), next.to()), zone());
5970
    } else {
5971
      AddRangeOrEscape(ranges, char_class, first, zone());
5972 5973 5974
    }
  }
  if (!has_more()) {
5975
    return ReportError(CStrVector(kUnterminated) CHECK_FAILED);
5976 5977 5978
  }
  Advance();
  if (ranges->length() == 0) {
5979
    ranges->Add(CharacterRange::Everything(), zone());
5980 5981
    is_negated = !is_negated;
  }
5982
  return new(zone()) RegExpCharacterClass(ranges, is_negated);
5983 5984 5985
}


5986 5987 5988
// ----------------------------------------------------------------------------
// The Parser interface.

5989 5990 5991
bool RegExpParser::ParseRegExp(Isolate* isolate, Zone* zone,
                               FlatStringReader* input, bool multiline,
                               bool unicode, RegExpCompileData* result) {
5992
  DCHECK(result != NULL);
5993
  RegExpParser parser(input, &result->error, multiline, unicode, isolate, zone);
5994
  RegExpTree* tree = parser.ParsePattern();
5995
  if (parser.failed()) {
5996 5997
    DCHECK(tree == NULL);
    DCHECK(!result->error.is_null());
5998
  } else {
5999 6000
    DCHECK(tree != NULL);
    DCHECK(result->error.is_null());
6001 6002 6003
    result->tree = tree;
    int capture_count = parser.captures_started();
    result->simple = tree->IsAtom() && parser.simple() && capture_count == 0;
6004
    result->contains_anchor = parser.contains_anchor();
6005
    result->capture_count = capture_count;
6006
  }
6007
  return !parser.failed();
6008 6009 6010
}


6011 6012
bool Parser::ParseStatic(ParseInfo* info) {
  Parser parser(info);
6013
  if (parser.Parse(info)) {
6014
    info->set_language_mode(info->literal()->language_mode());
6015 6016 6017 6018 6019 6020
    return true;
  }
  return false;
}


6021
bool Parser::Parse(ParseInfo* info) {
6022
  DCHECK(info->literal() == NULL);
6023
  FunctionLiteral* result = NULL;
6024 6025 6026 6027
  // Ok to use Isolate here; this function is only called in the main thread.
  DCHECK(parsing_on_main_thread_);
  Isolate* isolate = info->isolate();
  pre_parse_timer_ = isolate->counters()->pre_parse();
6028
  if (FLAG_trace_parse || allow_natives() || extension_ != NULL) {
6029
    // If intrinsics are allowed, the Parser cannot operate independent of the
6030
    // V8 heap because of Runtime. Tell the string table to internalize strings
6031
    // and values right after they're created.
6032
    ast_value_factory()->Internalize(isolate);
6033 6034
  }

6035 6036 6037
  if (info->is_lazy()) {
    DCHECK(!info->is_eval());
    if (info->shared_info()->is_function()) {
6038
      result = ParseLazy(isolate, info);
6039
    } else {
6040
      result = ParseProgram(isolate, info);
6041
    }
6042
  } else {
6043
    SetCachedData(info);
6044
    result = ParseProgram(isolate, info);
6045
  }
6046
  info->set_literal(result);
6047

6048
  Internalize(isolate, info->script(), result == NULL);
6049
  DCHECK(ast_value_factory()->IsInternalized());
6050
  return (result != NULL);
6051 6052
}

6053

6054
void Parser::ParseOnBackground(ParseInfo* info) {
6055 6056
  parsing_on_main_thread_ = false;

6057
  DCHECK(info->literal() == NULL);
6058 6059 6060 6061
  FunctionLiteral* result = NULL;
  fni_ = new (zone()) FuncNameInferrer(ast_value_factory(), zone());

  CompleteParserRecorder recorder;
6062
  if (produce_cached_parse_data()) log_ = &recorder;
6063

6064 6065 6066
  DCHECK(info->source_stream() != NULL);
  ExternalStreamingStream stream(info->source_stream(),
                                 info->source_stream_encoding());
6067
  scanner_.Initialize(&stream);
6068
  DCHECK(info->context().is_null() || info->context()->IsNativeContext());
6069 6070 6071 6072 6073 6074 6075

  // When streaming, we don't know the length of the source until we have parsed
  // it. The raw data can be UTF-8, so we wouldn't know the source length until
  // we have decoded it anyway even if we knew the raw data length (which we
  // don't). We work around this by storing all the scopes which need their end
  // position set at the end of the script (the top scope and possible eval
  // scopes) and set their end position after we know the script length.
wingo's avatar
wingo committed
6076
  result = DoParseProgram(info);
6077

6078
  info->set_literal(result);
6079 6080 6081 6082

  // We cannot internalize on a background thread; a foreground task will take
  // care of calling Parser::Internalize just before compilation.

6083
  if (produce_cached_parse_data()) {
6084
    if (result != NULL) *info->cached_data() = recorder.GetScriptData();
6085 6086 6087
    log_ = NULL;
  }
}
6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098


ParserTraits::TemplateLiteralState Parser::OpenTemplateLiteral(int pos) {
  return new (zone()) ParserTraits::TemplateLiteral(zone(), pos);
}


void Parser::AddTemplateSpan(TemplateLiteralState* state, bool tail) {
  int pos = scanner()->location().beg_pos;
  int end = scanner()->location().end_pos - (tail ? 1 : 2);
  const AstRawString* tv = scanner()->CurrentSymbol(ast_value_factory());
6099
  const AstRawString* trv = scanner()->CurrentRawSymbol(ast_value_factory());
6100
  Literal* cooked = factory()->NewStringLiteral(tv, pos);
6101 6102
  Literal* raw = factory()->NewStringLiteral(trv, pos);
  (*state)->AddTemplateSpan(cooked, raw, end, zone());
6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
}


void Parser::AddTemplateExpression(TemplateLiteralState* state,
                                   Expression* expression) {
  (*state)->AddExpression(expression, zone());
}


Expression* Parser::CloseTemplateLiteral(TemplateLiteralState* state, int start,
                                         Expression* tag) {
  TemplateLiteral* lit = *state;
  int pos = lit->position();
  const ZoneList<Expression*>* cooked_strings = lit->cooked();
6117
  const ZoneList<Expression*>* raw_strings = lit->raw();
6118
  const ZoneList<Expression*>* expressions = lit->expressions();
6119 6120
  DCHECK_EQ(cooked_strings->length(), raw_strings->length());
  DCHECK_EQ(cooked_strings->length(), expressions->length() + 1);
6121 6122 6123

  if (!tag) {
    // Build tree of BinaryOps to simplify code-generation
6124 6125 6126 6127 6128 6129 6130 6131 6132 6133
    Expression* expr = cooked_strings->at(0);
    int i = 0;
    while (i < expressions->length()) {
      Expression* sub = expressions->at(i++);
      Expression* cooked_str = cooked_strings->at(i);

      // Let middle be ToString(sub).
      ZoneList<Expression*>* args =
          new (zone()) ZoneList<Expression*>(1, zone());
      args->Add(sub, zone());
6134 6135
      Expression* middle = factory()->NewCallRuntime(Runtime::kInlineToString,
                                                     args, sub->position());
6136 6137

      expr = factory()->NewBinaryOperation(
6138 6139 6140
          Token::ADD, factory()->NewBinaryOperation(
                          Token::ADD, expr, middle, expr->position()),
          cooked_str, sub->position());
6141 6142 6143
    }
    return expr;
  } else {
6144
    uint32_t hash = ComputeTemplateLiteralHash(lit);
6145 6146 6147 6148

    int cooked_idx = function_state_->NextMaterializedLiteralIndex();
    int raw_idx = function_state_->NextMaterializedLiteralIndex();

6149
    // $getTemplateCallSite
6150 6151 6152
    ZoneList<Expression*>* args = new (zone()) ZoneList<Expression*>(4, zone());
    args->Add(factory()->NewArrayLiteral(
                  const_cast<ZoneList<Expression*>*>(cooked_strings),
6153
                  cooked_idx, is_strong(language_mode()), pos),
6154 6155 6156
              zone());
    args->Add(
        factory()->NewArrayLiteral(
6157 6158
            const_cast<ZoneList<Expression*>*>(raw_strings), raw_idx,
            is_strong(language_mode()), pos),
6159
        zone());
6160

6161
    // Ensure hash is suitable as a Smi value
6162 6163 6164
    Smi* hash_obj = Smi::cast(Internals::IntToSmi(static_cast<int>(hash)));
    args->Add(factory()->NewSmiLiteral(hash_obj->value(), pos), zone());

6165 6166
    this->CheckPossibleEvalCall(tag, scope_);
    Expression* call_site = factory()->NewCallRuntime(
6167
        Context::GET_TEMPLATE_CALL_SITE_INDEX, args, start);
6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178

    // Call TagFn
    ZoneList<Expression*>* call_args =
        new (zone()) ZoneList<Expression*>(expressions->length() + 1, zone());
    call_args->Add(call_site, zone());
    call_args->AddAll(*expressions, zone());
    return factory()->NewCall(tag, call_args, pos);
  }
}


6179 6180 6181
uint32_t Parser::ComputeTemplateLiteralHash(const TemplateLiteral* lit) {
  const ZoneList<Expression*>* raw_strings = lit->raw();
  int total = raw_strings->length();
6182 6183
  DCHECK(total);

6184
  uint32_t running_hash = 0;
6185

6186
  for (int index = 0; index < total; ++index) {
6187
    if (index) {
6188 6189
      running_hash = StringHasher::ComputeRunningHashOneByte(
          running_hash, "${}", 3);
6190 6191
    }

6192 6193 6194 6195 6196 6197
    const AstRawString* raw_string =
        raw_strings->at(index)->AsLiteral()->raw_value()->AsString();
    if (raw_string->is_one_byte()) {
      const char* data = reinterpret_cast<const char*>(raw_string->raw_data());
      running_hash = StringHasher::ComputeRunningHashOneByte(
          running_hash, data, raw_string->length());
6198
    } else {
6199 6200 6201
      const uc16* data = reinterpret_cast<const uc16*>(raw_string->raw_data());
      running_hash = StringHasher::ComputeRunningHash(running_hash, data,
                                                      raw_string->length());
6202
    }
6203 6204
  }

6205
  return running_hash;
6206
}
6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222


ZoneList<v8::internal::Expression*>* Parser::PrepareSpreadArguments(
    ZoneList<v8::internal::Expression*>* list) {
  ZoneList<v8::internal::Expression*>* args =
      new (zone()) ZoneList<v8::internal::Expression*>(1, zone());
  if (list->length() == 1) {
    // Spread-call with single spread argument produces an InternalArray
    // containing the values from the array.
    //
    // Function is called or constructed with the produced array of arguments
    //
    // EG: Apply(Func, Spread(spread0))
    ZoneList<Expression*>* spread_list =
        new (zone()) ZoneList<Expression*>(0, zone());
    spread_list->Add(list->at(0)->AsSpread()->expression(), zone());
6223 6224 6225
    args->Add(factory()->NewCallRuntime(Context::SPREAD_ITERABLE_INDEX,
                                        spread_list, RelocInfo::kNoPosition),
              zone());
6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247
    return args;
  } else {
    // Spread-call with multiple arguments produces array literals for each
    // sequences of unspread arguments, and converts each spread iterable to
    // an Internal array. Finally, all of these produced arrays are flattened
    // into a single InternalArray, containing the arguments for the call.
    //
    // EG: Apply(Func, Flatten([unspread0, unspread1], Spread(spread0),
    //                         Spread(spread1), [unspread2, unspread3]))
    int i = 0;
    int n = list->length();
    while (i < n) {
      if (!list->at(i)->IsSpread()) {
        ZoneList<v8::internal::Expression*>* unspread =
            new (zone()) ZoneList<v8::internal::Expression*>(1, zone());

        // Push array of unspread parameters
        while (i < n && !list->at(i)->IsSpread()) {
          unspread->Add(list->at(i++), zone());
        }
        int literal_index = function_state_->NextMaterializedLiteralIndex();
        args->Add(factory()->NewArrayLiteral(unspread, literal_index,
6248
                                             is_strong(language_mode()),
6249 6250 6251 6252 6253 6254 6255 6256 6257 6258
                                             RelocInfo::kNoPosition),
                  zone());

        if (i == n) break;
      }

      // Push eagerly spread argument
      ZoneList<v8::internal::Expression*>* spread_list =
          new (zone()) ZoneList<v8::internal::Expression*>(1, zone());
      spread_list->Add(list->at(i++)->AsSpread()->expression(), zone());
6259 6260
      args->Add(factory()->NewCallRuntime(Context::SPREAD_ITERABLE_INDEX,
                                          spread_list, RelocInfo::kNoPosition),
6261 6262 6263 6264
                zone());
    }

    list = new (zone()) ZoneList<v8::internal::Expression*>(1, zone());
6265 6266
    list->Add(factory()->NewCallRuntime(Context::SPREAD_ARGUMENTS_INDEX, args,
                                        RelocInfo::kNoPosition),
6267 6268 6269 6270 6271 6272 6273 6274 6275 6276
              zone());
    return list;
  }
  UNREACHABLE();
}


Expression* Parser::SpreadCall(Expression* function,
                               ZoneList<v8::internal::Expression*>* args,
                               int pos) {
6277
  if (function->IsSuperCallReference()) {
6278
    // Super calls
6279
    // %reflect_construct(%GetPrototype(<this-function>), args, new.target))
6280 6281
    ZoneList<Expression*>* tmp = new (zone()) ZoneList<Expression*>(1, zone());
    tmp->Add(function->AsSuperCallReference()->this_function_var(), zone());
6282 6283
    Expression* get_prototype =
        factory()->NewCallRuntime(Runtime::kGetPrototype, tmp, pos);
6284
    args->InsertAt(0, get_prototype, zone());
6285
    args->Add(function->AsSuperCallReference()->new_target_var(), zone());
6286 6287
    return factory()->NewCallRuntime(Context::REFLECT_CONSTRUCT_INDEX, args,
                                     pos);
6288 6289 6290
  } else {
    if (function->IsProperty()) {
      // Method calls
6291
      if (function->AsProperty()->IsSuperAccess()) {
6292 6293
        Expression* home =
            ThisExpression(scope_, factory(), RelocInfo::kNoPosition);
6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308
        args->InsertAt(0, function, zone());
        args->InsertAt(1, home, zone());
      } else {
        Variable* temp =
            scope_->NewTemporary(ast_value_factory()->empty_string());
        VariableProxy* obj = factory()->NewVariableProxy(temp);
        Assignment* assign_obj = factory()->NewAssignment(
            Token::ASSIGN, obj, function->AsProperty()->obj(),
            RelocInfo::kNoPosition);
        function = factory()->NewProperty(
            assign_obj, function->AsProperty()->key(), RelocInfo::kNoPosition);
        args->InsertAt(0, function, zone());
        obj = factory()->NewVariableProxy(temp);
        args->InsertAt(1, obj, zone());
      }
6309 6310 6311 6312 6313 6314
    } else {
      // Non-method calls
      args->InsertAt(0, function, zone());
      args->InsertAt(1, factory()->NewUndefinedLiteral(RelocInfo::kNoPosition),
                     zone());
    }
6315
    return factory()->NewCallRuntime(Context::REFLECT_APPLY_INDEX, args, pos);
6316 6317 6318 6319 6320 6321 6322 6323 6324
  }
}


Expression* Parser::SpreadCallNew(Expression* function,
                                  ZoneList<v8::internal::Expression*>* args,
                                  int pos) {
  args->InsertAt(0, function, zone());

6325
  return factory()->NewCallRuntime(Context::REFLECT_CONSTRUCT_INDEX, args, pos);
6326
}
6327 6328
}  // namespace internal
}  // namespace v8