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

5 6
// Features shared by parsing and pre-parsing scanners.

7 8
#ifndef V8_PARSING_SCANNER_H_
#define V8_PARSING_SCANNER_H_
9

10 11
#include <algorithm>

12
#include "src/allocation.h"
13
#include "src/base/logging.h"
14 15
#include "src/char-predicates.h"
#include "src/globals.h"
16
#include "src/messages.h"
17
#include "src/parsing/token.h"
18
#include "src/unicode-decoder.h"
lpy's avatar
lpy committed
19
#include "src/unicode.h"
20

21 22
namespace v8 {
namespace internal {
23

24

25 26
class AstRawString;
class AstValueFactory;
27
class DuplicateFinder;
28 29
class ExternalOneByteString;
class ExternalTwoByteString;
30
class ParserRecorder;
31
class UnicodeCache;
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
// ---------------------------------------------------------------------
// Buffered stream of UTF-16 code units, using an internal UTF-16 buffer.
// A code unit is a 16 bit value representing either a 16 bit code point
// or one part of a surrogate pair that make a single 21 bit code point.
class Utf16CharacterStream {
 public:
  static const uc32 kEndOfInput = -1;

  virtual ~Utf16CharacterStream() {}

  inline uc32 Peek() {
    if (V8_LIKELY(buffer_cursor_ < buffer_end_)) {
      return static_cast<uc32>(*buffer_cursor_);
    } else if (ReadBlockChecked()) {
      return static_cast<uc32>(*buffer_cursor_);
    } else {
      return kEndOfInput;
    }
  }

  // Returns and advances past the next UTF-16 code unit in the input
  // stream. If there are no more code units it returns kEndOfInput.
  inline uc32 Advance() {
    uc32 result = Peek();
    buffer_cursor_++;
    return result;
  }

  // Returns and advances past the next UTF-16 code unit in the input stream
  // that meets the checks requirement. If there are no more code units it
  // returns kEndOfInput.
  template <typename FunctionType>
  V8_INLINE uc32 AdvanceUntil(FunctionType check) {
    while (true) {
      auto next_cursor_pos =
          std::find_if(buffer_cursor_, buffer_end_, [&check](uint16_t raw_c0_) {
            uc32 c0_ = static_cast<uc32>(raw_c0_);
            return check(c0_);
          });

      if (next_cursor_pos == buffer_end_) {
        buffer_cursor_ = buffer_end_;
        if (!ReadBlockChecked()) {
          buffer_cursor_++;
          return kEndOfInput;
        }
      } else {
        buffer_cursor_ = next_cursor_pos + 1;
        return static_cast<uc32>(*next_cursor_pos);
      }
    }
  }

  // Go back one by one character in the input stream.
  // This undoes the most recent Advance().
  inline void Back() {
    // The common case - if the previous character is within
    // buffer_start_ .. buffer_end_ will be handles locally.
    // Otherwise, a new block is requested.
    if (V8_LIKELY(buffer_cursor_ > buffer_start_)) {
      buffer_cursor_--;
    } else {
      ReadBlockAt(pos() - 1);
    }
  }

  inline size_t pos() const {
    return buffer_pos_ + (buffer_cursor_ - buffer_start_);
  }

  inline void Seek(size_t pos) {
    if (V8_LIKELY(pos >= buffer_pos_ &&
                  pos < (buffer_pos_ + (buffer_end_ - buffer_start_)))) {
      buffer_cursor_ = buffer_start_ + (pos - buffer_pos_);
    } else {
      ReadBlockAt(pos);
    }
  }

112 113 114 115 116 117 118 119
  // Returns true if the stream can be cloned with Clone.
  // TODO(rmcilroy): Remove this once ChunkedStreams can be cloned.
  virtual bool can_be_cloned() const = 0;

  // Clones the character stream to enable another independent scanner to access
  // the same underlying stream.
  virtual std::unique_ptr<Utf16CharacterStream> Clone() const = 0;

120
  // Returns true if the stream could access the V8 heap after construction.
121
  virtual bool can_access_heap() const = 0;
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 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

 protected:
  Utf16CharacterStream(const uint16_t* buffer_start,
                       const uint16_t* buffer_cursor,
                       const uint16_t* buffer_end, size_t buffer_pos)
      : buffer_start_(buffer_start),
        buffer_cursor_(buffer_cursor),
        buffer_end_(buffer_end),
        buffer_pos_(buffer_pos) {}
  Utf16CharacterStream() : Utf16CharacterStream(nullptr, nullptr, nullptr, 0) {}

  bool ReadBlockChecked() {
    size_t position = pos();
    USE(position);
    bool success = ReadBlock();

    // Post-conditions: 1, We should always be at the right position.
    //                  2, Cursor should be inside the buffer.
    //                  3, We should have more characters available iff success.
    DCHECK_EQ(pos(), position);
    DCHECK_LE(buffer_cursor_, buffer_end_);
    DCHECK_LE(buffer_start_, buffer_cursor_);
    DCHECK_EQ(success, buffer_cursor_ < buffer_end_);
    return success;
  }

  void ReadBlockAt(size_t new_pos) {
    // The callers of this method (Back/Back2/Seek) should handle the easy
    // case (seeking within the current buffer), and we should only get here
    // if we actually require new data.
    // (This is really an efficiency check, not a correctness invariant.)
    DCHECK(new_pos < buffer_pos_ ||
           new_pos >= buffer_pos_ + (buffer_end_ - buffer_start_));

    // Change pos() to point to new_pos.
    buffer_pos_ = new_pos;
    buffer_cursor_ = buffer_start_;
    DCHECK_EQ(pos(), new_pos);
    ReadBlockChecked();
  }

  // Read more data, and update buffer_*_ to point to it.
  // Returns true if more data was available.
  //
  // ReadBlock() may modify any of the buffer_*_ members, but must sure that
  // the result of pos() remains unaffected.
  //
  // Examples:
  // - a stream could either fill a separate buffer. Then buffer_start_ and
  //   buffer_cursor_ would point to the beginning of the buffer, and
  //   buffer_pos would be the old pos().
  // - a stream with existing buffer chunks would set buffer_start_ and
  //   buffer_end_ to cover the full chunk, and then buffer_cursor_ would
  //   point into the middle of the buffer, while buffer_pos_ would describe
  //   the start of the buffer.
  virtual bool ReadBlock() = 0;

  const uint16_t* buffer_start_;
  const uint16_t* buffer_cursor_;
  const uint16_t* buffer_end_;
  size_t buffer_pos_;
};

185
// ----------------------------------------------------------------------------
186
// JavaScript Scanner.
187 188

class Scanner {
189
 public:
190 191 192
  // Scoped helper for a re-settable bookmark.
  class BookmarkScope {
   public:
193 194
    explicit BookmarkScope(Scanner* scanner)
        : scanner_(scanner), bookmark_(kNoBookmark) {
195 196
      DCHECK_NOT_NULL(scanner_);
    }
197
    ~BookmarkScope() {}
198

199 200
    void Set();
    void Apply();
201 202
    bool HasBeenSet() const;
    bool HasBeenApplied() const;
203 204

   private:
205 206 207 208
    static const size_t kNoBookmark;
    static const size_t kBookmarkWasApplied;
    static const size_t kBookmarkAtFirstPos;

209
    Scanner* scanner_;
210
    size_t bookmark_;
211 212 213 214

    DISALLOW_COPY_AND_ASSIGN(BookmarkScope);
  };

215
  // Representation of an interval of source positions.
216 217 218 219 220 221 222 223 224 225 226 227 228 229
  struct Location {
    Location(int b, int e) : beg_pos(b), end_pos(e) { }
    Location() : beg_pos(0), end_pos(0) { }

    bool IsValid() const {
      return beg_pos >= 0 && end_pos >= beg_pos;
    }

    static Location invalid() { return Location(-1, -1); }

    int beg_pos;
    int end_pos;
  };

230 231
  // -1 is outside of the range of any real source code.
  static const int kNoOctalLocation = -1;
232
  static const uc32 kEndOfInput = Utf16CharacterStream::kEndOfInput;
233

234 235
  explicit Scanner(UnicodeCache* scanner_contants, Utf16CharacterStream* source,
                   bool is_module);
236

237
  void Initialize();
238 239

  // Returns the next token and advances input.
240
  Token::Value Next();
littledan's avatar
littledan committed
241
  // Returns the token following peek()
242
  Token::Value PeekAhead();
243
  // Returns the current token again.
244
  Token::Value current_token() const { return current().token; }
245

246 247 248 249
  Token::Value current_contextual_token() const {
    return current().contextual_token;
  }
  Token::Value next_contextual_token() const { return next().contextual_token; }
250

251
  // Returns the location information for the current token
252
  // (the token last returned by Next()).
253
  const Location& location() const { return current().location; }
254

255
  // This error is specifically an invalid hex or unicode escape sequence.
256 257
  bool has_error() const { return scanner_error_ != MessageTemplate::kNone; }
  MessageTemplate::Template error() const { return scanner_error_; }
258
  const Location& error_location() const { return scanner_error_location_; }
259

260
  bool has_invalid_template_escape() const {
261
    return current().invalid_template_escape_message != MessageTemplate::kNone;
262 263
  }
  MessageTemplate::Template invalid_template_escape_message() const {
264
    DCHECK(has_invalid_template_escape());
265
    return current().invalid_template_escape_message;
266 267 268
  }
  Location invalid_template_escape_location() const {
    DCHECK(has_invalid_template_escape());
269
    return current().invalid_template_escape_location;
270 271
  }

272 273 274
  // Similar functions for the upcoming token.

  // One token look-ahead (past the token returned by Next()).
275
  Token::Value peek() const { return next().token; }
276

277
  const Location& peek_location() const { return next().location; }
278 279

  bool literal_contains_escapes() const {
280
    return LiteralContainsEscapes(current());
281
  }
282

283
  const AstRawString* CurrentSymbol(AstValueFactory* ast_value_factory) const;
284

285 286 287
  const AstRawString* NextSymbol(AstValueFactory* ast_value_factory) const;
  const AstRawString* CurrentRawSymbol(
      AstValueFactory* ast_value_factory) const;
288 289

  double DoubleValue();
290

291 292
  const char* CurrentLiteralAsCString(Zone* zone) const;

293 294
  inline bool CurrentMatches(Token::Value token) const {
    DCHECK(Token::IsKeyword(token));
295
    return current().token == token;
296
  }
297 298 299

  inline bool CurrentMatchesContextual(Token::Value token) const {
    DCHECK(Token::IsContextualKeyword(token));
300
    return current_contextual_token() == token;
301 302
  }

303 304 305 306 307 308
  // Match the token against the contextual keyword or literal buffer.
  inline bool CurrentMatchesContextualEscaped(Token::Value token) const {
    DCHECK(Token::IsContextualKeyword(token) || token == Token::LET);
    // Escaped keywords are not matched as tokens. So if we require escape
    // and/or string processing we need to look at the literal content
    // (which was escape-processed already).
309 310
    // Conveniently, !current().literal_chars.is_used() for all proper
    // keywords, so this second condition should exit early in common cases.
311
    return (current_contextual_token() == token) ||
312 313
           (current().literal_chars.is_used() &&
            current().literal_chars.Equals(Vector<const char>(
314 315 316 317
                Token::String(token), Token::StringLength(token))));
  }

  bool IsUseStrict() const {
318 319
    return current().token == Token::STRING &&
           current().literal_chars.Equals(
320 321
               Vector<const char>("use strict", strlen("use strict")));
  }
322

323 324 325
  bool IsGet() { return CurrentMatchesContextual(Token::GET); }

  bool IsSet() { return CurrentMatchesContextual(Token::SET); }
326

327 328 329
  bool IsLet() const {
    return CurrentMatches(Token::LET) ||
           CurrentMatchesContextualEscaped(Token::LET);
330 331
  }

332 333 334 335 336
  // Check whether the CurrentSymbol() has already been seen.
  // The DuplicateFinder holds the data, so different instances can be used
  // for different sets of duplicates to check for.
  bool IsDuplicateSymbol(DuplicateFinder* duplicate_finder,
                         AstValueFactory* ast_value_factory) const;
337

338
  UnicodeCache* unicode_cache() const { return unicode_cache_; }
339 340 341

  // Returns the location of the last seen octal literal.
  Location octal_position() const { return octal_pos_; }
342 343 344 345 346
  void clear_octal_position() {
    octal_pos_ = Location::invalid();
    octal_message_ = MessageTemplate::kNone;
  }
  MessageTemplate::Template octal_message() const { return octal_message_; }
347

verwaest's avatar
verwaest committed
348
  // Returns the value of the last smi that was scanned.
349
  uint32_t smi_value() const { return current().smi_value_; }
verwaest's avatar
verwaest committed
350

351 352 353 354 355 356 357 358
  // Seek forward to the given position.  This operation does not
  // work in general, for instance when there are pushed back
  // characters, but works for seeking forward until simple delimiter
  // tokens, which is what it is used for.
  void SeekForward(int pos);

  // Returns true if there was a line terminator before the peek'ed token,
  // possibly inside a multi-line comment.
359 360
  bool HasLineTerminatorBeforeNext() const {
    return next().after_line_terminator;
361 362
  }

363
  bool HasLineTerminatorAfterNext() {
364 365
    Token::Value ensure_next_next = PeekAhead();
    USE(ensure_next_next);
366
    return next_next().after_line_terminator;
367 368
  }

369 370
  // Scans the input as a regular expression pattern, next token must be /(=).
  // Returns true if a pattern is scanned.
371
  bool ScanRegExpPattern();
372
  // Scans the input as regular expression flags. Returns the flags on success.
373
  Maybe<RegExp::Flags> ScanRegExpFlags();
374

375
  // Scans the input as a template literal
376
  Token::Value ScanTemplateContinuation() {
377
    DCHECK_EQ(next().token, Token::RBRACE);
378
    DCHECK_EQ(source_pos() - 1, next().location.beg_pos);
379
    return ScanTemplateSpan();
380
  }
381

382 383
  Handle<String> SourceUrl(Isolate* isolate) const;
  Handle<String> SourceMappingUrl(Isolate* isolate) const;
384

385 386
  bool FoundHtmlComment() const { return found_html_comment_; }

387 388
  bool allow_harmony_bigint() const { return allow_harmony_bigint_; }
  void set_allow_harmony_bigint(bool allow) { allow_harmony_bigint_ = allow; }
389 390 391 392 393 394
  bool allow_harmony_private_fields() const {
    return allow_harmony_private_fields_;
  }
  void set_allow_harmony_private_fields(bool allow) {
    allow_harmony_private_fields_ = allow;
  }
395 396 397 398 399 400
  bool allow_harmony_numeric_separator() const {
    return allow_harmony_numeric_separator_;
  }
  void set_allow_harmony_numeric_separator(bool allow) {
    allow_harmony_numeric_separator_ = allow;
  }
401

402 403
  const Utf16CharacterStream* stream() const { return source_; }

404
 private:
405 406 407 408 409
  // Scoped helper for saving & restoring scanner error state.
  // This is used for tagged template literals, in which normally forbidden
  // escape sequences are allowed.
  class ErrorState;

410 411 412
  // LiteralBuffer -  Collector of chars of literals.
  class LiteralBuffer {
   public:
413
    LiteralBuffer()
414
        : backing_store_(), position_(0), is_one_byte_(true), is_used_(false) {}
415 416 417

    ~LiteralBuffer() { backing_store_.Dispose(); }

418
    V8_INLINE void AddChar(char code_unit) {
419
      DCHECK(is_used_);
420
      DCHECK(IsValidAscii(code_unit));
421
      AddOneByteChar(static_cast<byte>(code_unit));
422 423
    }

424
    V8_INLINE void AddChar(uc32 code_unit) {
425
      DCHECK(is_used_);
426 427 428 429 430 431
      if (is_one_byte_) {
        if (code_unit <= static_cast<uc32>(unibrow::Latin1::kMaxChar)) {
          AddOneByteChar(static_cast<byte>(code_unit));
          return;
        }
        ConvertToTwoByte();
432
      }
433
      AddTwoByteChar(code_unit);
434 435 436 437
    }

    bool is_one_byte() const { return is_one_byte_; }

438
    bool Equals(Vector<const char> keyword) const {
439
      DCHECK(is_used_);
440 441 442 443 444 445
      return is_one_byte() && keyword.length() == position_ &&
             (memcmp(keyword.start(), backing_store_.start(), position_) == 0);
    }

    Vector<const uint16_t> two_byte_literal() const {
      DCHECK(!is_one_byte_);
446
      DCHECK(is_used_);
447
      DCHECK_EQ(position_ & 0x1, 0);
448 449 450 451 452 453 454
      return Vector<const uint16_t>(
          reinterpret_cast<const uint16_t*>(backing_store_.start()),
          position_ >> 1);
    }

    Vector<const uint8_t> one_byte_literal() const {
      DCHECK(is_one_byte_);
455
      DCHECK(is_used_);
456 457 458 459 460 461
      return Vector<const uint8_t>(
          reinterpret_cast<const uint8_t*>(backing_store_.start()), position_);
    }

    int length() const { return is_one_byte_ ? position_ : (position_ >> 1); }

462 463 464 465 466 467 468 469 470 471
    void Start() {
      DCHECK(!is_used_);
      DCHECK_EQ(0, position_);
      is_used_ = true;
    }

    bool is_used() const { return is_used_; }

    void Drop() {
      is_used_ = false;
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
      position_ = 0;
      is_one_byte_ = true;
    }

    Handle<String> Internalize(Isolate* isolate) const;

   private:
    static const int kInitialCapacity = 16;
    static const int kGrowthFactory = 4;
    static const int kMinConversionSlack = 256;
    static const int kMaxGrowth = 1 * MB;

    inline bool IsValidAscii(char code_unit) {
      // Control characters and printable characters span the range of
      // valid ASCII characters (0-127). Chars are unsigned on some
      // platforms which causes compiler warnings if the validity check
      // tests the lower bound >= 0 as it's always true.
      return iscntrl(code_unit) || isprint(code_unit);
    }

492
    V8_INLINE void AddOneByteChar(byte one_byte_char) {
493
      DCHECK(is_one_byte_);
494 495 496
      if (position_ >= backing_store_.length()) ExpandBuffer();
      backing_store_[position_] = one_byte_char;
      position_ += kOneByteSize;
497 498
    }

499
    void AddTwoByteChar(uc32 code_unit);
500 501 502 503
    int NewCapacity(int min_capacity);
    void ExpandBuffer();
    void ConvertToTwoByte();

504
    Vector<byte> backing_store_;
505
    int position_;
506 507
    bool is_one_byte_;
    bool is_used_;
508 509 510 511

    DISALLOW_COPY_AND_ASSIGN(LiteralBuffer);
  };

512 513 514 515 516
  // Scoped helper for literal recording. Automatically drops the literal
  // if aborting the scanning before it's complete.
  class LiteralScope {
   public:
    explicit LiteralScope(Scanner* scanner)
517
        : buffer_(&scanner->next().literal_chars), complete_(false) {
518 519 520 521 522 523 524 525 526 527 528 529
      buffer_->Start();
    }
    ~LiteralScope() {
      if (!complete_) buffer_->Drop();
    }
    void Complete() { complete_ = true; }

   private:
    LiteralBuffer* buffer_;
    bool complete_;
  };

530 531
  // The current and look-ahead token.
  struct TokenDesc {
532 533 534 535 536 537
    Location location = {0, 0};
    LiteralBuffer literal_chars;
    LiteralBuffer raw_literal_chars;
    Token::Value token = Token::UNINITIALIZED;
    MessageTemplate::Template invalid_template_escape_message =
        MessageTemplate::kNone;
538
    Location invalid_template_escape_location;
539 540 541
    Token::Value contextual_token = Token::UNINITIALIZED;
    uint32_t smi_value_ = 0;
    bool after_line_terminator = false;
542 543
  };

544 545 546 547 548 549 550 551 552
  enum NumberKind {
    BINARY,
    OCTAL,
    IMPLICIT_OCTAL,
    HEX,
    DECIMAL,
    DECIMAL_WITH_LEADING_ZERO
  };

553
  static const int kCharacterLookaheadBufferSize = 1;
554
  static const int kMaxAscii = 127;
555 556

  // Scans octal escape sequence. Also accepts "\0" decimal escape sequence.
557
  template <bool capture_raw>
558
  uc32 ScanOctalEscape(uc32 c, int length);
559

560 561 562 563 564
  // Call this after setting source_ to the input.
  void Init() {
    // Set c0_ (one character ahead)
    STATIC_ASSERT(kCharacterLookaheadBufferSize == 1);
    Advance();
565

566 567 568 569
    current_ = &token_storage_[0];
    next_ = &token_storage_[1];
    next_next_ = &token_storage_[2];

570 571 572
    found_html_comment_ = false;
    scanner_error_ = MessageTemplate::kNone;
  }
573

574 575 576 577 578 579 580 581 582 583 584 585 586
  void ReportScannerError(const Location& location,
                          MessageTemplate::Template error) {
    if (has_error()) return;
    scanner_error_ = error;
    scanner_error_location_ = location;
  }

  void ReportScannerError(int pos, MessageTemplate::Template error) {
    if (has_error()) return;
    scanner_error_ = error;
    scanner_error_location_ = Location(pos, pos + 1);
  }

587 588 589
  // Seek to the next_ token at the given position.
  void SeekNext(size_t position);

590 591 592
  V8_INLINE void AddLiteralChar(uc32 c) { next().literal_chars.AddChar(c); }

  V8_INLINE void AddLiteralChar(char c) { next().literal_chars.AddChar(c); }
593

594
  V8_INLINE void AddRawLiteralChar(uc32 c) {
595
    next().raw_literal_chars.AddChar(c);
596 597
  }

598
  V8_INLINE void AddLiteralCharAdvance() {
599
    AddLiteralChar(c0_);
600
    Advance();
601 602 603
  }

  // Low-level scanning support.
604
  template <bool capture_raw = false>
605
  void Advance() {
606 607 608 609
    if (capture_raw) {
      AddRawLiteralChar(c0_);
    }
    c0_ = source_->Advance();
610 611
  }

612
  template <typename FunctionType>
613
  V8_INLINE void AdvanceUntil(FunctionType check) {
614
    c0_ = source_->AdvanceUntil(check);
615 616
  }

617
  bool CombineSurrogatePair() {
618
    DCHECK(!unibrow::Utf16::IsLeadSurrogate(kEndOfInput));
619
    if (unibrow::Utf16::IsLeadSurrogate(c0_)) {
620
      uc32 c1 = source_->Advance();
621
      DCHECK(!unibrow::Utf16::IsTrailSurrogate(kEndOfInput));
622
      if (unibrow::Utf16::IsTrailSurrogate(c1)) {
623
        c0_ = unibrow::Utf16::CombineSurrogatePair(c0_, c1);
624
        return true;
625
      }
626
      source_->Back();
627
    }
628
    return false;
629 630
  }

631
  void PushBack(uc32 ch) {
632 633
    DCHECK_LE(c0_, static_cast<uc32>(unibrow::Utf16::kMaxNonSurrogateCharCode));
    source_->Back();
634 635 636
    c0_ = ch;
  }

637
  uc32 Peek() const { return source_->Peek(); }
638

639
  inline Token::Value Select(Token::Value tok) {
640
    Advance();
641 642 643 644
    return tok;
  }

  inline Token::Value Select(uc32 next, Token::Value then, Token::Value else_) {
645
    Advance();
646
    if (c0_ == next) {
647
      Advance();
648
      return then;
649 650
    } else {
      return else_;
651 652
    }
  }
653 654
  // Returns the literal string, if any, for the current token (the
  // token last returned by Next()). The string is 0-terminated.
655 656 657
  // Literal strings are collected for identifiers, strings, numbers as well
  // as for template literals. For template literals we also collect the raw
  // form.
658 659
  // These functions only give the correct result if the literal was scanned
  // when a LiteralScope object is alive.
660 661 662 663 664 665
  //
  // Current usage of these functions is unfortunately a little undisciplined,
  // and is_literal_one_byte() + is_literal_one_byte_string() is also
  // requested for tokens that do not have a literal. Hence, we treat any
  // token as a one-byte literal. E.g. Token::FUNCTION pretends to have a
  // literal "function".
666
  Vector<const uint8_t> literal_one_byte_string() const {
667 668 669
    if (current().literal_chars.is_used())
      return current().literal_chars.one_byte_literal();
    const char* str = Token::String(current().token);
670 671
    const uint8_t* str_as_uint8 = reinterpret_cast<const uint8_t*>(str);
    return Vector<const uint8_t>(str_as_uint8,
672
                                 Token::StringLength(current().token));
673
  }
674
  Vector<const uint16_t> literal_two_byte_string() const {
675 676
    DCHECK(current().literal_chars.is_used());
    return current().literal_chars.two_byte_literal();
677
  }
678
  bool is_literal_one_byte() const {
679 680
    return !current().literal_chars.is_used() ||
           current().literal_chars.is_one_byte();
681 682 683
  }
  // Returns the literal string for the next token (the token that
  // would be returned if Next() were called).
684
  Vector<const uint8_t> next_literal_one_byte_string() const {
685 686
    DCHECK(next().literal_chars.is_used());
    return next().literal_chars.one_byte_literal();
687
  }
688
  Vector<const uint16_t> next_literal_two_byte_string() const {
689 690
    DCHECK(next().literal_chars.is_used());
    return next().literal_chars.two_byte_literal();
691
  }
692
  bool is_next_literal_one_byte() const {
693 694
    DCHECK(next().literal_chars.is_used());
    return next().literal_chars.is_one_byte();
695
  }
696
  Vector<const uint8_t> raw_literal_one_byte_string() const {
697 698
    DCHECK(current().raw_literal_chars.is_used());
    return current().raw_literal_chars.one_byte_literal();
699
  }
700
  Vector<const uint16_t> raw_literal_two_byte_string() const {
701 702
    DCHECK(current().raw_literal_chars.is_used());
    return current().raw_literal_chars.two_byte_literal();
703
  }
704
  bool is_raw_literal_one_byte() const {
705 706
    DCHECK(current().raw_literal_chars.is_used());
    return current().raw_literal_chars.is_one_byte();
707 708
  }

709
  template <bool capture_raw, bool unicode = false>
710
  uc32 ScanHexNumber(int expected_length);
marja's avatar
marja committed
711 712 713
  // Scan a number of any length but not bigger than max_value. For example, the
  // number can be 000000001, so it's very long in characters but its value is
  // small.
714
  template <bool capture_raw>
715
  uc32 ScanUnlimitedLengthHexNumber(int max_value, int beg_pos);
716

717
  // Scans a single JavaScript token.
718
  V8_INLINE Token::Value ScanSingleToken();
719
  V8_INLINE void Scan();
720

721
  V8_INLINE Token::Value SkipWhiteSpace();
722
  Token::Value SkipSingleHTMLComment();
723
  Token::Value SkipSingleLineComment();
724 725
  Token::Value SkipSourceURLComment();
  void TryToParseSourceURLComment();
726
  Token::Value SkipMultiLineComment();
727 728
  // Scans a possible HTML comment -- begins with '<!'.
  Token::Value ScanHtmlComment();
729

730 731
  bool ScanDigitsWithNumericSeparators(bool (*predicate)(uc32 ch),
                                       bool is_check_first_digit);
732
  bool ScanDecimalDigits();
733
  // Optimized function to scan decimal number as Smi.
734 735 736 737 738 739
  bool ScanDecimalAsSmi(uint64_t* value);
  bool ScanDecimalAsSmiWithNumericSeparators(uint64_t* value);
  bool ScanHexDigits();
  bool ScanBinaryDigits();
  bool ScanSignedInteger();
  bool ScanOctalDigits();
740
  bool ScanImplicitOctalDigits(int start_pos, NumberKind* kind);
741

742
  Token::Value ScanNumber(bool seen_period);
743 744 745 746
  V8_INLINE Token::Value ScanIdentifierOrKeyword();
  V8_INLINE Token::Value ScanIdentifierOrKeywordInner(LiteralScope* literal);
  Token::Value ScanIdentifierOrKeywordInnerSlow(LiteralScope* literal,
                                                bool escaped);
747 748

  Token::Value ScanString();
749
  Token::Value ScanPrivateName();
750

751 752 753
  // Scans an escape-sequence which is part of a string and adds the
  // decoded character to the current literal. Returns true if a pattern
  // is scanned.
754
  template <bool capture_raw>
755
  bool ScanEscape();
756

757
  // Decodes a Unicode escape-sequence which is part of an identifier.
758 759
  // If the escape sequence cannot be decoded the result is kBadChar.
  uc32 ScanIdentifierUnicodeEscape();
marja's avatar
marja committed
760
  // Helper for the above functions.
761
  template <bool capture_raw>
marja's avatar
marja committed
762
  uc32 ScanUnicodeEscape();
763

764 765
  Token::Value ScanTemplateSpan();

766
  // Return the current source position.
767 768
  int source_pos() {
    return static_cast<int>(source_->pos()) - kCharacterLookaheadBufferSize;
769 770
  }

771 772 773 774 775 776 777
  static bool LiteralContainsEscapes(const TokenDesc& token) {
    Location location = token.location;
    int source_length = (location.end_pos - location.beg_pos);
    if (token.token == Token::STRING) {
      // Subtract delimiters.
      source_length -= 2;
    }
778 779
    return token.literal_chars.is_used() &&
           (token.literal_chars.length() != source_length);
780 781
  }

782 783 784 785
#ifdef DEBUG
  void SanityCheckTokenDesc(const TokenDesc&) const;
#endif

786
  UnicodeCache* const unicode_cache_;
787

788
  TokenDesc& next() { return *next_; }
789

790 791 792
  const TokenDesc& current() const { return *current_; }
  const TokenDesc& next() const { return *next_; }
  const TokenDesc& next_next() const { return *next_next_; }
793

794 795 796
  TokenDesc* current_;    // desc for current token (as returned by Next())
  TokenDesc* next_;       // desc for next token (one token look-ahead)
  TokenDesc* next_next_;  // desc for the token after next (after PeakAhead())
797

798
  // Input stream. Must be initialized to an Utf16CharacterStream.
799
  Utf16CharacterStream* const source_;
800 801 802 803

  // One Unicode character look-ahead; c0_ < 0 at the end of the input.
  uc32 c0_;

804 805
  TokenDesc token_storage_[3];

806 807
  // Whether this scanner encountered an HTML comment.
  bool found_html_comment_;
808

809
  // Harmony flags to allow ESNext features.
810
  bool allow_harmony_bigint_;
811
  bool allow_harmony_private_fields_;
812
  bool allow_harmony_numeric_separator_;
813

814 815
  const bool is_module_;

816 817 818 819 820 821 822 823
  // Values parsed from magic comments.
  LiteralBuffer source_url_;
  LiteralBuffer source_mapping_url_;

  // Last-seen positions of potentially problematic tokens.
  Location octal_pos_;
  MessageTemplate::Template octal_message_;

824 825
  MessageTemplate::Template scanner_error_;
  Location scanner_error_location_;
826 827
};

828 829
}  // namespace internal
}  // namespace v8
830

831
#endif  // V8_PARSING_SCANNER_H_