quilt/lift/mod.rs
1//! Heterogeneous lifting: turn host-language (Rust) values into `QTerm`s of a
2//! *target* object language, selected by a zero-sized marker type.
3//!
4//! The homogeneous `↑` (Rust lifting into Rust) is `QLift`/`qlift()` in
5//! `langs::rust::ops`; this module generalizes it to `LiftTo<L>`, indexed by
6//! the target language. Inside `wgsl↖ … ↙x.↑↘ … ↗` the `↑` expands to
7//! `qlift_to::<Wgsl>()` (see `langs::rust::ops::lift_spelling`), so a Rust
8//! `3u32` lifts to the WGSL term `3u` instead of the Rust term `3`.
9//!
10//! The impls themselves live in [`gen`], generated by `bin/gen-lifts` from
11//! sample literals parsed by the vendored grammars — so a lift's tags, child
12//! structure and layout are the parser's rather than a transcription of it
13//! (issue #203). What stays here by hand is what is not a shape: the markers,
14//! the trait, and the per-target escaping rules the generated shapes call.
15//!
16//! This module is deliberately *not* gated behind the per-language parser
17//! features: lift impls are runtime code for expanded programs, which may not
18//! enable the target language's parser (e.g. `nanobots-web` builds quilt with
19//! only the `rust` feature but splices WGSL terms). The markers index lifting;
20//! they don't need the parser.
21
22use crate::qterm::QTerm;
23use std::sync::Arc;
24
25mod gen;
26pub use gen::*;
27
28mod text;
29pub use text::{
30 json_escape, json_float, json_string, InQuotes, Json, Raw, Text, TextDialect, TextValue,
31 TEXT_IN_QUOTES,
32};
33
34/**************************************************************/
35
36/// Marker: the Rust object language (the homogeneous case; see `QLift`).
37pub struct Rust;
38
39/// Marker: the Python object language.
40pub struct Python;
41
42/// Marker: the WGSL object language.
43pub struct Wgsl;
44
45/// Marker: the Zsh object language.
46pub struct Zsh;
47
48/// Marker: the Bash object language.
49pub struct Bash;
50
51/// Marker: the Nix object language.
52pub struct Nix;
53
54/// Marker: the Lean 4 object language.
55pub struct Lean;
56
57/// Marker: the TypeScript object language.
58pub struct TypeScript;
59
60/// Marker: the HTML object language. A value lifts to an entity-escaped `text`
61/// node — the same rule as the Python and TypeScript runtimes' `qlift_html`,
62/// which call [`escape_html`] too.
63pub struct Html;
64
65/// Marker: the SQL object language, standard dialect.
66///
67/// Escaping follows the SQL standard, which is also what `PostgreSQL` (with
68/// `standard_conforming_strings = on`, the default since 9.1), `SQLite` and SQL
69/// Server read. See [`MySql`] for the one widespread dialect that differs.
70pub struct Sql;
71
72/// Marker: the SQL object language, `MySQL`/`MariaDB` dialect.
73///
74/// Reached by annotating the quote `mysql↖ … ↗` (or `mariadb↖ … ↗`) instead of
75/// `sql↖ … ↗` — both are registered names for the same grammar, so the *parse*
76/// is identical and only the escaping differs. See [`mysql_squote_escape`] for
77/// why that is not a detail (#233).
78pub struct MySql;
79
80/**************************************************************/
81
82/// Lift a value to a `QTerm` of the object language `L` (the `↑` operator).
83///
84/// Implement this per (Rust type, target language) pair; the impl owns the
85/// target language's spelling and tags (e.g. WGSL `u32` literals are
86/// `int_literal`s spelled `3u`).
87pub trait LiftTo<L> {
88 fn lift_to(&self) -> Arc<QTerm>;
89}
90
91/// Postfix sugar for [`LiftTo`]: `x.qlift_to::<Wgsl>()`. Blanket-implemented,
92/// so it is always in scope via the prelude; the bound is only required at the
93/// call site.
94pub trait QLiftTo {
95 fn qlift_to<L>(&self) -> Arc<QTerm>
96 where
97 Self: LiftTo<L>,
98 {
99 LiftTo::<L>::lift_to(self)
100 }
101}
102
103impl<T: ?Sized> QLiftTo for T {}
104
105/**************************************************************/
106// Escaping rules. A generated shape in `gen` holds the literal's *structure*
107// and calls one of these for its content, so each is the single place its
108// target's quoting is decided. Several are shared further — with a host
109// (`langs::shell::ops`) or a binding (`quilt-python`) — which is the point:
110// two implementations of one escaping rule is how #150, #176 and #192 each
111// started.
112
113/// Escape a string for inclusion in a Python double-quoted literal.
114///
115/// Public because the `quilt-python` runtime's own `qlift` needs exactly this
116/// rule: there were two implementations of "lift a string into Python" — this
117/// one, and the binding's, which did no escaping at all, so `qlift('a"b')`
118/// produced an unparseable literal and `qlift('a\\b')` silently changed the
119/// value (`\\b` is a backspace escape in Python). Sharing the function is what
120/// keeps them from drifting apart again. Found by the shared runtime corpus
121/// (#159), which runs the same cases against all three published runtimes.
122pub fn py_dquote_escape(s: &str) -> String {
123 use std::fmt::Write as _;
124 let mut out = String::with_capacity(s.len());
125 for c in s.chars() {
126 match c {
127 '"' | '\\' => {
128 out.push('\\');
129 out.push(c);
130 }
131 '\n' => out.push_str("\\n"),
132 '\r' => out.push_str("\\r"),
133 '\t' => out.push_str("\\t"),
134 c if c.is_control() => write!(out, "\\x{:02x}", c as u32).unwrap(),
135 c => out.push(c),
136 }
137 }
138 out
139}
140
141/**************************************************************/
142// TypeScript. A string lifts to a double-quoted `string`, escaped as the
143// TypeScript meta escapes the strings in generated code.
144
145/// Escape a string for inclusion in a TypeScript/JavaScript double-quoted
146/// literal: `"` and `\` backslash-escaped, `\n` `\r` `\t` spelled short, every
147/// other control character as `\uXXXX`.
148///
149/// Public for the same reason as [`py_dquote_escape`]: `quilt-python`'s
150/// `qlift_ts` builds the same literal, and `langs::typescript::ops` writes
151/// generated code's strings with it. `quilt-wasm`'s JavaScript runtime keeps a
152/// copy (`tsStringLit`), which the shared runtime corpus holds to this one.
153#[must_use]
154pub fn ts_dquote_escape(s: &str) -> String {
155 use std::fmt::Write as _;
156 let mut out = String::with_capacity(s.len());
157 for c in s.chars() {
158 match c {
159 '"' | '\\' => {
160 out.push('\\');
161 out.push(c);
162 }
163 '\n' => out.push_str("\\n"),
164 '\r' => out.push_str("\\r"),
165 '\t' => out.push_str("\\t"),
166 c if c.is_control() => write!(out, "\\u{:04x}", c as u32).unwrap(),
167 c => out.push(c),
168 }
169 }
170 out
171}
172
173/**************************************************************/
174// HTML. `LiftTo<Html>` (generated, in `gen`) and both runtimes' `qlift_html`
175// call this, so a value is escaped the same way whichever host lifts it.
176
177/// Escape `& < > " '` so `s` is inert HTML wherever a hole can sit: as text
178/// content, and inside a single- or double-quoted attribute value.
179///
180/// Public for the same reason as [`py_dquote_escape`]: the `quilt-python` and
181/// `quilt-wasm` runtimes each need exactly this rule for their `qlift_html`,
182/// and each had grown its own byte-identical copy. Three copies of an escaping
183/// table is three chances to fix a hole in one of them — the class of bug the
184/// conformance epic (#144) exists to close — so the rule lives here and the
185/// bindings call it. Tested directly here; issue #192 is where the two copies
186/// having no direct test at all was written up.
187///
188/// Not idempotent, and deliberately so: escaping `&` yields `&amp;`,
189/// because the input is a *value*, not markup. A caller lifting an
190/// already-escaped fragment wants the term pass-through both `qlift_html`
191/// implementations do, not a second trip through this function.
192#[must_use]
193pub fn escape_html(s: &str) -> String {
194 let mut out = String::with_capacity(s.len());
195 for c in s.chars() {
196 match c {
197 '&' => out.push_str("&"),
198 '<' => out.push_str("<"),
199 '>' => out.push_str(">"),
200 '"' => out.push_str("""),
201 '\'' => out.push_str("'"),
202 _ => out.push(c),
203 }
204 }
205 out
206}
207
208/**************************************************************/
209// Shells (Zsh, Bash). A Rust string lifts to a double-quoted `string` literal
210// so the value is treated as inert data: characters the shell would interpret
211// inside `"…"` (`"`, `\`, `$`, `` ` ``) are backslash-escaped. The two shells
212// share a grammar lineage, so one escaping rule serves both — their *shapes*
213// are still derived separately, since #150 is what assuming otherwise costs.
214
215/// Escape a string for inclusion in a POSIX shell double-quoted literal.
216///
217/// Shared with the shell *hosts* (`langs::shell::ops`, #151), which reconstruct
218/// a quoted fragment as one of these literals: a lifted value and the literal
219/// text around it land in the same generated word, so escaping them two
220/// different ways is the drift issue #150 is about. It lives here rather than
221/// beside the host because `lift.rs` is compiled unconditionally, while
222/// `langs::shell` needs the `bash` or `zsh` feature.
223pub(crate) fn sh_dquote_escape(s: &str) -> String {
224 let mut out = String::with_capacity(s.len());
225 for c in s.chars() {
226 if matches!(c, '"' | '\\' | '$' | '`') {
227 out.push('\\');
228 }
229 out.push(c);
230 }
231 out
232}
233
234/**************************************************************/
235// Nix. Nix is a pure expression language, so every value lifts to its literal
236// expression; a string lifts to a double-quoted `string_expression`.
237
238/// Escape a string for inclusion in a Nix double-quoted literal. Besides `"`
239/// and `\`, the antiquotation opener `${` is escaped (to `\${`) so the value
240/// stays inert data rather than triggering interpolation.
241fn nix_dquote_escape(s: &str) -> String {
242 let mut out = String::with_capacity(s.len());
243 let mut chars = s.chars().peekable();
244 while let Some(c) = chars.next() {
245 match c {
246 '"' | '\\' => {
247 out.push('\\');
248 out.push(c);
249 }
250 '\n' => out.push_str("\\n"),
251 '\r' => out.push_str("\\r"),
252 '\t' => out.push_str("\\t"),
253 '$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
254 c => out.push(c),
255 }
256 }
257 out
258}
259
260/**************************************************************/
261// Lean. A string lifts to a `str_lit`, whose body is raw text between two quote
262// tokens rather than a node of its own.
263
264/// Escape a string for inclusion in a Lean double-quoted literal. Lean's string
265/// escapes are the familiar C-like set; note `{` is *not* escaped here — that is
266/// only special inside an interpolated `s!"…"`, which a lifted literal is not.
267fn lean_dquote_escape(s: &str) -> String {
268 use std::fmt::Write as _;
269 let mut out = String::with_capacity(s.len());
270 for c in s.chars() {
271 match c {
272 '"' | '\\' => {
273 out.push('\\');
274 out.push(c);
275 }
276 '\n' => out.push_str("\\n"),
277 '\r' => out.push_str("\\r"),
278 '\t' => out.push_str("\\t"),
279 c if c.is_control() => write!(out, "\\u{:04x}", c as u32).unwrap(),
280 c => out.push(c),
281 }
282 }
283 out
284}
285
286/**************************************************************/
287// SQL. This is the module's security-relevant corner (#219): a value spliced
288// into a quoted query with `↑` becomes a *literal node*, so it is data the
289// parser has already accepted as a single token rather than text pasted into a
290// statement. Every scalar lifts to a `literal`, the one tag this grammar gives
291// every constant. Which is why the escaping rule below is the part that has to
292// be right by hand — the shapes around it are derived (see `gen`).
293
294/// Escape a string for inclusion in a SQL single-quoted literal.
295///
296/// Standard SQL has exactly **one** escape inside `'…'`: a single quote is
297/// written twice. Backslash is an ordinary character — this grammar's
298/// `_single_quote_string` rule (`/([uU]&|[nN])?'([^']|'')*'/`) says the same —
299/// so it is passed through unchanged. Escaping it would be a silent corruption
300/// of the value under the standard, not extra safety.
301///
302/// That makes the result safe against quote-breakout for standard SQL and for
303/// `PostgreSQL` with `standard_conforming_strings = on` (the default since 9.1),
304/// as well as `SQLite` and SQL Server. It is **not** safe for `MySQL` in its
305/// default mode — write `mysql↖ … ↗` and get [`mysql_squote_escape`] instead.
306pub(crate) fn sql_squote_escape(s: &str) -> String {
307 s.replace('\'', "''")
308}
309
310/// Escape a string for inclusion in a `MySQL`/`MariaDB` single-quoted literal.
311///
312/// `MySQL` in its **default** `sql_mode` (`NO_BACKSLASH_ESCAPES` *off*) reads a
313/// backslash inside `'…'` as an escape character, which the SQL standard does
314/// not. So a value ending in `\` escapes the closing quote and the statement
315/// keeps consuming — the exact breakout [`sql_squote_escape`] prevents for
316/// quotes but cannot prevent here (#233):
317///
318/// | value | standard escape | how `MySQL` reads it |
319/// | --- | --- | --- |
320/// | `a\` | `'a\'` | unterminated string |
321///
322/// Doubling the backslash as well fixes `MySQL` and *silently corrupts the
323/// value* under the standard, where `'a\\'` is two characters. There is no
324/// spelling correct in both, which is why the dialect is chosen by the
325/// annotation on the quote rather than guessed.
326///
327/// Those two are the whole rule: `MySQL`'s other escape sequences (`\n`, `\0`,
328/// `\Z`, `\%`, …) all begin with a backslash, so escaping every backslash
329/// leaves nothing else that can be read as anything but itself.
330pub(crate) fn mysql_squote_escape(s: &str) -> String {
331 s.replace('\\', "\\\\").replace('\'', "''")
332}
333
334/**************************************************************/
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use crate::term::STerm;
340
341 #[test]
342 fn wgsl_ints() {
343 assert_eq!(3u32.qlift_to::<Wgsl>().coparse(), "3u");
344 assert_eq!(7usize.qlift_to::<Wgsl>().coparse(), "7u");
345 assert_eq!((-2i32).qlift_to::<Wgsl>().coparse(), "-2i");
346 }
347
348 #[test]
349 fn wgsl_float_bool() {
350 assert_eq!(1.5f32.qlift_to::<Wgsl>().coparse(), "1.5f");
351 assert_eq!(true.qlift_to::<Wgsl>().coparse(), "true");
352 }
353
354 #[test]
355 fn wgsl_tags() {
356 let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Wgsl>() else {
357 panic!("expected tuple");
358 };
359 assert_eq!(&**tag, "int_literal");
360 }
361
362 #[test]
363 fn sql_scalars() {
364 assert_eq!(42u64.qlift_to::<Sql>().coparse(), "42");
365 assert_eq!((-7i32).qlift_to::<Sql>().coparse(), "-7");
366 assert_eq!(1.0f64.qlift_to::<Sql>().coparse(), "1.0");
367 assert_eq!(2.5f32.qlift_to::<Sql>().coparse(), "2.5");
368 assert_eq!((-1.5f32).qlift_to::<Sql>().coparse(), "-1.5");
369 assert_eq!(true.qlift_to::<Sql>().coparse(), "TRUE");
370 assert_eq!(false.qlift_to::<Sql>().coparse(), "FALSE");
371 }
372
373 /// The sign is a child token in this grammar, not part of the number, so a
374 /// negative lift is a tuple and a positive one is a leaf. Text alone would
375 /// not catch a lift that got that backwards; `smatch` / `rewrite` would.
376 #[test]
377 fn sql_negative_numbers_are_signed_tuples() {
378 let QTerm::Tuple { tag, terms, .. } = &*(-7i32).qlift_to::<Sql>() else {
379 panic!("expected tuple");
380 };
381 assert_eq!(&**tag, "literal");
382 assert_eq!(terms.len(), 1, "the `-` is the literal's only child");
383 assert_eq!(terms[0].coparse(), "-");
384
385 let QTerm::Tuple { terms, .. } = &*7i32.qlift_to::<Sql>() else {
386 panic!("expected tuple");
387 };
388 assert!(terms.is_empty(), "a positive literal is a leaf");
389 }
390
391 /// The whole point of the SQL target (#219): a value carrying the delimiter
392 /// comes back as one literal with the quote doubled, never as syntax.
393 #[test]
394 fn sql_strings_cannot_break_out() {
395 assert_eq!("hi".qlift_to::<Sql>().coparse(), "'hi'");
396 assert_eq!(String::new().qlift_to::<Sql>().coparse(), "''");
397 assert_eq!("O'Hara".qlift_to::<Sql>().coparse(), "'O''Hara'");
398 assert_eq!(
399 "x'; DROP TABLE t; --".qlift_to::<Sql>().coparse(),
400 "'x''; DROP TABLE t; --'"
401 );
402 // Backslash is an ordinary character in a standard SQL literal, so it
403 // passes through: doubling it would change the value. `mysql↖ … ↗` is
404 // the annotation for the dialect where that is not enough (#233).
405 //
406 // (These two assertions carried a literal backspace byte instead of a
407 // backslash until now — a shell-quoting slip in #236 that left the test
408 // agreeing with itself about nothing.)
409 assert_eq!(r"a\b".qlift_to::<Sql>().coparse(), r"'a\b'");
410 assert_eq!(r"a\".qlift_to::<Sql>().coparse(), r"'a\'");
411 }
412
413 /// The `MySQL` dialect differs from the standard in exactly one place, and
414 /// this is it: a backslash is doubled, because `MySQL` reads it as an escape
415 /// inside `'…'` and the standard does not (#233).
416 #[test]
417 fn mysql_doubles_the_backslash_and_the_standard_does_not() {
418 // Everything the standard does, MySQL does too.
419 assert_eq!("hi".qlift_to::<MySql>().coparse(), "'hi'");
420 assert_eq!(String::new().qlift_to::<MySql>().coparse(), "''");
421 assert_eq!("O'Hara".qlift_to::<MySql>().coparse(), "'O''Hara'");
422
423 // …and one thing more.
424 assert_eq!(r"a\b".qlift_to::<MySql>().coparse(), r"'a\\b'");
425 assert_eq!(r"a\".qlift_to::<MySql>().coparse(), r"'a\\'");
426
427 // The two dialects disagree only where a backslash appears; anything
428 // without one lifts identically, which is what makes `sql` a safe
429 // default for the values most programs actually carry.
430 for v in ["hi", "O'Hara", "x'; DROP TABLE t; --", "", "a, b"] {
431 assert_eq!(
432 v.qlift_to::<Sql>().coparse(),
433 v.qlift_to::<MySql>().coparse(),
434 "dialects should agree on a backslash-free value: {v:?}"
435 );
436 }
437 }
438
439 /// Numbers, booleans and lists are dialect-independent: `MySQL` reuses the
440 /// standard's shape constructors, so the two markers cannot drift apart on
441 /// anything but the string escape.
442 #[test]
443 fn mysql_shares_every_non_string_shape() {
444 assert_eq!(
445 42u64.qlift_to::<MySql>().coparse(),
446 42u64.qlift_to::<Sql>().coparse()
447 );
448 assert_eq!(
449 (-7i32).qlift_to::<MySql>().coparse(),
450 (-7i32).qlift_to::<Sql>().coparse()
451 );
452 assert_eq!(
453 (-1.5f32).qlift_to::<MySql>().coparse(),
454 (-1.5f32).qlift_to::<Sql>().coparse()
455 );
456 assert_eq!(
457 true.qlift_to::<MySql>().coparse(),
458 true.qlift_to::<Sql>().coparse()
459 );
460 assert_eq!(
461 vec![1u32, 2].qlift_to::<MySql>().coparse(),
462 vec![1u32, 2].qlift_to::<Sql>().coparse()
463 );
464 }
465
466 #[test]
467 fn sql_lists_are_paren_lists() {
468 // The shape an `IN (…)` right-hand side takes.
469 assert_eq!(vec![1u32, 2, 3].qlift_to::<Sql>().coparse(), "(1, 2, 3)");
470 // `Vec<String>`, not `Vec<&str>`: the element bound is `LiftTo<Sql>`,
471 // which `str` satisfies and `&str` does not.
472 let names = vec![String::from("a"), String::from("b'c")];
473 assert_eq!(names.qlift_to::<Sql>().coparse(), "('a', 'b''c')");
474 }
475
476 #[test]
477 fn python_scalars() {
478 assert_eq!(42u64.qlift_to::<Python>().coparse(), "42");
479 assert_eq!((-7i32).qlift_to::<Python>().coparse(), "-7");
480 assert_eq!(1.0f64.qlift_to::<Python>().coparse(), "1.0");
481 assert_eq!(2.5f32.qlift_to::<Python>().coparse(), "2.5");
482 assert_eq!(true.qlift_to::<Python>().coparse(), "True");
483 assert_eq!(false.qlift_to::<Python>().coparse(), "False");
484 }
485
486 #[test]
487 fn python_strings() {
488 // Characters Python interprets inside "…" are backslash-escaped.
489 let owned = String::from("hi there");
490 assert_eq!(owned.qlift_to::<Python>().coparse(), "\"hi there\"");
491 assert_eq!(
492 "say \"hi\\\"\nbye".qlift_to::<Python>().coparse(),
493 "\"say \\\"hi\\\\\\\"\\nbye\""
494 );
495 assert_eq!("".qlift_to::<Python>().coparse(), "\"\"");
496 }
497
498 /// A lifted Python string is the term the Python parser produces for the same
499 /// text — not merely something that coparses to it.
500 ///
501 /// The lift used to be a single flat `leaf("string", "\"…\"")`, a shape
502 /// tree-sitter-python never emits, which the text-level assertions above
503 /// could not see. Structure matters because `smatch`/`rewrite` compare it.
504 ///
505 /// Only escape-free strings are checked: with escapes the parser nests
506 /// `escape_sequence` children inside `string_content`, which neither this
507 /// lift nor `quilt-python`'s `qlift` reproduces (issue #174, finding A2).
508 #[cfg(feature = "parse")]
509 #[test]
510 fn python_string_lift_matches_the_parser() -> crate::prelude::Result<()> {
511 use crate::lang::{flat_nodes, Language};
512 use crate::langs::python::lang::PythonLanguage;
513
514 let mut py = PythonLanguage::default();
515 for s in ["", "hi there", "/usr/bin", "no escapes at all"] {
516 let lifted = s.qlift_to::<Python>();
517 let text = lifted.coparse();
518 let parsed = py.parse_as(None, &flat_nodes(&text))?;
519 assert_eq!(
520 &*parsed,
521 &*lifted,
522 "lift of {s:?} is {:?} but the parser reads {text} as {:?}",
523 lifted.sexp(),
524 parsed.sexp()
525 );
526 }
527 Ok(())
528 }
529
530 #[test]
531 fn python_lists() {
532 let squares: Vec<u64> = (1..=5).map(|n| n * n).collect();
533 assert_eq!(squares.qlift_to::<Python>().coparse(), "[1, 4, 9, 16, 25]");
534 let nested = vec![vec![1u8], vec![2, 3]];
535 assert_eq!(nested.qlift_to::<Python>().coparse(), "[[1], [2, 3]]");
536 let empty: Vec<u8> = Vec::new();
537 assert_eq!(empty.qlift_to::<Python>().coparse(), "[]");
538 }
539
540 #[test]
541 fn python_tags() {
542 let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Python>() else {
543 panic!("expected tuple");
544 };
545 assert_eq!(&**tag, "integer");
546 let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Python>() else {
547 panic!("expected tuple");
548 };
549 assert_eq!(&**tag, "list");
550 }
551
552 #[test]
553 fn zsh_strings() {
554 // String, &str (via deref to `str`), and a literal all lift to a
555 // double-quoted zsh string.
556 let owned = String::from("hi there");
557 let borrowed: &str = "/var/log";
558 assert_eq!(owned.qlift_to::<Zsh>().coparse(), "\"hi there\"");
559 assert_eq!(borrowed.qlift_to::<Zsh>().coparse(), "\"/var/log\"");
560 assert_eq!("plain".qlift_to::<Zsh>().coparse(), "\"plain\"");
561 }
562
563 #[test]
564 fn zsh_escaping() {
565 // Characters zsh interprets inside "…" are backslash-escaped.
566 assert_eq!(
567 "say \"$x\" `now`".qlift_to::<Zsh>().coparse(),
568 "\"say \\\"\\$x\\\" \\`now\\`\""
569 );
570 }
571
572 #[test]
573 fn zsh_ints() {
574 assert_eq!(42u32.qlift_to::<Zsh>().coparse(), "42");
575 assert_eq!((-7i32).qlift_to::<Zsh>().coparse(), "-7");
576 }
577
578 #[test]
579 fn bash_lifts() {
580 // Bash shares the shell lift behaviour with zsh.
581 let p: &str = "/var/log";
582 assert_eq!(p.qlift_to::<Bash>().coparse(), "\"/var/log\"");
583 assert_eq!(
584 "echo `id`".qlift_to::<Bash>().coparse(),
585 "\"echo \\`id\\`\""
586 );
587 assert_eq!(42u32.qlift_to::<Bash>().coparse(), "42");
588 }
589
590 #[test]
591 fn nix_scalars() {
592 assert_eq!(42u64.qlift_to::<Nix>().coparse(), "42");
593 assert_eq!((-7i32).qlift_to::<Nix>().coparse(), "-7");
594 assert_eq!(1.0f64.qlift_to::<Nix>().coparse(), "1.0");
595 assert_eq!(2.5f32.qlift_to::<Nix>().coparse(), "2.5");
596 assert_eq!(true.qlift_to::<Nix>().coparse(), "true");
597 assert_eq!(false.qlift_to::<Nix>().coparse(), "false");
598 }
599
600 #[test]
601 fn nix_strings() {
602 let owned = String::from("/etc/nixos");
603 assert_eq!(owned.qlift_to::<Nix>().coparse(), "\"/etc/nixos\"");
604 // `"`, `\` are escaped, and the antiquotation opener `${` becomes `\${`.
605 assert_eq!(
606 "say \"hi\" ${x}".qlift_to::<Nix>().coparse(),
607 "\"say \\\"hi\\\" \\${x}\""
608 );
609 }
610
611 #[test]
612 fn nix_lists() {
613 let squares: Vec<u64> = (1..=3).map(|n| n * n).collect();
614 // Nix lists are space-separated, not comma-separated.
615 assert_eq!(squares.qlift_to::<Nix>().coparse(), "[ 1 4 9 ]");
616 let empty: Vec<u8> = Vec::new();
617 assert_eq!(empty.qlift_to::<Nix>().coparse(), "[ ]");
618 }
619
620 #[test]
621 fn lean_ints() {
622 assert_eq!(3u32.qlift_to::<Lean>().coparse(), "3");
623 assert_eq!(7usize.qlift_to::<Lean>().coparse(), "7");
624 // `num_lit` is unsigned, so a negative lifts as a `unary_op`.
625 assert_eq!((-2i32).qlift_to::<Lean>().coparse(), "-2");
626 assert_eq!(i32::MIN.qlift_to::<Lean>().coparse(), "-2147483648");
627 }
628
629 #[test]
630 fn lean_floats_and_bools() {
631 assert_eq!(1.5f64.qlift_to::<Lean>().coparse(), "1.5");
632 // Keeps the decimal point so it stays a float, not a `Nat`.
633 assert_eq!(2.0f32.qlift_to::<Lean>().coparse(), "2.0");
634 assert_eq!((-0.5f64).qlift_to::<Lean>().coparse(), "-0.5");
635 assert_eq!(true.qlift_to::<Lean>().coparse(), "true");
636 assert_eq!(false.qlift_to::<Lean>().coparse(), "false");
637 }
638
639 #[test]
640 fn lean_strings() {
641 let owned = String::from("Nat.succ");
642 assert_eq!(owned.qlift_to::<Lean>().coparse(), "\"Nat.succ\"");
643 assert_eq!(
644 "say \"hi\"\n".qlift_to::<Lean>().coparse(),
645 r#""say \"hi\"\n""#
646 );
647 // A brace is *not* escaped: a lifted literal is a plain string, not an
648 // interpolated `s!"…"`.
649 assert_eq!("{x}".qlift_to::<Lean>().coparse(), "\"{x}\"");
650 }
651
652 #[test]
653 fn lean_lists() {
654 let squares: Vec<u64> = (1..=3).map(|n| n * n).collect();
655 assert_eq!(squares.qlift_to::<Lean>().coparse(), "[1, 4, 9]");
656 let empty: Vec<u8> = Vec::new();
657 assert_eq!(empty.qlift_to::<Lean>().coparse(), "[]");
658 }
659
660 #[test]
661 fn lean_tags() {
662 let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Lean>() else {
663 panic!("expected tuple");
664 };
665 assert_eq!(&**tag, "num_lit");
666 let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Lean>() else {
667 panic!("expected tuple");
668 };
669 assert_eq!(&**tag, "list_lit");
670 }
671
672 /// The whole escape table, one character at a time. The runtime corpus
673 /// reaches `escape_html` only through `qlift_html`, and only with a string
674 /// containing `& < > "` — so `'` was the one entry in the table with no
675 /// coverage anywhere, in either binding (issue #192).
676 #[test]
677 fn html_escape_table() {
678 assert_eq!(escape_html("&"), "&");
679 assert_eq!(escape_html("<"), "<");
680 assert_eq!(escape_html(">"), ">");
681 assert_eq!(escape_html("\""), """);
682 assert_eq!(escape_html("'"), "'");
683 }
684
685 /// A single-quoted attribute value is why `'` is in the table: without it,
686 /// `<a title='…'>` breaks out of the attribute the same way `"` does.
687 #[test]
688 fn html_escape_closes_both_attribute_quotings() {
689 assert_eq!(
690 escape_html("\" onclick='x'"),
691 "" onclick='x'"
692 );
693 assert_eq!(
694 escape_html("<script>alert(1)</script>"),
695 "<script>alert(1)</script>"
696 );
697 }
698
699 /// `&` is escaped first in the sense that matters: the replacements
700 /// themselves introduce `&`, and a rule that rescanned its own output would
701 /// turn `<` into `&lt;`. One pass over the *input* is the fix, so this
702 /// pins that a mixed string escapes each character exactly once.
703 #[test]
704 fn html_escape_does_not_rescan_its_own_output() {
705 assert_eq!(escape_html("a & b < c"), "a & b < c");
706 // Not idempotent, by design: the input is a value, not markup.
707 assert_eq!(escape_html("&"), "&amp;");
708 }
709
710 /// Everything outside the table is passed through byte-for-byte — the
711 /// runtime must not apply Quilt's own glyph escaping to target text.
712 #[test]
713 fn html_escape_leaves_everything_else_alone() {
714 assert_eq!(escape_html(""), "");
715 assert_eq!(escape_html("plain text"), "plain text");
716 assert_eq!(escape_html("héllo ← ↖ 世界"), "héllo ← ↖ 世界");
717 assert_eq!(escape_html("a\nb\t\\c"), "a\nb\t\\c");
718 }
719
720 /// The rule *set*, not just the rules that happen to have a line above: a
721 /// sixth escape added without a test shows up right here. Came from the
722 /// per-binding copies this function replaced, and is the reason the table
723 /// is worth having in one place — it can only be stated once.
724 #[test]
725 fn html_escape_table_is_exactly_five_characters() {
726 let changed: String = (0u8..=127)
727 .map(char::from)
728 .filter(|c| {
729 let s = c.to_string();
730 escape_html(&s) != s
731 })
732 .collect();
733 assert_eq!(changed, "\"&'<>");
734 }
735
736 #[test]
737 fn nix_tags() {
738 let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Nix>() else {
739 panic!("expected tuple");
740 };
741 assert_eq!(&**tag, "integer_expression");
742 let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Nix>() else {
743 panic!("expected tuple");
744 };
745 assert_eq!(&**tag, "list_expression");
746 }
747}