blob: 0acc7ab019a1c7e033ec9160d905990b4419b1bf [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_;
Ben Murdochc5610432016-08-08 18:44:38 +0100228 if (position_ < backing_store_.length()) {
229 std::copy(other->backing_store_.begin(),
230 other->backing_store_.begin() + position_,
231 backing_store_.begin());
232 } else {
233 backing_store_.Dispose();
234 backing_store_ = other->backing_store_.Clone();
235 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000236 }
237 }
238
239 private:
240 static const int kInitialCapacity = 16;
241 static const int kGrowthFactory = 4;
242 static const int kMinConversionSlack = 256;
243 static const int kMaxGrowth = 1 * MB;
244 inline int NewCapacity(int min_capacity) {
245 int capacity = Max(min_capacity, backing_store_.length());
246 int new_capacity = Min(capacity * kGrowthFactory, capacity + kMaxGrowth);
247 return new_capacity;
248 }
249
250 void ExpandBuffer() {
251 Vector<byte> new_store = Vector<byte>::New(NewCapacity(kInitialCapacity));
252 MemCopy(new_store.start(), backing_store_.start(), position_);
253 backing_store_.Dispose();
254 backing_store_ = new_store;
255 }
256
257 void ConvertToTwoByte() {
258 DCHECK(is_one_byte_);
259 Vector<byte> new_store;
260 int new_content_size = position_ * kUC16Size;
261 if (new_content_size >= backing_store_.length()) {
262 // Ensure room for all currently read code units as UC16 as well
263 // as the code unit about to be stored.
264 new_store = Vector<byte>::New(NewCapacity(new_content_size));
265 } else {
266 new_store = backing_store_;
267 }
268 uint8_t* src = backing_store_.start();
269 uint16_t* dst = reinterpret_cast<uint16_t*>(new_store.start());
270 for (int i = position_ - 1; i >= 0; i--) {
271 dst[i] = src[i];
272 }
273 if (new_store.start() != backing_store_.start()) {
274 backing_store_.Dispose();
275 backing_store_ = new_store;
276 }
277 position_ = new_content_size;
278 is_one_byte_ = false;
279 }
280
281 bool is_one_byte_;
282 int position_;
283 Vector<byte> backing_store_;
284
285 DISALLOW_COPY_AND_ASSIGN(LiteralBuffer);
286};
287
288
289// ----------------------------------------------------------------------------
290// JavaScript Scanner.
291
292class Scanner {
293 public:
294 // Scoped helper for literal recording. Automatically drops the literal
295 // if aborting the scanning before it's complete.
296 class LiteralScope {
297 public:
298 explicit LiteralScope(Scanner* self) : scanner_(self), complete_(false) {
299 scanner_->StartLiteral();
300 }
301 ~LiteralScope() {
302 if (!complete_) scanner_->DropLiteral();
303 }
304 void Complete() {
305 complete_ = true;
306 }
307
308 private:
309 Scanner* scanner_;
310 bool complete_;
311 };
312
313 // Scoped helper for a re-settable bookmark.
314 class BookmarkScope {
315 public:
316 explicit BookmarkScope(Scanner* scanner) : scanner_(scanner) {
317 DCHECK_NOT_NULL(scanner_);
318 }
319 ~BookmarkScope() { scanner_->DropBookmark(); }
320
321 bool Set() { return scanner_->SetBookmark(); }
322 void Reset() { scanner_->ResetToBookmark(); }
323 bool HasBeenSet() { return scanner_->BookmarkHasBeenSet(); }
324 bool HasBeenReset() { return scanner_->BookmarkHasBeenReset(); }
325
326 private:
327 Scanner* scanner_;
328
329 DISALLOW_COPY_AND_ASSIGN(BookmarkScope);
330 };
331
332 // Representation of an interval of source positions.
333 struct Location {
334 Location(int b, int e) : beg_pos(b), end_pos(e) { }
335 Location() : beg_pos(0), end_pos(0) { }
336
337 bool IsValid() const {
338 return beg_pos >= 0 && end_pos >= beg_pos;
339 }
340
341 static Location invalid() { return Location(-1, -1); }
342
343 int beg_pos;
344 int end_pos;
345 };
346
347 // -1 is outside of the range of any real source code.
348 static const int kNoOctalLocation = -1;
349
350 explicit Scanner(UnicodeCache* scanner_contants);
351
352 void Initialize(Utf16CharacterStream* source);
353
354 // Returns the next token and advances input.
355 Token::Value Next();
356 // Returns the token following peek()
357 Token::Value PeekAhead();
358 // Returns the current token again.
359 Token::Value current_token() { return current_.token; }
360 // Returns the location information for the current token
361 // (the token last returned by Next()).
362 Location location() const { return current_.location; }
363
Ben Murdochda12d292016-06-02 14:46:10 +0100364 bool has_error() const { return scanner_error_ != MessageTemplate::kNone; }
365 MessageTemplate::Template error() const { return scanner_error_; }
366 Location error_location() const { return scanner_error_location_; }
367
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000368 // Similar functions for the upcoming token.
369
370 // One token look-ahead (past the token returned by Next()).
371 Token::Value peek() const { return next_.token; }
372
373 Location peek_location() const { return next_.location; }
374
375 bool literal_contains_escapes() const {
376 return LiteralContainsEscapes(current_);
377 }
378 bool next_literal_contains_escapes() const {
379 return LiteralContainsEscapes(next_);
380 }
381 bool is_literal_contextual_keyword(Vector<const char> keyword) {
382 DCHECK_NOT_NULL(current_.literal_chars);
383 return current_.literal_chars->is_contextual_keyword(keyword);
384 }
385 bool is_next_contextual_keyword(Vector<const char> keyword) {
386 DCHECK_NOT_NULL(next_.literal_chars);
387 return next_.literal_chars->is_contextual_keyword(keyword);
388 }
389
390 const AstRawString* CurrentSymbol(AstValueFactory* ast_value_factory);
391 const AstRawString* NextSymbol(AstValueFactory* ast_value_factory);
392 const AstRawString* CurrentRawSymbol(AstValueFactory* ast_value_factory);
393
394 double DoubleValue();
395 bool ContainsDot();
396 bool LiteralMatches(const char* data, int length, bool allow_escapes = true) {
397 if (is_literal_one_byte() &&
398 literal_length() == length &&
399 (allow_escapes || !literal_contains_escapes())) {
400 const char* token =
401 reinterpret_cast<const char*>(literal_one_byte_string().start());
402 return !strncmp(token, data, length);
403 }
404 return false;
405 }
406 inline bool UnescapedLiteralMatches(const char* data, int length) {
407 return LiteralMatches(data, length, false);
408 }
409
410 void IsGetOrSet(bool* is_get, bool* is_set) {
411 if (is_literal_one_byte() &&
412 literal_length() == 3 &&
413 !literal_contains_escapes()) {
414 const char* token =
415 reinterpret_cast<const char*>(literal_one_byte_string().start());
416 *is_get = strncmp(token, "get", 3) == 0;
417 *is_set = !*is_get && strncmp(token, "set", 3) == 0;
418 }
419 }
420
421 int FindSymbol(DuplicateFinder* finder, int value);
422
423 UnicodeCache* unicode_cache() { return unicode_cache_; }
424
425 // Returns the location of the last seen octal literal.
426 Location octal_position() const { return octal_pos_; }
427 void clear_octal_position() { octal_pos_ = Location::invalid(); }
Ben Murdochc5610432016-08-08 18:44:38 +0100428 // Returns the location of the last seen decimal literal with a leading zero.
429 Location decimal_with_leading_zero_position() const {
430 return decimal_with_leading_zero_pos_;
431 }
432 void clear_decimal_with_leading_zero_position() {
433 decimal_with_leading_zero_pos_ = Location::invalid();
434 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000435
436 // Returns the value of the last smi that was scanned.
437 int smi_value() const { return current_.smi_value_; }
438
439 // Seek forward to the given position. This operation does not
440 // work in general, for instance when there are pushed back
441 // characters, but works for seeking forward until simple delimiter
442 // tokens, which is what it is used for.
443 void SeekForward(int pos);
444
445 // Returns true if there was a line terminator before the peek'ed token,
446 // possibly inside a multi-line comment.
447 bool HasAnyLineTerminatorBeforeNext() const {
448 return has_line_terminator_before_next_ ||
449 has_multiline_comment_before_next_;
450 }
451
Ben Murdochc5610432016-08-08 18:44:38 +0100452 bool HasAnyLineTerminatorAfterNext() {
453 Token::Value ensure_next_next = PeekAhead();
454 USE(ensure_next_next);
455 return has_line_terminator_after_next_;
456 }
457
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000458 // Scans the input as a regular expression pattern, previous
459 // character(s) must be /(=). Returns true if a pattern is scanned.
460 bool ScanRegExpPattern(bool seen_equal);
461 // Scans the input as regular expression flags. Returns the flags on success.
462 Maybe<RegExp::Flags> ScanRegExpFlags();
463
464 // Scans the input as a template literal
465 Token::Value ScanTemplateStart();
466 Token::Value ScanTemplateContinuation();
467
468 const LiteralBuffer* source_url() const { return &source_url_; }
469 const LiteralBuffer* source_mapping_url() const {
470 return &source_mapping_url_;
471 }
472
473 bool IdentifierIsFutureStrictReserved(const AstRawString* string) const;
474
Ben Murdoch097c5b22016-05-18 11:27:45 +0100475 bool FoundHtmlComment() const { return found_html_comment_; }
476
Ben Murdochda12d292016-06-02 14:46:10 +0100477#define DECLARE_ACCESSORS(name) \
478 inline bool allow_##name() const { return allow_##name##_; } \
479 inline void set_allow_##name(bool allow) { allow_##name##_ = allow; }
480 DECLARE_ACCESSORS(harmony_exponentiation_operator)
481#undef ACCESSOR
482
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000483 private:
484 // The current and look-ahead token.
485 struct TokenDesc {
486 Token::Value token;
487 Location location;
488 LiteralBuffer* literal_chars;
489 LiteralBuffer* raw_literal_chars;
490 int smi_value_;
491 };
492
493 static const int kCharacterLookaheadBufferSize = 1;
494
495 // Scans octal escape sequence. Also accepts "\0" decimal escape sequence.
496 template <bool capture_raw>
497 uc32 ScanOctalEscape(uc32 c, int length);
498
499 // Call this after setting source_ to the input.
500 void Init() {
501 // Set c0_ (one character ahead)
502 STATIC_ASSERT(kCharacterLookaheadBufferSize == 1);
503 Advance();
504 // Initialize current_ to not refer to a literal.
505 current_.literal_chars = NULL;
506 current_.raw_literal_chars = NULL;
507 next_next_.token = Token::UNINITIALIZED;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100508 found_html_comment_ = false;
Ben Murdochda12d292016-06-02 14:46:10 +0100509 scanner_error_ = MessageTemplate::kNone;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000510 }
511
512 // Support BookmarkScope functionality.
513 bool SetBookmark();
514 void ResetToBookmark();
515 bool BookmarkHasBeenSet();
516 bool BookmarkHasBeenReset();
517 void DropBookmark();
518 static void CopyTokenDesc(TokenDesc* to, TokenDesc* from);
519
Ben Murdochda12d292016-06-02 14:46:10 +0100520 void ReportScannerError(const Location& location,
521 MessageTemplate::Template error) {
522 if (has_error()) return;
523 scanner_error_ = error;
524 scanner_error_location_ = location;
525 }
526
527 void ReportScannerError(int pos, MessageTemplate::Template error) {
528 if (has_error()) return;
529 scanner_error_ = error;
530 scanner_error_location_ = Location(pos, pos + 1);
531 }
532
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000533 // Literal buffer support
534 inline void StartLiteral() {
535 LiteralBuffer* free_buffer =
536 (current_.literal_chars == &literal_buffer0_)
537 ? &literal_buffer1_
538 : (current_.literal_chars == &literal_buffer1_) ? &literal_buffer2_
539 : &literal_buffer0_;
540 free_buffer->Reset();
541 next_.literal_chars = free_buffer;
542 }
543
544 inline void StartRawLiteral() {
545 LiteralBuffer* free_buffer =
546 (current_.raw_literal_chars == &raw_literal_buffer0_)
547 ? &raw_literal_buffer1_
548 : (current_.raw_literal_chars == &raw_literal_buffer1_)
549 ? &raw_literal_buffer2_
550 : &raw_literal_buffer0_;
551 free_buffer->Reset();
552 next_.raw_literal_chars = free_buffer;
553 }
554
555 INLINE(void AddLiteralChar(uc32 c)) {
556 DCHECK_NOT_NULL(next_.literal_chars);
557 next_.literal_chars->AddChar(c);
558 }
559
560 INLINE(void AddRawLiteralChar(uc32 c)) {
561 DCHECK_NOT_NULL(next_.raw_literal_chars);
562 next_.raw_literal_chars->AddChar(c);
563 }
564
565 INLINE(void ReduceRawLiteralLength(int delta)) {
566 DCHECK_NOT_NULL(next_.raw_literal_chars);
567 next_.raw_literal_chars->ReduceLength(delta);
568 }
569
570 // Stops scanning of a literal and drop the collected characters,
571 // e.g., due to an encountered error.
572 inline void DropLiteral() {
573 next_.literal_chars = NULL;
574 next_.raw_literal_chars = NULL;
575 }
576
577 inline void AddLiteralCharAdvance() {
578 AddLiteralChar(c0_);
579 Advance();
580 }
581
582 // Low-level scanning support.
583 template <bool capture_raw = false, bool check_surrogate = true>
584 void Advance() {
585 if (capture_raw) {
586 AddRawLiteralChar(c0_);
587 }
588 c0_ = source_->Advance();
589 if (check_surrogate) HandleLeadSurrogate();
590 }
591
592 void HandleLeadSurrogate() {
593 if (unibrow::Utf16::IsLeadSurrogate(c0_)) {
594 uc32 c1 = source_->Advance();
595 if (!unibrow::Utf16::IsTrailSurrogate(c1)) {
596 source_->PushBack(c1);
597 } else {
598 c0_ = unibrow::Utf16::CombineSurrogatePair(c0_, c1);
599 }
600 }
601 }
602
603 void PushBack(uc32 ch) {
Ben Murdochc5610432016-08-08 18:44:38 +0100604 if (c0_ > static_cast<uc32>(unibrow::Utf16::kMaxNonSurrogateCharCode)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000605 source_->PushBack(unibrow::Utf16::TrailSurrogate(c0_));
606 source_->PushBack(unibrow::Utf16::LeadSurrogate(c0_));
607 } else {
608 source_->PushBack(c0_);
609 }
610 c0_ = ch;
611 }
612
613 inline Token::Value Select(Token::Value tok) {
614 Advance();
615 return tok;
616 }
617
618 inline Token::Value Select(uc32 next, Token::Value then, Token::Value else_) {
619 Advance();
620 if (c0_ == next) {
621 Advance();
622 return then;
623 } else {
624 return else_;
625 }
626 }
627
628 // Returns the literal string, if any, for the current token (the
629 // token last returned by Next()). The string is 0-terminated.
630 // Literal strings are collected for identifiers, strings, numbers as well
631 // as for template literals. For template literals we also collect the raw
632 // form.
633 // These functions only give the correct result if the literal was scanned
634 // when a LiteralScope object is alive.
635 Vector<const uint8_t> literal_one_byte_string() {
636 DCHECK_NOT_NULL(current_.literal_chars);
637 return current_.literal_chars->one_byte_literal();
638 }
639 Vector<const uint16_t> literal_two_byte_string() {
640 DCHECK_NOT_NULL(current_.literal_chars);
641 return current_.literal_chars->two_byte_literal();
642 }
643 bool is_literal_one_byte() {
644 DCHECK_NOT_NULL(current_.literal_chars);
645 return current_.literal_chars->is_one_byte();
646 }
647 int literal_length() const {
648 DCHECK_NOT_NULL(current_.literal_chars);
649 return current_.literal_chars->length();
650 }
651 // Returns the literal string for the next token (the token that
652 // would be returned if Next() were called).
653 Vector<const uint8_t> next_literal_one_byte_string() {
654 DCHECK_NOT_NULL(next_.literal_chars);
655 return next_.literal_chars->one_byte_literal();
656 }
657 Vector<const uint16_t> next_literal_two_byte_string() {
658 DCHECK_NOT_NULL(next_.literal_chars);
659 return next_.literal_chars->two_byte_literal();
660 }
661 bool is_next_literal_one_byte() {
662 DCHECK_NOT_NULL(next_.literal_chars);
663 return next_.literal_chars->is_one_byte();
664 }
665 Vector<const uint8_t> raw_literal_one_byte_string() {
666 DCHECK_NOT_NULL(current_.raw_literal_chars);
667 return current_.raw_literal_chars->one_byte_literal();
668 }
669 Vector<const uint16_t> raw_literal_two_byte_string() {
670 DCHECK_NOT_NULL(current_.raw_literal_chars);
671 return current_.raw_literal_chars->two_byte_literal();
672 }
673 bool is_raw_literal_one_byte() {
674 DCHECK_NOT_NULL(current_.raw_literal_chars);
675 return current_.raw_literal_chars->is_one_byte();
676 }
677
Ben Murdochda12d292016-06-02 14:46:10 +0100678 template <bool capture_raw, bool unicode = false>
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000679 uc32 ScanHexNumber(int expected_length);
680 // Scan a number of any length but not bigger than max_value. For example, the
681 // number can be 000000001, so it's very long in characters but its value is
682 // small.
683 template <bool capture_raw>
Ben Murdochda12d292016-06-02 14:46:10 +0100684 uc32 ScanUnlimitedLengthHexNumber(int max_value, int beg_pos);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000685
686 // Scans a single JavaScript token.
687 void Scan();
688
689 bool SkipWhiteSpace();
690 Token::Value SkipSingleLineComment();
691 Token::Value SkipSourceURLComment();
692 void TryToParseSourceURLComment();
693 Token::Value SkipMultiLineComment();
694 // Scans a possible HTML comment -- begins with '<!'.
695 Token::Value ScanHtmlComment();
696
697 void ScanDecimalDigits();
698 Token::Value ScanNumber(bool seen_period);
699 Token::Value ScanIdentifierOrKeyword();
700 Token::Value ScanIdentifierSuffix(LiteralScope* literal, bool escaped);
701
702 Token::Value ScanString();
703
704 // Scans an escape-sequence which is part of a string and adds the
705 // decoded character to the current literal. Returns true if a pattern
706 // is scanned.
707 template <bool capture_raw, bool in_template_literal>
708 bool ScanEscape();
709
710 // Decodes a Unicode escape-sequence which is part of an identifier.
711 // If the escape sequence cannot be decoded the result is kBadChar.
712 uc32 ScanIdentifierUnicodeEscape();
713 // Helper for the above functions.
714 template <bool capture_raw>
715 uc32 ScanUnicodeEscape();
716
717 Token::Value ScanTemplateSpan();
718
719 // Return the current source position.
720 int source_pos() {
721 return static_cast<int>(source_->pos()) - kCharacterLookaheadBufferSize;
722 }
723
724 static bool LiteralContainsEscapes(const TokenDesc& token) {
725 Location location = token.location;
726 int source_length = (location.end_pos - location.beg_pos);
727 if (token.token == Token::STRING) {
728 // Subtract delimiters.
729 source_length -= 2;
730 }
731 return token.literal_chars->length() != source_length;
732 }
733
734 UnicodeCache* unicode_cache_;
735
736 // Buffers collecting literal strings, numbers, etc.
737 LiteralBuffer literal_buffer0_;
738 LiteralBuffer literal_buffer1_;
739 LiteralBuffer literal_buffer2_;
740
741 // Values parsed from magic comments.
742 LiteralBuffer source_url_;
743 LiteralBuffer source_mapping_url_;
744
745 // Buffer to store raw string values
746 LiteralBuffer raw_literal_buffer0_;
747 LiteralBuffer raw_literal_buffer1_;
748 LiteralBuffer raw_literal_buffer2_;
749
750 TokenDesc current_; // desc for current token (as returned by Next())
751 TokenDesc next_; // desc for next token (one token look-ahead)
752 TokenDesc next_next_; // desc for the token after next (after PeakAhead())
753
754 // Variables for Scanner::BookmarkScope and the *Bookmark implementation.
755 // These variables contain the scanner state when a bookmark is set.
756 //
757 // We will use bookmark_c0_ as a 'control' variable, where:
758 // - bookmark_c0_ >= 0: A bookmark has been set and this contains c0_.
759 // - bookmark_c0_ == -1: No bookmark has been set.
760 // - bookmark_c0_ == -2: The bookmark has been applied (ResetToBookmark).
761 //
762 // Which state is being bookmarked? The parser state is distributed over
763 // several variables, roughly like this:
764 // ... 1234 + 5678 ..... [character stream]
765 // [current_] [next_] c0_ | [scanner state]
766 // So when the scanner is logically at the beginning of an expression
767 // like "1234 + 4567", then:
768 // - current_ contains "1234"
769 // - next_ contains "+"
770 // - c0_ contains ' ' (the space between "+" and "5678",
771 // - the source_ character stream points to the beginning of "5678".
772 // To be able to restore this state, we will keep copies of current_, next_,
773 // and c0_; we'll ask the stream to bookmark itself, and we'll copy the
774 // contents of current_'s and next_'s literal buffers to bookmark_*_literal_.
775 static const uc32 kNoBookmark = -1;
776 static const uc32 kBookmarkWasApplied = -2;
777 uc32 bookmark_c0_;
778 TokenDesc bookmark_current_;
779 TokenDesc bookmark_next_;
780 LiteralBuffer bookmark_current_literal_;
781 LiteralBuffer bookmark_current_raw_literal_;
782 LiteralBuffer bookmark_next_literal_;
783 LiteralBuffer bookmark_next_raw_literal_;
784
785 // Input stream. Must be initialized to an Utf16CharacterStream.
786 Utf16CharacterStream* source_;
787
Ben Murdochc5610432016-08-08 18:44:38 +0100788 // Last-seen positions of potentially problematic tokens.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000789 Location octal_pos_;
Ben Murdochc5610432016-08-08 18:44:38 +0100790 Location decimal_with_leading_zero_pos_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000791
792 // One Unicode character look-ahead; c0_ < 0 at the end of the input.
793 uc32 c0_;
794
795 // Whether there is a line terminator whitespace character after
796 // the current token, and before the next. Does not count newlines
797 // inside multiline comments.
798 bool has_line_terminator_before_next_;
799 // Whether there is a multi-line comment that contains a
800 // line-terminator after the current token, and before the next.
801 bool has_multiline_comment_before_next_;
Ben Murdochc5610432016-08-08 18:44:38 +0100802 bool has_line_terminator_after_next_;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100803
804 // Whether this scanner encountered an HTML comment.
805 bool found_html_comment_;
Ben Murdochda12d292016-06-02 14:46:10 +0100806
807 bool allow_harmony_exponentiation_operator_;
808
809 MessageTemplate::Template scanner_error_;
810 Location scanner_error_location_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000811};
812
813} // namespace internal
814} // namespace v8
815
816#endif // V8_PARSING_SCANNER_H_