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
#!/usr/bin/env quilt
⟨//⟩ Generate `quilt/src/lift/gen.rs` from parsed sample literals (issue #203).
⟨//⟩
⟨//⟩ Run with `bin/gen-lifts`; `bin/check-lifts` is the CI gate that it was.
⟨//⟩
⟨//⟩ The technique is the one `mk_meta.rs.quilt` uses for the numeric `Lift`
⟨//⟩ impls, and the oracle is quilt itself: a quote parses its fragment with the
⟨//⟩ vendored grammar, and `↑` on the resulting term prints the builder calls
⟨//⟩ that rebuild it. So
⟨//⟩
⟨//⟩     py↖"s"↗.↑   ==>   tb("string").c(&leaf("string_start", "\""))
⟨//⟩                          .c(&leaf("string_content", "s"))
⟨//⟩                          .c(&leaf("string_end", "\"")).b()
⟨//⟩
⟨//⟩ is the shape tree-sitter-python builds, written as the code that builds it.
⟨//⟩ Substituting the sample's own text (`"s"`) for a runtime expression turns
⟨//⟩ that into a lift. Nobody transcribes a tag.
⟨//⟩
⟨//⟩ Each family below is a sample literal, a root tag to descend to, and the
⟨//⟩ expression that replaces the sample's text. Adding a target is adding rows.
use quilt::term::CmdOrHole;
use std::process::Command;

/**************************************************************/
/* Reading a shape off a parsed sample                        */

/// The first subtree tagged `tag`, breadth-first.
///
/// Parsing a literal *standalone* is not always the literal alone: a shell
/// parses `"s"` at top level as `(command (command_name (string …)))`, because
/// a bare word in statement position is a command. Those wrappers are an
/// artifact of parsing the value on its own, not part of the value — spliced
/// into an argument position it is just the `string`. `lift_fidelity.rs` makes
/// the same descent for the same reason.
fn descend(term: &Arc<QTerm>, tag: &str) -> Arc<QTerm> {
    let mut queue = std::collections::VecDeque::from([term.clone()]);
    while let Some(t) = queue.pop_front() {
        if matches!(&*t, QTerm::Tuple { tag: g, .. } if &**g == tag) {
            return t;
        }
        match &*t {
            QTerm::Tuple { terms, .. } => queue.extend(terms.iter().cloned()),
            QTerm::Quote { term, .. } | QTerm::Unquote { term, .. } => queue.push_back(term.clone()),
        }
    }
    panic!("no {tag:?} in {}", term.sexp())
}

/// The text of a leaf term — the sample literal's own spelling, which is what
/// the generated code substitutes a runtime expression for.
fn text_of(term: &Arc<QTerm>) -> String {
    term.coparse()
}

/// The shape of `sample` as Rust code, with its own text replaced by `value`.
///
/// `sample.↑` is the builder-call source that rebuilds the parsed term; the
/// only thing in it that must not be a constant is the literal's text, and
/// that is a string literal we can find by value.
fn shape_with(sample: &Arc<QTerm>, text: &str, value: &Arc<QTerm>) -> Arc<QTerm> {
    let code = sample.↑;
    let find = text.to_string().↑;
    let out = code.rewrite_naive(&find, value);
    assert_ne!(
        out, code,
        "sample {} has no literal {text:?} to substitute",
        code.coparse()
    );
    out
}

/// `shape_with` over several samples that must agree once their text is out of
/// the way — e.g. WGSL's `3u` and `3i`, which differ only in the suffix. If a
/// grammar ever gives them different shapes this fails loudly instead of
/// silently generating one of them for both.
fn shape_of_all(samples: &[(Arc<QTerm>, String)], value: &Arc<QTerm>) -> Arc<QTerm> {
    let mut it = samples
        .iter()
        .map(|(s, text)| shape_with(s, text, value));
    let first = it.next().expect("no samples");
    for other in it {
        assert_eq!(
            first.coparse(),
            other.coparse(),
            "samples disagree on the shape"
        );
    }
    first
}

/**************************************************************/
/* Containers: the loop stays hand-written, the sample supplies the pieces */

/// One step of a term's serialization: a child, or a layout command.
#[derive(Clone, Debug, PartialEq)]
enum Piece {
    Child(Arc<QTerm>),
    Cmd(StrCmd),
}

/// A tuple's `cmds`, with each hole resolved to the child that fills it.
fn pieces(term: &Arc<QTerm>) -> Vec<Piece> {
    let QTerm::Tuple { terms, cmds, .. } = &**term else {
        panic!("not a tuple: {}", term.sexp())
    };
    let mut i = 0;
    let mut out = Vec::new();
    for c in cmds {
        match c {
            CmdOrHole::Hole => {
                out.push(Piece::Child(terms[i].clone()));
                i += 1;
            }
            CmdOrHole::Cmd(sc) => out.push(Piece::Cmd(sc.clone())),
        }
    }
    out
}

fn index_of(ps: &[Piece], child: &Arc<QTerm>) -> usize {
    ps.iter()
        .position(|p| matches!(p, Piece::Child(c) if c == child))
        .expect("element not among the container's children")
}

/// Split two samples — an empty container and a two-element one — into the four
/// pieces a container's serialization is made of:
///
/// ```text
/// OPEN  (elem  (MID elem)*  END)?  CLOSE
/// ```
///
/// Both idioms fall out of this. Python separates (`MID = ", "`, `END` empty);
/// Nix terminates (`OPEN = "[ "`, `MID = END = " "`), which is why its empty
/// list is `[ ]` and its last element still gets a trailing space.
///
/// A *one*-element sample would be the obvious third input and is deliberately
/// not one: SQL parses `(1)` as a `parenthesized_expression`, since a
/// parenthesised single value is not a list in any grammar that has both. Two
/// samples pin all four pieces anyway — `OPEN` is what precedes the first
/// element, and the empty container is `OPEN ++ CLOSE`, which splits `CLOSE`
/// off the tail.
fn container_pieces(
    empty: &Arc<QTerm>,
    two: &Arc<QTerm>,
    e1: &Arc<QTerm>,
    e2: &Arc<QTerm>,
) -> (Vec<Piece>, Vec<Piece>, Vec<Piece>, Vec<Piece>) {
    let (pe, pt) = (pieces(empty), pieces(two));

    let (j1, j2) = (index_of(&pt, e1), index_of(&pt, e2));
    let open = pt[..j1].to_vec();
    assert!(pe.starts_with(&open), "empty container is not OPEN ++ CLOSE");
    let close = pe[open.len()..].to_vec();

    let mid = pt[j1 + 1..j2].to_vec();
    let tail = &pt[j2 + 1..];
    assert!(tail.ends_with(&close), "two-element tail does not end in CLOSE");
    let end = tail[..tail.len() - close.len()].to_vec();

    (open, mid, end, close)
}

/// The statement that appends one piece to the builder `b`.
fn piece_stmt(p: &Piece) -> Arc<QTerm> {
    match p {
        Piece::Child(c) => ↖b.child(&↙c.↑↘);↗,
        Piece::Cmd(StrCmd::Write(s)) => ↖b.write(↙s.to_string().↑↘);↗,
        Piece::Cmd(StrCmd::NewLine) => ↖b.nl();↗,
        Piece::Cmd(StrCmd::Push(s)) => ↖b.push(↙s.to_string().↑↘);↗,
        Piece::Cmd(StrCmd::Pop) => ↖b.pop();↗,
    }
}

/// The container constructor for one target: `NAME(items) -> Arc<QTerm>`.
fn container_fn(fname: &str, sample: &(Arc<QTerm>, Arc<QTerm>, Arc<QTerm>, Arc<QTerm>)) -> Arc<QTerm> {
    let (empty, two, e1, e2) = sample;
    let (open, mid, end, close) = container_pieces(empty, two, e1, e2);
    let QTerm::Tuple { tag, .. } = &**empty else {
        panic!("not a tuple")
    };
    let tag = tag.to_string();
    ↖
        /// The container shape, with the elements as a parameter. Derived from
        /// the empty, one- and two-element samples: what surrounds the first
        /// element is the opener, what sits between two of them is the
        /// separator, and what the empty container still writes is neither.
        pub fn ↙⟨N⟩(fname)↘(items: &[⟨T⟩]) -> ⟨T⟩ {
            let mut b = tb(↙tag.↑↘);
            ↙for p in &open { piece_stmt(p).← }↘
            ↙
                if mid.is_empty() {
                    ↖
                        for x in items {
                            b.child(x);
                        }
                    ↗.←;
                } else {
                    ↖
                        for (i, x) in items.iter().enumerate() {
                            if i > 0 {
                                ↙for p in &mid { piece_stmt(p).← }↘
                            }
                            b.child(x);
                        }
                    ↗.←;
                }
                if !end.is_empty() {
                    ↖
                        if !items.is_empty() {
                            ↙for p in &end { piece_stmt(p).← }↘
                        }
                    ↗.←;
                }
            ↘
            ↙for p in &close { piece_stmt(p).← }↘
            b.b()
        }
    ↗
}

/**************************************************************/
/* The impls, which are all one call to a shape above          */

⟨//⟩ A quote binds through a `let` rather than sitting as the tail of a block:
⟨//⟩ such a quote is a direct child of a variadic container, which the expander
⟨//⟩ wraps in an emit into a `b_` that only exists inside a generated block.
⟨//⟩
⟨//⟩ It used to be a closure-body problem too — `|ty| ↖…↗` read as an or-pattern
⟨//⟩ once the quote became a `{}` hole — but that was the fork's `quilt_hole`
⟨//⟩ token outbidding `{`, and it is fixed (#241). Only the emit reason is left,
⟨//⟩ and it is enough to keep this shape.
fn scalar_impls(marker: &str, types: &[&str], body: &Arc<QTerm>) -> Vec<Arc<QTerm>> {
    let mut out = Vec::new();
    for ty in types {
        let item: ⟨T⟩ = ↖
            impl LiftTo<↙⟨N⟩(marker)↘> for ↙⟨N⟩(ty)↘ {
                fn lift_to(&self) -> ⟨T⟩ {
                    ↙body.clone()↘
                }
            }
        ↗;
        out.push(item);
    }
    out
}

fn string_impls(marker: &str, body: &Arc<QTerm>) -> Vec<Arc<QTerm>> {
    vec![
        ↖
            impl LiftTo<↙⟨N⟩(marker)↘> for str {
                fn lift_to(&self) -> ⟨T⟩ {
                    ↙body.clone()↘
                }
            }
        ↗,
        ↖
            impl LiftTo<↙⟨N⟩(marker)↘> for String {
                fn lift_to(&self) -> ⟨T⟩ {
                    ↙body.clone()↘
                }
            }
        ↗,
    ]
}

fn list_impls(marker: &str, body: &Arc<QTerm>) -> Vec<Arc<QTerm>> {
    vec![
        ↖
            impl<T: LiftTo<↙⟨N⟩(marker)↘>> LiftTo<↙⟨N⟩(marker)↘> for [T] {
                fn lift_to(&self) -> ⟨T⟩ {
                    ↙body.clone()↘
                }
            }
        ↗,
        ↖
            impl<T: LiftTo<↙⟨N⟩(marker)↘>> LiftTo<↙⟨N⟩(marker)↘> for Vec<T> {
                fn lift_to(&self) -> ⟨T⟩ {
                    self.as_slice().lift_to()
                }
            }
        ↗,
    ]
}

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

fn main() -> Result<()> {
    ⟨//⟩ ---- the samples, parsed by the vendored grammars ----

    let text: ⟨T⟩ = ↖text↗;

    ⟨//⟩ WGSL. `3u` and `3i` must agree once the suffix is out of the way.
    let wgsl_int = shape_of_all(
        &[
            (descend(&wgsl↖3u↗, "int_literal"), "3u".to_string()),
            (descend(&wgsl↖3i↗, "int_literal"), "3i".to_string()),
        ],
        &text,
    );
    let wgsl_float_sample = descend(&wgsl↖1.5f↗, "float_literal");
    let wgsl_float = shape_with(&wgsl_float_sample, &text_of(&wgsl_float_sample), &text);
    let wgsl_true = descend(&wgsl↖true↗, "bool_literal").↑;
    let wgsl_false = descend(&wgsl↖false↗, "bool_literal").↑;

    ⟨//⟩ Python.
    let py_int_sample = descend(&py↖3↗, "integer");
    let py_int = shape_with(&py_int_sample, &text_of(&py_int_sample), &text);
    let py_float_sample = descend(&py↖1.5↗, "float");
    let py_float = shape_with(&py_float_sample, &text_of(&py_float_sample), &text);
    let py_true = descend(&py↖True↗, "true").↑;
    let py_false = descend(&py↖False↗, "false").↑;
    let py_str_empty = descend(&py↖""↗, "string").↑;
    let py_str = shape_with(
        &descend(&py↖"s"↗, "string"),
        "s",
        &rs↖&py_dquote_escape(s)↗,
    );

    ⟨//⟩ Shells. Derived per language rather than shared: bash and zsh have the
    ⟨//⟩ same grammar lineage, and #150 is what assuming that costs.
    let bash_num_sample = descend(&bash↖3↗, "number");
    let bash_num = shape_with(&bash_num_sample, &text_of(&bash_num_sample), &text);
    let bash_str_empty = descend(&bash↖""↗, "string").↑;
    let bash_str = shape_with(
        &descend(&bash↖"s"↗, "string"),
        "s",
        &rs↖&sh_dquote_escape(s)↗,
    );
    let zsh_num_sample = descend(&zsh↖3↗, "number");
    let zsh_num = shape_with(&zsh_num_sample, &text_of(&zsh_num_sample), &text);
    let zsh_str_empty = descend(&zsh↖""↗, "string").↑;
    let zsh_str = shape_with(
        &descend(&zsh↖"s"↗, "string"),
        "s",
        &rs↖&sh_dquote_escape(s)↗,
    );

    ⟨//⟩ Nix.
    let nix_int_sample = descend(&nix↖3↗, "integer_expression");
    let nix_int = shape_with(&nix_int_sample, &text_of(&nix_int_sample), &text);
    let nix_float_sample = descend(&nix↖1.5↗, "float_expression");
    let nix_float = shape_with(&nix_float_sample, &text_of(&nix_float_sample), &text);
    let nix_true = descend(&nix↖true↗, "variable_expression").↑;
    let nix_false = descend(&nix↖false↗, "variable_expression").↑;
    let nix_str_empty = descend(&nix↖""↗, "string_expression").↑;
    let nix_str = shape_with(
        &descend(&nix↖"s"↗, "string_expression"),
        "s",
        &rs↖&nix_dquote_escape(s)↗,
    );

    ⟨//⟩ Lean. `num_lit` and `scientific_lit` are unsigned in the grammar, so a
    ⟨//⟩ negative value is the `unary_op` `-` applied to its magnitude. That is a
    ⟨//⟩ second sample rather than a special case: both branches are the shape
    ⟨//⟩ the parser builds, with the same magnitude substituted into each.
    let lean_num_sample = descend(&lean↖3↗, "num_lit");
    let lean_num = shape_with(&lean_num_sample, &text_of(&lean_num_sample), &text);
    let lean_num_neg_sample = descend(&lean↖-3↗, "unary_op");
    let lean_num_neg = shape_with(
        &lean_num_neg_sample,
        &text_of(&descend(&lean_num_neg_sample, "num_lit")),
        &text,
    );
    let lean_float_sample = descend(&lean↖1.5↗, "scientific_lit");
    let lean_float = shape_with(&lean_float_sample, &text_of(&lean_float_sample), &text);
    let lean_float_neg_sample = descend(&lean↖-1.5↗, "unary_op");
    let lean_float_neg = shape_with(
        &lean_float_neg_sample,
        &text_of(&descend(&lean_float_neg_sample, "scientific_lit")),
        &text,
    );
    let lean_true = descend(&lean↖true↗, "true_const").↑;
    let lean_false = descend(&lean↖false↗, "false_const").↑;
    let lean_str_empty = descend(&lean↖""↗, "str_lit").↑;
    let lean_str = shape_with(
        &descend(&lean↖"s"↗, "str_lit"),
        "s",
        &rs↖&lean_dquote_escape(s)↗,
    );

    ⟨//⟩ SQL. The sign is *outside* the number token in this grammar
    ⟨//⟩ (`_integer` is `seq(optional(choice("-", "+")), /…/)`), so `-7` is a `-`
    ⟨//⟩ child followed by the magnitude as the literal's own text — a second
    ⟨//⟩ sample, like Lean's. A string is the opposite: quotes, doubling and all
    ⟨//⟩ sit inside one token, so there is nothing to special-case for the empty
    ⟨//⟩ string and nothing an escape can split.
    let sql_num_sample = descend(&sql↖7↗, "literal");
    let sql_num = shape_with(&sql_num_sample, &text_of(&sql_num_sample), &text);
    let sql_num_neg_sample = descend(&sql↖-7↗, "literal");
    let sql_num_neg = shape_with(&sql_num_neg_sample, "7", &text);
    let sql_true = descend(&sql↖TRUE↗, "literal").↑;
    let sql_false = descend(&sql↖FALSE↗, "literal").↑;
    let sql_str = shape_with(
        &descend(&sql↖'s'↗, "literal"),
        "'s'",
        &rs↖&format!("'{}'", sql_squote_escape(s))↗,
    );
    ⟨//⟩ The MySQL dialect differs from the standard in exactly one place: the
    ⟨//⟩ escaper. Same grammar, same token, so the same sample serves (#233).
    let mysql_str = shape_with(
        &descend(&sql↖'s'↗, "literal"),
        "'s'",
        &rs↖&format!("'{}'", mysql_squote_escape(s))↗,
    );

    ⟨//⟩ TypeScript. One `number` for integers and floats alike, and — like
    ⟨//⟩ Lean — unsigned, so a negative is the `unary_expression` `-` over its
    ⟨//⟩ magnitude: a second sample, not a special case.
    let ts_num_sample = descend(&ts↖3↗, "number");
    let ts_num = shape_with(&ts_num_sample, &text_of(&ts_num_sample), &text);
    let ts_num_neg_sample = descend(&ts↖-3↗, "unary_expression");
    let ts_num_neg = shape_with(
        &ts_num_neg_sample,
        &text_of(&descend(&ts_num_neg_sample, "number")),
        &text,
    );
    let ts_true = descend(&ts↖true↗, "true").↑;
    let ts_false = descend(&ts↖false↗, "false").↑;
    let ts_str_empty = descend(&ts↖""↗, "string").↑;
    let ts_str = shape_with(
        &descend(&ts↖"s"↗, "string"),
        "s",
        &rs↖&ts_dquote_escape(s)↗,
    );

    ⟨//⟩ HTML. Text content is a `text` node whatever the value was; the escape
    ⟨//⟩ makes it inert both there and inside a quoted attribute value.
    let html_text_sample = descend(&html↖x↗, "text");
    let html_text = shape_with(&html_text_sample, &text_of(&html_text_sample), &text);

    ⟨//⟩ Containers: an empty one, a two-element one, and the two elements.
    let py_list = (
        descend(&py↖[]↗, "list"),
        descend(&py↖[1, 4]↗, "list"),
        descend(&py↖1↗, "integer"),
        descend(&py↖4↗, "integer"),
    );
    let nix_list = (
        descend(&nix↖[ ]↗, "list_expression"),
        descend(&nix↖[ 1 4 ]↗, "list_expression"),
        descend(&nix↖1↗, "integer_expression"),
        descend(&nix↖4↗, "integer_expression"),
    );
    let lean_list = (
        descend(&lean↖[]↗, "list_lit"),
        descend(&lean↖[1, 4]↗, "list_lit"),
        descend(&lean↖1↗, "num_lit"),
        descend(&lean↖4↗, "num_lit"),
    );
    let ts_list = (
        descend(&ts↖[]↗, "array"),
        descend(&ts↖[1, 4]↗, "array"),
        descend(&ts↖1↗, "number"),
        descend(&ts↖4↗, "number"),
    );
    let sql_list = (
        descend(&sql↖()↗, "list"),
        descend(&sql↖(1, 4)↗, "list"),
        descend(&sql↖1↗, "literal"),
        descend(&sql↖4↗, "literal"),
    );

    ⟨//⟩ ---- the file ----

    let out: ⟨T⟩ = rs↖
        use super::{
            escape_html, lean_dquote_escape, mysql_squote_escape, nix_dquote_escape,
            py_dquote_escape, sh_dquote_escape, sql_squote_escape, ts_dquote_escape, Bash, Html,
            Lean, LiftTo, MySql, Nix, Python, Sql, TypeScript, Wgsl, Zsh,
        };
        use crate::qterm::{leaf, sym, tb, QTerm};
        use std::sync::Arc;

        ↙
            ⟨//⟩ ---------------- WGSL ----------------
            ⟨//⟩ WGSL has no 64-bit integers, so u64/i64 get no impl — lifting
            ⟨//⟩ one is a compile error in the expanded program rather than a
            ⟨//⟩ silent truncation.
            ↖
                /// WGSL `3u` / `3i`. The parser wraps a literal in a
                /// `const_literal`; this is the inner node, which is what
                /// `conformance/spec/wgsl.toml` pins — see issue #174.
                ///
                /// WGSL has no 64-bit integers, so `u64`/`i64` get no impl
                /// below: lifting one is a compile error in the expanded
                /// program rather than a silent truncation.
                pub fn wgsl_int_term(text: &str) -> ⟨T⟩ {
                    ↙wgsl_int↘
                }
            ↗.←;
            NL.←;
            scalar_impls("Wgsl", &["u8", "u16", "u32", "usize"], &↖wgsl_int_term(&format!("{self}u"))↗).←;
            scalar_impls("Wgsl", &["i8", "i16", "i32", "isize"], &↖wgsl_int_term(&format!("{self}i"))↗).←;
            NL.←;
            ↖
                /// WGSL `1.5f`.
                pub fn wgsl_float_term(text: &str) -> ⟨T⟩ {
                    ↙wgsl_float↘
                }
            ↗.←;
            NL.←;
            scalar_impls("Wgsl", &["f32"], &↖wgsl_float_term(&format!("{self}f"))↗).←;
            NL.←;
            ↖
                /// WGSL `true` / `false`. The keyword is a child token of the
                /// `bool_literal`, not its text — a lift that spelled it as
                /// text coparsed identically and matched nothing.
                pub fn wgsl_bool_term(b: bool) -> ⟨T⟩ {
                    if b {
                        ↙wgsl_true↘
                    } else {
                        ↙wgsl_false↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls("Wgsl", &["bool"], &↖wgsl_bool_term(*self)↗).←;
            NL.←;

            ⟨//⟩ ---------------- Python ----------------
            ↖
                /// Python `3`. Python integers are arbitrary-precision, so
                /// every Rust integer width lifts losslessly.
                pub fn py_int_term(text: &str) -> ⟨T⟩ {
                    ↙py_int↘
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Python",
                &["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"],
                &↖py_int_term(&self.to_string())↗,
            ).←;
            NL.←;
            ↖
                /// Python `1.5`.
                pub fn py_float_term(text: &str) -> ⟨T⟩ {
                    ↙py_float↘
                }
            ↗.←;
            NL.←;
            ⟨//⟩ `{:?}` keeps the decimal point (`1.0`, not `1`), so the lifted
            ⟨//⟩ literal stays a float.
            scalar_impls("Python", &["f32", "f64"], &↖py_float_term(&format!("{self:?}"))↗).←;
            NL.←;
            ↖
                /// Python `True` / `False` — two different node kinds, not one
                /// kind with two spellings.
                pub fn py_bool_term(b: bool) -> ⟨T⟩ {
                    if b {
                        ↙py_true↘
                    } else {
                        ↙py_false↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls("Python", &["bool"], &↖py_bool_term(*self)↗).←;
            NL.←;
            ↖
                /// Python `"s"` — a three-child `string`, and for the empty
                /// string a two-child one, because the parser emits no
                /// `string_content` when there is no content.
                ///
                /// Public because `quilt-python`'s own `qlift` needs exactly
                /// this shape: there were two implementations of "lift a string
                /// into Python", and they disagreed (#176). Sharing the
                /// constructor is what keeps them from drifting apart again —
                /// and generating it is what keeps *this* one honest.
                pub fn py_string_term(s: &str) -> ⟨T⟩ {
                    if s.is_empty() {
                        ↙py_str_empty↘
                    } else {
                        ↙py_str↘
                    }
                }
            ↗.←;
            NL.←;
            string_impls("Python", &↖py_string_term(self)↗).←;
            NL.←;
            container_fn("py_list_term", &py_list).←;
            NL.←;
            list_impls(
                "Python",
                &↖py_list_term(&self.iter().map(|x| x.lift_to()).collect::<Vec<_>>())↗,
            ).←;
            NL.←;

            ⟨//⟩ ---------------- Bash ----------------
            ↖
                /// Bash `3` — a bare `number` word.
                pub fn bash_number_term(text: &str) -> ⟨T⟩ {
                    ↙bash_num↘
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Bash",
                &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"],
                &↖bash_number_term(&self.to_string())↗,
            ).←;
            NL.←;
            ↖
                /// Bash `"s"`. Double-quoted so the value is inert data:
                /// everything the shell would interpret inside `"…"` is
                /// backslash-escaped first.
                pub fn bash_string_term(s: &str) -> ⟨T⟩ {
                    if s.is_empty() {
                        ↙bash_str_empty↘
                    } else {
                        ↙bash_str↘
                    }
                }
            ↗.←;
            NL.←;
            string_impls("Bash", &↖bash_string_term(self)↗).←;
            NL.←;

            ⟨//⟩ ---------------- Zsh ----------------
            ↖
                /// Zsh `3` — derived from the zsh grammar, not assumed equal to
                /// bash's. Eleven constructs the two shells were assumed to
                /// share had quietly drifted apart once already (#150).
                pub fn zsh_number_term(text: &str) -> ⟨T⟩ {
                    ↙zsh_num↘
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Zsh",
                &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"],
                &↖zsh_number_term(&self.to_string())↗,
            ).←;
            NL.←;
            ↖
                /// Zsh `"s"`.
                pub fn zsh_string_term(s: &str) -> ⟨T⟩ {
                    if s.is_empty() {
                        ↙zsh_str_empty↘
                    } else {
                        ↙zsh_str↘
                    }
                }
            ↗.←;
            NL.←;
            string_impls("Zsh", &↖zsh_string_term(self)↗).←;
            NL.←;

            ⟨//⟩ ---------------- Nix ----------------
            ↖
                /// Nix `3`. Nix integers are 64-bit, matching the shell widths.
                pub fn nix_int_term(text: &str) -> ⟨T⟩ {
                    ↙nix_int↘
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Nix",
                &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"],
                &↖nix_int_term(&self.to_string())↗,
            ).←;
            NL.←;
            ↖
                /// Nix `1.5`.
                pub fn nix_float_term(text: &str) -> ⟨T⟩ {
                    ↙nix_float↘
                }
            ↗.←;
            NL.←;
            scalar_impls("Nix", &["f32", "f64"], &↖nix_float_term(&format!("{self:?}"))↗).←;
            NL.←;
            ↖
                /// Nix `true` / `false`. They are builtins rather than
                /// keywords, so the parser reads them as a variable reference
                /// and the name is its own node.
                pub fn nix_bool_term(b: bool) -> ⟨T⟩ {
                    if b {
                        ↙nix_true↘
                    } else {
                        ↙nix_false↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls("Nix", &["bool"], &↖nix_bool_term(*self)↗).←;
            NL.←;
            ↖
                /// Nix `"s"`. Besides `"` and `\`, the antiquotation opener is
                /// escaped, so the value stays data rather than interpolating.
                pub fn nix_string_term(s: &str) -> ⟨T⟩ {
                    if s.is_empty() {
                        ↙nix_str_empty↘
                    } else {
                        ↙nix_str↘
                    }
                }
            ↗.←;
            NL.←;
            string_impls("Nix", &↖nix_string_term(self)↗).←;
            NL.←;
            container_fn("nix_list_term", &nix_list).←;
            NL.←;
            list_impls(
                "Nix",
                &↖nix_list_term(&self.iter().map(|x| x.lift_to()).collect::<Vec<_>>())↗,
            ).←;
            NL.←;

            ⟨//⟩ ---------------- Lean ----------------
            ↖
                /// Lean `3` and `-3`. `Nat`/`Int` are arbitrary-precision, so
                /// every Rust integer width lifts losslessly; `num_lit` itself
                /// is unsigned, so the sign is a node rather than a character.
                pub fn lean_num_term(negative: bool, text: &str) -> ⟨T⟩ {
                    if negative {
                        ↙lean_num_neg↘
                    } else {
                        ↙lean_num↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Lean",
                &["u8", "u16", "u32", "u64", "u128", "usize"],
                &↖lean_num_term(false, &self.to_string())↗,
            ).←;
            scalar_impls(
                "Lean",
                &["i8", "i16", "i32", "i64", "i128", "isize"],
                &↖lean_num_term(*self < 0, &self.unsigned_abs().to_string())↗,
            ).←;
            NL.←;
            ↖
                /// Lean `1.5` and `-1.5`.
                pub fn lean_float_term(negative: bool, text: &str) -> ⟨T⟩ {
                    if negative {
                        ↙lean_float_neg↘
                    } else {
                        ↙lean_float↘
                    }
                }
            ↗.←;
            NL.←;
            ⟨//⟩ `{:?}` keeps the decimal point so it stays a float, not a `Nat`.
            ⟨//⟩ The sign is read off the rendered text rather than compared
            ⟨//⟩ against zero, so `-0.0` — which is not `< 0.0` — still lifts to
            ⟨//⟩ the negation the parser builds for it.
            scalar_impls(
                "Lean",
                &["f32", "f64"],
                &↖
                    {
                        let s = format!("{self:?}");
                        match s.strip_prefix('-') {
                            Some(mag) => lean_float_term(true, mag),
                            None => lean_float_term(false, &s),
                        }
                    }
                ↗,
            ).←;
            NL.←;
            ↖
                /// Lean `true` / `false`.
                pub fn lean_bool_term(b: bool) -> ⟨T⟩ {
                    if b {
                        ↙lean_true↘
                    } else {
                        ↙lean_false↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls("Lean", &["bool"], &↖lean_bool_term(*self)↗).←;
            NL.←;
            ↖
                /// Lean `"s"`. The quote tokens are children and the body sits
                /// between them as raw text, not as a node of its own.
                pub fn lean_string_term(s: &str) -> ⟨T⟩ {
                    if s.is_empty() {
                        ↙lean_str_empty↘
                    } else {
                        ↙lean_str↘
                    }
                }
            ↗.←;
            NL.←;
            string_impls("Lean", &↖lean_string_term(self)↗).←;
            NL.←;
            container_fn("lean_list_term", &lean_list).←;
            NL.←;
            ⟨//⟩ ---------------- SQL ----------------
            ↖
                /// SQL `7` and `-7`. The sign is a child token of the
                /// `literal` rather than part of its text, because `_integer`
                /// is `seq(optional(choice("-", "+")), …)` — so a lift that
                /// spelled `-7` as one leaf built a tree the parser never
                /// produces, which `smatch` and `rewrite` can see (#174).
                pub fn sql_number_term(negative: bool, text: &str) -> ⟨T⟩ {
                    if negative {
                        ↙sql_num_neg↘
                    } else {
                        ↙sql_num↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Sql",
                &["u8", "u16", "u32", "u64", "u128", "usize"],
                &↖sql_number_term(false, &self.to_string())↗,
            ).←;
            scalar_impls(
                "Sql",
                &["i8", "i16", "i32", "i64", "i128", "isize"],
                &↖sql_number_term(*self < 0, &self.unsigned_abs().to_string())↗,
            ).←;
            ⟨//⟩ `{:?}` keeps the decimal point, which is what makes the literal
            ⟨//⟩ parse as `_decimal_number` rather than as an integer.
            scalar_impls(
                "Sql",
                &["f32", "f64"],
                &↖
                    {
                        let s = format!("{self:?}");
                        match s.strip_prefix('-') {
                            Some(mag) => sql_number_term(true, mag),
                            None => sql_number_term(false, &s),
                        }
                    }
                ↗,
            ).←;
            NL.←;
            ↖
                /// SQL `TRUE` / `FALSE`. The keyword is its own node inside the
                /// `literal`, unlike the numeric and string forms.
                pub fn sql_bool_term(b: bool) -> ⟨T⟩ {
                    if b {
                        ↙sql_true↘
                    } else {
                        ↙sql_false↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls("Sql", &["bool"], &↖sql_bool_term(*self)↗).←;
            NL.←;
            ↖
                /// SQL `'s'` — one `literal` token, quotes included. The empty
                /// string needs no separate branch and an escaped quote needs
                /// no exemption, because nothing inside the quotes is a node of
                /// its own: `'O''Hara'` is still a single token.
                pub fn sql_string_term(s: &str) -> ⟨T⟩ {
                    ↙sql_str↘
                }
            ↗.←;
            NL.←;
            string_impls("Sql", &↖sql_string_term(self)↗).←;
            NL.←;
            container_fn("sql_list_term", &sql_list).←;
            NL.←;
            list_impls(
                "Sql",
                &↖sql_list_term(&self.iter().map(|x| x.lift_to()).collect::<Vec<_>>())↗,
            ).←;
            NL.←;

            ⟨//⟩ ---------------- MySQL ----------------
            ⟨//⟩ The same grammar under a different name, so every *shape* here
            ⟨//⟩ is SQL's — the number, bool and list constructors are reused
            ⟨//⟩ verbatim. Only the string escaper differs, which is the whole
            ⟨//⟩ of issue #233: MySQL reads a backslash inside `'…'` as an
            ⟨//⟩ escape and the standard does not, and no single spelling is
            ⟨//⟩ right for both. Reusing the constructors is not just brevity —
            ⟨//⟩ it is what stops the two dialects drifting into two shapes.
            scalar_impls(
                "MySql",
                &["u8", "u16", "u32", "u64", "u128", "usize"],
                &↖sql_number_term(false, &self.to_string())↗,
            ).←;
            scalar_impls(
                "MySql",
                &["i8", "i16", "i32", "i64", "i128", "isize"],
                &↖sql_number_term(*self < 0, &self.unsigned_abs().to_string())↗,
            ).←;
            scalar_impls(
                "MySql",
                &["f32", "f64"],
                &↖
                    {
                        let s = format!("{self:?}");
                        match s.strip_prefix('-') {
                            Some(mag) => sql_number_term(true, mag),
                            None => sql_number_term(false, &s),
                        }
                    }
                ↗,
            ).←;
            scalar_impls("MySql", &["bool"], &↖sql_bool_term(*self)↗).←;
            NL.←;
            ↖
                /// `MySQL` `'s'`. Identical in shape to `sql_string_term` and
                /// different only in the escaper it calls — see
                /// `mysql_squote_escape` for why that difference exists.
                pub fn mysql_string_term(s: &str) -> ⟨T⟩ {
                    ↙mysql_str↘
                }
            ↗.←;
            NL.←;
            string_impls("MySql", &↖mysql_string_term(self)↗).←;
            NL.←;
            list_impls(
                "MySql",
                &↖sql_list_term(&self.iter().map(|x| x.lift_to()).collect::<Vec<_>>())↗,
            ).←;
            NL.←;

            ⟨//⟩ ---------------- TypeScript ----------------
            ↖
                /// TypeScript `3`, `1.5`, `-3`. One `number` node for integers
                /// and floats; unsigned, so the sign is a `unary_expression`
                /// rather than a character.
                ///
                /// Public because `quilt-python`'s `qlift_ts` builds the same
                /// literal, and a shape written twice is how #176 started.
                pub fn ts_number_term(negative: bool, text: &str) -> ⟨T⟩ {
                    if negative {
                        ↙ts_num_neg↘
                    } else {
                        ↙ts_num↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "TypeScript",
                &["u8", "u16", "u32", "u64", "u128", "usize"],
                &↖ts_number_term(false, &self.to_string())↗,
            ).←;
            scalar_impls(
                "TypeScript",
                &["i8", "i16", "i32", "i64", "i128", "isize"],
                &↖ts_number_term(*self < 0, &self.unsigned_abs().to_string())↗,
            ).←;
            ⟨//⟩ `{:?}` keeps the decimal point (`1.0`); the sign is read off the
            ⟨//⟩ text, as for Lean, so `-0.0` is the negation the parser builds.
            scalar_impls(
                "TypeScript",
                &["f32", "f64"],
                &↖
                    {
                        let s = format!("{self:?}");
                        match s.strip_prefix('-') {
                            Some(mag) => ts_number_term(true, mag),
                            None => ts_number_term(false, &s),
                        }
                    }
                ↗,
            ).←;
            NL.←;
            ↖
                /// TypeScript `true` / `false` — node kinds of their own.
                pub fn ts_bool_term(b: bool) -> ⟨T⟩ {
                    if b {
                        ↙ts_true↘
                    } else {
                        ↙ts_false↘
                    }
                }
            ↗.←;
            NL.←;
            scalar_impls("TypeScript", &["bool"], &↖ts_bool_term(*self)↗).←;
            NL.←;
            ↖
                /// TypeScript `"s"`. Like Python's, the empty string has no
                /// `string_fragment` child, because there is no content.
                pub fn ts_string_term(s: &str) -> ⟨T⟩ {
                    if s.is_empty() {
                        ↙ts_str_empty↘
                    } else {
                        ↙ts_str↘
                    }
                }
            ↗.←;
            NL.←;
            string_impls("TypeScript", &↖ts_string_term(self)↗).←;
            NL.←;
            container_fn("ts_list_term", &ts_list).←;
            NL.←;
            list_impls(
                "TypeScript",
                &↖ts_list_term(&self.iter().map(|x| x.lift_to()).collect::<Vec<_>>())↗,
            ).←;
            NL.←;

            ⟨//⟩ ---------------- HTML ----------------
            ↖
                /// HTML text content. Every value is a `text` node; a string's
                /// is entity-escaped by `escape_html` first, the rule the
                /// runtimes' `qlift_html` share. No list impl: HTML has no
                /// literal syntax for a sequence to borrow.
                pub fn html_text_term(text: &str) -> ⟨T⟩ {
                    ↙html_text↘
                }
            ↗.←;
            NL.←;
            scalar_impls(
                "Html",
                &["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool"],
                &↖html_text_term(&self.to_string())↗,
            ).←;
            scalar_impls("Html", &["f32", "f64"], &↖html_text_term(&format!("{self:?}"))↗).←;
            string_impls("Html", &↖html_text_term(&escape_html(self))↗).←;
            NL.←;

            ⟨//⟩ A loop, not `list_impls(…).←;`, because the expander terminates
            ⟨//⟩ the block's last statement itself: an emit in that position gets
            ⟨//⟩ two `;` and warns on every run. A `for` needs no terminator.
            for it in list_impls(
                "Lean",
                &↖lean_list_term(&self.iter().map(|x| x.lift_to()).collect::<Vec<_>>())↗,
            ) {
                it.←;
            }
        ↘
    ↗;

    out.dump_with_cmds("src/lift/gen.rs", &header(), &[])?;
    Command::new("cargo")
        .args(["fmt", "--", "src/lift/gen.rs"])
        .status()
        .ok();
    Ok(())
}

/// The `//!` block at the top of the generated file. Written as raw commands
/// rather than parsed, so it never has to survive a round trip.
fn header() -> Vec<StrCmd> {
    let mut cmds = Vec::new();
    for line in [
        "//! `LiftTo` impls: the shape each target's parser builds for a literal.",
        "//!",
        "//! @generated by `bin/gen-lifts` from `quilt/src/lift/mk_lifts.rs.quilt` —",
        "//! do not edit by hand. `bin/check-lifts` regenerates it and fails if it",
        "//! differs, so a lift cannot drift from the grammar it is meant to match.",
        "//!",
        "//! Every shape below was read off a *parsed sample literal*. The generator",
        "//! parses e.g. `py\u{2196}\"s\"\u{2197}` with the vendored grammar and lifts",
        "//! with `↑`, which prints the builder calls that rebuild it; the sample's",
        "//! own text is then replaced by the runtime expression. So the tags, the",
        "//! child structure and the layout are the parser's, not a transcription of",
        "//! it. Two hand surveys had to be done before this existed (#176, then",
        "//! `fed278b`); generating it is issue #203.",
        "//!",
        "//! Three families are still deliberately *not* the parser's shape:",
        "//!",
        "//! * WGSL literals parse wrapped in a `const_literal`; these lifts produce",
        "//!   the inner node, which is the tag `conformance/spec/wgsl.toml` pins.",
        "//!   Adopting the wrapper moves a declared claim — the open call in #174.",
        "//! * A negative Python or Nix integer parses as a `unary_operator` /",
        "//!   `unary_expression` over a positive literal; these lift one signed",
        "//!   literal. Same call. Lean's negatives *are* the parser's shape.",
        "//! * A string containing escapes parses with `escape_sequence` children",
        "//!   inside its content, which no runtime reproduces (#174, finding A2).",
    ] {
        cmds.push(write(line));
        cmds.push(NL);
    }
    cmds.push(NL);
    cmds
}