blob: 22c504c98ea206b760d84ae76b8bb85b5ddfe81c [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2011 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Features shared by parsing and pre-parsing scanners.
6
7#ifndef V8_PARSING_SCANNER_H_
8#define V8_PARSING_SCANNER_H_
9
10#include "src/allocation.h"
11#include "src/base/logging.h"
12#include "src/char-predicates.h"
Ben Murdochda12d292016-06-02 14:46:10 +010013#include "src/collector.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000014#include "src/globals.h"
15#include "src/hashmap.h"
16#include "src/list.h"
Ben Murdochda12d292016-06-02 14:46:10 +010017#include "src/messages.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000018#include "src/parsing/token.h"
19#include "src/unicode.h"
20#include "src/unicode-decoder.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000021
22namespace v8 {
23namespace internal {
24
25
26class AstRawString;
27class AstValueFactory;
28class ParserRecorder;
29class UnicodeCache;
30
31
32// ---------------------------------------------------------------------
33// Buffered stream of UTF-16 code units, using an internal UTF-16 buffer.
34// A code unit is a 16 bit value representing either a 16 bit code point
35// or one part of a surrogate pair that make a single 21 bit code point.
36
37class Utf16CharacterStream {
38 public:
39 Utf16CharacterStream() : pos_(0) { }
40 virtual ~Utf16CharacterStream() { }
41
42 // Returns and advances past the next UTF-16 code unit in the input
43 // stream. If there are no more code units, it returns a negative
44 // value.
45 inline uc32 Advance() {
46 if (buffer_cursor_ < buffer_end_ || ReadBlock()) {
47 pos_++;
48 return static_cast<uc32>(*(buffer_cursor_++));
49 }
50 // Note: currently the following increment is necessary to avoid a
51 // parser problem! The scanner treats the final kEndOfInput as
52 // a code unit with a position, and does math relative to that
53 // position.
54 pos_++;
55
56 return kEndOfInput;
57 }
58
59 // Return the current position in the code unit stream.
60 // Starts at zero.
61 inline size_t pos() const { return pos_; }
62
63 // Skips forward past the next code_unit_count UTF-16 code units
64 // in the input, or until the end of input if that comes sooner.
65 // Returns the number of code units actually skipped. If less
66 // than code_unit_count,
67 inline size_t SeekForward(size_t code_unit_count) {
68 size_t buffered_chars = buffer_end_ - buffer_cursor_;
69 if (code_unit_count <= buffered_chars) {
70 buffer_cursor_ += code_unit_count;
71 pos_ += code_unit_count;
72 return code_unit_count;
73 }
74 return SlowSeekForward(code_unit_count);
75 }
76
77 // Pushes back the most recently read UTF-16 code unit (or negative
78 // value if at end of input), i.e., the value returned by the most recent
79 // call to Advance.
80 // Must not be used right after calling SeekForward.
81 virtual void PushBack(int32_t code_unit) = 0;
82
83 virtual bool SetBookmark();
84 virtual void ResetToBookmark();
85
86 protected:
87 static const uc32 kEndOfInput = -1;
88
89 // Ensures that the buffer_cursor_ points to the code_unit at
90 // position pos_ of the input, if possible. If the position
91 // is at or after the end of the input, return false. If there
92 // are more code_units available, return true.
93 virtual bool ReadBlock() = 0;
94 virtual size_t SlowSeekForward(size_t code_unit_count) = 0;
95
96 const uint16_t* buffer_cursor_;
97 const uint16_t* buffer_end_;
98 size_t pos_;
99};
100
101
102// ---------------------------------------------------------------------
103// DuplicateFinder discovers duplicate symbols.
104
105class DuplicateFinder {
106 public:
107 explicit DuplicateFinder(UnicodeCache* constants)
108 : unicode_constants_(constants),
109 backing_store_(16),
110 map_(&Match) { }
111
112 int AddOneByteSymbol(Vector<const uint8_t> key, int value);
113 int AddTwoByteSymbol(Vector<const uint16_t> key, int value);
114 // Add a a number literal by converting it (if necessary)
115 // to the string that ToString(ToNumber(literal)) would generate.
116 // and then adding that string with AddOneByteSymbol.
117 // This string is the actual value used as key in an object literal,
118 // and the one that must be different from the other keys.
119 int AddNumber(Vector<const uint8_t> key, int value);
120
121 private:
122 int AddSymbol(Vector<const uint8_t> key, bool is_one_byte, int value);
123 // Backs up the key and its length in the backing store.
124 // The backup is stored with a base 127 encoding of the
125 // length (plus a bit saying whether the string is one byte),
126 // followed by the bytes of the key.
127 uint8_t* BackupKey(Vector<const uint8_t> key, bool is_one_byte);
128
129 // Compare two encoded keys (both pointing into the backing store)
130 // for having the same base-127 encoded lengths and representation.
131 // and then having the same 'length' bytes following.
132 static bool Match(void* first, void* second);
133 // Creates a hash from a sequence of bytes.
134 static uint32_t Hash(Vector<const uint8_t> key, bool is_one_byte);
135 // Checks whether a string containing a JS number is its canonical
136 // form.
137 static bool IsNumberCanonical(Vector<const uint8_t> key);
138
139 // Size of buffer. Sufficient for using it to call DoubleToCString in
140 // from conversions.h.
141 static const int kBufferSize = 100;
142
143 UnicodeCache* unicode_constants_;
144 // Backing store used to store strings used as hashmap keys.
145 SequenceCollector<unsigned char> backing_store_;
146 HashMap map_;
147 // Buffer used for string->number->canonical string conversions.
148 char number_buffer_[kBufferSize];
149};
150
151
152// ----------------------------------------------------------------------------
153// LiteralBuffer - Collector of chars of literals.
154
155class LiteralBuffer {
156 public:
157 LiteralBuffer() : is_one_byte_(true), position_(0), backing_store_() { }
158
159 ~LiteralBuffer() { backing_store_.Dispose(); }
160
161 INLINE(void AddChar(uint32_t code_unit)) {
162 if (position_ >= backing_store_.length()) ExpandBuffer();
163 if (is_one_byte_) {
164 if (code_unit <= unibrow::Latin1::kMaxChar) {
165 backing_store_[position_] = static_cast<byte>(code_unit);
166 position_ += kOneByteSize;
167 return;
168 }
169 ConvertToTwoByte();
170 }
171 if (code_unit <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
172 *reinterpret_cast<uint16_t*>(&backing_store_[position_]) = code_unit;
173 position_ += kUC16Size;
174 } else {
175 *reinterpret_cast<uint16_t*>(&backing_store_[position_]) =
176 unibrow::Utf16::LeadSurrogate(code_unit);
177 position_ += kUC16Size;
178 if (position_ >= backing_store_.length()) ExpandBuffer();
179 *reinterpret_cast<uint16_t*>(&backing_store_[position_]) =
180 unibrow::Utf16::TrailSurrogate(code_unit);
181 position_ += kUC16Size;
182 }
183 }
184
185 bool is_one_byte() const { return is_one_byte_; }
186
187 bool is_contextual_keyword(Vector<const char> keyword) const {
188 return is_one_byte() && keyword.length() == position_ &&
189 (memcmp(keyword.start(), backing_store_.start(), position_) == 0);
190 }
191
192 Vector<const uint16_t> two_byte_literal() const {
193 DCHECK(!is_one_byte_);
194 DCHECK((position_ & 0x1) == 0);
195 return Vector<const uint16_t>(
196 reinterpret_cast<const uint16_t*>(backing_store_.start()),
197 position_ >> 1);
198 }
199
200 Vector<const uint8_t> one_byte_literal() const {
201 DCHECK(is_one_byte_);
202 return Vector<const uint8_t>(
203 reinterpret_cast<const uint8_t*>(backing_store_.start()),
204 position_);
205 }
206
207 int length() const {
208 return is_one_byte_ ? position_ : (position_ >> 1);
209 }
210
211 void ReduceLength(int delta) {
212 position_ -= delta * (is_one_byte_ ? kOneByteSize : kUC16Size);
213 }
214
215 void Reset() {
216 position_ = 0;
217 is_one_byte_ = true;
218 }
219
220 Handle<String> Internalize(Isolate* isolate) const;
221
222 void CopyFrom(const LiteralBuffer* other) {
223 if (other == nullptr) {
224 Reset();
225 } else {
226 is_one_byte_ = other->is_one_byte_;
227 position_ = other->position_;
228 backing_store_.Dispose();
229 backing_store_ = other->backing_store_.Clone();
230 }
231 }
232
233 private:
234 static const int kInitialCapacity = 16;
235 static const int kGrowthFactory = 4;
236 static const int kMinConversionSlack = 256;
237 static const int kMaxGrowth = 1 * MB;
238 inline int NewCapacity(int min_capacity) {
239 int capacity = Max(min_capacity, backing_store_.length());
240 int new_capacity = Min(capacity * kGrowthFactory, capacity + kMaxGrowth);
241 return new_capacity;
242 }
243
244 void ExpandBuffer() {
245 Vector<byte> new_store = Vector<byte>::New(NewCapacity(kInitialCapacity));
246 MemCopy(new_store.start(), backing_store_.start(), position_);
247 backing_store_.Dispose();
248 backing_store_ = new_store;
249 }
250
251 void ConvertToTwoByte() {
252 DCHECK(is_one_byte_);
253 Vector<byte> new_store;
254 int new_content_size = position_ * kUC16Size;
255 if (new_content_size >= backing_store_.length()) {
256 // Ensure room for all currently read code units as UC16 as well
257 // as the code unit about to be stored.
258 new_store = Vector<byte>::New(NewCapacity(new_content_size));
259 } else {
260 new_store = backing_store_;
261 }
262 uint8_t* src = backing_store_.start();
263 uint16_t* dst = reinterpret_cast<uint16_t*>(new_store.start());
264 for (int i = position_ - 1; i >= 0; i--) {
265 dst[i] = src[i];
266 }
267 if (new_store.start() != backing_store_.start()) {
268 backing_store_.Dispose();
269 backing_store_ = new_store;
270 }
271 position_ = new_content_size;
272 is_one_byte_ = false;
273 }
274
275 bool is_one_byte_;
276 int position_;
277 Vector<byte> backing_store_;
278
279 DISALLOW_COPY_AND_ASSIGN(LiteralBuffer);
280};
281
282
283// ----------------------------------------------------------------------------
284// JavaScript Scanner.
285
286class Scanner {
287 public:
288 // Scoped helper for literal recording. Automatically drops the literal
289 // if aborting the scanning before it's complete.
290 class LiteralScope {
291 public:
292 explicit LiteralScope(Scanner* self) : scanner_(self), complete_(false) {
293 scanner_->StartLiteral();
294 }
295 ~LiteralScope() {
296 if (!complete_) scanner_->DropLiteral();
297 }
298 void Complete() {
299 complete_ = true;
300 }
301
302 private:
303 Scanner* scanner_;
304 bool complete_;
305 };
306
307 // Scoped helper for a re-settable bookmark.
308 class BookmarkScope {
309 public:
310 explicit BookmarkScope(Scanner* scanner) : scanner_(scanner) {
311 DCHECK_NOT_NULL(scanner_);
312 }
313 ~BookmarkScope() { scanner_->DropBookmark(); }
314
315 bool Set() { return scanner_->SetBookmark(); }
316 void Reset() { scanner_->ResetToBookmark(); }
317 bool HasBeenSet() { return scanner_->BookmarkHasBeenSet(); }
318 bool HasBeenReset() { return scanner_->BookmarkHasBeenReset(); }
319
320 private:
321 Scanner* scanner_;
322
323 DISALLOW_COPY_AND_ASSIGN(BookmarkScope);
324 };
325
326 // Representation of an interval of source positions.
327 struct Location {
328 Location(int b, int e) : beg_pos(b), end_pos(e) { }
329 Location() : beg_pos(0), end_pos(0) { }
330
331 bool IsValid() const {
332 return beg_pos >= 0 && end_pos >= beg_pos;
333 }
334
335 static Location invalid() { return Location(-1, -1); }
336
337 int beg_pos;
338 int end_pos;
339 };
340
341 // -1 is outside of the range of any real source code.
342 static const int kNoOctalLocation = -1;
343
344 explicit Scanner(UnicodeCache* scanner_contants);
345
346 void Initialize(Utf16CharacterStream* source);
347
348 // Returns the next token and advances input.
349 Token::Value Next();
350 // Returns the token following peek()
351 Token::Value PeekAhead();
352 // Returns the current token again.
353 Token::Value current_token() { return current_.token; }
354 // Returns the location information for the current token
355 // (the token last returned by Next()).
356 Location location() const { return current_.location; }
357
Ben Murdochda12d292016-06-02 14:46:10 +0100358 bool has_error() const { return scanner_error_ != MessageTemplate::kNone; }
359 MessageTemplate::Template error() const { return scanner_error_; }
360 Location error_location() const { return scanner_error_location_; }
361
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000362 // Similar functions for the upcoming token.
363
364 // One token look-ahead (past the token returned by Next()).
365 Token::Value peek() const { return next_.token; }
366
367 Location peek_location() const { return next_.location; }
368
369 bool literal_contains_escapes() const {
370 return LiteralContainsEscapes(current_);
371 }
372 bool next_literal_contains_escapes() const {
373 return LiteralContainsEscapes(next_);
374 }
375 bool is_literal_contextual_keyword(Vector<const char> keyword) {
376 DCHECK_NOT_NULL(current_.literal_chars);
377 return current_.literal_chars->is_contextual_keyword(keyword);
378 }
379 bool is_next_contextual_keyword(Vector<const char> keyword) {
380 DCHECK_NOT_NULL(next_.literal_chars);
381 return next_.literal_chars->is_contextual_keyword(keyword);
382 }
383
384 const AstRawString* CurrentSymbol(AstValueFactory* ast_value_factory);
385 const AstRawString* NextSymbol(AstValueFactory* ast_value_factory);
386 const AstRawString* CurrentRawSymbol(AstValueFactory* ast_value_factory);
387
388 double DoubleValue();
389 bool ContainsDot();
390 bool LiteralMatches(const char* data, int length, bool allow_escapes = true) {
391 if (is_literal_one_byte() &&
392 literal_length() == length &&
393 (allow_escapes || !literal_contains_escapes())) {
394 const char* token =
395 reinterpret_cast<const char*>(literal_one_byte_string().start());
396 return !strncmp(token, data, length);
397 }
398 return false;
399 }
400 inline bool UnescapedLiteralMatches(const char* data, int length) {
401 return LiteralMatches(data, length, false);
402 }
403
404 void IsGetOrSet(bool* is_get, bool* is_set) {
405 if (is_literal_one_byte() &&
406 literal_length() == 3 &&
407 !literal_contains_escapes()) {
408 const char* token =
409 reinterpret_cast<const char*>(literal_one_byte_string().start());
410 *is_get = strncmp(token, "get", 3) == 0;
411 *is_set = !*is_get && strncmp(token, "set", 3) == 0;
412 }
413 }
414
415 int FindSymbol(DuplicateFinder* finder, int value);
416
417 UnicodeCache* unicode_cache() { return unicode_cache_; }
418
419 // Returns the location of the last seen octal literal.
420 Location octal_position() const { return octal_pos_; }
421 void clear_octal_position() { octal_pos_ = Location::invalid(); }
422
423 // Returns the value of the last smi that was scanned.
424 int smi_value() const { return current_.smi_value_; }
425
426 // Seek forward to the given position. This operation does not
427 // work in general, for instance when there are pushed back
428 // characters, but works for seeking forward until simple delimiter
429 // tokens, which is what it is used for.
430 void SeekForward(int pos);
431
432 // Returns true if there was a line terminator before the peek'ed token,
433 // possibly inside a multi-line comment.
434 bool HasAnyLineTerminatorBeforeNext() const {
435 return has_line_terminator_before_next_ ||
436 has_multiline_comment_before_next_;
437 }
438
439 // Scans the input as a regular expression pattern, previous
440 // character(s) must be /(=). Returns true if a pattern is scanned.
441 bool ScanRegExpPattern(bool seen_equal);
442 // Scans the input as regular expression flags. Returns the flags on success.
443 Maybe<RegExp::Flags> ScanRegExpFlags();
444
445 // Scans the input as a template literal
446 Token::Value ScanTemplateStart();
447 Token::Value ScanTemplateContinuation();
448
449 const LiteralBuffer* source_url() const { return &source_url_; }
450 const LiteralBuffer* source_mapping_url() const {
451 return &source_mapping_url_;
452 }
453
454 bool IdentifierIsFutureStrictReserved(const AstRawString* string) const;
455
Ben Murdoch097c5b22016-05-18 11:27:45 +0100456 bool FoundHtmlComment() const { return found_html_comment_; }
457
Ben Murdochda12d292016-06-02 14:46:10 +0100458#define DECLARE_ACCESSORS(name) \
459 inline bool allow_##name() const { return allow_##name##_; } \
460 inline void set_allow_##name(bool allow) { allow_##name##_ = allow; }
461 DECLARE_ACCESSORS(harmony_exponentiation_operator)
462#undef ACCESSOR
463
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000464 private:
465 // The current and look-ahead token.
466 struct TokenDesc {
467 Token::Value token;
468 Location location;
469 LiteralBuffer* literal_chars;
470 LiteralBuffer* raw_literal_chars;
471 int smi_value_;
472 };
473
474 static const int kCharacterLookaheadBufferSize = 1;
475
476 // Scans octal escape sequence. Also accepts "\0" decimal escape sequence.
477 template <bool capture_raw>
478 uc32 ScanOctalEscape(uc32 c, int length);
479
480 // Call this after setting source_ to the input.
481 void Init() {
482 // Set c0_ (one character ahead)
483 STATIC_ASSERT(kCharacterLookaheadBufferSize == 1);
484 Advance();
485 // Initialize current_ to not refer to a literal.
486 current_.literal_chars = NULL;
487 current_.raw_literal_chars = NULL;
488 next_next_.token = Token::UNINITIALIZED;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100489 found_html_comment_ = false;
Ben Murdochda12d292016-06-02 14:46:10 +0100490 scanner_error_ = MessageTemplate::kNone;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000491 }
492
493 // Support BookmarkScope functionality.
494 bool SetBookmark();
495 void ResetToBookmark();
496 bool BookmarkHasBeenSet();
497 bool BookmarkHasBeenReset();
498 void DropBookmark();
499 static void CopyTokenDesc(TokenDesc* to, TokenDesc* from);
500
Ben Murdochda12d292016-06-02 14:46:10 +0100501 void ReportScannerError(const Location& location,
502 MessageTemplate::Template error) {
503 if (has_error()) return;
504 scanner_error_ = error;
505 scanner_error_location_ = location;
506 }
507
508 void ReportScannerError(int pos, MessageTemplate::Template error) {
509 if (has_error()) return;
510 scanner_error_ = error;
511 scanner_error_location_ = Location(pos, pos + 1);
512 }
513
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000514 // Literal buffer support
515 inline void StartLiteral() {
516 LiteralBuffer* free_buffer =
517 (current_.literal_chars == &literal_buffer0_)
518 ? &literal_buffer1_
519 : (current_.literal_chars == &literal_buffer1_) ? &literal_buffer2_
520 : &literal_buffer0_;
521 free_buffer->Reset();
522 next_.literal_chars = free_buffer;
523 }
524
525 inline void StartRawLiteral() {
526 LiteralBuffer* free_buffer =
527 (current_.raw_literal_chars == &raw_literal_buffer0_)
528 ? &raw_literal_buffer1_
529 : (current_.raw_literal_chars == &raw_literal_buffer1_)
530 ? &raw_literal_buffer2_
531 : &raw_literal_buffer0_;
532 free_buffer->Reset();
533 next_.raw_literal_chars = free_buffer;
534 }
535
536 INLINE(void AddLiteralChar(uc32 c)) {
537 DCHECK_NOT_NULL(next_.literal_chars);
538 next_.literal_chars->AddChar(c);
539 }
540
541 INLINE(void AddRawLiteralChar(uc32 c)) {
542 DCHECK_NOT_NULL(next_.raw_literal_chars);
543 next_.raw_literal_chars->AddChar(c);
544 }
545
546 INLINE(void ReduceRawLiteralLength(int delta)) {
547 DCHECK_NOT_NULL(next_.raw_literal_chars);
548 next_.raw_literal_chars->ReduceLength(delta);
549 }
550
551 // Stops scanning of a literal and drop the collected characters,
552 // e.g., due to an encountered error.
553 inline void DropLiteral() {
554 next_.literal_chars = NULL;
555 next_.raw_literal_chars = NULL;
556 }
557
558 inline void AddLiteralCharAdvance() {
559 AddLiteralChar(c0_);
560 Advance();
561 }
562
563 // Low-level scanning support.
564 template <bool capture_raw = false, bool check_surrogate = true>
565 void Advance() {
566 if (capture_raw) {
567 AddRawLiteralChar(c0_);
568 }
569 c0_ = source_->Advance();
570 if (check_surrogate) HandleLeadSurrogate();
571 }
572
573 void HandleLeadSurrogate() {
574 if (unibrow::Utf16::IsLeadSurrogate(c0_)) {
575 uc32 c1 = source_->Advance();
576 if (!unibrow::Utf16::IsTrailSurrogate(c1)) {
577 source_->PushBack(c1);
578 } else {
579 c0_ = unibrow::Utf16::CombineSurrogatePair(c0_, c1);
580 }
581 }
582 }
583
584 void PushBack(uc32 ch) {
585 if (ch > static_cast<uc32>(unibrow::Utf16::kMaxNonSurrogateCharCode)) {
586 source_->PushBack(unibrow::Utf16::TrailSurrogate(c0_));
587 source_->PushBack(unibrow::Utf16::LeadSurrogate(c0_));
588 } else {
589 source_->PushBack(c0_);
590 }
591 c0_ = ch;
592 }
593
594 inline Token::Value Select(Token::Value tok) {
595 Advance();
596 return tok;
597 }
598
599 inline Token::Value Select(uc32 next, Token::Value then, Token::Value else_) {
600 Advance();
601 if (c0_ == next) {
602 Advance();
603 return then;
604 } else {
605 return else_;
606 }
607 }
608
609 // Returns the literal string, if any, for the current token (the
610 // token last returned by Next()). The string is 0-terminated.
611 // Literal strings are collected for identifiers, strings, numbers as well
612 // as for template literals. For template literals we also collect the raw
613 // form.
614 // These functions only give the correct result if the literal was scanned
615 // when a LiteralScope object is alive.
616 Vector<const uint8_t> literal_one_byte_string() {
617 DCHECK_NOT_NULL(current_.literal_chars);
618 return current_.literal_chars->one_byte_literal();
619 }
620 Vector<const uint16_t> literal_two_byte_string() {
621 DCHECK_NOT_NULL(current_.literal_chars);
622 return current_.literal_chars->two_byte_literal();
623 }
624 bool is_literal_one_byte() {
625 DCHECK_NOT_NULL(current_.literal_chars);
626 return current_.literal_chars->is_one_byte();
627 }
628 int literal_length() const {
629 DCHECK_NOT_NULL(current_.literal_chars);
630 return current_.literal_chars->length();
631 }
632 // Returns the literal string for the next token (the token that
633 // would be returned if Next() were called).
634 Vector<const uint8_t> next_literal_one_byte_string() {
635 DCHECK_NOT_NULL(next_.literal_chars);
636 return next_.literal_chars->one_byte_literal();
637 }
638 Vector<const uint16_t> next_literal_two_byte_string() {
639 DCHECK_NOT_NULL(next_.literal_chars);
640 return next_.literal_chars->two_byte_literal();
641 }
642 bool is_next_literal_one_byte() {
643 DCHECK_NOT_NULL(next_.literal_chars);
644 return next_.literal_chars->is_one_byte();
645 }
646 Vector<const uint8_t> raw_literal_one_byte_string() {
647 DCHECK_NOT_NULL(current_.raw_literal_chars);
648 return current_.raw_literal_chars->one_byte_literal();
649 }
650 Vector<const uint16_t> raw_literal_two_byte_string() {
651 DCHECK_NOT_NULL(current_.raw_literal_chars);
652 return current_.raw_literal_chars->two_byte_literal();
653 }
654 bool is_raw_literal_one_byte() {
655 DCHECK_NOT_NULL(current_.raw_literal_chars);
656 return current_.raw_literal_chars->is_one_byte();
657 }
658
Ben Murdochda12d292016-06-02 14:46:10 +0100659 template <bool capture_raw, bool unicode = false>
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000660 uc32 ScanHexNumber(int expected_length);
661 // Scan a number of any length but not bigger than max_value. For example, the
662 // number can be 000000001, so it's very long in characters but its value is
663 // small.
664 template <bool capture_raw>
Ben Murdochda12d292016-06-02 14:46:10 +0100665 uc32 ScanUnlimitedLengthHexNumber(int max_value, int beg_pos);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000666
667 // Scans a single JavaScript token.
668 void Scan();
669
670 bool SkipWhiteSpace();
671 Token::Value SkipSingleLineComment();
672 Token::Value SkipSourceURLComment();
673 void TryToParseSourceURLComment();
674 Token::Value SkipMultiLineComment();
675 // Scans a possible HTML comment -- begins with '<!'.
676 Token::Value ScanHtmlComment();
677
678 void ScanDecimalDigits();
679 Token::Value ScanNumber(bool seen_period);
680 Token::Value ScanIdentifierOrKeyword();
681 Token::Value ScanIdentifierSuffix(LiteralScope* literal, bool escaped);
682
683 Token::Value ScanString();
684
685 // Scans an escape-sequence which is part of a string and adds the
686 // decoded character to the current literal. Returns true if a pattern
687 // is scanned.
688 template <bool capture_raw, bool in_template_literal>
689 bool ScanEscape();
690
691 // Decodes a Unicode escape-sequence which is part of an identifier.
692 // If the escape sequence cannot be decoded the result is kBadChar.
693 uc32 ScanIdentifierUnicodeEscape();
694 // Helper for the above functions.
695 template <bool capture_raw>
696 uc32 ScanUnicodeEscape();
697
698 Token::Value ScanTemplateSpan();
699
700 // Return the current source position.
701 int source_pos() {
702 return static_cast<int>(source_->pos()) - kCharacterLookaheadBufferSize;
703 }
704
705 static bool LiteralContainsEscapes(const TokenDesc& token) {
706 Location location = token.location;
707 int source_length = (location.end_pos - location.beg_pos);
708 if (token.token == Token::STRING) {
709 // Subtract delimiters.
710 source_length -= 2;
711 }
712 return token.literal_chars->length() != source_length;
713 }
714
715 UnicodeCache* unicode_cache_;
716
717 // Buffers collecting literal strings, numbers, etc.
718 LiteralBuffer literal_buffer0_;
719 LiteralBuffer literal_buffer1_;
720 LiteralBuffer literal_buffer2_;
721
722 // Values parsed from magic comments.
723 LiteralBuffer source_url_;
724 LiteralBuffer source_mapping_url_;
725
726 // Buffer to store raw string values
727 LiteralBuffer raw_literal_buffer0_;
728 LiteralBuffer raw_literal_buffer1_;
729 LiteralBuffer raw_literal_buffer2_;
730
731 TokenDesc current_; // desc for current token (as returned by Next())
732 TokenDesc next_; // desc for next token (one token look-ahead)
733 TokenDesc next_next_; // desc for the token after next (after PeakAhead())
734
735 // Variables for Scanner::BookmarkScope and the *Bookmark implementation.
736 // These variables contain the scanner state when a bookmark is set.
737 //
738 // We will use bookmark_c0_ as a 'control' variable, where:
739 // - bookmark_c0_ >= 0: A bookmark has been set and this contains c0_.
740 // - bookmark_c0_ == -1: No bookmark has been set.
741 // - bookmark_c0_ == -2: The bookmark has been applied (ResetToBookmark).
742 //
743 // Which state is being bookmarked? The parser state is distributed over
744 // several variables, roughly like this:
745 // ... 1234 + 5678 ..... [character stream]
746 // [current_] [next_] c0_ | [scanner state]
747 // So when the scanner is logically at the beginning of an expression
748 // like "1234 + 4567", then:
749 // - current_ contains "1234"
750 // - next_ contains "+"
751 // - c0_ contains ' ' (the space between "+" and "5678",
752 // - the source_ character stream points to the beginning of "5678".
753 // To be able to restore this state, we will keep copies of current_, next_,
754 // and c0_; we'll ask the stream to bookmark itself, and we'll copy the
755 // contents of current_'s and next_'s literal buffers to bookmark_*_literal_.
756 static const uc32 kNoBookmark = -1;
757 static const uc32 kBookmarkWasApplied = -2;
758 uc32 bookmark_c0_;
759 TokenDesc bookmark_current_;
760 TokenDesc bookmark_next_;
761 LiteralBuffer bookmark_current_literal_;
762 LiteralBuffer bookmark_current_raw_literal_;
763 LiteralBuffer bookmark_next_literal_;
764 LiteralBuffer bookmark_next_raw_literal_;
765
766 // Input stream. Must be initialized to an Utf16CharacterStream.
767 Utf16CharacterStream* source_;
768
769
770 // Start position of the octal literal last scanned.
771 Location octal_pos_;
772
773 // One Unicode character look-ahead; c0_ < 0 at the end of the input.
774 uc32 c0_;
775
776 // Whether there is a line terminator whitespace character after
777 // the current token, and before the next. Does not count newlines
778 // inside multiline comments.
779 bool has_line_terminator_before_next_;
780 // Whether there is a multi-line comment that contains a
781 // line-terminator after the current token, and before the next.
782 bool has_multiline_comment_before_next_;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100783
784 // Whether this scanner encountered an HTML comment.
785 bool found_html_comment_;
Ben Murdochda12d292016-06-02 14:46:10 +0100786
787 bool allow_harmony_exponentiation_operator_;
788
789 MessageTemplate::Template scanner_error_;
790 Location scanner_error_location_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000791};
792
793} // namespace internal
794} // namespace v8
795
796#endif // V8_PARSING_SCANNER_H_