-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.zig
More file actions
2719 lines (2597 loc) · 135 KB
/
Copy pathcompiler.zig
File metadata and controls
2719 lines (2597 loc) · 135 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
//! AST → bytecode compiler for the tier-1 VM.
//!
//! Lowers the subset of the AST the VM executes directly. Anything outside that
//! subset (`throw`/`try`, computed method calls, member `++`/`--`) returns
//! `error.Unsupported`, which the Context treats as a signal to run the whole
//! program on the tree-walker instead. That keeps conformance flat while the
//! VM's coverage grows — the compiler is widened one node at a time, never the
//! semantics.
//!
//! Variable resolution happens here, at compile time: a function's parameters
//! and (function-scoped) declarations are assigned frame **slot** indices,
//! captured names become `(depth, slot)` **upvalues**, and anything not found in
//! an enclosing function is a **global** resolved by name against the
//! Environment. Top-level program variables are globals (they persist across
//! `evaluate` calls, like a real global object). This mirrors the tree-walker's
//! block-transparent scoping exactly.
const std = @import("std");
const ast = @import("ast.zig");
const bc = @import("bytecode.zig");
const Node = ast.Node;
const Chunk = bc.Chunk;
const value_mod = @import("value.zig");
const Value = value_mod.Value;
pub const CompileError = error{ Unsupported, OutOfMemory };
/// Whether the result of a top-level expression statement becomes the program's
/// completion value (`program`) or is discarded (`function`).
const Mode = enum { program, function };
const Loop = struct {
breaks: std.ArrayListUnmanaged(usize) = .empty,
continues: std.ArrayListUnmanaged(usize) = .empty,
label: ?[]const u8 = null,
/// A labeled non-loop statement is breakable but not continuable.
is_loop: bool = true,
/// A `switch` is breakable but not continuable: `break` targets it, but
/// `continue` skips past it to the nearest enclosing loop.
is_switch: bool = false,
/// The `finally_depth` in effect where this loop/switch was entered. A
/// `break`/`continue` targeting it needs an `abrupt_*` unwind only when it
/// CROSSES a finally — i.e. the current finally_depth is deeper than this one.
/// A loop that lives entirely inside a finally (same depth) breaks with a
/// plain jump, so it does not disturb that finally's in-flight completion.
finally_depth: u32 = 0,
};
/// A function's local namespace: name → frame slot. Built once, up front, from
/// the parameters and the function-scoped declarations (var/let/const/function),
/// matching the engine's block-transparent scoping.
const FnScope = struct {
parent: ?*FnScope,
names: std.StringHashMapUnmanaged(u32) = .{},
count: u32 = 0,
fn addLocal(self: *FnScope, arena: std.mem.Allocator, name: []const u8) CompileError!u32 {
if (self.names.get(name)) |slot| return slot;
const slot = self.count;
try self.names.put(arena, name, slot);
self.count += 1;
return slot;
}
};
/// Whether a node embeds a `yield` reachable without crossing a function
/// boundary — used to decide whether a destructuring assignment must be lowered
/// to bytecode (yield present) or can defer to the tree-walker via `bind_pattern`.
fn nodeHasYield(node: *const ast.Node) bool {
return switch (node.*) {
.yield_expr => true,
.function => false, // a nested function/arrow is its own yield scope
.unary => |u| nodeHasYield(u.operand),
.delete_expr => |d| nodeHasYield(d),
.update => |u| nodeHasYield(u.target),
.binary => |b| nodeHasYield(b.left) or nodeHasYield(b.right),
.logical => |b| nodeHasYield(b.left) or nodeHasYield(b.right),
.sequence => |s| nodeHasYield(s.first) or nodeHasYield(s.second),
.assign => |a| nodeHasYield(a.target) or nodeHasYield(a.value),
.op_assign => |a| nodeHasYield(a.target) or nodeHasYield(a.value),
.logical_assign => |a| nodeHasYield(a.target) or nodeHasYield(a.value),
.conditional => |c| nodeHasYield(c.cond) or nodeHasYield(c.consequent) or nodeHasYield(c.alternate),
.await_expr => |a| nodeHasYield(a.argument),
.import_call => |ic| nodeHasYield(ic.specifier) or (ic.options != null and nodeHasYield(ic.options.?)),
.optional_chain => |c| nodeHasYield(c),
.spread => |s| nodeHasYield(s),
.member => |m| nodeHasYield(m.object) or (m.computed != null and nodeHasYield(m.computed.?)),
.super_member => |m| (m.computed != null and nodeHasYield(m.computed.?)),
.call => |c| blk: {
if (nodeHasYield(c.callee)) break :blk true;
for (c.args) |a| if (nodeHasYield(a)) break :blk true;
break :blk false;
},
.new_expr => |c| blk: {
if (nodeHasYield(c.callee)) break :blk true;
for (c.args) |a| if (nodeHasYield(a)) break :blk true;
break :blk false;
},
.tagged_template => |t| blk: {
if (nodeHasYield(t.tag)) break :blk true;
for (t.exprs) |e| if (nodeHasYield(e)) break :blk true;
break :blk false;
},
.array_lit => |elems| blk: {
for (elems) |e| if (nodeHasYield(e)) break :blk true;
break :blk false;
},
.object_lit => |props| blk: {
for (props) |p| {
if (p.key_expr) |ke| if (nodeHasYield(ke)) break :blk true;
if (nodeHasYield(p.value)) break :blk true;
}
break :blk false;
},
.arr_pattern => |p| blk: {
for (p.elems) |e| {
if (e.target) |t| if (nodeHasYield(t)) break :blk true;
if (e.default) |d| if (nodeHasYield(d)) break :blk true;
}
if (p.rest) |r| if (nodeHasYield(r)) break :blk true;
break :blk false;
},
.obj_pattern => |p| blk: {
for (p.props) |pp| {
if (pp.key_expr) |ke| if (nodeHasYield(ke)) break :blk true;
if (pp.default) |d| if (nodeHasYield(d)) break :blk true;
if (nodeHasYield(pp.target)) break :blk true;
}
break :blk false;
},
else => false,
};
}
/// Does a `let`/`const` for-loop's `body` capture one of the loop's per-iteration
/// binding names inside a nested closure? Such loops need a fresh binding created
/// per iteration (CreatePerIterationEnvironment); the frame-slot VM lowering in
/// `compileFor` reuses ONE slot across iterations, so every captured closure would
/// see the final value (`var` semantics). When this returns true `compileFor`
/// bails to the tree-walker, which binds per iteration correctly. `var` loops, and
/// lexical loops whose closures never reference a loop name, keep the fast VM path.
/// Whether a loop `body` declares a block-scoped (`let`/`const`) binding that a
/// closure in the body captures — which needs a fresh per-iteration binding the
/// VM's single flat frame slot can't provide (all iterations' closures would
/// share the last value). Descends into blocks/if/try/switch/labeled but NOT into
/// nested functions or nested loops (which manage their own body bindings).
fn loopBodyCapturesLexical(body: *const ast.Node) bool {
return bodyStmtCapturesLexical(body, body);
}
fn bodyStmtCapturesLexical(node: *const ast.Node, body: *const ast.Node) bool {
return switch (node.*) {
.var_decl => |d| d.kind != .@"var" and nameRefInClosure(body, d.name, false),
.destructure_decl => |d| d.kind != .@"var" and patternNameCaptured(d.pattern, body),
.block => |stmts| blk: {
for (stmts) |s| if (bodyStmtCapturesLexical(s, body)) break :blk true;
break :blk false;
},
.decl_group => |stmts| blk: {
for (stmts) |s| if (bodyStmtCapturesLexical(s, body)) break :blk true;
break :blk false;
},
.if_stmt => |s| bodyStmtCapturesLexical(s.consequent, body) or
(if (s.alternate) |a| bodyStmtCapturesLexical(a, body) else false),
.labeled_stmt => |s| bodyStmtCapturesLexical(s.body, body),
.try_stmt => |t| bodyStmtCapturesLexical(t.block, body) or
(if (t.catch_block) |cb| bodyStmtCapturesLexical(cb, body) else false) or
(if (t.finally_block) |fb| bodyStmtCapturesLexical(fb, body) else false),
.switch_stmt => |s| blk: {
for (s.cases) |c| for (c.body) |st| if (bodyStmtCapturesLexical(st, body)) break :blk true;
break :blk false;
},
else => false, // nested loops/functions manage their own bindings
};
}
fn forLoopCapturesLexical(init_node: *const ast.Node, body: *const ast.Node) bool {
return switch (init_node.*) {
.var_decl => |d| d.kind != .@"var" and nameRefInClosure(body, d.name, false),
.destructure_decl => |d| d.kind != .@"var" and patternNameCaptured(d.pattern, body),
// `let a = 0, b = 0` — a group of declarators; any captured name bails.
.decl_group => |group| blk: {
for (group) |n| if (forLoopCapturesLexical(n, body)) break :blk true;
break :blk false;
},
else => false,
};
}
/// Are any of the binding identifiers in a destructuring loop head (`for (let
/// [a, b] = …)`) captured by a closure in `body`?
fn patternNameCaptured(pat: *const ast.Node, body: *const ast.Node) bool {
return switch (pat.*) {
.identifier => |nm| nameRefInClosure(body, nm, false),
.obj_pattern => |p| blk: {
for (p.props) |pp| if (patternNameCaptured(pp.target, body)) break :blk true;
if (p.rest) |r| if (patternNameCaptured(r, body)) break :blk true;
break :blk false;
},
.arr_pattern => |p| blk: {
for (p.elems) |e| if (e.target) |t| if (patternNameCaptured(t, body)) break :blk true;
if (p.rest) |r| if (patternNameCaptured(r, body)) break :blk true;
break :blk false;
},
else => false,
};
}
/// Recursion core for `forLoopCapturesLexical`: is there an identifier reference
/// to `name` inside a nested function/arrow within `node`? `in_fn` tracks whether
/// the current subtree already sits (transitively) inside a function boundary —
/// only references there capture the loop variable, so a plain `body` read that is
/// NOT inside a closure does not force a bail. Unlike `nodeHasYield` this descends
/// INTO nested functions. The switch is exhaustive (no `else`) so a newly added
/// node kind can't silently become a false negative that reinstates the bug.
/// Deliberately ignores shadowing (an inner binding also named `name`) and treats
/// deferred class bodies as closures: over-matching only forces the correct-but-
/// slower tree-walker path, never a wrong VM lowering.
fn nameRefInClosure(node: *const ast.Node, name: []const u8, in_fn: bool) bool {
return switch (node.*) {
.identifier => |id| in_fn and std.mem.eql(u8, id, name),
.number, .bigint_lit, .string, .boolean, .null_lit, .undefined_lit, .elision, .this_expr, .new_target_expr, .regex_literal, .import_meta, .import_decl, .break_stmt, .continue_stmt => false,
// A nested function/arrow (expression or declaration): everything it (and
// any deeper closure) references is captured — descend with `in_fn = true`.
.function, .func_decl => |fnode| fnCaptures(fnode, name),
.unary => |u| nameRefInClosure(u.operand, name, in_fn),
.delete_expr => |d| nameRefInClosure(d, name, in_fn),
.update => |u| nameRefInClosure(u.target, name, in_fn),
.binary => |b| nameRefInClosure(b.left, name, in_fn) or nameRefInClosure(b.right, name, in_fn),
.logical => |b| nameRefInClosure(b.left, name, in_fn) or nameRefInClosure(b.right, name, in_fn),
.sequence => |s| nameRefInClosure(s.first, name, in_fn) or nameRefInClosure(s.second, name, in_fn),
.assign => |a| nameRefInClosure(a.target, name, in_fn) or nameRefInClosure(a.value, name, in_fn),
.op_assign => |a| nameRefInClosure(a.target, name, in_fn) or nameRefInClosure(a.value, name, in_fn),
.logical_assign => |a| nameRefInClosure(a.target, name, in_fn) or nameRefInClosure(a.value, name, in_fn),
.conditional => |c| nameRefInClosure(c.cond, name, in_fn) or nameRefInClosure(c.consequent, name, in_fn) or nameRefInClosure(c.alternate, name, in_fn),
.yield_expr => |y| y.argument != null and nameRefInClosure(y.argument.?, name, in_fn),
.await_expr => |a| nameRefInClosure(a.argument, name, in_fn),
.class_expr => |c| blk: {
// The superclass and computed member keys evaluate eagerly (current
// `in_fn`); method bodies, field initializers, and static blocks run
// deferred and so capture (`in_fn = true`).
if (c.superclass) |sc| if (nameRefInClosure(sc, name, in_fn)) break :blk true;
for (c.members) |m| {
if (m.key_expr) |ke| if (nameRefInClosure(ke, name, in_fn)) break :blk true;
if (m.func) |f| if (nameRefInClosure(f, name, in_fn)) break :blk true;
if (m.field_init) |fi| if (nameRefInClosure(fi, name, true)) break :blk true;
if (m.static_block) |sb| if (nameRefInClosure(sb, name, true)) break :blk true;
}
break :blk false;
},
.super_call => |args| blk: {
for (args) |a| if (nameRefInClosure(a, name, in_fn)) break :blk true;
break :blk false;
},
.super_member => |m| m.computed != null and nameRefInClosure(m.computed.?, name, in_fn),
.call => |c| blk: {
if (nameRefInClosure(c.callee, name, in_fn)) break :blk true;
for (c.args) |a| if (nameRefInClosure(a, name, in_fn)) break :blk true;
break :blk false;
},
.new_expr => |c| blk: {
if (nameRefInClosure(c.callee, name, in_fn)) break :blk true;
for (c.args) |a| if (nameRefInClosure(a, name, in_fn)) break :blk true;
break :blk false;
},
.tagged_template => |t| blk: {
if (nameRefInClosure(t.tag, name, in_fn)) break :blk true;
for (t.exprs) |e| if (nameRefInClosure(e, name, in_fn)) break :blk true;
break :blk false;
},
.member => |m| nameRefInClosure(m.object, name, in_fn) or (m.computed != null and nameRefInClosure(m.computed.?, name, in_fn)),
.optional_chain => |c| nameRefInClosure(c, name, in_fn),
.field_init_value => |v| nameRefInClosure(v, name, in_fn),
.private_field_def => |p| nameRefInClosure(p.value, name, in_fn),
.object_lit => |props| blk: {
for (props) |p| {
if (p.key_expr) |ke| if (nameRefInClosure(ke, name, in_fn)) break :blk true;
if (nameRefInClosure(p.value, name, in_fn)) break :blk true;
}
break :blk false;
},
.array_lit => |elems| blk: {
for (elems) |e| if (nameRefInClosure(e, name, in_fn)) break :blk true;
break :blk false;
},
.spread => |s| nameRefInClosure(s, name, in_fn),
.obj_pattern => |p| blk: {
for (p.props) |pp| {
if (pp.key_expr) |ke| if (nameRefInClosure(ke, name, in_fn)) break :blk true;
if (nameRefInClosure(pp.target, name, in_fn)) break :blk true;
if (pp.default) |d| if (nameRefInClosure(d, name, in_fn)) break :blk true;
}
if (p.rest) |r| if (nameRefInClosure(r, name, in_fn)) break :blk true;
break :blk false;
},
.arr_pattern => |p| blk: {
for (p.elems) |e| {
if (e.target) |t| if (nameRefInClosure(t, name, in_fn)) break :blk true;
if (e.default) |d| if (nameRefInClosure(d, name, in_fn)) break :blk true;
}
if (p.rest) |r| if (nameRefInClosure(r, name, in_fn)) break :blk true;
break :blk false;
},
.var_decl => |d| d.init != null and nameRefInClosure(d.init.?, name, in_fn),
.destructure_decl => |d| nameRefInClosure(d.pattern, name, in_fn) or nameRefInClosure(d.init, name, in_fn),
.return_stmt => |r| r != null and nameRefInClosure(r.?, name, in_fn),
.throw_stmt => |t| nameRefInClosure(t, name, in_fn),
.try_stmt => |t| blk: {
if (nameRefInClosure(t.block, name, in_fn)) break :blk true;
if (t.catch_param) |cp| if (nameRefInClosure(cp, name, in_fn)) break :blk true;
if (t.catch_block) |cb| if (nameRefInClosure(cb, name, in_fn)) break :blk true;
if (t.finally_block) |fb| if (nameRefInClosure(fb, name, in_fn)) break :blk true;
break :blk false;
},
.labeled_stmt => |l| nameRefInClosure(l.body, name, in_fn),
.expr_stmt => |e| nameRefInClosure(e, name, in_fn),
.block => |stmts| blk: {
for (stmts) |s| if (nameRefInClosure(s, name, in_fn)) break :blk true;
break :blk false;
},
.decl_group => |stmts| blk: {
for (stmts) |s| if (nameRefInClosure(s, name, in_fn)) break :blk true;
break :blk false;
},
.program => |stmts| blk: {
for (stmts) |s| if (nameRefInClosure(s, name, in_fn)) break :blk true;
break :blk false;
},
.if_stmt => |i| nameRefInClosure(i.cond, name, in_fn) or nameRefInClosure(i.consequent, name, in_fn) or (i.alternate != null and nameRefInClosure(i.alternate.?, name, in_fn)),
.while_stmt => |s| nameRefInClosure(s.cond, name, in_fn) or nameRefInClosure(s.body, name, in_fn),
.do_while_stmt => |s| nameRefInClosure(s.body, name, in_fn) or nameRefInClosure(s.cond, name, in_fn),
.for_stmt => |f| blk: {
if (f.init) |ini| if (nameRefInClosure(ini, name, in_fn)) break :blk true;
if (f.cond) |c| if (nameRefInClosure(c, name, in_fn)) break :blk true;
if (f.update) |u| if (nameRefInClosure(u, name, in_fn)) break :blk true;
break :blk nameRefInClosure(f.body, name, in_fn);
},
.for_in => |f| blk: {
if (nameRefInClosure(f.target, name, in_fn)) break :blk true;
if (f.var_init) |vi| if (nameRefInClosure(vi, name, in_fn)) break :blk true;
if (nameRefInClosure(f.iterable, name, in_fn)) break :blk true;
break :blk nameRefInClosure(f.body, name, in_fn);
},
.switch_stmt => |sw| blk: {
if (nameRefInClosure(sw.disc, name, in_fn)) break :blk true;
for (sw.cases) |c| {
if (c.@"test") |t| if (nameRefInClosure(t, name, in_fn)) break :blk true;
for (c.body) |s| if (nameRefInClosure(s, name, in_fn)) break :blk true;
}
break :blk false;
},
.with_stmt => |w| nameRefInClosure(w.obj, name, in_fn) or nameRefInClosure(w.body, name, in_fn),
.export_decl => |e| blk: {
if (e.declaration) |d| if (nameRefInClosure(d, name, in_fn)) break :blk true;
if (e.default_expr) |d| if (nameRefInClosure(d, name, in_fn)) break :blk true;
break :blk false;
},
.import_call => |ic| nameRefInClosure(ic.specifier, name, in_fn) or (ic.options != null and nameRefInClosure(ic.options.?, name, in_fn)),
};
}
/// A nested function/arrow captures `name` if its body — or any parameter default
/// or destructuring-pattern parameter (which execute in the function's own scope)
/// — references it. Always searched with `in_fn = true`.
fn fnCaptures(fnode: *const ast.FunctionNode, name: []const u8) bool {
for (fnode.params) |p| {
if (p.default) |d| if (nameRefInClosure(d, name, true)) return true;
if (p.pattern) |pat| if (nameRefInClosure(pat, name, true)) return true;
}
return nameRefInClosure(fnode.body, name, true);
}
/// Conservatively, does a statement subtree contain a construct that could leave a
/// `with` block ABRUPTLY (skipping the matching `exit_with`, which would leave the
/// VM's environment pointing at the popped with-record)? `with` bodies that might
/// `yield`/`return`/`throw`/`break`/`continue` are kept on the tree-walker. Stops at
/// nested function boundaries (their control flow is self-contained). Overly strict
/// (a `break` for an inner loop inside the `with` also bails), but always safe.
fn stmtCanEscapeAbruptly(node: *const ast.Node) bool {
return switch (node.*) {
.yield_expr, .return_stmt, .throw_stmt, .break_stmt, .continue_stmt => true,
.function => false,
.block => |b| blk: {
for (b) |s| if (stmtCanEscapeAbruptly(s)) break :blk true;
break :blk false;
},
.if_stmt => |i| stmtCanEscapeAbruptly(i.consequent) or (i.alternate != null and stmtCanEscapeAbruptly(i.alternate.?)),
.while_stmt => |s| stmtCanEscapeAbruptly(s.body),
.do_while_stmt => |s| stmtCanEscapeAbruptly(s.body),
.for_stmt => |f| stmtCanEscapeAbruptly(f.body),
.for_in => |f| stmtCanEscapeAbruptly(f.body),
.with_stmt => |w| stmtCanEscapeAbruptly(w.body),
.labeled_stmt => |l| stmtCanEscapeAbruptly(l.body),
.try_stmt => |t| stmtCanEscapeAbruptly(t.block) or
(t.catch_block != null and stmtCanEscapeAbruptly(t.catch_block.?)) or
(t.finally_block != null and stmtCanEscapeAbruptly(t.finally_block.?)),
.switch_stmt => |sw| blk: {
for (sw.cases) |c| for (c.body) |s| if (stmtCanEscapeAbruptly(s)) break :blk true;
break :blk false;
},
// An expression statement may embed a `yield` (e.g. `x = yield`).
else => nodeHasYield(node),
};
}
fn stmtContainsFuncDecl(node: *const ast.Node) bool {
return switch (node.*) {
.func_decl => true,
.function => false,
.block => |b| blk: {
for (b) |s| if (stmtContainsFuncDecl(s)) break :blk true;
break :blk false;
},
.if_stmt => |i| stmtContainsFuncDecl(i.consequent) or (i.alternate != null and stmtContainsFuncDecl(i.alternate.?)),
.while_stmt => |s| stmtContainsFuncDecl(s.body),
.do_while_stmt => |s| stmtContainsFuncDecl(s.body),
.for_stmt => |f| stmtContainsFuncDecl(f.body),
.for_in => |f| stmtContainsFuncDecl(f.body),
.with_stmt => |w| stmtContainsFuncDecl(w.body),
.labeled_stmt => |l| stmtContainsFuncDecl(l.body),
.try_stmt => |t| stmtContainsFuncDecl(t.block) or
(t.catch_block != null and stmtContainsFuncDecl(t.catch_block.?)) or
(t.finally_block != null and stmtContainsFuncDecl(t.finally_block.?)),
.switch_stmt => |sw| blk: {
for (sw.cases) |c| for (c.body) |s| if (stmtContainsFuncDecl(s)) break :blk true;
break :blk false;
},
else => false,
};
}
fn stmtListContainsNestedFuncDecl(stmts: []*Node) bool {
for (stmts) |s| switch (s.*) {
.func_decl => {},
else => if (stmtContainsFuncDecl(s)) return true,
};
return false;
}
fn functionHasBlockNestedFuncDecl(fnode: *const ast.FunctionNode) bool {
if (fnode.is_expr_body) return false;
return switch (fnode.body.*) {
.block => |stmts| stmtListContainsNestedFuncDecl(stmts),
else => stmtContainsFuncDecl(fnode.body),
};
}
fn stmtHasDisposableDecl(node: *const ast.Node) bool {
return switch (node.*) {
.var_decl => |d| d.dispose != 0,
.decl_group => |stmts| stmtListHasDisposableDecl(stmts),
else => false,
};
}
fn stmtListHasDisposableDecl(stmts: []*Node) bool {
for (stmts) |s| if (stmtHasDisposableDecl(s)) return true;
return false;
}
fn stmtHasAwaitUsingDecl(node: *const ast.Node) bool {
return switch (node.*) {
.var_decl => |d| d.dispose == 2,
.decl_group => |stmts| stmtListHasAwaitUsingDecl(stmts),
else => false,
};
}
fn stmtListHasAwaitUsingDecl(stmts: []*Node) bool {
for (stmts) |s| if (stmtHasAwaitUsingDecl(s)) return true;
return false;
}
fn stmtAwaitUsingDeclCount(node: *const ast.Node) usize {
return switch (node.*) {
.var_decl => |d| if (d.dispose == 2) 1 else 0,
.decl_group => |stmts| stmtListAwaitUsingDeclCount(stmts),
else => 0,
};
}
fn stmtListAwaitUsingDeclCount(stmts: []*Node) usize {
var count: usize = 0;
for (stmts) |s| count += stmtAwaitUsingDeclCount(s);
return count;
}
fn stmtListCanEscapeAbruptly(stmts: []*Node) bool {
for (stmts) |s| if (stmtCanEscapeAbruptly(s)) return true;
return false;
}
/// Where a referenced name lives.
const Resolved = union(enum) {
local: u32, // slot in the current frame
upval: struct { depth: u32, slot: u32 }, // an enclosing function's frame
global, // by name, against the Environment
};
pub const Compiler = struct {
arena: std.mem.Allocator,
chunk: *Chunk,
mode: Mode,
scope: ?*FnScope = null,
loops: std.ArrayListUnmanaged(*Loop) = .empty,
/// True while lowering a generator body, so `yield` may emit `gen_yield`.
in_generator: bool = false,
/// True while lowering an async function body, so `await` may suspend (it
/// reuses `gen_yield`; the async driver resumes it on promise settlement).
in_async: bool = false,
/// Counter for synthesized temp names (`yield*` iterator/result holders).
tmp_counter: u32 = 0,
/// >0 while compiling inside a `try` that has a `finally`. A `return`/`break`/
/// `continue` crossing it is lowered as `abrupt_*` so the finally still runs.
finally_depth: u32 = 0,
/// How many `finally` BLOCKS we are currently compiling the body of (nested).
/// A `return` in a finally body does not cross THAT finally (it is already
/// running), only enclosing ones — so a return is a tail-call candidate when
/// `finally_depth == active_finally` (every counted finally is one we are
/// inside the body of, none pending). Kept separate from `finally_depth` so
/// break/continue abrupt-vs-plain accounting (which compares against a loop's
/// captured `finally_depth`) is unaffected.
active_finally: u32 = 0,
/// >0 while compiling the body of a `try` whose catch handler is still live on
/// the VM handler stack (the no-finally case). A call in tail position there
/// must NOT be a tail call: the handler has to survive the call so a throw from
/// the callee is caught, but the tail-pop would discard it. Suppresses TCO in
/// compileTailExpr. (The finally case keeps the handler live via abrupt_return.)
try_depth: u32 = 0,
/// True while compiling a STRICT function body. Proper tail calls
/// (PrepareForTailCall) are a strict-mode-only guarantee, so compileTailExpr
/// only reuses the frame when this is set. A sloppy tail call must grow the
/// stack like any call and eventually throw RangeError (matching the
/// tree-walker) rather than looping forever on `function f(){ return f(); }`.
is_strict: bool = false,
/// Compile a whole program into a fresh chunk. The chunk ends with `halt`;
/// the VM returns its completion accumulator. Program scope is null, so all
/// top-level bindings are globals.
pub fn compileProgram(arena: std.mem.Allocator, program: *Node) CompileError!*Chunk {
const chunk = try arena.create(Chunk);
chunk.* = Chunk.init(arena);
var c = Compiler{ .arena = arena, .chunk = chunk, .mode = .program };
if (program.* != .program) return error.Unsupported;
try c.compileStmtList(program.program);
_ = try chunk.emit(.halt, 0);
try chunk.finalize();
return chunk;
}
/// Compile a `function*` body into its own chunk, run by the suspendable VM
/// (`vm.genNext`). Unlike `compileFunction`, this uses **env-mode** (no frame
/// scope): the body's parameters, locals, and free variables all resolve by
/// name against the generator's `Environment`, bound at call time. That keeps
/// a generator interoperable with the tree-walked code around it (shared
/// environment) and lets `yield` suspend mid-expression by snapshotting the
/// operand stack. Returns `error.Unsupported` for bodies (or parameter forms)
/// outside the VM's lowered subset, so the generator is reported unsupported
/// rather than run incorrectly.
pub fn compileGenerator(arena: std.mem.Allocator, fnode: *const ast.FunctionNode) CompileError!*Chunk {
// Parameters (including default/rest/destructuring) are bound at runtime
// by `makeGenerator` into the generator's environment — env-mode name
// resolution means the body's references resolve there — so the param
// shape never blocks compilation; only the body must lower.
if (fnode.is_expr_body) return error.Unsupported; // generators always have a block body
const chunk = try arena.create(Chunk);
chunk.* = Chunk.init(arena);
// An async generator body may also `await` (in_async enables await_op).
var c = Compiler{ .arena = arena, .chunk = chunk, .mode = .function, .scope = null, .in_generator = true, .in_async = fnode.is_async };
try c.compileStmt(fnode.body); // body is a block
_ = try chunk.emit(.ret_undef, 0);
try chunk.finalize();
return chunk;
}
/// Compile a plain `async function` body for the suspendable VM (env-mode,
/// like a generator). `await` lowers to a suspend (`gen_yield`); the async
/// driver promisifies the suspended value, resumes on settlement, and
/// settles the function's result promise on completion.
pub fn compileAsync(arena: std.mem.Allocator, fnode: *const ast.FunctionNode) CompileError!*Chunk {
if (fnode.is_generator) return error.Unsupported; // async generators not lowered yet
const chunk = try arena.create(Chunk);
chunk.* = Chunk.init(arena);
var c = Compiler{ .arena = arena, .chunk = chunk, .mode = .function, .scope = null, .in_async = true };
if (fnode.is_expr_body) {
try c.compileExpr(fnode.body);
_ = try chunk.emit(.ret, 0);
} else {
try c.compileStmt(fnode.body);
_ = try chunk.emit(.ret_undef, 0);
}
try chunk.finalize();
return chunk;
}
const ShadowBind = struct { count: u32 = 0, lexical: bool = false };
fn shadowAdd(arena: std.mem.Allocator, m: *std.StringHashMapUnmanaged(ShadowBind), name: []const u8, lexical: bool) CompileError!void {
if (name.len == 0) return;
const gop = try m.getOrPut(arena, name);
if (!gop.found_existing) gop.value_ptr.* = .{};
gop.value_ptr.count += 1;
if (lexical) gop.value_ptr.lexical = true;
}
fn shadowScanPattern(arena: std.mem.Allocator, m: *std.StringHashMapUnmanaged(ShadowBind), pattern: *Node, lexical: bool) CompileError!void {
switch (pattern.*) {
.identifier => |name| try shadowAdd(arena, m, name, lexical),
.obj_pattern => |p| {
for (p.props) |prop| try shadowScanPattern(arena, m, prop.target, lexical);
if (p.rest) |r| if (r.* == .identifier) try shadowAdd(arena, m, r.identifier, lexical);
},
.arr_pattern => |p| {
for (p.elems) |elem| if (elem.target) |t| try shadowScanPattern(arena, m, t, lexical);
if (p.rest) |rest| try shadowScanPattern(arena, m, rest, lexical);
},
else => {},
}
}
fn shadowScanStmt(arena: std.mem.Allocator, m: *std.StringHashMapUnmanaged(ShadowBind), node: *Node) CompileError!void {
switch (node.*) {
.var_decl => |d| try shadowAdd(arena, m, d.name, d.kind != .@"var"),
.destructure_decl => |d| try shadowScanPattern(arena, m, d.pattern, d.kind != .@"var"),
.func_decl => |f| try shadowAdd(arena, m, f.name, false), // nested fn has its own scope; don't descend
.block => |stmts| for (stmts) |s| try shadowScanStmt(arena, m, s),
.decl_group => |stmts| for (stmts) |s| try shadowScanStmt(arena, m, s),
.if_stmt => |s| {
try shadowScanStmt(arena, m, s.consequent);
if (s.alternate) |a| try shadowScanStmt(arena, m, a);
},
.while_stmt => |s| try shadowScanStmt(arena, m, s.body),
.do_while_stmt => |s| try shadowScanStmt(arena, m, s.body),
.for_stmt => |f| {
if (f.init) |i| try shadowScanStmt(arena, m, i);
try shadowScanStmt(arena, m, f.body);
},
.for_in => |f| {
if (f.decl_kind) |k| try shadowScanPattern(arena, m, f.target, k != .@"var");
try shadowScanStmt(arena, m, f.body);
},
.switch_stmt => |s| for (s.cases) |c| for (c.body) |st| try shadowScanStmt(arena, m, st),
.labeled_stmt => |s| try shadowScanStmt(arena, m, s.body),
.try_stmt => |t| {
try shadowScanStmt(arena, m, t.block);
if (t.catch_param) |p| try shadowScanPattern(arena, m, p, true); // catch binding is lexical
if (t.catch_block) |cb| try shadowScanStmt(arena, m, cb);
if (t.finally_block) |fb| try shadowScanStmt(arena, m, fb);
},
else => {},
}
}
/// The VM's `FnScope` keys locals by name across ALL block scopes (flat,
/// block-transparent slots), so two DIFFERENT bindings that share a name —
/// nested `let` shadowing, a catch param shadowing an outer binding, a `let`
/// shadowing a `var`/param — would collapse onto one slot and clobber each
/// other (and there is no TDZ). Detect any name introduced by a lexical
/// binding that also appears as another binding, and keep such a function on
/// the tree-walker, which scopes blocks correctly. Conservative: also bails
/// harmless same-name sibling blocks, which only forgoes tiering.
fn functionHasShadowableLexical(arena: std.mem.Allocator, fnode: *const ast.FunctionNode) CompileError!bool {
var m: std.StringHashMapUnmanaged(ShadowBind) = .empty;
for (fnode.params) |p| try shadowAdd(arena, &m, p.name, false);
if (!fnode.is_expr_body) try shadowScanStmt(arena, &m, fnode.body);
var it = m.iterator();
while (it.next()) |e| if (e.value_ptr.lexical and e.value_ptr.count >= 2) return true;
return false;
}
fn tdzDeclarePattern(arena: std.mem.Allocator, declared: *std.StringHashMapUnmanaged(void), pattern: *Node) CompileError!void {
switch (pattern.*) {
.identifier => |name| try declared.put(arena, name, {}),
.obj_pattern => |p| {
for (p.props) |prop| try tdzDeclarePattern(arena, declared, prop.target);
if (p.rest) |r| if (r.* == .identifier) try declared.put(arena, r.identifier, {});
},
.arr_pattern => |p| {
for (p.elems) |elem| if (elem.target) |t| try tdzDeclarePattern(arena, declared, t);
if (p.rest) |rest| try tdzDeclarePattern(arena, declared, rest);
},
else => {},
}
}
/// Does `node` reference (as an identifier) any lexical name from `m` that has
/// not been declared yet? Such a read would hit the Temporal Dead Zone.
fn tdzRefsPending(node: *Node, m: *const std.StringHashMapUnmanaged(ShadowBind), declared: *const std.StringHashMapUnmanaged(void)) bool {
var it = m.iterator();
while (it.next()) |e| {
if (!e.value_ptr.lexical) continue;
if (declared.contains(e.key_ptr.*)) continue;
if (nameRefInClosure(node, e.key_ptr.*, true)) return true;
}
return false;
}
/// Walk statements in source order, growing `declared` as each lexical binding
/// is reached, and report a read of a still-undeclared lexical (a TDZ hazard).
fn tdzScanStmt(arena: std.mem.Allocator, node: *Node, m: *const std.StringHashMapUnmanaged(ShadowBind), declared: *std.StringHashMapUnmanaged(void)) CompileError!bool {
switch (node.*) {
.var_decl => |d| {
if (d.init) |init| if (tdzRefsPending(init, m, declared)) return true;
if (d.kind != .@"var") try declared.put(arena, d.name, {});
},
.destructure_decl => |d| {
if (tdzRefsPending(d.init, m, declared)) return true;
if (d.kind != .@"var") try tdzDeclarePattern(arena, declared, d.pattern);
},
.expr_stmt => |e| return tdzRefsPending(e, m, declared),
.return_stmt => |mb| {
if (mb) |e| return tdzRefsPending(e, m, declared);
},
.throw_stmt => |e| return tdzRefsPending(e, m, declared),
.if_stmt => |s| {
if (tdzRefsPending(s.cond, m, declared)) return true;
if (try tdzScanStmt(arena, s.consequent, m, declared)) return true;
if (s.alternate) |a| if (try tdzScanStmt(arena, a, m, declared)) return true;
},
.while_stmt => |s| {
if (tdzRefsPending(s.cond, m, declared)) return true;
return tdzScanStmt(arena, s.body, m, declared);
},
.do_while_stmt => |s| {
if (try tdzScanStmt(arena, s.body, m, declared)) return true;
return tdzRefsPending(s.cond, m, declared);
},
.for_stmt => |f| {
if (f.init) |i| if (try tdzScanStmt(arena, i, m, declared)) return true;
if (f.cond) |c| if (tdzRefsPending(c, m, declared)) return true;
if (f.update) |u| if (tdzRefsPending(u, m, declared)) return true;
return tdzScanStmt(arena, f.body, m, declared);
},
.for_in => |f| {
if (tdzRefsPending(f.iterable, m, declared)) return true;
if (f.decl_kind) |k| if (k != .@"var") try tdzDeclarePattern(arena, declared, f.target);
return tdzScanStmt(arena, f.body, m, declared);
},
.block => |stmts| for (stmts) |s| {
if (try tdzScanStmt(arena, s, m, declared)) return true;
},
.decl_group => |stmts| for (stmts) |s| {
if (try tdzScanStmt(arena, s, m, declared)) return true;
},
.switch_stmt => |sw| {
if (tdzRefsPending(sw.disc, m, declared)) return true;
for (sw.cases) |c| {
if (c.@"test") |t| if (tdzRefsPending(t, m, declared)) return true;
for (c.body) |st| if (try tdzScanStmt(arena, st, m, declared)) return true;
}
},
.labeled_stmt => |s| return tdzScanStmt(arena, s.body, m, declared),
.try_stmt => |t| {
if (try tdzScanStmt(arena, t.block, m, declared)) return true;
if (t.catch_param) |p| try tdzDeclarePattern(arena, declared, p);
if (t.catch_block) |cb| if (try tdzScanStmt(arena, cb, m, declared)) return true;
if (t.finally_block) |fb| if (try tdzScanStmt(arena, fb, m, declared)) return true;
},
.func_decl => {}, // hoisted; not a read site here
else => return tdzRefsPending(node, m, declared), // unknown node: sound fallback
}
return false;
}
/// The VM has no Temporal Dead Zone: an uninitialized `let`/`const` slot reads
/// as `undefined` instead of throwing ReferenceError. Detecting a read of a
/// lexical before its declaration would need a per-load check on the hot path,
/// so instead keep any function that could hit its TDZ on the tree-walker,
/// which enforces it. Runs after the shadowing check, so lexical names are
/// unique here. Conservative (a captured forward reference also bails).
fn functionHasTdzHazard(arena: std.mem.Allocator, fnode: *const ast.FunctionNode) CompileError!bool {
if (fnode.is_expr_body) return false;
var m: std.StringHashMapUnmanaged(ShadowBind) = .empty;
for (fnode.params) |p| try shadowAdd(arena, &m, p.name, false);
try shadowScanStmt(arena, &m, fnode.body);
// With no lexical bindings collected, tdzRefsPending never fires.
var declared: std.StringHashMapUnmanaged(void) = .empty;
return tdzScanStmt(arena, fnode.body, &m, &declared);
}
pub const PlainFunctionCode = struct {
chunk: *Chunk,
local_count: u32,
};
pub fn compilePlainFunction(arena: std.mem.Allocator, fnode: *const ast.FunctionNode) CompileError!PlainFunctionCode {
if (fnode.is_generator or fnode.is_async) return error.Unsupported;
// A function declaration nested in a block needs the tree-walker in BOTH
// modes: strict scopes it to the block (a binding the flat slot model
// can't isolate), and sloppy gives it Annex B.3.3 dual bindings — a block
// lexical AND a function-scope var that is assigned the block binding's
// value at the point the declaration is evaluated. The flat model has one
// slot for the name, so it reports the block's final value instead of the
// decl-time snapshot (e.g. a reassignment after the declaration leaks).
if (functionHasBlockNestedFuncDecl(fnode)) return error.Unsupported;
// The flat slot model can't represent a lexical binding shadowing another
// same-named binding; keep those on the tree-walker (correct block scopes).
if (try functionHasShadowableLexical(arena, fnode)) return error.Unsupported;
// The VM has no TDZ; keep functions that could read a lexical before its
// declaration on the tree-walker, which throws ReferenceError.
if (try functionHasTdzHazard(arena, fnode)) return error.Unsupported;
const scope = try arena.create(FnScope);
scope.* = .{ .parent = null };
for (fnode.params) |p| {
if (p.default != null or p.is_rest or p.pattern != null) return error.Unsupported;
_ = try scope.addLocal(arena, p.name);
}
if (!fnode.is_expr_body) try collectLocals(arena, scope, fnode.body);
const chunk = try arena.create(Chunk);
chunk.* = Chunk.init(arena);
chunk.param_count = @intCast(fnode.params.len);
chunk.local_count = scope.count;
var c = Compiler{ .arena = arena, .chunk = chunk, .mode = .function, .scope = scope, .is_strict = fnode.is_strict };
if (fnode.is_expr_body) {
try c.compileTailExpr(fnode.body);
} else {
try c.compileStmt(fnode.body);
_ = try chunk.emit(.ret_undef, 0);
}
try chunk.finalize();
return .{ .chunk = chunk, .local_count = scope.count };
}
// ---- name resolution --------------------------------------------------
fn resolve(self: *Compiler, name: []const u8) Resolved {
var depth: u32 = 0;
var scope = self.scope;
while (scope) |sc| {
if (sc.names.get(name)) |slot| {
return if (depth == 0) .{ .local = slot } else .{ .upval = .{ .depth = depth, .slot = slot } };
}
depth += 1;
scope = sc.parent;
}
return .global;
}
/// Emit a load of `name` to the appropriate location (local / upvalue / global).
fn emitLoad(self: *Compiler, name: []const u8) CompileError!void {
// `arguments` inside a function is bound by the tree-walker only.
if (self.scope != null and std.mem.eql(u8, name, "arguments")) return error.Unsupported;
switch (self.resolve(name)) {
.local => |slot| _ = try self.chunk.emit(.load_local, slot),
.upval => |u| _ = try self.chunk.emitAB(.load_upval, u.depth, u.slot),
.global => _ = try self.chunk.emit(.load_var, try self.chunk.addName(name)),
}
}
/// Emit a store to `name` (assignment); leaves the value on the stack.
fn emitStore(self: *Compiler, name: []const u8) CompileError!void {
switch (self.resolve(name)) {
.local => |slot| _ = try self.chunk.emit(.store_local, slot),
.upval => |u| _ = try self.chunk.emitAB(.store_upval, u.depth, u.slot),
.global => _ = try self.chunk.emit(.store_var, try self.chunk.addName(name)),
}
}
/// Emit a definition of `name` (var/let/const/function decl) with its value
/// already on the stack; consumes the value.
fn emitDefine(self: *Compiler, name: []const u8) CompileError!void {
try self.emitDefineForce(name);
}
fn emitDefineForce(self: *Compiler, name: []const u8) CompileError!void {
switch (self.resolve(name)) {
.local => |slot| {
_ = try self.chunk.emit(.store_local, slot);
_ = try self.chunk.emit(.pop, 0);
},
.upval => |u| {
_ = try self.chunk.emitAB(.store_upval, u.depth, u.slot);
_ = try self.chunk.emit(.pop, 0);
},
.global => _ = try self.chunk.emitAB(.def_var, try self.chunk.addName(name), 2),
}
}
/// `has_init` marks a `var x = init` (vs a bare `var x;`): only the
/// initializer form may have its write redirected to a `with` object that
/// provides `x` (ResolveBinding before PutValue) — a bare declaration never
/// touches the `with` object.
fn emitDefineKind(self: *Compiler, name: []const u8, kind: ast.DeclKind, has_init: bool) CompileError!void {
switch (self.resolve(name)) {
.local => |slot| {
_ = try self.chunk.emit(.store_local, slot);
_ = try self.chunk.emit(.pop, 0);
},
.upval => |u| {
_ = try self.chunk.emitAB(.store_upval, u.depth, u.slot);
_ = try self.chunk.emit(.pop, 0);
},
.global => {
const ni = try self.chunk.addName(name);
// In env-mode (program / generator / async body) a `let`/`const`
// binds in the current lexical environment via `def_lex` (tracking
// const-ness and keeping it distinct from the variable scope's
// `var`s); a `var` hoists to the variable scope via `def_var`.
if (kind != .@"var")
_ = try self.chunk.emitAB(.def_lex, ni, if (kind == .@"const") 2 else 1)
else
// Only a real `var x = init` (b == 1) may redirect to a `with`
// object; a non-program `let`/`const` reaching this branch is a
// fresh lexical binding and must never touch the `with` object.
_ = try self.chunk.emitAB(.def_var, ni, if (has_init and kind == .@"var") 1 else 0);
},
}
}
// ---- statements -------------------------------------------------------
/// Compile a statement list with function-declaration hoisting: every
/// `func_decl` is emitted (closure + define) first, so forward references
/// like `bar(); function bar() {}` resolve, then the remaining statements
/// run in order (func_decls skipped, so each binds exactly once).
fn compileStmtList(self: *Compiler, stmts: []*Node) CompileError!void {
for (stmts) |s| switch (s.*) {
.func_decl => |fnode| {
const fi = try self.compileFunction(fnode, false);
_ = try self.chunk.emit(.make_closure, fi);
try self.emitDefineForce(fnode.name);
},
else => {},
};
for (stmts) |s| {
if (s.* == .func_decl) continue;
try self.compileStmt(s);
}
}
/// NamedEvaluation: if `value_node` is a bare anonymous function/class def
/// (matching interpreter.isAnonFnDef), emit `name_anon` so the value now on
/// the stack takes `name` as its Function.name — mirroring the tree-walker's
/// maybeNameAnon so `var f = function(){}` / `{foo: function(){}}` / `x = () =>
/// {}` name their functions on the VM too.
fn emitNamedEval(self: *Compiler, value_node: *const Node, name: []const u8) CompileError!void {
const anon = switch (value_node.*) {
.function => |f| f.name.len == 0,
.func_decl => |f| f.name.len == 0,
.class_expr => |c| c.name.len == 0,
else => false,
};
if (anon) _ = try self.chunk.emit(.name_anon, try self.chunk.addName(name));
}
fn compileStmt(self: *Compiler, node: *Node) CompileError!void {
switch (node.*) {
.var_decl => |d| {
if (d.init) |init_node| {
try self.compileExpr(init_node);
try self.emitNamedEval(init_node, d.name);
} else {
_ = try self.chunk.emit(.load_undefined, 0);
}
// `using x = v;` / `await using x = v;`: keep a copy of the resource
// to register for DisposeResources at the variable scope's exit.
if (d.dispose != 0) _ = try self.chunk.emit(.dup, 0);
try self.emitDefineKind(d.name, d.kind, d.init != null);
if (d.dispose != 0) _ = try self.chunk.emit(.register_disposable, if (d.dispose == 2) 1 else 0);
},
.destructure_decl => |d| {
if (self.scope != null) return error.Unsupported;
if (nodeHasYield(d.pattern)) {
if (d.kind != .@"var") return error.Unsupported;
try self.emitPatternVarDecls(d.pattern);
try self.compileDestructuringAssign(d.pattern, d.init);
_ = try self.chunk.emit(.pop, 0);
return;
}
try self.compileExpr(d.init);
const pi = try self.chunk.addPattern(d.pattern);
const mode: u32 = switch (d.kind) {
.@"var" => 0,
.let => 1,
.@"const" => 2,
};
_ = try self.chunk.emitAB(.bind_pattern, pi, mode);
},
.func_decl => |fnode| {
const fi = try self.compileFunction(fnode, false);
_ = try self.chunk.emit(.make_closure, fi);
try self.emitDefineForce(fnode.name);
},
.return_stmt => |maybe| {
// A `return` that crosses a PENDING finally (one not currently
// executing) must run it first: `abrupt_return` unwinds the
// handler stack, runs each finally carrying a return completion,
// and returns once they finish — a bare `ret` would skip it. A
// return directly in a finally BODY crosses only enclosing
// finallys, so `finally_depth > active_finally` is the real
// "pending finally to run" test (not `finally_depth > 0`).
if (self.finally_depth > self.active_finally) {
if (maybe) |e| {
try self.compileExpr(e);
if (self.in_generator and self.in_async) _ = try self.chunk.emit(.await_op, 0);