1 // 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.
5 // Features shared by parsing and pre-parsing scanners.
13 #include "src/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/parser.h"
18 #include "src/scanner.h"
24 Handle<String> LiteralBuffer::Internalize(Isolate* isolate) const {
26 return isolate->factory()->InternalizeOneByteString(one_byte_literal());
28 return isolate->factory()->InternalizeTwoByteString(two_byte_literal());
32 // ----------------------------------------------------------------------------
35 Scanner::Scanner(UnicodeCache* unicode_cache)
36 : unicode_cache_(unicode_cache),
37 octal_pos_(Location::invalid()),
38 harmony_scoping_(false),
39 harmony_modules_(false),
40 harmony_numeric_literals_(false),
41 harmony_classes_(false),
42 harmony_templates_(false),
43 harmony_unicode_(false) {}
46 void Scanner::Initialize(Utf16CharacterStream* source) {
48 // Need to capture identifiers in order to recognize "get" and "set"
49 // in object literals.
51 // Skip initial whitespace allowing HTML comment ends just like
52 // after a newline and scan first token.
53 has_line_terminator_before_next_ = true;
59 template <bool capture_raw>
60 uc32 Scanner::ScanHexNumber(int expected_length) {
61 DCHECK(expected_length <= 4); // prevent overflow
64 for (int i = 0; i < expected_length; i++) {
65 int d = HexValue(c0_);
70 Advance<capture_raw>();
77 template <bool capture_raw>
78 uc32 Scanner::ScanUnlimitedLengthHexNumber(int max_value) {
80 int d = HexValue(c0_);
86 if (x > max_value) return -1;
87 Advance<capture_raw>();
94 // Ensure that tokens can be stored in a byte.
95 STATIC_ASSERT(Token::NUM_TOKENS <= 0x100);
97 // Table of one-character tokens, by character (0x00..0x7f only).
98 static const byte one_char_tokens[] = {
139 Token::LPAREN, // 0x28
140 Token::RPAREN, // 0x29
143 Token::COMMA, // 0x2c
157 Token::COLON, // 0x3a
158 Token::SEMICOLON, // 0x3b
162 Token::CONDITIONAL, // 0x3f
190 Token::LBRACK, // 0x5b
192 Token::RBRACK, // 0x5d
222 Token::LBRACE, // 0x7b
224 Token::RBRACE, // 0x7d
225 Token::BIT_NOT, // 0x7e
230 Token::Value Scanner::Next() {
232 has_line_terminator_before_next_ = false;
233 has_multiline_comment_before_next_ = false;
234 if (static_cast<unsigned>(c0_) <= 0x7f) {
235 Token::Value token = static_cast<Token::Value>(one_char_tokens[c0_]);
236 if (token != Token::ILLEGAL) {
237 int pos = source_pos();
239 next_.location.beg_pos = pos;
240 next_.location.end_pos = pos + 1;
242 return current_.token;
246 return current_.token;
250 // TODO(yangguo): check whether this is actually necessary.
251 static inline bool IsLittleEndianByteOrderMark(uc32 c) {
252 // The Unicode value U+FFFE is guaranteed never to be assigned as a
253 // Unicode character; this implies that in a Unicode context the
254 // 0xFF, 0xFE byte pattern can only be interpreted as the U+FEFF
255 // character expressed in little-endian byte order (since it could
256 // not be a U+FFFE character expressed in big-endian byte
257 // order). Nevertheless, we check for it to be compatible with
263 bool Scanner::SkipWhiteSpace() {
264 int start_position = source_pos();
268 // The unicode cache accepts unsigned inputs.
270 // Advance as long as character is a WhiteSpace or LineTerminator.
271 // Remember if the latter is the case.
272 if (unicode_cache_->IsLineTerminator(c0_)) {
273 has_line_terminator_before_next_ = true;
274 } else if (!unicode_cache_->IsWhiteSpace(c0_) &&
275 !IsLittleEndianByteOrderMark(c0_)) {
281 // If there is an HTML comment end '-->' at the beginning of a
282 // line (with only whitespace in front of it), we treat the rest
283 // of the line as a comment. This is in line with the way
284 // SpiderMonkey handles it.
285 if (c0_ == '-' && has_line_terminator_before_next_) {
290 // Treat the rest of the line as a comment.
291 SkipSingleLineComment();
292 // Continue skipping white space after the comment.
295 PushBack('-'); // undo Advance()
297 PushBack('-'); // undo Advance()
299 // Return whether or not we skipped any characters.
300 return source_pos() != start_position;
305 Token::Value Scanner::SkipSingleLineComment() {
308 // The line terminator at the end of the line is not considered
309 // to be part of the single-line comment; it is recognized
310 // separately by the lexical grammar and becomes part of the
311 // stream of input elements for the syntactic grammar (see
312 // ECMA-262, section 7.4).
313 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
317 return Token::WHITESPACE;
321 Token::Value Scanner::SkipSourceURLComment() {
322 TryToParseSourceURLComment();
323 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
327 return Token::WHITESPACE;
331 void Scanner::TryToParseSourceURLComment() {
332 // Magic comments are of the form: //[#@]\s<name>=\s*<value>\s*.* and this
333 // function will just return if it cannot parse a magic comment.
334 if (c0_ < 0 || !unicode_cache_->IsWhiteSpace(c0_)) return;
337 while (c0_ >= 0 && !unicode_cache_->IsWhiteSpaceOrLineTerminator(c0_) &&
342 if (!name.is_one_byte()) return;
343 Vector<const uint8_t> name_literal = name.one_byte_literal();
344 LiteralBuffer* value;
345 if (name_literal == STATIC_CHAR_VECTOR("sourceURL")) {
346 value = &source_url_;
347 } else if (name_literal == STATIC_CHAR_VECTOR("sourceMappingURL")) {
348 value = &source_mapping_url_;
356 while (c0_ >= 0 && unicode_cache_->IsWhiteSpace(c0_)) {
359 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
360 // Disallowed characters.
361 if (c0_ == '"' || c0_ == '\'') {
365 if (unicode_cache_->IsWhiteSpace(c0_)) {
371 // Allow whitespace at the end.
372 while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) {
373 if (!unicode_cache_->IsWhiteSpace(c0_)) {
382 Token::Value Scanner::SkipMultiLineComment() {
389 if (c0_ >= 0 && unicode_cache_->IsLineTerminator(ch)) {
390 // Following ECMA-262, section 7.4, a comment containing
391 // a newline will make the comment count as a line-terminator.
392 has_multiline_comment_before_next_ = true;
394 // If we have reached the end of the multi-line comment, we
395 // consume the '/' and insert a whitespace. This way all
396 // multi-line comments are treated as whitespace.
397 if (ch == '*' && c0_ == '/') {
399 return Token::WHITESPACE;
403 // Unterminated multi-line comment.
404 return Token::ILLEGAL;
408 Token::Value Scanner::ScanHtmlComment() {
409 // Check for <!-- comments.
414 if (c0_ == '-') return SkipSingleLineComment();
415 PushBack('-'); // undo Advance()
417 PushBack('!'); // undo Advance()
423 void Scanner::Scan() {
424 next_.literal_chars = NULL;
425 next_.raw_literal_chars = NULL;
428 // Remember the position of the next token
429 next_.location.beg_pos = source_pos();
435 token = Token::WHITESPACE;
440 has_line_terminator_before_next_ = true;
441 token = Token::WHITESPACE;
445 token = ScanString();
452 token = Select(Token::LTE);
453 } else if (c0_ == '<') {
454 token = Select('=', Token::ASSIGN_SHL, Token::SHL);
455 } else if (c0_ == '!') {
456 token = ScanHtmlComment();
463 // > >= >> >>= >>> >>>=
466 token = Select(Token::GTE);
467 } else if (c0_ == '>') {
471 token = Select(Token::ASSIGN_SAR);
472 } else if (c0_ == '>') {
473 token = Select('=', Token::ASSIGN_SHR, Token::SHR);
486 token = Select('=', Token::EQ_STRICT, Token::EQ);
487 } else if (c0_ == '>') {
488 token = Select(Token::ARROW);
490 token = Token::ASSIGN;
498 token = Select('=', Token::NE_STRICT, Token::NE);
508 token = Select(Token::INC);
509 } else if (c0_ == '=') {
510 token = Select(Token::ASSIGN_ADD);
521 if (c0_ == '>' && has_line_terminator_before_next_) {
522 // For compatibility with SpiderMonkey, we skip lines that
523 // start with an HTML comment end '-->'.
524 token = SkipSingleLineComment();
528 } else if (c0_ == '=') {
529 token = Select(Token::ASSIGN_SUB);
537 token = Select('=', Token::ASSIGN_MUL, Token::MUL);
542 token = Select('=', Token::ASSIGN_MOD, Token::MOD);
550 if (c0_ == '@' || c0_ == '#') {
552 token = SkipSourceURLComment();
555 token = SkipSingleLineComment();
557 } else if (c0_ == '*') {
558 token = SkipMultiLineComment();
559 } else if (c0_ == '=') {
560 token = Select(Token::ASSIGN_DIV);
570 token = Select(Token::AND);
571 } else if (c0_ == '=') {
572 token = Select(Token::ASSIGN_BIT_AND);
574 token = Token::BIT_AND;
582 token = Select(Token::OR);
583 } else if (c0_ == '=') {
584 token = Select(Token::ASSIGN_BIT_OR);
586 token = Token::BIT_OR;
592 token = Select('=', Token::ASSIGN_BIT_XOR, Token::BIT_XOR);
598 if (IsDecimalDigit(c0_)) {
599 token = ScanNumber(true);
601 token = Token::PERIOD;
606 token = Token::ELLIPSIS;
615 token = Select(Token::COLON);
619 token = Select(Token::SEMICOLON);
623 token = Select(Token::COMMA);
627 token = Select(Token::LPAREN);
631 token = Select(Token::RPAREN);
635 token = Select(Token::LBRACK);
639 token = Select(Token::RBRACK);
643 token = Select(Token::LBRACE);
647 token = Select(Token::RBRACE);
651 token = Select(Token::CONDITIONAL);
655 token = Select(Token::BIT_NOT);
659 if (HarmonyTemplates()) {
660 token = ScanTemplateStart();
667 } else if (unicode_cache_->IsIdentifierStart(c0_)) {
668 token = ScanIdentifierOrKeyword();
669 } else if (IsDecimalDigit(c0_)) {
670 token = ScanNumber(false);
671 } else if (SkipWhiteSpace()) {
672 token = Token::WHITESPACE;
674 token = Select(Token::ILLEGAL);
679 // Continue scanning for tokens as long as we're just skipping
681 } while (token == Token::WHITESPACE);
683 next_.location.end_pos = source_pos();
688 void Scanner::SeekForward(int pos) {
689 // After this call, we will have the token at the given position as
690 // the "next" token. The "current" token will be invalid.
691 if (pos == next_.location.beg_pos) return;
692 int current_pos = source_pos();
693 DCHECK_EQ(next_.location.end_pos, current_pos);
694 // Positions inside the lookahead token aren't supported.
695 DCHECK(pos >= current_pos);
696 if (pos != current_pos) {
697 source_->SeekForward(pos - source_->pos());
699 // This function is only called to seek to the location
700 // of the end of a function (at the "}" token). It doesn't matter
701 // whether there was a line terminator in the part we skip.
702 has_line_terminator_before_next_ = false;
703 has_multiline_comment_before_next_ = false;
709 template <bool capture_raw, bool in_template_literal>
710 bool Scanner::ScanEscape() {
712 Advance<capture_raw>();
714 // Skip escaped newlines.
715 if (!in_template_literal && c0_ >= 0 && unicode_cache_->IsLineTerminator(c)) {
716 // Allow CR+LF newlines in multiline string literals.
717 if (IsCarriageReturn(c) && IsLineFeed(c0_)) Advance<capture_raw>();
718 // Allow LF+CR newlines in multiline string literals.
719 if (IsLineFeed(c) && IsCarriageReturn(c0_)) Advance<capture_raw>();
724 case '\'': // fall through
725 case '"' : // fall through
727 case 'b' : c = '\b'; break;
728 case 'f' : c = '\f'; break;
729 case 'n' : c = '\n'; break;
730 case 'r' : c = '\r'; break;
731 case 't' : c = '\t'; break;
733 c = ScanUnicodeEscape<capture_raw>();
734 if (c < 0) return false;
741 c = ScanHexNumber<capture_raw>(2);
742 if (c < 0) return false;
745 case '0': // Fall through.
746 case '1': // fall through
747 case '2': // fall through
748 case '3': // fall through
749 case '4': // fall through
750 case '5': // fall through
751 case '6': // fall through
753 c = ScanOctalEscape<capture_raw>(c, 2);
757 // According to ECMA-262, section 7.8.4, characters not covered by the
758 // above cases should be illegal, but they are commonly handled as
759 // non-escaped characters by JS VMs.
765 // Octal escapes of the forms '\0xx' and '\xxx' are not a part of
766 // ECMA-262. Other JS VMs support them.
767 template <bool capture_raw>
768 uc32 Scanner::ScanOctalEscape(uc32 c, int length) {
771 for (; i < length; i++) {
773 if (d < 0 || d > 7) break;
775 if (nx >= 256) break;
777 Advance<capture_raw>();
779 // Anything except '\0' is an octal escape sequence, illegal in strict mode.
780 // Remember the position of octal escape sequences so that an error
781 // can be reported later (in strict mode).
782 // We don't report the error immediately, because the octal escape can
783 // occur before the "use strict" directive.
784 if (c != '0' || i > 0) {
785 octal_pos_ = Location(source_pos() - i - 1, source_pos() - 1);
791 Token::Value Scanner::ScanString() {
793 Advance(); // consume quote
795 LiteralScope literal(this);
796 while (c0_ != quote && c0_ >= 0
797 && !unicode_cache_->IsLineTerminator(c0_)) {
801 if (c0_ < 0 || !ScanEscape<false, false>()) return Token::ILLEGAL;
806 if (c0_ != quote) return Token::ILLEGAL;
809 Advance(); // consume quote
810 return Token::STRING;
814 Token::Value Scanner::ScanTemplateSpan() {
815 // When scanning a TemplateSpan, we are looking for the following construct:
817 // ` LiteralChars* ${
818 // | } LiteralChars* ${
822 // | } LiteralChar* `
824 // A TEMPLATE_SPAN should always be followed by an Expression, while a
825 // TEMPLATE_TAIL terminates a TemplateLiteral and does not need to be
826 // followed by an Expression.
828 Token::Value result = Token::TEMPLATE_SPAN;
829 LiteralScope literal(this);
831 const bool capture_raw = true;
832 const bool in_template_literal = true;
836 Advance<capture_raw>();
838 result = Token::TEMPLATE_TAIL;
839 ReduceRawLiteralLength(1);
841 } else if (c == '$' && c0_ == '{') {
842 Advance<capture_raw>(); // Consume '{'
843 ReduceRawLiteralLength(2);
845 } else if (c == '\\') {
846 if (c0_ > 0 && unicode_cache_->IsLineTerminator(c0_)) {
847 // The TV of LineContinuation :: \ LineTerminatorSequence is the empty
848 // code unit sequence.
850 Advance<capture_raw>();
851 if (lastChar == '\r') {
852 ReduceRawLiteralLength(1); // Remove \r
854 Advance<capture_raw>(); // Adds \n
856 AddRawLiteralChar('\n');
859 } else if (!ScanEscape<capture_raw, in_template_literal>()) {
860 return Token::ILLEGAL;
863 // Unterminated template literal
867 // The TRV of LineTerminatorSequence :: <CR> is the CV 0x000A.
868 // The TRV of LineTerminatorSequence :: <CR><LF> is the sequence
869 // consisting of the CV 0x000A.
871 ReduceRawLiteralLength(1); // Remove \r
873 Advance<capture_raw>(); // Adds \n
875 AddRawLiteralChar('\n');
883 next_.location.end_pos = source_pos();
884 next_.token = result;
889 Token::Value Scanner::ScanTemplateStart() {
891 next_.location.beg_pos = source_pos();
892 Advance(); // Consume `
893 return ScanTemplateSpan();
897 Token::Value Scanner::ScanTemplateContinuation() {
898 DCHECK_EQ(next_.token, Token::RBRACE);
899 next_.location.beg_pos = source_pos() - 1; // We already consumed }
900 return ScanTemplateSpan();
904 void Scanner::ScanDecimalDigits() {
905 while (IsDecimalDigit(c0_))
906 AddLiteralCharAdvance();
910 Token::Value Scanner::ScanNumber(bool seen_period) {
911 DCHECK(IsDecimalDigit(c0_)); // the first digit of the number or the fraction
913 enum { DECIMAL, HEX, OCTAL, IMPLICIT_OCTAL, BINARY } kind = DECIMAL;
915 LiteralScope literal(this);
917 // we have already seen a decimal point of the float
919 ScanDecimalDigits(); // we know we have at least one digit
922 // if the first character is '0' we must check for octals and hex
924 int start_pos = source_pos(); // For reporting octal positions.
925 AddLiteralCharAdvance();
927 // either 0, 0exxx, 0Exxx, 0.xxx, a hex number, a binary number or
929 if (c0_ == 'x' || c0_ == 'X') {
932 AddLiteralCharAdvance();
933 if (!IsHexDigit(c0_)) {
934 // we must have at least one hex digit after 'x'/'X'
935 return Token::ILLEGAL;
937 while (IsHexDigit(c0_)) {
938 AddLiteralCharAdvance();
940 } else if (harmony_numeric_literals_ && (c0_ == 'o' || c0_ == 'O')) {
942 AddLiteralCharAdvance();
943 if (!IsOctalDigit(c0_)) {
944 // we must have at least one octal digit after 'o'/'O'
945 return Token::ILLEGAL;
947 while (IsOctalDigit(c0_)) {
948 AddLiteralCharAdvance();
950 } else if (harmony_numeric_literals_ && (c0_ == 'b' || c0_ == 'B')) {
952 AddLiteralCharAdvance();
953 if (!IsBinaryDigit(c0_)) {
954 // we must have at least one binary digit after 'b'/'B'
955 return Token::ILLEGAL;
957 while (IsBinaryDigit(c0_)) {
958 AddLiteralCharAdvance();
960 } else if ('0' <= c0_ && c0_ <= '7') {
961 // (possible) octal number
962 kind = IMPLICIT_OCTAL;
964 if (c0_ == '8' || c0_ == '9') {
968 if (c0_ < '0' || '7' < c0_) {
969 // Octal literal finished.
970 octal_pos_ = Location(start_pos, source_pos());
973 AddLiteralCharAdvance();
978 // Parse decimal digits and allow trailing fractional part.
979 if (kind == DECIMAL) {
980 ScanDecimalDigits(); // optional
982 AddLiteralCharAdvance();
983 ScanDecimalDigits(); // optional
988 // scan exponent, if any
989 if (c0_ == 'e' || c0_ == 'E') {
990 DCHECK(kind != HEX); // 'e'/'E' must be scanned as part of the hex number
991 if (kind != DECIMAL) return Token::ILLEGAL;
993 AddLiteralCharAdvance();
994 if (c0_ == '+' || c0_ == '-')
995 AddLiteralCharAdvance();
996 if (!IsDecimalDigit(c0_)) {
997 // we must have at least one decimal digit after 'e'/'E'
998 return Token::ILLEGAL;
1000 ScanDecimalDigits();
1003 // The source character immediately following a numeric literal must
1004 // not be an identifier start or a decimal digit; see ECMA-262
1005 // section 7.8.3, page 17 (note that we read only one decimal digit
1006 // if the value is 0).
1007 if (IsDecimalDigit(c0_) ||
1008 (c0_ >= 0 && unicode_cache_->IsIdentifierStart(c0_)))
1009 return Token::ILLEGAL;
1013 return Token::NUMBER;
1017 uc32 Scanner::ScanIdentifierUnicodeEscape() {
1019 if (c0_ != 'u') return -1;
1021 return ScanUnicodeEscape<false>();
1025 template <bool capture_raw>
1026 uc32 Scanner::ScanUnicodeEscape() {
1027 // Accept both \uxxxx and \u{xxxxxx} (if harmony unicode escapes are
1028 // allowed). In the latter case, the number of hex digits between { } is
1029 // arbitrary. \ and u have already been read.
1030 if (c0_ == '{' && HarmonyUnicode()) {
1031 Advance<capture_raw>();
1032 uc32 cp = ScanUnlimitedLengthHexNumber<capture_raw>(0x10ffff);
1039 Advance<capture_raw>();
1042 return ScanHexNumber<capture_raw>(4);
1046 // ----------------------------------------------------------------------------
1049 #define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
1050 KEYWORD_GROUP('b') \
1051 KEYWORD("break", Token::BREAK) \
1052 KEYWORD_GROUP('c') \
1053 KEYWORD("case", Token::CASE) \
1054 KEYWORD("catch", Token::CATCH) \
1056 harmony_classes ? Token::CLASS : Token::FUTURE_RESERVED_WORD) \
1057 KEYWORD("const", Token::CONST) \
1058 KEYWORD("continue", Token::CONTINUE) \
1059 KEYWORD_GROUP('d') \
1060 KEYWORD("debugger", Token::DEBUGGER) \
1061 KEYWORD("default", Token::DEFAULT) \
1062 KEYWORD("delete", Token::DELETE) \
1063 KEYWORD("do", Token::DO) \
1064 KEYWORD_GROUP('e') \
1065 KEYWORD("else", Token::ELSE) \
1066 KEYWORD("enum", Token::FUTURE_RESERVED_WORD) \
1068 harmony_modules ? Token::EXPORT : Token::FUTURE_RESERVED_WORD) \
1069 KEYWORD("extends", \
1070 harmony_classes ? Token::EXTENDS : Token::FUTURE_RESERVED_WORD) \
1071 KEYWORD_GROUP('f') \
1072 KEYWORD("false", Token::FALSE_LITERAL) \
1073 KEYWORD("finally", Token::FINALLY) \
1074 KEYWORD("for", Token::FOR) \
1075 KEYWORD("function", Token::FUNCTION) \
1076 KEYWORD_GROUP('i') \
1077 KEYWORD("if", Token::IF) \
1078 KEYWORD("implements", Token::FUTURE_STRICT_RESERVED_WORD) \
1080 harmony_modules ? Token::IMPORT : Token::FUTURE_RESERVED_WORD) \
1081 KEYWORD("in", Token::IN) \
1082 KEYWORD("instanceof", Token::INSTANCEOF) \
1083 KEYWORD("interface", Token::FUTURE_STRICT_RESERVED_WORD) \
1084 KEYWORD_GROUP('l') \
1086 harmony_scoping ? Token::LET : Token::FUTURE_STRICT_RESERVED_WORD) \
1087 KEYWORD_GROUP('n') \
1088 KEYWORD("new", Token::NEW) \
1089 KEYWORD("null", Token::NULL_LITERAL) \
1090 KEYWORD_GROUP('p') \
1091 KEYWORD("package", Token::FUTURE_STRICT_RESERVED_WORD) \
1092 KEYWORD("private", Token::FUTURE_STRICT_RESERVED_WORD) \
1093 KEYWORD("protected", Token::FUTURE_STRICT_RESERVED_WORD) \
1094 KEYWORD("public", Token::FUTURE_STRICT_RESERVED_WORD) \
1095 KEYWORD_GROUP('r') \
1096 KEYWORD("return", Token::RETURN) \
1097 KEYWORD_GROUP('s') \
1098 KEYWORD("static", harmony_classes ? Token::STATIC \
1099 : Token::FUTURE_STRICT_RESERVED_WORD) \
1101 harmony_classes ? Token::SUPER : Token::FUTURE_RESERVED_WORD) \
1102 KEYWORD("switch", Token::SWITCH) \
1103 KEYWORD_GROUP('t') \
1104 KEYWORD("this", Token::THIS) \
1105 KEYWORD("throw", Token::THROW) \
1106 KEYWORD("true", Token::TRUE_LITERAL) \
1107 KEYWORD("try", Token::TRY) \
1108 KEYWORD("typeof", Token::TYPEOF) \
1109 KEYWORD_GROUP('v') \
1110 KEYWORD("var", Token::VAR) \
1111 KEYWORD("void", Token::VOID) \
1112 KEYWORD_GROUP('w') \
1113 KEYWORD("while", Token::WHILE) \
1114 KEYWORD("with", Token::WITH) \
1115 KEYWORD_GROUP('y') \
1116 KEYWORD("yield", Token::YIELD)
1119 static Token::Value KeywordOrIdentifierToken(const uint8_t* input,
1121 bool harmony_scoping,
1122 bool harmony_modules,
1123 bool harmony_classes) {
1124 DCHECK(input_length >= 1);
1125 const int kMinLength = 2;
1126 const int kMaxLength = 10;
1127 if (input_length < kMinLength || input_length > kMaxLength) {
1128 return Token::IDENTIFIER;
1132 #define KEYWORD_GROUP_CASE(ch) \
1135 #define KEYWORD(keyword, token) \
1137 /* 'keyword' is a char array, so sizeof(keyword) is */ \
1138 /* strlen(keyword) plus 1 for the NUL char. */ \
1139 const int keyword_length = sizeof(keyword) - 1; \
1140 STATIC_ASSERT(keyword_length >= kMinLength); \
1141 STATIC_ASSERT(keyword_length <= kMaxLength); \
1142 if (input_length == keyword_length && \
1143 input[1] == keyword[1] && \
1144 (keyword_length <= 2 || input[2] == keyword[2]) && \
1145 (keyword_length <= 3 || input[3] == keyword[3]) && \
1146 (keyword_length <= 4 || input[4] == keyword[4]) && \
1147 (keyword_length <= 5 || input[5] == keyword[5]) && \
1148 (keyword_length <= 6 || input[6] == keyword[6]) && \
1149 (keyword_length <= 7 || input[7] == keyword[7]) && \
1150 (keyword_length <= 8 || input[8] == keyword[8]) && \
1151 (keyword_length <= 9 || input[9] == keyword[9])) { \
1155 KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
1157 return Token::IDENTIFIER;
1161 bool Scanner::IdentifierIsFutureStrictReserved(
1162 const AstRawString* string) const {
1163 // Keywords are always 1-byte strings.
1164 if (!string->is_one_byte()) return false;
1165 if (string->IsOneByteEqualTo("let") || string->IsOneByteEqualTo("static") ||
1166 string->IsOneByteEqualTo("yield")) {
1169 return Token::FUTURE_STRICT_RESERVED_WORD ==
1170 KeywordOrIdentifierToken(string->raw_data(), string->length(),
1171 harmony_scoping_, harmony_modules_,
1176 Token::Value Scanner::ScanIdentifierOrKeyword() {
1177 DCHECK(unicode_cache_->IsIdentifierStart(c0_));
1178 LiteralScope literal(this);
1179 // Scan identifier start character.
1181 uc32 c = ScanIdentifierUnicodeEscape();
1182 // Only allow legal identifier start characters.
1184 c == '\\' || // No recursive escapes.
1185 !unicode_cache_->IsIdentifierStart(c)) {
1186 return Token::ILLEGAL;
1189 return ScanIdentifierSuffix(&literal);
1192 uc32 first_char = c0_;
1194 AddLiteralChar(first_char);
1196 // Scan the rest of the identifier characters.
1197 while (c0_ >= 0 && unicode_cache_->IsIdentifierPart(c0_)) {
1199 uc32 next_char = c0_;
1201 AddLiteralChar(next_char);
1204 // Fallthrough if no longer able to complete keyword.
1205 return ScanIdentifierSuffix(&literal);
1210 if (next_.literal_chars->is_one_byte()) {
1211 Vector<const uint8_t> chars = next_.literal_chars->one_byte_literal();
1212 return KeywordOrIdentifierToken(chars.start(),
1219 return Token::IDENTIFIER;
1223 Token::Value Scanner::ScanIdentifierSuffix(LiteralScope* literal) {
1224 // Scan the rest of the identifier characters.
1225 while (c0_ >= 0 && unicode_cache_->IsIdentifierPart(c0_)) {
1227 uc32 c = ScanIdentifierUnicodeEscape();
1228 // Only allow legal identifier part characters.
1231 !unicode_cache_->IsIdentifierPart(c)) {
1232 return Token::ILLEGAL;
1236 AddLiteralChar(c0_);
1240 literal->Complete();
1242 return Token::IDENTIFIER;
1246 bool Scanner::ScanRegExpPattern(bool seen_equal) {
1247 // Scan: ('/' | '/=') RegularExpressionBody '/' RegularExpressionFlags
1248 bool in_character_class = false;
1250 // Previous token is either '/' or '/=', in the second case, the
1251 // pattern starts at =.
1252 next_.location.beg_pos = source_pos() - (seen_equal ? 2 : 1);
1253 next_.location.end_pos = source_pos() - (seen_equal ? 1 : 0);
1255 // Scan regular expression body: According to ECMA-262, 3rd, 7.8.5,
1256 // the scanner should pass uninterpreted bodies to the RegExp
1258 LiteralScope literal(this);
1260 AddLiteralChar('=');
1263 while (c0_ != '/' || in_character_class) {
1264 if (c0_ < 0 || unicode_cache_->IsLineTerminator(c0_)) return false;
1265 if (c0_ == '\\') { // Escape sequence.
1266 AddLiteralCharAdvance();
1267 if (c0_ < 0 || unicode_cache_->IsLineTerminator(c0_)) return false;
1268 AddLiteralCharAdvance();
1269 // If the escape allows more characters, i.e., \x??, \u????, or \c?,
1270 // only "safe" characters are allowed (letters, digits, underscore),
1271 // otherwise the escape isn't valid and the invalid character has
1272 // its normal meaning. I.e., we can just continue scanning without
1273 // worrying whether the following characters are part of the escape
1274 // or not, since any '/', '\\' or '[' is guaranteed to not be part
1275 // of the escape sequence.
1277 // TODO(896): At some point, parse RegExps more throughly to capture
1278 // octal esacpes in strict mode.
1279 } else { // Unescaped character.
1280 if (c0_ == '[') in_character_class = true;
1281 if (c0_ == ']') in_character_class = false;
1282 AddLiteralCharAdvance();
1285 Advance(); // consume '/'
1293 bool Scanner::ScanRegExpFlags() {
1294 // Scan regular expression flags.
1295 LiteralScope literal(this);
1296 while (c0_ >= 0 && unicode_cache_->IsIdentifierPart(c0_)) {
1298 AddLiteralCharAdvance();
1305 next_.location.end_pos = source_pos() - 1;
1310 const AstRawString* Scanner::CurrentSymbol(AstValueFactory* ast_value_factory) {
1311 if (is_literal_one_byte()) {
1312 return ast_value_factory->GetOneByteString(literal_one_byte_string());
1314 return ast_value_factory->GetTwoByteString(literal_two_byte_string());
1318 const AstRawString* Scanner::NextSymbol(AstValueFactory* ast_value_factory) {
1319 if (is_next_literal_one_byte()) {
1320 return ast_value_factory->GetOneByteString(next_literal_one_byte_string());
1322 return ast_value_factory->GetTwoByteString(next_literal_two_byte_string());
1326 const AstRawString* Scanner::CurrentRawSymbol(
1327 AstValueFactory* ast_value_factory) {
1328 if (is_raw_literal_one_byte()) {
1329 return ast_value_factory->GetOneByteString(raw_literal_one_byte_string());
1331 return ast_value_factory->GetTwoByteString(raw_literal_two_byte_string());
1335 double Scanner::DoubleValue() {
1336 DCHECK(is_literal_one_byte());
1337 return StringToDouble(
1339 literal_one_byte_string(),
1340 ALLOW_HEX | ALLOW_OCTAL | ALLOW_IMPLICIT_OCTAL | ALLOW_BINARY);
1344 int Scanner::FindNumber(DuplicateFinder* finder, int value) {
1345 return finder->AddNumber(literal_one_byte_string(), value);
1349 int Scanner::FindSymbol(DuplicateFinder* finder, int value) {
1350 if (is_literal_one_byte()) {
1351 return finder->AddOneByteSymbol(literal_one_byte_string(), value);
1353 return finder->AddTwoByteSymbol(literal_two_byte_string(), value);
1357 int DuplicateFinder::AddOneByteSymbol(Vector<const uint8_t> key, int value) {
1358 return AddSymbol(key, true, value);
1362 int DuplicateFinder::AddTwoByteSymbol(Vector<const uint16_t> key, int value) {
1363 return AddSymbol(Vector<const uint8_t>::cast(key), false, value);
1367 int DuplicateFinder::AddSymbol(Vector<const uint8_t> key,
1370 uint32_t hash = Hash(key, is_one_byte);
1371 byte* encoding = BackupKey(key, is_one_byte);
1372 HashMap::Entry* entry = map_.Lookup(encoding, hash, true);
1373 int old_value = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
1375 reinterpret_cast<void*>(static_cast<intptr_t>(value | old_value));
1380 int DuplicateFinder::AddNumber(Vector<const uint8_t> key, int value) {
1381 DCHECK(key.length() > 0);
1382 // Quick check for already being in canonical form.
1383 if (IsNumberCanonical(key)) {
1384 return AddOneByteSymbol(key, value);
1387 int flags = ALLOW_HEX | ALLOW_OCTAL | ALLOW_IMPLICIT_OCTAL | ALLOW_BINARY;
1388 double double_value = StringToDouble(
1389 unicode_constants_, key, flags, 0.0);
1392 if (!std::isfinite(double_value)) {
1393 string = "Infinity";
1394 length = 8; // strlen("Infinity");
1396 string = DoubleToCString(double_value,
1397 Vector<char>(number_buffer_, kBufferSize));
1398 length = StrLength(string);
1400 return AddSymbol(Vector<const byte>(reinterpret_cast<const byte*>(string),
1401 length), true, value);
1405 bool DuplicateFinder::IsNumberCanonical(Vector<const uint8_t> number) {
1406 // Test for a safe approximation of number literals that are already
1407 // in canonical form: max 15 digits, no leading zeroes, except an
1408 // integer part that is a single zero, and no trailing zeros below
1409 // the decimal point.
1411 int length = number.length();
1412 if (number.length() > 15) return false;
1413 if (number[pos] == '0') {
1416 while (pos < length &&
1417 static_cast<unsigned>(number[pos] - '0') <= ('9' - '0')) pos++;
1419 if (length == pos) return true;
1420 if (number[pos] != '.') return false;
1422 bool invalid_last_digit = true;
1423 while (pos < length) {
1424 uint8_t digit = number[pos] - '0';
1425 if (digit > '9' - '0') return false;
1426 invalid_last_digit = (digit == 0);
1429 return !invalid_last_digit;
1433 uint32_t DuplicateFinder::Hash(Vector<const uint8_t> key, bool is_one_byte) {
1434 // Primitive hash function, almost identical to the one used
1435 // for strings (except that it's seeded by the length and representation).
1436 int length = key.length();
1437 uint32_t hash = (length << 1) | (is_one_byte ? 1 : 0) ;
1438 for (int i = 0; i < length; i++) {
1439 uint32_t c = key[i];
1440 hash = (hash + c) * 1025;
1441 hash ^= (hash >> 6);
1447 bool DuplicateFinder::Match(void* first, void* second) {
1449 // Length + representation is encoded as base 128, most significant heptet
1450 // first, with a 8th bit being non-zero while there are more heptets.
1451 // The value encodes the number of bytes following, and whether the original
1453 byte* s1 = reinterpret_cast<byte*>(first);
1454 byte* s2 = reinterpret_cast<byte*>(second);
1455 uint32_t length_one_byte_field = 0;
1459 if (c1 != *s2) return false;
1460 length_one_byte_field = (length_one_byte_field << 7) | (c1 & 0x7f);
1463 } while ((c1 & 0x80) != 0);
1464 int length = static_cast<int>(length_one_byte_field >> 1);
1465 return memcmp(s1, s2, length) == 0;
1469 byte* DuplicateFinder::BackupKey(Vector<const uint8_t> bytes,
1471 uint32_t one_byte_length = (bytes.length() << 1) | (is_one_byte ? 1 : 0);
1472 backing_store_.StartSequence();
1473 // Emit one_byte_length as base-128 encoded number, with the 7th bit set
1474 // on the byte of every heptet except the last, least significant, one.
1475 if (one_byte_length >= (1 << 7)) {
1476 if (one_byte_length >= (1 << 14)) {
1477 if (one_byte_length >= (1 << 21)) {
1478 if (one_byte_length >= (1 << 28)) {
1480 static_cast<uint8_t>((one_byte_length >> 28) | 0x80));
1483 static_cast<uint8_t>((one_byte_length >> 21) | 0x80u));
1486 static_cast<uint8_t>((one_byte_length >> 14) | 0x80u));
1488 backing_store_.Add(static_cast<uint8_t>((one_byte_length >> 7) | 0x80u));
1490 backing_store_.Add(static_cast<uint8_t>(one_byte_length & 0x7f));
1492 backing_store_.AddBlock(bytes);
1493 return backing_store_.EndSequence().start();
1496 } } // namespace v8::internal