lower-lang 0.4.1

Lowers lossless syntax trees into HIR through declarative semantic archetypes and hygienic templates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
//! Instantiating a template: build its HIR with an explicit stack, one
//! expansion per instantiation (and per nested `apply`), fresh marked binders,
//! and the holes' values substituted.
//!
//! The holes of the template a node uses were lowered as the frame's fields
//! before this runs. A hole used once takes its value; each further use takes
//! a copy (`Builder::copy_subtree`, fresh binders for everything bound inside),
//! so HIR stays a tree. An `apply` evaluates the applied template in a new
//! context whose holes forward to the arguments, evaluated lazily in the
//! applying context.

use alloc::vec::Vec;

use hir_lang::{
    Arg, Arm, BindMode, BinderId, BinderKind, Block, Capture, Closure, DefaultEval, Expansion,
    ExpnId, Expr, ExprId, FloatLit, Ident, IntLit, List, Lit, Member, Name, NodeRef, Ns, Origin,
    Param, Pat, PatId, Path, Res, Segment, Span, Stmt, StmtId, Ty, TyId,
};
use syntax_lang::TokenKind;

use super::{Frame, Persist, Run, Slot, Val};
use crate::problem::{HoistBlocker, ProblemKind};
use crate::template::{
    HoleKind, LabelRef, LabelSlot, NONE, TArg, TLit, TNode, Template, TemplateId,
};

/// One instantiation context: a template, its expansion, its binder and
/// label tables, and where its holes come from.
#[derive(Clone, Copy)]
struct Ctx {
    tpl: u32,
    expn: ExpnId,
    benv: usize,
    lenv: usize,
    /// The applying context, or `NONE` for the instantiation the node made.
    parent: u32,
    /// The `apply`'s arguments in the parent template's argument pool.
    args: (u32, u32),
    depth: u32,
}

/// Where a hole's value comes from.
enum Source {
    /// The node's own hole `h` (lowered user code).
    Top(usize),
    /// A template node, evaluated in a context.
    Node(u32, u32),
    /// Nothing: an absent optional hole of template `tpl`.
    Absent(u32, usize),
}

#[derive(Clone, Copy)]
enum Work {
    Enter(u32, u32),
    Exit(u32, u32),
}

/// Buffers one instantiation uses, kept by the run and reused, so
/// instantiating a template allocates nothing once they have grown.
#[derive(Default)]
pub(crate) struct TplScratch {
    ctxs: Vec<Ctx>,
    benv: Vec<Option<BinderId>>,
    lenv: Vec<Option<BinderId>>,
    work: Vec<Work>,
    out: Vec<Slot>,
    kids: Vec<u32>,
    res: Vec<Slot>,
    uses: Vec<u32>,
}

/// Per-instantiation state for the node's own holes.
struct Holes {
    uses: Vec<u32>,
    /// Nodes the holes' user code took to build: the conservative charge for
    /// one copy of a hole.
    charge: u64,
    label: Option<BinderId>,
    missing_reported: bool,
    /// Function-scoped bindings of the pattern holes, and each hole's range
    /// in it (PHP scoping); whether each hole's were assigned already.
    binds: Vec<Persist>,
    ranges: Vec<(usize, usize)>,
    injected: Vec<bool>,
}

impl<K> Run<'_, '_, K>
where
    K: Copy + Ord + TokenKind,
{
    pub(crate) fn finish_template(
        &mut self,
        f: &Frame<K>,
        id: TemplateId,
        label: Option<BinderId>,
        nodes_at: u64,
    ) -> Val {
        let m = self.m;
        let span = f.span;
        let Some(t) = m.templates.get(id.index()) else {
            let e = self.err_expr(span);
            return self.adapt_expr(e, false, f.want, span);
        };
        let mut sc = core::mem::take(&mut self.tpl_scratch);
        sc.uses.clear();
        sc.uses.resize(t.holes.len(), 0);
        let mut holes = Holes {
            uses: core::mem::take(&mut sc.uses),
            charge: self.nodes.saturating_sub(nodes_at),
            label,
            missing_reported: false,
            binds: Vec::new(),
            ranges: Vec::new(),
            injected: Vec::new(),
        };
        if f.flag {
            self.take_hole_binds(t.holes.len(), &mut holes);
        }
        let expn = self.b.expansion(Expansion {
            kind: t.kind,
            name: self.sym(m.template_names.get(id.index()).copied().unwrap_or(0)),
            call_site: span,
            parent: ExpnId::ROOT,
            def_site: ExpnId::ROOT,
        });
        sc.ctxs.clear();
        sc.ctxs.push(Ctx {
            tpl: id.0,
            expn,
            benv: 0,
            lenv: 0,
            parent: NONE,
            args: (0, 0),
            depth: 1,
        });
        sc.benv.clear();
        sc.benv.resize(t.binders.len(), None);
        sc.lenv.clear();
        sc.lenv.resize(t.labels.len(), None);
        sc.work.clear();
        sc.work.push(Work::Enter(t.root, 0));
        sc.out.clear();
        let TplScratch {
            ctxs,
            benv,
            lenv,
            work,
            out,
            kids,
            res,
            ..
        } = &mut sc;
        while let Some(w) = work.pop() {
            if self.nodes > self.budget.max_nodes {
                break;
            }
            match w {
                Work::Enter(n, c) => {
                    self.t_enter(f, n, c, ctxs, benv, lenv, work, out, kids, &mut holes);
                }
                Work::Exit(n, c) => {
                    self.t_exit(f, n, c, ctxs, benv, lenv, out, kids, res, &mut holes);
                }
            }
        }
        let popped = out.pop();
        sc.uses = core::mem::take(&mut holes.uses);
        self.tpl_scratch = sc;
        let result = match popped {
            Some(Slot {
                v: Val::Expr(e), ..
            }) => e,
            _ => self.err_expr(span),
        };
        let uses = core::mem::take(&mut self.tpl_scratch.uses);
        let result = self.rescue(f, &uses, result);
        self.tpl_scratch.uses = uses;
        // A pattern hole whose bindings no `match` arm or `let` assigned.
        for (h, &(s, e)) in holes.ranges.iter().enumerate() {
            if s < e && !holes.injected.get(h).copied().unwrap_or(true) {
                let at = holes.binds.get(s).map_or(span, |p| p.span);
                self.report(
                    ProblemKind::CannotHoist {
                        reason: HoistBlocker::NoBindingSite,
                    },
                    at,
                );
            }
        }
        self.at(span);
        self.adapt_expr(result, false, f.want, span)
    }

    /// Takes this template frame's `Task::Mark`s and the function-scoped
    /// bindings logged between them: hole `h`'s bindings are those logged
    /// between marks `h` and `h + 1`.
    fn take_hole_binds(&mut self, nholes: usize, holes: &mut Holes) {
        let depth = u32::try_from(self.frames.len() + 1).unwrap_or(u32::MAX);
        let mut marks: Vec<usize> = Vec::new();
        while let Some(&(d, len)) = self.persist_marks.last() {
            if d != depth {
                break;
            }
            marks.push(len as usize);
            let _ = self.persist_marks.pop();
        }
        marks.reverse();
        let Some(&first) = marks.first() else {
            return;
        };
        let first = first.min(self.persist.len());
        holes.binds = self.persist.split_off(first);
        holes.ranges = (0..nholes)
            .map(|h| {
                let s = marks.get(h).copied().unwrap_or(first).saturating_sub(first);
                let e = marks
                    .get(h + 1)
                    .copied()
                    .unwrap_or(s + first)
                    .saturating_sub(first);
                (
                    s.min(holes.binds.len()),
                    e.min(holes.binds.len()).max(s.min(holes.binds.len())),
                )
            })
            .collect();
        holes.injected = alloc::vec![false; nholes];
    }

    /// The node's own pattern holes that template pattern `node` (in context
    /// `c`) contains, following `apply` arguments back to their source.
    fn pattern_holes(&self, node: u32, c: u32, ctxs: &[Ctx], out: &mut Vec<usize>) {
        out.clear();
        let mut stack: Vec<(u32, u32)> = alloc::vec![(node, c)];
        while let Some((n, c)) = stack.pop() {
            let Some(t) = ctxs.get(c as usize).and_then(|x| self.tpl_of(x)) else {
                continue;
            };
            match t.node(n).copied() {
                Some(TNode::PHole(h)) => match self.source(usize::from(h), c, ctxs) {
                    Source::Top(h) => out.push(h),
                    Source::Node(pn, pc) => stack.push((pn, pc)),
                    Source::Absent(..) => {}
                },
                Some(TNode::PTuple(l)) => {
                    stack.extend(t.list(l).iter().map(|&k| (k, c)));
                }
                Some(TNode::PCtor { elems, .. }) => {
                    stack.extend(t.list(elems).iter().map(|&k| (k, c)));
                }
                _ => {}
            }
        }
    }

    /// The bindings to assign where a template binds pattern node `pat`:
    /// those of the pattern holes it contains (each hole once; a second
    /// binding site is reported).
    fn binds_at(
        &mut self,
        f: &Frame<K>,
        pat: u32,
        c: u32,
        ctxs: &[Ctx],
        holes: &mut Holes,
    ) -> Vec<Persist> {
        let mut out = Vec::new();
        if holes.binds.is_empty() {
            return out;
        }
        let mut hs = Vec::new();
        self.pattern_holes(pat, c, ctxs, &mut hs);
        hs.sort_unstable();
        hs.dedup();
        for h in hs {
            let Some(&(s, e)) = holes.ranges.get(h) else {
                continue;
            };
            if s >= e {
                continue;
            }
            match holes.injected.get_mut(h) {
                Some(done) if *done => {
                    let at = holes.binds.get(s).map_or(f.span, |p| p.span);
                    self.report(
                        ProblemKind::CannotHoist {
                            reason: HoistBlocker::ReusedHole,
                        },
                        at,
                    );
                }
                Some(done) => {
                    *done = true;
                    out.extend_from_slice(holes.binds.get(s..e).unwrap_or(&[]));
                }
                None => {}
            }
        }
        out
    }

    /// Sets the builder's origin to the call site inside expansion `expn`.
    fn t_at(&mut self, f: &Frame<K>, expn: ExpnId) {
        self.b.set_origin(Origin::expanded(f.span, expn));
    }

    fn tpl_of(&self, ctx: &Ctx) -> Option<&Template> {
        self.m.templates.get(ctx.tpl as usize)
    }

    /// Follows hole `h` of context `c` back to where its value comes from.
    fn source(&self, mut h: usize, mut c: u32, ctxs: &[Ctx]) -> Source {
        loop {
            let Some(ctx) = ctxs.get(c as usize) else {
                return Source::Absent(0, h);
            };
            if ctx.parent == NONE {
                return Source::Top(h);
            }
            let parent = ctx.parent;
            let Some(pt) = ctxs.get(parent as usize).and_then(|p| self.tpl_of(p)) else {
                return Source::Absent(ctx.tpl, h);
            };
            let arg = pt.args.get(ctx.args.0 as usize + h).copied();
            match arg {
                Some(TArg::Expr(e)) => return Source::Node(e.0, parent),
                Some(TArg::Pat(p)) => return Source::Node(p.0, parent),
                Some(TArg::Ty(t)) => return Source::Node(t.0, parent),
                Some(TArg::Stmts(next)) => {
                    h = usize::from(next.0);
                    c = parent;
                }
                Some(TArg::Args(next)) => {
                    h = usize::from(next.0);
                    c = parent;
                }
                Some(TArg::Label(LabelRef::Hole(next))) => {
                    h = usize::from(next.0);
                    c = parent;
                }
                Some(TArg::Label(LabelRef::Own(_)) | TArg::Absent) | None => {
                    return Source::Absent(ctx.tpl, h);
                }
            }
        }
    }

    /// The binder a label slot names in context `c`.
    fn slot_label(
        &self,
        slot: LabelSlot,
        c: u32,
        ctxs: &[Ctx],
        lenv: &[Option<BinderId>],
        holes: &Holes,
    ) -> Option<BinderId> {
        match slot {
            LabelSlot::None => None,
            LabelSlot::Own(l) => {
                let ctx = ctxs.get(c as usize)?;
                lenv.get(ctx.lenv + usize::from(l)).copied().flatten()
            }
            LabelSlot::Hole(h) => {
                let mut h = usize::from(h);
                let mut c = c;
                loop {
                    let ctx = ctxs.get(c as usize)?;
                    if ctx.parent == NONE {
                        return holes.label;
                    }
                    let parent = ctx.parent;
                    let pt = ctxs.get(parent as usize).and_then(|p| self.tpl_of(p))?;
                    match pt.args.get(ctx.args.0 as usize + h).copied()? {
                        TArg::Label(LabelRef::Hole(next)) => {
                            h = usize::from(next.0);
                            c = parent;
                        }
                        TArg::Label(LabelRef::Own(l)) => {
                            let pctx = ctxs.get(parent as usize)?;
                            return lenv.get(pctx.lenv + usize::from(l.0)).copied().flatten();
                        }
                        _ => return None,
                    }
                }
            }
        }
    }

    /// The binder for template binder `b` in context `c`, created on first
    /// touch with the context's hygiene mark.
    fn t_binder(
        &mut self,
        f: &Frame<K>,
        b: usize,
        c: &Ctx,
        benv: &mut [Option<BinderId>],
        kind: BinderKind,
    ) -> Option<BinderId> {
        let slot = benv.get(c.benv + b).copied()?;
        if let Some(id) = slot {
            return Some(id);
        }
        let m = self.m;
        let t = m.templates.get(c.tpl as usize)?;
        let decl = *t.binders.get(b)?;
        let sym = self.sym(t.text_base + decl.name);
        self.t_at(f, c.expn);
        let id = self.binder(Name::marked(sym, c.expn), kind, decl.mutable);
        if let Some(s) = benv.get_mut(c.benv + b) {
            *s = Some(id);
        }
        Some(id)
    }

    /// The value of a node's own hole `h`, taken on first use and copied on
    /// later ones.
    fn top_hole(&mut self, f: &Frame<K>, h: usize, holes: &mut Holes, out: &mut Vec<Slot>) {
        let (s, e) = self.field_range(f, h);
        let first = holes.uses.get(h).copied().unwrap_or(0) == 0;
        if let Some(u) = holes.uses.get_mut(h) {
            *u = u.saturating_add(1);
        }
        let mut vals = self.bufs.pop().unwrap_or_default();
        vals.clear();
        for j in s..e {
            match self.vals.get(j).copied() {
                Some(Slot {
                    v: Val::Spill(ss, sl),
                    ..
                }) => {
                    let (ss, sl) = (ss as usize, sl as usize);
                    if let Some(run) = self.spill.get(ss..ss.saturating_add(sl)) {
                        vals.extend_from_slice(run);
                    }
                }
                Some(slot) => vals.push(slot),
                None => {}
            }
        }
        if !first {
            let charge = holes.charge.max(1);
            if self.nodes.saturating_add(charge) > self.budget.max_nodes {
                // Out of budget: stop here; the run reports `NodeBudget`.
                self.nodes = self.budget.max_nodes.saturating_add(1);
                out.push(Slot {
                    v: Val::Err,
                    span: f.span,
                    place: false,
                });
                return;
            }
            self.nodes += charge;
            for slot in &mut vals {
                slot.v = self.copy_val(slot.v);
            }
        }
        let kind = self
            .tpl_of_id(f)
            .and_then(|t| t.holes.get(h))
            .map(|d| d.kind);
        let v = match kind {
            Some(HoleKind::Stmts | HoleKind::Args) => self.spill_of(&vals),
            _ => match vals.first() {
                Some(slot) => slot.v,
                None => Val::Err,
            },
        };
        self.give(vals);
        out.push(Slot {
            v,
            span: f.span,
            place: false,
        });
    }

    fn tpl_of_id(&self, f: &Frame<K>) -> Option<&Template> {
        match f.build {
            super::Build::Template { id, .. } => self.m.templates.get(id.index()),
            _ => None,
        }
    }

    /// A copy of a hole value (fresh binders for everything bound inside).
    fn copy_val(&mut self, v: Val) -> Val {
        match v {
            Val::Expr(e) => match self.b.copy_subtree(NodeRef::Expr(e)) {
                NodeRef::Expr(c) => Val::Expr(c),
                _ => Val::Expr(e),
            },
            Val::Stmt(s) => match self.b.copy_subtree(NodeRef::Stmt(s)) {
                NodeRef::Stmt(c) => Val::Stmt(c),
                _ => Val::Stmt(s),
            },
            Val::Item(i) => match self.b.copy_subtree(NodeRef::Item(i)) {
                NodeRef::Item(c) => Val::Item(c),
                _ => Val::Item(i),
            },
            Val::Pat(p) => match self.b.copy_subtree(NodeRef::Pat(p)) {
                NodeRef::Pat(c) => Val::Pat(c),
                _ => Val::Pat(p),
            },
            Val::Ty(t) => match self.b.copy_subtree(NodeRef::Ty(t)) {
                NodeRef::Ty(c) => Val::Ty(c),
                _ => Val::Ty(t),
            },
            Val::Arg(a) => match self.b.copy_subtree(NodeRef::Expr(a.value)) {
                NodeRef::Expr(c) => Val::Arg(Arg { value: c, ..a }),
                _ => Val::Arg(a),
            },
            other => other,
        }
    }

    /// The value of an absent hole: its default literal, or `Val::Err`
    /// (left out where optional, an error where required). A required hole of
    /// the node itself is reported once.
    fn absent(&mut self, f: &Frame<K>, ctx: &Ctx, tpl: u32, h: usize, holes: &mut Holes) -> Val {
        let decl = self
            .m
            .templates
            .get(tpl as usize)
            .and_then(|t| t.holes.get(h))
            .cloned();
        match decl {
            Some(d) => {
                if let Some(lit) = d.default {
                    self.t_at(f, ctx.expn);
                    let lit = self.t_lit(lit);
                    return Val::Expr(self.ex(Expr::Lit(lit)));
                }
                if d.kind == HoleKind::Pat {
                    self.t_at(f, ctx.expn);
                    return Val::Pat(self.pt(Pat::Wild));
                }
                if !d.optional {
                    self.report_missing(f, holes);
                }
                Val::Err
            }
            None => Val::Err,
        }
    }

    fn report_missing(&mut self, f: &Frame<K>, holes: &mut Holes) {
        if !holes.missing_reported {
            holes.missing_reported = true;
            let template = match f.build {
                super::Build::Template { id, .. } => id,
                _ => TemplateId(0),
            };
            self.report(ProblemKind::MissingHole { template }, f.span);
        }
    }

    fn t_lit(&mut self, lit: TLit) -> Lit {
        match lit {
            TLit::Int(v) => Lit::Int(IntLit::signed(v)),
            TLit::Float(v) => Lit::Float(FloatLit::new(v)),
            TLit::Bool(b) => Lit::Bool(b),
            TLit::Null => Lit::Null,
            TLit::Char(c) => Lit::Char(c),
        }
    }

    /// A marked path for a free name the template writes (`a::b`).
    fn t_path(
        &mut self,
        f: &Frame<K>,
        ctx: &Ctx,
        text: u32,
        ns: Ns,
        external: bool,
    ) -> hir_lang::PathId {
        let m = self.m;
        let full = m.strings.get(text as usize).map_or("", |s| &**s);
        self.t_at(f, ctx.expn);
        let origin = Origin::expanded(f.span, ctx.expn);
        let mut segs = Vec::new();
        if external {
            let sym = self.sym(text);
            segs.push(Segment::new(Name::marked(sym, ctx.expn), origin));
        } else {
            for piece in full.split("::") {
                let sym = self.intern(piece);
                segs.push(Segment::new(Name::marked(sym, ctx.expn), origin));
            }
        }
        let list = self.list(&segs);
        let mut p = Path::new(list, ns);
        if external {
            p.res = Res::Extern(self.sym(text));
        }
        self.path(p)
    }

    #[allow(clippy::too_many_arguments)]
    fn t_enter(
        &mut self,
        f: &Frame<K>,
        n: u32,
        c: u32,
        ctxs: &mut Vec<Ctx>,
        benv: &mut Vec<Option<BinderId>>,
        lenv: &mut Vec<Option<BinderId>>,
        work: &mut Vec<Work>,
        out: &mut Vec<Slot>,
        kids: &mut Vec<u32>,
        holes: &mut Holes,
    ) {
        let Some(ctx) = ctxs.get(c as usize).copied() else {
            return;
        };
        let m = self.m;
        let Some(t) = m.templates.get(ctx.tpl as usize) else {
            return;
        };
        let Some(node) = t.node(n).copied() else {
            return;
        };
        let text_base = t.text_base;
        let push = |out: &mut Vec<Slot>, v: Val| {
            out.push(Slot {
                v,
                span: f.span,
                place: false,
            });
        };
        match node {
            TNode::Hole(h)
            | TNode::Splice(h)
            | TNode::Stmts(h)
            | TNode::PHole(h)
            | TNode::THole(h) => match self.source(usize::from(h), c, ctxs) {
                Source::Top(h) => {
                    if self.present(f, h) {
                        self.top_hole(f, h, holes, out);
                    } else {
                        let tpl = ctxs.first().map_or(0, |c| c.tpl);
                        let v = self.absent(f, &ctx, tpl, h, holes);
                        push(out, v);
                    }
                }
                Source::Node(node, pc) => work.push(Work::Enter(node, pc)),
                Source::Absent(tpl, h) => {
                    let v = self.absent(f, &ctx, tpl, h, holes);
                    push(out, v);
                }
            },
            TNode::Lit(l) => {
                self.t_at(f, ctx.expn);
                let lit = self.t_lit(l);
                let e = self.ex(Expr::Lit(lit));
                push(out, Val::Expr(e));
            }
            TNode::Str(s) => {
                let m = self.m;
                let text = m.strings.get((text_base + s) as usize).map_or("", |s| &**s);
                self.t_at(f, ctx.expn);
                let tr = self.b.text(text);
                let e = self.ex(Expr::Lit(Lit::Str(tr)));
                push(out, Val::Expr(e));
            }
            TNode::Var(b) => {
                let id = self.t_binder(f, usize::from(b), &ctx, benv, BinderKind::Local);
                self.t_at(f, ctx.expn);
                let e = match id {
                    Some(id) => self.b.use_binder(id),
                    None => self.ex(Expr::Err),
                };
                self.nodes += 2;
                push(out, Val::Expr(e));
            }
            TNode::Global(s) => {
                let p = self.t_path(f, &ctx, text_base + s, Ns::Value, false);
                let e = self.ex(Expr::Path(p));
                push(out, Val::Expr(e));
            }
            TNode::Extern(s) => {
                let p = self.t_path(f, &ctx, text_base + s, Ns::Value, true);
                let e = self.ex(Expr::Path(p));
                push(out, Val::Expr(e));
            }
            TNode::PWild => {
                self.t_at(f, ctx.expn);
                let p = self.pt(Pat::Wild);
                push(out, Val::Pat(p));
            }
            TNode::PBind(b) => {
                let id = self.t_binder(f, usize::from(b), &ctx, benv, BinderKind::Local);
                self.t_at(f, ctx.expn);
                let p = match id {
                    Some(binder) => self.pt(Pat::Bind {
                        binder,
                        mode: BindMode::Value,
                        sub: None,
                    }),
                    None => self.pt(Pat::Err),
                };
                push(out, Val::Pat(p));
            }
            TNode::PLit(l) => {
                self.t_at(f, ctx.expn);
                let lit = self.t_lit(l);
                let p = self.pt(Pat::Lit(lit));
                push(out, Val::Pat(p));
            }
            TNode::TPrim(p) => {
                self.t_at(f, ctx.expn);
                let t = self.ty(Ty::Prim(p));
                push(out, Val::Ty(t));
            }
            TNode::TNamed(s) => {
                let p = self.t_path(f, &ctx, text_base + s, Ns::Type, false);
                let t = self.ty(Ty::Path(p));
                push(out, Val::Ty(t));
            }
            TNode::TInfer => {
                self.t_at(f, ctx.expn);
                let t = self.ty(Ty::Infer);
                push(out, Val::Ty(t));
            }
            TNode::TAny => {
                self.t_at(f, ctx.expn);
                let t = self.ty(Ty::Any);
                push(out, Val::Ty(t));
            }
            TNode::Continue { label } => {
                let label = self.slot_label(label, c, ctxs, lenv, holes);
                self.t_at(f, ctx.expn);
                let e = self.ex(Expr::Continue { label });
                push(out, Val::Expr(e));
            }
            TNode::Apply { template, args } => {
                let max = self.budget.max_expansion_depth;
                let callee = self.m.templates.get(template as usize);
                match callee {
                    Some(callee) if ctx.depth < max => {
                        let expn = self.b.expansion(Expansion {
                            kind: callee.kind,
                            name: self.sym(
                                self.m
                                    .template_names
                                    .get(template as usize)
                                    .copied()
                                    .unwrap_or(0),
                            ),
                            call_site: f.span,
                            parent: ctx.expn,
                            def_site: ExpnId::ROOT,
                        });
                        let benv_base = benv.len();
                        benv.resize(benv_base + callee.binders.len(), None);
                        let lenv_base = lenv.len();
                        lenv.resize(lenv_base + callee.labels.len(), None);
                        let root = callee.root;
                        let Ok(idx) = u32::try_from(ctxs.len()) else {
                            push(out, Val::Err);
                            return;
                        };
                        ctxs.push(Ctx {
                            tpl: template,
                            expn,
                            benv: benv_base,
                            lenv: lenv_base,
                            parent: c,
                            args,
                            depth: ctx.depth + 1,
                        });
                        work.push(Work::Enter(root, idx));
                    }
                    _ => {
                        self.report(
                            ProblemKind::ExpansionTooDeep {
                                template: TemplateId(template),
                            },
                            f.span,
                        );
                        self.t_at(f, ctx.expn);
                        let e = self.ex(Expr::Err);
                        push(out, Val::Expr(e));
                    }
                }
            }
            _ => {
                // Composite nodes: bind what must exist before the children
                // (labels, closure parameters), then evaluate the children in
                // order and build on exit.
                match node {
                    TNode::Block {
                        label: LabelSlot::Own(l),
                        ..
                    }
                    | TNode::Loop {
                        label: LabelSlot::Own(l),
                        ..
                    } => {
                        if let Some(decl) = t.labels.get(usize::from(l)).copied() {
                            let sym = self.sym(text_base + decl.name);
                            self.t_at(f, ctx.expn);
                            let b =
                                self.binder(Name::marked(sym, ctx.expn), BinderKind::Label, false);
                            if let Some(s) = lenv.get_mut(ctx.lenv + usize::from(l)) {
                                *s = Some(b);
                            }
                        }
                    }
                    TNode::Closure { params, .. } => {
                        for &p in t.list(params) {
                            let _ = self.t_binder(f, p as usize, &ctx, benv, BinderKind::Param);
                        }
                    }
                    TNode::LetPlace { binder, .. } => {
                        let _ =
                            self.t_binder(f, usize::from(binder), &ctx, benv, BinderKind::Place);
                    }
                    _ => {}
                }
                work.push(Work::Exit(n, c));
                fill_children(t, &node, kids);
                for &k in kids.iter().rev() {
                    work.push(Work::Enter(k, c));
                }
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn t_exit(
        &mut self,
        f: &Frame<K>,
        n: u32,
        c: u32,
        ctxs: &[Ctx],
        benv: &mut [Option<BinderId>],
        lenv: &[Option<BinderId>],
        out: &mut Vec<Slot>,
        kids: &mut Vec<u32>,
        res: &mut Vec<Slot>,
        holes: &mut Holes,
    ) {
        let Some(ctx) = ctxs.get(c as usize).copied() else {
            return;
        };
        let m = self.m;
        let Some(t) = m.templates.get(ctx.tpl as usize) else {
            return;
        };
        let Some(node) = t.node(n).copied() else {
            return;
        };
        let text_base = t.text_base;
        fill_children(t, &node, kids);
        let start = out.len().saturating_sub(kids.len());
        res.clear();
        res.extend_from_slice(out.get(start..).unwrap_or(&[]));
        out.truncate(start);
        let mut it = res.iter();
        let mut next = || it.next().map_or(Val::Err, |s| s.v);
        self.t_at(f, ctx.expn);
        let v = match node {
            TNode::Call { args, .. } => {
                let callee = next();
                let callee = self.t_expr(f, callee, holes);
                let mut list = Vec::new();
                for _ in 0..args.1 {
                    let a = next();
                    self.t_args(a, &mut list);
                }
                self.t_at(f, ctx.expn);
                let args = self.list(&list);
                Val::Expr(self.ex(Expr::Call { callee, args }))
            }
            TNode::Method { name, args, .. } => {
                let recv = next();
                let receiver = self.t_expr(f, recv, holes);
                let mut list = Vec::new();
                for _ in 0..args.1 {
                    let a = next();
                    self.t_args(a, &mut list);
                }
                self.t_at(f, ctx.expn);
                let args = self.list(&list);
                let method = Ident::new(self.sym(text_base + name), f.span);
                Val::Expr(self.ex(Expr::MethodCall {
                    receiver,
                    method,
                    generic_args: List::EMPTY,
                    args,
                }))
            }
            TNode::Field { name, .. } => {
                let b = next();
                let base = self.t_expr(f, b, holes);
                self.t_at(f, ctx.expn);
                let member = Member::Named(self.sym(text_base + name));
                Val::Expr(self.ex(Expr::Field {
                    base,
                    member,
                    span: f.span,
                }))
            }
            TNode::Index { .. } => {
                let (b, i) = (next(), next());
                let base = self.t_expr(f, b, holes);
                let index = self.t_expr(f, i, holes);
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::Index { base, index }))
            }
            TNode::Op { op, exact, args } => {
                let mut ops = Vec::new();
                for _ in 0..args.1 {
                    let a = next();
                    ops.push(self.t_expr(f, a, holes));
                }
                let op = if exact { op } else { self.policy_op(op.kind) };
                self.t_at(f, ctx.expn);
                let args = self.list(&ops);
                Val::Expr(self.ex(Expr::Op { op, args }))
            }
            TNode::Assign { .. } => {
                let (a, b) = (next(), next());
                let target = self.t_expr(f, a, holes);
                let value = self.t_expr(f, b, holes);
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::Assign {
                    target,
                    op: None,
                    value,
                }))
            }
            TNode::Block { stmts, tail, label } => {
                let mut list: Vec<StmtId> = Vec::new();
                for _ in 0..stmts.1 {
                    let s = next();
                    self.t_stmts(f, ctx.expn, s, &mut list);
                }
                let tail = if tail == NONE {
                    None
                } else {
                    let v = next();
                    self.t_opt_expr(v)
                };
                let label = self.slot_label(label, c, ctxs, lenv, holes);
                self.t_at(f, ctx.expn);
                let stmts = self.list(&list);
                Val::Expr(self.ex(Expr::Block(Block {
                    stmts,
                    tail,
                    label,
                    is_unsafe: false,
                })))
            }
            TNode::If { else_, .. } => {
                let (a, b) = (next(), next());
                let cond = self.t_expr(f, a, holes);
                let then = self.t_expr(f, b, holes);
                let else_ = if else_ == NONE {
                    None
                } else {
                    let v = next();
                    self.t_opt_expr(v)
                };
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::If { cond, then, else_ }))
            }
            TNode::Match { arms, .. } => {
                let s = next();
                let scrutinee = self.t_expr(f, s, holes);
                let mut list = Vec::new();
                for arm in t.list(arms).chunks(3) {
                    let pat_node = arm.first().copied().unwrap_or(NONE);
                    let guard = arm.get(1).copied().unwrap_or(NONE);
                    let p = next();
                    let pat = self.t_pat(f, ctx.expn, p);
                    let guard = if guard == NONE {
                        None
                    } else {
                        let g = next();
                        self.t_opt_expr(g)
                    };
                    let b = next();
                    let body = self.t_expr(f, b, holes);
                    // PHP scoping: assign the pattern's bindings on entry.
                    let binds = self.binds_at(f, pat_node, c, ctxs, holes);
                    let body = if binds.is_empty() {
                        body
                    } else {
                        let b = self.with_assigns(&binds, body, f.span);
                        self.t_at(f, ctx.expn);
                        b
                    };
                    list.push(Arm { pat, guard, body });
                }
                self.t_at(f, ctx.expn);
                let arms = self.list(&list);
                Val::Expr(self.ex(Expr::Match { scrutinee, arms }))
            }
            TNode::Loop { label, step, .. } => {
                let b = next();
                let body = self.t_expr(f, b, holes);
                let step = if step == NONE {
                    None
                } else {
                    let s = next();
                    self.t_opt_expr(s)
                };
                let label = self.slot_label(label, c, ctxs, lenv, holes);
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::Loop { label, body, step }))
            }
            TNode::Break { label, value } => {
                let value = if value == NONE {
                    None
                } else {
                    let v = next();
                    self.t_opt_expr(v)
                };
                let label = self.slot_label(label, c, ctxs, lenv, holes);
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::Break { label, value }))
            }
            TNode::Return(v) => {
                let value = if v == NONE {
                    None
                } else {
                    let x = next();
                    self.t_opt_expr(x)
                };
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::Return(value)))
            }
            TNode::Yield { key, value } => {
                let key = if key == NONE {
                    None
                } else {
                    let x = next();
                    self.t_opt_expr(x)
                };
                let value = if value == NONE {
                    None
                } else {
                    let x = next();
                    self.t_opt_expr(x)
                };
                // A key without a value is malformed HIR; an absent optional
                // value hole yields null under its key.
                let value = match (key, value) {
                    (Some(_), None) => {
                        self.t_at(f, ctx.expn);
                        Some(self.ex(Expr::Lit(Lit::Null)))
                    }
                    (_, v) => v,
                };
                self.infer(hir_lang::Effects::YIELD);
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::Yield { key, value }))
            }
            TNode::YieldFrom(_) => {
                let x = next();
                let source = self.t_expr(f, x, holes);
                self.infer(hir_lang::Effects::YIELD);
                self.t_at(f, ctx.expn);
                Val::Expr(self.ex(Expr::YieldFrom(source)))
            }
            TNode::LetPlace { binder, .. } => {
                let (p, b) = (next(), next());
                let place = self.t_expr(f, p, holes);
                let body = self.t_expr(f, b, holes);
                let alias = benv.get(ctx.benv + usize::from(binder)).copied().flatten();
                self.t_at(f, ctx.expn);
                match alias {
                    Some(binder) => Val::Expr(self.ex(Expr::LetPlace {
                        binder,
                        place,
                        body,
                    })),
                    None => Val::Expr(self.ex(Expr::Err)),
                }
            }
            TNode::Throw(_) | TNode::Await(_) | TNode::Spawn(_) => {
                let x = next();
                let inner = self.t_expr(f, x, holes);
                self.t_at(f, ctx.expn);
                let e = match node {
                    TNode::Throw(_) => {
                        self.infer(hir_lang::Effects::THROWS);
                        Expr::Throw(inner)
                    }
                    TNode::Await(_) => {
                        self.infer(hir_lang::Effects::ASYNC);
                        Expr::Await(inner)
                    }
                    _ => Expr::Spawn(inner),
                };
                Val::Expr(self.ex(e))
            }
            TNode::Tuple(l) | TNode::Array(l) => {
                let mut list = Vec::new();
                for _ in 0..l.1 {
                    let a = next();
                    let mut args = Vec::new();
                    self.t_args(a, &mut args);
                    list.extend(args.iter().map(|a| a.value));
                }
                self.t_at(f, ctx.expn);
                let elems = self.list(&list);
                Val::Expr(self.ex(if matches!(node, TNode::Tuple(_)) {
                    Expr::Tuple(elems)
                } else {
                    Expr::Array(elems)
                }))
            }
            TNode::Closure {
                params, implicit, ..
            } => {
                let b = next();
                let body = self.t_expr(f, b, holes);
                let mut ps = Vec::new();
                for &p in t.list(params) {
                    let binder = benv.get(ctx.benv + p as usize).copied().flatten();
                    if let Some(binder) = binder {
                        self.t_at(f, ctx.expn);
                        let pat = self.pt(Pat::Bind {
                            binder,
                            mode: BindMode::Value,
                            sub: None,
                        });
                        self.nodes += 1;
                        ps.push(self.b.param(Param::new(pat)));
                    }
                }
                self.t_at(f, ctx.expn);
                let params = self.list(&ps);
                let captures: List<Capture> = List::EMPTY;
                Val::Expr(self.ex(Expr::Closure(Closure {
                    params,
                    ret: None,
                    body,
                    effects: hir_lang::Effects::NONE,
                    implicit,
                    captures,
                    self_binder: None,
                    defaults: DefaultEval::PerCall,
                })))
            }
            TNode::Let {
                pat: pat_node,
                ty,
                init,
            } => {
                let p = next();
                let pat = self.t_pat(f, ctx.expn, p);
                let ty = if ty == NONE {
                    None
                } else {
                    let v = next();
                    self.t_opt_ty(v)
                };
                let init = if init == NONE {
                    None
                } else {
                    let v = next();
                    self.t_opt_expr(v)
                };
                self.t_at(f, ctx.expn);
                let stmt = self.st(Stmt::Let {
                    pat,
                    ty,
                    init,
                    else_: None,
                });
                let binds = self.binds_at(f, pat_node, c, ctxs, holes);
                if binds.is_empty() {
                    Val::Stmt(stmt)
                } else {
                    let mut stmts = alloc::vec![stmt];
                    self.persist_assigns(&binds, &mut stmts);
                    self.t_at(f, ctx.expn);
                    let slots: Vec<Slot> = stmts
                        .into_iter()
                        .map(|s| Slot {
                            v: Val::Stmt(s),
                            span: f.span,
                            place: false,
                        })
                        .collect();
                    self.spill_of(&slots)
                }
            }
            TNode::ExprStmt(_) | TNode::Defer(_) => {
                let x = next();
                let e = self.t_expr(f, x, holes);
                self.t_at(f, ctx.expn);
                Val::Stmt(self.st(if matches!(node, TNode::Defer(_)) {
                    Stmt::Defer(e)
                } else {
                    Stmt::Expr(e)
                }))
            }
            TNode::PTuple(l) => {
                let mut list = Vec::new();
                for _ in 0..l.1 {
                    let p = next();
                    list.push(self.t_pat(f, ctx.expn, p));
                }
                self.t_at(f, ctx.expn);
                let elems = self.list(&list);
                Val::Pat(self.pt(Pat::Tuple { elems, rest: None }))
            }
            TNode::TUnion(l) | TNode::TInter(l) => {
                let mut list = Vec::new();
                for _ in 0..l.1 {
                    let v = next();
                    if let Some(t) = self.t_opt_ty(v) {
                        list.push(t);
                    }
                }
                self.t_at(f, ctx.expn);
                let members = self.list(&list);
                Val::Ty(self.ty(if matches!(node, TNode::TUnion(_)) {
                    Ty::Union(members)
                } else {
                    Ty::Intersection(members)
                }))
            }
            TNode::PCtor { path, elems } => {
                let mut list = Vec::new();
                for _ in 0..elems.1 {
                    let p = next();
                    list.push(self.t_pat(f, ctx.expn, p));
                }
                let path = self.t_path(f, &ctx, text_base + path, Ns::Pattern, false);
                self.t_at(f, ctx.expn);
                let elems = self.list(&list);
                Val::Pat(self.pt(Pat::Ctor {
                    path,
                    elems,
                    rest: None,
                }))
            }
            _ => Val::Err,
        };
        out.push(Slot {
            v,
            span: f.span,
            place: false,
        });
    }

    /// A required expression slot.
    fn t_expr(&mut self, f: &Frame<K>, v: Val, holes: &mut Holes) -> ExprId {
        match v {
            Val::Expr(e) => e,
            Val::Arg(a) => a.value,
            _ => {
                self.report_missing(f, holes);
                self.ex(Expr::Err)
            }
        }
    }

    fn t_opt_expr(&mut self, v: Val) -> Option<ExprId> {
        match v {
            Val::Expr(e) => Some(e),
            Val::Arg(a) => Some(a.value),
            _ => None,
        }
    }

    fn t_opt_ty(&mut self, v: Val) -> Option<TyId> {
        match v {
            Val::Ty(t) => Some(t),
            _ => None,
        }
    }

    fn t_pat(&mut self, f: &Frame<K>, expn: ExpnId, v: Val) -> PatId {
        match v {
            Val::Pat(p) => p,
            Val::Rest(_) => {
                self.report(
                    ProblemKind::NotAllowedHere {
                        expected: crate::Context::Pattern,
                    },
                    f.span,
                );
                self.t_at(f, expn);
                self.pt(Pat::Err)
            }
            _ => {
                self.t_at(f, expn);
                self.pt(Pat::Wild)
            }
        }
    }

    /// Arguments from a list element: an expression, or a spliced hole.
    fn t_args(&mut self, v: Val, out: &mut Vec<Arg>) {
        match v {
            Val::Expr(e) => out.push(Arg::positional(e)),
            Val::Arg(a) => out.push(a),
            Val::Spill(s, l) => {
                let (s, l) = (s as usize, l as usize);
                for j in s..s.saturating_add(l) {
                    match self.spill.get(j).map(|x| x.v) {
                        Some(Val::Arg(a)) => out.push(a),
                        Some(Val::Expr(e)) => out.push(Arg::positional(e)),
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    /// Statements from a block element: a statement, or a spliced hole.
    fn t_stmts(&mut self, f: &Frame<K>, expn: ExpnId, v: Val, out: &mut Vec<StmtId>) {
        let mut one = |this: &mut Self, v: Val, span: Span| match v {
            Val::Stmt(s) => out.push(s),
            Val::Expr(e) => {
                this.b.set_origin(Origin::expanded(span, ExpnId::ROOT));
                out.push(this.st(Stmt::Expr(e)));
            }
            Val::Item(i) => {
                this.b.set_origin(Origin::expanded(span, ExpnId::ROOT));
                out.push(this.st(Stmt::Item(i)));
            }
            _ => {}
        };
        match v {
            Val::Spill(s, l) => {
                let (s, l) = (s as usize, l as usize);
                for j in s..s.saturating_add(l) {
                    if let Some(slot) = self.spill.get(j).copied() {
                        one(self, slot.v, slot.span);
                    }
                }
            }
            other => one(self, other, f.span),
        }
        self.t_at(f, expn);
    }

    /// Attaches the values of holes no expansion used (only when an `apply`
    /// was cut short by the depth budget), so no lowered node is orphaned:
    /// `{ unused...; result }`.
    fn rescue(&mut self, f: &Frame<K>, uses: &[u32], result: ExprId) -> ExprId {
        if uses.iter().all(|&u| u > 0) {
            return result;
        }
        let mut stmts: Vec<StmtId> = Vec::new();
        for (h, &uses) in uses.iter().enumerate() {
            if uses > 0 {
                continue;
            }
            let (s, e) = self.field_range(f, h);
            let mut vals: Vec<Slot> = Vec::new();
            for j in s..e {
                match self.vals.get(j).copied() {
                    Some(Slot {
                        v: Val::Spill(ss, sl),
                        ..
                    }) => {
                        let (ss, sl) = (ss as usize, sl as usize);
                        if let Some(run) = self.spill.get(ss..ss.saturating_add(sl)) {
                            vals.extend_from_slice(run);
                        }
                    }
                    Some(slot) => vals.push(slot),
                    None => {}
                }
            }
            for slot in vals {
                self.at(slot.span);
                let st = match slot.v {
                    Val::Stmt(s) => Some(s),
                    Val::Expr(e) => Some(self.st(Stmt::Expr(e))),
                    Val::Item(i) => Some(self.st(Stmt::Item(i))),
                    Val::Arg(a) => Some(self.st(Stmt::Expr(a.value))),
                    Val::Pat(pat) => Some(self.st(Stmt::Let {
                        pat,
                        ty: None,
                        init: None,
                        else_: None,
                    })),
                    Val::Ty(ty) => {
                        let pat = self.pt(Pat::Wild);
                        Some(self.st(Stmt::Let {
                            pat,
                            ty: Some(ty),
                            init: None,
                            else_: None,
                        }))
                    }
                    _ => None,
                };
                if let Some(st) = st {
                    stmts.push(st);
                }
            }
        }
        if stmts.is_empty() {
            return result;
        }
        self.at(f.span);
        let list = self.list(&stmts);
        self.ex(Expr::Block(Block {
            stmts: list,
            tail: Some(result),
            label: None,
            is_unsafe: false,
        }))
    }
}

/// Fills `v` with a template node's children in evaluation order (absent
/// optional children left out).
fn fill_children(t: &Template, node: &TNode, v: &mut Vec<u32>) {
    let opt = |x: u32, v: &mut Vec<u32>| {
        if x != NONE {
            v.push(x);
        }
    };
    v.clear();
    match *node {
        TNode::Call { callee, args } => {
            v.push(callee);
            v.extend_from_slice(t.list(args));
        }
        TNode::Method { recv, args, .. } => {
            v.push(recv);
            v.extend_from_slice(t.list(args));
        }
        TNode::Field { base, .. } => v.push(base),
        TNode::Index { base, index } => v.extend([base, index]),
        TNode::Op { args, .. } => v.extend_from_slice(t.list(args)),
        TNode::Assign { target, value } => v.extend([target, value]),
        TNode::Block { stmts, tail, .. } => {
            v.extend_from_slice(t.list(stmts));
            opt(tail, v);
        }
        TNode::If { cond, then, else_ } => {
            v.extend([cond, then]);
            opt(else_, v);
        }
        TNode::Match { scrutinee, arms } => {
            v.push(scrutinee);
            for arm in t.list(arms).chunks(3) {
                for &x in arm {
                    opt(x, v);
                }
            }
        }
        TNode::Loop { body, step, .. } => {
            v.push(body);
            opt(step, v);
        }
        TNode::Break { value, .. } => opt(value, v),
        TNode::Return(x) => opt(x, v),
        TNode::Yield { key, value } => {
            opt(key, v);
            opt(value, v);
        }
        TNode::LetPlace { place, body, .. } => v.extend([place, body]),
        TNode::TUnion(l) | TNode::TInter(l) => v.extend_from_slice(t.list(l)),
        TNode::Throw(x)
        | TNode::YieldFrom(x)
        | TNode::Await(x)
        | TNode::Spawn(x)
        | TNode::ExprStmt(x)
        | TNode::Defer(x) => {
            v.push(x);
        }
        TNode::Tuple(l) | TNode::Array(l) | TNode::PTuple(l) => v.extend_from_slice(t.list(l)),
        TNode::PCtor { elems, .. } => v.extend_from_slice(t.list(elems)),
        TNode::Closure { body, .. } => v.push(body),
        TNode::Let { pat, ty, init } => {
            v.push(pat);
            opt(ty, v);
            opt(init, v);
        }
        _ => {}
    }
}