preparser.h 32.1 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// 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.

#ifndef V8_PREPARSER_H
#define V8_PREPARSER_H

31
#include "hashmap.h"
32 33 34
#include "token.h"
#include "scanner.h"

35
namespace v8 {
36
namespace internal {
37

38
// Common base class shared between parser and pre-parser.
39 40
template <typename Traits>
class ParserBase : public Traits {
41
 public:
42 43 44
  ParserBase(Scanner* scanner, uintptr_t stack_limit,
             typename Traits::ParserType this_object)
      : Traits(this_object),
45
        parenthesized_function_(false),
46
        scanner_(scanner),
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        stack_limit_(stack_limit),
        stack_overflow_(false),
        allow_lazy_(false),
        allow_natives_syntax_(false),
        allow_generators_(false),
        allow_for_of_(false) { }

  // Getters that indicate whether certain syntactical constructs are
  // allowed to be parsed by this instance of the parser.
  bool allow_lazy() const { return allow_lazy_; }
  bool allow_natives_syntax() const { return allow_natives_syntax_; }
  bool allow_generators() const { return allow_generators_; }
  bool allow_for_of() const { return allow_for_of_; }
  bool allow_modules() const { return scanner()->HarmonyModules(); }
  bool allow_harmony_scoping() const { return scanner()->HarmonyScoping(); }
  bool allow_harmony_numeric_literals() const {
    return scanner()->HarmonyNumericLiterals();
  }

  // Setters that determine whether certain syntactical constructs are
  // allowed to be parsed by this instance of the parser.
  void set_allow_lazy(bool allow) { allow_lazy_ = allow; }
  void set_allow_natives_syntax(bool allow) { allow_natives_syntax_ = allow; }
  void set_allow_generators(bool allow) { allow_generators_ = allow; }
  void set_allow_for_of(bool allow) { allow_for_of_ = allow; }
  void set_allow_modules(bool allow) { scanner()->SetHarmonyModules(allow); }
  void set_allow_harmony_scoping(bool allow) {
    scanner()->SetHarmonyScoping(allow);
  }
  void set_allow_harmony_numeric_literals(bool allow) {
    scanner()->SetHarmonyNumericLiterals(allow);
  }

 protected:
81 82 83 84 85
  enum AllowEvalOrArgumentsAsIdentifier {
    kAllowEvalOrArguments,
    kDontAllowEvalOrArguments
  };

86
  Scanner* scanner() const { return scanner_; }
87 88
  int position() { return scanner_->location().beg_pos; }
  int peek_position() { return scanner_->peek_location().beg_pos; }
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  bool stack_overflow() const { return stack_overflow_; }
  void set_stack_overflow() { stack_overflow_ = true; }

  INLINE(Token::Value peek()) {
    if (stack_overflow_) return Token::ILLEGAL;
    return scanner()->peek();
  }

  INLINE(Token::Value Next()) {
    if (stack_overflow_) return Token::ILLEGAL;
    {
      int marker;
      if (reinterpret_cast<uintptr_t>(&marker) < stack_limit_) {
        // Any further calls to Next or peek will return the illegal token.
        // The current call must return the next token, which might already
        // have been peek'ed.
        stack_overflow_ = true;
      }
    }
    return scanner()->Next();
  }

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

  bool Check(Token::Value token) {
    Token::Value next = peek();
    if (next == token) {
      Consume(next);
      return true;
    }
    return false;
  }

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

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  void ExpectSemicolon(bool* ok) {
    // Check for automatic semicolon insertion according to
    // the rules given in ECMA-262, section 7.9, page 21.
    Token::Value tok = peek();
    if (tok == Token::SEMICOLON) {
      Next();
      return;
    }
    if (scanner()->HasAnyLineTerminatorBeforeNext() ||
        tok == Token::RBRACE ||
        tok == Token::EOS) {
      return;
    }
    Expect(Token::SEMICOLON, ok);
  }

  bool peek_any_identifier() {
    Token::Value next = peek();
    return next == Token::IDENTIFIER ||
        next == Token::FUTURE_RESERVED_WORD ||
        next == Token::FUTURE_STRICT_RESERVED_WORD ||
        next == Token::YIELD;
  }
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
  bool CheckContextualKeyword(Vector<const char> keyword) {
    if (peek() == Token::IDENTIFIER &&
        scanner()->is_next_contextual_keyword(keyword)) {
      Consume(Token::IDENTIFIER);
      return true;
    }
    return false;
  }

  void ExpectContextualKeyword(Vector<const char> keyword, bool* ok) {
    Expect(Token::IDENTIFIER, ok);
    if (!*ok) return;
    if (!scanner()->is_literal_contextual_keyword(keyword)) {
      ReportUnexpectedToken(scanner()->current_token());
      *ok = false;
    }
  }

  // Checks whether an octal literal was last seen between beg_pos and end_pos.
  // If so, reports an error. Only called for strict mode.
  void CheckOctalLiteral(int beg_pos, int end_pos, bool* ok) {
    Scanner::Location octal = scanner()->octal_position();
    if (octal.IsValid() && beg_pos <= octal.beg_pos &&
        octal.end_pos <= end_pos) {
      ReportMessageAt(octal, "strict_octal_literal");
      scanner()->clear_octal_position();
      *ok = false;
    }
  }
188 189

  // Determine precedence of given token.
190 191 192 193 194
  static int Precedence(Token::Value token, bool accept_IN) {
    if (token == Token::IN && !accept_IN)
      return 0;  // 0 precedence will terminate binary expression parsing
    return Token::Precedence(token);
  }
195 196

  // Report syntax errors.
197 198 199
  void ReportMessage(const char* message, Vector<const char*> args) {
    Scanner::Location source_location = scanner()->location();
    Traits::ReportMessageAt(source_location, message, args);
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

  void ReportMessageAt(Scanner::Location location, const char* message) {
    Traits::ReportMessageAt(location, message, Vector<const char*>::empty());
  }

  void ReportUnexpectedToken(Token::Value token);

  // Recursive descent functions:

  // Parses an identifier that is valid for the current scope, in particular it
  // fails on strict mode future reserved keywords in a strict scope. If
  // allow_eval_or_arguments is kAllowEvalOrArguments, we allow "eval" or
  // "arguments" as identifier even in strict mode (this is needed in cases like
  // "var foo = eval;").
  typename Traits::IdentifierType ParseIdentifier(
      AllowEvalOrArgumentsAsIdentifier,
      bool* ok);
  // Parses an identifier or a strict mode future reserved word, and indicate
  // whether it is strict mode future reserved.
  typename Traits::IdentifierType ParseIdentifierOrStrictReservedWord(
      bool* is_strict_reserved,
      bool* ok);
  typename Traits::IdentifierType ParseIdentifierName(bool* ok);
  // Parses an identifier and determines whether or not it is 'get' or 'set'.
  typename Traits::IdentifierType ParseIdentifierNameOrGetOrSet(bool* is_get,
                                                                bool* is_set,
                                                                bool* ok);
228

229 230
  typename Traits::ExpressionType ParseRegExpLiteral(bool seen_equal, bool* ok);

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  // Used to detect duplicates in object literals. Each of the values
  // kGetterProperty, kSetterProperty and kValueProperty represents
  // a type of object literal property. When parsing a property, its
  // type value is stored in the DuplicateFinder for the property name.
  // Values are chosen so that having intersection bits means the there is
  // an incompatibility.
  // I.e., you can add a getter to a property that already has a setter, since
  // kGetterProperty and kSetterProperty doesn't intersect, but not if it
  // already has a getter or a value. Adding the getter to an existing
  // setter will store the value (kGetterProperty | kSetterProperty), which
  // is incompatible with adding any further properties.
  enum PropertyKind {
    kNone = 0,
    // Bit patterns representing different object literal property types.
    kGetterProperty = 1,
    kSetterProperty = 2,
    kValueProperty = 7,
    // Helper constants.
    kValueFlag = 4
  };

  // Validation per ECMA 262 - 11.1.5 "Object Initialiser".
  class ObjectLiteralChecker {
   public:
    ObjectLiteralChecker(ParserBase* parser, LanguageMode mode)
        : parser_(parser),
          finder_(scanner()->unicode_cache()),
          language_mode_(mode) { }

    void CheckProperty(Token::Value property, PropertyKind type, bool* ok);

   private:
    ParserBase* parser() const { return parser_; }
    Scanner* scanner() const { return parser_->scanner(); }

    // Checks the type of conflict based on values coming from PropertyType.
    bool HasConflict(PropertyKind type1, PropertyKind type2) {
      return (type1 & type2) != 0;
    }
    bool IsDataDataConflict(PropertyKind type1, PropertyKind type2) {
      return ((type1 & type2) & kValueFlag) != 0;
    }
    bool IsDataAccessorConflict(PropertyKind type1, PropertyKind type2) {
      return ((type1 ^ type2) & kValueFlag) != 0;
    }
    bool IsAccessorAccessorConflict(PropertyKind type1, PropertyKind type2) {
      return ((type1 | type2) & kValueFlag) == 0;
    }

    ParserBase* parser_;
    DuplicateFinder finder_;
    LanguageMode language_mode_;
  };
284

285 286 287 288 289 290
  // If true, the next (and immediately following) function literal is
  // preceded by a parenthesis.
  // Heuristically that means that the function will be called immediately,
  // so never lazily compile it.
  bool parenthesized_function_;

291 292 293 294 295 296 297 298 299 300 301 302
 private:
  Scanner* scanner_;
  uintptr_t stack_limit_;
  bool stack_overflow_;

  bool allow_lazy_;
  bool allow_natives_syntax_;
  bool allow_generators_;
  bool allow_for_of_;
};


303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
class PreParserIdentifier {
 public:
  static PreParserIdentifier Default() {
    return PreParserIdentifier(kUnknownIdentifier);
  }
  static PreParserIdentifier Eval() {
    return PreParserIdentifier(kEvalIdentifier);
  }
  static PreParserIdentifier Arguments() {
    return PreParserIdentifier(kArgumentsIdentifier);
  }
  static PreParserIdentifier FutureReserved() {
    return PreParserIdentifier(kFutureReservedIdentifier);
  }
  static PreParserIdentifier FutureStrictReserved() {
    return PreParserIdentifier(kFutureStrictReservedIdentifier);
  }
  static PreParserIdentifier Yield() {
    return PreParserIdentifier(kYieldIdentifier);
  }
  bool IsEval() { return type_ == kEvalIdentifier; }
  bool IsArguments() { return type_ == kArgumentsIdentifier; }
  bool IsEvalOrArguments() { return type_ >= kEvalIdentifier; }
  bool IsYield() { return type_ == kYieldIdentifier; }
  bool IsFutureReserved() { return type_ == kFutureReservedIdentifier; }
  bool IsFutureStrictReserved() {
    return type_ == kFutureStrictReservedIdentifier;
  }
  bool IsValidStrictVariable() { return type_ == kUnknownIdentifier; }

 private:
  enum Type {
    kUnknownIdentifier,
    kFutureReservedIdentifier,
    kFutureStrictReservedIdentifier,
    kYieldIdentifier,
    kEvalIdentifier,
    kArgumentsIdentifier
  };
  explicit PreParserIdentifier(Type type) : type_(type) {}
  Type type_;

  friend class PreParserExpression;
};


// Bits 0 and 1 are used to identify the type of expression:
// If bit 0 is set, it's an identifier.
// if bit 1 is set, it's a string literal.
// If neither is set, it's no particular type, and both set isn't
// use yet.
class PreParserExpression {
 public:
  static PreParserExpression Default() {
    return PreParserExpression(kUnknownExpression);
  }

  static PreParserExpression FromIdentifier(PreParserIdentifier id) {
    return PreParserExpression(kIdentifierFlag |
                               (id.type_ << kIdentifierShift));
  }

  static PreParserExpression StringLiteral() {
    return PreParserExpression(kUnknownStringLiteral);
  }

  static PreParserExpression UseStrictStringLiteral() {
    return PreParserExpression(kUseStrictString);
  }

  static PreParserExpression This() {
    return PreParserExpression(kThisExpression);
  }

  static PreParserExpression ThisProperty() {
    return PreParserExpression(kThisPropertyExpression);
  }

  static PreParserExpression StrictFunction() {
    return PreParserExpression(kStrictFunctionExpression);
  }

  bool IsIdentifier() { return (code_ & kIdentifierFlag) != 0; }

  // Only works corretly if it is actually an identifier expression.
  PreParserIdentifier AsIdentifier() {
    return PreParserIdentifier(
        static_cast<PreParserIdentifier::Type>(code_ >> kIdentifierShift));
  }

  bool IsStringLiteral() { return (code_ & kStringLiteralFlag) != 0; }

  bool IsUseStrictLiteral() {
    return (code_ & kStringLiteralMask) == kUseStrictString;
  }

  bool IsThis() { return code_ == kThisExpression; }

  bool IsThisProperty() { return code_ == kThisPropertyExpression; }

  bool IsStrictFunction() { return code_ == kStrictFunctionExpression; }

 private:
  // First two/three bits are used as flags.
  // Bit 0 and 1 represent identifiers or strings literals, and are
  // mutually exclusive, but can both be absent.
  enum {
    kUnknownExpression = 0,
    // Identifiers
    kIdentifierFlag = 1,  // Used to detect labels.
    kIdentifierShift = 3,

    kStringLiteralFlag = 2,  // Used to detect directive prologue.
    kUnknownStringLiteral = kStringLiteralFlag,
    kUseStrictString = kStringLiteralFlag | 8,
    kStringLiteralMask = kUseStrictString,

    // Below here applies if neither identifier nor string literal.
    kThisExpression = 4,
    kThisPropertyExpression = 8,
    kStrictFunctionExpression = 12
  };

  explicit PreParserExpression(int expression_code) : code_(expression_code) {}

  int code_;
};

class PreParser;


class PreParserTraits {
 public:
  typedef PreParser* ParserType;
  // Return types for traversing functions.
  typedef PreParserIdentifier IdentifierType;
439
  typedef PreParserExpression ExpressionType;
440 441 442 443 444 445 446 447 448

  explicit PreParserTraits(PreParser* pre_parser) : pre_parser_(pre_parser) {}

  // Helper functions for recursive descent.
  bool is_classic_mode() const;
  bool is_generator() const;
  static bool IsEvalOrArguments(IdentifierType identifier) {
    return identifier.IsEvalOrArguments();
  }
449
  int NextMaterializedLiteralIndex();
450 451 452 453 454 455 456 457 458 459 460 461 462

  // Reporting errors.
  void ReportMessageAt(Scanner::Location location,
                       const char* message,
                       Vector<const char*> args);
  void ReportMessageAt(Scanner::Location location,
                       const char* type,
                       const char* name_opt);
  void ReportMessageAt(int start_pos,
                       int end_pos,
                       const char* type,
                       const char* name_opt);

463
  // "null" return type creators.
464 465 466
  static IdentifierType EmptyIdentifier() {
    return PreParserIdentifier::Default();
  }
467 468 469
  static ExpressionType EmptyExpression() {
    return PreParserExpression::Default();
  }
470

471
  // Producing data during the recursive descent.
472
  IdentifierType GetSymbol();
473 474 475 476 477 478 479 480 481
  static IdentifierType NextLiteralString(PretenureFlag tenured) {
    return PreParserIdentifier::Default();
  }
  ExpressionType NewRegExpLiteral(IdentifierType js_pattern,
                                  IdentifierType js_flags,
                                  int literal_index,
                                  int pos) {
    return PreParserExpression::Default();
  }
482 483 484 485 486 487

 private:
  PreParser* pre_parser_;
};


488 489
// Preparsing checks a JavaScript program and emits preparse-data that helps
// a later parsing to be faster.
490
// See preparse-data-format.h for the data format.
491 492 493 494 495 496 497 498 499

// 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.
500
class PreParser : public ParserBase<PreParserTraits> {
501
 public:
502 503 504
  typedef PreParserIdentifier Identifier;
  typedef PreParserExpression Expression;

505 506 507 508 509
  enum PreParseResult {
    kPreParseStackOverflow,
    kPreParseSuccess
  };

510 511
  PreParser(Scanner* scanner,
            ParserRecorder* log,
512
            uintptr_t stack_limit)
513
      : ParserBase<PreParserTraits>(scanner, stack_limit, this),
514
        log_(log),
515
        function_state_(NULL),
516
        scope_(NULL) { }
517

518
  ~PreParser() {}
519 520 521 522 523

  // Pre-parse the program from the character stream; returns true on
  // success (even if parsing failed, the pre-parse data successfully
  // captured the syntax error), and false if a stack-overflow happened
  // during parsing.
524
  PreParseResult PreParseProgram() {
525
    FunctionState top_scope(&function_state_, &scope_, GLOBAL_SCOPE);
526
    bool ok = true;
527
    int start_position = scanner()->peek_location().beg_pos;
528
    ParseSourceElements(Token::EOS, &ok);
529
    if (stack_overflow()) return kPreParseStackOverflow;
530
    if (!ok) {
531
      ReportUnexpectedToken(scanner()->current_token());
532
    } else if (!scope_->is_classic_mode()) {
533
      CheckOctalLiteral(start_position, scanner()->location().end_pos, &ok);
534 535
    }
    return kPreParseSuccess;
536 537
  }

538 539
  // Parses a single function literal, from the opening parentheses before
  // parameters to the closing brace after the body.
540
  // Returns a FunctionEntry describing the body of the function in enough
541
  // detail that it can be lazily compiled.
542 543
  // The scanner is expected to have matched the "function" or "function*"
  // keyword and parameters, and have consumed the initial '{'.
544
  // At return, unless an error occurred, the scanner is positioned before the
545
  // the final '}'.
546
  PreParseResult PreParseLazyFunction(LanguageMode mode,
547
                                      bool is_generator,
548
                                      ParserRecorder* log);
549

550
 private:
551 552
  friend class PreParserTraits;

553 554 555 556 557
  // These types form an algebra over syntactic categories that is just
  // rich enough to let us recognize and propagate the constructs that
  // are either being counted in the preparser data, or is important
  // to throw the correct syntax error exceptions.

558 559 560 561 562 563
  enum VariableDeclarationContext {
    kSourceElement,
    kStatement,
    kForStatement
  };

564 565 566 567 568 569
  // If a list of variable declarations includes any initializers.
  enum VariableDeclarationProperties {
    kHasInitializers,
    kHasNoInitializers
  };

570 571 572 573 574 575
  class Statement {
   public:
    static Statement Default() {
      return Statement(kUnknownStatement);
    }

576 577 578 579
    static Statement FunctionDeclaration() {
      return Statement(kFunctionDeclaration);
    }

580 581 582 583
    // Creates expression statement from expression.
    // Preserves being an unparenthesized string literal, possibly
    // "use strict".
    static Statement ExpressionStatement(Expression expression) {
584 585 586 587 588
      if (expression.IsUseStrictLiteral()) {
        return Statement(kUseStrictExpressionStatement);
      }
      if (expression.IsStringLiteral()) {
        return Statement(kStringLiteralExpressionStatement);
589 590 591 592 593
      }
      return Default();
    }

    bool IsStringLiteral() {
594
      return code_ == kStringLiteralExpressionStatement;
595 596 597 598 599 600
    }

    bool IsUseStrictLiteral() {
      return code_ == kUseStrictExpressionStatement;
    }

601 602 603 604
    bool IsFunctionDeclaration() {
      return code_ == kFunctionDeclaration;
    }

605 606 607 608
   private:
    enum Type {
      kUnknownStatement,
      kStringLiteralExpressionStatement,
609 610
      kUseStrictExpressionStatement,
      kFunctionDeclaration
611 612 613 614
    };

    explicit Statement(Type code) : code_(code) {}
    Type code_;
615 616
  };

617 618
  enum SourceElements {
    kUnknownSourceElements
619 620 621 622
  };

  typedef int Arguments;

623 624
  class Scope {
   public:
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    explicit Scope(Scope* outer_scope, ScopeType scope_type)
        : scope_type_(scope_type) {
      if (outer_scope) {
        scope_inside_with_ =
            outer_scope->scope_inside_with_ || is_with_scope();
        language_mode_ = outer_scope->language_mode();
      } else {
        scope_inside_with_ = is_with_scope();
        language_mode_ = CLASSIC_MODE;
      }
    }

    bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
    bool is_classic_mode() const {
      return language_mode() == CLASSIC_MODE;
    }
    bool is_extended_mode() {
      return language_mode() == EXTENDED_MODE;
    }
    bool inside_with() const {
      return scope_inside_with_;
    }

    ScopeType type() { return scope_type_; }
    LanguageMode language_mode() const { return language_mode_; }
    void SetLanguageMode(LanguageMode language_mode) {
      language_mode_ = language_mode;
    }

   private:
    ScopeType scope_type_;
    bool scope_inside_with_;
    LanguageMode language_mode_;
  };

  class FunctionState {
   public:
    FunctionState(FunctionState** function_state_stack, Scope** scope_stack,
                  ScopeType scope_type)
        : function_state_stack_(function_state_stack),
          outer_function_state_(*function_state_stack),
          scope_stack_(scope_stack),
          outer_scope_(*scope_stack),
          scope_(*scope_stack, scope_type),
669 670
          materialized_literal_count_(0),
          expected_properties_(0),
671
          is_generator_(false) {
672 673 674 675 676 677
      *scope_stack = &scope_;
      *function_state_stack = this;
    }
    ~FunctionState() {
      *scope_stack_ = outer_scope_;
      *function_state_stack_ = outer_function_state_;
678
    }
679
    int NextMaterializedLiteralIndex() { return materialized_literal_count_++; }
680 681 682
    void AddProperty() { expected_properties_++; }
    int expected_properties() { return expected_properties_; }
    int materialized_literal_count() { return materialized_literal_count_; }
683 684
    bool is_generator() { return is_generator_; }
    void set_is_generator(bool is_generator) { is_generator_ = is_generator; }
685 686

   private:
687 688 689 690 691 692
    FunctionState** const function_state_stack_;
    FunctionState* const outer_function_state_;
    Scope** const scope_stack_;
    Scope* const outer_scope_;
    Scope scope_;

693 694
    int materialized_literal_count_;
    int expected_properties_;
695
    LanguageMode language_mode_;
696
    bool is_generator_;
697 698
  };

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
  class BlockState {
   public:
    BlockState(Scope** scope_stack, ScopeType scope_type)
        : scope_stack_(scope_stack),
          outer_scope_(*scope_stack),
          scope_(*scope_stack, scope_type) {
      *scope_stack_ = &scope_;
    }

    ~BlockState() { *scope_stack_ = outer_scope_; }

   private:
    Scope** scope_stack_;
    Scope* outer_scope_;
    Scope scope_;
  };

716 717 718 719
  // All ParseXXX functions take as the last argument an *ok parameter
  // which is set to false if parsing failed; it is unchanged otherwise.
  // By making the 'exception handling' explicit, we are forced to check
  // for failure at the call sites.
720
  Statement ParseSourceElement(bool* ok);
721 722 723 724
  SourceElements ParseSourceElements(int end_token, bool* ok);
  Statement ParseStatement(bool* ok);
  Statement ParseFunctionDeclaration(bool* ok);
  Statement ParseBlock(bool* ok);
725 726 727
  Statement ParseVariableStatement(VariableDeclarationContext var_context,
                                   bool* ok);
  Statement ParseVariableDeclarations(VariableDeclarationContext var_context,
728
                                      VariableDeclarationProperties* decl_props,
729 730
                                      int* num_decl,
                                      bool* ok);
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
  Statement ParseExpressionOrLabelledStatement(bool* ok);
  Statement ParseIfStatement(bool* ok);
  Statement ParseContinueStatement(bool* ok);
  Statement ParseBreakStatement(bool* ok);
  Statement ParseReturnStatement(bool* ok);
  Statement ParseWithStatement(bool* ok);
  Statement ParseSwitchStatement(bool* ok);
  Statement ParseDoWhileStatement(bool* ok);
  Statement ParseWhileStatement(bool* ok);
  Statement ParseForStatement(bool* ok);
  Statement ParseThrowStatement(bool* ok);
  Statement ParseTryStatement(bool* ok);
  Statement ParseDebuggerStatement(bool* ok);

  Expression ParseExpression(bool accept_IN, bool* ok);
  Expression ParseAssignmentExpression(bool accept_IN, bool* ok);
747
  Expression ParseYieldExpression(bool* ok);
748 749 750 751 752 753 754
  Expression ParseConditionalExpression(bool accept_IN, bool* ok);
  Expression ParseBinaryExpression(int prec, bool accept_IN, bool* ok);
  Expression ParseUnaryExpression(bool* ok);
  Expression ParsePostfixExpression(bool* ok);
  Expression ParseLeftHandSideExpression(bool* ok);
  Expression ParseNewExpression(bool* ok);
  Expression ParseMemberExpression(bool* ok);
755
  Expression ParseMemberWithNewPrefixesExpression(unsigned new_count, bool* ok);
756 757 758 759 760 761
  Expression ParsePrimaryExpression(bool* ok);
  Expression ParseArrayLiteral(bool* ok);
  Expression ParseObjectLiteral(bool* ok);
  Expression ParseV8Intrinsic(bool* ok);

  Arguments ParseArguments(bool* ok);
762 763 764 765 766 767
  Expression ParseFunctionLiteral(
      Identifier name,
      Scanner::Location function_name_location,
      bool name_is_strict_reserved,
      bool is_generator,
      bool* ok);
768
  void ParseLazyFunctionLiteralBody(bool* ok);
769

770 771 772
  // Logs the currently parsed literal as a symbol in the preparser data.
  void LogSymbol();
  // Log the currently parsed string literal.
773 774
  Expression GetStringSymbol();

775
  bool CheckInOrOf(bool accept_OF);
776

777
  ParserRecorder* log_;
778
  FunctionState* function_state_;
779 780
  Scope* scope_;
};
781

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

template<class Traits>
void ParserBase<Traits>::ReportUnexpectedToken(Token::Value token) {
  // We don't report stack overflows here, to avoid increasing the
  // stack depth even further.  Instead we report it after parsing is
  // over, in ParseProgram.
  if (token == Token::ILLEGAL && stack_overflow()) {
    return;
  }
  Scanner::Location source_location = scanner()->location();

  // Four of the tokens are treated specially
  switch (token) {
    case Token::EOS:
      return ReportMessageAt(source_location, "unexpected_eos");
    case Token::NUMBER:
      return ReportMessageAt(source_location, "unexpected_token_number");
    case Token::STRING:
      return ReportMessageAt(source_location, "unexpected_token_string");
    case Token::IDENTIFIER:
      return ReportMessageAt(source_location, "unexpected_token_identifier");
    case Token::FUTURE_RESERVED_WORD:
      return ReportMessageAt(source_location, "unexpected_reserved");
    case Token::YIELD:
    case Token::FUTURE_STRICT_RESERVED_WORD:
      return ReportMessageAt(
          source_location,
          this->is_classic_mode() ? "unexpected_token_identifier"
                                  : "unexpected_strict_reserved");
    default:
      const char* name = Token::String(token);
      ASSERT(name != NULL);
      Traits::ReportMessageAt(
          source_location, "unexpected_token", Vector<const char*>(&name, 1));
  }
}


template<class Traits>
typename Traits::IdentifierType ParserBase<Traits>::ParseIdentifier(
    AllowEvalOrArgumentsAsIdentifier allow_eval_or_arguments,
    bool* ok) {
  Token::Value next = Next();
  if (next == Token::IDENTIFIER) {
    typename Traits::IdentifierType name = this->GetSymbol();
    if (allow_eval_or_arguments == kDontAllowEvalOrArguments &&
        !this->is_classic_mode() && this->IsEvalOrArguments(name)) {
      ReportMessageAt(scanner()->location(), "strict_eval_arguments");
      *ok = false;
    }
    return name;
  } else if (this->is_classic_mode() &&
             (next == Token::FUTURE_STRICT_RESERVED_WORD ||
              (next == Token::YIELD && !this->is_generator()))) {
    return this->GetSymbol();
  } else {
    this->ReportUnexpectedToken(next);
    *ok = false;
    return Traits::EmptyIdentifier();
  }
}


template <class Traits>
typename Traits::IdentifierType ParserBase<
    Traits>::ParseIdentifierOrStrictReservedWord(bool* is_strict_reserved,
                                                 bool* ok) {
  Token::Value next = Next();
  if (next == Token::IDENTIFIER) {
    *is_strict_reserved = false;
  } else if (next == Token::FUTURE_STRICT_RESERVED_WORD ||
             (next == Token::YIELD && !this->is_generator())) {
    *is_strict_reserved = true;
  } else {
    ReportUnexpectedToken(next);
    *ok = false;
    return Traits::EmptyIdentifier();
  }
  return this->GetSymbol();
}


template <class Traits>
typename Traits::IdentifierType ParserBase<Traits>::ParseIdentifierName(
    bool* ok) {
  Token::Value next = Next();
  if (next != Token::IDENTIFIER && next != Token::FUTURE_RESERVED_WORD &&
      next != Token::FUTURE_STRICT_RESERVED_WORD && !Token::IsKeyword(next)) {
    this->ReportUnexpectedToken(next);
    *ok = false;
    return Traits::EmptyIdentifier();
  }
  return this->GetSymbol();
}


template <class Traits>
typename Traits::IdentifierType
ParserBase<Traits>::ParseIdentifierNameOrGetOrSet(bool* is_get,
                                                  bool* is_set,
                                                  bool* ok) {
  typename Traits::IdentifierType result = ParseIdentifierName(ok);
  if (!*ok) return Traits::EmptyIdentifier();
  if (scanner()->is_literal_ascii() &&
      scanner()->literal_length() == 3) {
    const char* token = scanner()->literal_ascii_string().start();
    *is_get = strncmp(token, "get", 3) == 0;
    *is_set = !*is_get && strncmp(token, "set", 3) == 0;
  }
  return result;
}


895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
template <class Traits>
typename Traits::ExpressionType
ParserBase<Traits>::ParseRegExpLiteral(bool seen_equal, bool* ok) {
  int pos = peek_position();
  if (!scanner()->ScanRegExpPattern(seen_equal)) {
    Next();
    ReportMessage("unterminated_regexp", Vector<const char*>::empty());
    *ok = false;
    return Traits::EmptyExpression();
  }

  int literal_index = this->NextMaterializedLiteralIndex();

  typename Traits::IdentifierType js_pattern = this->NextLiteralString(TENURED);
  if (!scanner()->ScanRegExpFlags()) {
    Next();
    ReportMessageAt(scanner()->location(), "invalid_regexp_flags");
    *ok = false;
    return Traits::EmptyExpression();
  }
  typename Traits::IdentifierType js_flags = this->NextLiteralString(TENURED);
  Next();
  return this->NewRegExpLiteral(js_pattern, js_flags, literal_index, pos);
}


921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
template <typename Traits>
void ParserBase<Traits>::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;
  }
}


956
} }  // v8::internal
957 958

#endif  // V8_PREPARSER_H