Skip to main content

quilt/langs/rust/
ops.rs

1//! Direct term-lifting for the Rust meta-language.
2//!
3//! These helpers build the `Arc<QTerm>` that *reconstructs* a term by writing
4//! constructor source (`tb(..).c(&child)..b()`, `quote(..)`, ...) directly and
5//! splicing child terms at holes. This is the term-valued analogue of
6//! `langs::bootstrap::strlift` — same emitted source, but with no string
7//! round-trip (no re-parse).
8//!
9//! The fold that assembles those chains is shared with the Python and
10//! TypeScript metas — see [`crate::langs::chain`], which also carries the
11//! generated table of Rust's fragments (`.c(&x)`, `&[..]`). Two things here are
12//! Rust's alone and stay hand-written: the [`build_variadic_block`] below,
13//! which is an imperative `b_` block rather than a chain, and the escaping.
14//!
15//! [`QLift`] runs the same fold in [`Lit::Term`] mode, which is the difference
16//! between code that only has to serialize and code that has to be
17//! *matchable*: `qlift` emits structured `string_literal` subterms so
18//! `rewrite_naive` can find them.
19
20use crate::langs::chain::{Chain, Lit, RUST};
21use crate::meta::Prelude;
22use crate::prelude::*;
23use crate::term::{is_aligned_splice, CmdOrHole};
24use miette::{bail, IntoDiagnostic};
25use serde::{Deserialize, Serialize};
26use std::io::Read;
27use std::process::Command;
28
29/**************************************************************/
30
31/// Escape the body of a Rust double-quoted string literal.
32fn str_body(s: &str) -> String {
33    s.replace('\\', "\\\\").replace('"', "\\\"")
34}
35
36/// Render a Rust string literal, escaping `\` and `"` (matches `strlift` for
37/// `str`).
38fn str_lit(s: &str) -> String {
39    format!("\"{}\"", str_body(s))
40}
41
42/// The shared builder-call fold, spelled for Rust, emitting literals as source
43/// text. The dump-only path the three `build_*_code` helpers take.
44const FLAT: Chain = Chain::new(&RUST, Lit::Flat(str_lit));
45
46/// The same fold, emitting literals as structured `string_literal` subterms so
47/// the result can be manipulated as Rust AST. The path [`QLift`] takes.
48const TERM: Chain = Chain::new(&RUST, Lit::Term(strlit_term));
49
50/**************************************************************/
51
52/// Build code that reconstructs a tuple: `tb(tag).w(..).c(&child)..b()`, using
53/// the `sym`/`leaf` shorthands when possible. `children` are the already-built
54/// child expressions spliced at hole positions.
55pub fn build_tuple_code(tag: &str, cmds: &[CmdOrHole], children: &[Arc<QTerm>]) -> Arc<QTerm> {
56    FLAT.tuple_code(tag, cmds, children)
57}
58
59/// Build `quote(tag, index, lang, <term>, &[..cmds..])`, splicing `term`.
60pub fn build_quote_code(
61    tag: &str,
62    index: Index,
63    lang: &str,
64    term: &Arc<QTerm>,
65    cmds: &[CmdOrHole],
66) -> Arc<QTerm> {
67    FLAT.quote_code(tag, index, lang, term, cmds)
68}
69
70/// Build `unquote(tag, index, lang, <term>, &[..cmds..])`, splicing `term`.
71pub fn build_unquote_code(
72    tag: &str,
73    index: Index,
74    lang: &str,
75    term: &Arc<QTerm>,
76    cmds: &[CmdOrHole],
77) -> Arc<QTerm> {
78    FLAT.unquote_code(tag, index, lang, term, cmds)
79}
80
81/// Build a variadic node as an imperative block:
82/// `{ let mut b_ = tb("tag"); b_.write(..); <child>; ..; b_.b() }`.
83/// `children` are already wrapped (see [`wrap_emit`]/[`wrap_splice`]).
84pub fn build_variadic_block(tag: &str, cmds: &[CmdOrHole], children: &[Arc<QTerm>]) -> Arc<QTerm> {
85    let mut b = tb("block");
86    b.child(&sym("{")).push("    ").nl();
87    b.write(&format!("let mut b_ = tb({});", str_lit(tag))).nl();
88    let mut it = children.iter();
89    for (k, c) in cmds.iter().enumerate() {
90        match c {
91            CmdOrHole::Cmd(StrCmd::Write(s)) => {
92                b.write(&format!("b_.write({});", str_lit(s)));
93            }
94            CmdOrHole::Cmd(StrCmd::NewLine) => {
95                b.write("b_.nl();");
96            }
97            CmdOrHole::Cmd(StrCmd::Push(s)) if is_aligned_splice(cmds, k) => {
98                b.write(&format!("b_.align({});", str_lit(s)));
99            }
100            CmdOrHole::Cmd(StrCmd::Push(s)) => {
101                b.write(&format!("b_.push({});", str_lit(s)));
102            }
103            CmdOrHole::Cmd(StrCmd::Pop) => {
104                b.write("b_.pop();");
105            }
106            CmdOrHole::Hole => {
107                b.child(
108                    it.next()
109                        .expect("build_variadic_block: not enough children"),
110                );
111            }
112        }
113        b.nl();
114    }
115    b.write("b_.b()");
116    b.pop().nl().child(&sym("}"));
117    b.b()
118}
119
120/// Wrap an expanded child for emission into a variadic block: `<child>.emit(&mut b_);`.
121pub fn wrap_emit(child: &Arc<QTerm>) -> Arc<QTerm> {
122    let mut b = tb("_");
123    b.child(child).write(".emit(&mut b_);");
124    b.b()
125}
126
127/// Wrap an emitted or spliced child of a comma-separated list in a separated
128/// region (#293): `b_.sep(","); <child> b_.end_sep();`, each on its line.
129pub fn wrap_separated(child: &Arc<QTerm>, sep: &str) -> Arc<QTerm> {
130    let mut b = tb("_");
131    b.write(&format!("b_.sep({});", str_lit(sep)))
132        .nl()
133        .child(child)
134        .nl()
135        .write("b_.end_sep();");
136    b.b()
137}
138
139/// Wrap an expanded child spliced as a statement: `<child>;`.
140pub fn wrap_splice(child: &Arc<QTerm>) -> Arc<QTerm> {
141    let mut b = tb("_");
142    b.child(child).write(";");
143    b.b()
144}
145
146/**************************************************************/
147
148/// Make an identifier term (the `⟨N⟩` operator).
149pub fn name(s: &str) -> Arc<QTerm> {
150    leaf("identifier", s)
151}
152
153/// Code for a pattern metavariable splice: `mvar("name")`.
154///
155/// This and [`pattern_let_code`] used to live in `crate::qmatch`, beside the
156/// runtime they call into. But `mvar(..)` and `qmatch_n(&p, &v)` are *Rust*
157/// source, so emitting them from the language-agnostic core is what made
158/// pattern matching Rust-only while reading as though it were not. A second
159/// host would add its own pair next to its own `build_*_code`.
160pub fn pattern_var_code(name: &str) -> Arc<QTerm> {
161    leaf("_", &format!("mvar(\"{name}\")"))
162}
163
164/// The two terms a pattern-let rewrites to: the destructuring binder
165/// `[a, b]` that replaces the pattern quote, and the matching call
166/// `qmatch_n(&*<pattern>, &<value>)` that replaces the initializer.
167///
168/// The pattern is dereferenced explicitly (`&*`) because it is not always a
169/// method chain. A variadic pattern node that holds a metavariable expands to
170/// an accumulator block, `{ let mut b_ = ..; ..; b_.b() }`, and in
171/// `&{ .. }` the `&QTerm` that `qmatch_n` expects flows into the block, which
172/// makes its `Arc<QTerm>` tail a type error that no deref coercion repairs.
173/// `&*` derefs the `Arc` the block evaluates to, whatever form it takes.
174pub fn pattern_let_code(
175    names: &[Box<str>],
176    pattern: &Arc<QTerm>,
177    value: &Arc<QTerm>,
178) -> (Arc<QTerm>, Arc<QTerm>) {
179    let binder = leaf("_", &format!("[{}]", names.join(", ")));
180    let call = tb("_")
181        .w("qmatch_n(&*")
182        .c(pattern)
183        .w(", &")
184        .c(value)
185        .w(")")
186        .b();
187    (binder, call)
188}
189
190/// A Rust string-literal term, structured exactly as the parser (and `↖"s"↗`)
191/// produces it, so lifted code can be matched/rewritten as Rust AST (e.g. by
192/// `rewrite_naive`).
193///
194/// `s` is escaped with the same rules as [`str_lit`]. This used to assume the
195/// caller had already ensured `s` needed no escaping, which held for the
196/// expander's own tags and language names but not for the two paths that pass
197/// arbitrary user data: `QLift for str`/`String` (a lifted Rust string) and the
198/// `Write`/`Push` command bodies (arbitrary source text). A `"` in either
199/// produced a generated program that did not parse. Escaping here is also the
200/// *more* faithful reproduction of the parser's own output, since tree-sitter
201/// records `string_content` exactly as it appears in source — backslashes and
202/// all.
203/// The empty string is `(string_literal "\"" "\"")` — the parser emits no
204/// `string_content` child when there is no content — so this mirrors that rather
205/// than emitting an empty one.
206fn strlit_term(s: &str) -> Arc<QTerm> {
207    let mut b = tb("string_literal").c(&sym("\""));
208    if !s.is_empty() {
209        b = b.c(&leaf("string_content", &str_body(s)));
210    }
211    b.c(&sym("\"")).b()
212}
213
214/// The runtime import expanded Rust opens with (used by the generated
215/// `RustMetaLanguage::prelude`, and shared with the bootstrap meta, whose
216/// generated code calls the same runtime under different names — `bs_lift`
217/// rather than `qlift`, both re-exported by `quilt::prelude`).
218///
219/// Target-independent: `↑` reaches every object language through `qlift_to::<L>`
220/// and the `LiftTo` impls, all of which arrive with the one glob (issue #274).
221///
222/// The marker is the *path*, not the whole line, so a file that says
223/// `use quilt::prelude::{tb, name};` — or writes `quilt::prelude::tb(..)` out
224/// in full — counts as having brought the runtime in itself.
225pub fn prelude_spelling() -> Prelude {
226    Prelude::new("use quilt::prelude::*;", ["quilt::prelude"])
227}
228
229/// The Rust spelling of `↑` lifting into the object language `target` (used
230/// by the generated `RustMetaLanguage::lift_str`). Homogeneous lifts keep the
231/// `qlift()` spelling; heterogeneous ones go through `LiftTo` with the
232/// target's marker type (see `crate::lift`).
233pub fn lift_spelling(target: &str) -> Result<&'static str> {
234    match target {
235        "rust" | "rs" => Ok("qlift()"),
236        "python" | "py" => Ok("qlift_to::<Python>()"),
237        "wgsl" => Ok("qlift_to::<Wgsl>()"),
238        "zsh" => Ok("qlift_to::<Zsh>()"),
239        "bash" => Ok("qlift_to::<Bash>()"),
240        "nix" => Ok("qlift_to::<Nix>()"),
241        "lean" | "lean4" => Ok("qlift_to::<Lean>()"),
242        "sql" => Ok("qlift_to::<Sql>()"),
243        // Same grammar, different escaping: MySQL reads a backslash inside
244        // `'…'` as an escape and the standard does not (#233).
245        "mysql" | "mariadb" => Ok("qlift_to::<MySql>()"),
246        "typescript" | "ts" => Ok("qlift_to::<TypeScript>()"),
247        "html" => Ok("qlift_to::<Html>()"),
248        // `Text` is named unqualified on purpose: the prelude's is
249        // `Text<Json>`, and a module that declares its own `type Text = …`
250        // shadows it, which is how a host picks a dialect for every `↑` in
251        // its text quotes (`lift::text`).
252        "text" | "txt" => Ok("qlift_to::<Text>()"),
253        crate::lift::TEXT_IN_QUOTES => Ok("qlift_to::<InQuotes<Text>>()"),
254        _ => bail!("rust can't lift into {target:?}: no spelling/LiftTo impls registered"),
255    }
256}
257
258/// The Rust spelling of `↓` reducing with meta-language `target`. The
259/// homogeneous case (`target` == `""` or `"rust"`/`"rs"`) keeps `reduce()`;
260/// heterogeneous targets invoke the corresponding cross-language reducer.
261pub fn reduce_spelling(target: &str) -> Result<&'static str> {
262    match target {
263        "" | "rust" | "rs" => Ok("reduce()"),
264        "python" | "py" => Ok("reduce_py()"),
265        _ => bail!("rust can't reduce via {target:?}: no reduce_spelling registered"),
266    }
267}
268
269/// The Rust spelling of `↓` in *method position* — `db.↓(&term)`, machine-
270/// directed reduce (#268): the machine binding's `eval` method
271/// ([`crate::machine::Machine::eval`]), which the source's own argument
272/// list completes. Target-agnostic: the machine value, not the annotation,
273/// knows its language.
274pub fn reduce_method_spelling(target: &str) -> Result<&'static str> {
275    match target {
276        "" => Ok("eval"),
277        _ => bail!(
278            "rust spells machine eval as a method on the machine value — write `m.↓(&term)` \
279             with no annotation; the machine knows its own language"
280        ),
281    }
282}
283
284/// The Rust spelling of `⟨T⟩` in *method position* — `db.⟨T⟩(&term)`, the
285/// machine's typing judgment (#273): [`Machine::type_of`], which the
286/// source's own argument list completes. The companion of
287/// [`reduce_method_spelling`]'s value judgment, and target-agnostic for the
288/// same reason.
289///
290/// [`Machine::type_of`]: crate::machine::Machine::type_of
291pub fn type_method_spelling() -> Result<&'static str> {
292    Ok("type_of")
293}
294
295/// The Rust spelling of `lang⟨M⟩` — [`qspawn`], which reads the same
296/// registered spec table `Multi::machine` reaches through the `Language`
297/// registry (#273).
298///
299/// `qspawn` and not `Multi::spawn_machine` because an expanded `.rs.quilt`
300/// file is built runtime-only (`default-features = false`), where there is no
301/// registry: the spec table is data and lives on that side of the feature
302/// gate, so the expansion is a stable one-liner rather than a `ReplSpec`
303/// literal frozen into every artifact.
304///
305/// [`qspawn`]: crate::machine::qspawn
306pub fn spawn_spelling(lang: &str) -> Result<String> {
307    crate::meta::spawn_spelling("rust", lang, |lang| format!("qspawn({lang:?})"))
308}
309
310/// Evaluate a `QTerm` by running it as Python code, then deserialize the
311/// result (the `py↓` operator from a Rust meta-program). The term's code is
312/// run via `python3` with the `quilt` Python bindings on `PYTHONPATH`; the
313/// result `QTerm` is shuttled back via its postcard serialization.
314pub fn reduce_py(x: &QTerm) -> Result<Arc<QTerm>> {
315    let input = x.coparse();
316    let mut out_file = tempfile::NamedTempFile::new().into_diagnostic()?;
317    let out_path = out_file.path().to_str().unwrap();
318
319    let quilt_dir = env!("CARGO_MANIFEST_DIR");
320    // The quilt Python package lives next to the quilt crate.
321    let py_pkg = format!("{quilt_dir}/../quilt-python");
322    let script = indoc::formatdoc! {r#"
323        import sys
324        sys.path.insert(0, "{py_pkg}")
325        from quilt import *
326        result = {input}
327        data = result.postcard_bytes()
328        with open("{out_path}", "wb") as f:
329            f.write(data)
330    "#};
331
332    let script_file = tempfile::Builder::new()
333        .suffix(".py")
334        .tempfile()
335        .into_diagnostic()?;
336    std::fs::write(script_file.path(), script).into_diagnostic()?;
337    let status = Command::new("python3")
338        .arg(script_file.path())
339        .stdout(std::process::Stdio::inherit())
340        .stderr(std::process::Stdio::inherit())
341        .status()
342        .into_diagnostic()?;
343
344    if !status.success() {
345        bail!("reduce_py: script failed with status {status}");
346    }
347
348    let mut data = Vec::new();
349    out_file.read_to_end(&mut data).into_diagnostic()?;
350    postcard::from_bytes(&data).into_diagnostic()
351}
352
353impl QTerm {
354    pub fn reduce_py(&self) -> Result<Arc<QTerm>> {
355        reduce_py(self)
356    }
357}
358
359/// Lift a value to a `QTerm` whose code reconstructs it (the `↑` operator).
360///
361/// Unlike the `build_*_code` helpers (flat, dump-only), the strings here are
362/// emitted as structured `string_literal` subterms so the lifted code can be
363/// manipulated as Rust AST — the part the bootstrap's parse-based `bs_lift`
364/// gets for free and that `rewrite_naive` relies on.
365pub trait QLift {
366    fn qlift(&self) -> Arc<QTerm>;
367}
368
369pub fn qlift<T: QLift + ?Sized>(x: &T) -> Arc<QTerm> {
370    x.qlift()
371}
372
373/// Homogeneous lifting is the `L = Rust` instance of [`LiftTo`]: anything
374/// `QLift` lifts into Rust.
375impl<T: QLift + ?Sized> crate::lift::LiftTo<crate::lift::Rust> for T {
376    fn lift_to(&self) -> Arc<QTerm> {
377        self.qlift()
378    }
379}
380
381impl QLift for Arc<QTerm> {
382    fn qlift(&self) -> Arc<QTerm> {
383        match &**self {
384            // span is dropped: lifted code rebuilds the term without one
385            QTerm::Quote {
386                tag,
387                index,
388                lang,
389                term,
390                cmds,
391                ..
392            } => TERM.quote_code(tag, *index, lang, &term.qlift(), cmds),
393            QTerm::Unquote {
394                tag,
395                index,
396                lang,
397                term,
398                cmds,
399                ..
400            } => TERM.unquote_code(tag, *index, lang, &term.qlift(), cmds),
401            QTerm::Tuple { tag, terms, cmds } => {
402                let children: Vec<Arc<QTerm>> = terms.iter().map(QLift::qlift).collect();
403                TERM.tuple_code(tag, cmds, &children)
404            }
405        }
406    }
407}
408
409impl QLift for str {
410    fn qlift(&self) -> Arc<QTerm> {
411        strlit_term(self)
412    }
413}
414
415impl QLift for String {
416    fn qlift(&self) -> Arc<QTerm> {
417        strlit_term(self)
418    }
419}
420
421impl QLift for char {
422    fn qlift(&self) -> Arc<QTerm> {
423        leaf("char_literal", &format!("'{self}'"))
424    }
425}
426
427macro_rules! qlift_display {
428    ($($t:ty),* $(,)?) => {$(
429        impl QLift for $t {
430            fn qlift(&self) -> Arc<QTerm> {
431                leaf("integer_literal", &self.to_string())
432            }
433        }
434    )*};
435}
436qlift_display!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
437
438/// Floats need `{:?}` rather than `{}`: `1.0f64.to_string()` is `"1"`, which
439/// would lift a float as an *integer* literal and silently change the type of
440/// the generated code. A negative float is a `unary_expression` over a positive
441/// literal, matching how the parser sees `-1.5` — the same shape the Lean lift
442/// uses for the same reason.
443macro_rules! qlift_float {
444    ($($t:ty),* $(,)?) => {$(
445        impl QLift for $t {
446            fn qlift(&self) -> Arc<QTerm> {
447                let s = format!("{self:?}");
448                if *self < 0.0 {
449                    // `-1.5` parses as `(unary_expression "-" (float_literal))`:
450                    // the sign is a child token, not literal text.
451                    return tb("unary_expression")
452                        .c(&sym("-"))
453                        .c(&leaf("float_literal", s.trim_start_matches('-')))
454                        .b();
455                }
456                leaf("float_literal", &s)
457            }
458        }
459    )*};
460}
461qlift_float!(f32, f64);
462
463impl QLift for bool {
464    fn qlift(&self) -> Arc<QTerm> {
465        // `true` parses as `(boolean_literal "true")` — the keyword is a child
466        // token, so a flat leaf is a shape the parser never produces.
467        tb("boolean_literal")
468            .c(&sym(if *self { "true" } else { "false" }))
469            .b()
470    }
471}
472
473/**************************************************************/
474
475/// Evaluate a `QTerm` by compiling and running it, then deserialize the result
476/// (the `↓` operator). The term's code is run as a `rust-script` linked against
477/// quilt's `rust` feature; the value is shuttled back via `postcard`.
478pub fn reduce<T: Serialize + for<'de> Deserialize<'de>>(x: &QTerm) -> Result<T> {
479    // get x as a string
480    let input = x.coparse();
481    // create the file the result is shuttled back through (postcard bytes)
482    let mut out_file = tempfile::NamedTempFile::new().into_diagnostic()?;
483    let out_path = out_file.path().to_str().unwrap();
484
485    // build a full rust-script program with its dependencies in the frontmatter.
486    // `CARGO_MANIFEST_DIR` is an absolute path to *this* quilt crate, so the
487    // manifest works regardless of cwd (embedded-manifest relative paths would
488    // resolve against rust-script's cache dir, not cwd).
489    let quilt_dir = env!("CARGO_MANIFEST_DIR");
490    let script = indoc::formatdoc! {r#"
491        //! ```cargo
492        //! [dependencies]
493        //! quilt = {{ path = "{quilt_dir}", package = "quiltlang", default-features = false, features = ["rust"] }}
494        //! postcard = {{ version = "1.1", features = ["alloc"] }}
495        //! ```
496        #[allow(unused_imports)]
497        use quilt::prelude::*;
498        use std::io::Write;
499        fn main() -> Result<()> {{
500            let output = {input};
501            let data = postcard::to_allocvec(&output).unwrap();
502            let mut file = std::fs::File::create("{out_path}").unwrap();
503            file.write_all(&data).unwrap();
504            Ok(())
505        }}
506    "#};
507
508    // write the script to a temp file and run it
509    let script_file = tempfile::Builder::new()
510        .suffix(".rs")
511        .tempfile()
512        .into_diagnostic()?;
513    std::fs::write(script_file.path(), script).into_diagnostic()?;
514    let status = Command::new("rust-script")
515        .arg(script_file.path())
516        .stdout(std::process::Stdio::inherit())
517        .stderr(std::process::Stdio::inherit())
518        .status()
519        .into_diagnostic()?;
520
521    if !status.success() {
522        bail!("reduce: script failed with status {status}");
523    }
524
525    let mut data = Vec::new();
526    out_file.read_to_end(&mut data).into_diagnostic()?;
527    postcard::from_bytes(&data).into_diagnostic()
528}
529
530impl QTerm {
531    pub fn reduce<T: Serialize + for<'de> Deserialize<'de>>(&self) -> Result<T> {
532        reduce(self)
533    }
534}