-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathmerve.cpp
More file actions
2137 lines (1984 loc) · 66.8 KB
/
merve.cpp
File metadata and controls
2137 lines (1984 loc) · 66.8 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
/* auto-generated on 2026-03-11 12:53:21 -0400. Do not edit! */
#include "merve.h"
/* begin file src/parser.cpp */
#include <array>
#include <cstdint>
#include <limits>
#ifdef MERVE_USE_SIMDUTF
#include <simdutf.h>
#endif
namespace lexer {
// ============================================================================
// Compile-time lookup tables for character classification
// ============================================================================
// Hex digit lookup table: maps char -> hex value (0-15), or 255 if invalid
static constexpr std::array<uint8_t, 256> kHexTable = []() consteval {
std::array<uint8_t, 256> table{};
for (int i = 0; i < 256; ++i) table[i] = 255;
for (int i = '0'; i <= '9'; ++i) table[i] = static_cast<uint8_t>(i - '0');
for (int i = 'a'; i <= 'f'; ++i) table[i] = static_cast<uint8_t>(i - 'a' + 10);
for (int i = 'A'; i <= 'F'; ++i) table[i] = static_cast<uint8_t>(i - 'A' + 10);
return table;
}();
// Simple escape lookup table: maps escape char -> result char
// Uses 0xFF as "not a simple escape" marker since '\0' is a valid escape result
static constexpr std::array<uint8_t, 256> kSimpleEscapeTable = []() consteval {
std::array<uint8_t, 256> table{};
for (int i = 0; i < 256; ++i) table[i] = 0xFF;
table['n'] = '\n';
table['r'] = '\r';
table['t'] = '\t';
table['b'] = '\b';
table['f'] = '\f';
table['v'] = '\v';
table['0'] = '\0';
table['\\'] = '\\';
table['\''] = '\'';
table['"'] = '"';
return table;
}();
// Punctuator lookup table
static constexpr std::array<bool, 256> kPunctuatorTable = []() consteval {
std::array<bool, 256> table{};
table['!'] = true;
table['%'] = true;
table['&'] = true;
// ch > 39 && ch < 48: '(' ')' '*' '+' ',' '-' '.' '/'
for (int i = 40; i < 48; ++i) table[i] = true;
// ch > 57 && ch < 64: ':' ';' '<' '=' '>' '?'
for (int i = 58; i < 64; ++i) table[i] = true;
table['['] = true;
table[']'] = true;
table['^'] = true;
// ch > 122 && ch < 127: '{' '|' '}' '~'
for (int i = 123; i < 127; ++i) table[i] = true;
return table;
}();
// Expression punctuator lookup table (similar but excludes ')' and '}')
static constexpr std::array<bool, 256> kExpressionPunctuatorTable = []() consteval {
std::array<bool, 256> table{};
table['!'] = true;
table['%'] = true;
table['&'] = true;
// ch > 39 && ch < 47 && ch != 41: '(' '*' '+' ',' '-' '.'
for (int i = 40; i < 47; ++i) {
if (i != 41) table[i] = true; // Skip ')'
}
// ch > 57 && ch < 64: ':' ';' '<' '=' '>' '?'
for (int i = 58; i < 64; ++i) table[i] = true;
table['['] = true;
table['^'] = true;
// ch > 122 && ch < 127 && ch != '}': '{' '|' '~'
for (int i = 123; i < 127; ++i) {
if (i != 125) table[i] = true; // Skip '}'
}
return table;
}();
// Identifier start lookup table (a-z, A-Z, _, $, >= 0x80)
static constexpr std::array<bool, 256> kIdentifierStartTable = []() consteval {
std::array<bool, 256> table{};
for (int i = 'a'; i <= 'z'; ++i) table[i] = true;
for (int i = 'A'; i <= 'Z'; ++i) table[i] = true;
table['_'] = true;
table['$'] = true;
// UTF-8 continuation bytes and lead bytes (>= 0x80)
for (int i = 0x80; i < 256; ++i) table[i] = true;
return table;
}();
// Identifier char lookup table (identifier start + digits)
static constexpr std::array<bool, 256> kIdentifierCharTable = []() consteval {
std::array<bool, 256> table{};
for (int i = 'a'; i <= 'z'; ++i) table[i] = true;
for (int i = 'A'; i <= 'Z'; ++i) table[i] = true;
table['_'] = true;
table['$'] = true;
for (int i = 0x80; i < 256; ++i) table[i] = true;
for (int i = '0'; i <= '9'; ++i) table[i] = true;
return table;
}();
// Whitespace/line break lookup table
static constexpr std::array<bool, 256> kBrOrWsTable = []() consteval {
std::array<bool, 256> table{};
// c > 8 && c < 14: \t \n \v \f \r
for (int i = 9; i < 14; ++i) table[i] = true;
table[32] = true; // space
return table;
}();
// ============================================================================
// Inline functions using lookup tables
// ============================================================================
// Parse a hex digit, returns -1 if invalid
inline int hexDigit(unsigned char c) {
uint8_t val = kHexTable[c];
return val == 255 ? -1 : static_cast<int>(val);
}
// Encode a Unicode code point as UTF-8 into the output string
inline void encodeUtf8(std::string& out, uint32_t codepoint) {
#ifdef MERVE_USE_SIMDUTF
// Use simdutf for optimized UTF-32 to UTF-8 conversion
char buf[4];
size_t len = simdutf::convert_utf32_to_utf8(
reinterpret_cast<const char32_t*>(&codepoint), 1, buf);
out.append(buf, len);
#else
if (codepoint <= 0x7F) {
out.push_back(static_cast<char>(codepoint));
} else if (codepoint <= 0x7FF) {
out.push_back(static_cast<char>(0xC0 | (codepoint >> 6)));
out.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
} else if (codepoint <= 0xFFFF) {
out.push_back(static_cast<char>(0xE0 | (codepoint >> 12)));
out.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
} else if (codepoint <= 0x10FFFF) {
out.push_back(static_cast<char>(0xF0 | (codepoint >> 18)));
out.push_back(static_cast<char>(0x80 | ((codepoint >> 12) & 0x3F)));
out.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
}
#endif
}
// Unescape JavaScript string escape sequences
// Returns empty optional on invalid escape sequences (like lone surrogates)
std::optional<std::string> unescapeJsString(std::string_view str) {
std::string result;
result.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
if (str[i] != '\\') {
result.push_back(str[i]);
continue;
}
if (++i >= str.size()) {
return std::nullopt; // Trailing backslash
}
// Check simple escape table first (single character escapes)
uint8_t simple = kSimpleEscapeTable[static_cast<unsigned char>(str[i])];
if (simple != 0xFF) {
result.push_back(static_cast<char>(simple));
continue;
}
// Handle complex escapes
switch (str[i]) {
case 'x': {
// \xHH - two hex digits
if (i + 2 >= str.size()) return std::nullopt;
int h1 = hexDigit(static_cast<unsigned char>(str[i + 1]));
int h2 = hexDigit(static_cast<unsigned char>(str[i + 2]));
if (h1 < 0 || h2 < 0) return std::nullopt;
result.push_back(static_cast<char>((h1 << 4) | h2));
i += 2;
break;
}
case 'u': {
if (i + 1 >= str.size()) return std::nullopt;
if (str[i + 1] == '{') {
// \u{XXXX} - variable length hex
size_t start = i + 2;
size_t end_brace = str.find('}', start);
if (end_brace == std::string_view::npos || end_brace == start) return std::nullopt;
uint32_t codepoint = 0;
for (size_t j = start; j < end_brace; ++j) {
int digit = hexDigit(static_cast<unsigned char>(str[j]));
if (digit < 0) return std::nullopt;
codepoint = (codepoint << 4) | static_cast<uint32_t>(digit);
if (codepoint > 0x10FFFF) return std::nullopt; // Invalid codepoint
}
// Handle surrogate pairs in \u{XXXX} format
if (codepoint >= 0xD800 && codepoint <= 0xDBFF) {
// High surrogate - check for low surrogate \u{XXXX}
if (end_brace + 3 < str.size() && str[end_brace + 1] == '\\' &&
str[end_brace + 2] == 'u' && str[end_brace + 3] == '{') {
size_t low_start = end_brace + 4;
size_t low_end = str.find('}', low_start);
if (low_end != std::string_view::npos && low_end > low_start) {
uint32_t low = 0;
bool valid_low = true;
for (size_t j = low_start; j < low_end; ++j) {
int digit = hexDigit(static_cast<unsigned char>(str[j]));
if (digit < 0) {
valid_low = false;
break;
}
low = (low << 4) | static_cast<uint32_t>(digit);
}
if (valid_low && low >= 0xDC00 && low <= 0xDFFF) {
// Valid surrogate pair - combine into single codepoint
codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + (low - 0xDC00);
end_brace = low_end; // Skip past the low surrogate
} else {
// Lone high surrogate
return std::nullopt;
}
} else {
// Lone high surrogate
return std::nullopt;
}
} else {
// Lone high surrogate
return std::nullopt;
}
} else if (codepoint >= 0xDC00 && codepoint <= 0xDFFF) {
// Lone low surrogate
return std::nullopt;
}
encodeUtf8(result, codepoint);
i = end_brace;
} else {
// \uHHHH - exactly four hex digits
if (i + 4 >= str.size()) return std::nullopt;
uint32_t codepoint = 0;
for (int j = 1; j <= 4; ++j) {
int digit = hexDigit(static_cast<unsigned char>(str[i + static_cast<size_t>(j)]));
if (digit < 0) return std::nullopt;
codepoint = (codepoint << 4) | static_cast<uint32_t>(digit);
}
// Handle surrogate pairs
if (codepoint >= 0xD800 && codepoint <= 0xDBFF) {
// High surrogate - check for low surrogate
if (i + 10 < str.size() && str[i + 5] == '\\' && str[i + 6] == 'u') {
uint32_t low = 0;
bool valid_low = true;
for (int j = 7; j <= 10; ++j) {
int digit = hexDigit(static_cast<unsigned char>(str[i + static_cast<size_t>(j)]));
if (digit < 0) {
valid_low = false;
break;
}
low = (low << 4) | static_cast<uint32_t>(digit);
}
if (valid_low && low >= 0xDC00 && low <= 0xDFFF) {
// Valid surrogate pair - combine into single codepoint
codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + (low - 0xDC00);
i += 6; // Skip the low surrogate
} else {
// Lone high surrogate
return std::nullopt;
}
} else {
// Lone high surrogate
return std::nullopt;
}
} else if (codepoint >= 0xDC00 && codepoint <= 0xDFFF) {
// Lone low surrogate
return std::nullopt;
}
encodeUtf8(result, codepoint);
i += 4;
}
break;
}
default:
// Unknown escape - just include the character as-is
result.push_back(str[i]);
break;
}
}
return result;
}
// Stack depth limits
constexpr size_t STACK_DEPTH = 2048;
constexpr size_t MAX_STAR_EXPORTS = 256;
// RequireType enum for parsing require statements
enum class RequireType {
Import,
ExportAssign,
ExportStar
};
// StarExportBinding structure for tracking star export bindings
struct StarExportBinding {
std::string_view specifier;
std::string_view id;
};
// Thread-local state for error tracking (safe for concurrent parse calls).
thread_local std::optional<lexer_error> last_error;
thread_local std::optional<error_location> last_error_location;
static error_location makeErrorLocation(const char* source, const char* end, const char* at) {
const char* target = at;
if (target < source) target = source;
if (target > end) target = end;
uint32_t line = 1;
uint32_t column = 1;
const char* cur = source;
while (cur < target) {
const char ch = *cur++;
if (ch == '\n') {
line++;
column = 1;
continue;
}
if (ch == '\r') {
line++;
column = 1;
if (cur < target && *cur == '\n') {
cur++;
}
continue;
}
column++;
}
error_location loc{};
loc.line = line;
loc.column = column;
return loc;
}
// Lexer state class
class CJSLexer {
private:
const char* source;
const char* pos;
const char* end;
const char* lastTokenPos;
uint16_t templateStackDepth;
uint16_t openTokenDepth;
uint16_t templateDepth;
uint32_t line;
bool lastSlashWasDivision;
bool nextBraceIsClass;
std::array<uint16_t, STACK_DEPTH> templateStack_;
std::array<const char*, STACK_DEPTH> openTokenPosStack_;
std::array<char, STACK_DEPTH> openTokenTypeStack_;
std::array<bool, STACK_DEPTH> openClassPosStack;
std::array<StarExportBinding, MAX_STAR_EXPORTS> starExportStack_;
StarExportBinding* starExportStack;
const StarExportBinding* STAR_EXPORT_STACK_END;
std::vector<export_entry>& exports;
std::vector<export_entry>& re_exports;
// Increments `line` when consuming a line terminator.
// - Counts '\n' as a newline.
// - Counts '\r' as a newline only when it is not part of a CRLF sequence.
// (i.e., the next character is not '\n' or we're at end-of-input.)
void countNewline(char ch) {
line += (ch == '\n') || (ch == '\r' && (pos + 1 >= end || *(pos + 1) != '\n'));
}
// Character classification helpers using lookup tables
static bool isBr(char c) {
return c == '\r' || c == '\n';
}
static bool isBrOrWs(unsigned char c) {
return kBrOrWsTable[c];
}
static bool isBrOrWsOrPunctuatorNotDot(unsigned char c) {
return kBrOrWsTable[c] || (kPunctuatorTable[c] && c != '.');
}
static bool isPunctuator(unsigned char ch) {
return kPunctuatorTable[ch];
}
static bool isExpressionPunctuator(unsigned char ch) {
return kExpressionPunctuatorTable[ch];
}
// String comparison helpers using string_view for cleaner, more maintainable code
static constexpr bool matchesAt(const char* p, const char* end_pos, std::string_view expected) {
size_t available = static_cast<size_t>(end_pos - p);
if (available < expected.size()) return false;
for (size_t i = 0; i < expected.size(); ++i) {
if (p[i] != expected[i]) return false;
}
return true;
}
// Character type detection using lookup tables
static bool isIdentifierStart(uint8_t ch) {
return kIdentifierStartTable[ch];
}
static bool isIdentifierChar(uint8_t ch) {
return kIdentifierCharTable[ch];
}
constexpr bool keywordStart(const char* p) const {
return p == source || isBrOrWsOrPunctuatorNotDot(*(p - 1));
}
constexpr bool readPrecedingKeyword(const char* p, std::string_view keyword) const {
if (p - static_cast<ptrdiff_t>(keyword.size()) + 1 < source) return false;
const char* start = p - keyword.size() + 1;
return matchesAt(start, end, keyword) && (start == source || isBrOrWsOrPunctuatorNotDot(*(start - 1)));
}
// Keyword detection
constexpr bool isExpressionKeyword(const char* p) const {
switch (*p) {
case 'd':
switch (*(p - 1)) {
case 'i':
return readPrecedingKeyword(p - 2, "vo");
case 'l':
return readPrecedingKeyword(p - 2, "yie");
default:
return false;
}
case 'e':
switch (*(p - 1)) {
case 's':
switch (*(p - 2)) {
case 'l':
return p - 3 >= source && *(p - 3) == 'e' && keywordStart(p - 3);
case 'a':
return p - 3 >= source && *(p - 3) == 'c' && keywordStart(p - 3);
default:
return false;
}
case 't':
return readPrecedingKeyword(p - 2, "dele");
default:
return false;
}
case 'f':
if (*(p - 1) != 'o' || *(p - 2) != 'e')
return false;
switch (*(p - 3)) {
case 'c':
return readPrecedingKeyword(p - 4, "instan");
case 'p':
return readPrecedingKeyword(p - 4, "ty");
default:
return false;
}
case 'n':
return (p - 1 >= source && *(p - 1) == 'i' && keywordStart(p - 1)) ||
readPrecedingKeyword(p - 1, "retur");
case 'o':
return p - 1 >= source && *(p - 1) == 'd' && keywordStart(p - 1);
case 'r':
return readPrecedingKeyword(p - 1, "debugge");
case 't':
return readPrecedingKeyword(p - 1, "awai");
case 'w':
switch (*(p - 1)) {
case 'e':
return p - 2 >= source && *(p - 2) == 'n' && keywordStart(p - 2);
case 'o':
return readPrecedingKeyword(p - 2, "thr");
default:
return false;
}
}
return false;
}
constexpr bool isParenKeyword(const char* curPos) const {
return readPrecedingKeyword(curPos, "while") ||
readPrecedingKeyword(curPos, "for") ||
readPrecedingKeyword(curPos, "if");
}
constexpr bool isExpressionTerminator(const char* curPos) const {
switch (*curPos) {
case '>':
return *(curPos - 1) == '=';
case ';':
case ')':
return true;
case 'h':
return readPrecedingKeyword(curPos - 1, "catc");
case 'y':
return readPrecedingKeyword(curPos - 1, "finall");
case 'e':
return readPrecedingKeyword(curPos - 1, "els");
}
return false;
}
// Parsing utilities
void syntaxError(lexer_error code, const char* at = nullptr) {
if (!last_error) {
last_error = code;
const char* error_pos = at ? at : pos;
last_error_location = makeErrorLocation(source, end, error_pos);
}
pos = end + 1;
}
char commentWhitespace() {
char ch;
do {
if (pos >= end) return '\0';
ch = *pos;
if (ch == '/') {
char next_ch = pos + 1 < end ? *(pos + 1) : '\0';
if (next_ch == '/')
lineComment();
else if (next_ch == '*')
blockComment();
else
return ch;
} else if (!isBrOrWs(ch)) {
return ch;
} else {
countNewline(ch);
}
} while (pos++ < end);
return ch;
}
void lineComment() {
while (pos++ < end) {
char ch = *pos;
if (ch == '\n' || ch == '\r') {
countNewline(ch);
return;
}
}
}
void blockComment() {
pos++;
while (pos++ < end) {
char ch = *pos;
if (ch == '*' && *(pos + 1) == '/') {
pos++;
return;
}
countNewline(ch);
}
}
void stringLiteral(char quote) {
while (pos++ < end) {
char ch = *pos;
if (ch == quote)
return;
if (ch == '\\') {
if (pos + 1 >= end) break;
ch = *++pos;
if (ch == '\r') {
++line;
if (*(pos + 1) == '\n')
pos++;
} else if (ch == '\n') {
++line;
}
} else if (isBr(ch))
break;
}
syntaxError(lexer_error::UNTERMINATED_STRING_LITERAL);
}
void regularExpression() {
while (pos++ < end) {
char ch = *pos;
if (ch == '/')
return;
if (ch == '[') {
regexCharacterClass();
} else if (ch == '\\') {
if (pos + 1 < end)
pos++;
} else if (ch == '\n' || ch == '\r')
break;
}
syntaxError(lexer_error::UNTERMINATED_REGEX);
}
void regexCharacterClass() {
while (pos++ < end) {
char ch = *pos;
if (ch == ']')
return;
if (ch == '\\') {
if (pos + 1 < end)
pos++;
} else if (ch == '\n' || ch == '\r')
break;
}
syntaxError(lexer_error::UNTERMINATED_REGEX_CHARACTER_CLASS);
}
void templateString() {
while (pos++ < end) {
char ch = *pos;
if (ch == '$' && *(pos + 1) == '{') {
pos++;
if (templateStackDepth >= STACK_DEPTH) {
syntaxError(lexer_error::TEMPLATE_NEST_OVERFLOW);
return;
}
templateStack_[templateStackDepth++] = templateDepth;
templateDepth = ++openTokenDepth;
return;
}
if (ch == '`')
return;
if (ch == '\\' && pos + 1 < end) {
pos++;
countNewline(*pos);
} else {
countNewline(ch);
}
}
syntaxError(lexer_error::UNTERMINATED_TEMPLATE_STRING);
}
bool identifier(char startCh) {
if (!isIdentifierStart(static_cast<uint8_t>(startCh)))
return false;
pos++;
while (pos < end) {
char ch = *pos;
if (isIdentifierChar(static_cast<uint8_t>(ch))) {
pos++;
} else {
break;
}
}
return true;
}
// Check if string contains escape sequences
static bool needsUnescaping(std::string_view str) {
#ifdef MERVE_USE_SIMDUTF
// simdutf provides fast SIMD-based ASCII validation
// If the string is valid ASCII without high bytes, we can use a faster path
// But we still need to check for backslash
const char* ptr = simdutf::find(str.data(), str.data() + str.size(), '\\');
return ptr != str.data() + str.size();
#else
return str.find('\\') != std::string_view::npos;
#endif
}
void addExport(std::string_view export_name, uint32_t at_line) {
// Skip surrounding quotes if present
if (!export_name.empty() && (export_name.front() == '\'' || export_name.front() == '"')) {
export_name.remove_prefix(1);
export_name.remove_suffix(1);
}
// Fast path: no escaping needed, use string_view directly
if (!needsUnescaping(export_name)) {
// Check if this export already exists (avoid duplicates)
for (const auto& existing : exports) {
if (get_string_view(existing.name) == export_name) {
return; // Already exists, skip
}
}
exports.push_back(export_entry{export_name, at_line});
return;
}
// Slow path: unescape the export name (handles \u{XXXX}, \uHHHH, etc.)
// Returns nullopt for invalid sequences like lone surrogates
auto unescaped = unescapeJsString(export_name);
if (!unescaped.has_value()) {
return; // Skip invalid escape sequences
}
const std::string& name = unescaped.value();
// Check if this export already exists (avoid duplicates)
for (const auto& existing : exports) {
if (get_string_view(existing.name) == name) {
return; // Already exists, skip
}
}
exports.push_back(export_entry{std::move(unescaped.value()), at_line});
}
void addReexport(std::string_view reexport_name, uint32_t at_line) {
// Skip surrounding quotes if present
if (!reexport_name.empty() && (reexport_name.front() == '\'' || reexport_name.front() == '"')) {
reexport_name.remove_prefix(1);
reexport_name.remove_suffix(1);
}
// Fast path: no escaping needed, use string_view directly
if (!needsUnescaping(reexport_name)) {
re_exports.push_back(export_entry{reexport_name, at_line});
return;
}
// Slow path: unescape the reexport name
auto unescaped = unescapeJsString(reexport_name);
if (!unescaped.has_value()) {
return; // Skip invalid escape sequences
}
re_exports.push_back(export_entry{std::move(unescaped.value()), at_line});
}
bool readExportsOrModuleDotExports(char ch) {
const char* revertPos = pos;
if (ch == 'm' && matchesAt(pos + 1, end, "odule")) {
pos += 6;
ch = commentWhitespace();
if (ch != '.') {
pos = revertPos;
return false;
}
pos++;
ch = commentWhitespace();
}
if (ch == 'e' && matchesAt(pos + 1, end, "xports")) {
pos += 7;
return true;
}
pos = revertPos;
return false;
}
bool tryParseRequire(RequireType requireType) {
const char* revertPos = pos;
if (!matchesAt(pos + 1, end, "equire")) {
return false;
}
pos += 7;
char ch = commentWhitespace();
if (ch == '(') {
pos++;
ch = commentWhitespace();
const char* reexportStart = pos;
if (ch == '\'' || ch == '"') {
stringLiteral(ch);
const char* reexportEnd = ++pos;
ch = commentWhitespace();
if (ch == ')') {
switch (requireType) {
case RequireType::ExportStar:
case RequireType::ExportAssign:
addReexport(std::string_view(reexportStart, reexportEnd - reexportStart), line);
return true;
default:
if (starExportStack < STAR_EXPORT_STACK_END) {
starExportStack->specifier = std::string_view(reexportStart, reexportEnd - reexportStart);
}
return true;
}
}
}
}
pos = revertPos;
return false;
}
// Helper to parse property value in object literal (identifier or require())
bool tryParsePropertyValue(char& ch) {
if (ch == 'r' && tryParseRequire(RequireType::ExportAssign)) {
ch = *pos;
return true;
}
if (identifier(ch)) {
ch = *pos;
return true;
}
return false;
}
void tryParseLiteralExports() {
const char* revertPos = pos - 1;
while (pos++ < end) {
char ch = commentWhitespace();
const char* startPos = pos;
if (identifier(ch)) {
const char* endPos = pos;
ch = commentWhitespace();
// Check if this is a getter syntax: get identifier() { ... }
if (ch != ':' && endPos - startPos == 3 && matchesAt(startPos, end, "get") && identifier(ch)) {
ch = commentWhitespace();
if (ch == '(') {
// This is a getter, stop parsing here (early termination)
pos = revertPos;
return;
}
}
if (ch == ':') {
pos++;
ch = commentWhitespace();
if (!tryParsePropertyValue(ch)) {
pos = revertPos;
return;
}
}
addExport(std::string_view(startPos, endPos - startPos), line);
} else if (ch == '\'' || ch == '"') {
const char* start = pos;
stringLiteral(ch);
const char* end_pos = ++pos;
ch = commentWhitespace();
if (ch == ':') {
pos++;
ch = commentWhitespace();
if (!tryParsePropertyValue(ch)) {
pos = revertPos;
return;
}
addExport(std::string_view(start, end_pos - start), line);
}
} else if (ch == '.' && matchesAt(pos + 1, end, "..")) {
pos += 3;
if (pos < end && *pos == 'r' && tryParseRequire(RequireType::ExportAssign)) {
pos++;
} else if (pos < end && !identifier(*pos)) {
pos = revertPos;
return;
}
ch = commentWhitespace();
} else {
pos = revertPos;
return;
}
if (ch == '}')
return;
if (ch != ',') {
pos = revertPos;
return;
}
}
}
void tryParseExportsDotAssign(bool assign) {
pos += 7;
const char* revertPos = pos - 1;
char ch = commentWhitespace();
switch (ch) {
case '.': {
pos++;
ch = commentWhitespace();
const char* startPos = pos;
if (identifier(ch)) {
const char* endPos = pos;
ch = commentWhitespace();
if (ch == '=') {
addExport(std::string_view(startPos, endPos - startPos), line);
return;
}
}
break;
}
case '[': {
pos++;
ch = commentWhitespace();
if (ch == '\'' || ch == '"') {
const char* startPos = pos;
stringLiteral(ch);
const char* endPos = ++pos;
ch = commentWhitespace();
if (ch != ']') break;
pos++;
ch = commentWhitespace();
if (ch != '=') break;
addExport(std::string_view(startPos, endPos - startPos), line);
}
break;
}
case '=': {
if (assign) {
re_exports.clear();
pos++;
ch = commentWhitespace();
if (ch == '{') {
tryParseLiteralExports();
return;
}
if (ch == 'r')
tryParseRequire(RequireType::ExportAssign);
}
break;
}
}
pos = revertPos;
}
void tryParseModuleExportsDotAssign() {
pos += 6;
const char* revertPos = pos - 1;
char ch = commentWhitespace();
if (ch == '.') {
pos++;
ch = commentWhitespace();
if (ch == 'e' && matchesAt(pos + 1, end, "xports")) {
tryParseExportsDotAssign(true);
return;
}
}
pos = revertPos;
}
bool tryParseObjectHasOwnProperty(std::string_view it_id) {
char ch = commentWhitespace();
if (ch != 'O' || !matchesAt(pos + 1, end, "bject")) return false;
pos += 6;
ch = commentWhitespace();
if (ch != '.') return false;
pos++;
ch = commentWhitespace();
if (ch == 'p') {
if (!matchesAt(pos + 1, end, "rototype")) return false;
pos += 9;
ch = commentWhitespace();
if (ch != '.') return false;
pos++;
ch = commentWhitespace();
}
if (ch != 'h' || !matchesAt(pos + 1, end, "asOwnProperty")) return false;
pos += 14;
ch = commentWhitespace();
if (ch != '.') return false;
pos++;
ch = commentWhitespace();
if (ch != 'c' || !matchesAt(pos + 1, end, "all")) return false;
pos += 4;
ch = commentWhitespace();
if (ch != '(') return false;
pos++;
ch = commentWhitespace();
if (!identifier(ch)) return false;
ch = commentWhitespace();
if (ch != ',') return false;
pos++;
ch = commentWhitespace();
if (!matchesAt(pos, end, it_id)) return false;
pos += it_id.size();
ch = commentWhitespace();
if (ch != ')') return false;
pos++;
return true;
}
void tryParseObjectDefineOrKeys(bool keys) {
pos += 6;
const char* revertPos = pos - 1;
char ch = commentWhitespace();
if (ch == '.') {
pos++;
ch = commentWhitespace();
if (ch == 'd' && matchesAt(pos + 1, end, "efineProperty")) {
const char* exportStart = nullptr;
const char* exportEnd = nullptr;
while (true) {
pos += 14;
revertPos = pos - 1;
ch = commentWhitespace();
if (ch != '(') break;
pos++;
ch = commentWhitespace();
if (!readExportsOrModuleDotExports(ch)) break;
ch = commentWhitespace();