preparser.cc 49.3 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
#if V8_CC_MSVC && (_MSC_VER < 1800)
46 47
namespace std {

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

}  // namespace std
53 54
#endif

55
namespace v8 {
56
namespace internal {
57

58
PreParser::PreParseResult PreParser::PreParseLazyFunction(
59
    LanguageMode mode, bool is_generator, ParserRecorder* log) {
60 61 62 63 64
  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);
65
  function_scope.set_is_generator(is_generator);
66
  ASSERT_EQ(Token::LBRACE, scanner()->current_token());
67
  bool ok = true;
68
  int start_position = peek_position();
69
  ParseLazyFunctionLiteralBody(&ok);
70
  if (stack_overflow()) return kPreParseStackOverflow;
71
  if (!ok) {
72
    ReportUnexpectedToken(scanner()->current_token());
73
  } else {
74
    ASSERT_EQ(Token::RBRACE, scanner()->peek());
75
    if (!is_classic_mode()) {
76
      int end_pos = scanner()->location().end_pos;
77 78 79 80 81 82 83 84 85 86
      CheckOctalLiteral(start_position, end_pos, &ok);
      if (ok) {
        CheckDelayedStrictModeViolation(start_position, end_pos, &ok);
      }
    }
  }
  return kPreParseSuccess;
}


87 88 89 90 91 92 93 94 95 96 97 98 99
// 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.

100
void PreParser::ReportUnexpectedToken(Token::Value token) {
101 102 103
  // 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.
104
  if (token == Token::ILLEGAL && stack_overflow()) {
105 106
    return;
  }
107
  Scanner::Location source_location = scanner()->location();
108 109 110

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


132 133 134 135 136 137 138
#define CHECK_OK  ok);                      \
  if (!*ok) return kUnknownSourceElements;  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


139
PreParser::Statement PreParser::ParseSourceElement(bool* ok) {
140 141 142 143 144 145 146 147
  // (Ecma 262 5th Edition, clause 14):
  // SourceElement:
  //    Statement
  //    FunctionDeclaration
  //
  // In harmony mode we allow additionally the following productions
  // SourceElement:
  //    LetDeclaration
148
  //    ConstDeclaration
149
  //    GeneratorDeclaration
150

151
  switch (peek()) {
152
    case Token::FUNCTION:
153
      return ParseFunctionDeclaration(ok);
154 155
    case Token::LET:
    case Token::CONST:
156 157 158 159 160 161 162
      return ParseVariableStatement(kSourceElement, ok);
    default:
      return ParseStatement(ok);
  }
}


163 164
PreParser::SourceElements PreParser::ParseSourceElements(int end_token,
                                                         bool* ok) {
165 166 167
  // SourceElements ::
  //   (Statement)* <end_token>

168
  bool allow_directive_prologue = true;
169
  while (peek() != end_token) {
170
    Statement statement = ParseSourceElement(CHECK_OK);
171
    if (allow_directive_prologue) {
172
      if (statement.IsUseStrictLiteral()) {
173
        set_language_mode(allow_harmony_scoping() ?
174
                          EXTENDED_MODE : STRICT_MODE);
175
      } else if (!statement.IsStringLiteral()) {
176 177 178
        allow_directive_prologue = false;
      }
    }
179 180 181 182 183
  }
  return kUnknownSourceElements;
}


184 185 186 187 188 189 190 191
#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
192
PreParser::Statement PreParser::ParseStatement(bool* ok) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  // 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()) {
219
    case Token::LBRACE:
220 221
      return ParseBlock(ok);

222 223 224
    case Token::CONST:
    case Token::LET:
    case Token::VAR:
225
      return ParseVariableStatement(kStatement, ok);
226

227
    case Token::SEMICOLON:
228
      Next();
229
      return Statement::Default();
230

231
    case Token::IF:
232
      return ParseIfStatement(ok);
233

234
    case Token::DO:
235 236
      return ParseDoWhileStatement(ok);

237
    case Token::WHILE:
238 239
      return ParseWhileStatement(ok);

240
    case Token::FOR:
241 242
      return ParseForStatement(ok);

243
    case Token::CONTINUE:
244 245
      return ParseContinueStatement(ok);

246
    case Token::BREAK:
247 248
      return ParseBreakStatement(ok);

249
    case Token::RETURN:
250 251
      return ParseReturnStatement(ok);

252
    case Token::WITH:
253 254
      return ParseWithStatement(ok);

255
    case Token::SWITCH:
256 257
      return ParseSwitchStatement(ok);

258
    case Token::THROW:
259 260
      return ParseThrowStatement(ok);

261
    case Token::TRY:
262 263
      return ParseTryStatement(ok);

264 265
    case Token::FUNCTION: {
      Scanner::Location start_location = scanner()->peek_location();
266
      Statement statement = ParseFunctionDeclaration(CHECK_OK);
267
      Scanner::Location end_location = scanner()->location();
268
      if (!is_classic_mode()) {
269 270 271 272 273 274 275 276
        ReportMessageAt(start_location.beg_pos, end_location.end_pos,
                        "strict_function", NULL);
        *ok = false;
        return Statement::Default();
      } else {
        return statement;
      }
    }
277

278
    case Token::DEBUGGER:
279 280 281 282 283 284 285 286
      return ParseDebuggerStatement(ok);

    default:
      return ParseExpressionOrLabelledStatement(ok);
  }
}


287
PreParser::Statement PreParser::ParseFunctionDeclaration(bool* ok) {
288 289
  // FunctionDeclaration ::
  //   'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
290 291 292
  // GeneratorDeclaration ::
  //   'function' '*' Identifier '(' FormalParameterListopt ')'
  //      '{' FunctionBody '}'
293
  Expect(Token::FUNCTION, CHECK_OK);
294

295
  bool is_generator = allow_generators() && Check(Token::MUL);
296
  Identifier identifier = ParseIdentifier(CHECK_OK);
297
  Scanner::Location location = scanner()->location();
298

299
  Expression function_value = ParseFunctionLiteral(is_generator, CHECK_OK);
300 301 302 303 304 305

  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";
306
    if (identifier.IsFutureStrictReserved() || identifier.IsYield()) {
307 308
      type = "strict_reserved_word";
    }
309
    ReportMessageAt(location, type, NULL);
310 311
    *ok = false;
  }
312
  return Statement::FunctionDeclaration();
313 314 315
}


316
PreParser::Statement PreParser::ParseBlock(bool* ok) {
317 318 319 320 321 322
  // Block ::
  //   '{' Statement* '}'

  // Note that a Block does not introduce a new execution scope!
  // (ECMA-262, 3rd, 12.2)
  //
323 324
  Expect(Token::LBRACE, CHECK_OK);
  while (peek() != Token::RBRACE) {
325
    if (is_extended_mode()) {
326 327 328
      ParseSourceElement(CHECK_OK);
    } else {
      ParseStatement(CHECK_OK);
329
    }
330
  }
331
  Expect(Token::RBRACE, ok);
332
  return Statement::Default();
333 334 335
}


336 337 338
PreParser::Statement PreParser::ParseVariableStatement(
    VariableDeclarationContext var_context,
    bool* ok) {
339 340 341
  // VariableStatement ::
  //   VariableDeclarations ';'

342
  Statement result = ParseVariableDeclarations(var_context,
343
                                               NULL,
344 345
                                               NULL,
                                               CHECK_OK);
346 347 348 349 350 351 352 353 354 355
  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.
356 357
PreParser::Statement PreParser::ParseVariableDeclarations(
    VariableDeclarationContext var_context,
358
    VariableDeclarationProperties* decl_props,
359 360
    int* num_decl,
    bool* ok) {
361 362
  // VariableDeclarations ::
  //   ('var' | 'const') (Identifier ('=' AssignmentExpression)?)+[',']
363 364 365 366 367 368 369 370 371 372 373 374
  //
  // 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;
375 376 377
  if (peek() == Token::VAR) {
    Consume(Token::VAR);
  } else if (peek() == Token::CONST) {
378 379 380 381 382 383 384 385 386 387
    // 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.
388
    Consume(Token::CONST);
389
    switch (language_mode()) {
390
      case CLASSIC_MODE:
391
        break;
392 393
      case STRICT_MODE: {
        Scanner::Location location = scanner()->peek_location();
394
        ReportMessageAt(location, "strict_const", NULL);
395 396 397
        *ok = false;
        return Statement::Default();
      }
398
      case EXTENDED_MODE:
399 400
        if (var_context != kSourceElement &&
            var_context != kForStatement) {
401
          Scanner::Location location = scanner()->peek_location();
402 403 404 405 406 407 408
          ReportMessageAt(location.beg_pos, location.end_pos,
                          "unprotected_const", NULL);
          *ok = false;
          return Statement::Default();
        }
        require_initializer = true;
        break;
409
    }
410
  } else if (peek() == Token::LET) {
411 412 413 414 415 416 417
    // 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()) {
418
      Scanner::Location location = scanner()->peek_location();
419 420 421 422 423
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "illegal_let", NULL);
      *ok = false;
      return Statement::Default();
    }
424
    Consume(Token::LET);
425 426
    if (var_context != kSourceElement &&
        var_context != kForStatement) {
427
      Scanner::Location location = scanner()->peek_location();
428 429 430 431 432
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "unprotected_let", NULL);
      *ok = false;
      return Statement::Default();
    }
433 434
  } else {
    *ok = false;
435
    return Statement::Default();
436 437
  }

438 439 440 441
  // 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.
442 443 444
  int nvars = 0;  // the number of variables declared
  do {
    // Parse variable name.
445
    if (nvars > 0) Consume(Token::COMMA);
446
    Identifier identifier  = ParseIdentifier(CHECK_OK);
447
    if (!is_classic_mode() && !identifier.IsValidStrictVariable()) {
448
      StrictModeIdentifierViolation(scanner()->location(),
449 450 451 452 453
                                    "strict_var_name",
                                    identifier,
                                    ok);
      return Statement::Default();
    }
454
    nvars++;
455 456
    if (peek() == Token::ASSIGN || require_initializer) {
      Expect(Token::ASSIGN, CHECK_OK);
457
      ParseAssignmentExpression(var_context != kForStatement, CHECK_OK);
458
      if (decl_props != NULL) *decl_props = kHasInitializers;
459
    }
460
  } while (peek() == Token::COMMA);
461 462

  if (num_decl != NULL) *num_decl = nvars;
463
  return Statement::Default();
464 465 466
}


467
PreParser::Statement PreParser::ParseExpressionOrLabelledStatement(bool* ok) {
468 469 470 471 472
  // ExpressionStatement | LabelledStatement ::
  //   Expression ';'
  //   Identifier ':' Statement

  Expression expr = ParseExpression(true, CHECK_OK);
473
  if (expr.IsRawIdentifier()) {
474
    ASSERT(!expr.AsIdentifier().IsFutureReserved());
475 476 477
    ASSERT(is_classic_mode() ||
           (!expr.AsIdentifier().IsFutureStrictReserved() &&
            !expr.AsIdentifier().IsYield()));
478 479
    if (peek() == Token::COLON) {
      Consume(Token::COLON);
480
      return ParseStatement(ok);
481
    }
482 483 484
    // 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.
485 486 487
  }
  // Parsed expression statement.
  ExpectSemicolon(CHECK_OK);
488
  return Statement::ExpressionStatement(expr);
489 490 491
}


492
PreParser::Statement PreParser::ParseIfStatement(bool* ok) {
493 494 495
  // IfStatement ::
  //   'if' '(' Expression ')' Statement ('else' Statement)?

496 497
  Expect(Token::IF, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
498
  ParseExpression(true, CHECK_OK);
499
  Expect(Token::RPAREN, CHECK_OK);
500
  ParseStatement(CHECK_OK);
501
  if (peek() == Token::ELSE) {
502 503 504
    Next();
    ParseStatement(CHECK_OK);
  }
505
  return Statement::Default();
506 507 508
}


509
PreParser::Statement PreParser::ParseContinueStatement(bool* ok) {
510 511 512
  // ContinueStatement ::
  //   'continue' [no line terminator] Identifier? ';'

513 514
  Expect(Token::CONTINUE, CHECK_OK);
  Token::Value tok = peek();
515
  if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
516 517 518
      tok != Token::SEMICOLON &&
      tok != Token::RBRACE &&
      tok != Token::EOS) {
519 520 521
    ParseIdentifier(CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
522
  return Statement::Default();
523 524 525
}


526
PreParser::Statement PreParser::ParseBreakStatement(bool* ok) {
527 528 529
  // BreakStatement ::
  //   'break' [no line terminator] Identifier? ';'

530 531
  Expect(Token::BREAK, CHECK_OK);
  Token::Value tok = peek();
532
  if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
533 534 535
      tok != Token::SEMICOLON &&
      tok != Token::RBRACE &&
      tok != Token::EOS) {
536 537 538
    ParseIdentifier(CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
539
  return Statement::Default();
540 541 542
}


543
PreParser::Statement PreParser::ParseReturnStatement(bool* ok) {
544 545 546 547 548 549
  // 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).
550
  Expect(Token::RETURN, CHECK_OK);
551 552 553 554 555 556

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

557
  Token::Value tok = peek();
558
  if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
559 560 561
      tok != Token::SEMICOLON &&
      tok != Token::RBRACE &&
      tok != Token::EOS) {
562 563 564
    ParseExpression(true, CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
565
  return Statement::Default();
566 567 568
}


569
PreParser::Statement PreParser::ParseWithStatement(bool* ok) {
570 571
  // WithStatement ::
  //   'with' '(' Expression ')' Statement
572
  Expect(Token::WITH, CHECK_OK);
573
  if (!is_classic_mode()) {
574
    Scanner::Location location = scanner()->location();
575
    ReportMessageAt(location, "strict_mode_with", NULL);
576 577 578
    *ok = false;
    return Statement::Default();
  }
579
  Expect(Token::LPAREN, CHECK_OK);
580
  ParseExpression(true, CHECK_OK);
581
  Expect(Token::RPAREN, CHECK_OK);
582

583
  Scope::InsideWith iw(scope_);
584
  ParseStatement(CHECK_OK);
585
  return Statement::Default();
586 587 588
}


589
PreParser::Statement PreParser::ParseSwitchStatement(bool* ok) {
590 591 592
  // SwitchStatement ::
  //   'switch' '(' Expression ')' '{' CaseClause* '}'

593 594
  Expect(Token::SWITCH, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
595
  ParseExpression(true, CHECK_OK);
596
  Expect(Token::RPAREN, CHECK_OK);
597

598 599 600 601 602
  Expect(Token::LBRACE, CHECK_OK);
  Token::Value token = peek();
  while (token != Token::RBRACE) {
    if (token == Token::CASE) {
      Expect(Token::CASE, CHECK_OK);
603 604
      ParseExpression(true, CHECK_OK);
    } else {
605
      Expect(Token::DEFAULT, CHECK_OK);
606
    }
607
    Expect(Token::COLON, CHECK_OK);
608
    token = peek();
609 610 611
    while (token != Token::CASE &&
           token != Token::DEFAULT &&
           token != Token::RBRACE) {
612 613 614
      ParseStatement(CHECK_OK);
      token = peek();
    }
615
  }
616
  Expect(Token::RBRACE, ok);
617
  return Statement::Default();
618 619 620
}


621
PreParser::Statement PreParser::ParseDoWhileStatement(bool* ok) {
622 623 624
  // DoStatement ::
  //   'do' Statement 'while' '(' Expression ')' ';'

625
  Expect(Token::DO, CHECK_OK);
626
  ParseStatement(CHECK_OK);
627 628
  Expect(Token::WHILE, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
629
  ParseExpression(true, CHECK_OK);
630 631
  Expect(Token::RPAREN, ok);
  if (peek() == Token::SEMICOLON) Consume(Token::SEMICOLON);
632
  return Statement::Default();
633 634 635
}


636
PreParser::Statement PreParser::ParseWhileStatement(bool* ok) {
637 638 639
  // WhileStatement ::
  //   'while' '(' Expression ')' Statement

640 641
  Expect(Token::WHILE, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
642
  ParseExpression(true, CHECK_OK);
643
  Expect(Token::RPAREN, CHECK_OK);
644 645
  ParseStatement(ok);
  return Statement::Default();
646 647 648
}


649
bool PreParser::CheckInOrOf(bool accept_OF) {
650 651 652
  if (Check(Token::IN) ||
      (allow_for_of() && accept_OF &&
       CheckContextualKeyword(CStrVector("of")))) {
653 654 655 656 657 658
    return true;
  }
  return false;
}


659
PreParser::Statement PreParser::ParseForStatement(bool* ok) {
660 661 662
  // ForStatement ::
  //   'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement

663 664 665 666 667 668
  Expect(Token::FOR, CHECK_OK);
  Expect(Token::LPAREN, CHECK_OK);
  if (peek() != Token::SEMICOLON) {
    if (peek() == Token::VAR || peek() == Token::CONST ||
        peek() == Token::LET) {
      bool is_let = peek() == Token::LET;
669
      int decl_count;
670 671 672
      VariableDeclarationProperties decl_props = kHasNoInitializers;
      ParseVariableDeclarations(
          kForStatement, &decl_props, &decl_count, CHECK_OK);
673 674 675 676
      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)) {
677
        ParseExpression(true, CHECK_OK);
678
        Expect(Token::RPAREN, CHECK_OK);
679 680

        ParseStatement(CHECK_OK);
681
        return Statement::Default();
682 683
      }
    } else {
684 685
      Expression lhs = ParseExpression(false, CHECK_OK);
      if (CheckInOrOf(lhs.IsIdentifier())) {
686
        ParseExpression(true, CHECK_OK);
687
        Expect(Token::RPAREN, CHECK_OK);
688 689

        ParseStatement(CHECK_OK);
690
        return Statement::Default();
691 692 693 694 695
      }
    }
  }

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

698
  if (peek() != Token::SEMICOLON) {
699 700
    ParseExpression(true, CHECK_OK);
  }
701
  Expect(Token::SEMICOLON, CHECK_OK);
702

703
  if (peek() != Token::RPAREN) {
704 705
    ParseExpression(true, CHECK_OK);
  }
706
  Expect(Token::RPAREN, CHECK_OK);
707

708 709
  ParseStatement(ok);
  return Statement::Default();
710 711 712
}


713
PreParser::Statement PreParser::ParseThrowStatement(bool* ok) {
714 715 716
  // ThrowStatement ::
  //   'throw' [no line terminator] Expression ';'

717
  Expect(Token::THROW, CHECK_OK);
718
  if (scanner()->HasAnyLineTerminatorBeforeNext()) {
719
    Scanner::Location pos = scanner()->location();
720
    ReportMessageAt(pos, "newline_after_throw", NULL);
721
    *ok = false;
722
    return Statement::Default();
723 724
  }
  ParseExpression(true, CHECK_OK);
725 726
  ExpectSemicolon(ok);
  return Statement::Default();
727 728 729
}


730
PreParser::Statement PreParser::ParseTryStatement(bool* ok) {
731 732 733 734 735 736 737 738 739 740 741 742 743 744
  // 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.

745
  Expect(Token::TRY, CHECK_OK);
746 747 748 749

  ParseBlock(CHECK_OK);

  bool catch_or_finally_seen = false;
750 751 752
  if (peek() == Token::CATCH) {
    Consume(Token::CATCH);
    Expect(Token::LPAREN, CHECK_OK);
753
    Identifier id = ParseIdentifier(CHECK_OK);
754
    if (!is_classic_mode() && !id.IsValidStrictVariable()) {
755
      StrictModeIdentifierViolation(scanner()->location(),
756 757 758 759 760
                                    "strict_catch_variable",
                                    id,
                                    ok);
      return Statement::Default();
    }
761
    Expect(Token::RPAREN, CHECK_OK);
762 763 764
    { Scope::InsideWith iw(scope_);
      ParseBlock(CHECK_OK);
    }
765 766
    catch_or_finally_seen = true;
  }
767 768
  if (peek() == Token::FINALLY) {
    Consume(Token::FINALLY);
769 770 771 772 773 774
    ParseBlock(CHECK_OK);
    catch_or_finally_seen = true;
  }
  if (!catch_or_finally_seen) {
    *ok = false;
  }
775
  return Statement::Default();
776 777 778
}


779
PreParser::Statement PreParser::ParseDebuggerStatement(bool* ok) {
780 781 782 783 784 785
  // 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' ';'

786
  Expect(Token::DEBUGGER, CHECK_OK);
787 788
  ExpectSemicolon(ok);
  return Statement::Default();
789 790 791
}


792 793 794 795 796 797 798 799
#undef CHECK_OK
#define CHECK_OK  ok);                     \
  if (!*ok) return Expression::Default();  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


800
// Precedence = 1
801
PreParser::Expression PreParser::ParseExpression(bool accept_IN, bool* ok) {
802 803 804 805 806
  // Expression ::
  //   AssignmentExpression
  //   Expression ',' AssignmentExpression

  Expression result = ParseAssignmentExpression(accept_IN, CHECK_OK);
807 808
  while (peek() == Token::COMMA) {
    Expect(Token::COMMA, CHECK_OK);
809
    ParseAssignmentExpression(accept_IN, CHECK_OK);
810
    result = Expression::Default();
811 812 813 814 815 816
  }
  return result;
}


// Precedence = 2
817 818
PreParser::Expression PreParser::ParseAssignmentExpression(bool accept_IN,
                                                           bool* ok) {
819 820
  // AssignmentExpression ::
  //   ConditionalExpression
821
  //   YieldExpression
822 823
  //   LeftHandSideExpression AssignmentOperator AssignmentExpression

824
  if (scope_->is_generator() && peek() == Token::YIELD) {
825 826 827
    return ParseYieldExpression(ok);
  }

828
  Scanner::Location before = scanner()->peek_location();
829 830
  Expression expression = ParseConditionalExpression(accept_IN, CHECK_OK);

831
  if (!Token::IsAssignmentOp(peek())) {
832 833 834 835
    // Parsed conditional expression only (no assignment).
    return expression;
  }

836 837
  if (!is_classic_mode() &&
      expression.IsIdentifier() &&
838
      expression.AsIdentifier().IsEvalOrArguments()) {
839
    Scanner::Location after = scanner()->location();
840 841 842 843 844 845
    ReportMessageAt(before.beg_pos, after.end_pos,
                    "strict_lhs_assignment", NULL);
    *ok = false;
    return Expression::Default();
  }

846
  Token::Value op = Next();  // Get assignment operator.
847 848
  ParseAssignmentExpression(accept_IN, CHECK_OK);

849
  if ((op == Token::ASSIGN) && expression.IsThisProperty()) {
850 851 852
    scope_->AddProperty();
  }

853
  return Expression::Default();
854 855 856
}


857 858 859 860
// Precedence = 3
PreParser::Expression PreParser::ParseYieldExpression(bool* ok) {
  // YieldExpression ::
  //   'yield' '*'? AssignmentExpression
861 862
  Consume(Token::YIELD);
  Check(Token::MUL);
863 864 865 866 867 868 869

  ParseAssignmentExpression(false, CHECK_OK);

  return Expression::Default();
}


870
// Precedence = 3
871 872
PreParser::Expression PreParser::ParseConditionalExpression(bool accept_IN,
                                                            bool* ok) {
873 874 875 876 877 878
  // ConditionalExpression ::
  //   LogicalOrExpression
  //   LogicalOrExpression '?' AssignmentExpression ':' AssignmentExpression

  // We start using the binary expression parser for prec >= 4 only!
  Expression expression = ParseBinaryExpression(4, accept_IN, CHECK_OK);
879 880
  if (peek() != Token::CONDITIONAL) return expression;
  Consume(Token::CONDITIONAL);
881 882 883 884
  // 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);
885
  Expect(Token::COLON, CHECK_OK);
886
  ParseAssignmentExpression(accept_IN, CHECK_OK);
887
  return Expression::Default();
888 889 890 891
}


// Precedence >= 4
892 893 894
PreParser::Expression PreParser::ParseBinaryExpression(int prec,
                                                       bool accept_IN,
                                                       bool* ok) {
895 896 897 898 899 900
  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);
901
      result = Expression::Default();
902 903 904 905 906 907
    }
  }
  return result;
}


908
PreParser::Expression PreParser::ParseUnaryExpression(bool* ok) {
909 910 911 912 913 914 915 916 917 918 919 920
  // UnaryExpression ::
  //   PostfixExpression
  //   'delete' UnaryExpression
  //   'void' UnaryExpression
  //   'typeof' UnaryExpression
  //   '++' UnaryExpression
  //   '--' UnaryExpression
  //   '+' UnaryExpression
  //   '-' UnaryExpression
  //   '~' UnaryExpression
  //   '!' UnaryExpression

921 922
  Token::Value op = peek();
  if (Token::IsUnaryOp(op)) {
923 924
    op = Next();
    ParseUnaryExpression(ok);
925
    return Expression::Default();
926
  } else if (Token::IsCountOp(op)) {
927
    op = Next();
928
    Scanner::Location before = scanner()->peek_location();
929
    Expression expression = ParseUnaryExpression(CHECK_OK);
930 931
    if (!is_classic_mode() &&
        expression.IsIdentifier() &&
932
        expression.AsIdentifier().IsEvalOrArguments()) {
933
      Scanner::Location after = scanner()->location();
934 935 936 937 938
      ReportMessageAt(before.beg_pos, after.end_pos,
                      "strict_lhs_prefix", NULL);
      *ok = false;
    }
    return Expression::Default();
939 940 941 942 943 944
  } else {
    return ParsePostfixExpression(ok);
  }
}


945
PreParser::Expression PreParser::ParsePostfixExpression(bool* ok) {
946 947 948
  // PostfixExpression ::
  //   LeftHandSideExpression ('++' | '--')?

949
  Scanner::Location before = scanner()->peek_location();
950
  Expression expression = ParseLeftHandSideExpression(CHECK_OK);
951
  if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
952
      Token::IsCountOp(peek())) {
953 954
    if (!is_classic_mode() &&
        expression.IsIdentifier() &&
955
        expression.AsIdentifier().IsEvalOrArguments()) {
956
      Scanner::Location after = scanner()->location();
957 958 959 960 961
      ReportMessageAt(before.beg_pos, after.end_pos,
                      "strict_lhs_postfix", NULL);
      *ok = false;
      return Expression::Default();
    }
962
    Next();
963
    return Expression::Default();
964 965 966 967 968
  }
  return expression;
}


969
PreParser::Expression PreParser::ParseLeftHandSideExpression(bool* ok) {
970 971 972
  // LeftHandSideExpression ::
  //   (NewExpression | MemberExpression) ...

973
  Expression result = Expression::Default();
974
  if (peek() == Token::NEW) {
975 976 977 978 979 980 981
    result = ParseNewExpression(CHECK_OK);
  } else {
    result = ParseMemberExpression(CHECK_OK);
  }

  while (true) {
    switch (peek()) {
982 983
      case Token::LBRACK: {
        Consume(Token::LBRACK);
984
        ParseExpression(true, CHECK_OK);
985
        Expect(Token::RBRACK, CHECK_OK);
986 987
        if (result.IsThis()) {
          result = Expression::ThisProperty();
988
        } else {
989
          result = Expression::Default();
990 991 992 993
        }
        break;
      }

994
      case Token::LPAREN: {
995
        ParseArguments(CHECK_OK);
996
        result = Expression::Default();
997 998 999
        break;
      }

1000 1001
      case Token::PERIOD: {
        Consume(Token::PERIOD);
1002
        ParseIdentifierName(CHECK_OK);
1003 1004
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1005
        } else {
1006
          result = Expression::Default();
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        }
        break;
      }

      default:
        return result;
    }
  }
}


1018
PreParser::Expression PreParser::ParseNewExpression(bool* ok) {
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
  // 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 {
1032
    Consume(Token::NEW);
1033
    new_count++;
1034
  } while (peek() == Token::NEW);
1035 1036 1037 1038 1039

  return ParseMemberWithNewPrefixesExpression(new_count, ok);
}


1040
PreParser::Expression PreParser::ParseMemberExpression(bool* ok) {
1041 1042 1043 1044
  return ParseMemberWithNewPrefixesExpression(0, ok);
}


1045
PreParser::Expression PreParser::ParseMemberWithNewPrefixesExpression(
1046 1047 1048 1049 1050 1051
    unsigned new_count, bool* ok) {
  // MemberExpression ::
  //   (PrimaryExpression | FunctionLiteral)
  //     ('[' Expression ']' | '.' Identifier | Arguments)*

  // Parse the initial primary or function expression.
1052
  Expression result = Expression::Default();
1053 1054
  if (peek() == Token::FUNCTION) {
    Consume(Token::FUNCTION);
1055

1056
    bool is_generator = allow_generators() && Check(Token::MUL);
1057
    Identifier identifier = Identifier::Default();
1058
    if (peek_any_identifier()) {
1059
      identifier = ParseIdentifier(CHECK_OK);
1060
    }
1061
    result = ParseFunctionLiteral(is_generator, CHECK_OK);
1062
    if (result.IsStrictFunction() && !identifier.IsValidStrictVariable()) {
1063
      StrictModeIdentifierViolation(scanner()->location(),
1064 1065 1066 1067 1068
                                    "strict_function_name",
                                    identifier,
                                    ok);
      return Expression::Default();
    }
1069 1070 1071 1072 1073 1074
  } else {
    result = ParsePrimaryExpression(CHECK_OK);
  }

  while (true) {
    switch (peek()) {
1075 1076
      case Token::LBRACK: {
        Consume(Token::LBRACK);
1077
        ParseExpression(true, CHECK_OK);
1078
        Expect(Token::RBRACK, CHECK_OK);
1079 1080
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1081
        } else {
1082
          result = Expression::Default();
1083 1084 1085
        }
        break;
      }
1086 1087
      case Token::PERIOD: {
        Consume(Token::PERIOD);
1088
        ParseIdentifierName(CHECK_OK);
1089 1090
        if (result.IsThis()) {
          result = Expression::ThisProperty();
1091
        } else {
1092
          result = Expression::Default();
1093 1094 1095
        }
        break;
      }
1096
      case Token::LPAREN: {
1097 1098 1099 1100
        if (new_count == 0) return result;
        // Consume one of the new prefixes (already parsed).
        ParseArguments(CHECK_OK);
        new_count--;
1101
        result = Expression::Default();
1102 1103 1104 1105 1106 1107 1108 1109 1110
        break;
      }
      default:
        return result;
    }
  }
}


1111
PreParser::Expression PreParser::ParsePrimaryExpression(bool* ok) {
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
  // PrimaryExpression ::
  //   'this'
  //   'null'
  //   'true'
  //   'false'
  //   Identifier
  //   Number
  //   String
  //   ArrayLiteral
  //   ObjectLiteral
  //   RegExpLiteral
  //   '(' Expression ')'

1125
  Expression result = Expression::Default();
1126
  switch (peek()) {
1127
    case Token::THIS: {
1128
      Next();
1129
      result = Expression::This();
1130 1131 1132
      break;
    }

1133 1134 1135 1136
    case Token::FUTURE_RESERVED_WORD:
    case Token::FUTURE_STRICT_RESERVED_WORD:
    case Token::YIELD:
    case Token::IDENTIFIER: {
1137
      Identifier id = ParseIdentifier(CHECK_OK);
1138
      result = Expression::FromIdentifier(id);
1139 1140 1141
      break;
    }

1142 1143 1144 1145
    case Token::NULL_LITERAL:
    case Token::TRUE_LITERAL:
    case Token::FALSE_LITERAL:
    case Token::NUMBER: {
1146 1147 1148
      Next();
      break;
    }
1149
    case Token::STRING: {
1150 1151 1152 1153 1154
      Next();
      result = GetStringSymbol();
      break;
    }

1155
    case Token::ASSIGN_DIV:
1156 1157 1158
      result = ParseRegExpLiteral(true, CHECK_OK);
      break;

1159
    case Token::DIV:
1160 1161 1162
      result = ParseRegExpLiteral(false, CHECK_OK);
      break;

1163
    case Token::LBRACK:
1164 1165 1166
      result = ParseArrayLiteral(CHECK_OK);
      break;

1167
    case Token::LBRACE:
1168 1169 1170
      result = ParseObjectLiteral(CHECK_OK);
      break;

1171 1172 1173
    case Token::LPAREN:
      Consume(Token::LPAREN);
      parenthesized_function_ = (peek() == Token::FUNCTION);
1174
      result = ParseExpression(true, CHECK_OK);
1175
      Expect(Token::RPAREN, CHECK_OK);
1176
      result = result.Parenthesize();
1177 1178
      break;

1179
    case Token::MOD:
1180 1181 1182 1183 1184 1185
      result = ParseV8Intrinsic(CHECK_OK);
      break;

    default: {
      Next();
      *ok = false;
1186
      return Expression::Default();
1187 1188 1189 1190 1191 1192 1193
    }
  }

  return result;
}


1194
PreParser::Expression PreParser::ParseArrayLiteral(bool* ok) {
1195 1196
  // ArrayLiteral ::
  //   '[' Expression? (',' Expression?)* ']'
1197 1198 1199
  Expect(Token::LBRACK, CHECK_OK);
  while (peek() != Token::RBRACK) {
    if (peek() != Token::COMMA) {
1200 1201
      ParseAssignmentExpression(true, CHECK_OK);
    }
1202 1203
    if (peek() != Token::RBRACK) {
      Expect(Token::COMMA, CHECK_OK);
1204 1205
    }
  }
1206
  Expect(Token::RBRACK, CHECK_OK);
1207 1208

  scope_->NextMaterializedLiteralIndex();
1209
  return Expression::Default();
1210 1211 1212
}


1213
PreParser::Expression PreParser::ParseObjectLiteral(bool* ok) {
1214 1215 1216 1217 1218 1219
  // ObjectLiteral ::
  //   '{' (
  //       ((IdentifierName | String | Number) ':' AssignmentExpression)
  //     | (('get' | 'set') (IdentifierName | String | Number) FunctionLiteral)
  //    )*[','] '}'

1220
  ObjectLiteralChecker checker(this, language_mode());
1221

1222 1223 1224
  Expect(Token::LBRACE, CHECK_OK);
  while (peek() != Token::RBRACE) {
    Token::Value next = peek();
1225
    switch (next) {
1226 1227 1228
      case Token::IDENTIFIER:
      case Token::FUTURE_RESERVED_WORD:
      case Token::FUTURE_STRICT_RESERVED_WORD: {
1229 1230
        bool is_getter = false;
        bool is_setter = false;
1231
        ParseIdentifierNameOrGetOrSet(&is_getter, &is_setter, CHECK_OK);
1232 1233 1234 1235 1236 1237 1238 1239
        if ((is_getter || is_setter) && peek() != Token::COLON) {
            Token::Value name = Next();
            bool is_keyword = Token::IsKeyword(name);
            if (name != Token::IDENTIFIER &&
                name != Token::FUTURE_RESERVED_WORD &&
                name != Token::FUTURE_STRICT_RESERVED_WORD &&
                name != Token::NUMBER &&
                name != Token::STRING &&
1240
                !is_keyword) {
1241
              *ok = false;
1242
              return Expression::Default();
1243
            }
1244 1245 1246
            if (!is_keyword) {
              LogSymbol();
            }
1247
            PropertyKind type = is_getter ? kGetterProperty : kSetterProperty;
1248
            checker.CheckProperty(name, type, CHECK_OK);
1249
            ParseFunctionLiteral(false, CHECK_OK);
1250 1251
            if (peek() != Token::RBRACE) {
              Expect(Token::COMMA, CHECK_OK);
1252 1253 1254
            }
            continue;  // restart the while
        }
1255
        checker.CheckProperty(next, kValueProperty, CHECK_OK);
1256 1257
        break;
      }
1258
      case Token::STRING:
1259
        Consume(next);
1260
        checker.CheckProperty(next, kValueProperty, CHECK_OK);
1261 1262
        GetStringSymbol();
        break;
1263
      case Token::NUMBER:
1264
        Consume(next);
1265
        checker.CheckProperty(next, kValueProperty, CHECK_OK);
1266 1267
        break;
      default:
1268
        if (Token::IsKeyword(next)) {
1269
          Consume(next);
1270
          checker.CheckProperty(next, kValueProperty, CHECK_OK);
1271 1272 1273
        } else {
          // Unexpected token.
          *ok = false;
1274
          return Expression::Default();
1275 1276 1277
        }
    }

1278
    Expect(Token::COLON, CHECK_OK);
1279 1280 1281
    ParseAssignmentExpression(true, CHECK_OK);

    // TODO(1240767): Consider allowing trailing comma.
1282
    if (peek() != Token::RBRACE) Expect(Token::COMMA, CHECK_OK);
1283
  }
1284
  Expect(Token::RBRACE, CHECK_OK);
1285 1286

  scope_->NextMaterializedLiteralIndex();
1287
  return Expression::Default();
1288 1289 1290
}


1291 1292
PreParser::Expression PreParser::ParseRegExpLiteral(bool seen_equal,
                                                    bool* ok) {
1293
  if (!scanner()->ScanRegExpPattern(seen_equal)) {
1294
    Next();
1295
    ReportMessageAt(scanner()->location(), "unterminated_regexp", NULL);
1296
    *ok = false;
1297
    return Expression::Default();
1298 1299 1300 1301
  }

  scope_->NextMaterializedLiteralIndex();

1302
  if (!scanner()->ScanRegExpFlags()) {
1303
    Next();
1304
    ReportMessageAt(scanner()->location(), "invalid_regexp_flags", NULL);
1305
    *ok = false;
1306
    return Expression::Default();
1307 1308
  }
  Next();
1309
  return Expression::Default();
1310 1311 1312
}


1313
PreParser::Arguments PreParser::ParseArguments(bool* ok) {
1314 1315 1316
  // Arguments ::
  //   '(' (AssignmentExpression)*[','] ')'

1317
  Expect(Token::LPAREN, ok);
1318
  if (!*ok) return -1;
1319
  bool done = (peek() == Token::RPAREN);
1320 1321
  int argc = 0;
  while (!done) {
1322 1323
    ParseAssignmentExpression(true, ok);
    if (!*ok) return -1;
1324
    argc++;
1325
    done = (peek() == Token::RPAREN);
1326
    if (!done) {
1327
      Expect(Token::COMMA, ok);
1328 1329
      if (!*ok) return -1;
    }
1330
  }
1331
  Expect(Token::RPAREN, ok);
1332 1333 1334 1335
  return argc;
}


1336 1337
PreParser::Expression PreParser::ParseFunctionLiteral(bool is_generator,
                                                      bool* ok) {
1338 1339 1340 1341 1342 1343 1344
  // Function ::
  //   '(' FormalParameterList? ')' '{' FunctionBody '}'

  // Parse function body.
  ScopeType outer_scope_type = scope_->type();
  bool inside_with = scope_->IsInsideWith();
  Scope function_scope(&scope_, kFunctionScope);
1345
  function_scope.set_is_generator(is_generator);
1346 1347
  //  FormalParameterList ::
  //    '(' (Identifier)*[','] ')'
1348
  Expect(Token::LPAREN, CHECK_OK);
1349
  int start_position = position();
1350 1351
  bool done = (peek() == Token::RPAREN);
  DuplicateFinder duplicate_finder(scanner()->unicode_cache());
1352
  while (!done) {
1353 1354
    Identifier id = ParseIdentifier(CHECK_OK);
    if (!id.IsValidStrictVariable()) {
1355
      StrictModeIdentifierViolation(scanner()->location(),
1356 1357 1358 1359
                                    "strict_param_name",
                                    id,
                                    CHECK_OK);
    }
1360
    int prev_value;
1361
    if (scanner()->is_literal_ascii()) {
1362
      prev_value =
1363
          duplicate_finder.AddAsciiSymbol(scanner()->literal_ascii_string(), 1);
1364 1365
    } else {
      prev_value =
1366
          duplicate_finder.AddUtf16Symbol(scanner()->literal_utf16_string(), 1);
1367 1368 1369
    }

    if (prev_value != 0) {
1370
      SetStrictModeViolation(scanner()->location(),
1371 1372 1373
                             "strict_param_dupe",
                             CHECK_OK);
    }
1374
    done = (peek() == Token::RPAREN);
1375
    if (!done) {
1376
      Expect(Token::COMMA, CHECK_OK);
1377 1378
    }
  }
1379
  Expect(Token::RPAREN, CHECK_OK);
1380 1381 1382 1383

  // 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.
1384
  bool is_lazily_compiled = (outer_scope_type == kTopLevelScope &&
1385
                             !inside_with && allow_lazy() &&
1386 1387
                             !parenthesized_function_);
  parenthesized_function_ = false;
1388

1389
  Expect(Token::LBRACE, CHECK_OK);
1390
  if (is_lazily_compiled) {
1391
    ParseLazyFunctionLiteralBody(CHECK_OK);
1392
  } else {
1393
    ParseSourceElements(Token::RBRACE, ok);
1394
  }
1395
  Expect(Token::RBRACE, CHECK_OK);
1396

1397
  if (!is_classic_mode()) {
1398
    int end_position = scanner()->location().end_pos;
1399
    CheckOctalLiteral(start_position, end_position, CHECK_OK);
1400 1401
    CheckDelayedStrictModeViolation(start_position, end_position, CHECK_OK);
    return Expression::StrictFunction();
1402 1403
  }

1404
  return Expression::Default();
1405 1406 1407
}


1408
void PreParser::ParseLazyFunctionLiteralBody(bool* ok) {
1409
  int body_start = position();
1410
  log_->PauseRecording();
1411
  ParseSourceElements(Token::RBRACE, ok);
1412 1413 1414 1415
  log_->ResumeRecording();
  if (!*ok) return;

  // Position right after terminal '}'.
1416
  ASSERT_EQ(Token::RBRACE, scanner()->peek());
1417
  int body_end = scanner()->peek_location().end_pos;
1418 1419 1420 1421 1422 1423 1424
  log_->LogFunction(body_start, body_end,
                    scope_->materialized_literal_count(),
                    scope_->expected_properties(),
                    language_mode());
}


1425
PreParser::Expression PreParser::ParseV8Intrinsic(bool* ok) {
1426 1427
  // CallRuntime ::
  //   '%' Identifier Arguments
1428
  Expect(Token::MOD, CHECK_OK);
1429
  if (!allow_natives_syntax()) {
1430 1431 1432
    *ok = false;
    return Expression::Default();
  }
1433
  ParseIdentifier(CHECK_OK);
1434
  ParseArguments(ok);
1435

1436
  return Expression::Default();
1437 1438
}

1439 1440
#undef CHECK_OK

1441

1442
void PreParser::LogSymbol() {
1443
  int identifier_pos = position();
1444 1445
  if (scanner()->is_literal_ascii()) {
    log_->LogAsciiSymbol(identifier_pos, scanner()->literal_ascii_string());
1446
  } else {
1447
    log_->LogUtf16Symbol(identifier_pos, scanner()->literal_utf16_string());
1448
  }
1449 1450 1451
}


1452
PreParser::Expression PreParser::GetStringSymbol() {
1453 1454
  const int kUseStrictLength = 10;
  const char* kUseStrictChars = "use strict";
1455
  LogSymbol();
1456 1457 1458 1459
  if (scanner()->is_literal_ascii() &&
      scanner()->literal_length() == kUseStrictLength &&
      !scanner()->literal_contains_escapes() &&
      !strncmp(scanner()->literal_ascii_string().start(), kUseStrictChars,
1460
               kUseStrictLength)) {
1461 1462 1463 1464 1465 1466 1467 1468
    return Expression::UseStrictStringLiteral();
  }
  return Expression::StringLiteral();
}


PreParser::Identifier PreParser::GetIdentifierSymbol() {
  LogSymbol();
1469
  if (scanner()->current_token() == Token::FUTURE_RESERVED_WORD) {
1470
    return Identifier::FutureReserved();
1471
  } else if (scanner()->current_token() ==
1472
             Token::FUTURE_STRICT_RESERVED_WORD) {
1473
    return Identifier::FutureStrictReserved();
1474
  } else if (scanner()->current_token() == Token::YIELD) {
1475
    return Identifier::Yield();
1476
  }
1477
  if (scanner()->is_literal_ascii()) {
1478
    // Detect strict-mode poison words.
1479 1480
    if (scanner()->literal_length() == 4 &&
        !strncmp(scanner()->literal_ascii_string().start(), "eval", 4)) {
1481 1482
      return Identifier::Eval();
    }
1483 1484
    if (scanner()->literal_length() == 9 &&
        !strncmp(scanner()->literal_ascii_string().start(), "arguments", 9)) {
1485 1486
      return Identifier::Arguments();
    }
1487
  }
1488
  return Identifier::Default();
1489 1490 1491
}


1492
PreParser::Identifier PreParser::ParseIdentifier(bool* ok) {
1493
  Token::Value next = Next();
1494
  switch (next) {
1495 1496
    case Token::FUTURE_RESERVED_WORD: {
      Scanner::Location location = scanner()->location();
1497 1498 1499
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "reserved_word", NULL);
      *ok = false;
1500
      return GetIdentifierSymbol();
1501
    }
1502
    case Token::YIELD:
1503 1504
      if (scope_->is_generator()) {
        // 'yield' in a generator is only valid as part of a YieldExpression.
1505
        ReportMessageAt(scanner()->location(), "unexpected_token", "yield");
1506 1507 1508 1509
        *ok = false;
        return Identifier::Yield();
      }
      // FALLTHROUGH
1510
    case Token::FUTURE_STRICT_RESERVED_WORD:
1511
      if (!is_classic_mode()) {
1512
        Scanner::Location location = scanner()->location();
1513 1514 1515 1516 1517
        ReportMessageAt(location.beg_pos, location.end_pos,
                        "strict_reserved_word", NULL);
        *ok = false;
      }
      // FALLTHROUGH
1518
    case Token::IDENTIFIER:
1519 1520 1521 1522
      return GetIdentifierSymbol();
    default:
      *ok = false;
      return Identifier::Default();
1523
  }
1524 1525 1526
}


1527
void PreParser::SetStrictModeViolation(Scanner::Location location,
1528 1529
                                       const char* type,
                                       bool* ok) {
1530
  if (!is_classic_mode()) {
1531
    ReportMessageAt(location, type, NULL);
1532 1533 1534 1535 1536 1537
    *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).
1538 1539 1540 1541 1542
  // 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).
1543 1544 1545 1546 1547 1548 1549 1550
  strict_mode_violation_location_ = location;
  strict_mode_violation_type_ = type;
}


void PreParser::CheckDelayedStrictModeViolation(int beg_pos,
                                                int end_pos,
                                                bool* ok) {
1551
  Scanner::Location location = strict_mode_violation_location_;
1552 1553
  if (location.IsValid() &&
      location.beg_pos > beg_pos && location.end_pos < end_pos) {
1554
    ReportMessageAt(location, strict_mode_violation_type_, NULL);
1555 1556 1557 1558 1559
    *ok = false;
  }
}


1560
void PreParser::StrictModeIdentifierViolation(Scanner::Location location,
1561 1562 1563 1564 1565
                                              const char* eval_args_type,
                                              Identifier identifier,
                                              bool* ok) {
  const char* type = eval_args_type;
  if (identifier.IsFutureReserved()) {
1566
    type = "reserved_word";
1567
  } else if (identifier.IsFutureStrictReserved() || identifier.IsYield()) {
1568 1569
    type = "strict_reserved_word";
  }
1570
  if (!is_classic_mode()) {
1571
    ReportMessageAt(location, type, NULL);
1572 1573 1574 1575 1576 1577 1578 1579
    *ok = false;
    return;
  }
  strict_mode_violation_location_ = location;
  strict_mode_violation_type_ = type;
}


1580
PreParser::Identifier PreParser::ParseIdentifierName(bool* ok) {
1581 1582
  Token::Value next = Next();
  if (Token::IsKeyword(next)) {
1583
    int pos = position();
1584 1585
    const char* keyword = Token::String(next);
    log_->LogAsciiSymbol(pos, Vector<const char>(keyword, StrLength(keyword)));
1586
    return Identifier::Default();
1587
  }
1588 1589 1590
  if (next == Token::IDENTIFIER ||
      next == Token::FUTURE_RESERVED_WORD ||
      next == Token::FUTURE_STRICT_RESERVED_WORD) {
1591 1592 1593
    return GetIdentifierSymbol();
  }
  *ok = false;
1594
  return Identifier::Default();
1595 1596
}

1597 1598
#undef CHECK_OK

1599 1600

// This function reads an identifier and determines whether or not it
1601
// is 'get' or 'set'.
1602 1603 1604 1605
PreParser::Identifier PreParser::ParseIdentifierNameOrGetOrSet(bool* is_get,
                                                               bool* is_set,
                                                               bool* ok) {
  Identifier result = ParseIdentifierName(ok);
1606
  if (!*ok) return Identifier::Default();
1607 1608 1609
  if (scanner()->is_literal_ascii() &&
      scanner()->literal_length() == 3) {
    const char* token = scanner()->literal_ascii_string().start();
1610 1611 1612
    *is_get = strncmp(token, "get", 3) == 0;
    *is_set = !*is_get && strncmp(token, "set", 3) == 0;
  }
1613 1614 1615
  return result;
}

1616

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
void PreParser::ObjectLiteralChecker::CheckProperty(Token::Value property,
                                                    PropertyKind type,
                                                    bool* ok) {
  int old;
  if (property == Token::NUMBER) {
    old = finder_.AddNumber(scanner()->literal_ascii_string(), type);
  } else if (scanner()->is_literal_ascii()) {
    old = finder_.AddAsciiSymbol(scanner()->literal_ascii_string(), type);
  } else {
    old = finder_.AddUtf16Symbol(scanner()->literal_utf16_string(), type);
  }
  PropertyKind old_type = static_cast<PropertyKind>(old);
  if (HasConflict(old_type, type)) {
    if (IsDataDataConflict(old_type, type)) {
      // Both are data properties.
      if (language_mode_ == CLASSIC_MODE) return;
      parser()->ReportMessageAt(scanner()->location(),
                               "strict_duplicate_property");
    } else if (IsDataAccessorConflict(old_type, type)) {
      // Both a data and an accessor property with the same name.
      parser()->ReportMessageAt(scanner()->location(),
                               "accessor_data_property");
    } else {
      ASSERT(IsAccessorAccessorConflict(old_type, type));
      // Both accessors of the same type.
      parser()->ReportMessageAt(scanner()->location(),
                               "accessor_get_set");
    }
    *ok = false;
  }
}

1649
} }  // v8::internal