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
//! Heterogeneous lifting: turn host-language (Rust) values into `QTerm`s of a
//! *target* object language, selected by a zero-sized marker type.
//!
//! The homogeneous `↑` (Rust lifting into Rust) is `QLift`/`qlift()` in
//! `langs::rust::ops`; this module generalizes it to `LiftTo<L>`, indexed by
//! the target language. Inside `wgsl↖ … ↙x.↑↘ … ↗` the `↑` expands to
//! `qlift_to::<Wgsl>()` (see `langs::rust::ops::lift_spelling`), so a Rust
//! `3u32` lifts to the WGSL term `3u` instead of the Rust term `3`.
//!
//! The impls themselves live in [`gen`], generated by `bin/gen-lifts` from
//! sample literals parsed by the vendored grammars — so a lift's tags, child
//! structure and layout are the parser's rather than a transcription of it
//! (issue #203). What stays here by hand is what is not a shape: the markers,
//! the trait, and the per-target escaping rules the generated shapes call.
//!
//! This module is deliberately *not* gated behind the per-language parser
//! features: lift impls are runtime code for expanded programs, which may not
//! enable the target language's parser (e.g. `nanobots-web` builds quilt with
//! only the `rust` feature but splices WGSL terms). The markers index lifting;
//! they don't need the parser.

use crate::qterm::QTerm;
use std::sync::Arc;

mod gen;
pub use gen::*;

mod text;
pub use text::{
    json_escape, json_float, json_string, InQuotes, Json, Raw, Text, TextDialect, TextValue,
    TEXT_IN_QUOTES,
};

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

/// Marker: the Rust object language (the homogeneous case; see `QLift`).
pub struct Rust;

/// Marker: the Python object language.
pub struct Python;

/// Marker: the WGSL object language.
pub struct Wgsl;

/// Marker: the Zsh object language.
pub struct Zsh;

/// Marker: the Bash object language.
pub struct Bash;

/// Marker: the Nix object language.
pub struct Nix;

/// Marker: the Lean 4 object language.
pub struct Lean;

/// Marker: the TypeScript object language.
pub struct TypeScript;

/// Marker: the HTML object language. A value lifts to an entity-escaped `text`
/// node — the same rule as the Python and TypeScript runtimes' `qlift_html`,
/// which call [`escape_html`] too.
pub struct Html;

/// Marker: the SQL object language, standard dialect.
///
/// Escaping follows the SQL standard, which is also what `PostgreSQL` (with
/// `standard_conforming_strings = on`, the default since 9.1), `SQLite` and SQL
/// Server read. See [`MySql`] for the one widespread dialect that differs.
pub struct Sql;

/// Marker: the SQL object language, `MySQL`/`MariaDB` dialect.
///
/// Reached by annotating the quote `mysql↖ … ↗` (or `mariadb↖ … ↗`) instead of
/// `sql↖ … ↗` — both are registered names for the same grammar, so the *parse*
/// is identical and only the escaping differs. See [`mysql_squote_escape`] for
/// why that is not a detail (#233).
pub struct MySql;

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

/// Lift a value to a `QTerm` of the object language `L` (the `↑` operator).
///
/// Implement this per (Rust type, target language) pair; the impl owns the
/// target language's spelling and tags (e.g. WGSL `u32` literals are
/// `int_literal`s spelled `3u`).
pub trait LiftTo<L> {
    fn lift_to(&self) -> Arc<QTerm>;
}

/// Postfix sugar for [`LiftTo`]: `x.qlift_to::<Wgsl>()`. Blanket-implemented,
/// so it is always in scope via the prelude; the bound is only required at the
/// call site.
pub trait QLiftTo {
    fn qlift_to<L>(&self) -> Arc<QTerm>
    where
        Self: LiftTo<L>,
    {
        LiftTo::<L>::lift_to(self)
    }
}

impl<T: ?Sized> QLiftTo for T {}

/**************************************************************/
// Escaping rules. A generated shape in `gen` holds the literal's *structure*
// and calls one of these for its content, so each is the single place its
// target's quoting is decided. Several are shared further — with a host
// (`langs::shell::ops`) or a binding (`quilt-python`) — which is the point:
// two implementations of one escaping rule is how #150, #176 and #192 each
// started.

/// Escape a string for inclusion in a Python double-quoted literal.
///
/// Public because the `quilt-python` runtime's own `qlift` needs exactly this
/// rule: there were two implementations of "lift a string into Python" — this
/// one, and the binding's, which did no escaping at all, so `qlift('a"b')`
/// produced an unparseable literal and `qlift('a\\b')` silently changed the
/// value (`\\b` is a backspace escape in Python). Sharing the function is what
/// keeps them from drifting apart again. Found by the shared runtime corpus
/// (#159), which runs the same cases against all three published runtimes.
pub fn py_dquote_escape(s: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' | '\\' => {
                out.push('\\');
                out.push(c);
            }
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => write!(out, "\\x{:02x}", c as u32).unwrap(),
            c => out.push(c),
        }
    }
    out
}

/**************************************************************/
// TypeScript. A string lifts to a double-quoted `string`, escaped as the
// TypeScript meta escapes the strings in generated code.

/// Escape a string for inclusion in a TypeScript/JavaScript double-quoted
/// literal: `"` and `\` backslash-escaped, `\n` `\r` `\t` spelled short, every
/// other control character as `\uXXXX`.
///
/// Public for the same reason as [`py_dquote_escape`]: `quilt-python`'s
/// `qlift_ts` builds the same literal, and `langs::typescript::ops` writes
/// generated code's strings with it. `quilt-wasm`'s JavaScript runtime keeps a
/// copy (`tsStringLit`), which the shared runtime corpus holds to this one.
#[must_use]
pub fn ts_dquote_escape(s: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' | '\\' => {
                out.push('\\');
                out.push(c);
            }
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => write!(out, "\\u{:04x}", c as u32).unwrap(),
            c => out.push(c),
        }
    }
    out
}

/**************************************************************/
// HTML. `LiftTo<Html>` (generated, in `gen`) and both runtimes' `qlift_html`
// call this, so a value is escaped the same way whichever host lifts it.

/// Escape `& < > " '` so `s` is inert HTML wherever a hole can sit: as text
/// content, and inside a single- or double-quoted attribute value.
///
/// Public for the same reason as [`py_dquote_escape`]: the `quilt-python` and
/// `quilt-wasm` runtimes each need exactly this rule for their `qlift_html`,
/// and each had grown its own byte-identical copy. Three copies of an escaping
/// table is three chances to fix a hole in one of them — the class of bug the
/// conformance epic (#144) exists to close — so the rule lives here and the
/// bindings call it. Tested directly here; issue #192 is where the two copies
/// having no direct test at all was written up.
///
/// Not idempotent, and deliberately so: escaping `&amp;` yields `&amp;amp;`,
/// because the input is a *value*, not markup. A caller lifting an
/// already-escaped fragment wants the term pass-through both `qlift_html`
/// implementations do, not a second trip through this function.
#[must_use]
pub fn escape_html(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#x27;"),
            _ => out.push(c),
        }
    }
    out
}

/**************************************************************/
// Shells (Zsh, Bash). A Rust string lifts to a double-quoted `string` literal
// so the value is treated as inert data: characters the shell would interpret
// inside `"…"` (`"`, `\`, `$`, `` ` ``) are backslash-escaped. The two shells
// share a grammar lineage, so one escaping rule serves both — their *shapes*
// are still derived separately, since #150 is what assuming otherwise costs.

/// Escape a string for inclusion in a POSIX shell double-quoted literal.
///
/// Shared with the shell *hosts* (`langs::shell::ops`, #151), which reconstruct
/// a quoted fragment as one of these literals: a lifted value and the literal
/// text around it land in the same generated word, so escaping them two
/// different ways is the drift issue #150 is about. It lives here rather than
/// beside the host because `lift.rs` is compiled unconditionally, while
/// `langs::shell` needs the `bash` or `zsh` feature.
pub(crate) fn sh_dquote_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '"' | '\\' | '$' | '`') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/**************************************************************/
// Nix. Nix is a pure expression language, so every value lifts to its literal
// expression; a string lifts to a double-quoted `string_expression`.

/// Escape a string for inclusion in a Nix double-quoted literal. Besides `"`
/// and `\`, the antiquotation opener `${` is escaped (to `\${`) so the value
/// stays inert data rather than triggering interpolation.
fn nix_dquote_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '"' | '\\' => {
                out.push('\\');
                out.push(c);
            }
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
            c => out.push(c),
        }
    }
    out
}

/**************************************************************/
// Lean. A string lifts to a `str_lit`, whose body is raw text between two quote
// tokens rather than a node of its own.

/// Escape a string for inclusion in a Lean double-quoted literal. Lean's string
/// escapes are the familiar C-like set; note `{` is *not* escaped here — that is
/// only special inside an interpolated `s!"…"`, which a lifted literal is not.
fn lean_dquote_escape(s: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' | '\\' => {
                out.push('\\');
                out.push(c);
            }
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => write!(out, "\\u{:04x}", c as u32).unwrap(),
            c => out.push(c),
        }
    }
    out
}

/**************************************************************/
// SQL. This is the module's security-relevant corner (#219): a value spliced
// into a quoted query with `↑` becomes a *literal node*, so it is data the
// parser has already accepted as a single token rather than text pasted into a
// statement. Every scalar lifts to a `literal`, the one tag this grammar gives
// every constant. Which is why the escaping rule below is the part that has to
// be right by hand — the shapes around it are derived (see `gen`).

/// Escape a string for inclusion in a SQL single-quoted literal.
///
/// Standard SQL has exactly **one** escape inside `'…'`: a single quote is
/// written twice. Backslash is an ordinary character — this grammar's
/// `_single_quote_string` rule (`/([uU]&|[nN])?'([^']|'')*'/`) says the same —
/// so it is passed through unchanged. Escaping it would be a silent corruption
/// of the value under the standard, not extra safety.
///
/// That makes the result safe against quote-breakout for standard SQL and for
/// `PostgreSQL` with `standard_conforming_strings = on` (the default since 9.1),
/// as well as `SQLite` and SQL Server. It is **not** safe for `MySQL` in its
/// default mode — write `mysql↖ … ↗` and get [`mysql_squote_escape`] instead.
pub(crate) fn sql_squote_escape(s: &str) -> String {
    s.replace('\'', "''")
}

/// Escape a string for inclusion in a `MySQL`/`MariaDB` single-quoted literal.
///
/// `MySQL` in its **default** `sql_mode` (`NO_BACKSLASH_ESCAPES` *off*) reads a
/// backslash inside `'…'` as an escape character, which the SQL standard does
/// not. So a value ending in `\` escapes the closing quote and the statement
/// keeps consuming — the exact breakout [`sql_squote_escape`] prevents for
/// quotes but cannot prevent here (#233):
///
/// | value | standard escape | how `MySQL` reads it |
/// | --- | --- | --- |
/// | `a\` | `'a\'` | unterminated string |
///
/// Doubling the backslash as well fixes `MySQL` and *silently corrupts the
/// value* under the standard, where `'a\\'` is two characters. There is no
/// spelling correct in both, which is why the dialect is chosen by the
/// annotation on the quote rather than guessed.
///
/// Those two are the whole rule: `MySQL`'s other escape sequences (`\n`, `\0`,
/// `\Z`, `\%`, …) all begin with a backslash, so escaping every backslash
/// leaves nothing else that can be read as anything but itself.
pub(crate) fn mysql_squote_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('\'', "''")
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::term::STerm;

    #[test]
    fn wgsl_ints() {
        assert_eq!(3u32.qlift_to::<Wgsl>().coparse(), "3u");
        assert_eq!(7usize.qlift_to::<Wgsl>().coparse(), "7u");
        assert_eq!((-2i32).qlift_to::<Wgsl>().coparse(), "-2i");
    }

    #[test]
    fn wgsl_float_bool() {
        assert_eq!(1.5f32.qlift_to::<Wgsl>().coparse(), "1.5f");
        assert_eq!(true.qlift_to::<Wgsl>().coparse(), "true");
    }

    #[test]
    fn wgsl_tags() {
        let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Wgsl>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "int_literal");
    }

    #[test]
    fn sql_scalars() {
        assert_eq!(42u64.qlift_to::<Sql>().coparse(), "42");
        assert_eq!((-7i32).qlift_to::<Sql>().coparse(), "-7");
        assert_eq!(1.0f64.qlift_to::<Sql>().coparse(), "1.0");
        assert_eq!(2.5f32.qlift_to::<Sql>().coparse(), "2.5");
        assert_eq!((-1.5f32).qlift_to::<Sql>().coparse(), "-1.5");
        assert_eq!(true.qlift_to::<Sql>().coparse(), "TRUE");
        assert_eq!(false.qlift_to::<Sql>().coparse(), "FALSE");
    }

    /// The sign is a child token in this grammar, not part of the number, so a
    /// negative lift is a tuple and a positive one is a leaf. Text alone would
    /// not catch a lift that got that backwards; `smatch` / `rewrite` would.
    #[test]
    fn sql_negative_numbers_are_signed_tuples() {
        let QTerm::Tuple { tag, terms, .. } = &*(-7i32).qlift_to::<Sql>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "literal");
        assert_eq!(terms.len(), 1, "the `-` is the literal's only child");
        assert_eq!(terms[0].coparse(), "-");

        let QTerm::Tuple { terms, .. } = &*7i32.qlift_to::<Sql>() else {
            panic!("expected tuple");
        };
        assert!(terms.is_empty(), "a positive literal is a leaf");
    }

    /// The whole point of the SQL target (#219): a value carrying the delimiter
    /// comes back as one literal with the quote doubled, never as syntax.
    #[test]
    fn sql_strings_cannot_break_out() {
        assert_eq!("hi".qlift_to::<Sql>().coparse(), "'hi'");
        assert_eq!(String::new().qlift_to::<Sql>().coparse(), "''");
        assert_eq!("O'Hara".qlift_to::<Sql>().coparse(), "'O''Hara'");
        assert_eq!(
            "x'; DROP TABLE t; --".qlift_to::<Sql>().coparse(),
            "'x''; DROP TABLE t; --'"
        );
        // Backslash is an ordinary character in a standard SQL literal, so it
        // passes through: doubling it would change the value. `mysql↖ … ↗` is
        // the annotation for the dialect where that is not enough (#233).
        //
        // (These two assertions carried a literal backspace byte instead of a
        // backslash until now — a shell-quoting slip in #236 that left the test
        // agreeing with itself about nothing.)
        assert_eq!(r"a\b".qlift_to::<Sql>().coparse(), r"'a\b'");
        assert_eq!(r"a\".qlift_to::<Sql>().coparse(), r"'a\'");
    }

    /// The `MySQL` dialect differs from the standard in exactly one place, and
    /// this is it: a backslash is doubled, because `MySQL` reads it as an escape
    /// inside `'…'` and the standard does not (#233).
    #[test]
    fn mysql_doubles_the_backslash_and_the_standard_does_not() {
        // Everything the standard does, MySQL does too.
        assert_eq!("hi".qlift_to::<MySql>().coparse(), "'hi'");
        assert_eq!(String::new().qlift_to::<MySql>().coparse(), "''");
        assert_eq!("O'Hara".qlift_to::<MySql>().coparse(), "'O''Hara'");

        // …and one thing more.
        assert_eq!(r"a\b".qlift_to::<MySql>().coparse(), r"'a\\b'");
        assert_eq!(r"a\".qlift_to::<MySql>().coparse(), r"'a\\'");

        // The two dialects disagree only where a backslash appears; anything
        // without one lifts identically, which is what makes `sql` a safe
        // default for the values most programs actually carry.
        for v in ["hi", "O'Hara", "x'; DROP TABLE t; --", "", "a, b"] {
            assert_eq!(
                v.qlift_to::<Sql>().coparse(),
                v.qlift_to::<MySql>().coparse(),
                "dialects should agree on a backslash-free value: {v:?}"
            );
        }
    }

    /// Numbers, booleans and lists are dialect-independent: `MySQL` reuses the
    /// standard's shape constructors, so the two markers cannot drift apart on
    /// anything but the string escape.
    #[test]
    fn mysql_shares_every_non_string_shape() {
        assert_eq!(
            42u64.qlift_to::<MySql>().coparse(),
            42u64.qlift_to::<Sql>().coparse()
        );
        assert_eq!(
            (-7i32).qlift_to::<MySql>().coparse(),
            (-7i32).qlift_to::<Sql>().coparse()
        );
        assert_eq!(
            (-1.5f32).qlift_to::<MySql>().coparse(),
            (-1.5f32).qlift_to::<Sql>().coparse()
        );
        assert_eq!(
            true.qlift_to::<MySql>().coparse(),
            true.qlift_to::<Sql>().coparse()
        );
        assert_eq!(
            vec![1u32, 2].qlift_to::<MySql>().coparse(),
            vec![1u32, 2].qlift_to::<Sql>().coparse()
        );
    }

    #[test]
    fn sql_lists_are_paren_lists() {
        // The shape an `IN (…)` right-hand side takes.
        assert_eq!(vec![1u32, 2, 3].qlift_to::<Sql>().coparse(), "(1, 2, 3)");
        // `Vec<String>`, not `Vec<&str>`: the element bound is `LiftTo<Sql>`,
        // which `str` satisfies and `&str` does not.
        let names = vec![String::from("a"), String::from("b'c")];
        assert_eq!(names.qlift_to::<Sql>().coparse(), "('a', 'b''c')");
    }

    #[test]
    fn python_scalars() {
        assert_eq!(42u64.qlift_to::<Python>().coparse(), "42");
        assert_eq!((-7i32).qlift_to::<Python>().coparse(), "-7");
        assert_eq!(1.0f64.qlift_to::<Python>().coparse(), "1.0");
        assert_eq!(2.5f32.qlift_to::<Python>().coparse(), "2.5");
        assert_eq!(true.qlift_to::<Python>().coparse(), "True");
        assert_eq!(false.qlift_to::<Python>().coparse(), "False");
    }

    #[test]
    fn python_strings() {
        // Characters Python interprets inside "…" are backslash-escaped.
        let owned = String::from("hi there");
        assert_eq!(owned.qlift_to::<Python>().coparse(), "\"hi there\"");
        assert_eq!(
            "say \"hi\\\"\nbye".qlift_to::<Python>().coparse(),
            "\"say \\\"hi\\\\\\\"\\nbye\""
        );
        assert_eq!("".qlift_to::<Python>().coparse(), "\"\"");
    }

    /// A lifted Python string is the term the Python parser produces for the same
    /// text — not merely something that coparses to it.
    ///
    /// The lift used to be a single flat `leaf("string", "\"…\"")`, a shape
    /// tree-sitter-python never emits, which the text-level assertions above
    /// could not see. Structure matters because `smatch`/`rewrite` compare it.
    ///
    /// Only escape-free strings are checked: with escapes the parser nests
    /// `escape_sequence` children inside `string_content`, which neither this
    /// lift nor `quilt-python`'s `qlift` reproduces (issue #174, finding A2).
    #[cfg(feature = "parse")]
    #[test]
    fn python_string_lift_matches_the_parser() -> crate::prelude::Result<()> {
        use crate::lang::{flat_nodes, Language};
        use crate::langs::python::lang::PythonLanguage;

        let mut py = PythonLanguage::default();
        for s in ["", "hi there", "/usr/bin", "no escapes at all"] {
            let lifted = s.qlift_to::<Python>();
            let text = lifted.coparse();
            let parsed = py.parse_as(None, &flat_nodes(&text))?;
            assert_eq!(
                &*parsed,
                &*lifted,
                "lift of {s:?} is {:?} but the parser reads {text} as {:?}",
                lifted.sexp(),
                parsed.sexp()
            );
        }
        Ok(())
    }

    #[test]
    fn python_lists() {
        let squares: Vec<u64> = (1..=5).map(|n| n * n).collect();
        assert_eq!(squares.qlift_to::<Python>().coparse(), "[1, 4, 9, 16, 25]");
        let nested = vec![vec![1u8], vec![2, 3]];
        assert_eq!(nested.qlift_to::<Python>().coparse(), "[[1], [2, 3]]");
        let empty: Vec<u8> = Vec::new();
        assert_eq!(empty.qlift_to::<Python>().coparse(), "[]");
    }

    #[test]
    fn python_tags() {
        let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Python>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "integer");
        let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Python>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "list");
    }

    #[test]
    fn zsh_strings() {
        // String, &str (via deref to `str`), and a literal all lift to a
        // double-quoted zsh string.
        let owned = String::from("hi there");
        let borrowed: &str = "/var/log";
        assert_eq!(owned.qlift_to::<Zsh>().coparse(), "\"hi there\"");
        assert_eq!(borrowed.qlift_to::<Zsh>().coparse(), "\"/var/log\"");
        assert_eq!("plain".qlift_to::<Zsh>().coparse(), "\"plain\"");
    }

    #[test]
    fn zsh_escaping() {
        // Characters zsh interprets inside "…" are backslash-escaped.
        assert_eq!(
            "say \"$x\" `now`".qlift_to::<Zsh>().coparse(),
            "\"say \\\"\\$x\\\" \\`now\\`\""
        );
    }

    #[test]
    fn zsh_ints() {
        assert_eq!(42u32.qlift_to::<Zsh>().coparse(), "42");
        assert_eq!((-7i32).qlift_to::<Zsh>().coparse(), "-7");
    }

    #[test]
    fn bash_lifts() {
        // Bash shares the shell lift behaviour with zsh.
        let p: &str = "/var/log";
        assert_eq!(p.qlift_to::<Bash>().coparse(), "\"/var/log\"");
        assert_eq!(
            "echo `id`".qlift_to::<Bash>().coparse(),
            "\"echo \\`id\\`\""
        );
        assert_eq!(42u32.qlift_to::<Bash>().coparse(), "42");
    }

    #[test]
    fn nix_scalars() {
        assert_eq!(42u64.qlift_to::<Nix>().coparse(), "42");
        assert_eq!((-7i32).qlift_to::<Nix>().coparse(), "-7");
        assert_eq!(1.0f64.qlift_to::<Nix>().coparse(), "1.0");
        assert_eq!(2.5f32.qlift_to::<Nix>().coparse(), "2.5");
        assert_eq!(true.qlift_to::<Nix>().coparse(), "true");
        assert_eq!(false.qlift_to::<Nix>().coparse(), "false");
    }

    #[test]
    fn nix_strings() {
        let owned = String::from("/etc/nixos");
        assert_eq!(owned.qlift_to::<Nix>().coparse(), "\"/etc/nixos\"");
        // `"`, `\` are escaped, and the antiquotation opener `${` becomes `\${`.
        assert_eq!(
            "say \"hi\" ${x}".qlift_to::<Nix>().coparse(),
            "\"say \\\"hi\\\" \\${x}\""
        );
    }

    #[test]
    fn nix_lists() {
        let squares: Vec<u64> = (1..=3).map(|n| n * n).collect();
        // Nix lists are space-separated, not comma-separated.
        assert_eq!(squares.qlift_to::<Nix>().coparse(), "[ 1 4 9 ]");
        let empty: Vec<u8> = Vec::new();
        assert_eq!(empty.qlift_to::<Nix>().coparse(), "[ ]");
    }

    #[test]
    fn lean_ints() {
        assert_eq!(3u32.qlift_to::<Lean>().coparse(), "3");
        assert_eq!(7usize.qlift_to::<Lean>().coparse(), "7");
        // `num_lit` is unsigned, so a negative lifts as a `unary_op`.
        assert_eq!((-2i32).qlift_to::<Lean>().coparse(), "-2");
        assert_eq!(i32::MIN.qlift_to::<Lean>().coparse(), "-2147483648");
    }

    #[test]
    fn lean_floats_and_bools() {
        assert_eq!(1.5f64.qlift_to::<Lean>().coparse(), "1.5");
        // Keeps the decimal point so it stays a float, not a `Nat`.
        assert_eq!(2.0f32.qlift_to::<Lean>().coparse(), "2.0");
        assert_eq!((-0.5f64).qlift_to::<Lean>().coparse(), "-0.5");
        assert_eq!(true.qlift_to::<Lean>().coparse(), "true");
        assert_eq!(false.qlift_to::<Lean>().coparse(), "false");
    }

    #[test]
    fn lean_strings() {
        let owned = String::from("Nat.succ");
        assert_eq!(owned.qlift_to::<Lean>().coparse(), "\"Nat.succ\"");
        assert_eq!(
            "say \"hi\"\n".qlift_to::<Lean>().coparse(),
            r#""say \"hi\"\n""#
        );
        // A brace is *not* escaped: a lifted literal is a plain string, not an
        // interpolated `s!"…"`.
        assert_eq!("{x}".qlift_to::<Lean>().coparse(), "\"{x}\"");
    }

    #[test]
    fn lean_lists() {
        let squares: Vec<u64> = (1..=3).map(|n| n * n).collect();
        assert_eq!(squares.qlift_to::<Lean>().coparse(), "[1, 4, 9]");
        let empty: Vec<u8> = Vec::new();
        assert_eq!(empty.qlift_to::<Lean>().coparse(), "[]");
    }

    #[test]
    fn lean_tags() {
        let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Lean>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "num_lit");
        let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Lean>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "list_lit");
    }

    /// The whole escape table, one character at a time. The runtime corpus
    /// reaches `escape_html` only through `qlift_html`, and only with a string
    /// containing `& < > "` — so `'` was the one entry in the table with no
    /// coverage anywhere, in either binding (issue #192).
    #[test]
    fn html_escape_table() {
        assert_eq!(escape_html("&"), "&amp;");
        assert_eq!(escape_html("<"), "&lt;");
        assert_eq!(escape_html(">"), "&gt;");
        assert_eq!(escape_html("\""), "&quot;");
        assert_eq!(escape_html("'"), "&#x27;");
    }

    /// A single-quoted attribute value is why `'` is in the table: without it,
    /// `<a title='…'>` breaks out of the attribute the same way `"` does.
    #[test]
    fn html_escape_closes_both_attribute_quotings() {
        assert_eq!(
            escape_html("\" onclick='x'"),
            "&quot; onclick=&#x27;x&#x27;"
        );
        assert_eq!(
            escape_html("<script>alert(1)</script>"),
            "&lt;script&gt;alert(1)&lt;/script&gt;"
        );
    }

    /// `&` is escaped first in the sense that matters: the replacements
    /// themselves introduce `&`, and a rule that rescanned its own output would
    /// turn `<` into `&amp;lt;`. One pass over the *input* is the fix, so this
    /// pins that a mixed string escapes each character exactly once.
    #[test]
    fn html_escape_does_not_rescan_its_own_output() {
        assert_eq!(escape_html("a & b < c"), "a &amp; b &lt; c");
        // Not idempotent, by design: the input is a value, not markup.
        assert_eq!(escape_html("&amp;"), "&amp;amp;");
    }

    /// Everything outside the table is passed through byte-for-byte — the
    /// runtime must not apply Quilt's own glyph escaping to target text.
    #[test]
    fn html_escape_leaves_everything_else_alone() {
        assert_eq!(escape_html(""), "");
        assert_eq!(escape_html("plain text"), "plain text");
        assert_eq!(escape_html("héllo ← ↖ 世界"), "héllo ← ↖ 世界");
        assert_eq!(escape_html("a\nb\t\\c"), "a\nb\t\\c");
    }

    /// The rule *set*, not just the rules that happen to have a line above: a
    /// sixth escape added without a test shows up right here. Came from the
    /// per-binding copies this function replaced, and is the reason the table
    /// is worth having in one place — it can only be stated once.
    #[test]
    fn html_escape_table_is_exactly_five_characters() {
        let changed: String = (0u8..=127)
            .map(char::from)
            .filter(|c| {
                let s = c.to_string();
                escape_html(&s) != s
            })
            .collect();
        assert_eq!(changed, "\"&'<>");
    }

    #[test]
    fn nix_tags() {
        let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Nix>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "integer_expression");
        let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Nix>() else {
            panic!("expected tuple");
        };
        assert_eq!(&**tag, "list_expression");
    }
}