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

28
#include <cmath>
29

30
#include "../include/v8stdint.h"
31

32
#include "allocation.h"
33
#include "checks.h"
34
#include "conversions.h"
35 36
#include "conversions-inl.h"
#include "globals.h"
37
#include "hashmap.h"
38
#include "list.h"
39
#include "preparse-data-format.h"
40 41
#include "preparse-data.h"
#include "preparser.h"
42 43
#include "unicode.h"
#include "utils.h"
44

45
#ifdef _MSC_VER
46 47
namespace std {

48 49 50
// Usually defined in math.h, but not in MSVC.
// Abstracted to work
int isfinite(double value);
51 52

}  // namespace std
53 54
#endif

55 56
namespace v8 {

57 58
namespace preparser {

59
PreParser::PreParseResult PreParser::PreParseLazyFunction(
60
    i::LanguageMode mode, bool is_generator, i::ParserRecorder* log) {
61 62 63 64 65
  log_ = log;
  // Lazy functions always have trivial outer scopes (no with/catch scopes).
  Scope top_scope(&scope_, kTopLevelScope);
  set_language_mode(mode);
  Scope function_scope(&scope_, kFunctionScope);
66
  function_scope.set_is_generator(is_generator);
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  ASSERT_EQ(i::Token::LBRACE, scanner_->current_token());
  bool ok = true;
  int start_position = scanner_->peek_location().beg_pos;
  ParseLazyFunctionLiteralBody(&ok);
  if (stack_overflow_) return kPreParseStackOverflow;
  if (!ok) {
    ReportUnexpectedToken(scanner_->current_token());
  } else {
    ASSERT_EQ(i::Token::RBRACE, scanner_->peek());
    if (!is_classic_mode()) {
      int end_pos = scanner_->location().end_pos;
      CheckOctalLiteral(start_position, end_pos, &ok);
      if (ok) {
        CheckDelayedStrictModeViolation(start_position, end_pos, &ok);
      }
    }
  }
  return kPreParseSuccess;
}


88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
// Preparsing checks a JavaScript program and emits preparse-data that helps
// a later parsing to be faster.
// See preparser-data.h for the data.

// The PreParser checks that the syntax follows the grammar for JavaScript,
// and collects some information about the program along the way.
// The grammar check is only performed in order to understand the program
// sufficiently to deduce some information about it, that can be used
// to speed up later parsing. Finding errors is not the goal of pre-parsing,
// rather it is to speed up properly written and correct programs.
// That means that contextual checks (like a label being declared where
// it is used) are generally omitted.

void PreParser::ReportUnexpectedToken(i::Token::Value token) {
  // We don't report stack overflows here, to avoid increasing the
  // stack depth even further.  Instead we report it after parsing is
  // over, in ParseProgram.
105
  if (token == i::Token::ILLEGAL && stack_overflow_) {
106 107
    return;
  }
108
  i::Scanner::Location source_location = scanner_->location();
109 110 111 112

  // Four of the tokens are treated specially
  switch (token) {
  case i::Token::EOS:
113
    return ReportMessageAt(source_location, "unexpected_eos", NULL);
114
  case i::Token::NUMBER:
115
    return ReportMessageAt(source_location, "unexpected_token_number", NULL);
116
  case i::Token::STRING:
117
    return ReportMessageAt(source_location, "unexpected_token_string", NULL);
118
  case i::Token::IDENTIFIER:
119
    return ReportMessageAt(source_location,
120
                           "unexpected_token_identifier", NULL);
121
  case i::Token::FUTURE_RESERVED_WORD:
122
    return ReportMessageAt(source_location, "unexpected_reserved", NULL);
123
  case i::Token::FUTURE_STRICT_RESERVED_WORD:
124
    return ReportMessageAt(source_location,
125
                           "unexpected_strict_reserved", NULL);
126 127
  default:
    const char* name = i::Token::String(token);
128
    ReportMessageAt(source_location, "unexpected_token", name);
129 130 131 132
  }
}


133 134 135 136 137
// Checks whether octal literal last seen is between beg_pos and end_pos.
// If so, reports an error.
void PreParser::CheckOctalLiteral(int beg_pos, int end_pos, bool* ok) {
  i::Scanner::Location octal = scanner_->octal_position();
  if (beg_pos <= octal.beg_pos && octal.end_pos <= end_pos) {
138
    ReportMessageAt(octal, "strict_octal_literal", NULL);
139 140 141 142 143 144
    scanner_->clear_octal_position();
    *ok = false;
  }
}


145 146 147 148 149 150 151
#define CHECK_OK  ok);                      \
  if (!*ok) return kUnknownSourceElements;  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


152
PreParser::Statement PreParser::ParseSourceElement(bool* ok) {
153 154 155 156 157 158 159 160
  // (Ecma 262 5th Edition, clause 14):
  // SourceElement:
  //    Statement
  //    FunctionDeclaration
  //
  // In harmony mode we allow additionally the following productions
  // SourceElement:
  //    LetDeclaration
161
  //    ConstDeclaration
162
  //    GeneratorDeclaration
163

164
  switch (peek()) {
165 166
    case i::Token::FUNCTION:
      return ParseFunctionDeclaration(ok);
167
    case i::Token::LET:
168
    case i::Token::CONST:
169 170 171 172 173 174 175
      return ParseVariableStatement(kSourceElement, ok);
    default:
      return ParseStatement(ok);
  }
}


176 177
PreParser::SourceElements PreParser::ParseSourceElements(int end_token,
                                                         bool* ok) {
178 179 180
  // SourceElements ::
  //   (Statement)* <end_token>

181
  bool allow_directive_prologue = true;
182
  while (peek() != end_token) {
183
    Statement statement = ParseSourceElement(CHECK_OK);
184
    if (allow_directive_prologue) {
185
      if (statement.IsUseStrictLiteral()) {
186
        set_language_mode(allow_harmony_scoping() ?
187
                          i::EXTENDED_MODE : i::STRICT_MODE);
188
      } else if (!statement.IsStringLiteral()) {
189 190 191
        allow_directive_prologue = false;
      }
    }
192 193 194 195 196
  }
  return kUnknownSourceElements;
}


197 198 199 200 201 202 203 204
#undef CHECK_OK
#define CHECK_OK  ok);                   \
  if (!*ok) return Statement::Default();  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


ager@chromium.org's avatar
ager@chromium.org committed
205
PreParser::Statement PreParser::ParseStatement(bool* ok) {
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  // Statement ::
  //   Block
  //   VariableStatement
  //   EmptyStatement
  //   ExpressionStatement
  //   IfStatement
  //   IterationStatement
  //   ContinueStatement
  //   BreakStatement
  //   ReturnStatement
  //   WithStatement
  //   LabelledStatement
  //   SwitchStatement
  //   ThrowStatement
  //   TryStatement
  //   DebuggerStatement

  // Note: Since labels can only be used by 'break' and 'continue'
  // statements, which themselves are only valid within blocks,
  // iterations or 'switch' statements (i.e., BreakableStatements),
  // labels can be simply ignored in all other cases; except for
  // trivial labeled break statements 'label: break label' which is
  // parsed into an empty statement.

  // Keep the source position of the statement
  switch (peek()) {
    case i::Token::LBRACE:
      return ParseBlock(ok);

    case i::Token::CONST:
236
    case i::Token::LET:
237
    case i::Token::VAR:
238
      return ParseVariableStatement(kStatement, ok);
239 240 241

    case i::Token::SEMICOLON:
      Next();
242
      return Statement::Default();
243 244

    case i::Token::IF:
245
      return ParseIfStatement(ok);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

    case i::Token::DO:
      return ParseDoWhileStatement(ok);

    case i::Token::WHILE:
      return ParseWhileStatement(ok);

    case i::Token::FOR:
      return ParseForStatement(ok);

    case i::Token::CONTINUE:
      return ParseContinueStatement(ok);

    case i::Token::BREAK:
      return ParseBreakStatement(ok);

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

    case i::Token::WITH:
      return ParseWithStatement(ok);

    case i::Token::SWITCH:
      return ParseSwitchStatement(ok);

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

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

277 278 279 280
    case i::Token::FUNCTION: {
      i::Scanner::Location start_location = scanner_->peek_location();
      Statement statement = ParseFunctionDeclaration(CHECK_OK);
      i::Scanner::Location end_location = scanner_->location();
281
      if (!is_classic_mode()) {
282 283 284 285 286 287 288 289
        ReportMessageAt(start_location.beg_pos, end_location.end_pos,
                        "strict_function", NULL);
        *ok = false;
        return Statement::Default();
      } else {
        return statement;
      }
    }
290 291 292 293 294 295 296 297 298 299

    case i::Token::DEBUGGER:
      return ParseDebuggerStatement(ok);

    default:
      return ParseExpressionOrLabelledStatement(ok);
  }
}


300
PreParser::Statement PreParser::ParseFunctionDeclaration(bool* ok) {
301 302
  // FunctionDeclaration ::
  //   'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
303 304 305
  // GeneratorDeclaration ::
  //   'function' '*' Identifier '(' FormalParameterListopt ')'
  //      '{' FunctionBody '}'
306
  Expect(i::Token::FUNCTION, CHECK_OK);
307

308
  bool is_generator = allow_generators_ && Check(i::Token::MUL);
309 310 311
  Identifier identifier = ParseIdentifier(CHECK_OK);
  i::Scanner::Location location = scanner_->location();

312
  Expression function_value = ParseFunctionLiteral(is_generator, CHECK_OK);
313 314 315 316 317 318

  if (function_value.IsStrictFunction() &&
      !identifier.IsValidStrictVariable()) {
    // Strict mode violation, using either reserved word or eval/arguments
    // as name of strict function.
    const char* type = "strict_function_name";
319
    if (identifier.IsFutureStrictReserved() || identifier.IsYield()) {
320 321
      type = "strict_reserved_word";
    }
322
    ReportMessageAt(location, type, NULL);
323 324
    *ok = false;
  }
325
  return Statement::FunctionDeclaration();
326 327 328
}


329
PreParser::Statement PreParser::ParseBlock(bool* ok) {
330 331 332 333 334 335 336 337
  // Block ::
  //   '{' Statement* '}'

  // Note that a Block does not introduce a new execution scope!
  // (ECMA-262, 3rd, 12.2)
  //
  Expect(i::Token::LBRACE, CHECK_OK);
  while (peek() != i::Token::RBRACE) {
338
    if (is_extended_mode()) {
339 340 341
      ParseSourceElement(CHECK_OK);
    } else {
      ParseStatement(CHECK_OK);
342
    }
343
  }
344 345
  Expect(i::Token::RBRACE, ok);
  return Statement::Default();
346 347 348
}


349 350 351
PreParser::Statement PreParser::ParseVariableStatement(
    VariableDeclarationContext var_context,
    bool* ok) {
352 353 354
  // VariableStatement ::
  //   VariableDeclarations ';'

355
  Statement result = ParseVariableDeclarations(var_context,
356
                                               NULL,
357 358
                                               NULL,
                                               CHECK_OK);
359 360 361 362 363 364 365 366 367 368
  ExpectSemicolon(CHECK_OK);
  return result;
}


// If the variable declaration declares exactly one non-const
// variable, then *var is set to that variable. In all other cases,
// *var is untouched; in particular, it is the caller's responsibility
// to initialize it properly. This mechanism is also used for the parsing
// of 'for-in' loops.
369 370
PreParser::Statement PreParser::ParseVariableDeclarations(
    VariableDeclarationContext var_context,
371
    VariableDeclarationProperties* decl_props,
372 373
    int* num_decl,
    bool* ok) {
374 375
  // VariableDeclarations ::
  //   ('var' | 'const') (Identifier ('=' AssignmentExpression)?)+[',']
376 377 378 379 380 381 382 383 384 385 386 387
  //
  // The ES6 Draft Rev3 specifies the following grammar for const declarations
  //
  // ConstDeclaration ::
  //   const ConstBinding (',' ConstBinding)* ';'
  // ConstBinding ::
  //   Identifier '=' AssignmentExpression
  //
  // TODO(ES6):
  // ConstBinding ::
  //   BindingPattern '=' AssignmentExpression
  bool require_initializer = false;
388 389 390
  if (peek() == i::Token::VAR) {
    Consume(i::Token::VAR);
  } else if (peek() == i::Token::CONST) {
391 392 393 394 395 396 397 398 399 400 401
    // TODO(ES6): The ES6 Draft Rev4 section 12.2.2 reads:
    //
    // ConstDeclaration : const ConstBinding (',' ConstBinding)* ';'
    //
    // * It is a Syntax Error if the code that matches this production is not
    //   contained in extended code.
    //
    // However disallowing const in classic mode will break compatibility with
    // existing pages. Therefore we keep allowing const with the old
    // non-harmony semantics in classic mode.
    Consume(i::Token::CONST);
402 403 404 405
    switch (language_mode()) {
      case i::CLASSIC_MODE:
        break;
      case i::STRICT_MODE: {
406
        i::Scanner::Location location = scanner_->peek_location();
407
        ReportMessageAt(location, "strict_const", NULL);
408 409 410
        *ok = false;
        return Statement::Default();
      }
411 412 413 414 415 416 417 418 419 420 421
      case i::EXTENDED_MODE:
        if (var_context != kSourceElement &&
            var_context != kForStatement) {
          i::Scanner::Location location = scanner_->peek_location();
          ReportMessageAt(location.beg_pos, location.end_pos,
                          "unprotected_const", NULL);
          *ok = false;
          return Statement::Default();
        }
        require_initializer = true;
        break;
422
    }
423
  } else if (peek() == i::Token::LET) {
424 425 426 427 428 429 430 431 432 433 434 435 436 437
    // ES6 Draft Rev4 section 12.2.1:
    //
    // LetDeclaration : let LetBindingList ;
    //
    // * It is a Syntax Error if the code that matches this production is not
    //   contained in extended code.
    if (!is_extended_mode()) {
      i::Scanner::Location location = scanner_->peek_location();
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "illegal_let", NULL);
      *ok = false;
      return Statement::Default();
    }
    Consume(i::Token::LET);
438 439 440 441 442 443 444 445
    if (var_context != kSourceElement &&
        var_context != kForStatement) {
      i::Scanner::Location location = scanner_->peek_location();
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "unprotected_let", NULL);
      *ok = false;
      return Statement::Default();
    }
446 447
  } else {
    *ok = false;
448
    return Statement::Default();
449 450
  }

451 452 453 454
  // 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). The scope
  // of a let declared variable is the scope of the immediately enclosing
  // block.
455 456 457 458
  int nvars = 0;  // the number of variables declared
  do {
    // Parse variable name.
    if (nvars > 0) Consume(i::Token::COMMA);
459
    Identifier identifier  = ParseIdentifier(CHECK_OK);
460
    if (!is_classic_mode() && !identifier.IsValidStrictVariable()) {
461 462 463 464 465 466
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_var_name",
                                    identifier,
                                    ok);
      return Statement::Default();
    }
467
    nvars++;
468
    if (peek() == i::Token::ASSIGN || require_initializer) {
469
      Expect(i::Token::ASSIGN, CHECK_OK);
470
      ParseAssignmentExpression(var_context != kForStatement, CHECK_OK);
471
      if (decl_props != NULL) *decl_props = kHasInitializers;
472 473 474 475
    }
  } while (peek() == i::Token::COMMA);

  if (num_decl != NULL) *num_decl = nvars;
476
  return Statement::Default();
477 478 479
}


480
PreParser::Statement PreParser::ParseExpressionOrLabelledStatement(bool* ok) {
481 482 483 484 485
  // ExpressionStatement | LabelledStatement ::
  //   Expression ';'
  //   Identifier ':' Statement

  Expression expr = ParseExpression(true, CHECK_OK);
486
  if (expr.IsRawIdentifier()) {
487
    ASSERT(!expr.AsIdentifier().IsFutureReserved());
488 489 490
    ASSERT(is_classic_mode() ||
           (!expr.AsIdentifier().IsFutureStrictReserved() &&
            !expr.AsIdentifier().IsYield()));
491
    if (peek() == i::Token::COLON) {
492
      Consume(i::Token::COLON);
493
      return ParseStatement(ok);
494
    }
495 496 497
    // Preparsing is disabled for extensions (because the extension details
    // aren't passed to lazily compiled functions), so we don't
    // accept "native function" in the preparser.
498 499 500
  }
  // Parsed expression statement.
  ExpectSemicolon(CHECK_OK);
501
  return Statement::ExpressionStatement(expr);
502 503 504
}


505
PreParser::Statement PreParser::ParseIfStatement(bool* ok) {
506 507 508 509 510 511 512 513 514 515 516 517
  // IfStatement ::
  //   'if' '(' Expression ')' Statement ('else' Statement)?

  Expect(i::Token::IF, CHECK_OK);
  Expect(i::Token::LPAREN, CHECK_OK);
  ParseExpression(true, CHECK_OK);
  Expect(i::Token::RPAREN, CHECK_OK);
  ParseStatement(CHECK_OK);
  if (peek() == i::Token::ELSE) {
    Next();
    ParseStatement(CHECK_OK);
  }
518
  return Statement::Default();
519 520 521
}


522
PreParser::Statement PreParser::ParseContinueStatement(bool* ok) {
523 524 525 526 527
  // ContinueStatement ::
  //   'continue' [no line terminator] Identifier? ';'

  Expect(i::Token::CONTINUE, CHECK_OK);
  i::Token::Value tok = peek();
528
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
529 530 531 532 533 534
      tok != i::Token::SEMICOLON &&
      tok != i::Token::RBRACE &&
      tok != i::Token::EOS) {
    ParseIdentifier(CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
535
  return Statement::Default();
536 537 538
}


539
PreParser::Statement PreParser::ParseBreakStatement(bool* ok) {
540 541 542 543 544
  // BreakStatement ::
  //   'break' [no line terminator] Identifier? ';'

  Expect(i::Token::BREAK, CHECK_OK);
  i::Token::Value tok = peek();
545
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
546 547 548 549 550 551
      tok != i::Token::SEMICOLON &&
      tok != i::Token::RBRACE &&
      tok != i::Token::EOS) {
    ParseIdentifier(CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
552
  return Statement::Default();
553 554 555
}


556
PreParser::Statement PreParser::ParseReturnStatement(bool* ok) {
557 558 559 560 561 562 563 564 565 566 567 568 569 570
  // ReturnStatement ::
  //   'return' [no line terminator] Expression? ';'

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

  // An ECMAScript program is considered syntactically incorrect if it
  // contains a return statement that is not within the body of a
  // function. See ECMA-262, section 12.9, page 67.
  // This is not handled during preparsing.

  i::Token::Value tok = peek();
571
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
572 573 574 575 576 577
      tok != i::Token::SEMICOLON &&
      tok != i::Token::RBRACE &&
      tok != i::Token::EOS) {
    ParseExpression(true, CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
578
  return Statement::Default();
579 580 581
}


582
PreParser::Statement PreParser::ParseWithStatement(bool* ok) {
583 584 585
  // WithStatement ::
  //   'with' '(' Expression ')' Statement
  Expect(i::Token::WITH, CHECK_OK);
586
  if (!is_classic_mode()) {
587
    i::Scanner::Location location = scanner_->location();
588
    ReportMessageAt(location, "strict_mode_with", NULL);
589 590 591
    *ok = false;
    return Statement::Default();
  }
592 593 594 595
  Expect(i::Token::LPAREN, CHECK_OK);
  ParseExpression(true, CHECK_OK);
  Expect(i::Token::RPAREN, CHECK_OK);

596
  Scope::InsideWith iw(scope_);
597
  ParseStatement(CHECK_OK);
598
  return Statement::Default();
599 600 601
}


602
PreParser::Statement PreParser::ParseSwitchStatement(bool* ok) {
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
  // SwitchStatement ::
  //   'switch' '(' Expression ')' '{' CaseClause* '}'

  Expect(i::Token::SWITCH, CHECK_OK);
  Expect(i::Token::LPAREN, CHECK_OK);
  ParseExpression(true, CHECK_OK);
  Expect(i::Token::RPAREN, CHECK_OK);

  Expect(i::Token::LBRACE, CHECK_OK);
  i::Token::Value token = peek();
  while (token != i::Token::RBRACE) {
    if (token == i::Token::CASE) {
      Expect(i::Token::CASE, CHECK_OK);
      ParseExpression(true, CHECK_OK);
    } else {
618
      Expect(i::Token::DEFAULT, CHECK_OK);
619
    }
620
    Expect(i::Token::COLON, CHECK_OK);
621
    token = peek();
622 623 624 625 626 627
    while (token != i::Token::CASE &&
           token != i::Token::DEFAULT &&
           token != i::Token::RBRACE) {
      ParseStatement(CHECK_OK);
      token = peek();
    }
628
  }
629 630
  Expect(i::Token::RBRACE, ok);
  return Statement::Default();
631 632 633
}


634
PreParser::Statement PreParser::ParseDoWhileStatement(bool* ok) {
635 636 637 638 639 640 641 642
  // DoStatement ::
  //   'do' Statement 'while' '(' Expression ')' ';'

  Expect(i::Token::DO, CHECK_OK);
  ParseStatement(CHECK_OK);
  Expect(i::Token::WHILE, CHECK_OK);
  Expect(i::Token::LPAREN, CHECK_OK);
  ParseExpression(true, CHECK_OK);
643
  Expect(i::Token::RPAREN, ok);
644
  if (peek() == i::Token::SEMICOLON) Consume(i::Token::SEMICOLON);
645
  return Statement::Default();
646 647 648
}


649
PreParser::Statement PreParser::ParseWhileStatement(bool* ok) {
650 651 652 653 654 655 656
  // WhileStatement ::
  //   'while' '(' Expression ')' Statement

  Expect(i::Token::WHILE, CHECK_OK);
  Expect(i::Token::LPAREN, CHECK_OK);
  ParseExpression(true, CHECK_OK);
  Expect(i::Token::RPAREN, CHECK_OK);
657 658
  ParseStatement(ok);
  return Statement::Default();
659 660 661
}


662
bool PreParser::CheckInOrOf(bool accept_OF) {
663
  if (peek() == i::Token::IN ||
664
      (allow_for_of() && accept_OF && peek() == i::Token::IDENTIFIER &&
665 666 667 668 669 670 671 672
       scanner_->is_next_contextual_keyword(v8::internal::CStrVector("of")))) {
    Next();
    return true;
  }
  return false;
}


673
PreParser::Statement PreParser::ParseForStatement(bool* ok) {
674 675 676 677 678 679
  // ForStatement ::
  //   'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement

  Expect(i::Token::FOR, CHECK_OK);
  Expect(i::Token::LPAREN, CHECK_OK);
  if (peek() != i::Token::SEMICOLON) {
680 681
    if (peek() == i::Token::VAR || peek() == i::Token::CONST ||
        peek() == i::Token::LET) {
682
      bool is_let = peek() == i::Token::LET;
683
      int decl_count;
684 685 686
      VariableDeclarationProperties decl_props = kHasNoInitializers;
      ParseVariableDeclarations(
          kForStatement, &decl_props, &decl_count, CHECK_OK);
687 688 689 690
      bool has_initializers = decl_props == kHasInitializers;
      bool accept_IN = decl_count == 1 && !(is_let && has_initializers);
      bool accept_OF = !has_initializers;
      if (accept_IN && CheckInOrOf(accept_OF)) {
691 692 693 694
        ParseExpression(true, CHECK_OK);
        Expect(i::Token::RPAREN, CHECK_OK);

        ParseStatement(CHECK_OK);
695
        return Statement::Default();
696 697
      }
    } else {
698 699
      Expression lhs = ParseExpression(false, CHECK_OK);
      if (CheckInOrOf(lhs.IsIdentifier())) {
700 701 702 703
        ParseExpression(true, CHECK_OK);
        Expect(i::Token::RPAREN, CHECK_OK);

        ParseStatement(CHECK_OK);
704
        return Statement::Default();
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
      }
    }
  }

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

  if (peek() != i::Token::SEMICOLON) {
    ParseExpression(true, CHECK_OK);
  }
  Expect(i::Token::SEMICOLON, CHECK_OK);

  if (peek() != i::Token::RPAREN) {
    ParseExpression(true, CHECK_OK);
  }
  Expect(i::Token::RPAREN, CHECK_OK);

722 723
  ParseStatement(ok);
  return Statement::Default();
724 725 726
}


727
PreParser::Statement PreParser::ParseThrowStatement(bool* ok) {
728 729 730 731
  // ThrowStatement ::
  //   'throw' [no line terminator] Expression ';'

  Expect(i::Token::THROW, CHECK_OK);
732
  if (scanner_->HasAnyLineTerminatorBeforeNext()) {
733
    i::Scanner::Location pos = scanner_->location();
734
    ReportMessageAt(pos, "newline_after_throw", NULL);
735
    *ok = false;
736
    return Statement::Default();
737 738
  }
  ParseExpression(true, CHECK_OK);
739 740
  ExpectSemicolon(ok);
  return Statement::Default();
741 742 743
}


744
PreParser::Statement PreParser::ParseTryStatement(bool* ok) {
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
  // TryStatement ::
  //   'try' Block Catch
  //   'try' Block Finally
  //   'try' Block Catch Finally
  //
  // Catch ::
  //   'catch' '(' Identifier ')' Block
  //
  // Finally ::
  //   'finally' Block

  // In preparsing, allow any number of catch/finally blocks, including zero
  // of both.

  Expect(i::Token::TRY, CHECK_OK);

  ParseBlock(CHECK_OK);

  bool catch_or_finally_seen = false;
  if (peek() == i::Token::CATCH) {
    Consume(i::Token::CATCH);
    Expect(i::Token::LPAREN, CHECK_OK);
767
    Identifier id = ParseIdentifier(CHECK_OK);
768
    if (!is_classic_mode() && !id.IsValidStrictVariable()) {
769 770 771 772 773 774
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_catch_variable",
                                    id,
                                    ok);
      return Statement::Default();
    }
775
    Expect(i::Token::RPAREN, CHECK_OK);
776 777 778
    { Scope::InsideWith iw(scope_);
      ParseBlock(CHECK_OK);
    }
779 780 781 782 783 784 785 786 787 788
    catch_or_finally_seen = true;
  }
  if (peek() == i::Token::FINALLY) {
    Consume(i::Token::FINALLY);
    ParseBlock(CHECK_OK);
    catch_or_finally_seen = true;
  }
  if (!catch_or_finally_seen) {
    *ok = false;
  }
789
  return Statement::Default();
790 791 792
}


793
PreParser::Statement PreParser::ParseDebuggerStatement(bool* ok) {
794 795 796 797 798 799 800
  // 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 if a
  // break point is present.
  // DebuggerStatement ::
  //   'debugger' ';'

  Expect(i::Token::DEBUGGER, CHECK_OK);
801 802
  ExpectSemicolon(ok);
  return Statement::Default();
803 804 805
}


806 807 808 809 810 811 812 813
#undef CHECK_OK
#define CHECK_OK  ok);                     \
  if (!*ok) return Expression::Default();  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


814
// Precedence = 1
815
PreParser::Expression PreParser::ParseExpression(bool accept_IN, bool* ok) {
816 817 818 819 820 821 822 823
  // Expression ::
  //   AssignmentExpression
  //   Expression ',' AssignmentExpression

  Expression result = ParseAssignmentExpression(accept_IN, CHECK_OK);
  while (peek() == i::Token::COMMA) {
    Expect(i::Token::COMMA, CHECK_OK);
    ParseAssignmentExpression(accept_IN, CHECK_OK);
824
    result = Expression::Default();
825 826 827 828 829 830
  }
  return result;
}


// Precedence = 2
831 832
PreParser::Expression PreParser::ParseAssignmentExpression(bool accept_IN,
                                                           bool* ok) {
833 834
  // AssignmentExpression ::
  //   ConditionalExpression
835
  //   YieldExpression
836 837
  //   LeftHandSideExpression AssignmentOperator AssignmentExpression

838 839 840 841
  if (scope_->is_generator() && peek() == i::Token::YIELD) {
    return ParseYieldExpression(ok);
  }

842
  i::Scanner::Location before = scanner_->peek_location();
843 844 845 846 847 848 849
  Expression expression = ParseConditionalExpression(accept_IN, CHECK_OK);

  if (!i::Token::IsAssignmentOp(peek())) {
    // Parsed conditional expression only (no assignment).
    return expression;
  }

850 851
  if (!is_classic_mode() &&
      expression.IsIdentifier() &&
852 853 854 855 856 857 858 859
      expression.AsIdentifier().IsEvalOrArguments()) {
    i::Scanner::Location after = scanner_->location();
    ReportMessageAt(before.beg_pos, after.end_pos,
                    "strict_lhs_assignment", NULL);
    *ok = false;
    return Expression::Default();
  }

860 861 862
  i::Token::Value op = Next();  // Get assignment operator.
  ParseAssignmentExpression(accept_IN, CHECK_OK);

863
  if ((op == i::Token::ASSIGN) && expression.IsThisProperty()) {
864 865 866
    scope_->AddProperty();
  }

867
  return Expression::Default();
868 869 870
}


871 872 873 874 875 876 877 878 879 880 881 882 883
// Precedence = 3
PreParser::Expression PreParser::ParseYieldExpression(bool* ok) {
  // YieldExpression ::
  //   'yield' '*'? AssignmentExpression
  Consume(i::Token::YIELD);
  Check(i::Token::MUL);

  ParseAssignmentExpression(false, CHECK_OK);

  return Expression::Default();
}


884
// Precedence = 3
885 886
PreParser::Expression PreParser::ParseConditionalExpression(bool accept_IN,
                                                            bool* ok) {
887 888 889 890 891 892 893 894 895 896 897 898 899 900
  // ConditionalExpression ::
  //   LogicalOrExpression
  //   LogicalOrExpression '?' AssignmentExpression ':' AssignmentExpression

  // We start using the binary expression parser for prec >= 4 only!
  Expression expression = ParseBinaryExpression(4, accept_IN, CHECK_OK);
  if (peek() != i::Token::CONDITIONAL) return expression;
  Consume(i::Token::CONDITIONAL);
  // In parsing the first assignment expression in conditional
  // expressions we always accept the 'in' keyword; see ECMA-262,
  // section 11.12, page 58.
  ParseAssignmentExpression(true, CHECK_OK);
  Expect(i::Token::COLON, CHECK_OK);
  ParseAssignmentExpression(accept_IN, CHECK_OK);
901
  return Expression::Default();
902 903 904 905 906 907 908 909 910 911 912 913
}


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

  return i::Token::Precedence(tok);
}


// Precedence >= 4
914 915 916
PreParser::Expression PreParser::ParseBinaryExpression(int prec,
                                                       bool accept_IN,
                                                       bool* ok) {
917 918 919 920 921 922
  Expression result = ParseUnaryExpression(CHECK_OK);
  for (int prec1 = Precedence(peek(), accept_IN); prec1 >= prec; prec1--) {
    // prec1 >= 4
    while (Precedence(peek(), accept_IN) == prec1) {
      Next();
      ParseBinaryExpression(prec1 + 1, accept_IN, CHECK_OK);
923
      result = Expression::Default();
924 925 926 927 928 929
    }
  }
  return result;
}


930
PreParser::Expression PreParser::ParseUnaryExpression(bool* ok) {
931 932 933 934 935 936 937 938 939 940 941 942 943
  // UnaryExpression ::
  //   PostfixExpression
  //   'delete' UnaryExpression
  //   'void' UnaryExpression
  //   'typeof' UnaryExpression
  //   '++' UnaryExpression
  //   '--' UnaryExpression
  //   '+' UnaryExpression
  //   '-' UnaryExpression
  //   '~' UnaryExpression
  //   '!' UnaryExpression

  i::Token::Value op = peek();
944
  if (i::Token::IsUnaryOp(op)) {
945 946
    op = Next();
    ParseUnaryExpression(ok);
947 948 949 950 951
    return Expression::Default();
  } else if (i::Token::IsCountOp(op)) {
    op = Next();
    i::Scanner::Location before = scanner_->peek_location();
    Expression expression = ParseUnaryExpression(CHECK_OK);
952 953
    if (!is_classic_mode() &&
        expression.IsIdentifier() &&
954 955 956 957 958 959 960
        expression.AsIdentifier().IsEvalOrArguments()) {
      i::Scanner::Location after = scanner_->location();
      ReportMessageAt(before.beg_pos, after.end_pos,
                      "strict_lhs_prefix", NULL);
      *ok = false;
    }
    return Expression::Default();
961 962 963 964 965 966
  } else {
    return ParsePostfixExpression(ok);
  }
}


967
PreParser::Expression PreParser::ParsePostfixExpression(bool* ok) {
968 969 970
  // PostfixExpression ::
  //   LeftHandSideExpression ('++' | '--')?

971
  i::Scanner::Location before = scanner_->peek_location();
972
  Expression expression = ParseLeftHandSideExpression(CHECK_OK);
973
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
974
      i::Token::IsCountOp(peek())) {
975 976
    if (!is_classic_mode() &&
        expression.IsIdentifier() &&
977 978 979 980 981 982 983
        expression.AsIdentifier().IsEvalOrArguments()) {
      i::Scanner::Location after = scanner_->location();
      ReportMessageAt(before.beg_pos, after.end_pos,
                      "strict_lhs_postfix", NULL);
      *ok = false;
      return Expression::Default();
    }
984
    Next();
985
    return Expression::Default();
986 987 988 989 990
  }
  return expression;
}


991
PreParser::Expression PreParser::ParseLeftHandSideExpression(bool* ok) {
992 993 994
  // LeftHandSideExpression ::
  //   (NewExpression | MemberExpression) ...

995
  Expression result = Expression::Default();
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
  if (peek() == i::Token::NEW) {
    result = ParseNewExpression(CHECK_OK);
  } else {
    result = ParseMemberExpression(CHECK_OK);
  }

  while (true) {
    switch (peek()) {
      case i::Token::LBRACK: {
        Consume(i::Token::LBRACK);
        ParseExpression(true, CHECK_OK);
        Expect(i::Token::RBRACK, CHECK_OK);
1008 1009
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1010
        } else {
1011
          result = Expression::Default();
1012 1013 1014 1015 1016 1017
        }
        break;
      }

      case i::Token::LPAREN: {
        ParseArguments(CHECK_OK);
1018
        result = Expression::Default();
1019 1020 1021 1022 1023 1024
        break;
      }

      case i::Token::PERIOD: {
        Consume(i::Token::PERIOD);
        ParseIdentifierName(CHECK_OK);
1025 1026
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1027
        } else {
1028
          result = Expression::Default();
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        }
        break;
      }

      default:
        return result;
    }
  }
}


1040
PreParser::Expression PreParser::ParseNewExpression(bool* ok) {
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  // NewExpression ::
  //   ('new')+ MemberExpression

  // The grammar for new expressions is pretty warped. The keyword
  // 'new' can either be a part of the new expression (where it isn't
  // followed by an argument list) or a part of the member expression,
  // where it must be followed by an argument list. To accommodate
  // this, we parse the 'new' keywords greedily and keep track of how
  // many we have parsed. This information is then passed on to the
  // member expression parser, which is only allowed to match argument
  // lists as long as it has 'new' prefixes left
  unsigned new_count = 0;
  do {
    Consume(i::Token::NEW);
    new_count++;
  } while (peek() == i::Token::NEW);

  return ParseMemberWithNewPrefixesExpression(new_count, ok);
}


1062
PreParser::Expression PreParser::ParseMemberExpression(bool* ok) {
1063 1064 1065 1066
  return ParseMemberWithNewPrefixesExpression(0, ok);
}


1067
PreParser::Expression PreParser::ParseMemberWithNewPrefixesExpression(
1068 1069 1070 1071 1072 1073
    unsigned new_count, bool* ok) {
  // MemberExpression ::
  //   (PrimaryExpression | FunctionLiteral)
  //     ('[' Expression ']' | '.' Identifier | Arguments)*

  // Parse the initial primary or function expression.
1074
  Expression result = Expression::Default();
1075 1076
  if (peek() == i::Token::FUNCTION) {
    Consume(i::Token::FUNCTION);
1077 1078

    bool is_generator = allow_generators_ && Check(i::Token::MUL);
1079
    Identifier identifier = Identifier::Default();
1080
    if (peek_any_identifier()) {
1081
      identifier = ParseIdentifier(CHECK_OK);
1082
    }
1083
    result = ParseFunctionLiteral(is_generator, CHECK_OK);
1084 1085 1086 1087 1088 1089 1090
    if (result.IsStrictFunction() && !identifier.IsValidStrictVariable()) {
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_function_name",
                                    identifier,
                                    ok);
      return Expression::Default();
    }
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
  } else {
    result = ParsePrimaryExpression(CHECK_OK);
  }

  while (true) {
    switch (peek()) {
      case i::Token::LBRACK: {
        Consume(i::Token::LBRACK);
        ParseExpression(true, CHECK_OK);
        Expect(i::Token::RBRACK, CHECK_OK);
1101 1102
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1103
        } else {
1104
          result = Expression::Default();
1105 1106 1107 1108 1109 1110
        }
        break;
      }
      case i::Token::PERIOD: {
        Consume(i::Token::PERIOD);
        ParseIdentifierName(CHECK_OK);
1111 1112
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1113
        } else {
1114
          result = Expression::Default();
1115 1116 1117 1118 1119 1120 1121 1122
        }
        break;
      }
      case i::Token::LPAREN: {
        if (new_count == 0) return result;
        // Consume one of the new prefixes (already parsed).
        ParseArguments(CHECK_OK);
        new_count--;
1123
        result = Expression::Default();
1124 1125 1126 1127 1128 1129 1130 1131 1132
        break;
      }
      default:
        return result;
    }
  }
}


1133
PreParser::Expression PreParser::ParsePrimaryExpression(bool* ok) {
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  // PrimaryExpression ::
  //   'this'
  //   'null'
  //   'true'
  //   'false'
  //   Identifier
  //   Number
  //   String
  //   ArrayLiteral
  //   ObjectLiteral
  //   RegExpLiteral
  //   '(' Expression ')'

1147
  Expression result = Expression::Default();
1148 1149 1150
  switch (peek()) {
    case i::Token::THIS: {
      Next();
1151
      result = Expression::This();
1152 1153 1154
      break;
    }

1155
    case i::Token::FUTURE_RESERVED_WORD:
1156
    case i::Token::FUTURE_STRICT_RESERVED_WORD:
1157
    case i::Token::YIELD:
1158 1159
    case i::Token::IDENTIFIER: {
      Identifier id = ParseIdentifier(CHECK_OK);
1160
      result = Expression::FromIdentifier(id);
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
      break;
    }

    case i::Token::NULL_LITERAL:
    case i::Token::TRUE_LITERAL:
    case i::Token::FALSE_LITERAL:
    case i::Token::NUMBER: {
      Next();
      break;
    }
    case i::Token::STRING: {
      Next();
      result = GetStringSymbol();
      break;
    }

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

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

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

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

    case i::Token::LPAREN:
      Consume(i::Token::LPAREN);
1195
      parenthesized_function_ = (peek() == i::Token::FUNCTION);
1196 1197
      result = ParseExpression(true, CHECK_OK);
      Expect(i::Token::RPAREN, CHECK_OK);
1198
      result = result.Parenthesize();
1199 1200 1201 1202 1203 1204 1205 1206 1207
      break;

    case i::Token::MOD:
      result = ParseV8Intrinsic(CHECK_OK);
      break;

    default: {
      Next();
      *ok = false;
1208
      return Expression::Default();
1209 1210 1211 1212 1213 1214 1215
    }
  }

  return result;
}


1216
PreParser::Expression PreParser::ParseArrayLiteral(bool* ok) {
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
  // ArrayLiteral ::
  //   '[' Expression? (',' Expression?)* ']'
  Expect(i::Token::LBRACK, CHECK_OK);
  while (peek() != i::Token::RBRACK) {
    if (peek() != i::Token::COMMA) {
      ParseAssignmentExpression(true, CHECK_OK);
    }
    if (peek() != i::Token::RBRACK) {
      Expect(i::Token::COMMA, CHECK_OK);
    }
  }
  Expect(i::Token::RBRACK, CHECK_OK);

  scope_->NextMaterializedLiteralIndex();
1231
  return Expression::Default();
1232 1233
}

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
void PreParser::CheckDuplicate(DuplicateFinder* finder,
                               i::Token::Value property,
                               int type,
                               bool* ok) {
  int old_type;
  if (property == i::Token::NUMBER) {
    old_type = finder->AddNumber(scanner_->literal_ascii_string(), type);
  } else if (scanner_->is_literal_ascii()) {
    old_type = finder->AddAsciiSymbol(scanner_->literal_ascii_string(),
                                      type);
  } else {
1245
    old_type = finder->AddUtf16Symbol(scanner_->literal_utf16_string(), type);
1246 1247 1248 1249
  }
  if (HasConflict(old_type, type)) {
    if (IsDataDataConflict(old_type, type)) {
      // Both are data properties.
1250
      if (is_classic_mode()) return;
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
      ReportMessageAt(scanner_->location(),
                      "strict_duplicate_property", NULL);
    } else if (IsDataAccessorConflict(old_type, type)) {
      // Both a data and an accessor property with the same name.
      ReportMessageAt(scanner_->location(),
                      "accessor_data_property", NULL);
    } else {
      ASSERT(IsAccessorAccessorConflict(old_type, type));
      // Both accessors of the same type.
      ReportMessageAt(scanner_->location(),
                      "accessor_get_set", NULL);
    }
    *ok = false;
  }
}

1267

1268
PreParser::Expression PreParser::ParseObjectLiteral(bool* ok) {
1269 1270 1271 1272 1273 1274 1275
  // ObjectLiteral ::
  //   '{' (
  //       ((IdentifierName | String | Number) ':' AssignmentExpression)
  //     | (('get' | 'set') (IdentifierName | String | Number) FunctionLiteral)
  //    )*[','] '}'

  Expect(i::Token::LBRACE, CHECK_OK);
1276
  DuplicateFinder duplicate_finder(scanner_->unicode_cache());
1277 1278 1279
  while (peek() != i::Token::RBRACE) {
    i::Token::Value next = peek();
    switch (next) {
1280
      case i::Token::IDENTIFIER:
1281 1282
      case i::Token::FUTURE_RESERVED_WORD:
      case i::Token::FUTURE_STRICT_RESERVED_WORD: {
1283 1284
        bool is_getter = false;
        bool is_setter = false;
1285
        ParseIdentifierNameOrGetOrSet(&is_getter, &is_setter, CHECK_OK);
1286 1287
        if ((is_getter || is_setter) && peek() != i::Token::COLON) {
            i::Token::Value name = Next();
1288
            bool is_keyword = i::Token::IsKeyword(name);
1289
            if (name != i::Token::IDENTIFIER &&
1290
                name != i::Token::FUTURE_RESERVED_WORD &&
1291
                name != i::Token::FUTURE_STRICT_RESERVED_WORD &&
1292 1293
                name != i::Token::NUMBER &&
                name != i::Token::STRING &&
1294
                !is_keyword) {
1295
              *ok = false;
1296
              return Expression::Default();
1297
            }
1298 1299 1300
            if (!is_keyword) {
              LogSymbol();
            }
1301 1302
            PropertyType type = is_getter ? kGetterProperty : kSetterProperty;
            CheckDuplicate(&duplicate_finder, name, type, CHECK_OK);
1303
            ParseFunctionLiteral(false, CHECK_OK);
1304 1305 1306 1307 1308
            if (peek() != i::Token::RBRACE) {
              Expect(i::Token::COMMA, CHECK_OK);
            }
            continue;  // restart the while
        }
1309
        CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1310 1311 1312 1313
        break;
      }
      case i::Token::STRING:
        Consume(next);
1314
        CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1315 1316 1317 1318
        GetStringSymbol();
        break;
      case i::Token::NUMBER:
        Consume(next);
1319
        CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1320 1321 1322 1323
        break;
      default:
        if (i::Token::IsKeyword(next)) {
          Consume(next);
1324
          CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1325 1326 1327
        } else {
          // Unexpected token.
          *ok = false;
1328
          return Expression::Default();
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
        }
    }

    Expect(i::Token::COLON, CHECK_OK);
    ParseAssignmentExpression(true, CHECK_OK);

    // TODO(1240767): Consider allowing trailing comma.
    if (peek() != i::Token::RBRACE) Expect(i::Token::COMMA, CHECK_OK);
  }
  Expect(i::Token::RBRACE, CHECK_OK);

  scope_->NextMaterializedLiteralIndex();
1341
  return Expression::Default();
1342 1343 1344
}


1345 1346
PreParser::Expression PreParser::ParseRegExpLiteral(bool seen_equal,
                                                    bool* ok) {
1347 1348
  if (!scanner_->ScanRegExpPattern(seen_equal)) {
    Next();
1349
    ReportMessageAt(scanner_->location(), "unterminated_regexp", NULL);
1350
    *ok = false;
1351
    return Expression::Default();
1352 1353 1354 1355 1356 1357
  }

  scope_->NextMaterializedLiteralIndex();

  if (!scanner_->ScanRegExpFlags()) {
    Next();
1358
    ReportMessageAt(scanner_->location(), "invalid_regexp_flags", NULL);
1359
    *ok = false;
1360
    return Expression::Default();
1361 1362
  }
  Next();
1363
  return Expression::Default();
1364 1365 1366
}


1367
PreParser::Arguments PreParser::ParseArguments(bool* ok) {
1368 1369 1370
  // Arguments ::
  //   '(' (AssignmentExpression)*[','] ')'

1371 1372
  Expect(i::Token::LPAREN, ok);
  if (!*ok) return -1;
1373 1374 1375
  bool done = (peek() == i::Token::RPAREN);
  int argc = 0;
  while (!done) {
1376 1377
    ParseAssignmentExpression(true, ok);
    if (!*ok) return -1;
1378 1379
    argc++;
    done = (peek() == i::Token::RPAREN);
1380 1381 1382 1383
    if (!done) {
      Expect(i::Token::COMMA, ok);
      if (!*ok) return -1;
    }
1384
  }
1385
  Expect(i::Token::RPAREN, ok);
1386 1387 1388 1389
  return argc;
}


1390 1391
PreParser::Expression PreParser::ParseFunctionLiteral(bool is_generator,
                                                      bool* ok) {
1392 1393 1394 1395 1396 1397 1398
  // Function ::
  //   '(' FormalParameterList? ')' '{' FunctionBody '}'

  // Parse function body.
  ScopeType outer_scope_type = scope_->type();
  bool inside_with = scope_->IsInsideWith();
  Scope function_scope(&scope_, kFunctionScope);
1399
  function_scope.set_is_generator(is_generator);
1400 1401 1402
  //  FormalParameterList ::
  //    '(' (Identifier)*[','] ')'
  Expect(i::Token::LPAREN, CHECK_OK);
1403
  int start_position = scanner_->location().beg_pos;
1404
  bool done = (peek() == i::Token::RPAREN);
1405
  DuplicateFinder duplicate_finder(scanner_->unicode_cache());
1406
  while (!done) {
1407 1408 1409 1410 1411 1412 1413
    Identifier id = ParseIdentifier(CHECK_OK);
    if (!id.IsValidStrictVariable()) {
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_param_name",
                                    id,
                                    CHECK_OK);
    }
1414 1415 1416 1417 1418 1419
    int prev_value;
    if (scanner_->is_literal_ascii()) {
      prev_value =
          duplicate_finder.AddAsciiSymbol(scanner_->literal_ascii_string(), 1);
    } else {
      prev_value =
1420
          duplicate_finder.AddUtf16Symbol(scanner_->literal_utf16_string(), 1);
1421 1422 1423 1424 1425 1426 1427
    }

    if (prev_value != 0) {
      SetStrictModeViolation(scanner_->location(),
                             "strict_param_dupe",
                             CHECK_OK);
    }
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    done = (peek() == i::Token::RPAREN);
    if (!done) {
      Expect(i::Token::COMMA, CHECK_OK);
    }
  }
  Expect(i::Token::RPAREN, CHECK_OK);

  // Determine if the function will be lazily compiled.
  // Currently only happens to top-level functions.
  // Optimistically assume that all top-level functions are lazily compiled.
1438 1439 1440 1441
  bool is_lazily_compiled = (outer_scope_type == kTopLevelScope &&
                             !inside_with && allow_lazy_ &&
                             !parenthesized_function_);
  parenthesized_function_ = false;
1442

1443
  Expect(i::Token::LBRACE, CHECK_OK);
1444
  if (is_lazily_compiled) {
1445
    ParseLazyFunctionLiteralBody(CHECK_OK);
1446
  } else {
1447
    ParseSourceElements(i::Token::RBRACE, ok);
1448
  }
1449
  Expect(i::Token::RBRACE, CHECK_OK);
1450

1451
  if (!is_classic_mode()) {
1452 1453
    int end_position = scanner_->location().end_pos;
    CheckOctalLiteral(start_position, end_position, CHECK_OK);
1454 1455
    CheckDelayedStrictModeViolation(start_position, end_position, CHECK_OK);
    return Expression::StrictFunction();
1456 1457
  }

1458
  return Expression::Default();
1459 1460 1461
}


1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
void PreParser::ParseLazyFunctionLiteralBody(bool* ok) {
  int body_start = scanner_->location().beg_pos;
  log_->PauseRecording();
  ParseSourceElements(i::Token::RBRACE, ok);
  log_->ResumeRecording();
  if (!*ok) return;

  // Position right after terminal '}'.
  ASSERT_EQ(i::Token::RBRACE, scanner_->peek());
  int body_end = scanner_->peek_location().end_pos;
  log_->LogFunction(body_start, body_end,
                    scope_->materialized_literal_count(),
                    scope_->expected_properties(),
                    language_mode());
}


1479
PreParser::Expression PreParser::ParseV8Intrinsic(bool* ok) {
1480 1481 1482
  // CallRuntime ::
  //   '%' Identifier Arguments
  Expect(i::Token::MOD, CHECK_OK);
1483 1484 1485 1486
  if (!allow_natives_syntax_) {
    *ok = false;
    return Expression::Default();
  }
1487
  ParseIdentifier(CHECK_OK);
1488
  ParseArguments(ok);
1489

1490
  return Expression::Default();
1491 1492
}

1493 1494
#undef CHECK_OK

1495 1496 1497 1498 1499 1500 1501 1502 1503

void PreParser::ExpectSemicolon(bool* ok) {
  // Check for automatic semicolon insertion according to
  // the rules given in ECMA-262, section 7.9, page 21.
  i::Token::Value tok = peek();
  if (tok == i::Token::SEMICOLON) {
    Next();
    return;
  }
1504
  if (scanner_->HasAnyLineTerminatorBeforeNext() ||
1505 1506 1507 1508 1509 1510 1511 1512
      tok == i::Token::RBRACE ||
      tok == i::Token::EOS) {
    return;
  }
  Expect(i::Token::SEMICOLON, ok);
}


1513
void PreParser::LogSymbol() {
1514
  int identifier_pos = scanner_->location().beg_pos;
1515 1516 1517
  if (scanner_->is_literal_ascii()) {
    log_->LogAsciiSymbol(identifier_pos, scanner_->literal_ascii_string());
  } else {
1518
    log_->LogUtf16Symbol(identifier_pos, scanner_->literal_utf16_string());
1519
  }
1520 1521 1522
}


1523
PreParser::Expression PreParser::GetStringSymbol() {
1524 1525
  const int kUseStrictLength = 10;
  const char* kUseStrictChars = "use strict";
1526
  LogSymbol();
1527 1528 1529 1530 1531
  if (scanner_->is_literal_ascii() &&
      scanner_->literal_length() == kUseStrictLength &&
      !scanner_->literal_contains_escapes() &&
      !strncmp(scanner_->literal_ascii_string().start(), kUseStrictChars,
               kUseStrictLength)) {
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    return Expression::UseStrictStringLiteral();
  }
  return Expression::StringLiteral();
}


PreParser::Identifier PreParser::GetIdentifierSymbol() {
  LogSymbol();
  if (scanner_->current_token() == i::Token::FUTURE_RESERVED_WORD) {
    return Identifier::FutureReserved();
1542 1543 1544
  } else if (scanner_->current_token() ==
             i::Token::FUTURE_STRICT_RESERVED_WORD) {
    return Identifier::FutureStrictReserved();
1545 1546
  } else if (scanner_->current_token() == i::Token::YIELD) {
    return Identifier::Yield();
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
  }
  if (scanner_->is_literal_ascii()) {
    // Detect strict-mode poison words.
    if (scanner_->literal_length() == 4 &&
        !strncmp(scanner_->literal_ascii_string().start(), "eval", 4)) {
      return Identifier::Eval();
    }
    if (scanner_->literal_length() == 9 &&
        !strncmp(scanner_->literal_ascii_string().start(), "arguments", 9)) {
      return Identifier::Arguments();
    }
1558
  }
1559
  return Identifier::Default();
1560 1561 1562
}


1563
PreParser::Identifier PreParser::ParseIdentifier(bool* ok) {
1564 1565 1566 1567 1568 1569 1570
  i::Token::Value next = Next();
  switch (next) {
    case i::Token::FUTURE_RESERVED_WORD: {
      i::Scanner::Location location = scanner_->location();
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "reserved_word", NULL);
      *ok = false;
1571
      return GetIdentifierSymbol();
1572
    }
1573 1574 1575 1576 1577 1578 1579 1580
    case i::Token::YIELD:
      if (scope_->is_generator()) {
        // 'yield' in a generator is only valid as part of a YieldExpression.
        ReportMessageAt(scanner_->location(), "unexpected_token", "yield");
        *ok = false;
        return Identifier::Yield();
      }
      // FALLTHROUGH
1581
    case i::Token::FUTURE_STRICT_RESERVED_WORD:
1582
      if (!is_classic_mode()) {
1583 1584 1585 1586 1587 1588
        i::Scanner::Location location = scanner_->location();
        ReportMessageAt(location.beg_pos, location.end_pos,
                        "strict_reserved_word", NULL);
        *ok = false;
      }
      // FALLTHROUGH
1589 1590 1591 1592 1593
    case i::Token::IDENTIFIER:
      return GetIdentifierSymbol();
    default:
      *ok = false;
      return Identifier::Default();
1594
  }
1595 1596 1597
}


1598 1599 1600
void PreParser::SetStrictModeViolation(i::Scanner::Location location,
                                       const char* type,
                                       bool* ok) {
1601
  if (!is_classic_mode()) {
1602
    ReportMessageAt(location, type, NULL);
1603 1604 1605 1606 1607 1608
    *ok = false;
    return;
  }
  // Delay report in case this later turns out to be strict code
  // (i.e., for function names and parameters prior to a "use strict"
  // directive).
1609 1610 1611 1612 1613
  // It's safe to overwrite an existing violation.
  // It's either from a function that turned out to be non-strict,
  // or it's in the current function (and we just need to report
  // one error), or it's in a unclosed nesting function that wasn't
  // strict (otherwise we would already be in strict mode).
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
  strict_mode_violation_location_ = location;
  strict_mode_violation_type_ = type;
}


void PreParser::CheckDelayedStrictModeViolation(int beg_pos,
                                                int end_pos,
                                                bool* ok) {
  i::Scanner::Location location = strict_mode_violation_location_;
  if (location.IsValid() &&
      location.beg_pos > beg_pos && location.end_pos < end_pos) {
1625
    ReportMessageAt(location, strict_mode_violation_type_, NULL);
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    *ok = false;
  }
}


void PreParser::StrictModeIdentifierViolation(i::Scanner::Location location,
                                              const char* eval_args_type,
                                              Identifier identifier,
                                              bool* ok) {
  const char* type = eval_args_type;
  if (identifier.IsFutureReserved()) {
1637
    type = "reserved_word";
1638
  } else if (identifier.IsFutureStrictReserved() || identifier.IsYield()) {
1639 1640
    type = "strict_reserved_word";
  }
1641
  if (!is_classic_mode()) {
1642
    ReportMessageAt(location, type, NULL);
1643 1644 1645 1646 1647 1648 1649 1650
    *ok = false;
    return;
  }
  strict_mode_violation_location_ = location;
  strict_mode_violation_type_ = type;
}


1651
PreParser::Identifier PreParser::ParseIdentifierName(bool* ok) {
1652 1653 1654 1655
  i::Token::Value next = Next();
  if (i::Token::IsKeyword(next)) {
    int pos = scanner_->location().beg_pos;
    const char* keyword = i::Token::String(next);
1656 1657
    log_->LogAsciiSymbol(pos, i::Vector<const char>(keyword,
                                                    i::StrLength(keyword)));
1658
    return Identifier::Default();
1659
  }
1660
  if (next == i::Token::IDENTIFIER ||
1661 1662
      next == i::Token::FUTURE_RESERVED_WORD ||
      next == i::Token::FUTURE_STRICT_RESERVED_WORD) {
1663 1664 1665
    return GetIdentifierSymbol();
  }
  *ok = false;
1666
  return Identifier::Default();
1667 1668
}

1669 1670
#undef CHECK_OK

1671 1672

// This function reads an identifier and determines whether or not it
1673
// is 'get' or 'set'.
1674 1675 1676 1677
PreParser::Identifier PreParser::ParseIdentifierNameOrGetOrSet(bool* is_get,
                                                               bool* is_set,
                                                               bool* ok) {
  Identifier result = ParseIdentifierName(ok);
1678 1679 1680
  if (!*ok) return Identifier::Default();
  if (scanner_->is_literal_ascii() &&
      scanner_->literal_length() == 3) {
1681
    const char* token = scanner_->literal_ascii_string().start();
1682 1683 1684
    *is_get = strncmp(token, "get", 3) == 0;
    *is_set = !*is_get && strncmp(token, "set", 3) == 0;
  }
1685 1686 1687
  return result;
}

1688

1689 1690 1691
bool PreParser::peek_any_identifier() {
  i::Token::Value next = peek();
  return next == i::Token::IDENTIFIER ||
1692
         next == i::Token::FUTURE_RESERVED_WORD ||
1693 1694
         next == i::Token::FUTURE_STRICT_RESERVED_WORD ||
         next == i::Token::YIELD;
1695
}
1696 1697 1698 1699 1700 1701


int DuplicateFinder::AddAsciiSymbol(i::Vector<const char> key, int value) {
  return AddSymbol(i::Vector<const byte>::cast(key), true, value);
}

1702

1703
int DuplicateFinder::AddUtf16Symbol(i::Vector<const uint16_t> key, int value) {
1704 1705 1706 1707 1708 1709 1710 1711
  return AddSymbol(i::Vector<const byte>::cast(key), false, value);
}

int DuplicateFinder::AddSymbol(i::Vector<const byte> key,
                               bool is_ascii,
                               int value) {
  uint32_t hash = Hash(key, is_ascii);
  byte* encoding = BackupKey(key, is_ascii);
lrn@chromium.org's avatar
lrn@chromium.org committed
1712
  i::HashMap::Entry* entry = map_.Lookup(encoding, hash, true);
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
  int old_value = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
  entry->value =
    reinterpret_cast<void*>(static_cast<intptr_t>(value | old_value));
  return old_value;
}


int DuplicateFinder::AddNumber(i::Vector<const char> key, int value) {
  ASSERT(key.length() > 0);
  // Quick check for already being in canonical form.
  if (IsNumberCanonical(key)) {
    return AddAsciiSymbol(key, value);
  }

  int flags = i::ALLOW_HEX | i::ALLOW_OCTALS;
  double double_value = StringToDouble(unicode_constants_, key, flags, 0.0);
  int length;
  const char* string;
1731
  if (!std::isfinite(double_value)) {
1732 1733 1734 1735 1736 1737 1738
    string = "Infinity";
    length = 8;  // strlen("Infinity");
  } else {
    string = DoubleToCString(double_value,
                             i::Vector<char>(number_buffer_, kBufferSize));
    length = i::StrLength(string);
  }
lrn@chromium.org's avatar
lrn@chromium.org committed
1739 1740
  return AddSymbol(i::Vector<const byte>(reinterpret_cast<const byte*>(string),
                                         length), true, value);
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
}


bool DuplicateFinder::IsNumberCanonical(i::Vector<const char> number) {
  // Test for a safe approximation of number literals that are already
  // in canonical form: max 15 digits, no leading zeroes, except an
  // integer part that is a single zero, and no trailing zeros below
  // the decimal point.
  int pos = 0;
  int length = number.length();
  if (number.length() > 15) return false;
  if (number[pos] == '0') {
    pos++;
  } else {
    while (pos < length &&
           static_cast<unsigned>(number[pos] - '0') <= ('9' - '0')) pos++;
  }
  if (length == pos) return true;
  if (number[pos] != '.') return false;
  pos++;
  bool invalid_last_digit = true;
  while (pos < length) {
    byte digit = number[pos] - '0';
    if (digit > '9' - '0') return false;
    invalid_last_digit = (digit == 0);
    pos++;
  }
  return !invalid_last_digit;
}


uint32_t DuplicateFinder::Hash(i::Vector<const byte> key, bool is_ascii) {
  // Primitive hash function, almost identical to the one used
  // for strings (except that it's seeded by the length and ASCII-ness).
  int length = key.length();
  uint32_t hash = (length << 1) | (is_ascii ? 1 : 0) ;
  for (int i = 0; i < length; i++) {
    uint32_t c = key[i];
    hash = (hash + c) * 1025;
    hash ^= (hash >> 6);
  }
  return hash;
}


bool DuplicateFinder::Match(void* first, void* second) {
  // Decode lengths.
  // Length + ASCII-bit is encoded as base 128, most significant heptet first,
  // with a 8th bit being non-zero while there are more heptets.
  // The value encodes the number of bytes following, and whether the original
  // was ASCII.
  byte* s1 = reinterpret_cast<byte*>(first);
  byte* s2 = reinterpret_cast<byte*>(second);
  uint32_t length_ascii_field = 0;
  byte c1;
  do {
    c1 = *s1;
    if (c1 != *s2) return false;
    length_ascii_field = (length_ascii_field << 7) | (c1 & 0x7f);
    s1++;
    s2++;
  } while ((c1 & 0x80) != 0);
  int length = static_cast<int>(length_ascii_field >> 1);
  return memcmp(s1, s2, length) == 0;
}


byte* DuplicateFinder::BackupKey(i::Vector<const byte> bytes,
                                 bool is_ascii) {
  uint32_t ascii_length = (bytes.length() << 1) | (is_ascii ? 1 : 0);
  backing_store_.StartSequence();
  // Emit ascii_length as base-128 encoded number, with the 7th bit set
  // on the byte of every heptet except the last, least significant, one.
  if (ascii_length >= (1 << 7)) {
    if (ascii_length >= (1 << 14)) {
      if (ascii_length >= (1 << 21)) {
        if (ascii_length >= (1 << 28)) {
          backing_store_.Add(static_cast<byte>((ascii_length >> 28) | 0x80));
        }
        backing_store_.Add(static_cast<byte>((ascii_length >> 21) | 0x80u));
      }
      backing_store_.Add(static_cast<byte>((ascii_length >> 14) | 0x80u));
    }
    backing_store_.Add(static_cast<byte>((ascii_length >> 7) | 0x80u));
  }
  backing_store_.Add(static_cast<byte>(ascii_length & 0x7f));

  backing_store_.AddBlock(bytes);
  return backing_store_.EndSequence().start();
}
1831
} }  // v8::preparser