preparser.cc 51.2 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 29
#include <math.h>

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
namespace v8 {
46 47 48 49 50 51 52

#ifdef _MSC_VER
// Usually defined in math.h, but not in MSVC.
// Abstracted to work
int isfinite(double value);
#endif

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
namespace preparser {

// 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.
72
  if (token == i::Token::ILLEGAL && stack_overflow_) {
73 74 75 76 77 78 79
    return;
  }
  i::JavaScriptScanner::Location source_location = scanner_->location();

  // Four of the tokens are treated specially
  switch (token) {
  case i::Token::EOS:
80
    return ReportMessageAt(source_location, "unexpected_eos", NULL);
81
  case i::Token::NUMBER:
82
    return ReportMessageAt(source_location, "unexpected_token_number", NULL);
83
  case i::Token::STRING:
84
    return ReportMessageAt(source_location, "unexpected_token_string", NULL);
85
  case i::Token::IDENTIFIER:
86
    return ReportMessageAt(source_location,
87
                           "unexpected_token_identifier", NULL);
88
  case i::Token::FUTURE_RESERVED_WORD:
89
    return ReportMessageAt(source_location, "unexpected_reserved", NULL);
90
  case i::Token::FUTURE_STRICT_RESERVED_WORD:
91
    return ReportMessageAt(source_location,
92
                           "unexpected_strict_reserved", NULL);
93 94
  default:
    const char* name = i::Token::String(token);
95
    ReportMessageAt(source_location, "unexpected_token", name);
96 97 98 99
  }
}


100 101 102 103 104
// 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) {
105
    ReportMessageAt(octal, "strict_octal_literal", NULL);
106 107 108 109 110 111
    scanner_->clear_octal_position();
    *ok = false;
  }
}


112 113 114 115 116 117 118
#define CHECK_OK  ok);                      \
  if (!*ok) return kUnknownSourceElements;  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


119 120 121 122 123 124 125 126 127 128
PreParser::Statement PreParser::ParseSourceElement(bool* ok) {
  switch (peek()) {
    case i::Token::LET:
      return ParseVariableStatement(kSourceElement, ok);
    default:
      return ParseStatement(ok);
  }
}


129 130
PreParser::SourceElements PreParser::ParseSourceElements(int end_token,
                                                         bool* ok) {
131 132 133
  // SourceElements ::
  //   (Statement)* <end_token>

134
  bool allow_directive_prologue = true;
135
  while (peek() != end_token) {
136
    Statement statement = ParseSourceElement(CHECK_OK);
137
    if (allow_directive_prologue) {
138
      if (statement.IsUseStrictLiteral()) {
139
        set_strict_mode();
140
      } else if (!statement.IsStringLiteral()) {
141 142 143
        allow_directive_prologue = false;
      }
    }
144 145 146 147 148
  }
  return kUnknownSourceElements;
}


149 150 151 152 153 154 155 156
#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
157
PreParser::Statement PreParser::ParseStatement(bool* ok) {
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  // 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:
    case i::Token::VAR:
189
      return ParseVariableStatement(kStatement, ok);
190 191 192

    case i::Token::SEMICOLON:
      Next();
193
      return Statement::Default();
194 195

    case i::Token::IF:
196
      return ParseIfStatement(ok);
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

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

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

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

    default:
      return ParseExpressionOrLabelledStatement(ok);
  }
}


240
PreParser::Statement PreParser::ParseFunctionDeclaration(bool* ok) {
241 242 243
  // FunctionDeclaration ::
  //   'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
  Expect(i::Token::FUNCTION, CHECK_OK);
244 245 246 247 248 249 250 251 252 253 254

  Identifier identifier = ParseIdentifier(CHECK_OK);
  i::Scanner::Location location = scanner_->location();

  Expression function_value = ParseFunctionLiteral(CHECK_OK);

  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";
255
    if (identifier.IsFutureStrictReserved()) {
256 257
      type = "strict_reserved_word";
    }
258
    ReportMessageAt(location, type, NULL);
259 260
    *ok = false;
  }
261
  return Statement::FunctionDeclaration();
262 263 264
}


265
PreParser::Statement PreParser::ParseBlock(bool* ok) {
266 267 268 269 270 271 272 273
  // 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) {
274
    i::Scanner::Location start_location = scanner_->peek_location();
275
    Statement statement = ParseSourceElement(CHECK_OK);
276 277 278 279 280 281 282
    i::Scanner::Location end_location = scanner_->location();
    if (strict_mode() && statement.IsFunctionDeclaration()) {
      ReportMessageAt(start_location.beg_pos, end_location.end_pos,
                      "strict_function", NULL);
      *ok = false;
      return Statement::Default();
    }
283
  }
284 285
  Expect(i::Token::RBRACE, ok);
  return Statement::Default();
286 287 288
}


289 290 291
PreParser::Statement PreParser::ParseVariableStatement(
    VariableDeclarationContext var_context,
    bool* ok) {
292 293 294
  // VariableStatement ::
  //   VariableDeclarations ';'

295 296 297
  Statement result = ParseVariableDeclarations(var_context,
                                               NULL,
                                               CHECK_OK);
298 299 300 301 302 303 304 305 306 307
  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.
308 309 310 311
PreParser::Statement PreParser::ParseVariableDeclarations(
    VariableDeclarationContext var_context,
    int* num_decl,
    bool* ok) {
312 313 314 315 316 317
  // VariableDeclarations ::
  //   ('var' | 'const') (Identifier ('=' AssignmentExpression)?)+[',']

  if (peek() == i::Token::VAR) {
    Consume(i::Token::VAR);
  } else if (peek() == i::Token::CONST) {
318 319
    if (strict_mode()) {
      i::Scanner::Location location = scanner_->peek_location();
320
      ReportMessageAt(location, "strict_const", NULL);
321 322 323
      *ok = false;
      return Statement::Default();
    }
324
    Consume(i::Token::CONST);
325 326 327 328 329 330 331 332 333 334
  } else if (peek() == i::Token::LET) {
    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();
    }
    Consume(i::Token::LET);
335 336
  } else {
    *ok = false;
337
    return Statement::Default();
338 339
  }

340 341 342 343
  // 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.
344 345 346 347
  int nvars = 0;  // the number of variables declared
  do {
    // Parse variable name.
    if (nvars > 0) Consume(i::Token::COMMA);
348 349 350 351 352 353 354 355
    Identifier identifier  = ParseIdentifier(CHECK_OK);
    if (strict_mode() && !identifier.IsValidStrictVariable()) {
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_var_name",
                                    identifier,
                                    ok);
      return Statement::Default();
    }
356 357 358
    nvars++;
    if (peek() == i::Token::ASSIGN) {
      Expect(i::Token::ASSIGN, CHECK_OK);
359
      ParseAssignmentExpression(var_context != kForStatement, CHECK_OK);
360 361 362 363
    }
  } while (peek() == i::Token::COMMA);

  if (num_decl != NULL) *num_decl = nvars;
364
  return Statement::Default();
365 366 367
}


368
PreParser::Statement PreParser::ParseExpressionOrLabelledStatement(bool* ok) {
369 370 371 372 373
  // ExpressionStatement | LabelledStatement ::
  //   Expression ';'
  //   Identifier ':' Statement

  Expression expr = ParseExpression(true, CHECK_OK);
374 375 376
  if (expr.IsRawIdentifier()) {
    if (peek() == i::Token::COLON &&
        (!strict_mode() || !expr.AsIdentifier().IsFutureReserved())) {
377
      Consume(i::Token::COLON);
378 379 380 381 382 383 384 385
      i::Scanner::Location start_location = scanner_->peek_location();
      Statement statement = ParseStatement(CHECK_OK);
      if (strict_mode() && statement.IsFunctionDeclaration()) {
        i::Scanner::Location end_location = scanner_->location();
        ReportMessageAt(start_location.beg_pos, end_location.end_pos,
                        "strict_function", NULL);
        *ok = false;
      }
386 387
      return Statement::Default();
    }
388 389 390
    // 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.
391 392 393
  }
  // Parsed expression statement.
  ExpectSemicolon(CHECK_OK);
394
  return Statement::ExpressionStatement(expr);
395 396 397
}


398
PreParser::Statement PreParser::ParseIfStatement(bool* ok) {
399 400 401 402 403 404 405 406 407 408 409 410
  // 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);
  }
411
  return Statement::Default();
412 413 414
}


415
PreParser::Statement PreParser::ParseContinueStatement(bool* ok) {
416 417 418 419 420
  // ContinueStatement ::
  //   'continue' [no line terminator] Identifier? ';'

  Expect(i::Token::CONTINUE, CHECK_OK);
  i::Token::Value tok = peek();
421
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
422 423 424 425 426 427
      tok != i::Token::SEMICOLON &&
      tok != i::Token::RBRACE &&
      tok != i::Token::EOS) {
    ParseIdentifier(CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
428
  return Statement::Default();
429 430 431
}


432
PreParser::Statement PreParser::ParseBreakStatement(bool* ok) {
433 434 435 436 437
  // BreakStatement ::
  //   'break' [no line terminator] Identifier? ';'

  Expect(i::Token::BREAK, CHECK_OK);
  i::Token::Value tok = peek();
438
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
439 440 441 442 443 444
      tok != i::Token::SEMICOLON &&
      tok != i::Token::RBRACE &&
      tok != i::Token::EOS) {
    ParseIdentifier(CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
445
  return Statement::Default();
446 447 448
}


449
PreParser::Statement PreParser::ParseReturnStatement(bool* ok) {
450 451 452 453 454 455 456 457 458 459 460 461 462 463
  // 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();
464
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
465 466 467 468 469 470
      tok != i::Token::SEMICOLON &&
      tok != i::Token::RBRACE &&
      tok != i::Token::EOS) {
    ParseExpression(true, CHECK_OK);
  }
  ExpectSemicolon(CHECK_OK);
471
  return Statement::Default();
472 473 474
}


475
PreParser::Statement PreParser::ParseWithStatement(bool* ok) {
476 477 478
  // WithStatement ::
  //   'with' '(' Expression ')' Statement
  Expect(i::Token::WITH, CHECK_OK);
479 480
  if (strict_mode()) {
    i::Scanner::Location location = scanner_->location();
481
    ReportMessageAt(location, "strict_mode_with", NULL);
482 483 484
    *ok = false;
    return Statement::Default();
  }
485 486 487 488 489 490 491
  Expect(i::Token::LPAREN, CHECK_OK);
  ParseExpression(true, CHECK_OK);
  Expect(i::Token::RPAREN, CHECK_OK);

  scope_->EnterWith();
  ParseStatement(CHECK_OK);
  scope_->LeaveWith();
492
  return Statement::Default();
493 494 495
}


496
PreParser::Statement PreParser::ParseSwitchStatement(bool* ok) {
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
  // 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);
      Expect(i::Token::COLON, CHECK_OK);
    } else if (token == i::Token::DEFAULT) {
      Expect(i::Token::DEFAULT, CHECK_OK);
      Expect(i::Token::COLON, CHECK_OK);
    } else {
516 517 518 519 520 521 522 523 524
      i::Scanner::Location start_location = scanner_->peek_location();
      Statement statement = ParseStatement(CHECK_OK);
      if (strict_mode() && statement.IsFunctionDeclaration()) {
        i::Scanner::Location end_location = scanner_->location();
        ReportMessageAt(start_location.beg_pos, end_location.end_pos,
                        "strict_function", NULL);
        *ok = false;
        return Statement::Default();
      }
525 526 527
    }
    token = peek();
  }
528 529
  Expect(i::Token::RBRACE, ok);
  return Statement::Default();
530 531 532
}


533
PreParser::Statement PreParser::ParseDoWhileStatement(bool* ok) {
534 535 536 537 538 539 540 541
  // 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);
542 543
  Expect(i::Token::RPAREN, ok);
  return Statement::Default();
544 545 546
}


547
PreParser::Statement PreParser::ParseWhileStatement(bool* ok) {
548 549 550 551 552 553 554
  // 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);
555 556
  ParseStatement(ok);
  return Statement::Default();
557 558 559
}


560
PreParser::Statement PreParser::ParseForStatement(bool* ok) {
561 562 563 564 565 566
  // ForStatement ::
  //   'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement

  Expect(i::Token::FOR, CHECK_OK);
  Expect(i::Token::LPAREN, CHECK_OK);
  if (peek() != i::Token::SEMICOLON) {
567 568
    if (peek() == i::Token::VAR || peek() == i::Token::CONST ||
        peek() == i::Token::LET) {
569
      int decl_count;
570
      ParseVariableDeclarations(kForStatement, &decl_count, CHECK_OK);
571 572 573 574 575 576
      if (peek() == i::Token::IN && decl_count == 1) {
        Expect(i::Token::IN, CHECK_OK);
        ParseExpression(true, CHECK_OK);
        Expect(i::Token::RPAREN, CHECK_OK);

        ParseStatement(CHECK_OK);
577
        return Statement::Default();
578 579 580 581 582 583 584 585 586
      }
    } else {
      ParseExpression(false, CHECK_OK);
      if (peek() == i::Token::IN) {
        Expect(i::Token::IN, CHECK_OK);
        ParseExpression(true, CHECK_OK);
        Expect(i::Token::RPAREN, CHECK_OK);

        ParseStatement(CHECK_OK);
587
        return Statement::Default();
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
      }
    }
  }

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

605 606
  ParseStatement(ok);
  return Statement::Default();
607 608 609
}


610
PreParser::Statement PreParser::ParseThrowStatement(bool* ok) {
611 612 613 614
  // ThrowStatement ::
  //   'throw' [no line terminator] Expression ';'

  Expect(i::Token::THROW, CHECK_OK);
615
  if (scanner_->HasAnyLineTerminatorBeforeNext()) {
616
    i::JavaScriptScanner::Location pos = scanner_->location();
617
    ReportMessageAt(pos, "newline_after_throw", NULL);
618
    *ok = false;
619
    return Statement::Default();
620 621
  }
  ParseExpression(true, CHECK_OK);
622 623
  ExpectSemicolon(ok);
  return Statement::Default();
624 625 626
}


627
PreParser::Statement PreParser::ParseTryStatement(bool* ok) {
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  // 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);
650 651 652 653 654 655 656 657
    Identifier id = ParseIdentifier(CHECK_OK);
    if (strict_mode() && !id.IsValidStrictVariable()) {
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_catch_variable",
                                    id,
                                    ok);
      return Statement::Default();
    }
658 659 660 661
    Expect(i::Token::RPAREN, CHECK_OK);
    scope_->EnterWith();
    ParseBlock(ok);
    scope_->LeaveWith();
662
    if (!*ok) Statement::Default();
663 664 665 666 667 668 669 670 671 672
    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;
  }
673
  return Statement::Default();
674 675 676
}


677
PreParser::Statement PreParser::ParseDebuggerStatement(bool* ok) {
678 679 680 681 682 683 684
  // 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);
685 686
  ExpectSemicolon(ok);
  return Statement::Default();
687 688 689
}


690 691 692 693 694 695 696 697
#undef CHECK_OK
#define CHECK_OK  ok);                     \
  if (!*ok) return Expression::Default();  \
  ((void)0
#define DUMMY )  // to make indentation work
#undef DUMMY


698
// Precedence = 1
699
PreParser::Expression PreParser::ParseExpression(bool accept_IN, bool* ok) {
700 701 702 703 704 705 706 707
  // 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);
708
    result = Expression::Default();
709 710 711 712 713 714
  }
  return result;
}


// Precedence = 2
715 716
PreParser::Expression PreParser::ParseAssignmentExpression(bool accept_IN,
                                                           bool* ok) {
717 718 719 720
  // AssignmentExpression ::
  //   ConditionalExpression
  //   LeftHandSideExpression AssignmentOperator AssignmentExpression

721
  i::Scanner::Location before = scanner_->peek_location();
722 723 724 725 726 727 728
  Expression expression = ParseConditionalExpression(accept_IN, CHECK_OK);

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

729 730 731 732 733 734 735 736 737
  if (strict_mode() && expression.IsIdentifier() &&
      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();
  }

738 739 740
  i::Token::Value op = Next();  // Get assignment operator.
  ParseAssignmentExpression(accept_IN, CHECK_OK);

741
  if ((op == i::Token::ASSIGN) && expression.IsThisProperty()) {
742 743 744
    scope_->AddProperty();
  }

745
  return Expression::Default();
746 747 748 749
}


// Precedence = 3
750 751
PreParser::Expression PreParser::ParseConditionalExpression(bool accept_IN,
                                                            bool* ok) {
752 753 754 755 756 757 758 759 760 761 762 763 764 765
  // 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);
766
  return Expression::Default();
767 768 769 770 771 772 773 774 775 776 777 778
}


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
779 780 781
PreParser::Expression PreParser::ParseBinaryExpression(int prec,
                                                       bool accept_IN,
                                                       bool* ok) {
782 783 784 785 786 787
  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);
788
      result = Expression::Default();
789 790 791 792 793 794
    }
  }
  return result;
}


795
PreParser::Expression PreParser::ParseUnaryExpression(bool* ok) {
796 797 798 799 800 801 802 803 804 805 806 807 808
  // UnaryExpression ::
  //   PostfixExpression
  //   'delete' UnaryExpression
  //   'void' UnaryExpression
  //   'typeof' UnaryExpression
  //   '++' UnaryExpression
  //   '--' UnaryExpression
  //   '+' UnaryExpression
  //   '-' UnaryExpression
  //   '~' UnaryExpression
  //   '!' UnaryExpression

  i::Token::Value op = peek();
809
  if (i::Token::IsUnaryOp(op)) {
810 811
    op = Next();
    ParseUnaryExpression(ok);
812 813 814 815 816 817 818 819 820 821 822 823 824
    return Expression::Default();
  } else if (i::Token::IsCountOp(op)) {
    op = Next();
    i::Scanner::Location before = scanner_->peek_location();
    Expression expression = ParseUnaryExpression(CHECK_OK);
    if (strict_mode() && expression.IsIdentifier() &&
        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();
825 826 827 828 829 830
  } else {
    return ParsePostfixExpression(ok);
  }
}


831
PreParser::Expression PreParser::ParsePostfixExpression(bool* ok) {
832 833 834
  // PostfixExpression ::
  //   LeftHandSideExpression ('++' | '--')?

835
  i::Scanner::Location before = scanner_->peek_location();
836
  Expression expression = ParseLeftHandSideExpression(CHECK_OK);
837
  if (!scanner_->HasAnyLineTerminatorBeforeNext() &&
838
      i::Token::IsCountOp(peek())) {
839 840 841 842 843 844 845 846
    if (strict_mode() && expression.IsIdentifier() &&
        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();
    }
847
    Next();
848
    return Expression::Default();
849 850 851 852 853
  }
  return expression;
}


854
PreParser::Expression PreParser::ParseLeftHandSideExpression(bool* ok) {
855 856 857
  // LeftHandSideExpression ::
  //   (NewExpression | MemberExpression) ...

858
  Expression result = Expression::Default();
859 860 861 862 863 864 865 866 867 868 869 870
  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);
871 872
        if (result.IsThis()) {
          result = Expression::ThisProperty();
873
        } else {
874
          result = Expression::Default();
875 876 877 878 879 880
        }
        break;
      }

      case i::Token::LPAREN: {
        ParseArguments(CHECK_OK);
881
        result = Expression::Default();
882 883 884 885 886 887
        break;
      }

      case i::Token::PERIOD: {
        Consume(i::Token::PERIOD);
        ParseIdentifierName(CHECK_OK);
888 889
        if (result.IsThis()) {
          result = Expression::ThisProperty();
890
        } else {
891
          result = Expression::Default();
892 893 894 895 896 897 898 899 900 901 902
        }
        break;
      }

      default:
        return result;
    }
  }
}


903
PreParser::Expression PreParser::ParseNewExpression(bool* ok) {
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  // 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);
}


925
PreParser::Expression PreParser::ParseMemberExpression(bool* ok) {
926 927 928 929
  return ParseMemberWithNewPrefixesExpression(0, ok);
}


930
PreParser::Expression PreParser::ParseMemberWithNewPrefixesExpression(
931 932 933 934 935 936
    unsigned new_count, bool* ok) {
  // MemberExpression ::
  //   (PrimaryExpression | FunctionLiteral)
  //     ('[' Expression ']' | '.' Identifier | Arguments)*

  // Parse the initial primary or function expression.
937
  Expression result = Expression::Default();
938 939
  if (peek() == i::Token::FUNCTION) {
    Consume(i::Token::FUNCTION);
940
    Identifier identifier = Identifier::Default();
941
    if (peek_any_identifier()) {
942
      identifier = ParseIdentifier(CHECK_OK);
943 944
    }
    result = ParseFunctionLiteral(CHECK_OK);
945 946 947 948 949 950 951
    if (result.IsStrictFunction() && !identifier.IsValidStrictVariable()) {
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_function_name",
                                    identifier,
                                    ok);
      return Expression::Default();
    }
952 953 954 955 956 957 958 959 960 961
  } 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);
962 963
        if (result.IsThis()) {
          result = Expression::ThisProperty();
964
        } else {
965
          result = Expression::Default();
966 967 968 969 970 971
        }
        break;
      }
      case i::Token::PERIOD: {
        Consume(i::Token::PERIOD);
        ParseIdentifierName(CHECK_OK);
972 973
        if (result.IsThis()) {
          result = Expression::ThisProperty();
974
        } else {
975
          result = Expression::Default();
976 977 978 979 980 981 982 983
        }
        break;
      }
      case i::Token::LPAREN: {
        if (new_count == 0) return result;
        // Consume one of the new prefixes (already parsed).
        ParseArguments(CHECK_OK);
        new_count--;
984
        result = Expression::Default();
985 986 987 988 989 990 991 992 993
        break;
      }
      default:
        return result;
    }
  }
}


994
PreParser::Expression PreParser::ParsePrimaryExpression(bool* ok) {
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
  // PrimaryExpression ::
  //   'this'
  //   'null'
  //   'true'
  //   'false'
  //   Identifier
  //   Number
  //   String
  //   ArrayLiteral
  //   ObjectLiteral
  //   RegExpLiteral
  //   '(' Expression ')'

1008
  Expression result = Expression::Default();
1009 1010 1011
  switch (peek()) {
    case i::Token::THIS: {
      Next();
1012
      result = Expression::This();
1013 1014 1015
      break;
    }

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    case i::Token::FUTURE_RESERVED_WORD: {
      Next();
      i::Scanner::Location location = scanner_->location();
      ReportMessageAt(location.beg_pos, location.end_pos,
                      "reserved_word", NULL);
      *ok = false;
      return Expression::Default();
    }

    case i::Token::FUTURE_STRICT_RESERVED_WORD:
1026 1027 1028
      if (strict_mode()) {
        Next();
        i::Scanner::Location location = scanner_->location();
1029
        ReportMessageAt(location, "strict_reserved_word", NULL);
1030 1031 1032 1033 1034 1035
        *ok = false;
        return Expression::Default();
      }
      // FALLTHROUGH
    case i::Token::IDENTIFIER: {
      Identifier id = ParseIdentifier(CHECK_OK);
1036
      result = Expression::FromIdentifier(id);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
      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);
1071
      parenthesized_function_ = (peek() == i::Token::FUNCTION);
1072 1073
      result = ParseExpression(true, CHECK_OK);
      Expect(i::Token::RPAREN, CHECK_OK);
1074
      result = result.Parenthesize();
1075 1076 1077 1078 1079 1080 1081 1082 1083
      break;

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

    default: {
      Next();
      *ok = false;
1084
      return Expression::Default();
1085 1086 1087 1088 1089 1090 1091
    }
  }

  return result;
}


1092
PreParser::Expression PreParser::ParseArrayLiteral(bool* ok) {
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  // 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();
1107
  return Expression::Default();
1108 1109
}

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
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 {
    old_type = finder->AddUC16Symbol(scanner_->literal_uc16_string(), type);
  }
  if (HasConflict(old_type, type)) {
    if (IsDataDataConflict(old_type, type)) {
      // Both are data properties.
      if (!strict_mode()) return;
      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;
  }
}

1143

1144
PreParser::Expression PreParser::ParseObjectLiteral(bool* ok) {
1145 1146 1147 1148 1149 1150 1151
  // ObjectLiteral ::
  //   '{' (
  //       ((IdentifierName | String | Number) ':' AssignmentExpression)
  //     | (('get' | 'set') (IdentifierName | String | Number) FunctionLiteral)
  //    )*[','] '}'

  Expect(i::Token::LBRACE, CHECK_OK);
1152
  DuplicateFinder duplicate_finder(scanner_->unicode_cache());
1153 1154 1155
  while (peek() != i::Token::RBRACE) {
    i::Token::Value next = peek();
    switch (next) {
1156
      case i::Token::IDENTIFIER:
1157 1158
      case i::Token::FUTURE_RESERVED_WORD:
      case i::Token::FUTURE_STRICT_RESERVED_WORD: {
1159 1160
        bool is_getter = false;
        bool is_setter = false;
1161
        ParseIdentifierNameOrGetOrSet(&is_getter, &is_setter, CHECK_OK);
1162 1163
        if ((is_getter || is_setter) && peek() != i::Token::COLON) {
            i::Token::Value name = Next();
1164
            bool is_keyword = i::Token::IsKeyword(name);
1165
            if (name != i::Token::IDENTIFIER &&
1166
                name != i::Token::FUTURE_RESERVED_WORD &&
1167
                name != i::Token::FUTURE_STRICT_RESERVED_WORD &&
1168 1169
                name != i::Token::NUMBER &&
                name != i::Token::STRING &&
1170
                !is_keyword) {
1171
              *ok = false;
1172
              return Expression::Default();
1173
            }
1174 1175 1176
            if (!is_keyword) {
              LogSymbol();
            }
1177 1178
            PropertyType type = is_getter ? kGetterProperty : kSetterProperty;
            CheckDuplicate(&duplicate_finder, name, type, CHECK_OK);
1179 1180 1181 1182 1183 1184
            ParseFunctionLiteral(CHECK_OK);
            if (peek() != i::Token::RBRACE) {
              Expect(i::Token::COMMA, CHECK_OK);
            }
            continue;  // restart the while
        }
1185
        CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1186 1187 1188 1189
        break;
      }
      case i::Token::STRING:
        Consume(next);
1190
        CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1191 1192 1193 1194
        GetStringSymbol();
        break;
      case i::Token::NUMBER:
        Consume(next);
1195
        CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1196 1197 1198 1199
        break;
      default:
        if (i::Token::IsKeyword(next)) {
          Consume(next);
1200
          CheckDuplicate(&duplicate_finder, next, kValueProperty, CHECK_OK);
1201 1202 1203
        } else {
          // Unexpected token.
          *ok = false;
1204
          return Expression::Default();
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        }
    }

    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();
1217
  return Expression::Default();
1218 1219 1220
}


1221 1222
PreParser::Expression PreParser::ParseRegExpLiteral(bool seen_equal,
                                                    bool* ok) {
1223 1224
  if (!scanner_->ScanRegExpPattern(seen_equal)) {
    Next();
1225
    ReportMessageAt(scanner_->location(), "unterminated_regexp", NULL);
1226
    *ok = false;
1227
    return Expression::Default();
1228 1229 1230 1231 1232 1233
  }

  scope_->NextMaterializedLiteralIndex();

  if (!scanner_->ScanRegExpFlags()) {
    Next();
1234
    ReportMessageAt(scanner_->location(), "invalid_regexp_flags", NULL);
1235
    *ok = false;
1236
    return Expression::Default();
1237 1238
  }
  Next();
1239
  return Expression::Default();
1240 1241 1242
}


1243
PreParser::Arguments PreParser::ParseArguments(bool* ok) {
1244 1245 1246
  // Arguments ::
  //   '(' (AssignmentExpression)*[','] ')'

1247 1248
  Expect(i::Token::LPAREN, ok);
  if (!*ok) return -1;
1249 1250 1251
  bool done = (peek() == i::Token::RPAREN);
  int argc = 0;
  while (!done) {
1252 1253
    ParseAssignmentExpression(true, ok);
    if (!*ok) return -1;
1254 1255
    argc++;
    done = (peek() == i::Token::RPAREN);
1256 1257 1258 1259
    if (!done) {
      Expect(i::Token::COMMA, ok);
      if (!*ok) return -1;
    }
1260
  }
1261
  Expect(i::Token::RPAREN, ok);
1262 1263 1264 1265
  return argc;
}


1266
PreParser::Expression PreParser::ParseFunctionLiteral(bool* ok) {
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
  // Function ::
  //   '(' FormalParameterList? ')' '{' FunctionBody '}'

  // Parse function body.
  ScopeType outer_scope_type = scope_->type();
  bool inside_with = scope_->IsInsideWith();
  Scope function_scope(&scope_, kFunctionScope);
  //  FormalParameterList ::
  //    '(' (Identifier)*[','] ')'
  Expect(i::Token::LPAREN, CHECK_OK);
1277
  int start_position = scanner_->location().beg_pos;
1278
  bool done = (peek() == i::Token::RPAREN);
1279
  DuplicateFinder duplicate_finder(scanner_->unicode_cache());
1280
  while (!done) {
1281 1282 1283 1284 1285 1286 1287
    Identifier id = ParseIdentifier(CHECK_OK);
    if (!id.IsValidStrictVariable()) {
      StrictModeIdentifierViolation(scanner_->location(),
                                    "strict_param_name",
                                    id,
                                    CHECK_OK);
    }
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    int prev_value;
    if (scanner_->is_literal_ascii()) {
      prev_value =
          duplicate_finder.AddAsciiSymbol(scanner_->literal_ascii_string(), 1);
    } else {
      prev_value =
          duplicate_finder.AddUC16Symbol(scanner_->literal_uc16_string(), 1);
    }

    if (prev_value != 0) {
      SetStrictModeViolation(scanner_->location(),
                             "strict_param_dupe",
                             CHECK_OK);
    }
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    done = (peek() == i::Token::RPAREN);
    if (!done) {
      Expect(i::Token::COMMA, CHECK_OK);
    }
  }
  Expect(i::Token::RPAREN, CHECK_OK);

  Expect(i::Token::LBRACE, CHECK_OK);
  int function_block_pos = scanner_->location().beg_pos;

  // 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.
1315 1316 1317 1318
  bool is_lazily_compiled = (outer_scope_type == kTopLevelScope &&
                             !inside_with && allow_lazy_ &&
                             !parenthesized_function_);
  parenthesized_function_ = false;
1319 1320 1321 1322 1323

  if (is_lazily_compiled) {
    log_->PauseRecording();
    ParseSourceElements(i::Token::RBRACE, ok);
    log_->ResumeRecording();
1324
    if (!*ok) Expression::Default();
1325 1326 1327

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

1328
    // Position right after terminal '}'.
1329 1330 1331
    int end_pos = scanner_->location().end_pos;
    log_->LogFunction(function_block_pos, end_pos,
                      function_scope.materialized_literal_count(),
1332 1333
                      function_scope.expected_properties(),
                      strict_mode() ? 1 : 0);
1334 1335 1336 1337
  } else {
    ParseSourceElements(i::Token::RBRACE, CHECK_OK);
    Expect(i::Token::RBRACE, CHECK_OK);
  }
1338

1339
  if (strict_mode()) {
1340 1341
    int end_position = scanner_->location().end_pos;
    CheckOctalLiteral(start_position, end_position, CHECK_OK);
1342 1343
    CheckDelayedStrictModeViolation(start_position, end_position, CHECK_OK);
    return Expression::StrictFunction();
1344 1345
  }

1346
  return Expression::Default();
1347 1348 1349
}


1350
PreParser::Expression PreParser::ParseV8Intrinsic(bool* ok) {
1351 1352 1353 1354 1355
  // CallRuntime ::
  //   '%' Identifier Arguments

  Expect(i::Token::MOD, CHECK_OK);
  ParseIdentifier(CHECK_OK);
1356
  ParseArguments(ok);
1357

1358
  return Expression::Default();
1359 1360
}

1361 1362
#undef CHECK_OK

1363 1364 1365 1366 1367 1368 1369 1370 1371

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;
  }
1372
  if (scanner_->HasAnyLineTerminatorBeforeNext() ||
1373 1374 1375 1376 1377 1378 1379 1380
      tok == i::Token::RBRACE ||
      tok == i::Token::EOS) {
    return;
  }
  Expect(i::Token::SEMICOLON, ok);
}


1381
void PreParser::LogSymbol() {
1382
  int identifier_pos = scanner_->location().beg_pos;
1383 1384 1385 1386 1387
  if (scanner_->is_literal_ascii()) {
    log_->LogAsciiSymbol(identifier_pos, scanner_->literal_ascii_string());
  } else {
    log_->LogUC16Symbol(identifier_pos, scanner_->literal_uc16_string());
  }
1388 1389 1390
}


1391
PreParser::Expression PreParser::GetStringSymbol() {
1392 1393
  const int kUseStrictLength = 10;
  const char* kUseStrictChars = "use strict";
1394
  LogSymbol();
1395 1396 1397 1398 1399
  if (scanner_->is_literal_ascii() &&
      scanner_->literal_length() == kUseStrictLength &&
      !scanner_->literal_contains_escapes() &&
      !strncmp(scanner_->literal_ascii_string().start(), kUseStrictChars,
               kUseStrictLength)) {
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
    return Expression::UseStrictStringLiteral();
  }
  return Expression::StringLiteral();
}


PreParser::Identifier PreParser::GetIdentifierSymbol() {
  LogSymbol();
  if (scanner_->current_token() == i::Token::FUTURE_RESERVED_WORD) {
    return Identifier::FutureReserved();
1410 1411 1412
  } else if (scanner_->current_token() ==
             i::Token::FUTURE_STRICT_RESERVED_WORD) {
    return Identifier::FutureStrictReserved();
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  }
  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();
    }
1424
  }
1425
  return Identifier::Default();
1426 1427 1428
}


1429
PreParser::Identifier PreParser::ParseIdentifier(bool* ok) {
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
  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;
    }
      // FALLTHROUGH
    case i::Token::FUTURE_STRICT_RESERVED_WORD:
    case i::Token::IDENTIFIER:
      return GetIdentifierSymbol();
    default:
      *ok = false;
      return Identifier::Default();
1445
  }
1446 1447 1448
}


1449 1450 1451 1452
void PreParser::SetStrictModeViolation(i::Scanner::Location location,
                                       const char* type,
                                       bool* ok) {
  if (strict_mode()) {
1453
    ReportMessageAt(location, type, NULL);
1454 1455 1456 1457 1458 1459
    *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).
1460 1461 1462 1463 1464
  // 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).
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
  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) {
1476
    ReportMessageAt(location, strict_mode_violation_type_, NULL);
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    *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()) {
1488 1489
    type = "reserved_word";
  } else if (identifier.IsFutureStrictReserved()) {
1490 1491 1492
    type = "strict_reserved_word";
  }
  if (strict_mode()) {
1493
    ReportMessageAt(location, type, NULL);
1494 1495 1496 1497 1498 1499 1500 1501
    *ok = false;
    return;
  }
  strict_mode_violation_location_ = location;
  strict_mode_violation_type_ = type;
}


1502
PreParser::Identifier PreParser::ParseIdentifierName(bool* ok) {
1503 1504 1505 1506
  i::Token::Value next = Next();
  if (i::Token::IsKeyword(next)) {
    int pos = scanner_->location().beg_pos;
    const char* keyword = i::Token::String(next);
1507 1508
    log_->LogAsciiSymbol(pos, i::Vector<const char>(keyword,
                                                    i::StrLength(keyword)));
1509
    return Identifier::Default();
1510
  }
1511
  if (next == i::Token::IDENTIFIER ||
1512 1513
      next == i::Token::FUTURE_RESERVED_WORD ||
      next == i::Token::FUTURE_STRICT_RESERVED_WORD) {
1514 1515 1516
    return GetIdentifierSymbol();
  }
  *ok = false;
1517
  return Identifier::Default();
1518 1519
}

1520 1521
#undef CHECK_OK

1522 1523

// This function reads an identifier and determines whether or not it
1524
// is 'get' or 'set'.
1525 1526 1527 1528
PreParser::Identifier PreParser::ParseIdentifierNameOrGetOrSet(bool* is_get,
                                                               bool* is_set,
                                                               bool* ok) {
  Identifier result = ParseIdentifierName(ok);
1529 1530 1531
  if (!*ok) return Identifier::Default();
  if (scanner_->is_literal_ascii() &&
      scanner_->literal_length() == 3) {
1532
    const char* token = scanner_->literal_ascii_string().start();
1533 1534 1535
    *is_get = strncmp(token, "get", 3) == 0;
    *is_set = !*is_get && strncmp(token, "set", 3) == 0;
  }
1536 1537 1538 1539 1540 1541
  return result;
}

bool PreParser::peek_any_identifier() {
  i::Token::Value next = peek();
  return next == i::Token::IDENTIFIER ||
1542 1543
         next == i::Token::FUTURE_RESERVED_WORD ||
         next == i::Token::FUTURE_STRICT_RESERVED_WORD;
1544
}
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559


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

int DuplicateFinder::AddUC16Symbol(i::Vector<const uint16_t> key, int value) {
  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
1560
  i::HashMap::Entry* entry = map_.Lookup(encoding, hash, true);
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
  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;
  if (!isfinite(double_value)) {
    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
1587 1588
  return AddSymbol(i::Vector<const byte>(reinterpret_cast<const byte*>(string),
                                         length), true, value);
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 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 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
}


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();
}
1679
} }  // v8::preparser