-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.zig
More file actions
4744 lines (4459 loc) · 241 KB
/
Copy pathparser.zig
File metadata and controls
4744 lines (4459 loc) · 241 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
const std = @import("std");
const lex = @import("lexer.zig");
const ast = @import("ast.zig");
const value_mod = @import("value.zig");
const regex = @import("regex");
const regexp_compat = @import("regexp_compat.zig");
const Token = lex.Token;
const TokenKind = lex.TokenKind;
const Node = ast.Node;
pub const ParseError = lex.LexError || error{ UnexpectedToken, ExpectedToken, InvalidAssignmentTarget };
pub const SourceLocation = struct {
byte_offset: usize,
line: usize,
column: usize,
};
pub fn sourceLocationAt(source: []const u8, raw_offset: usize) SourceLocation {
const offset = @min(raw_offset, source.len);
var line: usize = 1;
var line_start: usize = 0;
var i: usize = 0;
while (i < offset) {
if (lex.lineTerminatorLen(source, i)) |len| {
line += 1;
i += len;
line_start = i;
} else {
i += 1;
}
}
return .{
.byte_offset = offset,
.line = line,
.column = offset - line_start + 1,
};
}
/// Recursive-descent + precedence-climbing parser producing an arena-allocated
/// AST for the v1 subset (expressions, var/let/const, if/else, while, blocks).
pub const Parser = struct {
tokens: []Token,
pos: usize = 0,
arena: std.mem.Allocator,
/// The original source text, so function definitions can capture their exact
/// source span for `Function.prototype.toString`.
source: []const u8 = "",
/// True while parsing a generator body, so `yield` is recognized as a yield
/// expression rather than an identifier. Saved/restored around each function.
in_generator: bool = false,
/// True while parsing an async function body, so `await` is recognized as an
/// await expression rather than an identifier. Saved/restored per function.
in_async: bool = false,
/// Inside a class body (so a private name `#x` is in scope) — gates the
/// `#field in obj` brand check, which is a syntax error outside any class.
in_class: bool = false,
/// Set when parsing a direct eval whose caller is inside a class element: the
/// eval'd code may reference the enclosing class's private names, so the
/// "every used private name must be declared here" check is skipped (the host
/// resolves them against the class's private map and the runtime brand-checks).
eval_private_allowed: bool = false,
/// True while parsing strict-mode code: the program (or an enclosing
/// function) had a `"use strict"` directive prologue, a function body has
/// its own such directive, or we're inside a class (always strict). Inherited
/// by nested functions. Recorded on each `FunctionNode.is_strict`.
strict: bool = false,
/// Strictness of the most recently parsed function body, read by the caller
/// to stamp `FunctionNode.is_strict` (since `parseFnBody` restores `strict`).
last_fn_strict: bool = false,
/// Syntactic-context depths for early errors: `return` requires a function,
/// unlabeled `break` a loop/switch, unlabeled `continue` a loop. A function
/// boundary resets the loop/switch depths (you can't break across it).
fn_depth: u32 = 0,
iter_depth: u32 = 0,
switch_depth: u32 = 0,
/// Depth of syntax contexts where `new.target` is allowed. Ordinary
/// functions/methods introduce one; arrows only inherit an outer one.
new_target_depth: u32 = 0,
/// True when parsing a Module (via `parseModule`): top-level `import` and
/// `export` declarations are recognized, and the body is implicitly strict.
module: bool = false,
/// When false (the default), `scanSuperAndArgs` also flags an `arguments`
/// reference — used for class field initializers, where `arguments` is an
/// early error. Set true to scan only for SuperCall (e.g. a method body,
/// where `arguments` is legal).
scan_allow_arguments: bool = false,
/// When true, `scanSuperAndArgs` also flags a SuperProperty (`super.x`) —
/// used to validate indirect-eval code, which is global and may contain no
/// `super` at all (a direct eval from a field initializer leaves this false,
/// since `super.prop` is permitted there).
scan_forbid_super_property: bool = false,
/// When true, `scanSuperAndArgs` descends into the eagerly evaluated pieces
/// of nested class expressions (heritage, computed names, field initializers,
/// and static blocks). Global/method scans leave this false so a class body
/// remains its own syntactic context.
scan_descend_class_expr: bool = false,
/// When true, `scanSuperAndArgs` flags a YieldExpression — used to enforce
/// the early error "FormalParameters of a generator must not contain a
/// YieldExpression" (e.g. `function* g(a = yield) {}`).
scan_forbid_yield: bool = false,
/// When true, `scanSuperAndArgs` flags an AwaitExpression — used to enforce
/// the early error "FormalParameters of an async function/arrow must not
/// contain an AwaitExpression" (e.g. `async function f(a = await x) {}`).
scan_forbid_await: bool = false,
/// Array literals (parsed as a cover for array patterns) that ended with a
/// trailing comma right after a rest element (`[...x,]`). Legal in a literal
/// but not in the destructuring refinement, so `litToPattern` rejects them.
/// Keyed by node pointer; only consulted during pattern conversion, so a
/// stale entry for an array used as a plain literal is simply never checked.
rest_trailing_comma_arrays: std.AutoHashMapUnmanaged(*Node, void) = .empty,
/// Object literals carrying a CoverInitializedName (`{ a = 1 }`), which is
/// valid ONLY when the object is later refined to an assignment pattern.
/// `litToPattern` removes an entry on conversion; any left when the
/// Script/Module finishes parsing was used as a real object literal — an
/// early SyntaxError (`({ a = 1 })`, `f({ a = 1 })`).
pending_cover_inits: std.AutoHashMapUnmanaged(*Node, void) = .empty,
/// Object literals with two or more `__proto__: value` colon properties,
/// which is an early error for a real object literal but legal when the object
/// is refined to a pattern (where `__proto__` is just a property key).
/// Same lifecycle as `pending_cover_inits`.
pending_proto_dup: std.AutoHashMapUnmanaged(*Node, void) = .empty,
/// Expression nodes that were wrapped in parentheses, keyed by node address
/// so the mark is true pointer identity rather than any structural hashing.
/// A parenthesized
/// array/object literal is not a valid destructuring assignment target
/// (`({}) = 1`, `([a]) = b`), so `litToPattern` rejects one; a parenthesized
/// identifier/member stays a valid target and is routed around litToPattern.
paren_wrapped: std.AutoHashMapUnmanaged(usize, void) = .empty,
/// Identifier name for the just-parsed parenthesized target in `(... ) =`.
/// This feeds NamedEvaluation, where `(f) = function(){}` must not name the
/// anonymous function even though the parenthesized identifier remains a valid
/// assignment target.
paren_assign_target_name: ?[]const u8 = null,
/// The `[~In]` grammar parameter: true while parsing a classic `for (init;…)`
/// init expression, where a top-level `in` (binary or `#x in obj`) is
/// forbidden so it can't be confused with a for-in head. Reset to `[+In]`
/// inside any bracketing construct (parens, `[]`, `{}`, call args, computed
/// member, conditional branches).
no_in: bool = false,
/// Set for the single statement that is the body of an `if`/loop/`with` or a
/// `label:` item — a Statement position, where a LexicalDeclaration is not
/// allowed. `let` there must be an ordinary identifier (so `if (x) let\ny=1`
/// is `let;` + `y=1` via ASI), not the start of a `let`-declaration. Consumed
/// (read and cleared) at the top of parseStatement so it applies only to that
/// one statement and never leaks into a nested block's StatementList.
suppress_let_decl: bool = false,
/// True where a `using`/`await using` declaration statement is permitted: the
/// StatementList of a Block (incl. function bodies, which parse via
/// parseBlock) and the top level of a Module. It is NOT permitted at the top
/// level of a Script or directly in a switch CaseClause/DefaultClause (a
/// nested Block there re-enables it). The for-of head is a separate path.
using_allowed: bool = false,
/// Active labels in the current function body. A function boundary resets
/// these because `break`/`continue` cannot target labels outside the
/// function it appears in.
active_labels: std.ArrayListUnmanaged([]const u8) = .empty,
/// Labels immediately wrapping the next statement. If that statement is an
/// iteration statement, those labels become valid labeled-continue targets.
pending_labels: std.ArrayListUnmanaged([]const u8) = .empty,
/// Labels of currently enclosing iteration statements.
continue_labels: std.ArrayListUnmanaged([]const u8) = .empty,
/// Best-effort byte offset for the most recent parse failure. The parser
/// still returns compact Zig error tags, but embedders can combine this with
/// `sourceLocationAt` to report useful source diagnostics.
last_error_offset: ?usize = null,
pub fn init(arena: std.mem.Allocator, source: []const u8) ParseError!Parser {
var ignored: ?SourceLocation = null;
return initWithDiagnostic(arena, source, &ignored);
}
pub fn initWithDiagnostic(arena: std.mem.Allocator, source: []const u8, diagnostic: *?SourceLocation) ParseError!Parser {
diagnostic.* = null;
var lx = lex.Lexer.init(arena, source);
var list: std.ArrayListUnmanaged(Token) = .empty;
while (true) {
const t = lx.next() catch |err| {
diagnostic.* = sourceLocationAt(source, lx.errorOffset());
return err;
};
try list.append(arena, t);
if (t.kind == .eof) break;
}
return .{ .tokens = list.items, .arena = arena, .source = source };
}
/// Source slice from the start position of the token at `start_pos` through
/// the end of the most recently consumed token (`self.pos - 1`). Used to
/// capture a function's exact definition text for `Function.prototype.toString`.
fn sourceFrom(self: *Parser, start_pos: usize) []const u8 {
if (self.source.len == 0 or self.pos == 0) return "";
const lo = self.tokens[start_pos].pos;
const hi = self.tokens[self.pos - 1].end;
if (lo > hi or hi > self.source.len) return "";
return self.source[lo..hi];
}
fn cur(self: *Parser) Token {
return self.tokens[self.pos];
}
fn containsLineTerminator(bytes: []const u8) bool {
if (std.mem.indexOfScalar(u8, bytes, '\n') != null) return true;
if (std.mem.indexOfScalar(u8, bytes, '\r') != null) return true;
var i: usize = 0;
while (i + 2 < bytes.len) : (i += 1) {
if (bytes[i] == 0xe2 and bytes[i + 1] == 0x80 and
(bytes[i + 2] == 0xa8 or bytes[i + 2] == 0xa9))
return true;
}
return false;
}
fn hasLineTerminatorBefore(self: *Parser, ahead: usize) bool {
const idx = self.pos + ahead;
if (idx == 0 or idx >= self.tokens.len) return false;
const gap = self.source[self.tokens[idx - 1].end..self.tokens[idx].pos];
return containsLineTerminator(gap);
}
fn fail(self: *Parser, err: ParseError) ParseError {
self.last_error_offset = if (self.pos < self.tokens.len) self.cur().pos else self.source.len;
return err;
}
pub fn errorLocation(self: *const Parser) SourceLocation {
const offset = self.last_error_offset orelse if (self.pos < self.tokens.len) self.tokens[self.pos].pos else self.source.len;
return sourceLocationAt(self.source, offset);
}
/// Whether no line terminator separates the token `ahead` positions away from
/// the one just before it (the restricted-production check, e.g. `using` may
/// not be followed by a newline before its binding identifier).
fn noNewlineBefore(self: *Parser, ahead: usize) bool {
return !self.hasLineTerminatorBefore(ahead);
}
fn consumeStatementTerminator(self: *Parser) ParseError!void {
if (self.match(.semicolon)) return;
if (self.check(.eof) or self.check(.rbrace)) return;
if (self.hasLineTerminatorBefore(0)) return;
return self.fail(ParseError.UnexpectedToken);
}
fn advance(self: *Parser) Token {
const t = self.tokens[self.pos];
if (self.pos + 1 < self.tokens.len) self.pos += 1;
return t;
}
fn check(self: *Parser, kind: TokenKind) bool {
return self.cur().kind == kind;
}
fn match(self: *Parser, kind: TokenKind) bool {
if (self.check(kind)) {
_ = self.advance();
return true;
}
return false;
}
fn expect(self: *Parser, kind: TokenKind) ParseError!void {
if (!self.match(kind)) return self.fail(ParseError.ExpectedToken);
}
fn isKeyword(t: Token, word: []const u8) bool {
return t.kind == .identifier and std.mem.eql(u8, t.text, word);
}
/// The current token is the contextual keyword `word` (an identifier token).
/// A contextual keyword written with a Unicode escape (`from`) is never
/// the keyword — it is an ordinary identifier — so an escaped form never
/// matches (e.g. `import {} from "x"` is a SyntaxError).
fn isContextual(self: *Parser, word: []const u8) bool {
return !self.cur().escaped_identifier and isKeyword(self.cur(), word);
}
/// Alias of `isContextual` for readability at peek sites.
fn checkContextual(self: *Parser, word: []const u8) bool {
return self.isContextual(word);
}
/// Consume a contextual keyword `word` or fail.
fn expectContextual(self: *Parser, word: []const u8) ParseError!void {
if (!self.isContextual(word)) return self.fail(ParseError.UnexpectedToken);
_ = self.advance();
}
/// The token `ahead` positions from the cursor has kind `kind`.
fn peekIs(self: *Parser, ahead: usize, kind: TokenKind) bool {
const idx = self.pos + ahead;
if (idx >= self.tokens.len) return false;
return self.tokens[idx].kind == kind;
}
/// A label after `break`/`continue` on the same logical line.
fn optionalLabel(self: *Parser) ?[]const u8 {
if (self.hasLineTerminatorBefore(0)) return null;
if (self.check(.identifier) and !self.isForbiddenLabelName(self.cur().text)) {
return self.advance().text;
}
return null;
}
fn labelListContains(labels: []const []const u8, label: []const u8) bool {
for (labels) |candidate| {
if (std.mem.eql(u8, candidate, label)) return true;
}
return false;
}
fn statementCanInheritPendingLabels(self: *Parser) bool {
const t = self.cur();
if (t.kind != .identifier) return false;
if (std.mem.eql(u8, t.text, "while") or
std.mem.eql(u8, t.text, "do") or
std.mem.eql(u8, t.text, "for"))
return true;
return self.peekKind(1) == .colon and !self.isForbiddenLabelName(t.text);
}
/// Keywords that can NEVER be a binding identifier, in any mode (the
/// unconditional ReservedWords). Excludes the contextual ones — `let`,
/// `yield`, `await`, `static`, `async`, `of`, `get`/`set`, `implements`,
/// `undefined`, `eval`/`arguments`, … — which are legal binding names in at
/// least some contexts, so this never false-rejects them.
fn isAlwaysReservedBinding(text: []const u8) bool {
const words = [_][]const u8{
"break", "case", "catch", "class", "const", "continue",
"debugger", "default", "delete", "do", "else", "enum",
"export", "extends", "false", "finally", "for", "function",
"if", "import", "in", "instanceof", "new", "null",
"return", "super", "switch", "this", "throw", "true",
"try", "typeof", "var", "void", "while", "with",
};
for (words) |w| if (std.mem.eql(u8, text, w)) return true;
return false;
}
fn isReservedWord(text: []const u8) bool {
const words = [_][]const u8{
"true", "false", "null", "this", "typeof",
"void", "new", "in", "instanceof", "function",
"return", "var", "let", "const", "if",
"else", "while", "do", "for", "switch",
"case", "default", "break", "continue", "throw",
"try", "catch", "finally", "delete", "class",
"enum", "export", "extends", "import", "super",
"yield",
};
for (words) |w| {
if (std.mem.eql(u8, text, w)) return true;
}
return false;
}
fn isStrictReservedBinding(text: []const u8) bool {
const words = [_][]const u8{
"implements", "interface", "let", "package", "private",
"protected", "public", "static", "yield",
};
for (words) |w| if (std.mem.eql(u8, text, w)) return true;
return false;
}
fn isForbiddenBindingName(self: *Parser, text: []const u8) bool {
return isAlwaysReservedBinding(text) or
((self.module or self.in_async) and std.mem.eql(u8, text, "await")) or
(self.in_generator and std.mem.eql(u8, text, "yield")) or
(self.strict and (isStrictReservedBinding(text) or isEvalOrArguments(text)));
}
fn isForbiddenLabelName(self: *Parser, text: []const u8) bool {
return isAlwaysReservedBinding(text) or
((self.module or self.in_async) and std.mem.eql(u8, text, "await")) or
(self.in_generator and std.mem.eql(u8, text, "yield")) or
(self.strict and isStrictReservedBinding(text));
}
fn isEscapedReservedWord(self: *Parser, t: Token) bool {
return t.kind == .identifier and t.escaped_identifier and
(isAlwaysReservedBinding(t.text) or (self.strict and isStrictReservedBinding(t.text)));
}
fn letDeclAhead(self: *Parser) bool {
// A `let` written with a Unicode escape (`let`) is never the keyword,
// so it cannot begin a LexicalDeclaration — it is an ordinary identifier.
if (self.cur().escaped_identifier) return false;
if (!isKeyword(self.cur(), "let")) return false;
return switch (self.peekKind(1)) {
.lbrace => self.noNewlineBefore(1),
.lbracket => true,
// `let` followed by a BindingIdentifier begins a LexicalDeclaration.
// The contextual keywords `let`/`yield`/`await` are BindingIdentifiers
// (then rejected as bound names where illegal), so `let let`/`let yield`
// is a declaration — not `let` the identifier followed by an operator
// keyword (`let in x`, `let instanceof X`), which stays an expression.
.identifier => blk: {
const t1 = self.tokens[self.pos + 1].text;
break :blk !isReservedWord(t1) or std.mem.eql(u8, t1, "let") or
std.mem.eql(u8, t1, "yield") or std.mem.eql(u8, t1, "await");
},
else => false,
};
}
fn alloc(self: *Parser, node: Node) ParseError!*Node {
const p = try self.arena.create(Node);
p.* = node;
return p;
}
fn markParenWrapped(self: *Parser, node: *Node) ParseError!void {
try self.paren_wrapped.put(self.arena, @intFromPtr(node), {});
}
fn isParenWrapped(self: *Parser, node: *Node) bool {
return self.paren_wrapped.contains(@intFromPtr(node));
}
fn parenWrappedIdentifierBefore(self: *Parser, pos: usize, name: []const u8) bool {
if (pos == 0 or self.tokens[pos - 1].kind != .rparen) return false;
var i = pos;
var depth: usize = 0;
var saw_ident = false;
var ident_matches = false;
while (i > 0) {
i -= 1;
const t = self.tokens[i];
switch (t.kind) {
.rparen => depth += 1,
.lparen => {
if (depth == 0) return false;
depth -= 1;
if (depth == 0) return saw_ident and ident_matches;
},
.identifier => {
if (depth != 1 or saw_ident) return false;
saw_ident = true;
ident_matches = std.mem.eql(u8, t.text, name);
},
else => if (depth == 1) return false,
}
}
return false;
}
/// NamedEvaluation (applied at parse time): an *anonymous* function/class
/// literal bound to a name takes that name (`var f = function(){}` ⇒
/// `f.name === "f"`). Doing it on the AST means it holds whether the program
/// runs on the VM or the tree-walker. A named function expression keeps its
/// own name. (Runtime sites — destructuring/param defaults — name anon
/// values too, for the dynamic cases this can't see.)
fn nameAnon(node: *Node, name: []const u8) void {
if (name.len == 0) return;
switch (node.*) {
.function => |f| {
if (f.name.len == 0) f.name = name;
},
.class_expr => {
if (node.class_expr.name.len == 0) node.class_expr.inferred_name = name;
},
else => {},
}
}
// ----- program / statements -------------------------------------------
pub fn parseProgram(self: *Parser) ParseError!*Node {
// A top-level `"use strict"` directive prologue makes the whole program
// (and every function in it, by inheritance) strict.
var i: usize = self.pos;
while (i < self.tokens.len and self.tokens[i].kind == .string) {
if (std.mem.eql(u8, self.tokens[i].text, "use strict")) {
self.strict = true;
break;
}
i += 1;
if (i < self.tokens.len and self.tokens[i].kind == .semicolon) i += 1;
}
var stmts: std.ArrayListUnmanaged(*Node) = .empty;
while (!self.check(.eof)) {
try stmts.append(self.arena, try self.parseStatement());
}
// Early error: no duplicate lexically-declared names in a scope.
try self.checkLexicalDupes(stmts.items, false);
if (!self.eval_private_allowed) try self.checkPrivateUsesInProgram(stmts.items);
// A CoverInitializedName (`{ a = 1 }`) never refined to a pattern is an
// early error.
if (self.pending_cover_inits.count() > 0 or self.pending_proto_dup.count() > 0) return self.fail(ParseError.UnexpectedToken);
return self.alloc(.{ .program = stmts.items });
}
/// Early-error check (13.2.1.1 et al.): a scope's lexically-declared names
/// (`let`/`const`/`class`, plus block-level `function`s) must be unique. This
/// flags only *same-scope* duplicates — always a SyntaxError — so valid
/// shadowing in nested scopes is never rejected. `funcs_lexical` is true for a
/// block/switch scope (where a function declaration is lexical) and false for
/// a function-body/script top level (where it is var-scoped). Incomplete
/// traversal only misses errors; it never produces a false positive.
fn checkLexicalDupes(self: *Parser, stmts: []const *Node, funcs_lexical: bool) ParseError!void {
// name → is the declaration "rigid"? A let/const/class — or an async/
// generator function — is rigid: any same-name collision is an error.
// Two *plain* function declarations in a sloppy block are allowed
// (Annex B.3.3), so a collision is reported only when a rigid one is
// involved — which keeps the check free of false positives.
var seen: std.StringHashMapUnmanaged(bool) = .empty;
for (stmts) |s| {
switch (s.*) {
.var_decl => |d| if (d.kind != .@"var") try self.addDecl(&seen, d.name, true),
.destructure_decl => |d| if (d.kind != .@"var") {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, d.pattern);
for (names.items) |n| try self.addDecl(&seen, n, true);
},
.decl_group => |g| for (g) |d2| {
if (d2.* == .var_decl and d2.var_decl.kind != .@"var") try self.addDecl(&seen, d2.var_decl.name, true);
if (d2.* == .destructure_decl and d2.destructure_decl.kind != .@"var") {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, d2.destructure_decl.pattern);
for (names.items) |n| try self.addDecl(&seen, n, true);
}
},
// A block-level function declaration is "rigid" (no duplicate
// allowed) when it is a generator/async — or in strict mode, which
// has no Annex B.3.3 plain-function duplicate allowance, so
// `{ function f(){} function f(){} }` is a strict SyntaxError.
.func_decl => |fnode| if (funcs_lexical and fnode.name.len > 0)
try self.addDecl(&seen, fnode.name, fnode.is_async or fnode.is_generator or self.strict),
else => {},
}
}
// Early error (Block 14.2.1, Script 16.1.1, FunctionBody 15.2.1): a scope's
// LexicallyDeclaredNames must not intersect its VarDeclaredNames — e.g.
// `{ var f; const f }` or `let x; { var x; }`. Var names hoist out of nested
// blocks/control-flow (but not functions), so collect them across the
// subtree. At a function/script scope, top-level function declarations are
// themselves var-scoped, so they participate too.
if (seen.count() > 0) {
var var_names: std.StringHashMapUnmanaged(void) = .empty;
for (stmts) |s| try self.collectVarNames(s, &var_names);
if (!funcs_lexical) for (stmts) |s| {
if (s.* == .func_decl and s.func_decl.name.len > 0)
try var_names.put(self.arena, s.func_decl.name, {});
};
var it = seen.iterator();
while (it.next()) |entry| {
if (var_names.contains(entry.key_ptr.*)) return ParseError.UnexpectedToken;
}
}
for (stmts) |s| try self.recurseScope(s);
}
/// Early error (15.2.1 etc.): no element of a function's parameter BoundNames
/// may also occur in the LexicallyDeclaredNames of its body —
/// `function f(a){ let a; }`, `(a) => { const a = 1; }`, `({ m(a){ class a{} } })`
/// are all SyntaxErrors. (A body `var a`/`function a(){}` is VarDeclared, not
/// Lexical, so it may legally shadow a parameter, and a `let a` nested in an
/// inner block has its own scope.) Applies to every function, method, and
/// block-body arrow. The body of an expression-bodied arrow has no
/// declarations, so nothing to check.
fn checkParamBodyConflict(self: *Parser, params: []const ast.Param, body: *Node) ParseError!void {
if (body.* != .block) return;
var pnames: std.StringHashMapUnmanaged(void) = .empty;
for (params) |p| {
if (p.pattern) |pat| {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, pat);
for (names.items) |n| if (n.len > 0) try pnames.put(self.arena, n, {});
} else if (p.name.len > 0) try pnames.put(self.arena, p.name, {});
}
if (pnames.count() == 0) return;
for (body.block) |s| switch (s.*) {
.var_decl => |d| if (d.kind != .@"var" and pnames.contains(d.name)) return ParseError.UnexpectedToken,
.destructure_decl => |d| if (d.kind != .@"var") {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, d.pattern);
for (names.items) |n| if (pnames.contains(n)) return ParseError.UnexpectedToken;
},
.decl_group => |g| for (g) |d2| {
if (d2.* == .var_decl and d2.var_decl.kind != .@"var" and pnames.contains(d2.var_decl.name)) return ParseError.UnexpectedToken;
if (d2.* == .destructure_decl and d2.destructure_decl.kind != .@"var") {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, d2.destructure_decl.pattern);
for (names.items) |n| if (pnames.contains(n)) return ParseError.UnexpectedToken;
}
},
.class_expr => |c| if (c.name.len > 0 and pnames.contains(c.name)) return ParseError.UnexpectedToken,
else => {},
};
}
/// Collect VarDeclaredNames reachable from `node` without crossing a function
/// boundary: `var` declarations (incl. destructuring and `for` heads) hoist out
/// of nested blocks and control-flow statements, so recurse through those but
/// not into nested functions/classes. Block-level function declarations are
/// *not* collected (they are lexical to their block per the static semantics).
fn collectVarNames(self: *Parser, node: *Node, out: *std.StringHashMapUnmanaged(void)) ParseError!void {
switch (node.*) {
.var_decl => |d| if (d.kind == .@"var" and d.name.len > 0) try out.put(self.arena, d.name, {}),
.destructure_decl => |d| if (d.kind == .@"var") try self.putPatternVarNames(d.pattern, out),
.decl_group => |g| for (g) |d2| try self.collectVarNames(d2, out),
.block => |b| for (b) |s| try self.collectVarNames(s, out),
.if_stmt => |i| {
try self.collectVarNames(i.consequent, out);
if (i.alternate) |a| try self.collectVarNames(a, out);
},
.while_stmt => |w| try self.collectVarNames(w.body, out),
.do_while_stmt => |w| try self.collectVarNames(w.body, out),
.for_stmt => |f| {
if (f.init) |ini| try self.collectVarNames(ini, out);
try self.collectVarNames(f.body, out);
},
.for_in => |f| {
if (f.decl_kind) |k| if (k == .@"var") try self.putPatternVarNames(f.target, out);
try self.collectVarNames(f.body, out);
},
.labeled_stmt => |l| try self.collectVarNames(l.body, out),
.try_stmt => |t| {
try self.collectVarNames(t.block, out);
if (t.catch_block) |c| try self.collectVarNames(c, out);
if (t.finally_block) |fb| try self.collectVarNames(fb, out);
},
.switch_stmt => |sw| for (sw.cases) |cs| for (cs.body) |s| try self.collectVarNames(s, out),
// func_decl / function / class bodies are separate var scopes.
else => {},
}
}
fn putPatternVarNames(self: *Parser, pattern: *Node, out: *std.StringHashMapUnmanaged(void)) ParseError!void {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, pattern);
for (names.items) |n| if (n.len > 0) try out.put(self.arena, n, {});
}
/// A lexical binding target's BoundNames must be unique (`let [x, x]` etc.).
/// The BoundNames of a *lexical* (`let`/`const`/`using`) for-in/of head must
/// be unique and must not contain `let` — `for (let [x, x] of …)` and
/// `for (const let of …)` are both early errors. Called only for lexical
/// heads (plain `var` permits both).
fn checkNoDuplicateBindings(self: *Parser, target: *Node) ParseError!void {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, target);
var seen: std.StringHashMapUnmanaged(void) = .empty;
for (names.items) |n| {
if (n.len == 0) continue;
if (std.mem.eql(u8, n, "let")) return ParseError.UnexpectedToken;
if (seen.contains(n)) return ParseError.UnexpectedToken;
try seen.put(self.arena, n, {});
}
}
fn checkNoDuplicateLexicalDeclNames(self: *Parser, decl: *Node) ParseError!void {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.collectLexicalDeclNames(decl, &names);
var seen: std.StringHashMapUnmanaged(void) = .empty;
for (names.items) |n| {
if (n.len == 0) continue;
if (std.mem.eql(u8, n, "let")) return ParseError.UnexpectedToken;
if (seen.contains(n)) return ParseError.UnexpectedToken;
try seen.put(self.arena, n, {});
}
}
/// A lexical for-in/of head's BoundNames must not also appear among the
/// VarDeclaredNames of the loop body — `for (const x of []) { var x; }` is an
/// early error (the body's `var` would redeclare the per-iteration lexical
/// binding). Called only for lexical heads.
fn checkForHeadVarConflict(self: *Parser, target: *Node, body: *Node) ParseError!void {
var head: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&head, target);
if (head.items.len == 0) return;
var vars: std.StringHashMapUnmanaged(void) = .empty;
try self.collectVarNames(body, &vars);
for (head.items) |n| if (n.len > 0 and vars.contains(n)) return ParseError.UnexpectedToken;
}
/// Collect the BoundNames of a *lexical* (`let`/`const`/`using`) declaration
/// node (single binding, destructuring, or `decl_group` of several). A `var`
/// declaration contributes nothing (its names are VarDeclaredNames).
fn collectLexicalDeclNames(self: *Parser, decl: *Node, out: *std.ArrayListUnmanaged([]const u8)) ParseError!void {
switch (decl.*) {
.var_decl => |d| if (d.kind != .@"var" and d.name.len > 0) try out.append(self.arena, d.name),
.destructure_decl => |d| if (d.kind != .@"var") try self.addPatternNames(out, d.pattern),
.decl_group => |g| for (g) |d2| try self.collectLexicalDeclNames(d2, out),
else => {},
}
}
/// A classic `for (lexical-decl; …) Statement`'s BoundNames must not also be
/// VarDeclaredNames of the body: `for (let x; …) { var x; }` is an early error.
fn checkForHeadDeclVarConflict(self: *Parser, decl: *Node, body: *Node) ParseError!void {
var head: std.ArrayListUnmanaged([]const u8) = .empty;
try self.collectLexicalDeclNames(decl, &head);
if (head.items.len == 0) return;
var vars: std.StringHashMapUnmanaged(void) = .empty;
try self.collectVarNames(body, &vars);
for (head.items) |n| if (n.len > 0 and vars.contains(n)) return ParseError.UnexpectedToken;
}
fn addDecl(self: *Parser, seen: *std.StringHashMapUnmanaged(bool), name: []const u8, rigid: bool) ParseError!void {
if (seen.get(name)) |existing_rigid| {
// A collision is an early error unless BOTH are plain functions.
if (rigid or existing_rigid) return ParseError.UnexpectedToken;
return; // plain-function vs plain-function: allowed
}
try seen.put(self.arena, name, rigid);
}
/// Descend into a statement's nested scopes, running `checkLexicalDupes` at
/// each new lexical scope.
fn recurseScope(self: *Parser, node: *Node) ParseError!void {
switch (node.*) {
.block => |b| try self.checkLexicalDupes(b, true),
.if_stmt => |i| {
try self.recurseScope(i.consequent);
if (i.alternate) |a| try self.recurseScope(a);
},
.while_stmt => |w| try self.recurseScope(w.body),
.do_while_stmt => |w| try self.recurseScope(w.body),
.for_stmt => |f| try self.recurseScope(f.body),
.for_in => |f| try self.recurseScope(f.body),
.labeled_stmt => |l| try self.recurseScope(l.body),
.try_stmt => |t| {
try self.recurseScope(t.block);
if (t.catch_block) |c| try self.recurseScope(c);
if (t.finally_block) |fb| try self.recurseScope(fb);
},
.switch_stmt => |sw| {
// The whole switch is one lexical (block) scope spanning all cases.
var combined: std.ArrayListUnmanaged(*Node) = .empty;
for (sw.cases) |cs| try combined.appendSlice(self.arena, cs.body);
try self.checkLexicalDupes(combined.items, true);
},
.func_decl => |fnode| try self.recurseFnBody(fnode),
// A class/function used as an initializer carries its own body scopes.
.var_decl => |d| if (d.init) |ini| try self.recurseScope(ini),
.function => |fnode| try self.recurseFnBody(fnode),
.class_expr => |c| for (c.members) |m| {
if (m.func) |mf| if (mf.* == .function) try self.recurseFnBody(mf.function);
},
.expr_stmt => |e| try self.recurseScope(e),
else => {},
}
}
/// A function body is a fresh function scope: its top-level function
/// declarations are var-scoped (not lexical), so `funcs_lexical = false`.
fn recurseFnBody(self: *Parser, fnode: *ast.FunctionNode) ParseError!void {
if (fnode.body.* == .block) try self.checkLexicalDupes(fnode.body.block, false);
}
fn addModuleLexicalName(
self: *Parser,
lexical: *std.StringHashMapUnmanaged(void),
vars: *std.StringHashMapUnmanaged(void),
name: []const u8,
) ParseError!void {
if (name.len == 0) return;
if (lexical.contains(name) or vars.contains(name)) return ParseError.UnexpectedToken;
try lexical.put(self.arena, name, {});
}
fn addModuleVarName(
self: *Parser,
lexical: *std.StringHashMapUnmanaged(void),
vars: *std.StringHashMapUnmanaged(void),
name: []const u8,
) ParseError!void {
if (name.len == 0) return;
if (lexical.contains(name)) return ParseError.UnexpectedToken;
try vars.put(self.arena, name, {});
}
fn addPatternNames(
self: *Parser,
out: *std.ArrayListUnmanaged([]const u8),
pattern: *Node,
) ParseError!void {
switch (pattern.*) {
.identifier => |name| try out.append(self.arena, name),
.obj_pattern => |p| {
for (p.props) |prop| try self.addPatternNames(out, prop.target);
if (p.rest) |r| if (r.* == .identifier) try out.append(self.arena, r.identifier);
},
.arr_pattern => |p| {
for (p.elems) |elem| if (elem.target) |target|
try self.addPatternNames(out, target);
if (p.rest) |rest| try self.addPatternNames(out, rest);
},
else => {},
}
}
fn collectModuleDeclNames(
self: *Parser,
node: *Node,
lexical: *std.StringHashMapUnmanaged(void),
vars: *std.StringHashMapUnmanaged(void),
) ParseError!void {
switch (node.*) {
.import_decl => |i| for (i.entries) |entry|
try self.addModuleLexicalName(lexical, vars, entry.local),
.export_decl => |e| {
if (e.declaration) |decl| try self.collectModuleDeclNames(decl, lexical, vars);
if (e.default_name.len > 0) try self.addModuleLexicalName(lexical, vars, e.default_name);
},
.var_decl => |d| {
if (d.kind == .@"var")
try self.addModuleVarName(lexical, vars, d.name)
else
try self.addModuleLexicalName(lexical, vars, d.name);
},
.decl_group => |group| for (group) |decl|
try self.collectModuleDeclNames(decl, lexical, vars),
.destructure_decl => |d| {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, d.pattern);
for (names.items) |name| {
if (d.kind == .@"var")
try self.addModuleVarName(lexical, vars, name)
else
try self.addModuleLexicalName(lexical, vars, name);
}
},
.func_decl => |f| try self.addModuleLexicalName(lexical, vars, f.name),
else => {},
}
}
fn addExportedName(
self: *Parser,
exported: *std.StringHashMapUnmanaged(void),
name: []const u8,
) ParseError!void {
if (name.len == 0) return;
if (exported.contains(name)) return ParseError.UnexpectedToken;
try exported.put(self.arena, name, {});
}
fn collectDeclExportedNames(
self: *Parser,
exported: *std.StringHashMapUnmanaged(void),
decl: *Node,
) ParseError!void {
switch (decl.*) {
.var_decl => |d| try self.addExportedName(exported, d.name),
.decl_group => |group| for (group) |item| try self.collectDeclExportedNames(exported, item),
.destructure_decl => |d| {
var names: std.ArrayListUnmanaged([]const u8) = .empty;
try self.addPatternNames(&names, d.pattern);
for (names.items) |name| try self.addExportedName(exported, name);
},
.func_decl => |f| try self.addExportedName(exported, f.name),
else => {},
}
}
fn collectExportedNames(
self: *Parser,
exported: *std.StringHashMapUnmanaged(void),
node: *Node,
) ParseError!void {
if (node.* != .export_decl) return;
const e = node.export_decl;
if (e.default_expr != null) try self.addExportedName(exported, "default");
if (e.star_as.len > 0) try self.addExportedName(exported, e.star_as);
for (e.entries) |entry| try self.addExportedName(exported, entry.exported);
if (e.declaration) |decl| try self.collectDeclExportedNames(exported, decl);
}
fn checkLocalExportedBindings(
node: *Node,
lexical: *const std.StringHashMapUnmanaged(void),
vars: *const std.StringHashMapUnmanaged(void),
) ParseError!void {
if (node.* != .export_decl) return;
const e = node.export_decl;
if (e.from.len != 0) return;
for (e.entries) |entry| {
if (!lexical.contains(entry.local) and !vars.contains(entry.local))
return ParseError.UnexpectedToken;
}
}
fn checkModuleEarlyErrors(self: *Parser, stmts: []const *Node) ParseError!void {
var lexical: std.StringHashMapUnmanaged(void) = .empty;
var vars: std.StringHashMapUnmanaged(void) = .empty;
var exported: std.StringHashMapUnmanaged(void) = .empty;
for (stmts) |stmt| {
try self.collectModuleDeclNames(stmt, &lexical, &vars);
try self.collectExportedNames(&exported, stmt);
}
for (stmts) |stmt| try checkLocalExportedBindings(stmt, &lexical, &vars);
for (stmts) |stmt| try self.recurseScope(stmt);
try self.checkPrivateUsesInProgram(stmts);
}
fn wtf8SurrogateAt(s: []const u8, i: usize) ?u16 {
if (i + 2 >= s.len) return null;
if (s[i] != 0xed) return null;
if (s[i + 1] < 0xa0 or s[i + 1] > 0xbf) return null;
if ((s[i + 2] & 0xc0) != 0x80) return null;
const cp = (@as(u16, s[i] & 0x0f) << 12) |
(@as(u16, s[i + 1] & 0x3f) << 6) |
@as(u16, s[i + 2] & 0x3f);
if (cp < 0xd800 or cp > 0xdfff) return null;
return cp;
}
fn isHighSurrogate(unit: u16) bool {
return unit >= 0xd800 and unit <= 0xdbff;
}
fn isLowSurrogate(unit: u16) bool {
return unit >= 0xdc00 and unit <= 0xdfff;
}
fn utf8SeqLen(bytes: []const u8, i: usize) usize {
const n = std.unicode.utf8ByteSequenceLength(bytes[i]) catch return 1;
if (i + n > bytes.len) return 1;
return if (std.unicode.utf8ValidateSlice(bytes[i .. i + n])) n else 1;
}
fn isWellFormedStringValue(s: []const u8) bool {
var i: usize = 0;
while (i < s.len) {
if (wtf8SurrogateAt(s, i)) |first| {
if (isHighSurrogate(first)) {
if (wtf8SurrogateAt(s, i + 3)) |second| if (isLowSurrogate(second)) {
i += 6;
continue;
};
}
return false;
}
i += utf8SeqLen(s, i);
}
return true;
}
/// Parse the token stream as a Module: a Module is always strict, and its
/// top level additionally permits `import`/`export` declarations.
pub fn parseModule(self: *Parser) ParseError!*Node {
self.module = true;
self.strict = true;
// HTML-like comments (Annex B B.1.3) are Script-only; a Module must reject
// `<!--` / `-->`. `init` tokenized with them enabled (the Script default),
// so re-tokenize the source with them disabled before parsing the module.
try self.retokenizeWithoutHtmlComments();
// A Module is an async context for `await` at the top level (top-level
// await). Nested non-async functions reset this via `parseFnBody`.
self.in_async = true;
// Module top level permits `using`/`await using` (unlike a Script's).
self.using_allowed = true;
var stmts: std.ArrayListUnmanaged(*Node) = .empty;
while (!self.check(.eof)) {
try stmts.append(self.arena, try self.parseModuleItem());
}
try self.checkModuleEarlyErrors(stmts.items);
if (self.pending_cover_inits.count() > 0 or self.pending_proto_dup.count() > 0) return self.fail(ParseError.UnexpectedToken);
return self.alloc(.{ .program = stmts.items });
}
/// Re-tokenize `self.source` with HTML-like comments disabled (Module goal)
/// and reset the cursor. Safe to call before any token has been consumed.
fn retokenizeWithoutHtmlComments(self: *Parser) ParseError!void {
var lx = lex.Lexer.initOptions(self.arena, self.source, false);
var list: std.ArrayListUnmanaged(Token) = .empty;
while (true) {
const t = lx.next() catch |err| {
self.last_error_offset = lx.errorOffset();
return err;
};
try list.append(self.arena, t);
if (t.kind == .eof) break;
}
self.tokens = list.items;
self.pos = 0;
}
/// A ModuleItem: an `import`/`export` declaration or an ordinary statement.
fn parseModuleItem(self: *Parser) ParseError!*Node {
const t = self.cur();
if (t.kind == .identifier) {
// `import` declaration — but `import(` (dynamic) and `import.meta`
// are expressions, so only treat it as a declaration otherwise.
if (std.mem.eql(u8, t.text, "import") and !self.peekIs(1, .lparen) and !self.peekIs(1, .dot))
return self.parseImportDecl();
if (std.mem.eql(u8, t.text, "export")) return self.parseExportDecl();
}
return self.parseStatement();
}
/// `import "spec";` | `import default, * as ns, { a as b } from "spec";`
fn parseImportDecl(self: *Parser) ParseError!*Node {
_ = self.advance(); // `import`
var entries: std.ArrayListUnmanaged(ast.ImportEntry) = .empty;
// Bare side-effect import: `import "spec";`
if (self.check(.string)) {
const spec = self.advance().text;