Skip to main content

quilt/langs/bootstrap/
meta.rs

1use super::lang::BootstrapLanguage;
2use super::strlift::StrLift;
3use crate::lang::{one_liner, Arity, FlatNode, Language};
4use crate::meta::{OuterKind, Prelude};
5use crate::prelude::*;
6use crate::qterm::tb;
7use crate::term::STerm;
8use crate::{meta::MetaLanguage, qterm::QTerm, term::CmdOrHole};
9use miette::{bail, IntoDiagnostic};
10use serde::{Deserialize, Serialize};
11use std::cell::RefCell;
12use std::io::Read;
13use std::process::Command;
14use std::sync::LazyLock;
15
16/**************************************************************/
17
18// NOTE: see bs_hole test below
19pub const BS_HOLE: &str = "__BS_HOLE__";
20pub static BS_HOLE_PARSE: LazyLock<Arc<QTerm>> = LazyLock::new(|| {
21    BootstrapLanguage::default()
22        .parse_expr(&one_liner(BS_HOLE))
23        .unwrap()
24});
25pub static BS_HOLE_EXPAND: LazyLock<Arc<QTerm>> = LazyLock::new(|| {
26    BootstrapMetaLanguage::default()
27        .str_expand(&(*BS_HOLE_PARSE))
28        .unwrap()
29});
30pub static BS_HOLE_CODE: LazyLock<String> = LazyLock::new(|| BS_HOLE_EXPAND.coparse().clone());
31
32/**************************************************************/
33
34/// Fill holes in a qterm with plugs.
35fn fill<'a, I: Iterator<Item = &'a Arc<QTerm>>>(
36    qterm: &QTerm,
37    plugs: &mut I,
38) -> Result<Arc<QTerm>> {
39    if *qterm == **BS_HOLE_PARSE {
40        plugs
41            .next()
42            .cloned()
43            .ok_or_else(|| miette!("fill: not enough plugs for {qterm:?}"))
44    } else if let QTerm::Tuple { tag, terms, cmds } = qterm {
45        let terms = terms
46            .iter()
47            .map(|x| fill(x, plugs))
48            .collect::<Result<Vec<_>>>()?;
49        Ok(tuple(tag, &terms, cmds))
50    } else {
51        bail!("fill: unexpected tuple: {qterm:?}")
52    }
53}
54
55/// Fill holes in an expanded qterm with plugs.
56fn fill_expanded<'a, I: Iterator<Item = &'a Arc<QTerm>>>(
57    qterm: &QTerm,
58    plugs: &mut I,
59) -> Result<Arc<QTerm>> {
60    if *qterm == **BS_HOLE_EXPAND {
61        plugs
62            .next()
63            .cloned()
64            .ok_or_else(|| miette!("fill: not enough plugs for {qterm:?}"))
65    } else if let QTerm::Tuple { tag, terms, cmds } = qterm {
66        let terms: Vec<Arc<QTerm>> = terms
67            .iter()
68            .map(|x| fill_expanded(x, plugs))
69            .collect::<Result<Vec<_>>>()?;
70        Ok(tuple(tag, &terms, cmds))
71    } else {
72        bail!("fill: unexpected tuple: {qterm:?}")
73    }
74}
75
76/**************************************************************/
77
78// NOTE: it's not normal for the a MetaLanguage to use a Language, but bootstrapping does.
79#[derive(Default)]
80pub struct BootstrapMetaLanguage(RefCell<BootstrapLanguage>);
81
82impl BootstrapMetaLanguage {
83    /// Expand using strings.
84    fn str_expand<T: StrLift>(&self, t: &T) -> Result<Arc<QTerm>> {
85        let lifted = t.strlift();
86        self.parse_expr(&one_liner(&lifted))
87    }
88
89    /// Expand using strings and fill holes with plugs.
90    fn str_expand_and_fill<T: StrLift>(
91        &self,
92        qterm: &T,
93        plugs: &[Arc<QTerm>],
94    ) -> Result<Arc<QTerm>> {
95        // lift to qterm
96        let qterm = self.str_expand(qterm)?;
97        // Fill the holes with plugs.
98        fill_expanded(&qterm, &mut plugs.iter())
99    }
100
101    fn parse_expr(&self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
102        self.0.borrow_mut().parse_expr(code)
103    }
104    fn parse_stmt(&self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
105        self.0.borrow_mut().parse_stmt(code)
106    }
107}
108
109impl MetaLanguage for BootstrapMetaLanguage {
110    fn expand_quote(
111        &self,
112        _lang1: &str,
113        tag: &str,
114        i: Index,
115        lang2: &str,
116        qterm: &Arc<QTerm>,
117        cmds: &[CmdOrHole],
118    ) -> Result<Arc<QTerm>> {
119        self.str_expand_and_fill(
120            &quote(tag, i, lang2, BS_HOLE_PARSE.clone(), cmds),
121            std::slice::from_ref(qterm),
122        )
123    }
124
125    fn expand_unquote(
126        &self,
127        _lang1: &str,
128        tag: &str,
129        i: Index,
130        lang2: &str,
131        qterm: &Arc<QTerm>,
132        cmds: &[CmdOrHole],
133    ) -> Result<Arc<QTerm>> {
134        self.str_expand_and_fill(
135            &unquote(tag, i, lang2, BS_HOLE_PARSE.clone(), cmds),
136            std::slice::from_ref(qterm),
137        )
138    }
139
140    fn expand_tuple(
141        &self,
142        _lang1: &str,
143        tag: &str,
144        qterms: &[Arc<QTerm>],
145        cmds: &[CmdOrHole],
146        arity: Arity,
147    ) -> Result<Arc<QTerm>> {
148        if arity == Arity::Variadic {
149            let mut b_ = tb("block");
150            b_.child(&sym("{")).push("    ").nl();
151
152            b_.child(&self.parse_stmt(&one_liner(&format!("let mut b_ = tb(\"{tag}\");")))?)
153                .nl();
154            for (k, cmd) in cmds.iter().enumerate() {
155                let child = match cmd {
156                    CmdOrHole::Cmd(cmd) => match cmd {
157                        StrCmd::Push(s) if crate::term::is_aligned_splice(cmds, k) => &self
158                            .parse_stmt(&one_liner(&format!(
159                                "b_.align({});",
160                                s.as_ref().strlift()
161                            )))?,
162                        StrCmd::Write(s) => &self.parse_stmt(&one_liner(&format!(
163                            "b_.write({});",
164                            s.as_ref().strlift()
165                        )))?,
166                        StrCmd::NewLine => &self.parse_stmt(&one_liner("b_.nl();"))?,
167                        StrCmd::Push(s) => &self.parse_stmt(&one_liner(&format!(
168                            "b_.push({});",
169                            s.as_ref().strlift()
170                        )))?,
171                        StrCmd::Pop => &self.parse_stmt(&one_liner("b_.pop();"))?,
172                    },
173                    CmdOrHole::Hole => &BS_HOLE_PARSE,
174                };
175                b_.child(child).nl();
176            }
177            b_.child(&self.parse_expr(&one_liner("b_.b()"))?);
178
179            b_.pop().nl().child(&sym("}"));
180            return fill(&b_.build(), &mut qterms.iter());
181        }
182
183        self.str_expand_and_fill(
184            &tuple(tag, &(vec![BS_HOLE_PARSE.clone(); qterms.len()]), cmds),
185            qterms,
186        )
187    }
188
189    fn wrap_child(&self, sterm: Arc<QTerm>, okind: OuterKind) -> Result<Arc<QTerm>> {
190        match okind {
191            OuterKind::None => Ok(sterm),
192            OuterKind::Emit => fill(
193                &*self
194                    .0
195                    .borrow_mut()
196                    // the `let` avoids having multiple mutable borrows of b_ for nested emits
197                    .parse_stmt(&one_liner(&format!("{BS_HOLE}.emit(&mut b_);")))?,
198                &mut std::iter::once(&sterm),
199            ),
200            OuterKind::Splice => fill(
201                &*self
202                    .0
203                    .borrow_mut()
204                    .parse_stmt(&one_liner(&format!("{BS_HOLE};")))?,
205                &mut std::iter::once(&sterm),
206            ),
207        }
208    }
209
210    fn wrap_separated(&self, sterm: Arc<QTerm>, sep: &str) -> Result<Arc<QTerm>> {
211        Ok(crate::langs::rust::ops::wrap_separated(&sterm, sep))
212    }
213
214    fn pattern_tag(&self) -> Option<&'static str> {
215        Some("let_declaration")
216    }
217
218    fn pattern_binding(&self, terms: &[Arc<QTerm>]) -> Option<(usize, usize)> {
219        crate::qmatch::pattern_binding_at(terms, "=", Some(":"))
220    }
221
222    fn pattern_var(&self, name: &str) -> Result<Arc<QTerm>> {
223        Ok(crate::langs::rust::ops::pattern_var_code(name))
224    }
225
226    fn pattern_let(
227        &self,
228        names: &[Box<str>],
229        pattern: &Arc<QTerm>,
230        value: &Arc<QTerm>,
231    ) -> Result<(Arc<QTerm>, Arc<QTerm>)> {
232        Ok(crate::langs::rust::ops::pattern_let_code(
233            names, pattern, value,
234        ))
235    }
236
237    // No heterogeneous lifting from the bootstrap meta: `target` is ignored.
238    fn lift_str(&self, _target: &str) -> Result<&'static str> {
239        Ok("bs_lift()")
240    }
241
242    // No heterogeneous reduction from the bootstrap meta: `target` is ignored.
243    fn reduce_str(&self, _target: &str) -> Result<&'static str> {
244        Ok("bs_reduce()")
245    }
246
247    fn type_str(&self) -> Result<&'static str> {
248        Ok("Arc<QTerm>")
249    }
250
251    fn name_str(&self) -> Result<&'static str> {
252        Ok("bs_name")
253    }
254
255    fn emit_str(&self) -> Result<&'static str> {
256        // "b_.emit"
257        Ok("emit(&mut b_)")
258    }
259
260    /// The same `use quilt::prelude::*;` the Omni Rust meta injects (issue
261    /// #274): the bootstrap engine emits the *same* runtime calls under
262    /// different names (`bs_lift` where Omni writes `qlift`), and
263    /// `quilt::prelude` re-exports both.
264    ///
265    /// Sharing the spelling is what keeps `quilt expand` and
266    /// `quilt expand -m bootstrap` differing only in that one call, which is
267    /// the property `expand_bootstrap_selects_the_other_engine` pins.
268    fn prelude(&self, _targets: &[&str]) -> Option<Prelude> {
269        Some(crate::langs::rust::ops::prelude_spelling())
270    }
271}
272
273pub fn bs_lift<T: StrLift>(x: &T) -> Arc<QTerm> {
274    let lifted = x.strlift();
275    BootstrapLanguage::default()
276        .parse_expr(&one_liner(&lifted))
277        .expect("bs_lift: failed to parse lifted code")
278}
279
280pub trait BsLift {
281    fn bs_lift(&self) -> Arc<QTerm>;
282}
283
284impl<T: StrLift> BsLift for T {
285    fn bs_lift(&self) -> Arc<QTerm> {
286        bs_lift(self)
287    }
288}
289
290pub fn bs_reduce<T: Serialize + for<'de> Deserialize<'de>>(x: &QTerm) -> Result<T> {
291    // get x as a string
292    let input = x.coparse();
293    // create the file the result is shuttled back through (postcard bytes)
294    let mut out_file = tempfile::NamedTempFile::new().into_diagnostic()?;
295    let out_path = out_file.path().to_str().unwrap();
296
297    // build a full rust-script program with its dependencies in the frontmatter.
298    // `CARGO_MANIFEST_DIR` is an absolute path to *this* quilt crate, so the
299    // manifest works regardless of cwd (embedded-manifest relative paths would
300    // resolve against rust-script's cache dir, not cwd).
301    let quilt_dir = env!("CARGO_MANIFEST_DIR");
302    let script = indoc::formatdoc! {r#"
303        //! ```cargo
304        //! [dependencies]
305        //! quilt = {{ path = "{quilt_dir}", package = "quiltlang", default-features = false, features = ["bootstrap"] }}
306        //! postcard = {{ version = "1.1", features = ["alloc"] }}
307        //! ```
308        #[allow(unused_imports)]
309        use quilt::prelude::*;
310        use std::io::Write;
311        fn main() -> Result<()> {{
312            let output = {input};
313            let data = postcard::to_allocvec(&output).unwrap();
314            let mut file = std::fs::File::create("{out_path}").unwrap();
315            file.write_all(&data).unwrap();
316            Ok(())
317        }}
318    "#};
319
320    // write the script to a temp file and run it
321    let script_file = tempfile::Builder::new()
322        .suffix(".rs")
323        .tempfile()
324        .into_diagnostic()?;
325    std::fs::write(script_file.path(), script).into_diagnostic()?;
326    let status = Command::new("rust-script")
327        .arg(script_file.path())
328        .stdout(std::process::Stdio::inherit())
329        .stderr(std::process::Stdio::inherit())
330        .status()
331        .into_diagnostic()?;
332
333    if !status.success() {
334        bail!("bs_reduce: script failed with status {status}");
335    }
336
337    let mut data = Vec::new();
338    out_file.read_to_end(&mut data).into_diagnostic()?;
339    postcard::from_bytes(&data).into_diagnostic()
340}
341
342impl QTerm {
343    pub fn bs_reduce<T: Serialize + for<'de> Deserialize<'de>>(&self) -> Result<T> {
344        bs_reduce(self)
345    }
346}
347
348pub fn bs_name(s: &str) -> Arc<QTerm> {
349    leaf("identifier", s)
350}