forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSLexer.cpp
More file actions
2040 lines (1839 loc) · 60.9 KB
/
JSLexer.cpp
File metadata and controls
2040 lines (1839 loc) · 60.9 KB
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
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/Parser/JSLexer.h"
#include "dtoa/dtoa.h"
#include "hermes/Support/Conversions.h"
#include "llvh/ADT/StringSwitch.h"
using llvh::Twine;
namespace hermes {
namespace parser {
namespace {
const char *g_tokenStr[] = {
#define TOK(name, str) str,
#include "hermes/Parser/TokenKinds.def"
};
const int UTF8_LINE_TERMINATOR_CHAR0 = 0xe2;
inline bool matchUnicodeLineTerminatorOffset1(const char *curCharPtr_) {
// Line separator \u2028 UTF8 encoded is : e2 80 a8
// Paragraph separator \u2029 UTF8 encoded is: e2 80 a9
return (unsigned char)curCharPtr_[1] == 0x80 &&
((unsigned char)curCharPtr_[2] == 0xa8 ||
(unsigned char)curCharPtr_[2] == 0xa9);
}
} // namespace
const char *tokenKindStr(TokenKind kind) {
assert(kind <= TokenKind::_last_token);
return g_tokenStr[static_cast<unsigned>(kind)];
}
JSLexer::JSLexer(
uint32_t bufId,
SourceErrorManager &sm,
Allocator &allocator,
StringTable *strTab,
bool strictMode,
bool convertSurrogates)
: sm_(sm),
allocator_(allocator),
ownStrTab_(strTab ? nullptr : new StringTable(allocator_)),
strTab_(strTab ? *strTab : *ownStrTab_),
strictMode_(strictMode),
convertSurrogates_(convertSurrogates) {
initializeWithBufferId(bufId);
initializeReservedIdentifiers();
}
JSLexer::JSLexer(
std::unique_ptr<llvh::MemoryBuffer> input,
SourceErrorManager &sm,
Allocator &allocator,
StringTable *strTab,
bool strictMode,
bool convertSurrogates)
: sm_(sm),
allocator_(allocator),
ownStrTab_(strTab ? nullptr : new StringTable(allocator_)),
strTab_(strTab ? *strTab : *ownStrTab_),
strictMode_(strictMode),
convertSurrogates_(convertSurrogates) {
auto bufId = sm_.addNewSourceBuffer(std::move(input));
initializeWithBufferId(bufId);
initializeReservedIdentifiers();
}
void JSLexer::initializeWithBufferId(uint32_t bufId) {
auto *buffer = sm_.getSourceBuffer(bufId);
bufId_ = bufId;
bufferStart_ = buffer->getBufferStart();
bufferEnd_ = buffer->getBufferEnd();
curCharPtr_ = bufferStart_;
assert(*bufferEnd_ == 0 && "buffer must be zero terminated");
}
void JSLexer::initializeReservedIdentifiers() {
// Add all reserved words to the identifier table
#define RESWORD(name) resWordIdent(TokenKind::rw_##name) = getIdentifier(#name);
#include "hermes/Parser/TokenKinds.def"
}
const Token *JSLexer::advance(GrammarContext grammarContext) {
newLineBeforeCurrentToken_ = false;
for (;;) {
assert(curCharPtr_ <= bufferEnd_ && "lexing past end of input");
#define PUNC_L1_1(ch, tok) \
case ch: \
token_.setStart(curCharPtr_); \
token_.setPunctuator(tok); \
++curCharPtr_; \
break
#define PUNC_L2_3(ch1, tok1, ch2a, tok2a, ch2b, tok2b) \
case ch1: \
token_.setStart(curCharPtr_); \
if (curCharPtr_[1] == ch2a) { \
token_.setPunctuator(tok2a); \
curCharPtr_ += 2; \
} else if (curCharPtr_[1] == ch2b) { \
token_.setPunctuator(tok2b); \
curCharPtr_ += 2; \
} else { \
token_.setPunctuator(tok1); \
curCharPtr_ += 1; \
} \
break
#define PUNC_L2_2(ch1, tok1, ch2, tok2) \
case ch1: \
token_.setStart(curCharPtr_); \
if (curCharPtr_[1] == (ch2)) { \
token_.setPunctuator(tok2); \
curCharPtr_ += 2; \
} else { \
token_.setPunctuator(tok1); \
curCharPtr_ += 1; \
} \
break
#define PUNC_L3_3(ch1, tok1, ch2, tok2, ch3, tok3) \
case ch1: \
token_.setStart(curCharPtr_); \
if (curCharPtr_[1] != (ch2)) { \
token_.setPunctuator(tok1); \
curCharPtr_ += 1; \
} else if (curCharPtr_[2] == (ch3)) { \
token_.setPunctuator(tok3); \
curCharPtr_ += 3; \
} else { \
token_.setPunctuator(tok2); \
curCharPtr_ += 2; \
} \
break
switch ((unsigned char)*curCharPtr_) {
case 0:
token_.setStart(curCharPtr_);
if (curCharPtr_ == bufferEnd_) {
token_.setEof();
} else {
if (!error(
token_.getStartLoc(),
"unrecognized Unicode character \\u0000")) {
token_.setEof();
} else {
++curCharPtr_;
continue;
}
}
break;
// clang-format off
PUNC_L1_1('}', TokenKind::r_brace);
PUNC_L1_1('(', TokenKind::l_paren);
PUNC_L1_1(')', TokenKind::r_paren);
PUNC_L1_1('[', TokenKind::l_square);
PUNC_L1_1(']', TokenKind::r_square);
PUNC_L1_1(';', TokenKind::semi);
PUNC_L1_1(',', TokenKind::comma);
PUNC_L1_1('~', TokenKind::tilde);
PUNC_L1_1(':', TokenKind::colon);
// { {|
case '{':
token_.setStart(curCharPtr_);
if (HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow) &&
curCharPtr_[1] == '|') {
token_.setPunctuator(TokenKind::l_bracepipe);
curCharPtr_ += 2;
} else {
token_.setPunctuator(TokenKind::l_brace);
curCharPtr_ += 1;
}
break;
// = => == ===
case '=':
token_.setStart(curCharPtr_);
if (curCharPtr_[1] == '>') {
token_.setPunctuator(TokenKind::equalgreater);
curCharPtr_ += 2;
} else if (curCharPtr_[1] != '=') {
token_.setPunctuator(TokenKind::equal);
curCharPtr_ += 1;
} else if (curCharPtr_[2] == '=') {
token_.setPunctuator(TokenKind::equalequalequal);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::equalequal);
curCharPtr_ += 2;
}
break;
// ! != !==
PUNC_L3_3('!', TokenKind::exclaim, '=', TokenKind::exclaimequal, '=', TokenKind::exclaimequalequal);
// + ++ +=
// - -- -=
// & && &=
// | || |=
PUNC_L2_3('+', TokenKind::plus, '+', TokenKind::plusplus, '=', TokenKind::plusequal);
PUNC_L2_3('-', TokenKind::minus, '-', TokenKind::minusminus, '=', TokenKind::minusequal);
case '&':
token_.setStart(curCharPtr_);
if (curCharPtr_[1] == '&') {
if (curCharPtr_[2] == '=') {
token_.setPunctuator(TokenKind::ampampequal);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::ampamp);
curCharPtr_ += 2;
}
} else if (curCharPtr_[1] == '=') {
token_.setPunctuator(TokenKind::ampequal);
curCharPtr_ += 2;
} else {
token_.setPunctuator(TokenKind::amp);
curCharPtr_ += 1;
}
break;
case '|':
token_.setStart(curCharPtr_);
if (HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow) &&
curCharPtr_[1] == '}') {
token_.setPunctuator(TokenKind::piper_brace);
curCharPtr_ += 2;
} else {
if (curCharPtr_[1] == '|') {
if (curCharPtr_[2] == '=') {
token_.setPunctuator(TokenKind::pipepipeequal);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::pipepipe);
curCharPtr_ += 2;
}
} else if (curCharPtr_[1] == '=') {
token_.setPunctuator(TokenKind::pipeequal);
curCharPtr_ += 2;
} else {
token_.setPunctuator(TokenKind::pipe);
curCharPtr_ += 1;
}
}
break;
// ? ?? ?.
case '?':
token_.setStart(curCharPtr_);
if (HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow)) {
token_.setPunctuator(TokenKind::question);
curCharPtr_ += 1;
} else if (curCharPtr_[1] == '.' && !isdigit(curCharPtr_[2])) {
// OptionalChainingPunctuator ::
// ?. [lookahead does not contain DecimalDigit]
// This is done to prevent `x?.3:y` from being recognized
// as `x ?. 3 : y` instead of `x ? .3 : y`.
token_.setPunctuator(TokenKind::questiondot);
curCharPtr_ += 2;
} else if (curCharPtr_[1] == '?') {
if (curCharPtr_[2] == '=') {
token_.setPunctuator(TokenKind::questionquestionequal);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::questionquestion);
curCharPtr_ += 2;
}
} else {
token_.setPunctuator(TokenKind::question);
curCharPtr_ += 1;
}
break;
// * *= ** **=
case '*':
token_.setStart(curCharPtr_);
if (curCharPtr_[1] == '=') {
token_.setPunctuator(TokenKind::starequal);
curCharPtr_ += 2;
} else if (curCharPtr_[1] != '*') {
token_.setPunctuator(TokenKind::star);
curCharPtr_ += 1;
} else if (curCharPtr_[2] == '=') {
token_.setPunctuator(TokenKind::starstarequal);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::starstar);
curCharPtr_ += 2;
}
break;
// * *=
// ^ ^=
// / /=
PUNC_L2_2('^', TokenKind::caret, '=', TokenKind::caretequal);
// % %=
case '%':
token_.setStart(curCharPtr_);
if (HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow) &&
curCharPtr_ + 7 <= bufferEnd_ &&
llvh::StringRef(curCharPtr_, 7) == "%checks") {
token_.setIdentifier(getStringLiteral("%checks"));
curCharPtr_ += 7;
} else if (curCharPtr_[1] == ('=')) {
token_.setPunctuator(TokenKind::percentequal);
curCharPtr_ += 2;
} else {
token_.setPunctuator(TokenKind::percent);
curCharPtr_ += 1;
}
break;
// clang-format on
case '\r':
case '\n':
++curCharPtr_;
newLineBeforeCurrentToken_ = true;
continue;
// Line separator \u2028 UTF8 encoded is : e2 80 a8
// Paragraph separator \u2029 UTF8 encoded is : e2 80 a9
case UTF8_LINE_TERMINATOR_CHAR0:
if (matchUnicodeLineTerminatorOffset1(curCharPtr_)) {
curCharPtr_ += 3;
newLineBeforeCurrentToken_ = true;
continue;
} else {
goto default_label;
}
case '\v':
case '\f':
++curCharPtr_;
continue;
case '\t':
case ' ':
// Spaces frequently come in groups, so use a tight inner loop to skip.
do
++curCharPtr_;
while (*curCharPtr_ == '\t' || *curCharPtr_ == ' ');
continue;
// No-break space \u00A0 is UTF8 encoded as: c2 a0
case 0xc2:
if ((unsigned char)curCharPtr_[1] == 0xa0) {
curCharPtr_ += 2;
continue;
} else {
goto default_label;
}
// Byte-order mark \uFEFF is encoded as: ef bb bf
case 0xef:
if ((unsigned char)curCharPtr_[1] == 0xbb &&
(unsigned char)curCharPtr_[2] == 0xbf) {
curCharPtr_ += 3;
continue;
} else {
goto default_label;
}
case '/':
if (curCharPtr_[1] == '/') { // Line comment?
if (LLVM_UNLIKELY(curCharPtr_[2] == '#')) {
if (auto sourceMappingUrl =
tryReadMagicComment("sourceMappingURL", curCharPtr_)) {
sm_.setSourceMappingUrl(bufId_, sourceMappingUrl.getValue());
} else if (
auto sourceUrl =
tryReadMagicComment("sourceURL", curCharPtr_)) {
sm_.setSourceUrl(bufId_, sourceUrl.getValue());
}
}
curCharPtr_ = skipLineComment(curCharPtr_);
continue;
} else if (curCharPtr_[1] == '*') { // Block comment?
curCharPtr_ = skipBlockComment(curCharPtr_);
continue;
} else {
token_.setStart(curCharPtr_);
if (grammarContext == AllowRegExp) {
scanRegExp();
} else if (curCharPtr_[1] == '=') {
token_.setPunctuator(TokenKind::slashequal);
curCharPtr_ += 2;
} else {
token_.setPunctuator(TokenKind::slash);
curCharPtr_ += 1;
}
}
break;
// #! (hashbang) at the very start of the buffer.
case '#':
if (LLVM_UNLIKELY(
curCharPtr_ == bufferStart_ && curCharPtr_[1] == '!')) {
curCharPtr_ = skipLineComment(curCharPtr_);
continue;
} else {
goto default_label;
}
// < <= << <<=
case '<':
token_.setStart(curCharPtr_);
if (HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == JSLexer::GrammarContext::Flow)) {
token_.setPunctuator(TokenKind::less);
curCharPtr_ += 1;
} else if (curCharPtr_[1] == '=') {
token_.setPunctuator(TokenKind::lessequal);
curCharPtr_ += 2;
} else if (curCharPtr_[1] == '<') {
if (curCharPtr_[2] == '=') {
token_.setPunctuator(TokenKind::lesslessequal);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::lessless);
curCharPtr_ += 2;
}
} else {
token_.setPunctuator(TokenKind::less);
curCharPtr_ += 1;
}
break;
// > >= >> >>> >>= >>>=
case '>':
token_.setStart(curCharPtr_);
if ((HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == JSLexer::GrammarContext::Flow)) ||
(HERMES_PARSE_JSX &&
LLVM_UNLIKELY(
grammarContext ==
JSLexer::GrammarContext::AllowJSXIdentifier))) {
token_.setPunctuator(TokenKind::greater);
curCharPtr_ += 1;
} else if (curCharPtr_[1] == '=') { // >=
token_.setPunctuator(TokenKind::greaterequal);
curCharPtr_ += 2;
} else if (curCharPtr_[1] == '>') { // >>
if (curCharPtr_[2] == '=') { // >>=
token_.setPunctuator(TokenKind::greatergreaterequal);
curCharPtr_ += 3;
} else if (curCharPtr_[2] == '>') { // >>>
if (curCharPtr_[3] == '=') { // >>>=
token_.setPunctuator(TokenKind::greatergreatergreaterequal);
curCharPtr_ += 4;
} else {
token_.setPunctuator(TokenKind::greatergreatergreater);
curCharPtr_ += 3;
}
} else {
token_.setPunctuator(TokenKind::greatergreater);
curCharPtr_ += 2;
}
} else {
token_.setPunctuator(TokenKind::greater);
curCharPtr_ += 1;
}
break;
case '.':
token_.setStart(curCharPtr_);
if (curCharPtr_[1] >= '0' && curCharPtr_[1] <= '9') {
scanNumber();
} else if (curCharPtr_[1] == '.' && curCharPtr_[2] == '.') {
token_.setPunctuator(TokenKind::dotdotdot);
curCharPtr_ += 3;
} else {
token_.setPunctuator(TokenKind::period);
++curCharPtr_;
}
break;
// clang-format off
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
// clang-format on
token_.setStart(curCharPtr_);
scanNumber();
break;
// clang-format off
case '_': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
// clang-format on
token_.setStart(curCharPtr_);
scanIdentifierFastPathInContext(curCharPtr_, grammarContext);
break;
case '@':
token_.setStart(curCharPtr_);
if (HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow)) {
scanIdentifierFastPathInContext(curCharPtr_, grammarContext);
} else {
curCharPtr_ += 1;
errorRange(token_.getStartLoc(), "unrecognized character '@'");
continue;
}
break;
case '\\': {
token_.setStart(curCharPtr_);
tmpStorage_.clear();
uint32_t cp = consumeUnicodeEscape();
if (!isUnicodeIdentifierStart(cp)) {
errorRange(
token_.getStartLoc(),
"Unicode escape \\u" + Twine::utohexstr(cp) +
" is not a valid identifier start");
continue;
} else {
appendUnicodeToStorage(cp);
}
scanIdentifierPartsInContext(grammarContext);
break;
}
case '\'':
case '"':
token_.setStart(curCharPtr_);
scanStringInContext(grammarContext);
break;
case '`':
token_.setStart(curCharPtr_);
scanTemplateLiteral();
break;
default_label:
default: {
token_.setStart(curCharPtr_);
uint32_t ch = decodeUTF8();
if (isUnicodeOnlyLetter(ch)) {
tmpStorage_.clear();
appendUnicodeToStorage(ch);
scanIdentifierPartsInContext(grammarContext);
} else if (isUnicodeOnlySpace(ch)) {
continue;
} else {
if (ch > 31 && ch < 127)
errorRange(
token_.getStartLoc(),
"unrecognized character '" + Twine((char)ch) + "'");
else
errorRange(
token_.getStartLoc(),
"unrecognized Unicode character \\u" + Twine::utohexstr(ch));
continue;
}
break;
}
}
// Always terminate the loop unless "continue" was used.
break;
} // for(;;)
token_.setEnd(curCharPtr_);
return &token_;
}
const Token *JSLexer::advanceInJSXChild() {
token_.setStart(curCharPtr_);
for (;;) {
assert(curCharPtr_ <= bufferEnd_ && "lexing past end of input");
switch (*curCharPtr_) {
PUNC_L1_1('{', TokenKind::l_brace);
PUNC_L1_1('<', TokenKind::less);
case 0:
if (curCharPtr_ == bufferEnd_) {
token_.setEof();
break;
}
// Fall-through to start scanning text.
LLVM_FALLTHROUGH;
default: {
token_.setStart(curCharPtr_);
// FIXME: Cook rawStorage_ into a value using XHTML entities.
rawStorage_.clear();
for (;;) {
char c = *curCharPtr_;
if ((c == 0 && curCharPtr_ == bufferEnd_) || c == '{' || c == '<') {
token_.setJSXText(
getStringLiteral(rawStorage_.str()),
getStringLiteral(rawStorage_.str()));
break;
}
rawStorage_.push_back(c);
++curCharPtr_;
}
break;
}
}
// Always terminate the loop unless "continue" was used.
break;
}
token_.setEnd(curCharPtr_);
return &token_;
}
bool JSLexer::isCurrentTokenADirective() {
// The current token must be a string literal without escapes.
if (token_.getKind() != TokenKind::string_literal ||
token_.getStringLiteralContainsEscapes()) {
return false;
}
const char *ptr = curCharPtr_;
// A directive is a string literal (the current token, directly behind
// curCharPtr_), followed by a semicolon, new line, or eof that we will now
// try to find. There can also be comments. So, we loop, consuming whitespace
// until we encounter:
// - EOF. Don't consume it and succeed.
// - Semicolon. Don't consume it and succeed.
// - Right brace. Don't consume it and succeed.
// - A new line. Don't consume it and succeed.
// - A line comment. It implies a new line. Don't consume it and succeed.
// - A block comment. Consume it and continue.
// - Anything else. We consume nothing and fail.
for (;;) {
assert(ptr <= bufferEnd_ && "lexing past end of input");
switch (*((const unsigned char *)ptr)) {
case 0:
// EOF?
if (ptr == bufferEnd_)
return true;
// We encountered a stray 0 character.
return false;
case ';':
case '}':
return true;
case '\r':
case '\n':
return true;
// Line separator \u2028 UTF8 encoded is : e2 80 a8
// Paragraph separator \u2029 UTF8 encoded is : e2 80 a9
case UTF8_LINE_TERMINATOR_CHAR0:
if (matchUnicodeLineTerminatorOffset1(ptr))
return true;
return false;
case '\v':
case '\f':
// Skip whitespace.
++ptr;
continue;
case '\t':
case ' ':
// Spaces frequently come in groups, so use a tight inner loop to skip.
do
++ptr;
while (*ptr == '\t' || *ptr == ' ');
continue;
// No-break space \u00A0 is UTF8 encoded as: c2 a0
case 0xc2:
if ((unsigned char)ptr[1] == 0xa0) {
ptr += 2;
continue;
} else {
goto default_label;
}
// Byte-order mark \uFEFF is encoded as: ef bb bf
case 0xef:
if ((unsigned char)ptr[1] == 0xbb && (unsigned char)ptr[2] == 0xbf) {
ptr += 3;
continue;
} else {
goto default_label;
}
case '/':
if (ptr[1] == '/') { // Line comment?
// It implies a new line, so we are good.
return true;
} else if (ptr[1] == '*') { // Block comment?
SourceErrorManager::SaveAndSuppressMessages suppress(&sm_);
ptr = skipBlockComment(ptr);
continue;
} else {
return false;
}
// Handle all other characters: if it is a unicode space, skip it.
// Otherwise we have failed.
default_label:
default: {
if (hermes::isUTF8Start(*ptr)) {
auto peeked = _peekUTF8(ptr);
if (isUnicodeOnlySpace(peeked.first)) {
ptr = peeked.second;
continue;
}
}
return false;
}
}
}
// We arrive here if we matched a directive. 'ptr' is the final character.
return true;
}
const Token *JSLexer::rescanRBraceInTemplateLiteral() {
assert(token_.getKind() == TokenKind::r_brace && "need } to rescan");
--curCharPtr_;
assert(*curCharPtr_ == '}' && "non-} was scanned as r_brace");
token_.setStart(curCharPtr_);
scanTemplateLiteral();
token_.setEnd(curCharPtr_);
return &token_;
}
OptValue<TokenKind> JSLexer::lookahead1(OptValue<TokenKind> expectedToken) {
assert(
(token_.getKind() == TokenKind::identifier || token_.isResWord()) &&
"unsupported current token");
UniqueString *savedIdent = token_.getResWordOrIdentifier();
TokenKind savedKind = token_.getKind();
SMLoc start = token_.getStartLoc();
SMLoc end = token_.getEndLoc();
const char *cur = curCharPtr_;
SourceErrorManager::SaveAndSuppressMessages suppress(&sm_);
advance();
OptValue<TokenKind> kind = token_.getKind();
if (isNewLineBeforeCurrentToken()) {
// Disregard anything after LineTerminator.
kind = llvh::None;
} else if (expectedToken == kind) {
// Do not move the cursor back.
return kind;
}
token_.setStart(start.getPointer());
token_.setEnd(end.getPointer());
if (savedKind == TokenKind::identifier) {
token_.setIdentifier(savedIdent);
} else {
token_.setResWord(savedKind, savedIdent);
}
seek(SMLoc::getFromPointer(cur));
return kind;
}
uint32_t JSLexer::consumeUnicodeEscape() {
assert(*curCharPtr_ == '\\');
++curCharPtr_;
if (*curCharPtr_ != 'u') {
error(
{SMLoc::getFromPointer(curCharPtr_ - 1),
SMLoc::getFromPointer(curCharPtr_ + 1)},
"invalid Unicode escape");
return UNICODE_REPLACEMENT_CHARACTER;
}
++curCharPtr_;
if (*curCharPtr_ == '{') {
auto cp = consumeBracedCodePoint();
if (!cp.hasValue()) {
// consumeBracedCodePoint has reported an error.
return UNICODE_REPLACEMENT_CHARACTER;
}
return *cp;
}
auto cp = consumeHex(4);
if (!cp)
return UNICODE_REPLACEMENT_CHARACTER;
// We don't need t check for valid UTF-16. JavaScript allows invalid surrogate
// pairs, so we just encode every UTF-16 code into a UTF-8 sequence, even
// though theoretically it is not a valid UTF-8. (UTF-8 would be "valid" if we
// collected the surrogate pair, decoded it into UTF-32 and encoded that into
// UTF-16).
return cp.getValue();
}
llvh::Optional<uint32_t> JSLexer::consumeUnicodeEscapeOptional() {
const char *start = curCharPtr_;
assert(*curCharPtr_ == '\\');
++curCharPtr_;
if (*curCharPtr_ != 'u') {
curCharPtr_ = start;
return llvh::None;
}
++curCharPtr_;
if (*curCharPtr_ == '{') {
// Avoid reporting an error because we are consuming the escape optionally.
auto cp = consumeBracedCodePoint(false);
if (!cp) {
curCharPtr_ = start;
return llvh::None;
}
return *cp;
}
auto cp = consumeHex(4, false);
if (!cp) {
curCharPtr_ = start;
return llvh::None;
}
// We don't need t check for valid UTF-16. JavaScript allows invalid surrogate
// pairs, so we just encode every UTF-16 code into a UTF-8 sequence, even
// though theoretically it is not a valid UTF-8. (UTF-8 would be "valid" if we
// collected the surrogate pair, decoded it into UTF-32 and encoded that into
// UTF-16).
return cp.getValue();
}
bool JSLexer::consumeIdentifierStart() {
if (*curCharPtr_ == '_' || *curCharPtr_ == '$' ||
((*curCharPtr_ | 32) >= 'a' && (*curCharPtr_ | 32) <= 'z')) {
tmpStorage_.clear();
tmpStorage_.push_back(*curCharPtr_++);
return true;
}
if (*curCharPtr_ == '\\') {
SMLoc startLoc = SMLoc::getFromPointer(curCharPtr_);
tmpStorage_.clear();
uint32_t cp = consumeUnicodeEscape();
if (!isUnicodeIdentifierStart(cp)) {
errorRange(
startLoc,
"Unicode escape \\u" + Twine::utohexstr(cp) +
"is not a valid identifier start");
} else {
appendUnicodeToStorage(cp);
}
return true;
}
if (LLVM_LIKELY(!isUTF8Start(*curCharPtr_)))
return false;
auto decoded = _peekUTF8();
if (isUnicodeIdentifierStart(decoded.first)) {
tmpStorage_.clear();
appendUnicodeToStorage(decoded.first);
curCharPtr_ = decoded.second;
return true;
}
return false;
}
template <JSLexer::IdentifierMode Mode>
bool JSLexer::consumeOneIdentifierPartNoEscape() {
char ch = *curCharPtr_;
if (ch == '_' || ch == '$' || ((ch | 32) >= 'a' && (ch | 32) <= 'z') ||
(ch >= '0' && ch <= '9') || (Mode == IdentifierMode::JSX && ch == '-') ||
(Mode == IdentifierMode::Flow && ch == '@')) {
tmpStorage_.push_back(*curCharPtr_++);
return true;
} else if (LLVM_UNLIKELY(isUTF8Start(ch))) {
// If we have encountered a Unicode character, we try to decode it. If it
// can be a part of the identifier, we consume it, otherwise we leave it
// alone.
auto decoded = _peekUTF8();
if (isUnicodeIdentifierPart(decoded.first)) {
appendUnicodeToStorage(decoded.first);
curCharPtr_ = decoded.second;
return true;
}
}
return false;
}
template <JSLexer::IdentifierMode Mode>
void JSLexer::consumeIdentifierParts() {
for (;;) {
// Try consuming an non-escaped identifier part. Failing that, check for an
// escape.
if (consumeOneIdentifierPartNoEscape<Mode>())
continue;
else if (*curCharPtr_ == '\\') {
// Decode the escape.
SMLoc startLoc = SMLoc::getFromPointer(curCharPtr_);
uint32_t cp = consumeUnicodeEscape();
if (!isUnicodeIdentifierPart(cp)) {
errorRange(
startLoc,
"Unicode escape \\u" + Twine::utohexstr(cp) +
"is not a valid identifier codepoint");
} else {
appendUnicodeToStorage(cp);
}
} else
break;
}
}
unsigned char JSLexer::consumeOctal(unsigned maxLen) {
assert(*curCharPtr_ >= '0' && *curCharPtr_ <= '7');
if (strictMode_) {
if (!error(
SMLoc::getFromPointer(curCharPtr_ - 1),
"octals not allowed in strict mode")) {
return 0;
}
}
auto res = (unsigned char)(*curCharPtr_++ - '0');
while (--maxLen && *curCharPtr_ >= '0' && *curCharPtr_ <= '7')
res = (res << 3) + *curCharPtr_++ - '0';
return res;
}
llvh::Optional<uint32_t> JSLexer::consumeHex(
unsigned requiredLen,
bool errorOnFail) {
uint32_t cp = 0;
for (unsigned i = 0; i != requiredLen; ++i) {
unsigned ch = *curCharPtr_;
if (ch >= '0' && ch <= '9') {
ch -= '0';
} else {
// Now that we know it is not a digit, it is safe to lowercase.
ch |= 32;
if (ch >= 'a' && ch <= 'f') {
ch -= 'a' - 10;
} else {
if (errorOnFail) {
error(SMLoc::getFromPointer(curCharPtr_), "invalid hex number");
}
return llvh::None;
}
}
cp = (cp << 4) + ch;
++curCharPtr_;
}
return cp;
}
llvh::Optional<uint32_t> JSLexer::consumeBracedCodePoint(bool errorOnFail) {
assert(*curCharPtr_ == '{' && "braced codepoint must begin with {");
++curCharPtr_;
const char *start = curCharPtr_;
// Set to true if we failed to get a code point that is in bounds or saw
// an invalid character.
bool failed = false;
// Loop until we hit the } or eof, max out the value, or see an invalid char.
uint32_t cp = 0;
for (; *curCharPtr_ != '}'; ++curCharPtr_) {
int ch = *curCharPtr_;
if (ch >= '0' && ch <= '9') {