Skip to main content

quilt/langs/
hold.rs

1//! The identity meta-language, shared by every host that *holds* code
2//! rather than computing with it.
3//!
4//! Every other meta translates a quoted fragment into host code that rebuilds
5//! it — Rust and Python emit builder calls into a `QTerm` runtime, Nix and Lean
6//! emit string literals in the host's own syntax. A held language has neither:
7//! no expressions to translate *into*, and no runtime to translate *for*. So
8//! it does the one thing such a host can do — it **holds the object-level code
9//! as unparsed lines**: same tags, same `cmds`, same text. Expanding a held
10//! quote yields the quoted term itself, and `coparse` gives the fragment back
11//! verbatim.
12//!
13//! That makes the three `expand_*` methods a structural identity. The operator
14//! spellings (`↑ ↓ ← ⟨T⟩ ⟨N⟩`) are the other half of the same fact: each is a
15//! *host* operator that has to expand into a host expression, and a held
16//! language has none — so each returns an error naming a real host, rather
17//! than leaking a `__LIFT__`-style placeholder into the output.
18//!
19//! Two languages are held: text (`langs::text::meta`, the original) and HTML
20//! (`langs::html::meta`), whose notebooks run the held cells on machines
21//! instead. [`Holds`] is the two-line dialect marker that puts the right
22//! language name in the refusals. This module is not feature-gated, because
23//! either language may be enabled without the other.
24
25use std::marker::PhantomData;
26
27use miette::{bail, Result};
28
29use crate::lang::Arity;
30use crate::meta::OuterKind;
31use crate::prelude::{Index, *};
32use crate::{meta::MetaLanguage, qterm::QTerm, term::CmdOrHole};
33
34/**************************************************************/
35
36/// What distinguishes one identity host from another: only how it is named
37/// in the diagnostics that refuse the operators.
38pub trait Holds {
39    /// The language name, as the refusals spell it (`text`, `html`).
40    const NAME: &'static str;
41    /// The quote annotation a real host would use to reach this language
42    /// (`txt`, `html`) — the alternative every refusal names.
43    const ANNO: &'static str;
44}
45
46/// The identity meta-language, for a language that holds code rather than
47/// computing with it. See the module docs.
48pub struct HoldMetaLanguage<H: Holds>(PhantomData<H>);
49
50impl<H: Holds> Default for HoldMetaLanguage<H> {
51    fn default() -> Self {
52        HoldMetaLanguage(PhantomData)
53    }
54}
55
56/**************************************************************/
57
58/// Rebuild a node as itself: same `tag`, same `cmds`, `terms` back in its
59/// holes. This is the whole of an identity meta — the object-level code is
60/// kept rather than translated, so the `cmds` that serialized the fragment
61/// before expansion serialize it after.
62///
63/// Every node the expander hands over comes from a parse, where the hole count
64/// and the child count agree by construction. A hand-built term need not, and
65/// silently dropping children would be a worse failure than saying so.
66fn hold(name: &str, tag: &str, terms: &[Arc<QTerm>], cmds: &[CmdOrHole]) -> Result<Arc<QTerm>> {
67    let holes = cmds.iter().filter(|c| matches!(c, CmdOrHole::Hole)).count();
68    if holes != terms.len() {
69        bail!(
70            "{name} can't hold a {tag:?} node: {holes} hole(s) for {} child term(s)",
71            terms.len()
72        );
73    }
74    Ok(tuple(tag, terms, cmds))
75}
76
77impl<H: Holds> MetaLanguage for HoldMetaLanguage<H> {
78    /// A nested quote (`lang↖…↗` at quote depth > 0) belongs to a later stage,
79    /// so it stays as written. The quote's own `cmds` already hold its
80    /// annotation and both glyphs around a single hole for the body, so holding
81    /// them reproduces the source — including whether the author annotated the
82    /// quote at all, which `lang2` alone would not say.
83    fn expand_quote(
84        &self,
85        _lang1: &str,
86        tag: &str,
87        _i: Index,
88        _lang2: &str,
89        qterm: &Arc<QTerm>,
90        cmds: &[CmdOrHole],
91    ) -> Result<Arc<QTerm>> {
92        hold(H::NAME, tag, std::slice::from_ref(qterm), cmds)
93    }
94
95    /// An unquote that does not reach ground, held verbatim like a nested
96    /// quote. (One that *does* reach ground never arrives here: the expander
97    /// splices the ground term in its place, which for an identity host is
98    /// the ground text itself.)
99    fn expand_unquote(
100        &self,
101        _lang1: &str,
102        tag: &str,
103        _i: Index,
104        _lang2: &str,
105        qterm: &Arc<QTerm>,
106        cmds: &[CmdOrHole],
107    ) -> Result<Arc<QTerm>> {
108        hold(H::NAME, tag, std::slice::from_ref(qterm), cmds)
109    }
110
111    /// The quoted code itself. Variadic and fixed nodes are held identically —
112    /// there is no builder whose shape would differ between them.
113    fn expand_tuple(
114        &self,
115        _lang1: &str,
116        tag: &str,
117        qterms: &[Arc<QTerm>],
118        cmds: &[CmdOrHole],
119        _arity: Arity,
120    ) -> Result<Arc<QTerm>> {
121        hold(H::NAME, tag, qterms, cmds)
122    }
123
124    /// Identity: a child is already woven into its parent by the `cmds` that
125    /// [`hold`] keeps, so there is nothing to wrap it in. Emit and splice have
126    /// no accumulator to reach (see [`Self::emit_str`]).
127    fn wrap_child(&self, qterm: Arc<QTerm>, _okind: OuterKind) -> Result<Arc<QTerm>> {
128        Ok(qterm)
129    }
130
131    /// No spelling: `↑` turns a host *value* into a term, and an identity host
132    /// has no values — a fragment is already the text it stands for.
133    fn lift_str(&self, target: &str) -> Result<&'static str> {
134        bail!(
135            "{} can't lift `↑` into {target:?}: it holds code rather than building it, so \
136             there is no expression for a lift to be — quote {} from a real host \
137             (`{}↖ … ↗` in a `.rs.quilt` or `.py.quilt` file) and lift there",
138            H::NAME,
139            H::NAME,
140            H::ANNO
141        )
142    }
143
144    /// No spelling: `↓` evaluates a fragment at generation time, which needs a
145    /// runtime to evaluate it *with*. Nothing in a held file runs.
146    fn reduce_str(&self, target: &str) -> Result<&'static str> {
147        bail!(
148            "{} can't reduce `{target}↓`: it holds code rather than running it, so there is \
149             no runtime to evaluate a fragment with — reduce in a real host that quotes \
150             `{}↖ … ↗`",
151            H::NAME,
152            H::ANNO
153        )
154    }
155
156    /// No spelling: `←` appends into a `b_` accumulator, which only a meta that
157    /// *builds* its output has. An identity host holds its output whole.
158    fn emit_str(&self) -> Result<&'static str> {
159        bail!(
160            "{} can't emit `←`: it holds code rather than building it, so there is no `b_` \
161             accumulator to emit into — emit in a real host that quotes `{}↖ … ↗`",
162            H::NAME,
163            H::ANNO
164        )
165    }
166
167    /// No spelling: `⟨T⟩` names the type of a generated fragment in the host's
168    /// own syntax, and a held language has no type syntax to name it in.
169    fn type_str(&self) -> Result<&'static str> {
170        bail!(
171            "{} has no type for `⟨T⟩`: it has no type syntax — drop the annotation",
172            H::NAME
173        )
174    }
175
176    /// No spelling: `⟨N⟩` takes a string to an identifier term. In a held
177    /// language a name is already its own text, so the operator *is* the
178    /// identity — and there is no identity function to write it as.
179    fn name_str(&self) -> Result<&'static str> {
180        bail!(
181            "{} has no spelling for `⟨N⟩`: a name in {} is already its own text, so the \
182             operator would be the identity — drop it",
183            H::NAME,
184            H::NAME
185        )
186    }
187}