blob: 06ead2e827a4975369988448fdff459c17856aff [file] [log] [blame]
Ben Murdoch014dc512016-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#include "src/parsing/scanner.h"
8
9#include <stdint.h>
10
11#include <cmath>
12
13#include "src/ast/ast-value-factory.h"
14#include "src/char-predicates-inl.h"
15#include "src/conversions-inl.h"
16#include "src/list-inl.h"
17#include "src/parsing/parser.h"
18
19namespace v8 {
20namespace internal {
21
Ben Murdochf91f0612016-11-29 16:50:11 +000022Handle<String> Scanner::LiteralBuffer::Internalize(Isolate* isolate) const {
Ben Murdoch014dc512016-03-22 12:00:34 +000023 if (is_one_byte()) {
24 return isolate->factory()->InternalizeOneByteString(one_byte_literal());
25 }
26 return isolate->factory()->InternalizeTwoByteString(two_byte_literal());
27}
28
29
30// Default implementation for streams that do not support bookmarks.
31bool Utf16CharacterStream::SetBookmark() { return false; }
32void Utf16CharacterStream::ResetToBookmark() { UNREACHABLE(); }
33
34
35// ----------------------------------------------------------------------------
36// Scanner
37
38Scanner::Scanner(UnicodeCache* unicode_cache)
39 : unicode_cache_(unicode_cache),
40 bookmark_c0_(kNoBookmark),
Ben Murdoch109988c2016-05-18 11:27:45 +010041 octal_pos_(Location::invalid()),
Ben Murdochbcf72ee2016-08-08 18:44:38 +010042 decimal_with_leading_zero_pos_(Location::invalid()),
Ben Murdochf91f0612016-11-29 16:50:11 +000043 found_html_comment_(false) {
Ben Murdoch014dc512016-03-22 12:00:34 +000044 bookmark_current_.literal_chars = &bookmark_current_literal_;
45 bookmark_current_.raw_literal_chars = &bookmark_current_raw_literal_;
46 bookmark_next_.literal_chars = &bookmark_next_literal_;
47 bookmark_next_.raw_literal_chars = &bookmark_next_raw_literal_;
48}
49
50
51void Scanner::Initialize(Utf16CharacterStream* source) {
52 source_ = source;
53 // Need to capture identifiers in order to recognize "get" and "set"
54 // in object literals.
55 Init();
56 // Skip initial whitespace allowing HTML comment ends just like
57 // after a newline and scan first token.
58 has_line_terminator_before_next_ = true;
59 SkipWhiteSpace();
60 Scan();
61}
62
Ben Murdoch3b9bc312016-06-02 14:46:10 +010063template <bool capture_raw, bool unicode>
Ben Murdoch014dc512016-03-22 12:00:34 +000064uc32 Scanner::ScanHexNumber(int expected_length) {
65 DCHECK(expected_length <= 4); // prevent overflow
66
Ben Murdoch3b9bc312016-06-02 14:46:10 +010067 int begin = source_pos() - 2;
Ben Murdoch014dc512016-03-22 12:00:34 +000068 uc32 x = 0;
69 for (int i = 0; i < expected_length; i++) {
70 int d = HexValue(c0_);
71 if (d < 0) {
Ben Murdoch3b9bc312016-06-02 14:46:10 +010072 ReportScannerError(Location(begin, begin + expected_length + 2),
73 unicode
74 ? MessageTemplate::kInvalidUnicodeEscapeSequence
75 : MessageTemplate::kInvalidHexEscapeSequence);
Ben Murdoch014dc512016-03-22 12:00:34 +000076 return -1;
77 }
78 x = x * 16 + d;
79 Advance<capture_raw>();
80 }
81
82 return x;
83}
84
Ben Murdoch014dc512016-03-22 12:00:34 +000085template <bool capture_raw>
Ben Murdoch3b9bc312016-06-02 14:46:10 +010086uc32 Scanner::ScanUnlimitedLengthHexNumber(int max_value, int beg_pos) {
Ben Murdoch014dc512016-03-22 12:00:34 +000087 uc32 x = 0;
88 int d = HexValue(c0_);
Ben Murdoch3b9bc312016-06-02 14:46:10 +010089 if (d < 0) return -1;
90
Ben Murdoch014dc512016-03-22 12:00:34 +000091 while (d >= 0) {
92 x = x * 16 + d;
Ben Murdoch3b9bc312016-06-02 14:46:10 +010093 if (x > max_value) {
94 ReportScannerError(Location(beg_pos, source_pos() + 1),
95 MessageTemplate::kUndefinedUnicodeCodePoint);
96 return -1;
97 }
Ben Murdoch014dc512016-03-22 12:00:34 +000098 Advance<capture_raw>();
99 d = HexValue(c0_);
100 }
Ben Murdoch3b9bc312016-06-02 14:46:10 +0100101
Ben Murdoch014dc512016-03-22 12:00:34 +0000102 return x;
103}
104
105
106// Ensure that tokens can be stored in a byte.
107STATIC_ASSERT(Token::NUM_TOKENS <= 0x100);
108
109// Table of one-character tokens, by character (0x00..0x7f only).
110static const byte one_char_tokens[] = {
111 Token::ILLEGAL,
112 Token::ILLEGAL,
113 Token::ILLEGAL,
114 Token::ILLEGAL,
115 Token::ILLEGAL,
116 Token::ILLEGAL,
117 Token::ILLEGAL,
118 Token::ILLEGAL,
119 Token::ILLEGAL,
120 Token::ILLEGAL,
121 Token::ILLEGAL,
122 Token::ILLEGAL,
123 Token::ILLEGAL,
124 Token::ILLEGAL,
125 Token::ILLEGAL,
126 Token::ILLEGAL,
127 Token::ILLEGAL,
128 Token::ILLEGAL,
129 Token::ILLEGAL,
130 Token::ILLEGAL,
131 Token::ILLEGAL,
132 Token::ILLEGAL,
133 Token::ILLEGAL,
134 Token::ILLEGAL,
135 Token::ILLEGAL,
136 Token::ILLEGAL,
137 Token::ILLEGAL,
138 Token::ILLEGAL,
139 Token::ILLEGAL,
140 Token::ILLEGAL,
141 Token::ILLEGAL,
142 Token::ILLEGAL,
143 Token::ILLEGAL,
144 Token::ILLEGAL,
145 Token::ILLEGAL,
146 Token::ILLEGAL,
147 Token::ILLEGAL,
148 Token::ILLEGAL,
149 Token::ILLEGAL,
150 Token::ILLEGAL,
151 Token::LPAREN, // 0x28
152 Token::RPAREN, // 0x29
153 Token::ILLEGAL,
154 Token::ILLEGAL,
155 Token::COMMA, // 0x2c
156 Token::ILLEGAL,
157 Token::ILLEGAL,
158 Token::ILLEGAL,
159 Token::ILLEGAL,
160 Token::ILLEGAL,
161 Token::ILLEGAL,
162 Token::ILLEGAL,
163 Token::ILLEGAL,
164 Token::ILLEGAL,
165 Token::ILLEGAL,
166 Token::ILLEGAL,
167 Token::ILLEGAL,
168 Token::ILLEGAL,
169 Token::COLON, // 0x3a
170 Token::SEMICOLON, // 0x3b
171 Token::ILLEGAL,
172 Token::ILLEGAL,
173 Token::ILLEGAL,
174 Token::CONDITIONAL, // 0x3f
175 Token::ILLEGAL,
176 Token::ILLEGAL,
177 Token::ILLEGAL,
178 Token::ILLEGAL,
179 Token::ILLEGAL,
180 Token::ILLEGAL,
181 Token::ILLEGAL,
182 Token::ILLEGAL,
183 Token::ILLEGAL,
184 Token::ILLEGAL,
185 Token::ILLEGAL,
186 Token::ILLEGAL,
187 Token::ILLEGAL,
188 Token::ILLEGAL,
189 Token::ILLEGAL,
190 Token::ILLEGAL,
191 Token::ILLEGAL,
192 Token::ILLEGAL,
193 Token::ILLEGAL,
194 Token::ILLEGAL,
195 Token::ILLEGAL,
196 Token::ILLEGAL,
197 Token::ILLEGAL,
198 Token::ILLEGAL,
199 Token::ILLEGAL,
200 Token::ILLEGAL,
201 Token::ILLEGAL,
202 Token::LBRACK, // 0x5b
203 Token::ILLEGAL,
204 Token::RBRACK, // 0x5d
205 Token::ILLEGAL,
206 Token::ILLEGAL,
207 Token::ILLEGAL,
208 Token::ILLEGAL,
209 Token::ILLEGAL,
210 Token::ILLEGAL,
211 Token::ILLEGAL,
212 Token::ILLEGAL,
213 Token::ILLEGAL,
214 Token::ILLEGAL,
215 Token::ILLEGAL,
216 Token::ILLEGAL,
217 Token::ILLEGAL,
218 Token::ILLEGAL,
219 Token::ILLEGAL,
220 Token::ILLEGAL,
221 Token::ILLEGAL,
222 Token::ILLEGAL,
223 Token::ILLEGAL,
224 Token::ILLEGAL,
225 Token::ILLEGAL,
226 Token::ILLEGAL,
227 Token::ILLEGAL,
228 Token::ILLEGAL,
229 Token::ILLEGAL,
230 Token::ILLEGAL,
231 Token::ILLEGAL,
232 Token::ILLEGAL,
233 Token::ILLEGAL,
234 Token::LBRACE, // 0x7b
235 Token::ILLEGAL,
236 Token::RBRACE, // 0x7d
237 Token::BIT_NOT, // 0x7e
238 Token::ILLEGAL
239};
240
241
242Token::Value Scanner::Next() {
243 if (next_.token == Token::EOS) {
244 next_.location.beg_pos = current_.location.beg_pos;
245 next_.location.end_pos = current_.location.end_pos;
246 }
247 current_ = next_;
248 if (V8_UNLIKELY(next_next_.token != Token::UNINITIALIZED)) {
249 next_ = next_next_;
250 next_next_.token = Token::UNINITIALIZED;
Ben Murdochbcf72ee2016-08-08 18:44:38 +0100251 has_line_terminator_before_next_ = has_line_terminator_after_next_;
Ben Murdoch014dc512016-03-22 12:00:34 +0000252 return current_.token;
253 }
254 has_line_terminator_before_next_ = false;
255 has_multiline_comment_before_next_ = false;
256 if (static_cast<unsigned>(c0_) <= 0x7f) {
257 Token::Value token = static_cast<Token::Value>(one_char_tokens[c0_]);
258 if (token != Token::ILLEGAL) {
259 int pos = source_pos();
260 next_.token = token;
261 next_.location.beg_pos = pos;
262 next_.location.end_pos = pos + 1;
Ben Murdochf91f0612016-11-29 16:50:11 +0000263 next_.literal_chars = nullptr;
264 next_.raw_literal_chars = nullptr;
Ben Murdoch014dc512016-03-22 12:00:34 +0000265 Advance();
266 return current_.token;
267 }
268 }
269 Scan();
270 return current_.token;
271}
272
273
274Token::Value Scanner::PeekAhead() {
Ben Murdochf91f0612016-11-29 16:50:11 +0000275 DCHECK(next_.token != Token::DIV);
276 DCHECK(next_.token != Token::ASSIGN_DIV);
277
Ben Murdoch014dc512016-03-22 12:00:34 +0000278 if (next_next_.token != Token::UNINITIALIZED) {
279 return next_next_.token;
280 }
281 TokenDesc prev = current_;
Ben Murdochbcf72ee2016-08-08 18:44:38 +0100282 bool has_line_terminator_before_next =
283 has_line_terminator_before_next_ || has_multiline_comment_before_next_;
Ben Murdoch014dc512016-03-22 12:00:34 +0000284 Next();
Ben Murdochbcf72ee2016-08-08 18:44:38 +0100285 has_line_terminator_after_next_ =
286 has_line_terminator_before_next_ || has_multiline_comment_before_next_;
287 has_line_terminator_before_next_ = has_line_terminator_before_next;
Ben Murdoch014dc512016-03-22 12:00:34 +0000288 Token::Value ret = next_.token;
289 next_next_ = next_;
290 next_ = current_;
291 current_ = prev;
292 return ret;
293}
294
295
296// TODO(yangguo): check whether this is actually necessary.
297static inline bool IsLittleEndianByteOrderMark(uc32 c) {
298 // The Unicode value U+FFFE is guaranteed never to be assigned as a
299 // Unicode character; this implies that in a Unicode context the
300 // 0xFF, 0xFE byte pattern can only be interpreted as the U+FEFF
301 // character expressed in little-endian byte order (since it could
302 // not be a U+FFFE character expressed in big-endian byte
303 // order). Nevertheless, we check for it to be compatible with
304 // Spidermonkey.
305 return c == 0xFFFE;
306}
307
308
309bool Scanner::SkipWhiteSpace() {
310 int start_position = source_pos();
311
312 while (true) {
313 while (true) {
314 // The unicode cache accepts unsigned inputs.
315 if (c0_ < 0) break;
316 // Advance as long as character is a WhiteSpace or LineTerminator.
317 // Remember if the latter is the case.
318 if (unicode_cache_->IsLineTerminator(c0_)) {
319 has_line_terminator_before_next_ = true;
320 } else if (!unicode_cache_->IsWhiteSpace(c0_) &&
321 !IsLittleEndianByteOrderMark(c0_)) {
322 break;
323 }
324 Advance();
325 }
326
327 // If there is an HTML comment end '-->' at the beginning of a
328 // line (with only whitespace in front of it), we treat the rest
329 // of the line as a comment. This is in line with the way
330 // SpiderMonkey handles it.
331 if (c0_ == '-' && has_line_terminator_before_next_) {
332 Advance();
333 if (c0_ == '-') {
334 Advance();
335 if (c0_ == '>') {
336 // Treat the rest of the line as a comment.
337 SkipSingleLineComment();
338 // Continue skipping white space after the comment.
339 continue;
340 }
341 PushBack('-'); // undo Advance()
342 }
343 PushBack('-'); // undo Advance()
344 }
345 // Return whether or not we skipped any characters.
346 return source_pos() != start_position;
347 }
348}
349
350
351Token::Value Scanner::SkipSingleLineComment() {
352 Advance();
353
354 // The line terminator at the end of the line is not considered
355 // to be part of the single-line comment; it is recognized
356 // separately by the lexical grammar and becomes part of the
357 // stream of input elements for the syntactic grammar (see
358 // ECMA-262, section 7.4).
359 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
360 Advance();
361 }
362
363 return Token::WHITESPACE;
364}
365
366
367Token::Value Scanner::SkipSourceURLComment() {
368 TryToParseSourceURLComment();
369 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
370 Advance();
371 }
372
373 return Token::WHITESPACE;
374}
375
376
377void Scanner::TryToParseSourceURLComment() {
378 // Magic comments are of the form: //[#@]\s<name>=\s*<value>\s*.* and this
379 // function will just return if it cannot parse a magic comment.
380 if (c0_ < 0 || !unicode_cache_->IsWhiteSpace(c0_)) return;
381 Advance();
382 LiteralBuffer name;
383 while (c0_ >= 0 && !unicode_cache_->IsWhiteSpaceOrLineTerminator(c0_) &&
384 c0_ != '=') {
385 name.AddChar(c0_);
386 Advance();
387 }
388 if (!name.is_one_byte()) return;
389 Vector<const uint8_t> name_literal = name.one_byte_literal();
390 LiteralBuffer* value;
391 if (name_literal == STATIC_CHAR_VECTOR("sourceURL")) {
392 value = &source_url_;
393 } else if (name_literal == STATIC_CHAR_VECTOR("sourceMappingURL")) {
394 value = &source_mapping_url_;
395 } else {
396 return;
397 }
398 if (c0_ != '=')
399 return;
400 Advance();
401 value->Reset();
402 while (c0_ >= 0 && unicode_cache_->IsWhiteSpace(c0_)) {
403 Advance();
404 }
405 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
406 // Disallowed characters.
407 if (c0_ == '"' || c0_ == '\'') {
408 value->Reset();
409 return;
410 }
411 if (unicode_cache_->IsWhiteSpace(c0_)) {
412 break;
413 }
414 value->AddChar(c0_);
415 Advance();
416 }
417 // Allow whitespace at the end.
418 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
419 if (!unicode_cache_->IsWhiteSpace(c0_)) {
420 value->Reset();
421 break;
422 }
423 Advance();
424 }
425}
426
427
428Token::Value Scanner::SkipMultiLineComment() {
429 DCHECK(c0_ == '*');
430 Advance();
431
432 while (c0_ >= 0) {
433 uc32 ch = c0_;
434 Advance();
435 if (c0_ >= 0 && unicode_cache_->IsLineTerminator(ch)) {
436 // Following ECMA-262, section 7.4, a comment containing
437 // a newline will make the comment count as a line-terminator.
438 has_multiline_comment_before_next_ = true;
439 }
440 // If we have reached the end of the multi-line comment, we
441 // consume the '/' and insert a whitespace. This way all
442 // multi-line comments are treated as whitespace.
443 if (ch == '*' && c0_ == '/') {
444 c0_ = ' ';
445 return Token::WHITESPACE;
446 }
447 }
448
449 // Unterminated multi-line comment.
450 return Token::ILLEGAL;
451}
452
453
454Token::Value Scanner::ScanHtmlComment() {
455 // Check for <!-- comments.
456 DCHECK(c0_ == '!');
457 Advance();
458 if (c0_ == '-') {
459 Advance();
Ben Murdoch109988c2016-05-18 11:27:45 +0100460 if (c0_ == '-') {
461 found_html_comment_ = true;
462 return SkipSingleLineComment();
463 }
Ben Murdoch014dc512016-03-22 12:00:34 +0000464 PushBack('-'); // undo Advance()
465 }
466 PushBack('!'); // undo Advance()
467 DCHECK(c0_ == '!');
468 return Token::LT;
469}
470
471
472void Scanner::Scan() {
473 next_.literal_chars = NULL;
474 next_.raw_literal_chars = NULL;
475 Token::Value token;
476 do {
477 // Remember the position of the next token
478 next_.location.beg_pos = source_pos();
479
480 switch (c0_) {
481 case ' ':
482 case '\t':
483 Advance();
484 token = Token::WHITESPACE;
485 break;
486
487 case '\n':
488 Advance();
489 has_line_terminator_before_next_ = true;
490 token = Token::WHITESPACE;
491 break;
492
493 case '"': case '\'':
494 token = ScanString();
495 break;
496
497 case '<':
498 // < <= << <<= <!--
499 Advance();
500 if (c0_ == '=') {
501 token = Select(Token::LTE);
502 } else if (c0_ == '<') {
503 token = Select('=', Token::ASSIGN_SHL, Token::SHL);
504 } else if (c0_ == '!') {
505 token = ScanHtmlComment();
506 } else {
507 token = Token::LT;
508 }
509 break;
510
511 case '>':
512 // > >= >> >>= >>> >>>=
513 Advance();
514 if (c0_ == '=') {
515 token = Select(Token::GTE);
516 } else if (c0_ == '>') {
517 // >> >>= >>> >>>=
518 Advance();
519 if (c0_ == '=') {
520 token = Select(Token::ASSIGN_SAR);
521 } else if (c0_ == '>') {
522 token = Select('=', Token::ASSIGN_SHR, Token::SHR);
523 } else {
524 token = Token::SAR;
525 }
526 } else {
527 token = Token::GT;
528 }
529 break;
530
531 case '=':
532 // = == === =>
533 Advance();
534 if (c0_ == '=') {
535 token = Select('=', Token::EQ_STRICT, Token::EQ);
536 } else if (c0_ == '>') {
537 token = Select(Token::ARROW);
538 } else {
539 token = Token::ASSIGN;
540 }
541 break;
542
543 case '!':
544 // ! != !==
545 Advance();
546 if (c0_ == '=') {
547 token = Select('=', Token::NE_STRICT, Token::NE);
548 } else {
549 token = Token::NOT;
550 }
551 break;
552
553 case '+':
554 // + ++ +=
555 Advance();
556 if (c0_ == '+') {
557 token = Select(Token::INC);
558 } else if (c0_ == '=') {
559 token = Select(Token::ASSIGN_ADD);
560 } else {
561 token = Token::ADD;
562 }
563 break;
564
565 case '-':
566 // - -- --> -=
567 Advance();
568 if (c0_ == '-') {
569 Advance();
Ben Murdochf91f0612016-11-29 16:50:11 +0000570 if (c0_ == '>' && HasAnyLineTerminatorBeforeNext()) {
Ben Murdoch014dc512016-03-22 12:00:34 +0000571 // For compatibility with SpiderMonkey, we skip lines that
572 // start with an HTML comment end '-->'.
573 token = SkipSingleLineComment();
574 } else {
575 token = Token::DEC;
576 }
577 } else if (c0_ == '=') {
578 token = Select(Token::ASSIGN_SUB);
579 } else {
580 token = Token::SUB;
581 }
582 break;
583
584 case '*':
585 // * *=
Ben Murdoch3b9bc312016-06-02 14:46:10 +0100586 Advance();
Ben Murdochf91f0612016-11-29 16:50:11 +0000587 if (c0_ == '*') {
Ben Murdoch3b9bc312016-06-02 14:46:10 +0100588 token = Select('=', Token::ASSIGN_EXP, Token::EXP);
589 } else if (c0_ == '=') {
590 token = Select(Token::ASSIGN_MUL);
591 } else {
592 token = Token::MUL;
593 }
Ben Murdoch014dc512016-03-22 12:00:34 +0000594 break;
595
596 case '%':
597 // % %=
598 token = Select('=', Token::ASSIGN_MOD, Token::MOD);
599 break;
600
601 case '/':
602 // / // /* /=
603 Advance();
604 if (c0_ == '/') {
605 Advance();
606 if (c0_ == '#' || c0_ == '@') {
607 Advance();
608 token = SkipSourceURLComment();
609 } else {
610 PushBack(c0_);
611 token = SkipSingleLineComment();
612 }
613 } else if (c0_ == '*') {
614 token = SkipMultiLineComment();
615 } else if (c0_ == '=') {
616 token = Select(Token::ASSIGN_DIV);
617 } else {
618 token = Token::DIV;
619 }
620 break;
621
622 case '&':
623 // & && &=
624 Advance();
625 if (c0_ == '&') {
626 token = Select(Token::AND);
627 } else if (c0_ == '=') {
628 token = Select(Token::ASSIGN_BIT_AND);
629 } else {
630 token = Token::BIT_AND;
631 }
632 break;
633
634 case '|':
635 // | || |=
636 Advance();
637 if (c0_ == '|') {
638 token = Select(Token::OR);
639 } else if (c0_ == '=') {
640 token = Select(Token::ASSIGN_BIT_OR);
641 } else {
642 token = Token::BIT_OR;
643 }
644 break;
645
646 case '^':
647 // ^ ^=
648 token = Select('=', Token::ASSIGN_BIT_XOR, Token::BIT_XOR);
649 break;
650
651 case '.':
652 // . Number
653 Advance();
654 if (IsDecimalDigit(c0_)) {
655 token = ScanNumber(true);
656 } else {
657 token = Token::PERIOD;
658 if (c0_ == '.') {
659 Advance();
660 if (c0_ == '.') {
661 Advance();
662 token = Token::ELLIPSIS;
663 } else {
664 PushBack('.');
665 }
666 }
667 }
668 break;
669
670 case ':':
671 token = Select(Token::COLON);
672 break;
673
674 case ';':
675 token = Select(Token::SEMICOLON);
676 break;
677
678 case ',':
679 token = Select(Token::COMMA);
680 break;
681
682 case '(':
683 token = Select(Token::LPAREN);
684 break;
685
686 case ')':
687 token = Select(Token::RPAREN);
688 break;
689
690 case '[':
691 token = Select(Token::LBRACK);
692 break;
693
694 case ']':
695 token = Select(Token::RBRACK);
696 break;
697
698 case '{':
699 token = Select(Token::LBRACE);
700 break;
701
702 case '}':
703 token = Select(Token::RBRACE);
704 break;
705
706 case '?':
707 token = Select(Token::CONDITIONAL);
708 break;
709
710 case '~':
711 token = Select(Token::BIT_NOT);
712 break;
713
714 case '`':
715 token = ScanTemplateStart();
716 break;
717
718 default:
719 if (c0_ < 0) {
720 token = Token::EOS;
721 } else if (unicode_cache_->IsIdentifierStart(c0_)) {
722 token = ScanIdentifierOrKeyword();
723 } else if (IsDecimalDigit(c0_)) {
724 token = ScanNumber(false);
725 } else if (SkipWhiteSpace()) {
726 token = Token::WHITESPACE;
727 } else {
728 token = Select(Token::ILLEGAL);
729 }
730 break;
731 }
732
733 // Continue scanning for tokens as long as we're just skipping
734 // whitespace.
735 } while (token == Token::WHITESPACE);
736
737 next_.location.end_pos = source_pos();
738 next_.token = token;
Ben Murdochf91f0612016-11-29 16:50:11 +0000739
740#ifdef DEBUG
741 SanityCheckTokenDesc(current_);
742 SanityCheckTokenDesc(next_);
743 SanityCheckTokenDesc(next_next_);
744#endif
Ben Murdoch014dc512016-03-22 12:00:34 +0000745}
746
Ben Murdochf91f0612016-11-29 16:50:11 +0000747#ifdef DEBUG
748void Scanner::SanityCheckTokenDesc(const TokenDesc& token) const {
749 // Most tokens should not have literal_chars or even raw_literal chars.
750 // The rules are:
751 // - UNINITIALIZED: we don't care.
752 // - TEMPLATE_*: need both literal + raw literal chars.
753 // - IDENTIFIERS, STRINGS, etc.: need a literal, but no raw literal.
754 // - all others: should have neither.
755
756 switch (token.token) {
757 case Token::UNINITIALIZED:
758 // token.literal_chars & other members might be garbage. That's ok.
759 break;
760 case Token::TEMPLATE_SPAN:
761 case Token::TEMPLATE_TAIL:
762 DCHECK_NOT_NULL(token.raw_literal_chars);
763 DCHECK_NOT_NULL(token.literal_chars);
764 break;
765 case Token::ESCAPED_KEYWORD:
766 case Token::ESCAPED_STRICT_RESERVED_WORD:
767 case Token::FUTURE_STRICT_RESERVED_WORD:
768 case Token::IDENTIFIER:
769 case Token::NUMBER:
770 case Token::REGEXP_LITERAL:
771 case Token::SMI:
772 case Token::STRING:
773 DCHECK_NOT_NULL(token.literal_chars);
774 DCHECK_NULL(token.raw_literal_chars);
775 break;
776 default:
777 DCHECK_NULL(token.literal_chars);
778 DCHECK_NULL(token.raw_literal_chars);
779 break;
780 }
781}
782#endif // DEBUG
Ben Murdoch014dc512016-03-22 12:00:34 +0000783
784void Scanner::SeekForward(int pos) {
785 // After this call, we will have the token at the given position as
786 // the "next" token. The "current" token will be invalid.
787 if (pos == next_.location.beg_pos) return;
788 int current_pos = source_pos();
789 DCHECK_EQ(next_.location.end_pos, current_pos);
790 // Positions inside the lookahead token aren't supported.
791 DCHECK(pos >= current_pos);
792 if (pos != current_pos) {
793 source_->SeekForward(pos - source_->pos());
794 Advance();
795 // This function is only called to seek to the location
796 // of the end of a function (at the "}" token). It doesn't matter
797 // whether there was a line terminator in the part we skip.
798 has_line_terminator_before_next_ = false;
799 has_multiline_comment_before_next_ = false;
800 }
801 Scan();
802}
803
804
805template <bool capture_raw, bool in_template_literal>
806bool Scanner::ScanEscape() {
807 uc32 c = c0_;
808 Advance<capture_raw>();
809
810 // Skip escaped newlines.
811 if (!in_template_literal && c0_ >= 0 && unicode_cache_->IsLineTerminator(c)) {
812 // Allow CR+LF newlines in multiline string literals.
813 if (IsCarriageReturn(c) && IsLineFeed(c0_)) Advance<capture_raw>();
814 // Allow LF+CR newlines in multiline string literals.
815 if (IsLineFeed(c) && IsCarriageReturn(c0_)) Advance<capture_raw>();
816 return true;
817 }
818
819 switch (c) {
820 case '\'': // fall through
821 case '"' : // fall through
822 case '\\': break;
823 case 'b' : c = '\b'; break;
824 case 'f' : c = '\f'; break;
825 case 'n' : c = '\n'; break;
826 case 'r' : c = '\r'; break;
827 case 't' : c = '\t'; break;
828 case 'u' : {
829 c = ScanUnicodeEscape<capture_raw>();
830 if (c < 0) return false;
831 break;
832 }
833 case 'v':
834 c = '\v';
835 break;
836 case 'x': {
837 c = ScanHexNumber<capture_raw>(2);
838 if (c < 0) return false;
839 break;
840 }
841 case '0': // Fall through.
842 case '1': // fall through
843 case '2': // fall through
844 case '3': // fall through
845 case '4': // fall through
846 case '5': // fall through
847 case '6': // fall through
848 case '7':
849 c = ScanOctalEscape<capture_raw>(c, 2);
850 break;
851 }
852
853 // According to ECMA-262, section 7.8.4, characters not covered by the
854 // above cases should be illegal, but they are commonly handled as
855 // non-escaped characters by JS VMs.
856 AddLiteralChar(c);
857 return true;
858}
859
860
861// Octal escapes of the forms '\0xx' and '\xxx' are not a part of
862// ECMA-262. Other JS VMs support them.
863template <bool capture_raw>
864uc32 Scanner::ScanOctalEscape(uc32 c, int length) {
865 uc32 x = c - '0';
866 int i = 0;
867 for (; i < length; i++) {
868 int d = c0_ - '0';
869 if (d < 0 || d > 7) break;
870 int nx = x * 8 + d;
871 if (nx >= 256) break;
872 x = nx;
873 Advance<capture_raw>();
874 }
875 // Anything except '\0' is an octal escape sequence, illegal in strict mode.
876 // Remember the position of octal escape sequences so that an error
877 // can be reported later (in strict mode).
878 // We don't report the error immediately, because the octal escape can
879 // occur before the "use strict" directive.
880 if (c != '0' || i > 0) {
881 octal_pos_ = Location(source_pos() - i - 1, source_pos() - 1);
882 }
883 return x;
884}
885
886
Ben Murdoch014dc512016-03-22 12:00:34 +0000887Token::Value Scanner::ScanString() {
888 uc32 quote = c0_;
889 Advance<false, false>(); // consume quote
890
891 LiteralScope literal(this);
892 while (true) {
893 if (c0_ > kMaxAscii) {
894 HandleLeadSurrogate();
895 break;
896 }
897 if (c0_ < 0 || c0_ == '\n' || c0_ == '\r') return Token::ILLEGAL;
898 if (c0_ == quote) {
899 literal.Complete();
900 Advance<false, false>();
901 return Token::STRING;
902 }
Ben Murdoch13e2dad2016-09-16 13:49:30 +0100903 char c = static_cast<char>(c0_);
Ben Murdoch014dc512016-03-22 12:00:34 +0000904 if (c == '\\') break;
905 Advance<false, false>();
906 AddLiteralChar(c);
907 }
908
909 while (c0_ != quote && c0_ >= 0
910 && !unicode_cache_->IsLineTerminator(c0_)) {
911 uc32 c = c0_;
912 Advance();
913 if (c == '\\') {
Ben Murdoch3b9bc312016-06-02 14:46:10 +0100914 if (c0_ < 0 || !ScanEscape<false, false>()) {
915 return Token::ILLEGAL;
916 }
Ben Murdoch014dc512016-03-22 12:00:34 +0000917 } else {
918 AddLiteralChar(c);
919 }
920 }
921 if (c0_ != quote) return Token::ILLEGAL;
922 literal.Complete();
923
924 Advance(); // consume quote
925 return Token::STRING;
926}
927
928
929Token::Value Scanner::ScanTemplateSpan() {
930 // When scanning a TemplateSpan, we are looking for the following construct:
931 // TEMPLATE_SPAN ::
932 // ` LiteralChars* ${
933 // | } LiteralChars* ${
934 //
935 // TEMPLATE_TAIL ::
936 // ` LiteralChars* `
937 // | } LiteralChar* `
938 //
939 // A TEMPLATE_SPAN should always be followed by an Expression, while a
940 // TEMPLATE_TAIL terminates a TemplateLiteral and does not need to be
941 // followed by an Expression.
942
943 Token::Value result = Token::TEMPLATE_SPAN;
944 LiteralScope literal(this);
945 StartRawLiteral();
946 const bool capture_raw = true;
947 const bool in_template_literal = true;
Ben Murdoch014dc512016-03-22 12:00:34 +0000948 while (true) {
949 uc32 c = c0_;
950 Advance<capture_raw>();
951 if (c == '`') {
952 result = Token::TEMPLATE_TAIL;
953 ReduceRawLiteralLength(1);
954 break;
955 } else if (c == '$' && c0_ == '{') {
956 Advance<capture_raw>(); // Consume '{'
957 ReduceRawLiteralLength(2);
958 break;
959 } else if (c == '\\') {
960 if (c0_ > 0 && unicode_cache_->IsLineTerminator(c0_)) {
961 // The TV of LineContinuation :: \ LineTerminatorSequence is the empty
962 // code unit sequence.
963 uc32 lastChar = c0_;
964 Advance<capture_raw>();
965 if (lastChar == '\r') {
966 ReduceRawLiteralLength(1); // Remove \r
967 if (c0_ == '\n') {
968 Advance<capture_raw>(); // Adds \n
969 } else {
970 AddRawLiteralChar('\n');
971 }
972 }
973 } else if (!ScanEscape<capture_raw, in_template_literal>()) {
974 return Token::ILLEGAL;
975 }
976 } else if (c < 0) {
977 // Unterminated template literal
978 PushBack(c);
979 break;
980 } else {
981 // The TRV of LineTerminatorSequence :: <CR> is the CV 0x000A.
982 // The TRV of LineTerminatorSequence :: <CR><LF> is the sequence
983 // consisting of the CV 0x000A.
984 if (c == '\r') {
985 ReduceRawLiteralLength(1); // Remove \r
986 if (c0_ == '\n') {
987 Advance<capture_raw>(); // Adds \n
988 } else {
989 AddRawLiteralChar('\n');
990 }
991 c = '\n';
992 }
993 AddLiteralChar(c);
994 }
995 }
996 literal.Complete();
997 next_.location.end_pos = source_pos();
998 next_.token = result;
999 return result;
1000}
1001
1002
1003Token::Value Scanner::ScanTemplateStart() {
Ben Murdochf91f0612016-11-29 16:50:11 +00001004 DCHECK(next_next_.token == Token::UNINITIALIZED);
Ben Murdoch014dc512016-03-22 12:00:34 +00001005 DCHECK(c0_ == '`');
1006 next_.location.beg_pos = source_pos();
1007 Advance(); // Consume `
1008 return ScanTemplateSpan();
1009}
1010
1011
1012Token::Value Scanner::ScanTemplateContinuation() {
1013 DCHECK_EQ(next_.token, Token::RBRACE);
1014 next_.location.beg_pos = source_pos() - 1; // We already consumed }
1015 return ScanTemplateSpan();
1016}
1017
1018
1019void Scanner::ScanDecimalDigits() {
1020 while (IsDecimalDigit(c0_))
1021 AddLiteralCharAdvance();
1022}
1023
1024
1025Token::Value Scanner::ScanNumber(bool seen_period) {
1026 DCHECK(IsDecimalDigit(c0_)); // the first digit of the number or the fraction
1027
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001028 enum {
1029 DECIMAL,
1030 DECIMAL_WITH_LEADING_ZERO,
1031 HEX,
1032 OCTAL,
1033 IMPLICIT_OCTAL,
1034 BINARY
1035 } kind = DECIMAL;
Ben Murdoch014dc512016-03-22 12:00:34 +00001036
1037 LiteralScope literal(this);
1038 bool at_start = !seen_period;
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001039 int start_pos = source_pos(); // For reporting octal positions.
Ben Murdoch014dc512016-03-22 12:00:34 +00001040 if (seen_period) {
1041 // we have already seen a decimal point of the float
1042 AddLiteralChar('.');
1043 ScanDecimalDigits(); // we know we have at least one digit
1044
1045 } else {
1046 // if the first character is '0' we must check for octals and hex
1047 if (c0_ == '0') {
Ben Murdoch014dc512016-03-22 12:00:34 +00001048 AddLiteralCharAdvance();
1049
1050 // either 0, 0exxx, 0Exxx, 0.xxx, a hex number, a binary number or
1051 // an octal number.
1052 if (c0_ == 'x' || c0_ == 'X') {
1053 // hex number
1054 kind = HEX;
1055 AddLiteralCharAdvance();
1056 if (!IsHexDigit(c0_)) {
1057 // we must have at least one hex digit after 'x'/'X'
1058 return Token::ILLEGAL;
1059 }
1060 while (IsHexDigit(c0_)) {
1061 AddLiteralCharAdvance();
1062 }
1063 } else if (c0_ == 'o' || c0_ == 'O') {
1064 kind = OCTAL;
1065 AddLiteralCharAdvance();
1066 if (!IsOctalDigit(c0_)) {
1067 // we must have at least one octal digit after 'o'/'O'
1068 return Token::ILLEGAL;
1069 }
1070 while (IsOctalDigit(c0_)) {
1071 AddLiteralCharAdvance();
1072 }
1073 } else if (c0_ == 'b' || c0_ == 'B') {
1074 kind = BINARY;
1075 AddLiteralCharAdvance();
1076 if (!IsBinaryDigit(c0_)) {
1077 // we must have at least one binary digit after 'b'/'B'
1078 return Token::ILLEGAL;
1079 }
1080 while (IsBinaryDigit(c0_)) {
1081 AddLiteralCharAdvance();
1082 }
1083 } else if ('0' <= c0_ && c0_ <= '7') {
1084 // (possible) octal number
1085 kind = IMPLICIT_OCTAL;
1086 while (true) {
1087 if (c0_ == '8' || c0_ == '9') {
1088 at_start = false;
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001089 kind = DECIMAL_WITH_LEADING_ZERO;
Ben Murdoch014dc512016-03-22 12:00:34 +00001090 break;
1091 }
1092 if (c0_ < '0' || '7' < c0_) {
1093 // Octal literal finished.
1094 octal_pos_ = Location(start_pos, source_pos());
1095 break;
1096 }
1097 AddLiteralCharAdvance();
1098 }
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001099 } else if (c0_ == '8' || c0_ == '9') {
1100 kind = DECIMAL_WITH_LEADING_ZERO;
Ben Murdoch014dc512016-03-22 12:00:34 +00001101 }
1102 }
1103
1104 // Parse decimal digits and allow trailing fractional part.
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001105 if (kind == DECIMAL || kind == DECIMAL_WITH_LEADING_ZERO) {
Ben Murdoch014dc512016-03-22 12:00:34 +00001106 if (at_start) {
1107 uint64_t value = 0;
1108 while (IsDecimalDigit(c0_)) {
1109 value = 10 * value + (c0_ - '0');
1110
1111 uc32 first_char = c0_;
1112 Advance<false, false>();
1113 AddLiteralChar(first_char);
1114 }
1115
1116 if (next_.literal_chars->one_byte_literal().length() <= 10 &&
1117 value <= Smi::kMaxValue && c0_ != '.' && c0_ != 'e' && c0_ != 'E') {
1118 next_.smi_value_ = static_cast<int>(value);
1119 literal.Complete();
1120 HandleLeadSurrogate();
1121
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001122 if (kind == DECIMAL_WITH_LEADING_ZERO)
1123 decimal_with_leading_zero_pos_ = Location(start_pos, source_pos());
Ben Murdoch014dc512016-03-22 12:00:34 +00001124 return Token::SMI;
1125 }
1126 HandleLeadSurrogate();
1127 }
1128
1129 ScanDecimalDigits(); // optional
1130 if (c0_ == '.') {
1131 AddLiteralCharAdvance();
1132 ScanDecimalDigits(); // optional
1133 }
1134 }
1135 }
1136
1137 // scan exponent, if any
1138 if (c0_ == 'e' || c0_ == 'E') {
1139 DCHECK(kind != HEX); // 'e'/'E' must be scanned as part of the hex number
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001140 if (!(kind == DECIMAL || kind == DECIMAL_WITH_LEADING_ZERO))
1141 return Token::ILLEGAL;
Ben Murdoch014dc512016-03-22 12:00:34 +00001142 // scan exponent
1143 AddLiteralCharAdvance();
1144 if (c0_ == '+' || c0_ == '-')
1145 AddLiteralCharAdvance();
1146 if (!IsDecimalDigit(c0_)) {
1147 // we must have at least one decimal digit after 'e'/'E'
1148 return Token::ILLEGAL;
1149 }
1150 ScanDecimalDigits();
1151 }
1152
1153 // The source character immediately following a numeric literal must
1154 // not be an identifier start or a decimal digit; see ECMA-262
1155 // section 7.8.3, page 17 (note that we read only one decimal digit
1156 // if the value is 0).
1157 if (IsDecimalDigit(c0_) ||
1158 (c0_ >= 0 && unicode_cache_->IsIdentifierStart(c0_)))
1159 return Token::ILLEGAL;
1160
1161 literal.Complete();
1162
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001163 if (kind == DECIMAL_WITH_LEADING_ZERO)
1164 decimal_with_leading_zero_pos_ = Location(start_pos, source_pos());
Ben Murdoch014dc512016-03-22 12:00:34 +00001165 return Token::NUMBER;
1166}
1167
1168
1169uc32 Scanner::ScanIdentifierUnicodeEscape() {
1170 Advance();
1171 if (c0_ != 'u') return -1;
1172 Advance();
1173 return ScanUnicodeEscape<false>();
1174}
1175
1176
1177template <bool capture_raw>
1178uc32 Scanner::ScanUnicodeEscape() {
1179 // Accept both \uxxxx and \u{xxxxxx}. In the latter case, the number of
1180 // hex digits between { } is arbitrary. \ and u have already been read.
1181 if (c0_ == '{') {
Ben Murdoch3b9bc312016-06-02 14:46:10 +01001182 int begin = source_pos() - 2;
Ben Murdoch014dc512016-03-22 12:00:34 +00001183 Advance<capture_raw>();
Ben Murdoch3b9bc312016-06-02 14:46:10 +01001184 uc32 cp = ScanUnlimitedLengthHexNumber<capture_raw>(0x10ffff, begin);
1185 if (cp < 0 || c0_ != '}') {
1186 ReportScannerError(source_pos(),
1187 MessageTemplate::kInvalidUnicodeEscapeSequence);
Ben Murdoch014dc512016-03-22 12:00:34 +00001188 return -1;
1189 }
1190 Advance<capture_raw>();
1191 return cp;
1192 }
Ben Murdoch3b9bc312016-06-02 14:46:10 +01001193 const bool unicode = true;
1194 return ScanHexNumber<capture_raw, unicode>(4);
Ben Murdoch014dc512016-03-22 12:00:34 +00001195}
1196
1197
1198// ----------------------------------------------------------------------------
1199// Keyword Matcher
1200
1201#define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001202 KEYWORD_GROUP('a') \
1203 KEYWORD("async", Token::ASYNC) \
1204 KEYWORD("await", Token::AWAIT) \
Ben Murdoch014dc512016-03-22 12:00:34 +00001205 KEYWORD_GROUP('b') \
1206 KEYWORD("break", Token::BREAK) \
1207 KEYWORD_GROUP('c') \
1208 KEYWORD("case", Token::CASE) \
1209 KEYWORD("catch", Token::CATCH) \
1210 KEYWORD("class", Token::CLASS) \
1211 KEYWORD("const", Token::CONST) \
1212 KEYWORD("continue", Token::CONTINUE) \
1213 KEYWORD_GROUP('d') \
1214 KEYWORD("debugger", Token::DEBUGGER) \
1215 KEYWORD("default", Token::DEFAULT) \
1216 KEYWORD("delete", Token::DELETE) \
1217 KEYWORD("do", Token::DO) \
1218 KEYWORD_GROUP('e') \
1219 KEYWORD("else", Token::ELSE) \
Ben Murdochbcf72ee2016-08-08 18:44:38 +01001220 KEYWORD("enum", Token::ENUM) \
Ben Murdoch014dc512016-03-22 12:00:34 +00001221 KEYWORD("export", Token::EXPORT) \
1222 KEYWORD("extends", Token::EXTENDS) \
1223 KEYWORD_GROUP('f') \
1224 KEYWORD("false", Token::FALSE_LITERAL) \
1225 KEYWORD("finally", Token::FINALLY) \
1226 KEYWORD("for", Token::FOR) \
1227 KEYWORD("function", Token::FUNCTION) \
1228 KEYWORD_GROUP('i') \
1229 KEYWORD("if", Token::IF) \
1230 KEYWORD("implements", Token::FUTURE_STRICT_RESERVED_WORD) \
1231 KEYWORD("import", Token::IMPORT) \
1232 KEYWORD("in", Token::IN) \
1233 KEYWORD("instanceof", Token::INSTANCEOF) \
1234 KEYWORD("interface", Token::FUTURE_STRICT_RESERVED_WORD) \
1235 KEYWORD_GROUP('l') \
1236 KEYWORD("let", Token::LET) \
1237 KEYWORD_GROUP('n') \
1238 KEYWORD("new", Token::NEW) \
1239 KEYWORD("null", Token::NULL_LITERAL) \
1240 KEYWORD_GROUP('p') \
1241 KEYWORD("package", Token::FUTURE_STRICT_RESERVED_WORD) \
1242 KEYWORD("private", Token::FUTURE_STRICT_RESERVED_WORD) \
1243 KEYWORD("protected", Token::FUTURE_STRICT_RESERVED_WORD) \
1244 KEYWORD("public", Token::FUTURE_STRICT_RESERVED_WORD) \
1245 KEYWORD_GROUP('r') \
1246 KEYWORD("return", Token::RETURN) \
1247 KEYWORD_GROUP('s') \
1248 KEYWORD("static", Token::STATIC) \
1249 KEYWORD("super", Token::SUPER) \
1250 KEYWORD("switch", Token::SWITCH) \
1251 KEYWORD_GROUP('t') \
1252 KEYWORD("this", Token::THIS) \
1253 KEYWORD("throw", Token::THROW) \
1254 KEYWORD("true", Token::TRUE_LITERAL) \
1255 KEYWORD("try", Token::TRY) \
1256 KEYWORD("typeof", Token::TYPEOF) \
1257 KEYWORD_GROUP('v') \
1258 KEYWORD("var", Token::VAR) \
1259 KEYWORD("void", Token::VOID) \
1260 KEYWORD_GROUP('w') \
1261 KEYWORD("while", Token::WHILE) \
1262 KEYWORD("with", Token::WITH) \
1263 KEYWORD_GROUP('y') \
1264 KEYWORD("yield", Token::YIELD)
1265
Ben Murdoch014dc512016-03-22 12:00:34 +00001266static Token::Value KeywordOrIdentifierToken(const uint8_t* input,
Ben Murdochf91f0612016-11-29 16:50:11 +00001267 int input_length) {
Ben Murdoch014dc512016-03-22 12:00:34 +00001268 DCHECK(input_length >= 1);
1269 const int kMinLength = 2;
1270 const int kMaxLength = 10;
1271 if (input_length < kMinLength || input_length > kMaxLength) {
1272 return Token::IDENTIFIER;
1273 }
1274 switch (input[0]) {
1275 default:
1276#define KEYWORD_GROUP_CASE(ch) \
1277 break; \
1278 case ch:
1279#define KEYWORD(keyword, token) \
1280 { \
1281 /* 'keyword' is a char array, so sizeof(keyword) is */ \
1282 /* strlen(keyword) plus 1 for the NUL char. */ \
1283 const int keyword_length = sizeof(keyword) - 1; \
1284 STATIC_ASSERT(keyword_length >= kMinLength); \
1285 STATIC_ASSERT(keyword_length <= kMaxLength); \
1286 if (input_length == keyword_length && input[1] == keyword[1] && \
1287 (keyword_length <= 2 || input[2] == keyword[2]) && \
1288 (keyword_length <= 3 || input[3] == keyword[3]) && \
1289 (keyword_length <= 4 || input[4] == keyword[4]) && \
1290 (keyword_length <= 5 || input[5] == keyword[5]) && \
1291 (keyword_length <= 6 || input[6] == keyword[6]) && \
1292 (keyword_length <= 7 || input[7] == keyword[7]) && \
1293 (keyword_length <= 8 || input[8] == keyword[8]) && \
1294 (keyword_length <= 9 || input[9] == keyword[9])) { \
Ben Murdoch014dc512016-03-22 12:00:34 +00001295 return token; \
1296 } \
1297 }
1298 KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
1299 }
1300 return Token::IDENTIFIER;
1301}
1302
1303
1304bool Scanner::IdentifierIsFutureStrictReserved(
1305 const AstRawString* string) const {
1306 // Keywords are always 1-byte strings.
1307 if (!string->is_one_byte()) return false;
1308 if (string->IsOneByteEqualTo("let") || string->IsOneByteEqualTo("static") ||
1309 string->IsOneByteEqualTo("yield")) {
1310 return true;
1311 }
1312 return Token::FUTURE_STRICT_RESERVED_WORD ==
Ben Murdochf91f0612016-11-29 16:50:11 +00001313 KeywordOrIdentifierToken(string->raw_data(), string->length());
Ben Murdoch014dc512016-03-22 12:00:34 +00001314}
1315
1316
1317Token::Value Scanner::ScanIdentifierOrKeyword() {
1318 DCHECK(unicode_cache_->IsIdentifierStart(c0_));
1319 LiteralScope literal(this);
1320 if (IsInRange(c0_, 'a', 'z')) {
1321 do {
Ben Murdoch13e2dad2016-09-16 13:49:30 +01001322 char first_char = static_cast<char>(c0_);
Ben Murdoch014dc512016-03-22 12:00:34 +00001323 Advance<false, false>();
1324 AddLiteralChar(first_char);
1325 } while (IsInRange(c0_, 'a', 'z'));
1326
1327 if (IsDecimalDigit(c0_) || IsInRange(c0_, 'A', 'Z') || c0_ == '_' ||
1328 c0_ == '$') {
1329 // Identifier starting with lowercase.
Ben Murdoch13e2dad2016-09-16 13:49:30 +01001330 char first_char = static_cast<char>(c0_);
Ben Murdoch014dc512016-03-22 12:00:34 +00001331 Advance<false, false>();
1332 AddLiteralChar(first_char);
1333 while (IsAsciiIdentifier(c0_)) {
Ben Murdoch13e2dad2016-09-16 13:49:30 +01001334 char first_char = static_cast<char>(c0_);
Ben Murdoch014dc512016-03-22 12:00:34 +00001335 Advance<false, false>();
1336 AddLiteralChar(first_char);
1337 }
1338 if (c0_ <= kMaxAscii && c0_ != '\\') {
1339 literal.Complete();
1340 return Token::IDENTIFIER;
1341 }
1342 } else if (c0_ <= kMaxAscii && c0_ != '\\') {
1343 // Only a-z+: could be a keyword or identifier.
Ben Murdoch014dc512016-03-22 12:00:34 +00001344 Vector<const uint8_t> chars = next_.literal_chars->one_byte_literal();
Ben Murdochf91f0612016-11-29 16:50:11 +00001345 Token::Value token =
1346 KeywordOrIdentifierToken(chars.start(), chars.length());
1347 if (token == Token::IDENTIFIER ||
1348 token == Token::FUTURE_STRICT_RESERVED_WORD)
1349 literal.Complete();
1350 return token;
Ben Murdoch014dc512016-03-22 12:00:34 +00001351 }
1352
1353 HandleLeadSurrogate();
1354 } else if (IsInRange(c0_, 'A', 'Z') || c0_ == '_' || c0_ == '$') {
1355 do {
Ben Murdoch13e2dad2016-09-16 13:49:30 +01001356 char first_char = static_cast<char>(c0_);
Ben Murdoch014dc512016-03-22 12:00:34 +00001357 Advance<false, false>();
1358 AddLiteralChar(first_char);
1359 } while (IsAsciiIdentifier(c0_));
1360
1361 if (c0_ <= kMaxAscii && c0_ != '\\') {
1362 literal.Complete();
1363 return Token::IDENTIFIER;
1364 }
1365
1366 HandleLeadSurrogate();
1367 } else if (c0_ == '\\') {
1368 // Scan identifier start character.
1369 uc32 c = ScanIdentifierUnicodeEscape();
1370 // Only allow legal identifier start characters.
1371 if (c < 0 ||
1372 c == '\\' || // No recursive escapes.
1373 !unicode_cache_->IsIdentifierStart(c)) {
1374 return Token::ILLEGAL;
1375 }
1376 AddLiteralChar(c);
1377 return ScanIdentifierSuffix(&literal, true);
1378 } else {
1379 uc32 first_char = c0_;
1380 Advance();
1381 AddLiteralChar(first_char);
1382 }
1383
1384 // Scan the rest of the identifier characters.
1385 while (c0_ >= 0 && unicode_cache_->IsIdentifierPart(c0_)) {
1386 if (c0_ != '\\') {
1387 uc32 next_char = c0_;
1388 Advance();
1389 AddLiteralChar(next_char);
1390 continue;
1391 }
1392 // Fallthrough if no longer able to complete keyword.
1393 return ScanIdentifierSuffix(&literal, false);
1394 }
1395
Ben Murdoch014dc512016-03-22 12:00:34 +00001396 if (next_.literal_chars->is_one_byte()) {
1397 Vector<const uint8_t> chars = next_.literal_chars->one_byte_literal();
Ben Murdochf91f0612016-11-29 16:50:11 +00001398 Token::Value token =
1399 KeywordOrIdentifierToken(chars.start(), chars.length());
1400 if (token == Token::IDENTIFIER) literal.Complete();
1401 return token;
Ben Murdoch014dc512016-03-22 12:00:34 +00001402 }
Ben Murdochf91f0612016-11-29 16:50:11 +00001403 literal.Complete();
Ben Murdoch014dc512016-03-22 12:00:34 +00001404 return Token::IDENTIFIER;
1405}
1406
1407
1408Token::Value Scanner::ScanIdentifierSuffix(LiteralScope* literal,
1409 bool escaped) {
1410 // Scan the rest of the identifier characters.
1411 while (c0_ >= 0 && unicode_cache_->IsIdentifierPart(c0_)) {
1412 if (c0_ == '\\') {
1413 uc32 c = ScanIdentifierUnicodeEscape();
1414 escaped = true;
1415 // Only allow legal identifier part characters.
1416 if (c < 0 ||
1417 c == '\\' ||
1418 !unicode_cache_->IsIdentifierPart(c)) {
1419 return Token::ILLEGAL;
1420 }
1421 AddLiteralChar(c);
1422 } else {
1423 AddLiteralChar(c0_);
1424 Advance();
1425 }
1426 }
1427 literal->Complete();
1428
1429 if (escaped && next_.literal_chars->is_one_byte()) {
1430 Vector<const uint8_t> chars = next_.literal_chars->one_byte_literal();
Ben Murdochf91f0612016-11-29 16:50:11 +00001431 Token::Value token =
1432 KeywordOrIdentifierToken(chars.start(), chars.length());
1433 /* TODO(adamk): YIELD should be handled specially. */
1434 if (token == Token::IDENTIFIER) {
1435 return Token::IDENTIFIER;
1436 } else if (token == Token::FUTURE_STRICT_RESERVED_WORD ||
1437 token == Token::LET || token == Token::STATIC) {
1438 return Token::ESCAPED_STRICT_RESERVED_WORD;
1439 } else {
1440 return Token::ESCAPED_KEYWORD;
1441 }
Ben Murdoch014dc512016-03-22 12:00:34 +00001442 }
1443 return Token::IDENTIFIER;
1444}
1445
Ben Murdochf91f0612016-11-29 16:50:11 +00001446bool Scanner::ScanRegExpPattern() {
1447 DCHECK(next_next_.token == Token::UNINITIALIZED);
1448 DCHECK(next_.token == Token::DIV || next_.token == Token::ASSIGN_DIV);
Ben Murdoch014dc512016-03-22 12:00:34 +00001449
Ben Murdoch014dc512016-03-22 12:00:34 +00001450 // Scan: ('/' | '/=') RegularExpressionBody '/' RegularExpressionFlags
1451 bool in_character_class = false;
Ben Murdochf91f0612016-11-29 16:50:11 +00001452 bool seen_equal = (next_.token == Token::ASSIGN_DIV);
Ben Murdoch014dc512016-03-22 12:00:34 +00001453
1454 // Previous token is either '/' or '/=', in the second case, the
1455 // pattern starts at =.
1456 next_.location.beg_pos = source_pos() - (seen_equal ? 2 : 1);
1457 next_.location.end_pos = source_pos() - (seen_equal ? 1 : 0);
1458
1459 // Scan regular expression body: According to ECMA-262, 3rd, 7.8.5,
1460 // the scanner should pass uninterpreted bodies to the RegExp
1461 // constructor.
1462 LiteralScope literal(this);
1463 if (seen_equal) {
1464 AddLiteralChar('=');
1465 }
1466
1467 while (c0_ != '/' || in_character_class) {
1468 if (c0_ < 0 || unicode_cache_->IsLineTerminator(c0_)) return false;
1469 if (c0_ == '\\') { // Escape sequence.
1470 AddLiteralCharAdvance();
1471 if (c0_ < 0 || unicode_cache_->IsLineTerminator(c0_)) return false;
1472 AddLiteralCharAdvance();
1473 // If the escape allows more characters, i.e., \x??, \u????, or \c?,
1474 // only "safe" characters are allowed (letters, digits, underscore),
1475 // otherwise the escape isn't valid and the invalid character has
1476 // its normal meaning. I.e., we can just continue scanning without
1477 // worrying whether the following characters are part of the escape
1478 // or not, since any '/', '\\' or '[' is guaranteed to not be part
1479 // of the escape sequence.
1480
1481 // TODO(896): At some point, parse RegExps more throughly to capture
1482 // octal esacpes in strict mode.
1483 } else { // Unescaped character.
1484 if (c0_ == '[') in_character_class = true;
1485 if (c0_ == ']') in_character_class = false;
1486 AddLiteralCharAdvance();
1487 }
1488 }
1489 Advance(); // consume '/'
1490
1491 literal.Complete();
Ben Murdochf91f0612016-11-29 16:50:11 +00001492 next_.token = Token::REGEXP_LITERAL;
Ben Murdoch014dc512016-03-22 12:00:34 +00001493 return true;
1494}
1495
1496
1497Maybe<RegExp::Flags> Scanner::ScanRegExpFlags() {
Ben Murdochf91f0612016-11-29 16:50:11 +00001498 DCHECK(next_.token == Token::REGEXP_LITERAL);
1499
Ben Murdoch014dc512016-03-22 12:00:34 +00001500 // Scan regular expression flags.
Ben Murdoch014dc512016-03-22 12:00:34 +00001501 int flags = 0;
1502 while (c0_ >= 0 && unicode_cache_->IsIdentifierPart(c0_)) {
1503 RegExp::Flags flag = RegExp::kNone;
1504 switch (c0_) {
1505 case 'g':
1506 flag = RegExp::kGlobal;
1507 break;
1508 case 'i':
1509 flag = RegExp::kIgnoreCase;
1510 break;
1511 case 'm':
1512 flag = RegExp::kMultiline;
1513 break;
1514 case 'u':
Ben Murdoch014dc512016-03-22 12:00:34 +00001515 flag = RegExp::kUnicode;
1516 break;
1517 case 'y':
Ben Murdoch014dc512016-03-22 12:00:34 +00001518 flag = RegExp::kSticky;
1519 break;
1520 default:
1521 return Nothing<RegExp::Flags>();
1522 }
Ben Murdochf91f0612016-11-29 16:50:11 +00001523 if (flags & flag) {
1524 return Nothing<RegExp::Flags>();
1525 }
1526 Advance();
Ben Murdoch014dc512016-03-22 12:00:34 +00001527 flags |= flag;
1528 }
Ben Murdoch014dc512016-03-22 12:00:34 +00001529
1530 next_.location.end_pos = source_pos();
1531 return Just(RegExp::Flags(flags));
1532}
1533
1534
1535const AstRawString* Scanner::CurrentSymbol(AstValueFactory* ast_value_factory) {
1536 if (is_literal_one_byte()) {
1537 return ast_value_factory->GetOneByteString(literal_one_byte_string());
1538 }
1539 return ast_value_factory->GetTwoByteString(literal_two_byte_string());
1540}
1541
1542
1543const AstRawString* Scanner::NextSymbol(AstValueFactory* ast_value_factory) {
1544 if (is_next_literal_one_byte()) {
1545 return ast_value_factory->GetOneByteString(next_literal_one_byte_string());
1546 }
1547 return ast_value_factory->GetTwoByteString(next_literal_two_byte_string());
1548}
1549
1550
1551const AstRawString* Scanner::CurrentRawSymbol(
1552 AstValueFactory* ast_value_factory) {
1553 if (is_raw_literal_one_byte()) {
1554 return ast_value_factory->GetOneByteString(raw_literal_one_byte_string());
1555 }
1556 return ast_value_factory->GetTwoByteString(raw_literal_two_byte_string());
1557}
1558
1559
1560double Scanner::DoubleValue() {
1561 DCHECK(is_literal_one_byte());
1562 return StringToDouble(
1563 unicode_cache_,
1564 literal_one_byte_string(),
1565 ALLOW_HEX | ALLOW_OCTAL | ALLOW_IMPLICIT_OCTAL | ALLOW_BINARY);
1566}
1567
1568
1569bool Scanner::ContainsDot() {
1570 DCHECK(is_literal_one_byte());
1571 Vector<const uint8_t> str = literal_one_byte_string();
1572 return std::find(str.begin(), str.end(), '.') != str.end();
1573}
1574
1575
1576int Scanner::FindSymbol(DuplicateFinder* finder, int value) {
1577 if (is_literal_one_byte()) {
1578 return finder->AddOneByteSymbol(literal_one_byte_string(), value);
1579 }
1580 return finder->AddTwoByteSymbol(literal_two_byte_string(), value);
1581}
1582
1583
1584bool Scanner::SetBookmark() {
1585 if (c0_ != kNoBookmark && bookmark_c0_ == kNoBookmark &&
1586 next_next_.token == Token::UNINITIALIZED && source_->SetBookmark()) {
1587 bookmark_c0_ = c0_;
1588 CopyTokenDesc(&bookmark_current_, &current_);
1589 CopyTokenDesc(&bookmark_next_, &next_);
1590 return true;
1591 }
1592 return false;
1593}
1594
1595
1596void Scanner::ResetToBookmark() {
1597 DCHECK(BookmarkHasBeenSet()); // Caller hasn't called SetBookmark.
1598
1599 source_->ResetToBookmark();
1600 c0_ = bookmark_c0_;
Ben Murdochf91f0612016-11-29 16:50:11 +00001601 CopyToNextTokenDesc(&bookmark_current_);
Ben Murdoch014dc512016-03-22 12:00:34 +00001602 current_ = next_;
Ben Murdochf91f0612016-11-29 16:50:11 +00001603 CopyToNextTokenDesc(&bookmark_next_);
Ben Murdoch014dc512016-03-22 12:00:34 +00001604 bookmark_c0_ = kBookmarkWasApplied;
1605}
1606
1607
1608bool Scanner::BookmarkHasBeenSet() { return bookmark_c0_ >= 0; }
1609
1610
1611bool Scanner::BookmarkHasBeenReset() {
1612 return bookmark_c0_ == kBookmarkWasApplied;
1613}
1614
1615
1616void Scanner::DropBookmark() { bookmark_c0_ = kNoBookmark; }
1617
Ben Murdochf91f0612016-11-29 16:50:11 +00001618void Scanner::CopyToNextTokenDesc(TokenDesc* from) {
1619 StartLiteral();
1620 StartRawLiteral();
1621 CopyTokenDesc(&next_, from);
1622 if (next_.literal_chars->length() == 0) next_.literal_chars = nullptr;
1623 if (next_.raw_literal_chars->length() == 0) next_.raw_literal_chars = nullptr;
1624}
Ben Murdoch014dc512016-03-22 12:00:34 +00001625
1626void Scanner::CopyTokenDesc(TokenDesc* to, TokenDesc* from) {
1627 DCHECK_NOT_NULL(to);
1628 DCHECK_NOT_NULL(from);
1629 to->token = from->token;
1630 to->location = from->location;
1631 to->literal_chars->CopyFrom(from->literal_chars);
1632 to->raw_literal_chars->CopyFrom(from->raw_literal_chars);
1633}
1634
1635
1636int DuplicateFinder::AddOneByteSymbol(Vector<const uint8_t> key, int value) {
1637 return AddSymbol(key, true, value);
1638}
1639
1640
1641int DuplicateFinder::AddTwoByteSymbol(Vector<const uint16_t> key, int value) {
1642 return AddSymbol(Vector<const uint8_t>::cast(key), false, value);
1643}
1644
1645
1646int DuplicateFinder::AddSymbol(Vector<const uint8_t> key,
1647 bool is_one_byte,
1648 int value) {
1649 uint32_t hash = Hash(key, is_one_byte);
1650 byte* encoding = BackupKey(key, is_one_byte);
Ben Murdoch13e2dad2016-09-16 13:49:30 +01001651 base::HashMap::Entry* entry = map_.LookupOrInsert(encoding, hash);
Ben Murdoch014dc512016-03-22 12:00:34 +00001652 int old_value = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
1653 entry->value =
1654 reinterpret_cast<void*>(static_cast<intptr_t>(value | old_value));
1655 return old_value;
1656}
1657
1658
1659int DuplicateFinder::AddNumber(Vector<const uint8_t> key, int value) {
1660 DCHECK(key.length() > 0);
1661 // Quick check for already being in canonical form.
1662 if (IsNumberCanonical(key)) {
1663 return AddOneByteSymbol(key, value);
1664 }
1665
1666 int flags = ALLOW_HEX | ALLOW_OCTAL | ALLOW_IMPLICIT_OCTAL | ALLOW_BINARY;
1667 double double_value = StringToDouble(
1668 unicode_constants_, key, flags, 0.0);
1669 int length;
1670 const char* string;
1671 if (!std::isfinite(double_value)) {
1672 string = "Infinity";
1673 length = 8; // strlen("Infinity");
1674 } else {
1675 string = DoubleToCString(double_value,
1676 Vector<char>(number_buffer_, kBufferSize));
1677 length = StrLength(string);
1678 }
1679 return AddSymbol(Vector<const byte>(reinterpret_cast<const byte*>(string),
1680 length), true, value);
1681}
1682
1683
1684bool DuplicateFinder::IsNumberCanonical(Vector<const uint8_t> number) {
1685 // Test for a safe approximation of number literals that are already
1686 // in canonical form: max 15 digits, no leading zeroes, except an
1687 // integer part that is a single zero, and no trailing zeros below
1688 // the decimal point.
1689 int pos = 0;
1690 int length = number.length();
1691 if (number.length() > 15) return false;
1692 if (number[pos] == '0') {
1693 pos++;
1694 } else {
1695 while (pos < length &&
1696 static_cast<unsigned>(number[pos] - '0') <= ('9' - '0')) pos++;
1697 }
1698 if (length == pos) return true;
1699 if (number[pos] != '.') return false;
1700 pos++;
1701 bool invalid_last_digit = true;
1702 while (pos < length) {
1703 uint8_t digit = number[pos] - '0';
1704 if (digit > '9' - '0') return false;
1705 invalid_last_digit = (digit == 0);
1706 pos++;
1707 }
1708 return !invalid_last_digit;
1709}
1710
1711
1712uint32_t DuplicateFinder::Hash(Vector<const uint8_t> key, bool is_one_byte) {
1713 // Primitive hash function, almost identical to the one used
1714 // for strings (except that it's seeded by the length and representation).
1715 int length = key.length();
1716 uint32_t hash = (length << 1) | (is_one_byte ? 1 : 0);
1717 for (int i = 0; i < length; i++) {
1718 uint32_t c = key[i];
1719 hash = (hash + c) * 1025;
1720 hash ^= (hash >> 6);
1721 }
1722 return hash;
1723}
1724
1725
1726bool DuplicateFinder::Match(void* first, void* second) {
1727 // Decode lengths.
1728 // Length + representation is encoded as base 128, most significant heptet
1729 // first, with a 8th bit being non-zero while there are more heptets.
1730 // The value encodes the number of bytes following, and whether the original
1731 // was Latin1.
1732 byte* s1 = reinterpret_cast<byte*>(first);
1733 byte* s2 = reinterpret_cast<byte*>(second);
1734 uint32_t length_one_byte_field = 0;
1735 byte c1;
1736 do {
1737 c1 = *s1;
1738 if (c1 != *s2) return false;
1739 length_one_byte_field = (length_one_byte_field << 7) | (c1 & 0x7f);
1740 s1++;
1741 s2++;
1742 } while ((c1 & 0x80) != 0);
1743 int length = static_cast<int>(length_one_byte_field >> 1);
1744 return memcmp(s1, s2, length) == 0;
1745}
1746
1747
1748byte* DuplicateFinder::BackupKey(Vector<const uint8_t> bytes,
1749 bool is_one_byte) {
1750 uint32_t one_byte_length = (bytes.length() << 1) | (is_one_byte ? 1 : 0);
1751 backing_store_.StartSequence();
1752 // Emit one_byte_length as base-128 encoded number, with the 7th bit set
1753 // on the byte of every heptet except the last, least significant, one.
1754 if (one_byte_length >= (1 << 7)) {
1755 if (one_byte_length >= (1 << 14)) {
1756 if (one_byte_length >= (1 << 21)) {
1757 if (one_byte_length >= (1 << 28)) {
1758 backing_store_.Add(
1759 static_cast<uint8_t>((one_byte_length >> 28) | 0x80));
1760 }
1761 backing_store_.Add(
1762 static_cast<uint8_t>((one_byte_length >> 21) | 0x80u));
1763 }
1764 backing_store_.Add(
1765 static_cast<uint8_t>((one_byte_length >> 14) | 0x80u));
1766 }
1767 backing_store_.Add(static_cast<uint8_t>((one_byte_length >> 7) | 0x80u));
1768 }
1769 backing_store_.Add(static_cast<uint8_t>(one_byte_length & 0x7f));
1770
1771 backing_store_.AddBlock(bytes);
1772 return backing_store_.EndSequence().start();
1773}
1774
1775} // namespace internal
1776} // namespace v8