quiltlang 0.6.0

Quilt, a polyglot metaprogramming language: source code with arrow-bracket syntax for embedding and manipulating code fragments of other languages at code-generation time.
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
#[cfg(feature = "parse")]
use crate::glyphs::split_anno;
use crate::lang::{Arity, Language, LanguagePost};
#[cfg(feature = "parse")]
use crate::lang::{FlatNode, Hole};
use crate::meta::{MetaLanguage, OuterKind, Piece};
use crate::node::{Node, MACHINE};
use crate::prelude::*;
#[cfg(feature = "parse")]
use crate::qterm::QTermBuilder;
use crate::qterm::{tuple, QTerm, Repr};
use crate::strcmd::StrCmd;
use crate::term::CmdOrHole;
#[cfg(feature = "parse")]
use crate::zipper::{List, Zipper};
use miette::{ensure, miette, LabeledSpan};
#[cfg(feature = "parse")]
use regex::Regex;
use std::collections::BTreeMap;
#[cfg(feature = "parse")]
use std::sync::LazyLock;

/**************************************************************/

#[cfg(feature = "parse")]
static RE_WS_PREFIX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*").unwrap());
const DEFAULT_LANG: &str = "rs";

/**************************************************************/

/// The depth at which a term is being expanded. Either Ground or some language and positive depth.
#[derive(Debug, Clone, Default)]
pub enum Stage {
    #[default]
    Ground,
    /// invariant: Index > 0
    Sky(Box<str>, Index),
}

/// Seed a parse zipper from a language chain (host first, then the defaults for
/// nested un-annotated quotes). The host sits at the cursor (`head`) and the
/// rest seed `anti`, so an un-annotated `↖…↗` resolves the next default language
/// via [`Zipper::back`]; when the chain is exhausted, parsing falls back to the
/// host (matching the single-language `["rs"]` behavior).
#[cfg(feature = "parse")]
fn zipper_from_chain(chain: &[&str]) -> Zipper<Box<str>> {
    let host: Box<str> = chain.first().copied().unwrap_or(DEFAULT_LANG).into();
    let mut anti = List::new();
    for lang in chain.get(1..).unwrap_or(&[]).iter().rev() {
        anti = anti.cons((*lang).into());
    }
    Zipper {
        list: List::new().cons(host),
        anti,
    }
}

/**************************************************************/

pub trait Languages {
    type Language: Language + ?Sized;

    fn get(&self, lang: &str) -> Result<&Self::Language>;
    fn get_mut(&mut self, lang: &str) -> Result<&mut Self::Language>;

    /// The canonical registry key for `lang`, resolving aliases (`python` →
    /// `py`); identity for unknown names. The machine park keys by this, so
    /// [`Multi::machine`] hands the same machine to every alias.
    fn canonical<'a>(&'a self, lang: &'a str) -> &'a str {
        lang
    }
}

pub trait MetaLanguages {
    type MetaLanguage: MetaLanguage + ?Sized;

    fn get(&self, lang: &str) -> Result<&Self::MetaLanguage>;
    fn get_mut(&mut self, lang: &str) -> Result<&mut Self::MetaLanguage>;

    /**************************************************************/

    fn lift_str(&self, lang: &str, target: &str) -> Result<&'static str> {
        self.get(lang)?.lift_str(target)
    }
    fn reduce_str(&self, lang: &str, target: &str) -> Result<&'static str> {
        self.get(lang)?.reduce_str(target)
    }
    fn reduce_method_str(&self, lang: &str, target: &str) -> Result<&'static str> {
        self.get(lang)?.reduce_method_str(target)
    }
    fn emit_str(&self, lang: &str) -> Result<&'static str> {
        self.get(lang)?.emit_str()
    }
    fn lift_str_in(&self, lang: &str, target: &str, repr: Repr) -> Result<&'static str> {
        self.get(lang)?.lift_str_in(target, repr)
    }
    fn emit_str_in(&self, lang: &str, repr: Repr) -> Result<&'static str> {
        self.get(lang)?.emit_str_in(repr)
    }
    fn type_str(&self, lang: &str) -> Result<&'static str> {
        self.get(lang)?.type_str()
    }
    fn name_str(&self, lang: &str) -> Result<&'static str> {
        self.get(lang)?.name_str()
    }
    fn type_method_str(&self, lang: &str) -> Result<&'static str> {
        self.get(lang)?.type_method_str()
    }
    fn spawn_str(&self, lang: &str, target: &str) -> Result<String> {
        self.get(lang)?.spawn_str(target)
    }
    fn prelude(&self, lang: &str, targets: &[&str]) -> Result<Option<crate::meta::Prelude>> {
        Ok(self.get(lang)?.prelude(targets))
    }
}

#[derive(Default)]
pub struct Multi<LS: Languages, MS: MetaLanguages> {
    pub langs: LS,
    pub metas: MS,
    /// Live default machines, one per language, spawned on first use by
    /// [`machine`](Multi::machine) — so successive reduces share definitions
    /// for as long as this `Multi` lives. See `docs/design/machines.md`.
    pub machines: crate::machine::Park,
}

impl<LS: Languages, MS: MetaLanguages> Multi<LS, MS> {
    pub fn get_lang(&self, lang: &str) -> Result<&LS::Language> {
        self.langs.get(lang)
    }
    pub fn get_lang_mut(&mut self, lang: &str) -> Result<&mut LS::Language> {
        self.langs.get_mut(lang)
    }
    pub fn get_meta(&self, lang: &str) -> Result<&MS::MetaLanguage> {
        self.metas.get(lang)
    }
    pub fn get_meta_mut(&mut self, lang: &str) -> Result<&mut MS::MetaLanguage> {
        self.metas.get_mut(lang)
    }
    pub fn lift_str(&self, lang: &str, target: &str) -> Result<&'static str> {
        self.metas.lift_str(lang, target)
    }
    /// [`Self::lift_str`] for a `↑` in source. A host that cannot lift into
    /// text at all is told so about `text`, the language the author quoted,
    /// rather than about [`TEXT_IN_QUOTES`](crate::lift::TEXT_IN_QUOTES), a
    /// position inside it they never named.
    #[cfg(feature = "parse")]
    fn lift_spelling(&self, lang: &str, target: &str, repr: Repr) -> Result<&'static str> {
        match self.metas.lift_str_in(lang, target, repr) {
            Err(e) if target == crate::lift::TEXT_IN_QUOTES => {
                self.metas.lift_str_in(lang, "text", repr)?;
                Err(e)
            }
            r => r,
        }
    }
    pub fn reduce_str(&self, lang: &str, target: &str) -> Result<&'static str> {
        self.metas.reduce_str(lang, target)
    }
    pub fn reduce_method_str(&self, lang: &str, target: &str) -> Result<&'static str> {
        self.metas.reduce_method_str(lang, target)
    }
    pub fn emit_str(&self, lang: &str) -> Result<&'static str> {
        self.metas.emit_str(lang)
    }
    /// The runtime import a file expanded with `lang`'s meta must open with
    /// (issue #274), given the object languages it may lift into. See
    /// [`MetaLanguage::prelude`](crate::meta::MetaLanguage::prelude).
    pub fn prelude(&self, lang: &str, targets: &[&str]) -> Result<Option<crate::meta::Prelude>> {
        self.metas.prelude(lang, targets)
    }

    /// The runtime import the file expanded from `input` under `chain` (ground
    /// language first) should open with, or `None` (issue #274). Paired with
    /// [`with_prelude`](crate::meta::with_prelude), this is what `quilt expand`
    /// writes, and what the in-browser expander (`quilt-expand-wasm`) writes
    /// too, so a generated module is runnable whichever of them produced it.
    ///
    /// `None` for a host whose meta needs none (nix, lean and text generate no
    /// runtime calls at all), and by the two rules that keep the injection from
    /// becoming a footgun:
    ///
    /// * **The source uses no Quilt construct.** `examples/hello.rs.quilt`
    ///   expands to itself and must stay import-free: Rust tolerates an unused
    ///   glob silently, but a Python or TypeScript linter will not.
    /// * **The author already imported the runtime.** Two identical globs are
    ///   harmless in Rust and Python, but a doubled *named* import is a hard
    ///   error in TypeScript — so this is checked rather than assumed. See
    ///   [`Prelude::present_in`](crate::meta::Prelude::present_in).
    ///
    /// The targets the meta is asked about — which only a target-directed host
    /// like TypeScript reads — are the language chain plus every annotation the
    /// source's quotes name, so that a `sql↖…↗` inside a `.rs.quilt` counts even
    /// though the chain never mentions SQL. It over-approximates: a language
    /// listed but never lifted into costs an unused name, one missing costs a
    /// name that is not in scope.
    #[must_use]
    pub fn prelude_for(&self, chain: &[&str], input: &str) -> Option<crate::meta::Prelude> {
        let used = crate::node::constructs(input);
        if !used.any {
            return None;
        }
        let mut targets: Vec<&str> = chain.to_vec();
        for anno in &used.annos {
            if !targets.contains(&&**anno) {
                targets.push(anno);
            }
        }
        // A language with no meta is not an error here — an expansion that
        // succeeded proves the host is fine — so a failed lookup is simply "no
        // prelude".
        let prelude = self.prelude(chain[0], &targets).ok().flatten()?;
        (!prelude.present_in(input)).then_some(prelude)
    }
    pub fn type_str(&self, lang: &str) -> Result<&'static str> {
        self.metas.type_str(lang)
    }
    pub fn name_str(&self, lang: &str) -> Result<&'static str> {
        self.metas.name_str(lang)
    }
    pub fn type_method_str(&self, lang: &str) -> Result<&'static str> {
        self.metas.type_method_str(lang)
    }
    pub fn spawn_str(&self, lang: &str, target: &str) -> Result<String> {
        self.metas.spawn_str(lang, target)
    }

    /// Spawn a *fresh* machine for `lang`: the persistent
    /// [`ReplMachine`](crate::machine::ReplMachine) when the language
    /// declares a [`repl_spec`](Language::repl_spec), else the replay-based
    /// [`ScriptMachine`](crate::machine::ScriptMachine) from its
    /// [`machine_spec`](Language::machine_spec). The caller owns it: nothing
    /// is parked, so it shares state with no other machine.
    pub fn spawn_machine(&self, lang: &str) -> Result<Box<dyn crate::machine::Machine>> {
        crate::machine::spawn_machine(lang, self.langs.get(lang)?)
    }

    /// The *default* machine for `lang`: parked in
    /// [`machines`](Multi::machines), spawned on first use, shared by every
    /// caller of this `Multi` — which is what lets one reduce see the
    /// definitions another fed. Keyed by the canonical language name, so
    /// aliases (`py` / `python`) share one machine.
    pub fn machine(&mut self, lang: &str) -> Result<&mut dyn crate::machine::Machine> {
        let key: Box<str> = self.langs.canonical(lang).into();
        if !self.machines.contains(&key) {
            let machine = self.spawn_machine(lang)?;
            self.machines.insert(&key, machine);
        }
        Ok(self.machines.get_mut(&key).unwrap())
    }

    /// The end-user text door (tenet 2's actual subject): parse `src` as
    /// `kind` with `lang`'s `Language` — validating it — then feed the term
    /// to the default machine. Machines themselves traffic only in terms;
    /// raw text is turned into a term here, where the parser lives.
    pub fn feed_on(
        &mut self,
        lang: &str,
        kind: crate::lang::InnerKind,
        src: &str,
    ) -> Result<crate::machine::Answer> {
        let term = self
            .get_lang_mut(lang)?
            .parse_as(Some(kind), &crate::lang::flat_nodes(src))?;
        self.machine(lang)?.feed(kind, &term)
    }

    /// Evaluate a term on `lang`'s default machine and parse the answered
    /// literal back into a term of `lang` — machines answer with the
    /// value's own syntax, and the `Language` re-reads it here, where it
    /// lives.
    pub fn eval_on(&mut self, lang: &str, term: &QTerm) -> Result<Arc<QTerm>> {
        let answer = self.machine(lang)?.eval(term)?;
        let value = answer.value.ok_or_else(|| {
            miette!(
                "the {lang} machine answered no value for {:?}",
                term.coparse()
            )
        })?;
        self.get_lang_mut(lang)?
            .parse_expr(&crate::lang::one_liner(&value))
    }

    /// Classify a term for feeding a machine — which message sort it is —
    /// seeing through the tagless root wrapper `parse_chain` builds around a
    /// parsed fragment (whose tag would otherwise classify by the language's
    /// default). The REPL and the notebook both route feeds through this.
    pub fn classify_for_feed(&self, lang: &str, term: &QTerm) -> Result<crate::lang::InnerKind> {
        fn go<L: Language + ?Sized>(lang: &L, term: &QTerm) -> crate::lang::InnerKind {
            match term {
                QTerm::Tuple { tag, terms, .. } if tag.is_empty() && terms.len() == 1 => {
                    go(lang, &terms[0])
                }
                _ => lang.classify_term(term),
            }
        }
        Ok(go(self.get_lang(lang)?, term))
    }

    #[cfg(feature = "parse")]
    pub fn parse(&mut self, s: &str) -> Result<Arc<QTerm>> {
        self.parse_lang(DEFAULT_LANG, s)
    }

    #[cfg(feature = "parse")]
    pub fn parse_lang(&mut self, lang: &str, s: &str) -> Result<Arc<QTerm>> {
        self.parse_chain(&[lang], s)
    }

    /// Parse `s` whose language is given by a *chain* of file extensions: the
    /// host (ground) language first, then the default language for successively
    /// nested un-annotated `↖…↗` quotes. This comes from a file name like
    /// `shaders.wgsl.rs.quilt` (chain `["rs", "wgsl"]`): Rust is the host and a
    /// bare `↖…↗` defaults to WGSL. A single-element chain (`["rs"]`) is the
    /// plain `foo.rs.quilt` case where bare quotes default to the host.
    #[cfg(feature = "parse")]
    pub fn parse_chain(&mut self, chain: &[&str], s: &str) -> Result<Arc<QTerm>> {
        let nodes = Node::parse(s)?
            .iter()
            .map(|n| arc(n.clone()))
            .collect::<Vec<_>>();

        Ok(self
            .build_nodes(
                tb(""),
                &Hole::default(),
                &nodes,
                &zipper_from_chain(chain),
                None,
                None,
                false,
                0,
            )?
            .first()
            .unwrap())
    }

    /// Build a `QTerm` from quilt `Node`s. `splice_target` is the language the
    /// fragment's value will be spliced into: `Some` only for unquote bodies
    /// (the lang of the enclosing quote), `None` otherwise. It directs `↑` —
    /// a lift inside `wgsl↖ … ↙x.↑↘ … ↗` targets WGSL; elsewhere a lift is
    /// homogeneous (targets the fragment's own language). `bracketed` is true
    /// when `nodes` is the body of a `↖…↗`/`↙…↘` pair and false at the top
    /// level: only bracketed bodies get their boundary newlines trimmed.
    /// `sky_depth` is the net quote nesting (quotes minus unquotes) at this
    /// level: 0 at ground, +1 per enclosing quote, −1 per enclosing unquote.
    /// An operator (`↑`/`↓`/`←`) at sky depth > 0 runs at a *later* stage, so
    /// it is deferred (emitted as the glyph) rather than spelled out now.
    /// `enclosing` is the language and [`Repr`] of the nearest quote around
    /// `nodes` (`None` at the top): a bare quote inside its unquotes inherits
    /// its representation, and a `↑`/`←` there spells that representation's.
    #[cfg(feature = "parse")]
    #[allow(clippy::too_many_arguments)] // recursive parse state; a struct would obscure it
    pub fn build_nodes(
        &mut self,
        mut builder: QTermBuilder,
        hole: &Hole,
        nodes: &[Arc<Node>],
        zipper: &Zipper<Box<str>>,
        splice_target: Option<&str>,
        enclosing: Option<(&str, Repr)>,
        bracketed: bool,
        sky_depth: usize,
    ) -> Result<QTermBuilder> {
        let lang = zipper.head().unwrap();

        // dbg!(&nodes);

        // Pass 1: strip the enclosing-context prefix (`hole.prefix`, the indent
        // the quote sits at) from each line, and measure the body's own common
        // leading indent. This runs for every line after a newline — including
        // when there is no enclosing prefix — so a quote whose body is just
        // written indented (e.g. a top-level `py↖\n    …\n↗`) is dedented too,
        // not only one spliced into already-indented code.
        //
        // The enclosing prefix is only stripped as far as every line actually
        // carries it. A body written *left* of the code around the quote —
        //
        //         let g = rs↖
        // fn g() {}
        // ↗;
        //
        // — has nothing of the prefix to give up, and used to fail the whole
        // expansion with a bare "Failed to strip prefix". Stripping each line
        // by as much of the prefix as it happens to have would not do either:
        // it would flatten the body's own relative indentation. So the prefix
        // is cut back to what every line shares, the lines lose exactly that,
        // and the common-indent pass below takes care of the rest. Blank lines
        // say nothing about indentation, so they do not cut the prefix back.
        let full_prefix = hole.prefix.concat();
        let prefix = shared_prefix(&full_prefix, nodes);
        let mut nodes_new = Vec::with_capacity(nodes.len());
        let mut on_nl = false;
        let mut num_nl = 0;
        // The common leading indent of the continuation lines (every line after
        // a newline), measured after the enclosing prefix is stripped. Blank
        // lines — the closing `↗`'s own indentation among them — say nothing
        // about the body's indentation, so they do not bound it: a closer left
        // of the body (`↖\n        body\n      ↗`) leaves no indent behind.
        let mut cont: Option<&str> = None;
        // Where the last line (the one the `↗` is on) starts in `nodes_new`.
        let mut last_line = None;
        for (i, n) in nodes.iter().enumerate() {
            match &**n {
                Node::Content(s) if on_nl => {
                    // A blank line gives up as much of the *full* prefix as it
                    // has, so a closer at the host's indent leaves nothing behind.
                    let blank = is_blank(nodes, i);
                    let s = if blank {
                        &s[common_prefix_len(&full_prefix, s)..]
                    } else {
                        &s[prefix.len()..]
                    };
                    if !s.is_empty() {
                        nodes_new.push(arc(Node::Content(s.into())));
                        if !blank {
                            let ws = RE_WS_PREFIX.find(s).unwrap().as_str();
                            cont = Some(cont.map_or(ws, |pre| &pre[..common_prefix_len(pre, ws)]));
                        }
                    }
                }
                _ => nodes_new.push(n.clone()),
            }
            on_nl = **n == Node::NewLine;
            num_nl += usize::from(on_nl);
            if on_nl {
                last_line = Some(nodes_new.len());
            }
        }
        // Inline opener content (`↖foo…`) sits flush with the opener, so its own
        // leading whitespace bounds the common indent. This keeps a quote whose
        // body carries meaningful indentation — e.g. `↖def f():\n    body` —
        // from being dedented; a block-opened quote (`↖\n    body\n↗`), whose
        // first line is a newline, has its body's common indent stripped.
        //
        // The exception is an inline quote whose last line *closes* what the
        // opener line opened — it starts with `}`, `)` or `]`, as in
        //
        //     prog.push(↖F[1] = {
        //         a: 1,
        //       };↗);
        //
        // There the closer marks the column the body is written relative to,
        // whatever the host line's indent, so the continuation lines' common
        // indent is stripped as in a block quote: `F[1] = {\n  a: 1,\n};`.
        let opener = match nodes.first().map(|n| &**n) {
            Some(Node::Content(s)) => Some(RE_WS_PREFIX.find(s).unwrap().as_str()),
            _ => None,
        };
        let closes = last_line.is_some_and(|k| {
            matches!(nodes_new.get(k).map(|n| &**n), Some(Node::Content(s))
                if s.trim_start().starts_with(['}', ')', ']']))
        });
        let indent = match (opener, cont) {
            (Some(_), Some(cont)) if closes => Some(cont),
            (Some(op), Some(cont)) => Some(&op[..common_prefix_len(op, cont)]),
            (op, cont) => op.or(cont),
        };
        let mut nodes = nodes_new;
        let indent = indent.unwrap_or_default();

        // dbg!(&nodes_new);

        // Pass 2: dedent by common prefix. Reset `on_nl`: like Pass 1 it must
        // start false so the opener-line content (`↖foo…`, which has no leading
        // indent) is never stripped — only lines that follow a newline, which
        // are exactly the lines Pass 1 measured `indent` from.
        on_nl = false;
        if !indent.is_empty() {
            let mut nodes_new = Vec::with_capacity(nodes.len());
            for n in nodes {
                match &*n {
                    Node::Content(s) if on_nl => {
                        // A blank line did not bound `indent`, so it may have
                        // less of it than the others: it loses what it has.
                        let s = &s[common_prefix_len(indent, s)..];
                        if !s.is_empty() {
                            nodes_new.push(arc(Node::Content(s.into())));
                        }
                    }
                    _ => nodes_new.push(n.clone()),
                }
                on_nl = *n == Node::NewLine;
            }
            nodes = nodes_new;
        }
        // Trim one boundary newline on each side so `↖\n…\n↗` parses the same
        // body as `↖…↗`; the trimmed newlines are re-emitted as builder cmds
        // below. At the top level (no enclosing brackets) the boundary
        // newlines are real source content and must stay in `code`.
        let first_nl = bracketed && !nodes.is_empty() && **nodes.first().unwrap() == Node::NewLine;
        let last_nl = bracketed
            && !nodes.is_empty()
            && **nodes.last().unwrap() == Node::NewLine
            && num_nl != usize::from(first_nl); // distinguish ↖↗ from ↖\n↗
        let nodes = &nodes[usize::from(first_nl)..nodes.len() - usize::from(last_nl)];

        // Pass 3: build up a string of code with holes // TODO: avoid creating string
        //
        // `lang⟨M⟩` is the one operator whose expansion is *computed* rather
        // than a `&'static str` — it interpolates the resolved language name
        // (issue #273) — so the spellings are built here, up front, and the
        // `FlatNode::Str`s below borrow from this vector. Deferred `⟨M⟩`s
        // (sky depth > 0) belong to a later stage and get no spelling at all.
        // A bare `⟨M⟩` resolves as a bare quote in its place would, so it
        // reads the last annotated quote before it at this level too.
        let mut spawns = Vec::new();
        if sky_depth == 0 {
            let mut sibling = "";
            for n in nodes {
                match &**n {
                    Node::Quote { anno, .. } if !split_anno(anno).0.is_empty() => {
                        sibling = split_anno(anno).0;
                    }
                    Node::Machine { anno } => {
                        let anno = if anno.is_empty() { sibling } else { anno };
                        spawns.push(self.spawn_str(lang, &machine_lang(zipper, lang, anno))?);
                    }
                    _ => {}
                }
            }
        }
        let mut spawns = spawns.iter();

        // The representation a value spliced from here must have: the
        // enclosing quote's, inside one of its unquotes; `cst` at plain ground.
        let splice_repr = match (splice_target, enclosing) {
            (Some(_), Some((_, repr))) => repr,
            _ => Repr::Cst,
        };
        let mut code = Vec::with_capacity(nodes.len());
        for (i, n) in nodes.iter().enumerate() {
            match &**n {
                Node::Content(s) => code.push(FlatNode::Str(s)),
                Node::NewLine => code.push(FlatNode::NewLine),
                Node::Unquote { nodes, .. } if !nodes.iter().any(|n| **n == Node::NewLine) => {
                    code.push(FlatNode::Splice);
                }
                Node::Quote { .. } | Node::Unquote { .. } => code.push(FlatNode::Hole),
                // An operator (↑ lift, ↓ reduce, ← emit) inside an as-yet-
                // unresolved quote (sky depth > 0) belongs to a later stage:
                // defer it as a hole so it survives `coparse` as its glyph and
                // is spelled out when that stage runs, instead of being expanded
                // here one stage too early.
                Node::Lift | Node::Reduce { .. } | Node::Emit | Node::Machine { .. }
                    if sky_depth > 0 =>
                {
                    code.push(FlatNode::Hole);
                }
                Node::Lift => code.push(FlatNode::Str(self.lift_spelling(
                    lang,
                    splice_target.unwrap_or(lang),
                    splice_repr,
                )?)),
                // `↓` flush against an argument list — `db.↓(schema)` — is
                // *method position*: it spells the host's machine-eval method
                // name, completed by the source's own parentheses (#268).
                // Everywhere else it is the reduce operator as before.
                Node::Reduce { anno } if method_position(nodes, i) => {
                    let spelling = match self.reduce_method_str(lang, anno) {
                        Ok(spelling) => spelling,
                        // A host with no method-position reading *at all*
                        // keeps `↓`'s operator meaning, which is what a flush
                        // `(` meant before the rule existed: TypeScript's
                        // `gen(7).↓(6)` reduces a generated function and calls
                        // it. A host that has the reading and merely refused
                        // this annotation keeps its own diagnostic, which is
                        // more useful than either spelling.
                        Err(e) if self.reduce_method_str(lang, "").is_ok() => return Err(e),
                        Err(_) => self.reduce_str(lang, anno)?,
                    };
                    code.push(FlatNode::Str(spelling));
                }
                Node::Reduce { anno } => code.push(FlatNode::Str(self.reduce_str(lang, anno)?)),
                Node::Emit => {
                    let spelling = self.metas.emit_str_in(lang, splice_repr)?;
                    // A host whose `←` is a bare function name (TypeScript's
                    // `qseq`) is functional: it takes the whole sequence as an
                    // argument, so the glyph must open a call. Anything else —
                    // Rust's postfix `x.←` habit, say — would expand to a
                    // reference to the function and fail far from here. Asked
                    // of the host's `⟨cst⟩` spelling, since a `⟨str⟩` one may
                    // be a function *expression* (an inline join).
                    let functional = self
                        .emit_str(lang)
                        .is_ok_and(|s| s.chars().all(|c| c.is_alphanumeric() || c == '_'));
                    if functional && !method_position(nodes, i) {
                        miette::bail!(
                            "{lang}'s `←` is a function of the whole sequence: write `←(items)` \
                             (or `←(items, sep)`), which expands to `{spelling}(items)`"
                        );
                    }
                    code.push(FlatNode::Str(spelling));
                }
                // `⟨T⟩` flush against an argument list — `db.⟨T⟩(term)` — is
                // the *typing* judgment on a machine, the companion of
                // `db.↓(term)`'s value judgment (#273). In operand position it
                // is the term type as before.
                Node::Type if method_position(nodes, i) => {
                    // Same fallback as `↓` above: a host with no typing-
                    // judgment spelling keeps `⟨T⟩`'s operand meaning rather
                    // than losing a reading it already had.
                    let spelling = match self.type_method_str(lang) {
                        Ok(spelling) => spelling,
                        Err(_) => self.type_str(lang)?,
                    };
                    code.push(FlatNode::Str(spelling));
                }
                Node::Type => code.push(FlatNode::Str(self.type_str(lang)?)),
                Node::Name => code.push(FlatNode::Str(self.name_str(lang)?)),
                Node::Machine { .. } => {
                    let spelling = spawns.next().expect("one spelling per `⟨M⟩`, built above");
                    code.push(FlatNode::Str(spelling));
                }
                Node::PlainLineComment(s) | Node::PlainBlockComment(s) => {
                    code.push(FlatNode::Str(s));
                }
            }
        }

        // println!("PRE: code: '{code}'");

        // dbg!(&code);
        // dbg!(&indent);
        // dbg!(&first_nl);
        // dbg!(&last_nl);

        // parse this level and get hole types of children
        let post = self.get_lang_mut(lang)?.parse_pre(hole.ikind, &code)?;
        let mut holes = post.holes().iter();
        // How *this* language spells a bare identifier, for the deferred
        // operator placeholders below.
        let ident_tag = self.get_lang(lang)?.ident_tag();

        // parse children using hole types
        let mut plugs = Vec::new();
        let nodes_here = nodes;
        // The annotation of the last annotated quote at this level: a bare
        // `↖…↗` after `py↖…↗` is Python too, the way a bare quote *inside*
        // one already is. Only siblings count — a quote nested in an unquote
        // starts its own level — so the rule reads in source order, quote by
        // quote, and an annotation is what changes it.
        //
        // A representation (`ts⟨str⟩↖`) is inherited the same way, by the
        // quotes after it in the same language, and by those inside its
        // unquotes (`enclosing`).
        let mut sibling: Option<(Box<str>, Repr)> = None;
        for (i, n) in nodes.iter().enumerate() {
            match &**n {
                // Deferred operators (see the code-building pass): consume the
                // hole and plug the glyph back in, so the term coparses to a real
                // operator for the next stage to expand.
                Node::Lift if sky_depth > 0 => {
                    holes
                        .next()
                        .ok_or_else(|| miette!("Ran out of holes for lift: {n:?}"))?;
                    plugs.push(leaf(ident_tag, "↑"));
                }
                Node::Reduce { anno } if sky_depth > 0 => {
                    holes
                        .next()
                        .ok_or_else(|| miette!("Ran out of holes for reduce: {n:?}"))?;
                    plugs.push(leaf(ident_tag, &format!("{anno}↓")));
                }
                Node::Emit if sky_depth > 0 => {
                    holes
                        .next()
                        .ok_or_else(|| miette!("Ran out of holes for emit: {n:?}"))?;
                    plugs.push(leaf(ident_tag, "←"));
                }
                Node::Machine { anno } if sky_depth > 0 => {
                    holes
                        .next()
                        .ok_or_else(|| miette!("Ran out of holes for machine: {n:?}"))?;
                    // The *unresolved* annotation goes back in: the stage that
                    // runs this fragment resolves the bare form against its own
                    // chain, exactly as this one would have.
                    plugs.push(leaf(ident_tag, &format!("{anno}{MACHINE}")));
                }
                Node::Content(_)
                | Node::NewLine
                | Node::Lift
                | Node::Reduce { .. }
                | Node::Emit
                | Node::Type
                | Node::Name
                | Node::Machine { .. }
                | Node::PlainLineComment(_)
                | Node::PlainBlockComment(_) => {}
                Node::Quote { anno, nodes, span } => {
                    let hole = holes
                        .next()
                        .ok_or_else(|| miette!("Ran out of holes for quote: {n:?}"))?;
                    // .unwrap_or_else(|| miette!("Ran out of holes for quote: {n:?}"))?;
                    // Descend into the quote's embedded language. An annotation
                    // selects it explicitly, and is inherited by the bare
                    // quotes after it at this level. An un-annotated `↖…↗`
                    // with no annotated sibling before it resolves the
                    // default embedded language via `.back()`, which walks the
                    // file's extension chain (e.g. `wgsl` for `*.wgsl.rs.quilt`)
                    // or the enclosing quote's lang (from inside its unquote),
                    // falling back to the host when none is set. The quote's
                    // lang is then the head of the resolved zipper — the
                    // expander uses it to pick the arity for the body's tags
                    // (e.g. `wgsl`'s `case_compound_statement`).
                    let (lang_part, repr_part) = split_anno(anno);
                    let zipper = if !lang_part.is_empty() {
                        zipper.clone().cons(lang_part.into())
                    } else if let Some((sib, _)) = &sibling {
                        zipper.clone().cons(sib.clone())
                    } else {
                        zipper
                            .clone()
                            .back()
                            .unwrap_or_else(|| zipper.clone().cons(lang.clone()))
                    };
                    let quote_lang = zipper.head().unwrap().clone();
                    let repr = match repr_part {
                        Some(name) => Repr::from_name(name).map_err(|e| {
                            miette!(
                                labels = vec![LabeledSpan::at(span.clone(), "this quote")],
                                "{e}"
                            )
                        })?,
                        None => match (&sibling, enclosing) {
                            (Some((sib, repr)), _) if *sib == quote_lang => *repr,
                            (_, Some((outer, repr))) if *outer == *quote_lang => repr,
                            _ => Repr::Cst,
                        },
                    };
                    if !anno.is_empty() {
                        sibling = Some((quote_lang.clone(), repr));
                    }
                    let mut builder = qb(&hole.otag, 1, &quote_lang);
                    builder.span(span.clone());
                    builder.repr(repr);
                    builder.write(anno).write("↖");
                    // A quote's body is free-form (a statement-shaped term may
                    // fill an expression hole and vice versa), so don't coerce
                    // it to the hole's kind.
                    let hole = Hole {
                        ikind: None,
                        ..hole.clone()
                    };
                    let mut builder = self.build_nodes(
                        builder,
                        &hole,
                        nodes,
                        &zipper,
                        None,
                        Some((&quote_lang, repr)),
                        true,
                        sky_depth + 1,
                    )?;
                    builder.write("↗");
                    plugs.push(builder.b());
                }
                Node::Unquote { anno, nodes, span } => {
                    let hole = hole
                        + holes
                            .next()
                            .ok_or_else(|| miette!("Ran out of holes for unquote: {n:?}"))?;
                    let mut builder = ub(&hole.otag, 1, lang);
                    builder.span(span.clone());
                    // The body's value is spliced into *this* fragment's
                    // language: it directs any `↑` in the body (e.g. a lift
                    // inside `wgsl↖…↗` lifts into WGSL). Text has no grammar
                    // to say where the hole is, so its position comes from
                    // the characters around it (`text_splice_target`).
                    let splice_target = text_splice_target(lang, nodes_here, i).unwrap_or(lang);
                    let zipper = zipper.clone().tail().unwrap();
                    // an unquote with no enclosing quote pops the host off the
                    // zipper; catch it here (with a span) instead of panicking
                    // on the empty zipper when recursing into the body
                    if zipper.head().is_none() {
                        return Err(unquote_depth_error(Some(span)));
                    }
                    builder.write(anno).write("↙");
                    let mut builder = self.build_nodes(
                        builder,
                        &hole,
                        nodes,
                        &zipper,
                        Some(splice_target),
                        enclosing,
                        true,
                        sky_depth.saturating_sub(1),
                    )?;
                    builder.write("↘");
                    plugs.push(builder.b());
                }
            }
        }

        // fill holes with plugs
        let term = post.parse_post(&plugs)?;

        // builder result
        builder
            .push_if(indent, !indent.is_empty())
            .nl_if(first_nl)
            .child(&term)
            .pop_if(!indent.is_empty())
            .nl_if(last_nl);
        Ok(builder)
    }

    pub fn expand(&mut self, qterm: &QTerm) -> Result<Arc<QTerm>> {
        self.expand_lang(DEFAULT_LANG, qterm)
    }

    pub fn expand_lang(&mut self, lang: &str, qterm: &QTerm) -> Result<Arc<QTerm>> {
        let Multi {
            ref mut langs,
            ref mut metas,
            ..
        } = self;
        let meta = metas.get(lang)?;
        Expander {
            langs,
            meta,
            lang,
            pattern_vars: None,
            in_builder: false,
        }
        .expand(&Default::default(), qterm)
    }
}

/// Where a hole in a *text* quote sits, as a splice target: between two `"`
/// the author wrote, it is [`TEXT_IN_QUOTES`](crate::lift::TEXT_IN_QUOTES), so
/// `↑` renders a string's escaped contents rather than a second pair of quotes
/// (issue #149). Anything else, and any other language, is `None`: a grammar
/// already knows what a hole inside its string literal is.
///
/// "The author wrote" means unescaped: `\"↙x↘\"` is a quote character in the
/// text, not the opening of a quoted context.
#[cfg(feature = "parse")]
fn text_splice_target(lang: &str, nodes: &[Arc<Node>], i: usize) -> Option<&'static str> {
    if !matches!(lang, "text" | "txt") {
        return None;
    }
    let Some(Node::Content(before)) = nodes.get(i.checked_sub(1)?).map(|n| &**n) else {
        return None;
    };
    let Some(Node::Content(after)) = nodes.get(i + 1).map(|n| &**n) else {
        return None;
    };
    let opens = before
        .strip_suffix('"')
        .is_some_and(|rest| !rest.ends_with('\\'));
    (opens && after.starts_with('"')).then_some(crate::lift::TEXT_IN_QUOTES)
}

/// The language a `⟨M⟩` names. An annotation says it outright (the caller
/// passes an inherited sibling annotation as `anno`); the bare form resolves
/// exactly as a bare `↖…↗` does — the chain's next default language via the
/// zipper's `.back()`, falling back to the host — so `⟨M⟩` in a
/// `.sql.py.quilt` file is a SQL machine and in a plain `.py.quilt` file a
/// Python one (issue #273).
#[cfg(feature = "parse")]
fn machine_lang(zipper: &Zipper<Box<str>>, lang: &str, anno: &str) -> Box<str> {
    let zipper = if anno.is_empty() {
        zipper
            .clone()
            .back()
            .unwrap_or_else(|| zipper.clone().cons(lang.into()))
    } else {
        zipper.clone().cons(anno.into())
    };
    zipper.head().expect("a consed zipper has a head").clone()
}

/// Whether the node after `i` opens an argument list flush against the
/// operator — `recv.↓(arg)` — making the operator a *method name* that the
/// source's own parentheses complete. Flush means exactly that: `↓ (x)`
/// (with a space) stays the ordinary operator.
#[cfg(feature = "parse")]
fn method_position(nodes: &[Arc<Node>], i: usize) -> bool {
    matches!(nodes.get(i + 1).map(|n| &**n), Some(Node::Content(s)) if s.starts_with('('))
}

/// An "unquote depth too high" error pointing at the offending unquote when
/// its source span is known (parsed terms carry spans; constructed terms
/// don't). Callers with the source text at hand (e.g. the CLI) can attach it
/// via [`miette::Report::with_source_code`] to render the offending snippet.
fn unquote_depth_error(span: Option<&Span>) -> miette::Report {
    match span {
        Some(span) => miette!(
            labels = vec![LabeledSpan::at(span.clone(), "this unquote")],
            "unquote depth too high! (source bytes {}..{})",
            span.start,
            span.end
        ),
        None => miette!("unquote depth too high!"),
    }
}

/// `e`, pointing at the quote it came from when that quote's span is known.
fn at_span(e: miette::Report, span: Option<&Span>) -> miette::Report {
    match span {
        Some(span) => miette!(
            labels = vec![LabeledSpan::at(span.clone(), "this quote")],
            "{e}"
        ),
        None => e,
    }
}

pub struct Expander<'a, LS: Languages, M: MetaLanguage + ?Sized> {
    langs: &'a mut LS,
    meta: &'a M,
    /// The ground (host) language, used to classify tags of ground tuples.
    lang: &'a str,
    /// `Some` while expanding the pattern quote of a pattern-let: ground
    /// unquotes become metavariables, collected here in source order.
    pattern_vars: Option<Vec<Box<str>>>,
    /// Whether the ground code being expanded runs inside an accumulator — an
    /// unquote that is a direct child of a variadic quoted node, whose
    /// expansion binds `b_`. Only there can a quote in statement position be
    /// emitted; outside every unquote (a function body, say) there is no `b_`,
    /// and a statement-shaped quote in tail position is the block's value.
    in_builder: bool,
}

impl<M: MetaLanguage + ?Sized, LS: Languages> Expander<'_, LS, M> {
    // TODO: simplify a ton, remove unused concepts
    fn expand(&mut self, depth: &Stage, term: &QTerm) -> Result<Arc<QTerm>> {
        match depth {
            Stage::Ground => match term {
                // `ts⟨str⟩↖…↗` and `ts⟨qt⟩↖…↗`: the host's meta builds the
                // value from the quote flattened to text and holes, rather
                // than rebuilding its syntax tree node by node.
                QTerm::Quote {
                    index,
                    lang: lang2,
                    term,
                    span,
                    repr,
                    ..
                } if *repr != Repr::Cst => {
                    let mut pieces = Vec::new();
                    self.flatten(*repr, *index, term, &mut pieces)
                        .map_err(|e| at_span(e, span.as_ref()))?;
                    self.meta.expand_flat(*repr, lang2, &pieces)
                }
                QTerm::Quote {
                    index,
                    lang: lang1,
                    term,
                    ..
                } => {
                    self.expand(&Stage::Sky(lang1.clone(), *index), term)
                    // self.get_meta(meta).wrap_quote(meta, expanded, emit)
                }
                QTerm::Unquote { span, .. } => Err(unquote_depth_error(span.as_ref())),
                QTerm::Tuple { tag, terms, cmds } => {
                    // `let ↖pattern↗ = value;` — a quote in binding position
                    // destructures the value instead of building a term. The
                    // meta-language locates the two positions, since neither the
                    // separator token nor the child index is universal.
                    if self.meta.pattern_tag() == Some(&**tag) {
                        if let Some((p, v)) = self.meta.pattern_binding(terms) {
                            if let Some(QTerm::Quote { .. }) = terms.get(p).map(AsRef::as_ref) {
                                return self.expand_pattern_let(tag, terms, cmds, p, v);
                            }
                        }
                    }
                    let arity = self.langs.get(self.lang)?.arity(tag);
                    let terms = terms
                        .iter()
                        .map(|term| {
                            // expand each child
                            let expanded = self.expand(&Stage::Ground, term)?;
                            // then wrap the result
                            let mut okind = OuterKind::None;
                            // A quote in statement position of a variadic node
                            // would otherwise build a term and silently drop
                            // it, so infer Emit. A tail-expression quote parses
                            // with the same outer tag (`expression_statement`),
                            // so also require the quoted body to be a statement
                            // — an expression body means the quote is a value.
                            //
                            // The body's kind comes from the inner language's
                            // `classify_term` (the kind it actually parsed),
                            // which — unlike `typ` on the root tag — sees through
                            // wrappers like WGSL's `source_file(stmt, ;)`. This
                            // closes the feedback loop from issue #25 and makes
                            // the decision work across language boundaries.
                            //
                            // And only inside an accumulator: at plain ground
                            // there is no `b_`, so `fn f() -> Arc<QTerm> {
                            // ↖fn g() {}↗ }` returns the quote rather than
                            // emitting it into a builder that does not exist.
                            if self.in_builder && arity == Arity::Variadic {
                                if let QTerm::Quote {
                                    tag: qtag,
                                    lang: lang2,
                                    term: body,
                                    ..
                                } = &**term
                                {
                                    if self.langs.get(self.lang)?.typ(qtag).is_stmt_like()
                                        && self.langs.get(lang2)?.classify_term(body).is_stmt_like()
                                    {
                                        okind = OuterKind::Emit;
                                    }
                                }
                            }
                            self.meta.wrap_child(expanded, okind)
                        })
                        .collect::<Result<Vec<_>>>()?;
                    Ok(tuple(tag, &terms, cmds))
                } // QTerm::Lift(_gap) => todo!(),
                  // QTerm::Reduce(_gap) => todo!(),
            },
            Stage::Sky(lang1, d) => match term {
                QTerm::Quote {
                    tag,
                    index,
                    lang: lang2,
                    term,
                    cmds,
                    ..
                } => {
                    let term = self.expand(&Stage::Sky(lang1.clone(), d + index), term)?;
                    self.meta
                        .expand_quote(lang1, tag, *index, lang2, &term, cmds)
                }
                QTerm::Unquote {
                    tag,
                    index,
                    lang: lang2,
                    term,
                    cmds,
                    span,
                } => {
                    if index > d {
                        return Err(unquote_depth_error(span.as_ref()));
                    }
                    let new_depth = d - index;

                    if new_depth == 0 {
                        // Inside a pattern quote a ground unquote is a
                        // metavariable binder, not a splice: record its name
                        // and splice an `mvar` marker (see `crate::qmatch`).
                        if let Some(vars) = &mut self.pattern_vars {
                            let name = pattern_var_name(term)?;
                            vars.push(name.clone());
                            return self.meta.pattern_var(&name);
                        }
                        self.expand(&Stage::Ground, term)
                    } else {
                        let qterm = self.expand(&Stage::Sky(lang1.clone(), new_depth), term)?;
                        self.meta
                            .expand_unquote(lang1, tag, *index, lang2, &qterm, cmds)
                    }
                }
                QTerm::Tuple { tag, terms, cmds } => {
                    // Variadic is about *dynamic* children. The accumulator form
                    // (`{ let mut b_ = tb(tag); …; b_.b() }`) exists so a child
                    // can contribute zero-or-many terms, which only an unquote
                    // can do — a child that is literal quoted syntax always
                    // contributes exactly itself, and `x.emit(&mut b_)` on it is
                    // just a longhand `.c(&x)`.
                    //
                    // So a variadic node with no unquote among its children is
                    // downgraded to the fluent form: same term, far less
                    // generated code. This is what keeps the variadic set free
                    // to follow the grammar — `string_literal` and `token_tree`
                    // really do hold repeats, but a *literal* `"hi"` should not
                    // expand to six lines of accumulator to say so.
                    let mut arity = self.langs.get(lang1)?.arity(tag);
                    if arity == Arity::Variadic
                        && !terms.iter().any(|t| matches!(&**t, QTerm::Unquote { .. }))
                    {
                        arity = Arity::Unknown;
                    }
                    // A ground splice into a comma-separated list gets its
                    // elements separated (#293) — but only where the splice is
                    // in element position, which the grammar's tables cannot
                    // say: Lean's `def` holds a comma-separated list
                    // somewhere, and its other holes are not in it. So the
                    // splice must also sit between the list's brackets or
                    // separators (`[↙xs↘]`, `f(a, ↙xs↘)`), never next to a
                    // keyword or another element.
                    let sep = if arity == Arity::Variadic {
                        self.langs.get(lang1)?.separator(tag)
                    } else {
                        None
                    };
                    let separated = |i: usize| -> Option<&'static str> {
                        let sep = sep?;
                        let QTerm::Unquote { index, .. } = &*terms[i] else {
                            return None;
                        };
                        let opens =
                            |t: &str| t == sep || t.ends_with(['(', '[', '{', '<', '|', '⟨']);
                        let closes =
                            |t: &str| t == sep || t.starts_with([')', ']', '}', '>', '|', '⟩']);
                        let before = i.checked_sub(1).map(|j| &terms[j]);
                        let after = terms.get(i + 1);
                        (*index == *d
                            && before.is_none_or(|t| token_text(t).is_some_and(opens))
                            && after.is_none_or(|t| token_text(t).is_some_and(closes)))
                        .then_some(sep)
                    };
                    let expanded = terms
                        .iter()
                        .enumerate()
                        .map(|(i, term)| {
                            // expand each child. A ground unquote under an
                            // accumulator runs where `b_` is bound; under a
                            // fluent node it does not.
                            let outer =
                                std::mem::replace(&mut self.in_builder, arity == Arity::Variadic);
                            let expanded = self.expand(depth, term);
                            self.in_builder = outer;
                            let expanded = expanded?;
                            // then wrap the result
                            let mut okind = Default::default();
                            if arity == Arity::Variadic {
                                okind = OuterKind::Emit;
                                // A ground unquote (`index == d`) whose body is
                                // code — a statement, an item, or a *sequence*
                                // of them — is host code to run, so it is
                                // spliced verbatim. Only a value-shaped body is
                                // emitted into the enclosing builder.
                                //
                                // Two things this has to get right:
                                //
                                // * The body is **ground** code, so it is
                                //   classified with `self.lang`, not `lang1`.
                                //   `lang1` is the quoted language, which the
                                //   body is not written in — asking
                                //   `html↖<input value="↙w↘">↗` whether HTML
                                //   thinks the Rust expression `w` is a
                                //   statement is meaningless.
                                // * `is_code_like`, not `is_stmt_like`: a
                                //   multi-statement body parses with the file
                                //   root (`source_file`), and emitting one
                                //   appended `.emit(&mut b_);` to whatever its
                                //   last statement happened to be. That is a
                                //   syntax error unless the statement is
                                //   block-shaped (`for`/`if`/`{…}`), where it
                                //   silently hit the no-op `impl Emit for ()`
                                //   instead — which is why `mk_meta.rs.quilt`
                                //   bootstrapped straight past it.
                                //
                                // The two interact: `Language::typ` *defaults*
                                // to `InnerKind::File`, so widening to
                                // `is_code_like` while still asking `lang1`
                                // would read every non-classifying target
                                // language (html, wgsl, bash, zsh) as "always
                                // code" and splice splices that must be emitted.
                                if let QTerm::Unquote {
                                    index, term: child, ..
                                } = &**term
                                {
                                    if index == d {
                                        if let QTerm::Tuple { tag, .. } = &**child {
                                            if self.langs.get(self.lang)?.typ(tag).is_code_like() {
                                                okind = OuterKind::Splice;
                                            }
                                        }
                                    }
                                }
                            }
                            let wrapped = self.meta.wrap_child(expanded, okind)?;
                            match separated(i) {
                                Some(sep) => self.meta.wrap_separated(wrapped, sep),
                                None => Ok(wrapped),
                            }
                        })
                        .collect::<Result<Vec<_>>>()?;
                    self.meta.expand_tuple(lang1, tag, &expanded, cmds, arity)
                } // QTerm::Lift(gap) => self.expand_lift(lang1, gap),
                  // QTerm::Reduce(gap) => self.expand_run(lang1, gap),
            },
        }
    }

    /// Expand `let ↖pattern↗ = value;` (issue #18). The pattern quote is
    /// expanded with its ground unquotes replaced by `mvar` markers (their
    /// names collected via `pattern_vars`), and the statement is rewritten to
    /// destructure the result of matching the pattern against the value:
    /// `let [a, b] = qmatch_n(&*<pattern>, &<value>);` (see `crate::qmatch`).
    /// `pat` and `val` are the child indices the meta-language reported via
    /// [`MetaLanguage::pattern_binding`]; the expander no longer knows the
    /// separator token or where the pattern sits.
    /// Flatten the body of a `⟨str⟩`/`⟨qt⟩` quote at quote depth `d` into
    /// [`Piece`]s: its text and layout commands in order, and a
    /// [`Piece::Hole`] holding the expanded host code of each ground unquote.
    /// Adjacent text is merged, so a host spells one literal per run.
    fn flatten(&mut self, repr: Repr, d: Index, term: &QTerm, out: &mut Vec<Piece>) -> Result<()> {
        match term {
            QTerm::Tuple { terms, cmds, .. } => {
                let mut children = terms.iter();
                for c in cmds {
                    match c {
                        CmdOrHole::Cmd(StrCmd::Write(s)) => match out.last_mut() {
                            Some(Piece::Text(t)) => *t = format!("{t}{s}").into(),
                            _ => out.push(Piece::Text(s.clone())),
                        },
                        CmdOrHole::Cmd(StrCmd::NewLine) => out.push(Piece::NewLine),
                        CmdOrHole::Cmd(StrCmd::Push(s)) => out.push(Piece::Push(s.clone())),
                        CmdOrHole::Cmd(StrCmd::Pop) => out.push(Piece::Pop),
                        CmdOrHole::Hole => {
                            let child = children.next().ok_or_else(|| {
                                miette!("a hole in a `{repr}` quote has no child: {term:?}")
                            })?;
                            self.flatten(repr, d, child, out)?;
                        }
                    }
                }
                Ok(())
            }
            QTerm::Unquote {
                index, term, span, ..
            } => {
                if index > &d {
                    return Err(unquote_depth_error(span.as_ref()));
                }
                ensure!(
                    index == &d,
                    "a {repr} quote can't hold an unquote of a quote nested inside it yet: only \
                     `⟨cst⟩` quotes stage"
                );
                // Host code with no accumulator around it, like a `⟨cst⟩`
                // quote's ground unquote under a fluent node.
                let outer = std::mem::replace(&mut self.in_builder, false);
                let expanded = self.expand(&Stage::Ground, term);
                self.in_builder = outer;
                out.push(Piece::Hole(expanded?));
                Ok(())
            }
            QTerm::Quote { .. } => Err(miette!(
                "a {repr} quote can't hold a nested quote yet (a later stage): only `⟨cst⟩` \
                 quotes stage — quote the inner code inside an unquote instead"
            )),
        }
    }

    fn expand_pattern_let(
        &mut self,
        tag: &str,
        terms: &[Arc<QTerm>],
        cmds: &[CmdOrHole],
        pat: usize,
        val: usize,
    ) -> Result<Arc<QTerm>> {
        // expand the pattern quote with ground unquotes as metavariables
        ensure!(
            self.pattern_vars.is_none(),
            "pattern let nested inside another pattern"
        );
        if let QTerm::Quote { repr, .. } = &*terms[pat] {
            ensure!(
                *repr == Repr::Cst,
                "a pattern quote matches a syntax tree, so it must be `⟨cst⟩`, not {repr}"
            );
        }
        self.pattern_vars = Some(Vec::new());
        let pattern = self.expand(&Stage::Ground, &terms[pat]);
        let names = self.pattern_vars.take().unwrap();
        let pattern = pattern?;
        for (i, name) in names.iter().enumerate() {
            ensure!(
                !names[..i].contains(name),
                "pattern let binds metavariable `{name}` more than once"
            );
        }

        let value = self.expand(&Stage::Ground, &terms[val])?;
        let (binder, call) = self.meta.pattern_let(&names, &pattern, &value)?;

        let terms = terms
            .iter()
            .enumerate()
            .map(|(i, term)| match i {
                _ if i == pat => Ok(binder.clone()),
                _ if i == val => Ok(call.clone()),
                _ => self.expand(&Stage::Ground, term),
            })
            .collect::<Result<Vec<_>>>()?;
        Ok(tuple(tag, &terms, cmds))
    }
}

/// The metavariable name of a ground unquote inside a pattern quote: its body
/// must be a plain identifier.
fn pattern_var_name(term: &QTerm) -> Result<Box<str>> {
    let text = term.coparse();
    let name = text.trim();
    let mut chars = name.chars();
    let ident = chars.next().is_some_and(|c| c.is_alphabetic() || c == '_')
        && chars.all(|c| c.is_alphanumeric() || c == '_');
    ensure!(
        ident,
        "pattern metavariable must be a plain identifier, got {name:?}"
    );
    Ok(name.into())
}

/**************************************************************/

/// Resolve `lang` through an alias map; non-aliases pass through unchanged.
fn canonical<'a>(aliases: &'a BTreeMap<Box<str>, Box<str>>, lang: &'a str) -> &'a str {
    aliases.get(lang).map_or(lang, AsRef::as_ref)
}

#[derive(Default)]
pub struct DictLanguages {
    langs: BTreeMap<Box<str>, Box<dyn Language<Post = Box<dyn LanguagePost>>>>,
    /// alias → canonical key in `langs`, so aliases share one instance
    aliases: BTreeMap<Box<str>, Box<str>>,
}

impl Languages for DictLanguages {
    type Language = Box<dyn Language<Post = Box<dyn LanguagePost>>>;

    fn get(&self, lang: &str) -> Result<&Self::Language> {
        self.langs
            .get(canonical(&self.aliases, lang))
            .ok_or_else(|| miette!("Language {lang} not found"))
    }
    fn get_mut(&mut self, lang: &str) -> Result<&mut Self::Language> {
        self.langs
            .get_mut(canonical(&self.aliases, lang))
            .ok_or_else(|| miette!("Language {lang} not found"))
    }

    fn canonical<'a>(&'a self, lang: &'a str) -> &'a str {
        canonical(&self.aliases, lang)
    }
}

impl DictLanguages {
    pub fn add(&mut self, lang: &str, language: <Self as Languages>::Language) {
        self.langs.insert(lang.into(), language);
    }

    pub fn add_alias(&mut self, alias: &str, canonical: &str) {
        self.aliases.insert(alias.into(), canonical.into());
    }
}

#[derive(Default)]
pub struct DictMetaLanguages {
    metas: BTreeMap<Box<str>, Box<dyn MetaLanguage>>,
    /// alias → canonical key in `metas`, so aliases share one instance
    aliases: BTreeMap<Box<str>, Box<str>>,
}

impl MetaLanguages for DictMetaLanguages {
    type MetaLanguage = Box<dyn MetaLanguage>;

    fn get(&self, lang: &str) -> Result<&Self::MetaLanguage> {
        self.metas
            .get(canonical(&self.aliases, lang))
            .ok_or_else(|| miette!("Language {lang} not found"))
    }
    fn get_mut(&mut self, lang: &str) -> Result<&mut Self::MetaLanguage> {
        self.metas
            .get_mut(canonical(&self.aliases, lang))
            .ok_or_else(|| miette!("Language {lang} not found"))
    }
}

impl DictMetaLanguages {
    pub fn add(&mut self, lang: &str, meta_language: <Self as MetaLanguages>::MetaLanguage) {
        self.metas.insert(lang.into(), meta_language);
    }

    pub fn add_alias(&mut self, alias: &str, canonical: &str) {
        self.aliases.insert(alias.into(), canonical.into());
    }
}

pub type DictMulti = Multi<DictLanguages, DictMetaLanguages>;

impl DictMulti {
    pub fn add_lang(&mut self, lang: &str, language: <DictLanguages as Languages>::Language) {
        self.langs.add(lang, language);
    }

    pub fn add_meta(
        &mut self,
        lang: &str,
        meta: <DictMetaLanguages as MetaLanguages>::MetaLanguage,
    ) {
        self.metas.add(lang, meta);
    }

    /// Register `alias` as an alternate name for `canonical` in both the
    /// language and meta-language registries. Lookups under the alias resolve
    /// to the canonical entry's instance (no entry there → "not found").
    pub fn add_alias(&mut self, alias: &str, canonical: &str) {
        self.langs.add_alias(alias, canonical);
        self.metas.add_alias(alias, canonical);
    }
}

/**************************************************************/

// Singletons

#[derive(Default)]
pub struct Singleton<T>(T);

impl<L: Language> Languages for Singleton<L> {
    type Language = L;

    fn get(&self, _lang: &str) -> Result<&Self::Language> {
        Ok(&self.0)
    }
    fn get_mut(&mut self, _lang: &str) -> Result<&mut Self::Language> {
        Ok(&mut self.0)
    }
}

impl<M: MetaLanguage> MetaLanguages for Singleton<M> {
    type MetaLanguage = M;

    fn get(&self, _lang: &str) -> Result<&Self::MetaLanguage> {
        Ok(&self.0)
    }
    fn get_mut(&mut self, _lang: &str) -> Result<&mut Self::MetaLanguage> {
        Ok(&mut self.0)
    }
}

pub type Single<M, L> = Multi<Singleton<M>, Singleton<L>>;

/// Byte length of the longest common prefix of `a` and `b`, on a char boundary.
#[cfg(feature = "parse")]
fn common_prefix_len(a: &str, b: &str) -> usize {
    a.char_indices()
        .zip(b.chars())
        .find(|((_, x), y)| x != y)
        .map_or_else(|| a.len().min(b.len()), |((i, _), _)| i)
}

/// The part of `prefix` (an enclosing quote's indent) that every non-blank line
/// of `nodes` starts with — the most of it that can be stripped without
/// cutting into a line's own text. A blank line (see [`is_blank`]) does not
/// count; whitespace followed by a quote, an unquote or an operator is that
/// construct's indentation, and does.
#[cfg(feature = "parse")]
fn shared_prefix<'a>(prefix: &'a str, nodes: &[Arc<Node>]) -> &'a str {
    let mut shared = prefix;
    let mut on_nl = false;
    for (i, n) in nodes.iter().enumerate() {
        if let Node::Content(s) = &**n {
            if on_nl && !is_blank(nodes, i) {
                shared = &shared[..common_prefix_len(shared, s)];
            }
        }
        on_nl = **n == Node::NewLine;
    }
    shared
}

/// Whether `nodes[i]` is a blank line's content: only whitespace, and nothing
/// after it on the line.
#[cfg(feature = "parse")]
fn is_blank(nodes: &[Arc<Node>], i: usize) -> bool {
    matches!(&*nodes[i], Node::Content(s) if s.trim().is_empty())
        && nodes.get(i + 1).is_none_or(|next| **next == Node::NewLine)
}

/// The text of an anonymous token — a childless leaf whose tag is its own
/// text, as `sym` builds it and the parser makes `[`, `,` or `)` — or `None`
/// for anything else.
fn token_text(term: &QTerm) -> Option<&str> {
    match term {
        QTerm::Tuple { tag, terms, cmds } if terms.is_empty() => match &**cmds {
            [CmdOrHole::Cmd(StrCmd::Write(s))] if s == tag => Some(tag),
            _ => None,
        },
        _ => None,
    }
}