quilt/multi.rs
1#[cfg(feature = "parse")]
2use crate::glyphs::split_anno;
3use crate::lang::{Arity, Language, LanguagePost};
4#[cfg(feature = "parse")]
5use crate::lang::{FlatNode, Hole};
6use crate::meta::{MetaLanguage, OuterKind, Piece};
7use crate::node::{Node, MACHINE};
8use crate::prelude::*;
9#[cfg(feature = "parse")]
10use crate::qterm::QTermBuilder;
11use crate::qterm::{tuple, QTerm, Repr};
12use crate::strcmd::StrCmd;
13use crate::term::CmdOrHole;
14#[cfg(feature = "parse")]
15use crate::zipper::{List, Zipper};
16use miette::{ensure, miette, LabeledSpan};
17#[cfg(feature = "parse")]
18use regex::Regex;
19use std::collections::BTreeMap;
20#[cfg(feature = "parse")]
21use std::sync::LazyLock;
22
23/**************************************************************/
24
25#[cfg(feature = "parse")]
26static RE_WS_PREFIX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*").unwrap());
27const DEFAULT_LANG: &str = "rs";
28
29/**************************************************************/
30
31/// The depth at which a term is being expanded. Either Ground or some language and positive depth.
32#[derive(Debug, Clone, Default)]
33pub enum Stage {
34 #[default]
35 Ground,
36 /// invariant: Index > 0
37 Sky(Box<str>, Index),
38}
39
40/// Seed a parse zipper from a language chain (host first, then the defaults for
41/// nested un-annotated quotes). The host sits at the cursor (`head`) and the
42/// rest seed `anti`, so an un-annotated `↖…↗` resolves the next default language
43/// via [`Zipper::back`]; when the chain is exhausted, parsing falls back to the
44/// host (matching the single-language `["rs"]` behavior).
45#[cfg(feature = "parse")]
46fn zipper_from_chain(chain: &[&str]) -> Zipper<Box<str>> {
47 let host: Box<str> = chain.first().copied().unwrap_or(DEFAULT_LANG).into();
48 let mut anti = List::new();
49 for lang in chain.get(1..).unwrap_or(&[]).iter().rev() {
50 anti = anti.cons((*lang).into());
51 }
52 Zipper {
53 list: List::new().cons(host),
54 anti,
55 }
56}
57
58/**************************************************************/
59
60pub trait Languages {
61 type Language: Language + ?Sized;
62
63 fn get(&self, lang: &str) -> Result<&Self::Language>;
64 fn get_mut(&mut self, lang: &str) -> Result<&mut Self::Language>;
65
66 /// The canonical registry key for `lang`, resolving aliases (`python` →
67 /// `py`); identity for unknown names. The machine park keys by this, so
68 /// [`Multi::machine`] hands the same machine to every alias.
69 fn canonical<'a>(&'a self, lang: &'a str) -> &'a str {
70 lang
71 }
72}
73
74pub trait MetaLanguages {
75 type MetaLanguage: MetaLanguage + ?Sized;
76
77 fn get(&self, lang: &str) -> Result<&Self::MetaLanguage>;
78 fn get_mut(&mut self, lang: &str) -> Result<&mut Self::MetaLanguage>;
79
80 /**************************************************************/
81
82 fn lift_str(&self, lang: &str, target: &str) -> Result<&'static str> {
83 self.get(lang)?.lift_str(target)
84 }
85 fn reduce_str(&self, lang: &str, target: &str) -> Result<&'static str> {
86 self.get(lang)?.reduce_str(target)
87 }
88 fn reduce_method_str(&self, lang: &str, target: &str) -> Result<&'static str> {
89 self.get(lang)?.reduce_method_str(target)
90 }
91 fn emit_str(&self, lang: &str) -> Result<&'static str> {
92 self.get(lang)?.emit_str()
93 }
94 fn lift_str_in(&self, lang: &str, target: &str, repr: Repr) -> Result<&'static str> {
95 self.get(lang)?.lift_str_in(target, repr)
96 }
97 fn emit_str_in(&self, lang: &str, repr: Repr) -> Result<&'static str> {
98 self.get(lang)?.emit_str_in(repr)
99 }
100 fn type_str(&self, lang: &str) -> Result<&'static str> {
101 self.get(lang)?.type_str()
102 }
103 fn name_str(&self, lang: &str) -> Result<&'static str> {
104 self.get(lang)?.name_str()
105 }
106 fn type_method_str(&self, lang: &str) -> Result<&'static str> {
107 self.get(lang)?.type_method_str()
108 }
109 fn spawn_str(&self, lang: &str, target: &str) -> Result<String> {
110 self.get(lang)?.spawn_str(target)
111 }
112 fn prelude(&self, lang: &str, targets: &[&str]) -> Result<Option<crate::meta::Prelude>> {
113 Ok(self.get(lang)?.prelude(targets))
114 }
115}
116
117#[derive(Default)]
118pub struct Multi<LS: Languages, MS: MetaLanguages> {
119 pub langs: LS,
120 pub metas: MS,
121 /// Live default machines, one per language, spawned on first use by
122 /// [`machine`](Multi::machine) — so successive reduces share definitions
123 /// for as long as this `Multi` lives. See `docs/design/machines.md`.
124 pub machines: crate::machine::Park,
125}
126
127impl<LS: Languages, MS: MetaLanguages> Multi<LS, MS> {
128 pub fn get_lang(&self, lang: &str) -> Result<&LS::Language> {
129 self.langs.get(lang)
130 }
131 pub fn get_lang_mut(&mut self, lang: &str) -> Result<&mut LS::Language> {
132 self.langs.get_mut(lang)
133 }
134 pub fn get_meta(&self, lang: &str) -> Result<&MS::MetaLanguage> {
135 self.metas.get(lang)
136 }
137 pub fn get_meta_mut(&mut self, lang: &str) -> Result<&mut MS::MetaLanguage> {
138 self.metas.get_mut(lang)
139 }
140 pub fn lift_str(&self, lang: &str, target: &str) -> Result<&'static str> {
141 self.metas.lift_str(lang, target)
142 }
143 /// [`Self::lift_str`] for a `↑` in source. A host that cannot lift into
144 /// text at all is told so about `text`, the language the author quoted,
145 /// rather than about [`TEXT_IN_QUOTES`](crate::lift::TEXT_IN_QUOTES), a
146 /// position inside it they never named.
147 #[cfg(feature = "parse")]
148 fn lift_spelling(&self, lang: &str, target: &str, repr: Repr) -> Result<&'static str> {
149 match self.metas.lift_str_in(lang, target, repr) {
150 Err(e) if target == crate::lift::TEXT_IN_QUOTES => {
151 self.metas.lift_str_in(lang, "text", repr)?;
152 Err(e)
153 }
154 r => r,
155 }
156 }
157 pub fn reduce_str(&self, lang: &str, target: &str) -> Result<&'static str> {
158 self.metas.reduce_str(lang, target)
159 }
160 pub fn reduce_method_str(&self, lang: &str, target: &str) -> Result<&'static str> {
161 self.metas.reduce_method_str(lang, target)
162 }
163 pub fn emit_str(&self, lang: &str) -> Result<&'static str> {
164 self.metas.emit_str(lang)
165 }
166 /// The runtime import a file expanded with `lang`'s meta must open with
167 /// (issue #274), given the object languages it may lift into. See
168 /// [`MetaLanguage::prelude`](crate::meta::MetaLanguage::prelude).
169 pub fn prelude(&self, lang: &str, targets: &[&str]) -> Result<Option<crate::meta::Prelude>> {
170 self.metas.prelude(lang, targets)
171 }
172
173 /// The runtime import the file expanded from `input` under `chain` (ground
174 /// language first) should open with, or `None` (issue #274). Paired with
175 /// [`with_prelude`](crate::meta::with_prelude), this is what `quilt expand`
176 /// writes, and what the in-browser expander (`quilt-expand-wasm`) writes
177 /// too, so a generated module is runnable whichever of them produced it.
178 ///
179 /// `None` for a host whose meta needs none (nix, lean and text generate no
180 /// runtime calls at all), and by the two rules that keep the injection from
181 /// becoming a footgun:
182 ///
183 /// * **The source uses no Quilt construct.** `examples/hello.rs.quilt`
184 /// expands to itself and must stay import-free: Rust tolerates an unused
185 /// glob silently, but a Python or TypeScript linter will not.
186 /// * **The author already imported the runtime.** Two identical globs are
187 /// harmless in Rust and Python, but a doubled *named* import is a hard
188 /// error in TypeScript — so this is checked rather than assumed. See
189 /// [`Prelude::present_in`](crate::meta::Prelude::present_in).
190 ///
191 /// The targets the meta is asked about — which only a target-directed host
192 /// like TypeScript reads — are the language chain plus every annotation the
193 /// source's quotes name, so that a `sql↖…↗` inside a `.rs.quilt` counts even
194 /// though the chain never mentions SQL. It over-approximates: a language
195 /// listed but never lifted into costs an unused name, one missing costs a
196 /// name that is not in scope.
197 #[must_use]
198 pub fn prelude_for(&self, chain: &[&str], input: &str) -> Option<crate::meta::Prelude> {
199 let used = crate::node::constructs(input);
200 if !used.any {
201 return None;
202 }
203 let mut targets: Vec<&str> = chain.to_vec();
204 for anno in &used.annos {
205 if !targets.contains(&&**anno) {
206 targets.push(anno);
207 }
208 }
209 // A language with no meta is not an error here — an expansion that
210 // succeeded proves the host is fine — so a failed lookup is simply "no
211 // prelude".
212 let prelude = self.prelude(chain[0], &targets).ok().flatten()?;
213 (!prelude.present_in(input)).then_some(prelude)
214 }
215 pub fn type_str(&self, lang: &str) -> Result<&'static str> {
216 self.metas.type_str(lang)
217 }
218 pub fn name_str(&self, lang: &str) -> Result<&'static str> {
219 self.metas.name_str(lang)
220 }
221 pub fn type_method_str(&self, lang: &str) -> Result<&'static str> {
222 self.metas.type_method_str(lang)
223 }
224 pub fn spawn_str(&self, lang: &str, target: &str) -> Result<String> {
225 self.metas.spawn_str(lang, target)
226 }
227
228 /// Spawn a *fresh* machine for `lang`: the persistent
229 /// [`ReplMachine`](crate::machine::ReplMachine) when the language
230 /// declares a [`repl_spec`](Language::repl_spec), else the replay-based
231 /// [`ScriptMachine`](crate::machine::ScriptMachine) from its
232 /// [`machine_spec`](Language::machine_spec). The caller owns it: nothing
233 /// is parked, so it shares state with no other machine.
234 pub fn spawn_machine(&self, lang: &str) -> Result<Box<dyn crate::machine::Machine>> {
235 crate::machine::spawn_machine(lang, self.langs.get(lang)?)
236 }
237
238 /// The *default* machine for `lang`: parked in
239 /// [`machines`](Multi::machines), spawned on first use, shared by every
240 /// caller of this `Multi` — which is what lets one reduce see the
241 /// definitions another fed. Keyed by the canonical language name, so
242 /// aliases (`py` / `python`) share one machine.
243 pub fn machine(&mut self, lang: &str) -> Result<&mut dyn crate::machine::Machine> {
244 let key: Box<str> = self.langs.canonical(lang).into();
245 if !self.machines.contains(&key) {
246 let machine = self.spawn_machine(lang)?;
247 self.machines.insert(&key, machine);
248 }
249 Ok(self.machines.get_mut(&key).unwrap())
250 }
251
252 /// The end-user text door (tenet 2's actual subject): parse `src` as
253 /// `kind` with `lang`'s `Language` — validating it — then feed the term
254 /// to the default machine. Machines themselves traffic only in terms;
255 /// raw text is turned into a term here, where the parser lives.
256 pub fn feed_on(
257 &mut self,
258 lang: &str,
259 kind: crate::lang::InnerKind,
260 src: &str,
261 ) -> Result<crate::machine::Answer> {
262 let term = self
263 .get_lang_mut(lang)?
264 .parse_as(Some(kind), &crate::lang::flat_nodes(src))?;
265 self.machine(lang)?.feed(kind, &term)
266 }
267
268 /// Evaluate a term on `lang`'s default machine and parse the answered
269 /// literal back into a term of `lang` — machines answer with the
270 /// value's own syntax, and the `Language` re-reads it here, where it
271 /// lives.
272 pub fn eval_on(&mut self, lang: &str, term: &QTerm) -> Result<Arc<QTerm>> {
273 let answer = self.machine(lang)?.eval(term)?;
274 let value = answer.value.ok_or_else(|| {
275 miette!(
276 "the {lang} machine answered no value for {:?}",
277 term.coparse()
278 )
279 })?;
280 self.get_lang_mut(lang)?
281 .parse_expr(&crate::lang::one_liner(&value))
282 }
283
284 /// Classify a term for feeding a machine — which message sort it is —
285 /// seeing through the tagless root wrapper `parse_chain` builds around a
286 /// parsed fragment (whose tag would otherwise classify by the language's
287 /// default). The REPL and the notebook both route feeds through this.
288 pub fn classify_for_feed(&self, lang: &str, term: &QTerm) -> Result<crate::lang::InnerKind> {
289 fn go<L: Language + ?Sized>(lang: &L, term: &QTerm) -> crate::lang::InnerKind {
290 match term {
291 QTerm::Tuple { tag, terms, .. } if tag.is_empty() && terms.len() == 1 => {
292 go(lang, &terms[0])
293 }
294 _ => lang.classify_term(term),
295 }
296 }
297 Ok(go(self.get_lang(lang)?, term))
298 }
299
300 #[cfg(feature = "parse")]
301 pub fn parse(&mut self, s: &str) -> Result<Arc<QTerm>> {
302 self.parse_lang(DEFAULT_LANG, s)
303 }
304
305 #[cfg(feature = "parse")]
306 pub fn parse_lang(&mut self, lang: &str, s: &str) -> Result<Arc<QTerm>> {
307 self.parse_chain(&[lang], s)
308 }
309
310 /// Parse `s` whose language is given by a *chain* of file extensions: the
311 /// host (ground) language first, then the default language for successively
312 /// nested un-annotated `↖…↗` quotes. This comes from a file name like
313 /// `shaders.wgsl.rs.quilt` (chain `["rs", "wgsl"]`): Rust is the host and a
314 /// bare `↖…↗` defaults to WGSL. A single-element chain (`["rs"]`) is the
315 /// plain `foo.rs.quilt` case where bare quotes default to the host.
316 #[cfg(feature = "parse")]
317 pub fn parse_chain(&mut self, chain: &[&str], s: &str) -> Result<Arc<QTerm>> {
318 let nodes = Node::parse(s)?
319 .iter()
320 .map(|n| arc(n.clone()))
321 .collect::<Vec<_>>();
322
323 Ok(self
324 .build_nodes(
325 tb(""),
326 &Hole::default(),
327 &nodes,
328 &zipper_from_chain(chain),
329 None,
330 None,
331 false,
332 0,
333 )?
334 .first()
335 .unwrap())
336 }
337
338 /// Build a `QTerm` from quilt `Node`s. `splice_target` is the language the
339 /// fragment's value will be spliced into: `Some` only for unquote bodies
340 /// (the lang of the enclosing quote), `None` otherwise. It directs `↑` —
341 /// a lift inside `wgsl↖ … ↙x.↑↘ … ↗` targets WGSL; elsewhere a lift is
342 /// homogeneous (targets the fragment's own language). `bracketed` is true
343 /// when `nodes` is the body of a `↖…↗`/`↙…↘` pair and false at the top
344 /// level: only bracketed bodies get their boundary newlines trimmed.
345 /// `sky_depth` is the net quote nesting (quotes minus unquotes) at this
346 /// level: 0 at ground, +1 per enclosing quote, −1 per enclosing unquote.
347 /// An operator (`↑`/`↓`/`←`) at sky depth > 0 runs at a *later* stage, so
348 /// it is deferred (emitted as the glyph) rather than spelled out now.
349 /// `enclosing` is the language and [`Repr`] of the nearest quote around
350 /// `nodes` (`None` at the top): a bare quote inside its unquotes inherits
351 /// its representation, and a `↑`/`←` there spells that representation's.
352 #[cfg(feature = "parse")]
353 #[allow(clippy::too_many_arguments)] // recursive parse state; a struct would obscure it
354 pub fn build_nodes(
355 &mut self,
356 mut builder: QTermBuilder,
357 hole: &Hole,
358 nodes: &[Arc<Node>],
359 zipper: &Zipper<Box<str>>,
360 splice_target: Option<&str>,
361 enclosing: Option<(&str, Repr)>,
362 bracketed: bool,
363 sky_depth: usize,
364 ) -> Result<QTermBuilder> {
365 let lang = zipper.head().unwrap();
366
367 // dbg!(&nodes);
368
369 // Pass 1: strip the enclosing-context prefix (`hole.prefix`, the indent
370 // the quote sits at) from each line, and measure the body's own common
371 // leading indent. This runs for every line after a newline — including
372 // when there is no enclosing prefix — so a quote whose body is just
373 // written indented (e.g. a top-level `py↖\n …\n↗`) is dedented too,
374 // not only one spliced into already-indented code.
375 //
376 // The enclosing prefix is only stripped as far as every line actually
377 // carries it. A body written *left* of the code around the quote —
378 //
379 // let g = rs↖
380 // fn g() {}
381 // ↗;
382 //
383 // — has nothing of the prefix to give up, and used to fail the whole
384 // expansion with a bare "Failed to strip prefix". Stripping each line
385 // by as much of the prefix as it happens to have would not do either:
386 // it would flatten the body's own relative indentation. So the prefix
387 // is cut back to what every line shares, the lines lose exactly that,
388 // and the common-indent pass below takes care of the rest. Blank lines
389 // say nothing about indentation, so they do not cut the prefix back.
390 let full_prefix = hole.prefix.concat();
391 let prefix = shared_prefix(&full_prefix, nodes);
392 let mut nodes_new = Vec::with_capacity(nodes.len());
393 let mut on_nl = false;
394 let mut num_nl = 0;
395 // The common leading indent of the continuation lines (every line after
396 // a newline), measured after the enclosing prefix is stripped. Blank
397 // lines — the closing `↗`'s own indentation among them — say nothing
398 // about the body's indentation, so they do not bound it: a closer left
399 // of the body (`↖\n body\n ↗`) leaves no indent behind.
400 let mut cont: Option<&str> = None;
401 // Where the last line (the one the `↗` is on) starts in `nodes_new`.
402 let mut last_line = None;
403 for (i, n) in nodes.iter().enumerate() {
404 match &**n {
405 Node::Content(s) if on_nl => {
406 // A blank line gives up as much of the *full* prefix as it
407 // has, so a closer at the host's indent leaves nothing behind.
408 let blank = is_blank(nodes, i);
409 let s = if blank {
410 &s[common_prefix_len(&full_prefix, s)..]
411 } else {
412 &s[prefix.len()..]
413 };
414 if !s.is_empty() {
415 nodes_new.push(arc(Node::Content(s.into())));
416 if !blank {
417 let ws = RE_WS_PREFIX.find(s).unwrap().as_str();
418 cont = Some(cont.map_or(ws, |pre| &pre[..common_prefix_len(pre, ws)]));
419 }
420 }
421 }
422 _ => nodes_new.push(n.clone()),
423 }
424 on_nl = **n == Node::NewLine;
425 num_nl += usize::from(on_nl);
426 if on_nl {
427 last_line = Some(nodes_new.len());
428 }
429 }
430 // Inline opener content (`↖foo…`) sits flush with the opener, so its own
431 // leading whitespace bounds the common indent. This keeps a quote whose
432 // body carries meaningful indentation — e.g. `↖def f():\n body` —
433 // from being dedented; a block-opened quote (`↖\n body\n↗`), whose
434 // first line is a newline, has its body's common indent stripped.
435 //
436 // The exception is an inline quote whose last line *closes* what the
437 // opener line opened — it starts with `}`, `)` or `]`, as in
438 //
439 // prog.push(↖F[1] = {
440 // a: 1,
441 // };↗);
442 //
443 // There the closer marks the column the body is written relative to,
444 // whatever the host line's indent, so the continuation lines' common
445 // indent is stripped as in a block quote: `F[1] = {\n a: 1,\n};`.
446 let opener = match nodes.first().map(|n| &**n) {
447 Some(Node::Content(s)) => Some(RE_WS_PREFIX.find(s).unwrap().as_str()),
448 _ => None,
449 };
450 let closes = last_line.is_some_and(|k| {
451 matches!(nodes_new.get(k).map(|n| &**n), Some(Node::Content(s))
452 if s.trim_start().starts_with(['}', ')', ']']))
453 });
454 let indent = match (opener, cont) {
455 (Some(_), Some(cont)) if closes => Some(cont),
456 (Some(op), Some(cont)) => Some(&op[..common_prefix_len(op, cont)]),
457 (op, cont) => op.or(cont),
458 };
459 let mut nodes = nodes_new;
460 let indent = indent.unwrap_or_default();
461
462 // dbg!(&nodes_new);
463
464 // Pass 2: dedent by common prefix. Reset `on_nl`: like Pass 1 it must
465 // start false so the opener-line content (`↖foo…`, which has no leading
466 // indent) is never stripped — only lines that follow a newline, which
467 // are exactly the lines Pass 1 measured `indent` from.
468 on_nl = false;
469 if !indent.is_empty() {
470 let mut nodes_new = Vec::with_capacity(nodes.len());
471 for n in nodes {
472 match &*n {
473 Node::Content(s) if on_nl => {
474 // A blank line did not bound `indent`, so it may have
475 // less of it than the others: it loses what it has.
476 let s = &s[common_prefix_len(indent, s)..];
477 if !s.is_empty() {
478 nodes_new.push(arc(Node::Content(s.into())));
479 }
480 }
481 _ => nodes_new.push(n.clone()),
482 }
483 on_nl = *n == Node::NewLine;
484 }
485 nodes = nodes_new;
486 }
487 // Trim one boundary newline on each side so `↖\n…\n↗` parses the same
488 // body as `↖…↗`; the trimmed newlines are re-emitted as builder cmds
489 // below. At the top level (no enclosing brackets) the boundary
490 // newlines are real source content and must stay in `code`.
491 let first_nl = bracketed && !nodes.is_empty() && **nodes.first().unwrap() == Node::NewLine;
492 let last_nl = bracketed
493 && !nodes.is_empty()
494 && **nodes.last().unwrap() == Node::NewLine
495 && num_nl != usize::from(first_nl); // distinguish ↖↗ from ↖\n↗
496 let nodes = &nodes[usize::from(first_nl)..nodes.len() - usize::from(last_nl)];
497
498 // Pass 3: build up a string of code with holes // TODO: avoid creating string
499 //
500 // `lang⟨M⟩` is the one operator whose expansion is *computed* rather
501 // than a `&'static str` — it interpolates the resolved language name
502 // (issue #273) — so the spellings are built here, up front, and the
503 // `FlatNode::Str`s below borrow from this vector. Deferred `⟨M⟩`s
504 // (sky depth > 0) belong to a later stage and get no spelling at all.
505 // A bare `⟨M⟩` resolves as a bare quote in its place would, so it
506 // reads the last annotated quote before it at this level too.
507 let mut spawns = Vec::new();
508 if sky_depth == 0 {
509 let mut sibling = "";
510 for n in nodes {
511 match &**n {
512 Node::Quote { anno, .. } if !split_anno(anno).0.is_empty() => {
513 sibling = split_anno(anno).0;
514 }
515 Node::Machine { anno } => {
516 let anno = if anno.is_empty() { sibling } else { anno };
517 spawns.push(self.spawn_str(lang, &machine_lang(zipper, lang, anno))?);
518 }
519 _ => {}
520 }
521 }
522 }
523 let mut spawns = spawns.iter();
524
525 // The representation a value spliced from here must have: the
526 // enclosing quote's, inside one of its unquotes; `cst` at plain ground.
527 let splice_repr = match (splice_target, enclosing) {
528 (Some(_), Some((_, repr))) => repr,
529 _ => Repr::Cst,
530 };
531 let mut code = Vec::with_capacity(nodes.len());
532 for (i, n) in nodes.iter().enumerate() {
533 match &**n {
534 Node::Content(s) => code.push(FlatNode::Str(s)),
535 Node::NewLine => code.push(FlatNode::NewLine),
536 Node::Unquote { nodes, .. } if !nodes.iter().any(|n| **n == Node::NewLine) => {
537 code.push(FlatNode::Splice);
538 }
539 Node::Quote { .. } | Node::Unquote { .. } => code.push(FlatNode::Hole),
540 // An operator (↑ lift, ↓ reduce, ← emit) inside an as-yet-
541 // unresolved quote (sky depth > 0) belongs to a later stage:
542 // defer it as a hole so it survives `coparse` as its glyph and
543 // is spelled out when that stage runs, instead of being expanded
544 // here one stage too early.
545 Node::Lift | Node::Reduce { .. } | Node::Emit | Node::Machine { .. }
546 if sky_depth > 0 =>
547 {
548 code.push(FlatNode::Hole);
549 }
550 Node::Lift => code.push(FlatNode::Str(self.lift_spelling(
551 lang,
552 splice_target.unwrap_or(lang),
553 splice_repr,
554 )?)),
555 // `↓` flush against an argument list — `db.↓(schema)` — is
556 // *method position*: it spells the host's machine-eval method
557 // name, completed by the source's own parentheses (#268).
558 // Everywhere else it is the reduce operator as before.
559 Node::Reduce { anno } if method_position(nodes, i) => {
560 let spelling = match self.reduce_method_str(lang, anno) {
561 Ok(spelling) => spelling,
562 // A host with no method-position reading *at all*
563 // keeps `↓`'s operator meaning, which is what a flush
564 // `(` meant before the rule existed: TypeScript's
565 // `gen(7).↓(6)` reduces a generated function and calls
566 // it. A host that has the reading and merely refused
567 // this annotation keeps its own diagnostic, which is
568 // more useful than either spelling.
569 Err(e) if self.reduce_method_str(lang, "").is_ok() => return Err(e),
570 Err(_) => self.reduce_str(lang, anno)?,
571 };
572 code.push(FlatNode::Str(spelling));
573 }
574 Node::Reduce { anno } => code.push(FlatNode::Str(self.reduce_str(lang, anno)?)),
575 Node::Emit => {
576 let spelling = self.metas.emit_str_in(lang, splice_repr)?;
577 // A host whose `←` is a bare function name (TypeScript's
578 // `qseq`) is functional: it takes the whole sequence as an
579 // argument, so the glyph must open a call. Anything else —
580 // Rust's postfix `x.←` habit, say — would expand to a
581 // reference to the function and fail far from here. Asked
582 // of the host's `⟨cst⟩` spelling, since a `⟨str⟩` one may
583 // be a function *expression* (an inline join).
584 let functional = self
585 .emit_str(lang)
586 .is_ok_and(|s| s.chars().all(|c| c.is_alphanumeric() || c == '_'));
587 if functional && !method_position(nodes, i) {
588 miette::bail!(
589 "{lang}'s `←` is a function of the whole sequence: write `←(items)` \
590 (or `←(items, sep)`), which expands to `{spelling}(items)`"
591 );
592 }
593 code.push(FlatNode::Str(spelling));
594 }
595 // `⟨T⟩` flush against an argument list — `db.⟨T⟩(term)` — is
596 // the *typing* judgment on a machine, the companion of
597 // `db.↓(term)`'s value judgment (#273). In operand position it
598 // is the term type as before.
599 Node::Type if method_position(nodes, i) => {
600 // Same fallback as `↓` above: a host with no typing-
601 // judgment spelling keeps `⟨T⟩`'s operand meaning rather
602 // than losing a reading it already had.
603 let spelling = match self.type_method_str(lang) {
604 Ok(spelling) => spelling,
605 Err(_) => self.type_str(lang)?,
606 };
607 code.push(FlatNode::Str(spelling));
608 }
609 Node::Type => code.push(FlatNode::Str(self.type_str(lang)?)),
610 Node::Name => code.push(FlatNode::Str(self.name_str(lang)?)),
611 Node::Machine { .. } => {
612 let spelling = spawns.next().expect("one spelling per `⟨M⟩`, built above");
613 code.push(FlatNode::Str(spelling));
614 }
615 Node::PlainLineComment(s) | Node::PlainBlockComment(s) => {
616 code.push(FlatNode::Str(s));
617 }
618 }
619 }
620
621 // println!("PRE: code: '{code}'");
622
623 // dbg!(&code);
624 // dbg!(&indent);
625 // dbg!(&first_nl);
626 // dbg!(&last_nl);
627
628 // parse this level and get hole types of children
629 let post = self.get_lang_mut(lang)?.parse_pre(hole.ikind, &code)?;
630 let mut holes = post.holes().iter();
631 // How *this* language spells a bare identifier, for the deferred
632 // operator placeholders below.
633 let ident_tag = self.get_lang(lang)?.ident_tag();
634
635 // parse children using hole types
636 let mut plugs = Vec::new();
637 let nodes_here = nodes;
638 // The annotation of the last annotated quote at this level: a bare
639 // `↖…↗` after `py↖…↗` is Python too, the way a bare quote *inside*
640 // one already is. Only siblings count — a quote nested in an unquote
641 // starts its own level — so the rule reads in source order, quote by
642 // quote, and an annotation is what changes it.
643 //
644 // A representation (`ts⟨str⟩↖`) is inherited the same way, by the
645 // quotes after it in the same language, and by those inside its
646 // unquotes (`enclosing`).
647 let mut sibling: Option<(Box<str>, Repr)> = None;
648 for (i, n) in nodes.iter().enumerate() {
649 match &**n {
650 // Deferred operators (see the code-building pass): consume the
651 // hole and plug the glyph back in, so the term coparses to a real
652 // operator for the next stage to expand.
653 Node::Lift if sky_depth > 0 => {
654 holes
655 .next()
656 .ok_or_else(|| miette!("Ran out of holes for lift: {n:?}"))?;
657 plugs.push(leaf(ident_tag, "↑"));
658 }
659 Node::Reduce { anno } if sky_depth > 0 => {
660 holes
661 .next()
662 .ok_or_else(|| miette!("Ran out of holes for reduce: {n:?}"))?;
663 plugs.push(leaf(ident_tag, &format!("{anno}↓")));
664 }
665 Node::Emit if sky_depth > 0 => {
666 holes
667 .next()
668 .ok_or_else(|| miette!("Ran out of holes for emit: {n:?}"))?;
669 plugs.push(leaf(ident_tag, "←"));
670 }
671 Node::Machine { anno } if sky_depth > 0 => {
672 holes
673 .next()
674 .ok_or_else(|| miette!("Ran out of holes for machine: {n:?}"))?;
675 // The *unresolved* annotation goes back in: the stage that
676 // runs this fragment resolves the bare form against its own
677 // chain, exactly as this one would have.
678 plugs.push(leaf(ident_tag, &format!("{anno}{MACHINE}")));
679 }
680 Node::Content(_)
681 | Node::NewLine
682 | Node::Lift
683 | Node::Reduce { .. }
684 | Node::Emit
685 | Node::Type
686 | Node::Name
687 | Node::Machine { .. }
688 | Node::PlainLineComment(_)
689 | Node::PlainBlockComment(_) => {}
690 Node::Quote { anno, nodes, span } => {
691 let hole = holes
692 .next()
693 .ok_or_else(|| miette!("Ran out of holes for quote: {n:?}"))?;
694 // .unwrap_or_else(|| miette!("Ran out of holes for quote: {n:?}"))?;
695 // Descend into the quote's embedded language. An annotation
696 // selects it explicitly, and is inherited by the bare
697 // quotes after it at this level. An un-annotated `↖…↗`
698 // with no annotated sibling before it resolves the
699 // default embedded language via `.back()`, which walks the
700 // file's extension chain (e.g. `wgsl` for `*.wgsl.rs.quilt`)
701 // or the enclosing quote's lang (from inside its unquote),
702 // falling back to the host when none is set. The quote's
703 // lang is then the head of the resolved zipper — the
704 // expander uses it to pick the arity for the body's tags
705 // (e.g. `wgsl`'s `case_compound_statement`).
706 let (lang_part, repr_part) = split_anno(anno);
707 let zipper = if !lang_part.is_empty() {
708 zipper.clone().cons(lang_part.into())
709 } else if let Some((sib, _)) = &sibling {
710 zipper.clone().cons(sib.clone())
711 } else {
712 zipper
713 .clone()
714 .back()
715 .unwrap_or_else(|| zipper.clone().cons(lang.clone()))
716 };
717 let quote_lang = zipper.head().unwrap().clone();
718 let repr = match repr_part {
719 Some(name) => Repr::from_name(name).map_err(|e| {
720 miette!(
721 labels = vec![LabeledSpan::at(span.clone(), "this quote")],
722 "{e}"
723 )
724 })?,
725 None => match (&sibling, enclosing) {
726 (Some((sib, repr)), _) if *sib == quote_lang => *repr,
727 (_, Some((outer, repr))) if *outer == *quote_lang => repr,
728 _ => Repr::Cst,
729 },
730 };
731 if !anno.is_empty() {
732 sibling = Some((quote_lang.clone(), repr));
733 }
734 let mut builder = qb(&hole.otag, 1, "e_lang);
735 builder.span(span.clone());
736 builder.repr(repr);
737 builder.write(anno).write("↖");
738 // A quote's body is free-form (a statement-shaped term may
739 // fill an expression hole and vice versa), so don't coerce
740 // it to the hole's kind.
741 let hole = Hole {
742 ikind: None,
743 ..hole.clone()
744 };
745 let mut builder = self.build_nodes(
746 builder,
747 &hole,
748 nodes,
749 &zipper,
750 None,
751 Some(("e_lang, repr)),
752 true,
753 sky_depth + 1,
754 )?;
755 builder.write("↗");
756 plugs.push(builder.b());
757 }
758 Node::Unquote { anno, nodes, span } => {
759 let hole = hole
760 + holes
761 .next()
762 .ok_or_else(|| miette!("Ran out of holes for unquote: {n:?}"))?;
763 let mut builder = ub(&hole.otag, 1, lang);
764 builder.span(span.clone());
765 // The body's value is spliced into *this* fragment's
766 // language: it directs any `↑` in the body (e.g. a lift
767 // inside `wgsl↖…↗` lifts into WGSL). Text has no grammar
768 // to say where the hole is, so its position comes from
769 // the characters around it (`text_splice_target`).
770 let splice_target = text_splice_target(lang, nodes_here, i).unwrap_or(lang);
771 let zipper = zipper.clone().tail().unwrap();
772 // an unquote with no enclosing quote pops the host off the
773 // zipper; catch it here (with a span) instead of panicking
774 // on the empty zipper when recursing into the body
775 if zipper.head().is_none() {
776 return Err(unquote_depth_error(Some(span)));
777 }
778 builder.write(anno).write("↙");
779 let mut builder = self.build_nodes(
780 builder,
781 &hole,
782 nodes,
783 &zipper,
784 Some(splice_target),
785 enclosing,
786 true,
787 sky_depth.saturating_sub(1),
788 )?;
789 builder.write("↘");
790 plugs.push(builder.b());
791 }
792 }
793 }
794
795 // fill holes with plugs
796 let term = post.parse_post(&plugs)?;
797
798 // builder result
799 builder
800 .push_if(indent, !indent.is_empty())
801 .nl_if(first_nl)
802 .child(&term)
803 .pop_if(!indent.is_empty())
804 .nl_if(last_nl);
805 Ok(builder)
806 }
807
808 pub fn expand(&mut self, qterm: &QTerm) -> Result<Arc<QTerm>> {
809 self.expand_lang(DEFAULT_LANG, qterm)
810 }
811
812 pub fn expand_lang(&mut self, lang: &str, qterm: &QTerm) -> Result<Arc<QTerm>> {
813 let Multi {
814 ref mut langs,
815 ref mut metas,
816 ..
817 } = self;
818 let meta = metas.get(lang)?;
819 Expander {
820 langs,
821 meta,
822 lang,
823 pattern_vars: None,
824 in_builder: false,
825 }
826 .expand(&Default::default(), qterm)
827 }
828}
829
830/// Where a hole in a *text* quote sits, as a splice target: between two `"`
831/// the author wrote, it is [`TEXT_IN_QUOTES`](crate::lift::TEXT_IN_QUOTES), so
832/// `↑` renders a string's escaped contents rather than a second pair of quotes
833/// (issue #149). Anything else, and any other language, is `None`: a grammar
834/// already knows what a hole inside its string literal is.
835///
836/// "The author wrote" means unescaped: `\"↙x↘\"` is a quote character in the
837/// text, not the opening of a quoted context.
838#[cfg(feature = "parse")]
839fn text_splice_target(lang: &str, nodes: &[Arc<Node>], i: usize) -> Option<&'static str> {
840 if !matches!(lang, "text" | "txt") {
841 return None;
842 }
843 let Some(Node::Content(before)) = nodes.get(i.checked_sub(1)?).map(|n| &**n) else {
844 return None;
845 };
846 let Some(Node::Content(after)) = nodes.get(i + 1).map(|n| &**n) else {
847 return None;
848 };
849 let opens = before
850 .strip_suffix('"')
851 .is_some_and(|rest| !rest.ends_with('\\'));
852 (opens && after.starts_with('"')).then_some(crate::lift::TEXT_IN_QUOTES)
853}
854
855/// The language a `⟨M⟩` names. An annotation says it outright (the caller
856/// passes an inherited sibling annotation as `anno`); the bare form resolves
857/// exactly as a bare `↖…↗` does — the chain's next default language via the
858/// zipper's `.back()`, falling back to the host — so `⟨M⟩` in a
859/// `.sql.py.quilt` file is a SQL machine and in a plain `.py.quilt` file a
860/// Python one (issue #273).
861#[cfg(feature = "parse")]
862fn machine_lang(zipper: &Zipper<Box<str>>, lang: &str, anno: &str) -> Box<str> {
863 let zipper = if anno.is_empty() {
864 zipper
865 .clone()
866 .back()
867 .unwrap_or_else(|| zipper.clone().cons(lang.into()))
868 } else {
869 zipper.clone().cons(anno.into())
870 };
871 zipper.head().expect("a consed zipper has a head").clone()
872}
873
874/// Whether the node after `i` opens an argument list flush against the
875/// operator — `recv.↓(arg)` — making the operator a *method name* that the
876/// source's own parentheses complete. Flush means exactly that: `↓ (x)`
877/// (with a space) stays the ordinary operator.
878#[cfg(feature = "parse")]
879fn method_position(nodes: &[Arc<Node>], i: usize) -> bool {
880 matches!(nodes.get(i + 1).map(|n| &**n), Some(Node::Content(s)) if s.starts_with('('))
881}
882
883/// An "unquote depth too high" error pointing at the offending unquote when
884/// its source span is known (parsed terms carry spans; constructed terms
885/// don't). Callers with the source text at hand (e.g. the CLI) can attach it
886/// via [`miette::Report::with_source_code`] to render the offending snippet.
887fn unquote_depth_error(span: Option<&Span>) -> miette::Report {
888 match span {
889 Some(span) => miette!(
890 labels = vec![LabeledSpan::at(span.clone(), "this unquote")],
891 "unquote depth too high! (source bytes {}..{})",
892 span.start,
893 span.end
894 ),
895 None => miette!("unquote depth too high!"),
896 }
897}
898
899/// `e`, pointing at the quote it came from when that quote's span is known.
900fn at_span(e: miette::Report, span: Option<&Span>) -> miette::Report {
901 match span {
902 Some(span) => miette!(
903 labels = vec![LabeledSpan::at(span.clone(), "this quote")],
904 "{e}"
905 ),
906 None => e,
907 }
908}
909
910pub struct Expander<'a, LS: Languages, M: MetaLanguage + ?Sized> {
911 langs: &'a mut LS,
912 meta: &'a M,
913 /// The ground (host) language, used to classify tags of ground tuples.
914 lang: &'a str,
915 /// `Some` while expanding the pattern quote of a pattern-let: ground
916 /// unquotes become metavariables, collected here in source order.
917 pattern_vars: Option<Vec<Box<str>>>,
918 /// Whether the ground code being expanded runs inside an accumulator — an
919 /// unquote that is a direct child of a variadic quoted node, whose
920 /// expansion binds `b_`. Only there can a quote in statement position be
921 /// emitted; outside every unquote (a function body, say) there is no `b_`,
922 /// and a statement-shaped quote in tail position is the block's value.
923 in_builder: bool,
924}
925
926impl<M: MetaLanguage + ?Sized, LS: Languages> Expander<'_, LS, M> {
927 // TODO: simplify a ton, remove unused concepts
928 fn expand(&mut self, depth: &Stage, term: &QTerm) -> Result<Arc<QTerm>> {
929 match depth {
930 Stage::Ground => match term {
931 // `ts⟨str⟩↖…↗` and `ts⟨qt⟩↖…↗`: the host's meta builds the
932 // value from the quote flattened to text and holes, rather
933 // than rebuilding its syntax tree node by node.
934 QTerm::Quote {
935 index,
936 lang: lang2,
937 term,
938 span,
939 repr,
940 ..
941 } if *repr != Repr::Cst => {
942 let mut pieces = Vec::new();
943 self.flatten(*repr, *index, term, &mut pieces)
944 .map_err(|e| at_span(e, span.as_ref()))?;
945 self.meta.expand_flat(*repr, lang2, &pieces)
946 }
947 QTerm::Quote {
948 index,
949 lang: lang1,
950 term,
951 ..
952 } => {
953 self.expand(&Stage::Sky(lang1.clone(), *index), term)
954 // self.get_meta(meta).wrap_quote(meta, expanded, emit)
955 }
956 QTerm::Unquote { span, .. } => Err(unquote_depth_error(span.as_ref())),
957 QTerm::Tuple { tag, terms, cmds } => {
958 // `let ↖pattern↗ = value;` — a quote in binding position
959 // destructures the value instead of building a term. The
960 // meta-language locates the two positions, since neither the
961 // separator token nor the child index is universal.
962 if self.meta.pattern_tag() == Some(&**tag) {
963 if let Some((p, v)) = self.meta.pattern_binding(terms) {
964 if let Some(QTerm::Quote { .. }) = terms.get(p).map(AsRef::as_ref) {
965 return self.expand_pattern_let(tag, terms, cmds, p, v);
966 }
967 }
968 }
969 let arity = self.langs.get(self.lang)?.arity(tag);
970 let terms = terms
971 .iter()
972 .map(|term| {
973 // expand each child
974 let expanded = self.expand(&Stage::Ground, term)?;
975 // then wrap the result
976 let mut okind = OuterKind::None;
977 // A quote in statement position of a variadic node
978 // would otherwise build a term and silently drop
979 // it, so infer Emit. A tail-expression quote parses
980 // with the same outer tag (`expression_statement`),
981 // so also require the quoted body to be a statement
982 // — an expression body means the quote is a value.
983 //
984 // The body's kind comes from the inner language's
985 // `classify_term` (the kind it actually parsed),
986 // which — unlike `typ` on the root tag — sees through
987 // wrappers like WGSL's `source_file(stmt, ;)`. This
988 // closes the feedback loop from issue #25 and makes
989 // the decision work across language boundaries.
990 //
991 // And only inside an accumulator: at plain ground
992 // there is no `b_`, so `fn f() -> Arc<QTerm> {
993 // ↖fn g() {}↗ }` returns the quote rather than
994 // emitting it into a builder that does not exist.
995 if self.in_builder && arity == Arity::Variadic {
996 if let QTerm::Quote {
997 tag: qtag,
998 lang: lang2,
999 term: body,
1000 ..
1001 } = &**term
1002 {
1003 if self.langs.get(self.lang)?.typ(qtag).is_stmt_like()
1004 && self.langs.get(lang2)?.classify_term(body).is_stmt_like()
1005 {
1006 okind = OuterKind::Emit;
1007 }
1008 }
1009 }
1010 self.meta.wrap_child(expanded, okind)
1011 })
1012 .collect::<Result<Vec<_>>>()?;
1013 Ok(tuple(tag, &terms, cmds))
1014 } // QTerm::Lift(_gap) => todo!(),
1015 // QTerm::Reduce(_gap) => todo!(),
1016 },
1017 Stage::Sky(lang1, d) => match term {
1018 QTerm::Quote {
1019 tag,
1020 index,
1021 lang: lang2,
1022 term,
1023 cmds,
1024 ..
1025 } => {
1026 let term = self.expand(&Stage::Sky(lang1.clone(), d + index), term)?;
1027 self.meta
1028 .expand_quote(lang1, tag, *index, lang2, &term, cmds)
1029 }
1030 QTerm::Unquote {
1031 tag,
1032 index,
1033 lang: lang2,
1034 term,
1035 cmds,
1036 span,
1037 } => {
1038 if index > d {
1039 return Err(unquote_depth_error(span.as_ref()));
1040 }
1041 let new_depth = d - index;
1042
1043 if new_depth == 0 {
1044 // Inside a pattern quote a ground unquote is a
1045 // metavariable binder, not a splice: record its name
1046 // and splice an `mvar` marker (see `crate::qmatch`).
1047 if let Some(vars) = &mut self.pattern_vars {
1048 let name = pattern_var_name(term)?;
1049 vars.push(name.clone());
1050 return self.meta.pattern_var(&name);
1051 }
1052 self.expand(&Stage::Ground, term)
1053 } else {
1054 let qterm = self.expand(&Stage::Sky(lang1.clone(), new_depth), term)?;
1055 self.meta
1056 .expand_unquote(lang1, tag, *index, lang2, &qterm, cmds)
1057 }
1058 }
1059 QTerm::Tuple { tag, terms, cmds } => {
1060 // Variadic is about *dynamic* children. The accumulator form
1061 // (`{ let mut b_ = tb(tag); …; b_.b() }`) exists so a child
1062 // can contribute zero-or-many terms, which only an unquote
1063 // can do — a child that is literal quoted syntax always
1064 // contributes exactly itself, and `x.emit(&mut b_)` on it is
1065 // just a longhand `.c(&x)`.
1066 //
1067 // So a variadic node with no unquote among its children is
1068 // downgraded to the fluent form: same term, far less
1069 // generated code. This is what keeps the variadic set free
1070 // to follow the grammar — `string_literal` and `token_tree`
1071 // really do hold repeats, but a *literal* `"hi"` should not
1072 // expand to six lines of accumulator to say so.
1073 let mut arity = self.langs.get(lang1)?.arity(tag);
1074 if arity == Arity::Variadic
1075 && !terms.iter().any(|t| matches!(&**t, QTerm::Unquote { .. }))
1076 {
1077 arity = Arity::Unknown;
1078 }
1079 // A ground splice into a comma-separated list gets its
1080 // elements separated (#293) — but only where the splice is
1081 // in element position, which the grammar's tables cannot
1082 // say: Lean's `def` holds a comma-separated list
1083 // somewhere, and its other holes are not in it. So the
1084 // splice must also sit between the list's brackets or
1085 // separators (`[↙xs↘]`, `f(a, ↙xs↘)`), never next to a
1086 // keyword or another element.
1087 let sep = if arity == Arity::Variadic {
1088 self.langs.get(lang1)?.separator(tag)
1089 } else {
1090 None
1091 };
1092 let separated = |i: usize| -> Option<&'static str> {
1093 let sep = sep?;
1094 let QTerm::Unquote { index, .. } = &*terms[i] else {
1095 return None;
1096 };
1097 let opens =
1098 |t: &str| t == sep || t.ends_with(['(', '[', '{', '<', '|', '⟨']);
1099 let closes =
1100 |t: &str| t == sep || t.starts_with([')', ']', '}', '>', '|', '⟩']);
1101 let before = i.checked_sub(1).map(|j| &terms[j]);
1102 let after = terms.get(i + 1);
1103 (*index == *d
1104 && before.is_none_or(|t| token_text(t).is_some_and(opens))
1105 && after.is_none_or(|t| token_text(t).is_some_and(closes)))
1106 .then_some(sep)
1107 };
1108 let expanded = terms
1109 .iter()
1110 .enumerate()
1111 .map(|(i, term)| {
1112 // expand each child. A ground unquote under an
1113 // accumulator runs where `b_` is bound; under a
1114 // fluent node it does not.
1115 let outer =
1116 std::mem::replace(&mut self.in_builder, arity == Arity::Variadic);
1117 let expanded = self.expand(depth, term);
1118 self.in_builder = outer;
1119 let expanded = expanded?;
1120 // then wrap the result
1121 let mut okind = Default::default();
1122 if arity == Arity::Variadic {
1123 okind = OuterKind::Emit;
1124 // A ground unquote (`index == d`) whose body is
1125 // code — a statement, an item, or a *sequence*
1126 // of them — is host code to run, so it is
1127 // spliced verbatim. Only a value-shaped body is
1128 // emitted into the enclosing builder.
1129 //
1130 // Two things this has to get right:
1131 //
1132 // * The body is **ground** code, so it is
1133 // classified with `self.lang`, not `lang1`.
1134 // `lang1` is the quoted language, which the
1135 // body is not written in — asking
1136 // `html↖<input value="↙w↘">↗` whether HTML
1137 // thinks the Rust expression `w` is a
1138 // statement is meaningless.
1139 // * `is_code_like`, not `is_stmt_like`: a
1140 // multi-statement body parses with the file
1141 // root (`source_file`), and emitting one
1142 // appended `.emit(&mut b_);` to whatever its
1143 // last statement happened to be. That is a
1144 // syntax error unless the statement is
1145 // block-shaped (`for`/`if`/`{…}`), where it
1146 // silently hit the no-op `impl Emit for ()`
1147 // instead — which is why `mk_meta.rs.quilt`
1148 // bootstrapped straight past it.
1149 //
1150 // The two interact: `Language::typ` *defaults*
1151 // to `InnerKind::File`, so widening to
1152 // `is_code_like` while still asking `lang1`
1153 // would read every non-classifying target
1154 // language (html, wgsl, bash, zsh) as "always
1155 // code" and splice splices that must be emitted.
1156 if let QTerm::Unquote {
1157 index, term: child, ..
1158 } = &**term
1159 {
1160 if index == d {
1161 if let QTerm::Tuple { tag, .. } = &**child {
1162 if self.langs.get(self.lang)?.typ(tag).is_code_like() {
1163 okind = OuterKind::Splice;
1164 }
1165 }
1166 }
1167 }
1168 }
1169 let wrapped = self.meta.wrap_child(expanded, okind)?;
1170 match separated(i) {
1171 Some(sep) => self.meta.wrap_separated(wrapped, sep),
1172 None => Ok(wrapped),
1173 }
1174 })
1175 .collect::<Result<Vec<_>>>()?;
1176 self.meta.expand_tuple(lang1, tag, &expanded, cmds, arity)
1177 } // QTerm::Lift(gap) => self.expand_lift(lang1, gap),
1178 // QTerm::Reduce(gap) => self.expand_run(lang1, gap),
1179 },
1180 }
1181 }
1182
1183 /// Expand `let ↖pattern↗ = value;` (issue #18). The pattern quote is
1184 /// expanded with its ground unquotes replaced by `mvar` markers (their
1185 /// names collected via `pattern_vars`), and the statement is rewritten to
1186 /// destructure the result of matching the pattern against the value:
1187 /// `let [a, b] = qmatch_n(&*<pattern>, &<value>);` (see `crate::qmatch`).
1188 /// `pat` and `val` are the child indices the meta-language reported via
1189 /// [`MetaLanguage::pattern_binding`]; the expander no longer knows the
1190 /// separator token or where the pattern sits.
1191 /// Flatten the body of a `⟨str⟩`/`⟨qt⟩` quote at quote depth `d` into
1192 /// [`Piece`]s: its text and layout commands in order, and a
1193 /// [`Piece::Hole`] holding the expanded host code of each ground unquote.
1194 /// Adjacent text is merged, so a host spells one literal per run.
1195 fn flatten(&mut self, repr: Repr, d: Index, term: &QTerm, out: &mut Vec<Piece>) -> Result<()> {
1196 match term {
1197 QTerm::Tuple { terms, cmds, .. } => {
1198 let mut children = terms.iter();
1199 for c in cmds {
1200 match c {
1201 CmdOrHole::Cmd(StrCmd::Write(s)) => match out.last_mut() {
1202 Some(Piece::Text(t)) => *t = format!("{t}{s}").into(),
1203 _ => out.push(Piece::Text(s.clone())),
1204 },
1205 CmdOrHole::Cmd(StrCmd::NewLine) => out.push(Piece::NewLine),
1206 CmdOrHole::Cmd(StrCmd::Push(s)) => out.push(Piece::Push(s.clone())),
1207 CmdOrHole::Cmd(StrCmd::Pop) => out.push(Piece::Pop),
1208 CmdOrHole::Hole => {
1209 let child = children.next().ok_or_else(|| {
1210 miette!("a hole in a `{repr}` quote has no child: {term:?}")
1211 })?;
1212 self.flatten(repr, d, child, out)?;
1213 }
1214 }
1215 }
1216 Ok(())
1217 }
1218 QTerm::Unquote {
1219 index, term, span, ..
1220 } => {
1221 if index > &d {
1222 return Err(unquote_depth_error(span.as_ref()));
1223 }
1224 ensure!(
1225 index == &d,
1226 "a {repr} quote can't hold an unquote of a quote nested inside it yet: only \
1227 `⟨cst⟩` quotes stage"
1228 );
1229 // Host code with no accumulator around it, like a `⟨cst⟩`
1230 // quote's ground unquote under a fluent node.
1231 let outer = std::mem::replace(&mut self.in_builder, false);
1232 let expanded = self.expand(&Stage::Ground, term);
1233 self.in_builder = outer;
1234 out.push(Piece::Hole(expanded?));
1235 Ok(())
1236 }
1237 QTerm::Quote { .. } => Err(miette!(
1238 "a {repr} quote can't hold a nested quote yet (a later stage): only `⟨cst⟩` \
1239 quotes stage — quote the inner code inside an unquote instead"
1240 )),
1241 }
1242 }
1243
1244 fn expand_pattern_let(
1245 &mut self,
1246 tag: &str,
1247 terms: &[Arc<QTerm>],
1248 cmds: &[CmdOrHole],
1249 pat: usize,
1250 val: usize,
1251 ) -> Result<Arc<QTerm>> {
1252 // expand the pattern quote with ground unquotes as metavariables
1253 ensure!(
1254 self.pattern_vars.is_none(),
1255 "pattern let nested inside another pattern"
1256 );
1257 if let QTerm::Quote { repr, .. } = &*terms[pat] {
1258 ensure!(
1259 *repr == Repr::Cst,
1260 "a pattern quote matches a syntax tree, so it must be `⟨cst⟩`, not {repr}"
1261 );
1262 }
1263 self.pattern_vars = Some(Vec::new());
1264 let pattern = self.expand(&Stage::Ground, &terms[pat]);
1265 let names = self.pattern_vars.take().unwrap();
1266 let pattern = pattern?;
1267 for (i, name) in names.iter().enumerate() {
1268 ensure!(
1269 !names[..i].contains(name),
1270 "pattern let binds metavariable `{name}` more than once"
1271 );
1272 }
1273
1274 let value = self.expand(&Stage::Ground, &terms[val])?;
1275 let (binder, call) = self.meta.pattern_let(&names, &pattern, &value)?;
1276
1277 let terms = terms
1278 .iter()
1279 .enumerate()
1280 .map(|(i, term)| match i {
1281 _ if i == pat => Ok(binder.clone()),
1282 _ if i == val => Ok(call.clone()),
1283 _ => self.expand(&Stage::Ground, term),
1284 })
1285 .collect::<Result<Vec<_>>>()?;
1286 Ok(tuple(tag, &terms, cmds))
1287 }
1288}
1289
1290/// The metavariable name of a ground unquote inside a pattern quote: its body
1291/// must be a plain identifier.
1292fn pattern_var_name(term: &QTerm) -> Result<Box<str>> {
1293 let text = term.coparse();
1294 let name = text.trim();
1295 let mut chars = name.chars();
1296 let ident = chars.next().is_some_and(|c| c.is_alphabetic() || c == '_')
1297 && chars.all(|c| c.is_alphanumeric() || c == '_');
1298 ensure!(
1299 ident,
1300 "pattern metavariable must be a plain identifier, got {name:?}"
1301 );
1302 Ok(name.into())
1303}
1304
1305/**************************************************************/
1306
1307/// Resolve `lang` through an alias map; non-aliases pass through unchanged.
1308fn canonical<'a>(aliases: &'a BTreeMap<Box<str>, Box<str>>, lang: &'a str) -> &'a str {
1309 aliases.get(lang).map_or(lang, AsRef::as_ref)
1310}
1311
1312#[derive(Default)]
1313pub struct DictLanguages {
1314 langs: BTreeMap<Box<str>, Box<dyn Language<Post = Box<dyn LanguagePost>>>>,
1315 /// alias → canonical key in `langs`, so aliases share one instance
1316 aliases: BTreeMap<Box<str>, Box<str>>,
1317}
1318
1319impl Languages for DictLanguages {
1320 type Language = Box<dyn Language<Post = Box<dyn LanguagePost>>>;
1321
1322 fn get(&self, lang: &str) -> Result<&Self::Language> {
1323 self.langs
1324 .get(canonical(&self.aliases, lang))
1325 .ok_or_else(|| miette!("Language {lang} not found"))
1326 }
1327 fn get_mut(&mut self, lang: &str) -> Result<&mut Self::Language> {
1328 self.langs
1329 .get_mut(canonical(&self.aliases, lang))
1330 .ok_or_else(|| miette!("Language {lang} not found"))
1331 }
1332
1333 fn canonical<'a>(&'a self, lang: &'a str) -> &'a str {
1334 canonical(&self.aliases, lang)
1335 }
1336}
1337
1338impl DictLanguages {
1339 pub fn add(&mut self, lang: &str, language: <Self as Languages>::Language) {
1340 self.langs.insert(lang.into(), language);
1341 }
1342
1343 pub fn add_alias(&mut self, alias: &str, canonical: &str) {
1344 self.aliases.insert(alias.into(), canonical.into());
1345 }
1346}
1347
1348#[derive(Default)]
1349pub struct DictMetaLanguages {
1350 metas: BTreeMap<Box<str>, Box<dyn MetaLanguage>>,
1351 /// alias → canonical key in `metas`, so aliases share one instance
1352 aliases: BTreeMap<Box<str>, Box<str>>,
1353}
1354
1355impl MetaLanguages for DictMetaLanguages {
1356 type MetaLanguage = Box<dyn MetaLanguage>;
1357
1358 fn get(&self, lang: &str) -> Result<&Self::MetaLanguage> {
1359 self.metas
1360 .get(canonical(&self.aliases, lang))
1361 .ok_or_else(|| miette!("Language {lang} not found"))
1362 }
1363 fn get_mut(&mut self, lang: &str) -> Result<&mut Self::MetaLanguage> {
1364 self.metas
1365 .get_mut(canonical(&self.aliases, lang))
1366 .ok_or_else(|| miette!("Language {lang} not found"))
1367 }
1368}
1369
1370impl DictMetaLanguages {
1371 pub fn add(&mut self, lang: &str, meta_language: <Self as MetaLanguages>::MetaLanguage) {
1372 self.metas.insert(lang.into(), meta_language);
1373 }
1374
1375 pub fn add_alias(&mut self, alias: &str, canonical: &str) {
1376 self.aliases.insert(alias.into(), canonical.into());
1377 }
1378}
1379
1380pub type DictMulti = Multi<DictLanguages, DictMetaLanguages>;
1381
1382impl DictMulti {
1383 pub fn add_lang(&mut self, lang: &str, language: <DictLanguages as Languages>::Language) {
1384 self.langs.add(lang, language);
1385 }
1386
1387 pub fn add_meta(
1388 &mut self,
1389 lang: &str,
1390 meta: <DictMetaLanguages as MetaLanguages>::MetaLanguage,
1391 ) {
1392 self.metas.add(lang, meta);
1393 }
1394
1395 /// Register `alias` as an alternate name for `canonical` in both the
1396 /// language and meta-language registries. Lookups under the alias resolve
1397 /// to the canonical entry's instance (no entry there → "not found").
1398 pub fn add_alias(&mut self, alias: &str, canonical: &str) {
1399 self.langs.add_alias(alias, canonical);
1400 self.metas.add_alias(alias, canonical);
1401 }
1402}
1403
1404/**************************************************************/
1405
1406// Singletons
1407
1408#[derive(Default)]
1409pub struct Singleton<T>(T);
1410
1411impl<L: Language> Languages for Singleton<L> {
1412 type Language = L;
1413
1414 fn get(&self, _lang: &str) -> Result<&Self::Language> {
1415 Ok(&self.0)
1416 }
1417 fn get_mut(&mut self, _lang: &str) -> Result<&mut Self::Language> {
1418 Ok(&mut self.0)
1419 }
1420}
1421
1422impl<M: MetaLanguage> MetaLanguages for Singleton<M> {
1423 type MetaLanguage = M;
1424
1425 fn get(&self, _lang: &str) -> Result<&Self::MetaLanguage> {
1426 Ok(&self.0)
1427 }
1428 fn get_mut(&mut self, _lang: &str) -> Result<&mut Self::MetaLanguage> {
1429 Ok(&mut self.0)
1430 }
1431}
1432
1433pub type Single<M, L> = Multi<Singleton<M>, Singleton<L>>;
1434
1435/// Byte length of the longest common prefix of `a` and `b`, on a char boundary.
1436#[cfg(feature = "parse")]
1437fn common_prefix_len(a: &str, b: &str) -> usize {
1438 a.char_indices()
1439 .zip(b.chars())
1440 .find(|((_, x), y)| x != y)
1441 .map_or_else(|| a.len().min(b.len()), |((i, _), _)| i)
1442}
1443
1444/// The part of `prefix` (an enclosing quote's indent) that every non-blank line
1445/// of `nodes` starts with — the most of it that can be stripped without
1446/// cutting into a line's own text. A blank line (see [`is_blank`]) does not
1447/// count; whitespace followed by a quote, an unquote or an operator is that
1448/// construct's indentation, and does.
1449#[cfg(feature = "parse")]
1450fn shared_prefix<'a>(prefix: &'a str, nodes: &[Arc<Node>]) -> &'a str {
1451 let mut shared = prefix;
1452 let mut on_nl = false;
1453 for (i, n) in nodes.iter().enumerate() {
1454 if let Node::Content(s) = &**n {
1455 if on_nl && !is_blank(nodes, i) {
1456 shared = &shared[..common_prefix_len(shared, s)];
1457 }
1458 }
1459 on_nl = **n == Node::NewLine;
1460 }
1461 shared
1462}
1463
1464/// Whether `nodes[i]` is a blank line's content: only whitespace, and nothing
1465/// after it on the line.
1466#[cfg(feature = "parse")]
1467fn is_blank(nodes: &[Arc<Node>], i: usize) -> bool {
1468 matches!(&*nodes[i], Node::Content(s) if s.trim().is_empty())
1469 && nodes.get(i + 1).is_none_or(|next| **next == Node::NewLine)
1470}
1471
1472/// The text of an anonymous token — a childless leaf whose tag is its own
1473/// text, as `sym` builds it and the parser makes `[`, `,` or `)` — or `None`
1474/// for anything else.
1475fn token_text(term: &QTerm) -> Option<&str> {
1476 match term {
1477 QTerm::Tuple { tag, terms, cmds } if terms.is_empty() => match &**cmds {
1478 [CmdOrHole::Cmd(StrCmd::Write(s))] if s == tag => Some(tag),
1479 _ => None,
1480 },
1481 _ => None,
1482 }
1483}