scanner.h 25.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
#include <algorithm>
11
#include <memory>
12

13
#include "src/base/logging.h"
14
#include "src/base/strings.h"
15
#include "src/common/globals.h"
16
#include "src/common/message-template.h"
17
#include "src/parsing/literal-buffer.h"
18
#include "src/parsing/parse-info.h"
19
#include "src/parsing/token.h"
20
#include "src/regexp/regexp-flags.h"
21 22
#include "src/strings/char-predicates.h"
#include "src/strings/unicode.h"
23
#include "src/utils/allocation.h"
24

25 26
namespace v8 {
namespace internal {
27

28 29
class AstRawString;
class AstValueFactory;
30 31
class ExternalOneByteString;
class ExternalTwoByteString;
32
class ParserRecorder;
33
class RuntimeCallStats;
34
class Zone;
35

36 37 38 39 40 41
// ---------------------------------------------------------------------
// 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:
42
  static constexpr base::uc32 kEndOfInput = static_cast<base::uc32>(-1);
43

44
  virtual ~Utf16CharacterStream() = default;
45

46
  V8_INLINE void set_parser_error() {
47 48 49
    buffer_cursor_ = buffer_end_;
    has_parser_error_ = true;
  }
50 51
  V8_INLINE void reset_parser_error_flag() { has_parser_error_ = false; }
  V8_INLINE bool has_parser_error() const { return has_parser_error_; }
52

53
  inline base::uc32 Peek() {
54
    if (V8_LIKELY(buffer_cursor_ < buffer_end_)) {
55
      return static_cast<base::uc32>(*buffer_cursor_);
56
    } else if (ReadBlockChecked(pos())) {
57
      return static_cast<base::uc32>(*buffer_cursor_);
58 59 60 61 62 63 64
    } 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.
65 66
  inline base::uc32 Advance() {
    base::uc32 result = Peek();
67 68 69 70 71 72 73 74
    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>
75
  V8_INLINE base::uc32 AdvanceUntil(FunctionType check) {
76
    while (true) {
77 78
      auto next_cursor_pos =
          std::find_if(buffer_cursor_, buffer_end_, [&check](uint16_t raw_c0_) {
79
            base::uc32 c0_ = static_cast<base::uc32>(raw_c0_);
80 81 82 83 84
            return check(c0_);
          });

      if (next_cursor_pos == buffer_end_) {
        buffer_cursor_ = buffer_end_;
85
        if (!ReadBlockChecked(pos())) {
86
          buffer_cursor_++;
87
          return kEndOfInput;
88
        }
89 90
      } else {
        buffer_cursor_ = next_cursor_pos + 1;
91
        return static_cast<base::uc32>(*next_cursor_pos);
92 93 94 95 96 97 98 99 100 101 102 103 104
      }
    }
  }

  // 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 {
105
      ReadBlockChecked(pos() - 1);
106 107 108 109 110 111 112 113 114 115 116 117
    }
  }

  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 {
118
      ReadBlockChecked(pos);
119 120 121
    }
  }

122 123 124 125 126
  // Returns true if the stream could access the V8 heap after construction.
  bool can_be_cloned_for_parallel_access() const {
    return can_be_cloned() && !can_access_heap();
  }

127 128 129 130 131 132 133 134
  // 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;

135
  // Returns true if the stream could access the V8 heap after construction.
136
  virtual bool can_access_heap() const = 0;
137

138 139 140 141 142
  RuntimeCallStats* runtime_call_stats() const { return runtime_call_stats_; }
  void set_runtime_call_stats(RuntimeCallStats* runtime_call_stats) {
    runtime_call_stats_ = runtime_call_stats;
  }

143 144 145 146 147 148 149 150 151 152
 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) {}

153 154 155 156 157 158 159 160 161
  bool ReadBlockChecked(size_t position) {
    // 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(position < buffer_pos_ ||
           position >= buffer_pos_ + (buffer_end_ - buffer_start_));

    bool success = !has_parser_error() && ReadBlock(position);
162 163 164 165 166 167 168 169 170 171 172 173 174 175

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

  // Read more data, and update buffer_*_ to point to it.
  // Returns true if more data was available.
  //
176 177
  // ReadBlock(position) may modify any of the buffer_*_ members, but must make
  // sure that the result of pos() becomes |position|.
178 179 180 181 182 183 184 185 186
  //
  // 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.
187
  virtual bool ReadBlock(size_t position) = 0;
188

189 190 191 192 193 194 195 196 197 198 199 200 201
  // Fields describing the location of the current buffer physically in memory,
  // and semantically within the source string.
  //
  //                  0              buffer_pos_   pos()
  //                  |                        |   |
  //                  v________________________v___v_____________
  //                  |                        |        |        |
  //   Source string: |                        | Buffer |        |
  //                  |________________________|________|________|
  //                                           ^   ^    ^
  //                                           |   |    |
  //                   Pointers:   buffer_start_   |    buffer_end_
  //                                         buffer_cursor_
202 203 204 205
  const uint16_t* buffer_start_;
  const uint16_t* buffer_cursor_;
  const uint16_t* buffer_end_;
  size_t buffer_pos_;
206
  RuntimeCallStats* runtime_call_stats_;
207
  bool has_parser_error_ = false;
208 209
};

210
// ----------------------------------------------------------------------------
211
// JavaScript Scanner.
212

213
class V8_EXPORT_PRIVATE Scanner {
214
 public:
215
  // Scoped helper for a re-settable bookmark.
216
  class V8_EXPORT_PRIVATE V8_NODISCARD BookmarkScope {
217
   public:
218
    explicit BookmarkScope(Scanner* scanner)
219 220
        : scanner_(scanner),
          bookmark_(kNoBookmark),
221
          had_parser_error_(scanner->has_parser_error()) {
222 223
      DCHECK_NOT_NULL(scanner_);
    }
224
    ~BookmarkScope() = default;
225 226
    BookmarkScope(const BookmarkScope&) = delete;
    BookmarkScope& operator=(const BookmarkScope&) = delete;
227

228
    void Set(size_t bookmark);
229
    void Apply();
230 231
    bool HasBeenSet() const;
    bool HasBeenApplied() const;
232 233

   private:
234 235 236
    static const size_t kNoBookmark;
    static const size_t kBookmarkWasApplied;

237
    Scanner* scanner_;
238
    size_t bookmark_;
239
    bool had_parser_error_;
240 241
  };

242 243
  // Sets the Scanner into an error state to stop further scanning and terminate
  // the parsing by only returning ILLEGAL tokens after that.
244
  V8_INLINE void set_parser_error() {
245
    if (!has_parser_error()) {
246 247
      c0_ = kEndOfInput;
      source_->set_parser_error();
248
      for (TokenDesc& desc : token_storage_) desc.token = Token::ILLEGAL;
249 250
    }
  }
251 252 253
  V8_INLINE void reset_parser_error_flag() {
    source_->reset_parser_error_flag();
  }
254
  V8_INLINE bool has_parser_error() const {
255 256
    return source_->has_parser_error();
  }
257

258
  // Representation of an interval of source positions.
259 260 261 262
  struct Location {
    Location(int b, int e) : beg_pos(b), end_pos(e) { }
    Location() : beg_pos(0), end_pos(0) { }

263
    int length() const { return end_pos - beg_pos; }
264
    bool IsValid() const { return base::IsInRange(beg_pos, 0, end_pos); }
265

266
    static Location invalid() { return Location(-1, 0); }
267 268 269 270 271

    int beg_pos;
    int end_pos;
  };

272
  // -1 is outside of the range of any real source code.
273 274
  static constexpr base::uc32 kEndOfInput = Utf16CharacterStream::kEndOfInput;
  static constexpr base::uc32 kInvalidSequence = static_cast<base::uc32>(-1);
275

276 277
  static constexpr base::uc32 Invalid() { return Scanner::kInvalidSequence; }
  static bool IsInvalid(base::uc32 c);
278

279
  explicit Scanner(Utf16CharacterStream* source, UnoptimizedCompileFlags flags);
280

281
  void Initialize();
282 283

  // Returns the next token and advances input.
284
  Token::Value Next();
littledan's avatar
littledan committed
285
  // Returns the token following peek()
286
  Token::Value PeekAhead();
287
  // Returns the current token again.
288
  Token::Value current_token() const { return current().token; }
289

290
  // Returns the location information for the current token
291
  // (the token last returned by Next()).
292
  const Location& location() const { return current().location; }
293

294
  // This error is specifically an invalid hex or unicode escape sequence.
295
  bool has_error() const { return scanner_error_ != MessageTemplate::kNone; }
296
  MessageTemplate error() const { return scanner_error_; }
297
  const Location& error_location() const { return scanner_error_location_; }
298

299
  bool has_invalid_template_escape() const {
300
    return current().invalid_template_escape_message != MessageTemplate::kNone;
301
  }
302
  MessageTemplate invalid_template_escape_message() const {
303
    DCHECK(has_invalid_template_escape());
304
    return current().invalid_template_escape_message;
305
  }
306 307 308 309 310 311

  void clear_invalid_template_escape_message() {
    DCHECK(has_invalid_template_escape());
    current_->invalid_template_escape_message = MessageTemplate::kNone;
  }

312 313
  Location invalid_template_escape_location() const {
    DCHECK(has_invalid_template_escape());
314
    return current().invalid_template_escape_location;
315 316
  }

317 318 319
  // Similar functions for the upcoming token.

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

322
  const Location& peek_location() const { return next().location; }
323 324

  bool literal_contains_escapes() const {
325
    return LiteralContainsEscapes(current());
326
  }
327

328 329 330 331
  bool next_literal_contains_escapes() const {
    return LiteralContainsEscapes(next());
  }

332
  const AstRawString* CurrentSymbol(AstValueFactory* ast_value_factory) const;
333

334 335 336
  const AstRawString* NextSymbol(AstValueFactory* ast_value_factory) const;
  const AstRawString* CurrentRawSymbol(
      AstValueFactory* ast_value_factory) const;
337 338

  double DoubleValue();
339

340 341
  const char* CurrentLiteralAsCString(Zone* zone) const;

342 343
  inline bool CurrentMatches(Token::Value token) const {
    DCHECK(Token::IsKeyword(token));
344
    return current().token == token;
345
  }
346

347
  template <size_t N>
348 349
  bool NextLiteralExactlyEquals(const char (&s)[N]) {
    DCHECK(next().CanAccessLiteral());
350 351 352 353 354 355
    // The length of the token is used to make sure the literal equals without
    // taking escape sequences (e.g., "use \x73trict") or line continuations
    // (e.g., "use \(newline) strict") into account.
    if (!is_next_literal_one_byte()) return false;
    if (peek_location().length() != N + 1) return false;

356
    base::Vector<const uint8_t> next = next_literal_one_byte_string();
357
    const char* chars = reinterpret_cast<const char*>(next.begin());
358 359 360
    return next.length() == N - 1 && strncmp(s, chars, N - 1) == 0;
  }

361 362 363 364 365
  template <size_t N>
  bool CurrentLiteralEquals(const char (&s)[N]) {
    DCHECK(current().CanAccessLiteral());
    if (!is_literal_one_byte()) return false;

366
    base::Vector<const uint8_t> current = literal_one_byte_string();
367
    const char* chars = reinterpret_cast<const char*>(current.begin());
368 369 370
    return current.length() == N - 1 && strncmp(s, chars, N - 1) == 0;
  }

371 372
  // Returns the location of the last seen octal literal.
  Location octal_position() const { return octal_pos_; }
373 374 375 376
  void clear_octal_position() {
    octal_pos_ = Location::invalid();
    octal_message_ = MessageTemplate::kNone;
  }
377
  MessageTemplate octal_message() const { return octal_message_; }
378

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

382 383 384 385 386 387 388 389
  // 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.
390 391
  bool HasLineTerminatorBeforeNext() const {
    return next().after_line_terminator;
392 393
  }

394
  bool HasLineTerminatorAfterNext() {
395 396
    Token::Value ensure_next_next = PeekAhead();
    USE(ensure_next_next);
397
    return next_next().after_line_terminator;
398 399
  }

400 401
  // Scans the input as a regular expression pattern, next token must be /(=).
  // Returns true if a pattern is scanned.
402
  bool ScanRegExpPattern();
403
  // Scans the input as regular expression flags. Returns the flags on success.
404
  base::Optional<RegExpFlags> ScanRegExpFlags();
405

406
  // Scans the input as a template literal
407
  Token::Value ScanTemplateContinuation() {
408
    DCHECK_EQ(next().token, Token::RBRACE);
409
    DCHECK_EQ(source_pos() - 1, next().location.beg_pos);
410
    return ScanTemplateSpan();
411
  }
412

413 414 415 416
  template <typename IsolateT>
  Handle<String> SourceUrl(IsolateT* isolate) const;
  template <typename IsolateT>
  Handle<String> SourceMappingUrl(IsolateT* isolate) const;
417

418 419
  bool FoundHtmlComment() const { return found_html_comment_; }

420 421
  const Utf16CharacterStream* stream() const { return source_; }

422
 private:
423 424 425 426 427
  // 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;

428 429
  // The current and look-ahead token.
  struct TokenDesc {
430 431 432 433
    Location location = {0, 0};
    LiteralBuffer literal_chars;
    LiteralBuffer raw_literal_chars;
    Token::Value token = Token::UNINITIALIZED;
434
    MessageTemplate invalid_template_escape_message = MessageTemplate::kNone;
435
    Location invalid_template_escape_location;
436 437
    uint32_t smi_value_ = 0;
    bool after_line_terminator = false;
438 439 440 441

#ifdef DEBUG
    bool CanAccessLiteral() const {
      return token == Token::PRIVATE_NAME || token == Token::ILLEGAL ||
442 443
             token == Token::ESCAPED_KEYWORD || token == Token::UNINITIALIZED ||
             token == Token::REGEXP_LITERAL ||
444
             base::IsInRange(token, Token::NUMBER, Token::STRING) ||
445
             Token::IsAnyIdentifier(token) || Token::IsKeyword(token) ||
446
             base::IsInRange(token, Token::TEMPLATE_SPAN, Token::TEMPLATE_TAIL);
447 448 449
    }
    bool CanAccessRawLiteral() const {
      return token == Token::ILLEGAL || token == Token::UNINITIALIZED ||
450
             base::IsInRange(token, Token::TEMPLATE_SPAN, Token::TEMPLATE_TAIL);
451 452
    }
#endif  // DEBUG
453 454
  };

455
  enum NumberKind {
456
    IMPLICIT_OCTAL,
457 458 459 460 461 462 463
    BINARY,
    OCTAL,
    HEX,
    DECIMAL,
    DECIMAL_WITH_LEADING_ZERO
  };

464
  inline bool IsValidBigIntKind(NumberKind kind) {
465
    return base::IsInRange(kind, BINARY, DECIMAL);
466 467 468
  }

  inline bool IsDecimalNumberKind(NumberKind kind) {
469
    return base::IsInRange(kind, DECIMAL, DECIMAL_WITH_LEADING_ZERO);
470 471
  }

472
  static const int kCharacterLookaheadBufferSize = 1;
473
  static const int kMaxAscii = 127;
474 475

  // Scans octal escape sequence. Also accepts "\0" decimal escape sequence.
476
  template <bool capture_raw>
477
  base::uc32 ScanOctalEscape(base::uc32 c, int length);
478

479 480 481 482 483
  // Call this after setting source_ to the input.
  void Init() {
    // Set c0_ (one character ahead)
    STATIC_ASSERT(kCharacterLookaheadBufferSize == 1);
    Advance();
484

485 486 487 488
    current_ = &token_storage_[0];
    next_ = &token_storage_[1];
    next_next_ = &token_storage_[2];

489 490 491
    found_html_comment_ = false;
    scanner_error_ = MessageTemplate::kNone;
  }
492

493
  void ReportScannerError(const Location& location, MessageTemplate error) {
494 495 496 497 498
    if (has_error()) return;
    scanner_error_ = error;
    scanner_error_location_ = location;
  }

499
  void ReportScannerError(int pos, MessageTemplate error) {
500 501 502 503 504
    if (has_error()) return;
    scanner_error_ = error;
    scanner_error_location_ = Location(pos, pos + 1);
  }

505 506 507
  // Seek to the next_ token at the given position.
  void SeekNext(size_t position);

508 509 510
  V8_INLINE void AddLiteralChar(base::uc32 c) {
    next().literal_chars.AddChar(c);
  }
511 512

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

514
  V8_INLINE void AddRawLiteralChar(base::uc32 c) {
515
    next().raw_literal_chars.AddChar(c);
516 517
  }

518
  V8_INLINE void AddLiteralCharAdvance() {
519
    AddLiteralChar(c0_);
520
    Advance();
521 522 523
  }

  // Low-level scanning support.
524
  template <bool capture_raw = false>
525
  void Advance() {
526 527 528 529
    if (capture_raw) {
      AddRawLiteralChar(c0_);
    }
    c0_ = source_->Advance();
530 531
  }

532
  template <typename FunctionType>
533
  V8_INLINE void AdvanceUntil(FunctionType check) {
534
    c0_ = source_->AdvanceUntil(check);
535 536
  }

537
  bool CombineSurrogatePair() {
538
    DCHECK(!unibrow::Utf16::IsLeadSurrogate(kEndOfInput));
539
    if (unibrow::Utf16::IsLeadSurrogate(c0_)) {
540
      base::uc32 c1 = source_->Advance();
541
      DCHECK(!unibrow::Utf16::IsTrailSurrogate(kEndOfInput));
542
      if (unibrow::Utf16::IsTrailSurrogate(c1)) {
543
        c0_ = unibrow::Utf16::CombineSurrogatePair(c0_, c1);
544
        return true;
545
      }
546
      source_->Back();
547
    }
548
    return false;
549 550
  }

551
  void PushBack(base::uc32 ch) {
552 553
    DCHECK(IsInvalid(c0_) ||
           base::IsInRange(c0_, 0u, unibrow::Utf16::kMaxNonSurrogateCharCode));
554
    source_->Back();
555 556 557
    c0_ = ch;
  }

558
  base::uc32 Peek() const { return source_->Peek(); }
559

560
  inline Token::Value Select(Token::Value tok) {
561
    Advance();
562 563 564
    return tok;
  }

565 566
  inline Token::Value Select(base::uc32 next, Token::Value then,
                             Token::Value else_) {
567
    Advance();
568
    if (c0_ == next) {
569
      Advance();
570
      return then;
571 572
    } else {
      return else_;
573 574
    }
  }
575 576
  // Returns the literal string, if any, for the current token (the
  // token last returned by Next()). The string is 0-terminated.
577 578 579
  // Literal strings are collected for identifiers, strings, numbers as well
  // as for template literals. For template literals we also collect the raw
  // form.
580 581
  // These functions only give the correct result if the literal was scanned
  // when a LiteralScope object is alive.
582 583 584 585 586 587
  //
  // 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".
588
  base::Vector<const uint8_t> literal_one_byte_string() const {
589 590
    DCHECK(current().CanAccessLiteral() || Token::IsKeyword(current().token) ||
           current().token == Token::ESCAPED_KEYWORD);
591
    return current().literal_chars.one_byte_literal();
592
  }
593
  base::Vector<const uint16_t> literal_two_byte_string() const {
594 595
    DCHECK(current().CanAccessLiteral() || Token::IsKeyword(current().token) ||
           current().token == Token::ESCAPED_KEYWORD);
596
    return current().literal_chars.two_byte_literal();
597
  }
598
  bool is_literal_one_byte() const {
599 600
    DCHECK(current().CanAccessLiteral() || Token::IsKeyword(current().token) ||
           current().token == Token::ESCAPED_KEYWORD);
601
    return current().literal_chars.is_one_byte();
602 603 604
  }
  // Returns the literal string for the next token (the token that
  // would be returned if Next() were called).
605
  base::Vector<const uint8_t> next_literal_one_byte_string() const {
606
    DCHECK(next().CanAccessLiteral());
607
    return next().literal_chars.one_byte_literal();
608
  }
609
  base::Vector<const uint16_t> next_literal_two_byte_string() const {
610
    DCHECK(next().CanAccessLiteral());
611
    return next().literal_chars.two_byte_literal();
612
  }
613
  bool is_next_literal_one_byte() const {
614
    DCHECK(next().CanAccessLiteral());
615
    return next().literal_chars.is_one_byte();
616
  }
617
  base::Vector<const uint8_t> raw_literal_one_byte_string() const {
618
    DCHECK(current().CanAccessRawLiteral());
619
    return current().raw_literal_chars.one_byte_literal();
620
  }
621
  base::Vector<const uint16_t> raw_literal_two_byte_string() const {
622
    DCHECK(current().CanAccessRawLiteral());
623
    return current().raw_literal_chars.two_byte_literal();
624
  }
625
  bool is_raw_literal_one_byte() const {
626
    DCHECK(current().CanAccessRawLiteral());
627
    return current().raw_literal_chars.is_one_byte();
628 629
  }

630
  template <bool capture_raw, bool unicode = false>
631
  base::uc32 ScanHexNumber(int expected_length);
marja's avatar
marja committed
632 633 634
  // 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.
635
  template <bool capture_raw>
636
  base::uc32 ScanUnlimitedLengthHexNumber(base::uc32 max_value, int beg_pos);
637

638
  // Scans a single JavaScript token.
639
  V8_INLINE Token::Value ScanSingleToken();
640
  V8_INLINE void Scan();
641 642 643 644 645
  // Performance hack: pass through a pre-calculated "next()" value to avoid
  // having to re-calculate it in Scan. You'd think the compiler would be able
  // to hoist the next() calculation out of the inlined Scan method, but seems
  // that pointer aliasing analysis fails show that this is safe.
  V8_INLINE void Scan(TokenDesc* next_desc);
646

647
  V8_INLINE Token::Value SkipWhiteSpace();
648
  Token::Value SkipSingleHTMLComment();
649
  Token::Value SkipSingleLineComment();
650 651
  Token::Value SkipSourceURLComment();
  void TryToParseSourceURLComment();
652
  Token::Value SkipMultiLineComment();
653 654
  // Scans a possible HTML comment -- begins with '<!'.
  Token::Value ScanHtmlComment();
655

656
  bool ScanDigitsWithNumericSeparators(bool (*predicate)(base::uc32 ch),
657
                                       bool is_check_first_digit);
658
  bool ScanDecimalDigits(bool allow_numeric_separator);
659
  // Optimized function to scan decimal number as Smi.
660
  bool ScanDecimalAsSmi(uint64_t* value, bool allow_numeric_separator);
661 662 663 664 665
  bool ScanDecimalAsSmiWithNumericSeparators(uint64_t* value);
  bool ScanHexDigits();
  bool ScanBinaryDigits();
  bool ScanSignedInteger();
  bool ScanOctalDigits();
666
  bool ScanImplicitOctalDigits(int start_pos, NumberKind* kind);
667

668
  Token::Value ScanNumber(bool seen_period);
669
  V8_INLINE Token::Value ScanIdentifierOrKeyword();
670
  V8_INLINE Token::Value ScanIdentifierOrKeywordInner();
671 672
  Token::Value ScanIdentifierOrKeywordInnerSlow(bool escaped,
                                                bool can_be_keyword);
673 674

  Token::Value ScanString();
675
  Token::Value ScanPrivateName();
676

677 678 679
  // 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.
680
  template <bool capture_raw>
681
  bool ScanEscape();
682

683
  // Decodes a Unicode escape-sequence which is part of an identifier.
684
  // If the escape sequence cannot be decoded the result is kBadChar.
685
  base::uc32 ScanIdentifierUnicodeEscape();
marja's avatar
marja committed
686
  // Helper for the above functions.
687
  template <bool capture_raw>
688
  base::uc32 ScanUnicodeEscape();
689

690 691
  Token::Value ScanTemplateSpan();

692
  // Return the current source position.
693 694
  int source_pos() {
    return static_cast<int>(source_->pos()) - kCharacterLookaheadBufferSize;
695 696
  }

697 698 699 700 701 702 703
  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;
    }
704
    return token.literal_chars.length() != source_length;
705 706
  }

707 708 709 710
#ifdef DEBUG
  void SanityCheckTokenDesc(const TokenDesc&) const;
#endif

711
  TokenDesc& next() { return *next_; }
712

713 714 715
  const TokenDesc& current() const { return *current_; }
  const TokenDesc& next() const { return *next_; }
  const TokenDesc& next_next() const { return *next_next_; }
716

717 718
  UnoptimizedCompileFlags flags_;

719 720 721
  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())
722

723
  // Input stream. Must be initialized to an Utf16CharacterStream.
724
  Utf16CharacterStream* const source_;
725 726

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

729 730
  TokenDesc token_storage_[3];

731 732
  // Whether this scanner encountered an HTML comment.
  bool found_html_comment_;
733

734 735 736 737 738 739
  // Values parsed from magic comments.
  LiteralBuffer source_url_;
  LiteralBuffer source_mapping_url_;

  // Last-seen positions of potentially problematic tokens.
  Location octal_pos_;
740
  MessageTemplate octal_message_;
741

742
  MessageTemplate scanner_error_;
743
  Location scanner_error_location_;
744 745
};

746 747
}  // namespace internal
}  // namespace v8
748

749
#endif  // V8_PARSING_SCANNER_H_