1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
|
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Features shared by parsing and pre-parsing scanners.
#include "src/parsing/scanner.h"
#include <stdint.h>
#include <cmath>
#include "src/ast/ast-value-factory.h"
#include "src/numbers/conversions-inl.h"
#include "src/objects/bigint.h"
#include "src/parsing/scanner-inl.h"
#include "src/zone/zone.h"
namespace v8 {
namespace internal {
class Scanner::ErrorState {
public:
ErrorState(MessageTemplate* message_stack, Scanner::Location* location_stack)
: message_stack_(message_stack),
old_message_(*message_stack),
location_stack_(location_stack),
old_location_(*location_stack) {
*message_stack_ = MessageTemplate::kNone;
*location_stack_ = Location::invalid();
}
~ErrorState() {
*message_stack_ = old_message_;
*location_stack_ = old_location_;
}
void MoveErrorTo(TokenDesc* dest) {
if (*message_stack_ == MessageTemplate::kNone) {
return;
}
if (dest->invalid_template_escape_message == MessageTemplate::kNone) {
dest->invalid_template_escape_message = *message_stack_;
dest->invalid_template_escape_location = *location_stack_;
}
*message_stack_ = MessageTemplate::kNone;
*location_stack_ = Location::invalid();
}
private:
MessageTemplate* const message_stack_;
MessageTemplate const old_message_;
Scanner::Location* const location_stack_;
Scanner::Location const old_location_;
};
// ----------------------------------------------------------------------------
// Scanner::BookmarkScope
const size_t Scanner::BookmarkScope::kNoBookmark =
std::numeric_limits<size_t>::max() - 1;
const size_t Scanner::BookmarkScope::kBookmarkWasApplied =
std::numeric_limits<size_t>::max();
void Scanner::BookmarkScope::Set(size_t position) {
DCHECK_EQ(bookmark_, kNoBookmark);
bookmark_ = position;
}
void Scanner::BookmarkScope::Apply() {
DCHECK(HasBeenSet()); // Caller hasn't called SetBookmark.
if (had_parser_error_) {
scanner_->set_parser_error();
} else {
scanner_->reset_parser_error_flag();
scanner_->SeekNext(bookmark_);
}
bookmark_ = kBookmarkWasApplied;
}
bool Scanner::BookmarkScope::HasBeenSet() const {
return bookmark_ != kNoBookmark && bookmark_ != kBookmarkWasApplied;
}
bool Scanner::BookmarkScope::HasBeenApplied() const {
return bookmark_ == kBookmarkWasApplied;
}
// ----------------------------------------------------------------------------
// Scanner
Scanner::Scanner(Utf16CharacterStream* source, bool is_module)
: source_(source),
found_html_comment_(false),
allow_harmony_optional_chaining_(false),
allow_harmony_nullish_(false),
is_module_(is_module),
octal_pos_(Location::invalid()),
octal_message_(MessageTemplate::kNone) {
DCHECK_NOT_NULL(source);
}
void Scanner::Initialize() {
// Need to capture identifiers in order to recognize "get" and "set"
// in object literals.
Init();
next().after_line_terminator = true;
Scan();
}
template <bool capture_raw, bool unicode>
uc32 Scanner::ScanHexNumber(int expected_length) {
DCHECK_LE(expected_length, 4); // prevent overflow
int begin = source_pos() - 2;
uc32 x = 0;
for (int i = 0; i < expected_length; i++) {
int d = HexValue(c0_);
if (d < 0) {
ReportScannerError(Location(begin, begin + expected_length + 2),
unicode
? MessageTemplate::kInvalidUnicodeEscapeSequence
: MessageTemplate::kInvalidHexEscapeSequence);
return -1;
}
x = x * 16 + d;
Advance<capture_raw>();
}
return x;
}
template <bool capture_raw>
uc32 Scanner::ScanUnlimitedLengthHexNumber(int max_value, int beg_pos) {
uc32 x = 0;
int d = HexValue(c0_);
if (d < 0) return -1;
while (d >= 0) {
x = x * 16 + d;
if (x > max_value) {
ReportScannerError(Location(beg_pos, source_pos() + 1),
MessageTemplate::kUndefinedUnicodeCodePoint);
return -1;
}
Advance<capture_raw>();
d = HexValue(c0_);
}
return x;
}
Token::Value Scanner::Next() {
// Rotate through tokens.
TokenDesc* previous = current_;
current_ = next_;
// Either we already have the next token lined up, in which case next_next_
// simply becomes next_. In that case we use current_ as new next_next_ and
// clear its token to indicate that it wasn't scanned yet. Otherwise we use
// current_ as next_ and scan into it, leaving next_next_ uninitialized.
if (V8_LIKELY(next_next().token == Token::UNINITIALIZED)) {
next_ = previous;
// User 'previous' instead of 'next_' because for some reason the compiler
// thinks 'next_' could be modified before the entry into Scan.
previous->after_line_terminator = false;
Scan(previous);
} else {
next_ = next_next_;
next_next_ = previous;
previous->token = Token::UNINITIALIZED;
DCHECK_NE(Token::UNINITIALIZED, current().token);
}
return current().token;
}
Token::Value Scanner::PeekAhead() {
DCHECK(next().token != Token::DIV);
DCHECK(next().token != Token::ASSIGN_DIV);
if (next_next().token != Token::UNINITIALIZED) {
return next_next().token;
}
TokenDesc* temp = next_;
next_ = next_next_;
next().after_line_terminator = false;
Scan();
next_next_ = next_;
next_ = temp;
return next_next().token;
}
Token::Value Scanner::SkipSingleHTMLComment() {
if (is_module_) {
ReportScannerError(source_pos(), MessageTemplate::kHtmlCommentInModule);
return Token::ILLEGAL;
}
return SkipSingleLineComment();
}
Token::Value Scanner::SkipSingleLineComment() {
// The line terminator at the end of the line is not considered
// to be part of the single-line comment; it is recognized
// separately by the lexical grammar and becomes part of the
// stream of input elements for the syntactic grammar (see
// ECMA-262, section 7.4).
AdvanceUntil([](uc32 c0_) { return unibrow::IsLineTerminator(c0_); });
return Token::WHITESPACE;
}
Token::Value Scanner::SkipSourceURLComment() {
TryToParseSourceURLComment();
if (unibrow::IsLineTerminator(c0_) || c0_ == kEndOfInput) {
return Token::WHITESPACE;
}
return SkipSingleLineComment();
}
void Scanner::TryToParseSourceURLComment() {
// Magic comments are of the form: //[#@]\s<name>=\s*<value>\s*.* and this
// function will just return if it cannot parse a magic comment.
DCHECK(!IsWhiteSpaceOrLineTerminator(kEndOfInput));
if (!IsWhiteSpace(c0_)) return;
Advance();
LiteralBuffer name;
name.Start();
while (c0_ != kEndOfInput && !IsWhiteSpaceOrLineTerminator(c0_) &&
c0_ != '=') {
name.AddChar(c0_);
Advance();
}
if (!name.is_one_byte()) return;
Vector<const uint8_t> name_literal = name.one_byte_literal();
LiteralBuffer* value;
if (name_literal == StaticCharVector("sourceURL")) {
value = &source_url_;
} else if (name_literal == StaticCharVector("sourceMappingURL")) {
value = &source_mapping_url_;
} else {
return;
}
if (c0_ != '=')
return;
value->Start();
Advance();
while (IsWhiteSpace(c0_)) {
Advance();
}
while (c0_ != kEndOfInput && !unibrow::IsLineTerminator(c0_)) {
// Disallowed characters.
if (c0_ == '"' || c0_ == '\'') {
value->Start();
return;
}
if (IsWhiteSpace(c0_)) {
break;
}
value->AddChar(c0_);
Advance();
}
// Allow whitespace at the end.
while (c0_ != kEndOfInput && !unibrow::IsLineTerminator(c0_)) {
if (!IsWhiteSpace(c0_)) {
value->Start();
break;
}
Advance();
}
}
Token::Value Scanner::SkipMultiLineComment() {
DCHECK_EQ(c0_, '*');
// Until we see the first newline, check for * and newline characters.
if (!next().after_line_terminator) {
do {
AdvanceUntil([](uc32 c0) {
if (V8_UNLIKELY(static_cast<uint32_t>(c0) > kMaxAscii)) {
return unibrow::IsLineTerminator(c0);
}
uint8_t char_flags = character_scan_flags[c0];
return MultilineCommentCharacterNeedsSlowPath(char_flags);
});
while (c0_ == '*') {
Advance();
if (c0_ == '/') {
Advance();
return Token::WHITESPACE;
}
}
if (unibrow::IsLineTerminator(c0_)) {
next().after_line_terminator = true;
break;
}
} while (c0_ != kEndOfInput);
}
// After we've seen newline, simply try to find '*/'.
while (c0_ != kEndOfInput) {
AdvanceUntil([](uc32 c0) { return c0 == '*'; });
while (c0_ == '*') {
Advance();
if (c0_ == '/') {
Advance();
return Token::WHITESPACE;
}
}
}
return Token::ILLEGAL;
}
Token::Value Scanner::ScanHtmlComment() {
// Check for <!-- comments.
DCHECK_EQ(c0_, '!');
Advance();
if (c0_ != '-' || Peek() != '-') {
PushBack('!'); // undo Advance()
return Token::LT;
}
Advance();
found_html_comment_ = true;
return SkipSingleHTMLComment();
}
#ifdef DEBUG
void Scanner::SanityCheckTokenDesc(const TokenDesc& token) const {
// Only TEMPLATE_* tokens can have a invalid_template_escape_message.
// ILLEGAL and UNINITIALIZED can have garbage for the field.
switch (token.token) {
case Token::UNINITIALIZED:
case Token::ILLEGAL:
// token.literal_chars & other members might be garbage. That's ok.
case Token::TEMPLATE_SPAN:
case Token::TEMPLATE_TAIL:
break;
default:
DCHECK_EQ(token.invalid_template_escape_message, MessageTemplate::kNone);
break;
}
}
#endif // DEBUG
void Scanner::SeekForward(int pos) {
// After this call, we will have the token at the given position as
// the "next" token. The "current" token will be invalid.
if (pos == next().location.beg_pos) return;
int current_pos = source_pos();
DCHECK_EQ(next().location.end_pos, current_pos);
// Positions inside the lookahead token aren't supported.
DCHECK(pos >= current_pos);
if (pos != current_pos) {
source_->Seek(pos);
Advance();
// This function is only called to seek to the location
// of the end of a function (at the "}" token). It doesn't matter
// whether there was a line terminator in the part we skip.
next().after_line_terminator = false;
}
Scan();
}
template <bool capture_raw>
bool Scanner::ScanEscape() {
uc32 c = c0_;
Advance<capture_raw>();
// Skip escaped newlines.
DCHECK(!unibrow::IsLineTerminator(kEndOfInput));
if (!capture_raw && unibrow::IsLineTerminator(c)) {
// Allow escaped CR+LF newlines in multiline string literals.
if (IsCarriageReturn(c) && IsLineFeed(c0_)) Advance();
return true;
}
switch (c) {
case 'b' : c = '\b'; break;
case 'f' : c = '\f'; break;
case 'n' : c = '\n'; break;
case 'r' : c = '\r'; break;
case 't' : c = '\t'; break;
case 'u' : {
c = ScanUnicodeEscape<capture_raw>();
if (c < 0) return false;
break;
}
case 'v':
c = '\v';
break;
case 'x': {
c = ScanHexNumber<capture_raw>(2);
if (c < 0) return false;
break;
}
case '0': // Fall through.
case '1': // fall through
case '2': // fall through
case '3': // fall through
case '4': // fall through
case '5': // fall through
case '6': // fall through
case '7':
c = ScanOctalEscape<capture_raw>(c, 2);
break;
}
// Other escaped characters are interpreted as their non-escaped version.
AddLiteralChar(c);
return true;
}
template <bool capture_raw>
uc32 Scanner::ScanOctalEscape(uc32 c, int length) {
uc32 x = c - '0';
int i = 0;
for (; i < length; i++) {
int d = c0_ - '0';
if (d < 0 || d > 7) break;
int nx = x * 8 + d;
if (nx >= 256) break;
x = nx;
Advance<capture_raw>();
}
// Anything except '\0' is an octal escape sequence, illegal in strict mode.
// Remember the position of octal escape sequences so that an error
// can be reported later (in strict mode).
// We don't report the error immediately, because the octal escape can
// occur before the "use strict" directive.
if (c != '0' || i > 0 || IsNonOctalDecimalDigit(c0_)) {
octal_pos_ = Location(source_pos() - i - 1, source_pos() - 1);
octal_message_ = capture_raw ? MessageTemplate::kTemplateOctalLiteral
: MessageTemplate::kStrictOctalEscape;
}
return x;
}
Token::Value Scanner::ScanString() {
uc32 quote = c0_;
next().literal_chars.Start();
while (true) {
AdvanceUntil([this](uc32 c0) {
if (V8_UNLIKELY(static_cast<uint32_t>(c0) > kMaxAscii)) {
if (V8_UNLIKELY(unibrow::IsStringLiteralLineTerminator(c0))) {
return true;
}
AddLiteralChar(c0);
return false;
}
uint8_t char_flags = character_scan_flags[c0];
if (MayTerminateString(char_flags)) return true;
AddLiteralChar(c0);
return false;
});
while (c0_ == '\\') {
Advance();
// TODO(verwaest): Check whether we can remove the additional check.
if (V8_UNLIKELY(c0_ == kEndOfInput || !ScanEscape<false>())) {
return Token::ILLEGAL;
}
}
if (c0_ == quote) {
Advance();
return Token::STRING;
}
if (V8_UNLIKELY(c0_ == kEndOfInput ||
unibrow::IsStringLiteralLineTerminator(c0_))) {
return Token::ILLEGAL;
}
AddLiteralChar(c0_);
}
}
Token::Value Scanner::ScanPrivateName() {
next().literal_chars.Start();
DCHECK_EQ(c0_, '#');
DCHECK(!IsIdentifierStart(kEndOfInput));
if (!IsIdentifierStart(Peek())) {
ReportScannerError(source_pos(),
MessageTemplate::kInvalidOrUnexpectedToken);
return Token::ILLEGAL;
}
AddLiteralCharAdvance();
Token::Value token = ScanIdentifierOrKeywordInner();
return token == Token::ILLEGAL ? Token::ILLEGAL : Token::PRIVATE_NAME;
}
Token::Value Scanner::ScanTemplateSpan() {
// When scanning a TemplateSpan, we are looking for the following construct:
// TEMPLATE_SPAN ::
// ` LiteralChars* ${
// | } LiteralChars* ${
//
// TEMPLATE_TAIL ::
// ` LiteralChars* `
// | } LiteralChar* `
//
// A TEMPLATE_SPAN should always be followed by an Expression, while a
// TEMPLATE_TAIL terminates a TemplateLiteral and does not need to be
// followed by an Expression.
// These scoped helpers save and restore the original error state, so that we
// can specially treat invalid escape sequences in templates (which are
// handled by the parser).
ErrorState scanner_error_state(&scanner_error_, &scanner_error_location_);
ErrorState octal_error_state(&octal_message_, &octal_pos_);
Token::Value result = Token::TEMPLATE_SPAN;
next().literal_chars.Start();
next().raw_literal_chars.Start();
const bool capture_raw = true;
while (true) {
uc32 c = c0_;
if (c == '`') {
Advance(); // Consume '`'
result = Token::TEMPLATE_TAIL;
break;
} else if (c == '$' && Peek() == '{') {
Advance(); // Consume '$'
Advance(); // Consume '{'
break;
} else if (c == '\\') {
Advance(); // Consume '\\'
DCHECK(!unibrow::IsLineTerminator(kEndOfInput));
if (capture_raw) AddRawLiteralChar('\\');
if (unibrow::IsLineTerminator(c0_)) {
// The TV of LineContinuation :: \ LineTerminatorSequence is the empty
// code unit sequence.
uc32 lastChar = c0_;
Advance();
if (lastChar == '\r') {
// Also skip \n.
if (c0_ == '\n') Advance();
lastChar = '\n';
}
if (capture_raw) AddRawLiteralChar(lastChar);
} else {
bool success = ScanEscape<capture_raw>();
USE(success);
DCHECK_EQ(!success, has_error());
// For templates, invalid escape sequence checking is handled in the
// parser.
scanner_error_state.MoveErrorTo(next_);
octal_error_state.MoveErrorTo(next_);
}
} else if (c < 0) {
// Unterminated template literal
break;
} else {
Advance(); // Consume c.
// The TRV of LineTerminatorSequence :: <CR> is the CV 0x000A.
// The TRV of LineTerminatorSequence :: <CR><LF> is the sequence
// consisting of the CV 0x000A.
if (c == '\r') {
if (c0_ == '\n') Advance(); // Consume '\n'
c = '\n';
}
if (capture_raw) AddRawLiteralChar(c);
AddLiteralChar(c);
}
}
next().location.end_pos = source_pos();
next().token = result;
return result;
}
template <typename LocalIsolate>
Handle<String> Scanner::SourceUrl(LocalIsolate* isolate) const {
Handle<String> tmp;
if (source_url_.length() > 0) {
tmp = source_url_.Internalize(isolate);
}
return tmp;
}
template Handle<String> Scanner::SourceUrl(Isolate* isolate) const;
template Handle<String> Scanner::SourceUrl(OffThreadIsolate* isolate) const;
template <typename LocalIsolate>
Handle<String> Scanner::SourceMappingUrl(LocalIsolate* isolate) const {
Handle<String> tmp;
if (source_mapping_url_.length() > 0) {
tmp = source_mapping_url_.Internalize(isolate);
}
return tmp;
}
template Handle<String> Scanner::SourceMappingUrl(Isolate* isolate) const;
template Handle<String> Scanner::SourceMappingUrl(
OffThreadIsolate* isolate) const;
bool Scanner::ScanDigitsWithNumericSeparators(bool (*predicate)(uc32 ch),
bool is_check_first_digit) {
// we must have at least one digit after 'x'/'b'/'o'
if (is_check_first_digit && !predicate(c0_)) return false;
bool separator_seen = false;
while (predicate(c0_) || c0_ == '_') {
if (c0_ == '_') {
Advance();
if (c0_ == '_') {
ReportScannerError(Location(source_pos(), source_pos() + 1),
MessageTemplate::kContinuousNumericSeparator);
return false;
}
separator_seen = true;
continue;
}
separator_seen = false;
AddLiteralCharAdvance();
}
if (separator_seen) {
ReportScannerError(Location(source_pos(), source_pos() + 1),
MessageTemplate::kTrailingNumericSeparator);
return false;
}
return true;
}
bool Scanner::ScanDecimalDigits(bool allow_numeric_separator) {
if (allow_numeric_separator) {
return ScanDigitsWithNumericSeparators(&IsDecimalDigit, false);
}
while (IsDecimalDigit(c0_)) {
AddLiteralCharAdvance();
}
if (c0_ == '_') {
ReportScannerError(Location(source_pos(), source_pos() + 1),
MessageTemplate::kInvalidOrUnexpectedToken);
return false;
}
return true;
}
bool Scanner::ScanDecimalAsSmiWithNumericSeparators(uint64_t* value) {
bool separator_seen = false;
while (IsDecimalDigit(c0_) || c0_ == '_') {
if (c0_ == '_') {
Advance();
if (c0_ == '_') {
ReportScannerError(Location(source_pos(), source_pos() + 1),
MessageTemplate::kContinuousNumericSeparator);
return false;
}
separator_seen = true;
continue;
}
separator_seen = false;
*value = 10 * *value + (c0_ - '0');
uc32 first_char = c0_;
Advance();
AddLiteralChar(first_char);
}
if (separator_seen) {
ReportScannerError(Location(source_pos(), source_pos() + 1),
MessageTemplate::kTrailingNumericSeparator);
return false;
}
return true;
}
bool Scanner::ScanDecimalAsSmi(uint64_t* value, bool allow_numeric_separator) {
if (allow_numeric_separator) {
return ScanDecimalAsSmiWithNumericSeparators(value);
}
while (IsDecimalDigit(c0_)) {
*value = 10 * *value + (c0_ - '0');
uc32 first_char = c0_;
Advance();
AddLiteralChar(first_char);
}
return true;
}
bool Scanner::ScanBinaryDigits() {
return ScanDigitsWithNumericSeparators(&IsBinaryDigit, true);
}
bool Scanner::ScanOctalDigits() {
return ScanDigitsWithNumericSeparators(&IsOctalDigit, true);
}
bool Scanner::ScanImplicitOctalDigits(int start_pos,
Scanner::NumberKind* kind) {
*kind = IMPLICIT_OCTAL;
while (true) {
// (possible) octal number
if (IsNonOctalDecimalDigit(c0_)) {
*kind = DECIMAL_WITH_LEADING_ZERO;
return true;
}
if (!IsOctalDigit(c0_)) {
// Octal literal finished.
octal_pos_ = Location(start_pos, source_pos());
octal_message_ = MessageTemplate::kStrictOctalLiteral;
return true;
}
AddLiteralCharAdvance();
}
}
bool Scanner::ScanHexDigits() {
return ScanDigitsWithNumericSeparators(&IsHexDigit, true);
}
bool Scanner::ScanSignedInteger() {
if (c0_ == '+' || c0_ == '-') AddLiteralCharAdvance();
// we must have at least one decimal digit after 'e'/'E'
if (!IsDecimalDigit(c0_)) return false;
return ScanDecimalDigits(true);
}
Token::Value Scanner::ScanNumber(bool seen_period) {
DCHECK(IsDecimalDigit(c0_)); // the first digit of the number or the fraction
NumberKind kind = DECIMAL;
next().literal_chars.Start();
bool at_start = !seen_period;
int start_pos = source_pos(); // For reporting octal positions.
if (seen_period) {
// we have already seen a decimal point of the float
AddLiteralChar('.');
if (c0_ == '_') {
return Token::ILLEGAL;
}
// we know we have at least one digit
if (!ScanDecimalDigits(true)) return Token::ILLEGAL;
} else {
// if the first character is '0' we must check for octals and hex
if (c0_ == '0') {
AddLiteralCharAdvance();
// either 0, 0exxx, 0Exxx, 0.xxx, a hex number, a binary number or
// an octal number.
if (AsciiAlphaToLower(c0_) == 'x') {
AddLiteralCharAdvance();
kind = HEX;
if (!ScanHexDigits()) return Token::ILLEGAL;
} else if (AsciiAlphaToLower(c0_) == 'o') {
AddLiteralCharAdvance();
kind = OCTAL;
if (!ScanOctalDigits()) return Token::ILLEGAL;
} else if (AsciiAlphaToLower(c0_) == 'b') {
AddLiteralCharAdvance();
kind = BINARY;
if (!ScanBinaryDigits()) return Token::ILLEGAL;
} else if (IsOctalDigit(c0_)) {
kind = IMPLICIT_OCTAL;
if (!ScanImplicitOctalDigits(start_pos, &kind)) {
return Token::ILLEGAL;
}
if (kind == DECIMAL_WITH_LEADING_ZERO) {
at_start = false;
}
} else if (IsNonOctalDecimalDigit(c0_)) {
kind = DECIMAL_WITH_LEADING_ZERO;
} else if (c0_ == '_') {
ReportScannerError(Location(source_pos(), source_pos() + 1),
MessageTemplate::kZeroDigitNumericSeparator);
return Token::ILLEGAL;
}
}
// Parse decimal digits and allow trailing fractional part.
if (IsDecimalNumberKind(kind)) {
bool allow_numeric_separator = kind != DECIMAL_WITH_LEADING_ZERO;
// This is an optimization for parsing Decimal numbers as Smi's.
if (at_start) {
uint64_t value = 0;
// scan subsequent decimal digits
if (!ScanDecimalAsSmi(&value, allow_numeric_separator)) {
return Token::ILLEGAL;
}
if (next().literal_chars.one_byte_literal().length() <= 10 &&
value <= Smi::kMaxValue && c0_ != '.' && !IsIdentifierStart(c0_)) {
next().smi_value_ = static_cast<uint32_t>(value);
if (kind == DECIMAL_WITH_LEADING_ZERO) {
octal_pos_ = Location(start_pos, source_pos());
octal_message_ = MessageTemplate::kStrictDecimalWithLeadingZero;
}
return Token::SMI;
}
}
if (!ScanDecimalDigits(allow_numeric_separator)) {
return Token::ILLEGAL;
}
if (c0_ == '.') {
seen_period = true;
AddLiteralCharAdvance();
if (c0_ == '_') {
return Token::ILLEGAL;
}
if (!ScanDecimalDigits(true)) return Token::ILLEGAL;
}
}
}
bool is_bigint = false;
if (c0_ == 'n' && !seen_period && IsValidBigIntKind(kind)) {
// Check that the literal is within our limits for BigInt length.
// For simplicity, use 4 bits per character to calculate the maximum
// allowed literal length.
static const int kMaxBigIntCharacters = BigInt::kMaxLengthBits / 4;
int length = source_pos() - start_pos - (kind != DECIMAL ? 2 : 0);
if (length > kMaxBigIntCharacters) {
ReportScannerError(Location(start_pos, source_pos()),
MessageTemplate::kBigIntTooBig);
return Token::ILLEGAL;
}
is_bigint = true;
Advance();
} else if (AsciiAlphaToLower(c0_) == 'e') {
// scan exponent, if any
DCHECK(kind != HEX); // 'e'/'E' must be scanned as part of the hex number
if (!IsDecimalNumberKind(kind)) return Token::ILLEGAL;
// scan exponent
AddLiteralCharAdvance();
if (!ScanSignedInteger()) return Token::ILLEGAL;
}
// The source character immediately following a numeric literal must
// not be an identifier start or a decimal digit; see ECMA-262
// section 7.8.3, page 17 (note that we read only one decimal digit
// if the value is 0).
if (IsDecimalDigit(c0_) || IsIdentifierStart(c0_)) {
return Token::ILLEGAL;
}
if (kind == DECIMAL_WITH_LEADING_ZERO) {
octal_pos_ = Location(start_pos, source_pos());
octal_message_ = MessageTemplate::kStrictDecimalWithLeadingZero;
}
return is_bigint ? Token::BIGINT : Token::NUMBER;
}
uc32 Scanner::ScanIdentifierUnicodeEscape() {
Advance();
if (c0_ != 'u') return -1;
Advance();
return ScanUnicodeEscape<false>();
}
template <bool capture_raw>
uc32 Scanner::ScanUnicodeEscape() {
// Accept both \uxxxx and \u{xxxxxx}. In the latter case, the number of
// hex digits between { } is arbitrary. \ and u have already been read.
if (c0_ == '{') {
int begin = source_pos() - 2;
Advance<capture_raw>();
uc32 cp = ScanUnlimitedLengthHexNumber<capture_raw>(0x10FFFF, begin);
if (cp < 0 || c0_ != '}') {
ReportScannerError(source_pos(),
MessageTemplate::kInvalidUnicodeEscapeSequence);
return -1;
}
Advance<capture_raw>();
return cp;
}
const bool unicode = true;
return ScanHexNumber<capture_raw, unicode>(4);
}
Token::Value Scanner::ScanIdentifierOrKeywordInnerSlow(bool escaped,
bool can_be_keyword) {
while (true) {
if (c0_ == '\\') {
escaped = true;
uc32 c = ScanIdentifierUnicodeEscape();
// Only allow legal identifier part characters.
// TODO(verwaest): Make this true.
// DCHECK(!IsIdentifierPart('\'));
DCHECK(!IsIdentifierPart(-1));
if (c == '\\' || !IsIdentifierPart(c)) {
return Token::ILLEGAL;
}
can_be_keyword = can_be_keyword && CharCanBeKeyword(c);
AddLiteralChar(c);
} else if (IsIdentifierPart(c0_) ||
(CombineSurrogatePair() && IsIdentifierPart(c0_))) {
can_be_keyword = can_be_keyword && CharCanBeKeyword(c0_);
AddLiteralCharAdvance();
} else {
break;
}
}
if (can_be_keyword && next().literal_chars.is_one_byte()) {
Vector<const uint8_t> chars = next().literal_chars.one_byte_literal();
Token::Value token =
KeywordOrIdentifierToken(chars.begin(), chars.length());
if (base::IsInRange(token, Token::IDENTIFIER, Token::YIELD)) return token;
if (token == Token::FUTURE_STRICT_RESERVED_WORD) {
if (escaped) return Token::ESCAPED_STRICT_RESERVED_WORD;
return token;
}
if (!escaped) return token;
STATIC_ASSERT(Token::LET + 1 == Token::STATIC);
if (base::IsInRange(token, Token::LET, Token::STATIC)) {
return Token::ESCAPED_STRICT_RESERVED_WORD;
}
return Token::ESCAPED_KEYWORD;
}
return Token::IDENTIFIER;
}
bool Scanner::ScanRegExpPattern() {
DCHECK_EQ(Token::UNINITIALIZED, next_next().token);
DCHECK(next().token == Token::DIV || next().token == Token::ASSIGN_DIV);
// Scan: ('/' | '/=') RegularExpressionBody '/' RegularExpressionFlags
bool in_character_class = false;
// Scan regular expression body: According to ECMA-262, 3rd, 7.8.5,
// the scanner should pass uninterpreted bodies to the RegExp
// constructor.
next().literal_chars.Start();
if (next().token == Token::ASSIGN_DIV) {
AddLiteralChar('=');
}
while (c0_ != '/' || in_character_class) {
if (c0_ == kEndOfInput || unibrow::IsLineTerminator(c0_)) {
return false;
}
if (c0_ == '\\') { // Escape sequence.
AddLiteralCharAdvance();
if (c0_ == kEndOfInput || unibrow::IsLineTerminator(c0_)) {
return false;
}
AddLiteralCharAdvance();
// If the escape allows more characters, i.e., \x??, \u????, or \c?,
// only "safe" characters are allowed (letters, digits, underscore),
// otherwise the escape isn't valid and the invalid character has
// its normal meaning. I.e., we can just continue scanning without
// worrying whether the following characters are part of the escape
// or not, since any '/', '\\' or '[' is guaranteed to not be part
// of the escape sequence.
// TODO(896): At some point, parse RegExps more thoroughly to capture
// octal esacpes in strict mode.
} else { // Unescaped character.
if (c0_ == '[') in_character_class = true;
if (c0_ == ']') in_character_class = false;
AddLiteralCharAdvance();
}
}
Advance(); // consume '/'
next().token = Token::REGEXP_LITERAL;
return true;
}
Maybe<int> Scanner::ScanRegExpFlags() {
DCHECK_EQ(Token::REGEXP_LITERAL, next().token);
// Scan regular expression flags.
JSRegExp::Flags flags;
while (IsIdentifierPart(c0_)) {
JSRegExp::Flags flag = JSRegExp::FlagFromChar(c0_);
if (flag == JSRegExp::kInvalid) return Nothing<int>();
if (flags & flag) return Nothing<int>();
Advance();
flags |= flag;
}
next().location.end_pos = source_pos();
return Just<int>(flags);
}
const AstRawString* Scanner::CurrentSymbol(
AstValueFactory* ast_value_factory) const {
if (is_literal_one_byte()) {
return ast_value_factory->GetOneByteString(literal_one_byte_string());
}
return ast_value_factory->GetTwoByteString(literal_two_byte_string());
}
const AstRawString* Scanner::NextSymbol(
AstValueFactory* ast_value_factory) const {
if (is_next_literal_one_byte()) {
return ast_value_factory->GetOneByteString(next_literal_one_byte_string());
}
return ast_value_factory->GetTwoByteString(next_literal_two_byte_string());
}
const AstRawString* Scanner::CurrentRawSymbol(
AstValueFactory* ast_value_factory) const {
if (is_raw_literal_one_byte()) {
return ast_value_factory->GetOneByteString(raw_literal_one_byte_string());
}
return ast_value_factory->GetTwoByteString(raw_literal_two_byte_string());
}
double Scanner::DoubleValue() {
DCHECK(is_literal_one_byte());
return StringToDouble(
literal_one_byte_string(),
ALLOW_HEX | ALLOW_OCTAL | ALLOW_IMPLICIT_OCTAL | ALLOW_BINARY);
}
const char* Scanner::CurrentLiteralAsCString(Zone* zone) const {
DCHECK(is_literal_one_byte());
Vector<const uint8_t> vector = literal_one_byte_string();
int length = vector.length();
char* buffer = zone->NewArray<char>(length + 1);
memcpy(buffer, vector.begin(), length);
buffer[length] = '\0';
return buffer;
}
void Scanner::SeekNext(size_t position) {
// Use with care: This cleanly resets most, but not all scanner state.
// TODO(vogelheim): Fix this, or at least DCHECK the relevant conditions.
// To re-scan from a given character position, we need to:
// 1, Reset the current_, next_ and next_next_ tokens
// (next_ + next_next_ will be overwrittem by Next(),
// current_ will remain unchanged, so overwrite it fully.)
for (TokenDesc& token : token_storage_) {
token.token = Token::UNINITIALIZED;
token.invalid_template_escape_message = MessageTemplate::kNone;
}
// 2, reset the source to the desired position,
source_->Seek(position);
// 3, re-scan, by scanning the look-ahead char + 1 token (next_).
c0_ = source_->Advance();
next().after_line_terminator = false;
Scan();
DCHECK_EQ(next().location.beg_pos, static_cast<int>(position));
}
} // namespace internal
} // namespace v8
|