Skip to main content

quilt/
qterm.rs

1use crate::{
2    prelude::*,
3    strcmd::{PrefixWriter, StrCmd},
4    term::{CmdOrHole, STerm, Term},
5    validate::Validate,
6};
7use serde::{Deserialize, Serialize};
8use std::{iter::once, sync::Arc};
9
10/**************************************************************/
11
12pub type Gaps = Box<[CmdOrHole]>;
13
14/// What a quote expands to in its host (`ts⟨str⟩↖…↗`). The quote is parsed
15/// against its language's grammar either way; the representation only decides
16/// the runtime value the expanded code builds.
17///
18/// * `Cst` (the default, `⟨cst⟩`): a concrete syntax tree in the object
19///   language, rebuilt node by node — inspectable, matchable, re-indentable.
20/// * `Str` (`⟨str⟩`): a host string, spliced with the host's own string
21///   operations, the way hand-written string-based codegen would. Fastest.
22///   A value spliced at an indented hole is re-indented line by line, which
23///   lays out quoted values exactly as `Cst` does; the one difference is a
24///   host *string* holding a newline, which `Cst` writes raw and `Str`
25///   indents with the rest.
26/// * `Qt` (`⟨qt⟩`): a flat term — text, newlines and indentation commands
27///   with holes, the shape Quilt's own parser builds, with no object-language
28///   tags. Indents exactly as `Cst` does, but is not inspectable.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
30pub enum Repr {
31    #[default]
32    Cst,
33    Str,
34    Qt,
35}
36
37impl Repr {
38    /// The name written between `⟨…⟩` before a quote's `↖`.
39    #[must_use]
40    pub fn name(self) -> &'static str {
41        match self {
42            Repr::Cst => "cst",
43            Repr::Str => "str",
44            Repr::Qt => "qt",
45        }
46    }
47
48    /// The representation named `name`, as written in `ts⟨name⟩↖…↗`.
49    pub fn from_name(name: &str) -> Result<Self> {
50        match name {
51            "cst" => Ok(Repr::Cst),
52            "str" => Ok(Repr::Str),
53            "qt" => Ok(Repr::Qt),
54            _ => miette::bail!(
55                "unknown quote representation `⟨{name}⟩`: the representations are \
56                 `⟨cst⟩` (the default), `⟨str⟩` and `⟨qt⟩`"
57            ),
58        }
59    }
60}
61
62impl std::fmt::Display for Repr {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(f, "⟨{}⟩", self.name())
65    }
66}
67
68#[derive(Debug, Clone, Eq, Serialize, Deserialize)]
69pub enum QTerm {
70    Quote {
71        tag: Box<str>,
72        index: Index,
73        lang: Box<str>,
74        term: Arc<QTerm>,
75        cmds: Box<[CmdOrHole]>,
76        /// Byte range of the `anno↖…↗` in the original source, when this term
77        /// came from parsing one (`build_nodes` attaches it); `None` for
78        /// constructed terms. Diagnostic metadata only — not part of equality.
79        /// No serde skip: `reduce` round-trips terms through postcard, which
80        /// is positional and cannot tolerate omitted fields.
81        span: Option<Span>,
82        /// What the quote expands to (`ts⟨str⟩↖…↗`); `Repr::Cst` unless
83        /// written or inherited from a sibling or enclosing quote.
84        ///
85        /// Skipped by serde, unconditionally — which a positional format like
86        /// postcard tolerates, unlike a conditional skip — so the wire format
87        /// the runtimes share is unchanged. Only the expander reads it, and a
88        /// later stage re-reads it from the annotation text in `cmds`.
89        #[serde(skip)]
90        repr: Repr,
91    },
92    Unquote {
93        tag: Box<str>,
94        index: Index,
95        lang: Box<str>,
96        term: Arc<QTerm>,
97        cmds: Box<[CmdOrHole]>,
98        /// Byte range of the `anno↙…↘` in the original source, when this term
99        /// came from parsing one; diagnostic metadata only, like a quote's.
100        span: Option<Span>,
101    },
102    Tuple {
103        tag: Box<str>,
104        terms: Box<[Arc<QTerm>]>,
105        cmds: Box<[CmdOrHole]>,
106    },
107}
108
109/// Spans are diagnostic metadata, not part of a term's identity: a parsed term
110/// (which carries spans) compares equal to the equivalent constructed one.
111impl PartialEq for QTerm {
112    fn eq(&self, other: &Self) -> bool {
113        match (self, other) {
114            (
115                QTerm::Quote {
116                    tag,
117                    index,
118                    lang,
119                    term,
120                    cmds,
121                    span: _,
122                    repr,
123                },
124                QTerm::Quote {
125                    tag: tag2,
126                    index: index2,
127                    lang: lang2,
128                    term: term2,
129                    cmds: cmds2,
130                    span: _,
131                    repr: repr2,
132                },
133            ) => {
134                tag == tag2
135                    && index == index2
136                    && lang == lang2
137                    && term == term2
138                    && cmds == cmds2
139                    && repr == repr2
140            }
141            (
142                QTerm::Unquote {
143                    tag,
144                    index,
145                    lang,
146                    term,
147                    cmds,
148                    span: _,
149                },
150                QTerm::Unquote {
151                    tag: tag2,
152                    index: index2,
153                    lang: lang2,
154                    term: term2,
155                    cmds: cmds2,
156                    span: _,
157                },
158            ) => tag == tag2 && index == index2 && lang == lang2 && term == term2 && cmds == cmds2,
159            (
160                QTerm::Tuple { tag, terms, cmds },
161                QTerm::Tuple {
162                    tag: tag2,
163                    terms: terms2,
164                    cmds: cmds2,
165                },
166            ) => tag == tag2 && terms == terms2 && cmds == cmds2,
167            _ => false,
168        }
169    }
170}
171
172pub fn quote(
173    tag: &str,
174    index: Index,
175    lang: &str,
176    term: Arc<QTerm>,
177    cmds: &[CmdOrHole],
178) -> Arc<QTerm> {
179    qquote(tag, index, lang, term, cmds).into()
180}
181pub fn unquote(
182    tag: &str,
183    index: Index,
184    lang: &str,
185    term: Arc<QTerm>,
186    cmds: &[CmdOrHole],
187) -> Arc<QTerm> {
188    qunquote(tag, index, lang, term, cmds).into()
189}
190pub fn tuple(tag: &str, terms: &[Arc<QTerm>], cmds: &[CmdOrHole]) -> Arc<QTerm> {
191    QTerm::Tuple {
192        tag: tag.into(),
193        terms: terms.into(),
194        cmds: cmds.into(),
195    }
196    .into()
197}
198pub fn leaf(s: &str, code: &str) -> Arc<QTerm> {
199    tuple(s, &[], &[cmd(write(code))])
200}
201pub fn sym(s: &str) -> Arc<QTerm> {
202    leaf(s, s)
203}
204
205pub fn qquote(tag: &str, index: Index, lang: &str, term: Arc<QTerm>, cmds: &[CmdOrHole]) -> QTerm {
206    qquote_at(tag, index, lang, term, cmds, None)
207}
208pub fn qunquote(
209    tag: &str,
210    index: Index,
211    lang: &str,
212    term: Arc<QTerm>,
213    cmds: &[CmdOrHole],
214) -> QTerm {
215    qunquote_at(tag, index, lang, term, cmds, None)
216}
217pub fn qquote_at(
218    tag: &str,
219    index: Index,
220    lang: &str,
221    term: Arc<QTerm>,
222    cmds: &[CmdOrHole],
223    span: Option<Span>,
224) -> QTerm {
225    QTerm::Quote {
226        tag: tag.into(),
227        index,
228        lang: lang.into(),
229        term,
230        cmds: cmds.into(),
231        span,
232        repr: Repr::Cst,
233    }
234}
235/// [`qquote_at`] with a [`Repr`]: what code that rebuilds a quote calls, so
236/// the rebuilt quote expands as the original did.
237pub fn qquote_repr_at(
238    tag: &str,
239    index: Index,
240    lang: &str,
241    term: Arc<QTerm>,
242    cmds: &[CmdOrHole],
243    span: Option<Span>,
244    repr: Repr,
245) -> QTerm {
246    let mut q = qquote_at(tag, index, lang, term, cmds, span);
247    if let QTerm::Quote { repr: r, .. } = &mut q {
248        *r = repr;
249    }
250    q
251}
252pub fn qunquote_at(
253    tag: &str,
254    index: Index,
255    lang: &str,
256    term: Arc<QTerm>,
257    cmds: &[CmdOrHole],
258    span: Option<Span>,
259) -> QTerm {
260    QTerm::Unquote {
261        tag: tag.into(),
262        index,
263        lang: lang.into(),
264        term,
265        cmds: cmds.into(),
266        span,
267    }
268}
269pub fn qtuple(tag: &str, terms: &[Arc<QTerm>], cmds: &[CmdOrHole]) -> QTerm {
270    QTerm::Tuple {
271        tag: tag.into(),
272        terms: terms.into(),
273        cmds: cmds.into(),
274    }
275}
276pub fn qleaf(s: &str, code: &str) -> QTerm {
277    qtuple(s, &[], &[cmd(write(code))])
278}
279pub fn qsym(s: &str) -> QTerm {
280    qleaf(s, s)
281}
282
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub enum QTermTag {
285    Quote(Box<str>, Index, Box<str>),
286    Unquote(Box<str>, Index, Box<str>),
287    Tuple(Box<str>),
288}
289
290impl QTermTag {
291    pub fn tuple(tag: &str) -> Self {
292        QTermTag::Tuple(tag.into())
293    }
294}
295
296impl QTerm {
297    fn cmds(&self) -> &[CmdOrHole] {
298        match self {
299            QTerm::Quote { cmds, .. } | QTerm::Unquote { cmds, .. } | QTerm::Tuple { cmds, .. } => {
300                cmds
301            }
302        }
303    }
304
305    /// Gets the first child of this term without losing whitespace.
306    pub fn squash(&self) -> QTerm {
307        assert!(
308            self.len() == 1,
309            "squash called on term without exactly one child"
310        );
311        let child = &self[0];
312        let self_cmds = self.cmds();
313        let child_cmds = child.cmds();
314        let hole_ind = self_cmds
315            .iter()
316            .position(|cmd| matches!(cmd, CmdOrHole::Hole))
317            .unwrap();
318        let mut cmds = Vec::with_capacity(self_cmds.len() + child_cmds.len() - 1);
319        cmds.extend(self_cmds[..hole_ind].iter().cloned());
320        cmds.extend(child_cmds.iter().cloned());
321        cmds.extend(self_cmds[hole_ind + 1..].iter().cloned());
322        match child {
323            QTerm::Quote {
324                tag,
325                index,
326                lang,
327                term,
328                span,
329                ..
330            } => qquote_at(tag, *index, lang, term.clone(), &cmds, span.clone()),
331            QTerm::Unquote {
332                tag,
333                index,
334                lang,
335                term,
336                span,
337                ..
338            } => qunquote_at(tag, *index, lang, term.clone(), &cmds, span.clone()),
339            QTerm::Tuple { tag, terms, .. } => qtuple(tag, terms, &cmds),
340        }
341    }
342
343    pub fn rewrite_naive(&self, find: &Self, replace: &Self) -> Arc<Self> {
344        if self == find {
345            return arc(replace.clone());
346        }
347        match self {
348            QTerm::Quote {
349                tag,
350                index,
351                lang,
352                term,
353                cmds,
354                span,
355                repr,
356            } => {
357                let term = term.rewrite_naive(find, replace);
358                arc(qquote_repr_at(
359                    tag,
360                    *index,
361                    lang,
362                    term,
363                    cmds,
364                    span.clone(),
365                    *repr,
366                ))
367            }
368            QTerm::Unquote {
369                tag,
370                index,
371                lang,
372                term,
373                cmds,
374                span,
375            } => {
376                let term = term.rewrite_naive(find, replace);
377                arc(qunquote_at(tag, *index, lang, term, cmds, span.clone()))
378            }
379            QTerm::Tuple { tag, terms, cmds } => {
380                let terms = terms
381                    .iter()
382                    .map(|s| s.rewrite_naive(find, replace))
383                    .collect::<Vec<_>>();
384                tuple(tag, &terms, cmds)
385            }
386        }
387    }
388
389    pub fn with_content(&self, content: &str) -> Arc<Self> {
390        match self {
391            QTerm::Tuple { tag, terms, .. } if terms.is_empty() => leaf(tag, content),
392            _ => panic!("with_content: not a leaf: {self:?}"),
393        }
394    }
395
396    pub fn sexp(&self) -> String {
397        match self {
398            QTerm::Quote { lang, term, .. } => {
399                format!("{}↖{}↗", lang, term.sexp())
400            }
401            QTerm::Unquote { lang, term, .. } => {
402                format!("{}↙{}↘", lang, term.sexp())
403            }
404            QTerm::Tuple { tag, terms, .. } => {
405                if terms.is_empty() {
406                    return format!("{tag}");
407                }
408                let mut ret = String::new();
409                ret.push_str(tag);
410                ret.push('(');
411                for (i, term) in terms.iter().enumerate() {
412                    if i > 0 {
413                        ret.push(',');
414                    }
415                    ret.push_str(&term.sexp());
416                }
417                ret.push(')');
418                ret
419            }
420        }
421    }
422}
423
424impl Term for QTerm {
425    type Tag = QTermTag;
426
427    fn tag(&self) -> Self::Tag {
428        match self {
429            QTerm::Quote {
430                tag, index, lang, ..
431            } => QTermTag::Quote(tag.clone(), *index, lang.clone()),
432            QTerm::Unquote {
433                tag, index, lang, ..
434            } => QTermTag::Unquote(tag.clone(), *index, lang.clone()),
435            QTerm::Tuple { tag, .. } => QTermTag::Tuple(tag.clone()),
436        }
437    }
438
439    fn children(&self) -> impl Iterator<Item = &Self> {
440        let ret: Box<dyn Iterator<Item = _>> = match self {
441            QTerm::Quote { term, .. } | QTerm::Unquote { term, .. } => bx(once(term.as_ref())),
442            QTerm::Tuple { terms, .. } => bx(terms.iter().map(|x| x.as_ref())),
443        };
444        ret
445    }
446
447    fn len(&self) -> usize {
448        match self {
449            QTerm::Quote { .. } | QTerm::Unquote { .. } => 1,
450            QTerm::Tuple { terms, .. } => terms.len(),
451        }
452    }
453
454    fn is_empty(&self) -> bool {
455        match self {
456            QTerm::Quote { .. } | QTerm::Unquote { .. } => false,
457            QTerm::Tuple { terms, .. } => terms.is_empty(),
458        }
459    }
460}
461
462impl QTerm {
463    /// Whether this term is a Quilt operator that `Multi::build_nodes` deferred
464    /// to a later stage — `↑`, `←` or `<anno>↓` inside an unresolved quote,
465    /// plugged back in as `leaf(ident_tag, glyph)`.
466    ///
467    /// It matters only when rendering `.quilt` source (see
468    /// [`STerm::coparse_quilt`]): such a glyph is Quilt syntax and must stay
469    /// bare, while the same glyph arriving as escaped content must be written
470    /// `\`-escaped. The two are told apart by the tag. A language's own glyph
471    /// token comes back from its grammar as an anonymous node, which `sym`
472    /// builds with `tag == text` (Lean's bind is `sym("←")`); a deferred
473    /// operator is tagged with the language's *identifier* kind, which never
474    /// spells itself `←`. Anything with children is a fragment, not a leaf.
475    fn is_deferred_operator(&self) -> bool {
476        let QTerm::Tuple { tag, terms, cmds } = self else {
477            return false;
478        };
479        if !terms.is_empty() {
480            return false;
481        }
482        match cmds.as_ref() {
483            [CmdOrHole::Cmd(StrCmd::Write(text))] => {
484                **text != **tag && crate::glyphs::is_deferred_operator(text)
485            }
486            _ => false,
487        }
488    }
489
490    /// Whether this node is a comment **Quilt itself** lexes as raw text — a
491    /// `//` line comment or a `/* … */` block comment.
492    ///
493    /// Both halves of that matter, and only their conjunction is correct
494    /// (#237). The tag says the target language calls this a comment; the
495    /// spelling says Quilt does too. Quilt's grammar has `plain_line_comment`
496    /// and `plain_block_comment` and nothing else, so a `#` or `--` comment is
497    /// *not* raw to it: a `↑` written in a Python comment had to be spelled
498    /// `\↑` in the source, and rendering it back without the `\` would turn it
499    /// into a lift operator. Suppressing escapes on the tag alone would break
500    /// exactly those languages while fixing the C-style ones.
501    fn is_plain_comment(&self) -> bool {
502        matches!(self, QTerm::Tuple { tag, .. } if crate::lang::is_comment_tag(tag))
503            && self
504                .leading_text()
505                .is_some_and(|t| t.starts_with("//") || t.starts_with("/*"))
506    }
507
508    /// The first text this term writes, in document order — how a node's own
509    /// spelling is inspected without rendering the whole subtree.
510    fn leading_text(&self) -> Option<&str> {
511        for cmd in self.cmds() {
512            match cmd {
513                CmdOrHole::Cmd(StrCmd::Write(s)) if !s.is_empty() => return Some(s),
514                CmdOrHole::Cmd(_) => {}
515                CmdOrHole::Hole => return self.children().next().and_then(Self::leading_text),
516            }
517        }
518        None
519    }
520}
521
522impl STerm for QTerm {
523    fn write<W: std::io::Write>(&self, writer: &mut PrefixWriter<'_, W>) {
524        match self {
525            QTerm::Quote { term, cmds, .. } | QTerm::Unquote { term, cmds, .. } => {
526                // A quote's own `cmds` are the arrows and the language
527                // annotation — Quilt syntax, not content — so they are never
528                // escaped, however the body is written.
529                let outer = writer.set_escaping(false);
530                let outer_bracketed = writer.bracketed();
531                for cmd in cmds {
532                    match cmd {
533                        CmdOrHole::Cmd(cmd) => writer.interpret(cmd),
534                        CmdOrHole::Hole => {
535                            writer.set_escaping(outer);
536                            writer.set_bracketed(true);
537                            term.write(writer);
538                            writer.set_bracketed(outer_bracketed);
539                            writer.set_escaping(false);
540                        }
541                    }
542                }
543                writer.set_escaping(outer);
544            }
545            QTerm::Tuple { terms, cmds, .. } => {
546                // Two kinds of node hold text that is *not* escapable content,
547                // and writing a `\` into either corrupts it:
548                //
549                // * a deferred Quilt operator, which is Quilt syntax the next
550                //   stage still has to read (#223);
551                // * a comment, whose body the Quilt grammar treats as raw text,
552                //   so a `\` there is a literal backslash and not an escape
553                //   (#237). Suppressing for the whole subtree is right: the
554                //   node's children are the comment's own tokens.
555                let raw =
556                    (writer.bracketed() && self.is_deferred_operator()) || self.is_plain_comment();
557                let outer = if raw {
558                    writer.set_escaping(false)
559                } else {
560                    writer.escaping()
561                };
562                let mut children = terms.iter();
563                for cmd in cmds {
564                    match cmd {
565                        CmdOrHole::Cmd(cmd) => writer.interpret(cmd),
566                        CmdOrHole::Hole => children.next().unwrap().write(writer),
567                    }
568                }
569                writer.set_escaping(outer);
570            }
571        }
572    }
573}
574
575impl std::ops::Index<usize> for QTerm {
576    type Output = QTerm;
577
578    fn index(&self, index: usize) -> &Self::Output {
579        self.get(index).unwrap()
580    }
581}
582
583impl Validate for QTerm {
584    type Error = miette::Error;
585
586    fn validate(self) -> Result<Self, Self::Error> {
587        let mut depth: u32 = 0;
588        let mut holes = 0;
589        for cmd in self.cmds() {
590            match cmd {
591                CmdOrHole::Cmd(cmd) => match cmd {
592                    StrCmd::Push(_) => depth += 1,
593                    StrCmd::Pop => {
594                        if depth == 0 {
595                            miette::bail!("running stack depth below 0");
596                        }
597                        depth -= 1;
598                    }
599                    _ => (),
600                },
601                CmdOrHole::Hole => {
602                    holes += 1;
603                }
604            }
605        }
606        if depth != 0 {
607            miette::bail!("total stack depth not 0");
608        }
609        if holes != self.len() {
610            miette::bail!("number of holes does not match number of children");
611        }
612        Ok(self)
613    }
614}
615
616/**************************************************************/
617
618pub struct QTermBuilder {
619    tag: QTermTag,
620    children: Vec<Arc<QTerm>>,
621    cmds: Vec<CmdOrHole>,
622    /// Source span for the built Quote/Unquote (ignored for Tuple).
623    span: Option<Span>,
624    /// The built Quote's representation (ignored otherwise).
625    repr: Repr,
626    /// The open separated region, if any (see [`QTermBuilder::sep`]).
627    sep: Option<Separated>,
628    /// Inside an [`align`](QTermBuilder::align): text is laid out at the
629    /// hole's column.
630    aligned: bool,
631}
632
633/// A run of children that must be separated by `token` — the elements a
634/// splice contributes to a comma-separated list (#293).
635struct Separated {
636    token: Box<str>,
637    /// Where in `cmds` the hole of the region's last element is, once there is
638    /// one. A separator token the author placed resets it: what follows that
639    /// token is already separated.
640    last: Option<usize>,
641}
642
643impl Separated {
644    /// Whether `child` is the separator itself, as `sym(token)` builds it.
645    fn is_token(&self, child: &QTerm) -> bool {
646        match child {
647            QTerm::Tuple { tag, terms, cmds } => {
648                **tag == *self.token
649                    && terms.is_empty()
650                    && matches!(&**cmds, [CmdOrHole::Cmd(StrCmd::Write(s))] if **s == *self.token)
651            }
652            _ => false,
653        }
654    }
655}
656
657impl QTermBuilder {
658    pub fn new(tag: QTermTag) -> Self {
659        Self {
660            tag,
661            children: Vec::new(),
662            cmds: Vec::new(),
663            span: None,
664            repr: Repr::Cst,
665            sep: None,
666            aligned: false,
667        }
668    }
669
670    pub fn span(&mut self, span: Span) -> &mut Self {
671        self.span = Some(span);
672        self
673    }
674
675    /// Set the built Quote's [`Repr`].
676    pub fn repr(&mut self, repr: Repr) -> &mut Self {
677        self.repr = repr;
678        self
679    }
680
681    pub fn child(&mut self, child: &Arc<QTerm>) -> &mut Self {
682        if let Some(sep) = &mut self.sep {
683            if sep.is_token(child) {
684                sep.last = None;
685            } else {
686                if let Some(at) = sep.last {
687                    let between = &self.cmds[at + 1..];
688                    let placed = between.iter().any(
689                        |c| matches!(c, CmdOrHole::Cmd(StrCmd::Write(s)) if s.contains(&*sep.token)),
690                    );
691                    if !placed {
692                        // Right after the previous element, so a newline the
693                        // author put between the two lands after the
694                        // separator; a space only if nothing else is there.
695                        // No hole follows `at` (it is the region's last), so
696                        // the separator's child goes last too.
697                        let adjacent = between.is_empty();
698                        self.cmds.insert(at + 1, CmdOrHole::Hole);
699                        self.children.push(sym(&sep.token));
700                        if adjacent {
701                            self.cmds.push(CmdOrHole::Cmd(StrCmd::Write(" ".into())));
702                        }
703                    }
704                }
705                sep.last = Some(self.cmds.len());
706            }
707        }
708        self.cmds.push(CmdOrHole::Hole);
709        self.children.push(child.clone());
710        self
711    }
712
713    /// Open a separated region: until [`end_sep`](Self::end_sep), two
714    /// children added one after the other get `token` and a space between
715    /// them (#293).
716    ///
717    /// Expanded code opens one around a splice into a comma-separated list —
718    /// `[↙xs↘]`, `f(↙xs↘)` — so the elements a `Vec` or a loop of `←`
719    /// contributes come out `[1, 2]` instead of `[12]`. A separator the author
720    /// placed is kept rather than doubled: emitting `sym(token)` (or writing
721    /// text containing it) between two elements leaves them alone.
722    pub fn sep(&mut self, token: &str) -> &mut Self {
723        self.sep = Some(Separated {
724            token: token.into(),
725            last: None,
726        });
727        self
728    }
729
730    /// Close the region [`sep`](Self::sep) opened.
731    pub fn end_sep(&mut self) -> &mut Self {
732        self.sep = None;
733        self
734    }
735
736    pub fn cmd(&mut self, cmd: &StrCmd) -> &mut Self {
737        self.cmds.push(CmdOrHole::Cmd(cmd.clone()));
738        self
739    }
740
741    pub fn build(self) -> QTerm {
742        match self.tag {
743            QTermTag::Quote(tag, index, lang) => {
744                assert_eq!(self.children.len(), 1);
745                let mut q = qquote_at(
746                    &tag,
747                    index,
748                    &lang,
749                    self.children[0].clone(),
750                    &self.cmds,
751                    self.span,
752                );
753                if let QTerm::Quote { repr, .. } = &mut q {
754                    *repr = self.repr;
755                }
756                q
757            }
758            QTermTag::Unquote(tag, index, lang) => {
759                assert_eq!(self.children.len(), 1);
760                qunquote_at(
761                    &tag,
762                    index,
763                    &lang,
764                    self.children[0].clone(),
765                    &self.cmds,
766                    self.span,
767                )
768            }
769            QTermTag::Tuple(tag) => qtuple(&tag, &self.children, &self.cmds),
770        }
771    }
772
773    pub fn first(self) -> Option<Arc<QTerm>> {
774        self.children.first().cloned()
775    }
776
777    // convenience methods
778
779    pub fn write(&mut self, s: &str) -> &mut Self {
780        if s.is_empty() {
781            self
782        } else {
783            self.cmd(&StrCmd::Write(s.into()))
784        }
785    }
786
787    pub fn nl(&mut self) -> &mut Self {
788        self.cmd(&StrCmd::NewLine)
789    }
790
791    pub fn push(&mut self, s: &str) -> &mut Self {
792        // unlike write, we must push an empty string to avoid unmatched pops
793        // assert!(!s.is_empty());
794        self.cmd(&StrCmd::Push(s.into()))
795    }
796
797    pub fn pop(&mut self) -> &mut Self {
798        self.aligned = false;
799        self.cmd(&StrCmd::Pop)
800    }
801
802    /// Push `pad`, the indent that aligns a splice to its hole's column, for
803    /// the length of the splice (up to the next [`pop`](Self::pop)).
804    ///
805    /// The same push as [`push`](Self::push) for a term: its own newlines
806    /// write the prefix. The difference is for text: `\n` in a `&str` emitted
807    /// here is written as a newline too, so its later lines start at the
808    /// hole's column instead of flush left, as a term's would (#310).
809    /// Expanded code spells the push of an aligned splice this way (see
810    /// [`is_aligned_splice`](crate::term::is_aligned_splice)), which only a
811    /// column-sensitive language has.
812    pub fn align(&mut self, pad: &str) -> &mut Self {
813        self.push(pad);
814        self.aligned = true;
815        self
816    }
817
818    /// Write `s` as text spliced into this builder: as one
819    /// [`write`](Self::write), except inside an [`align`](Self::align), where
820    /// each line break is a [`nl`](Self::nl).
821    pub fn text(&mut self, s: &str) -> &mut Self {
822        if !self.aligned {
823            return self.write(s);
824        }
825        for (i, line) in s.split('\n').enumerate() {
826            if i > 0 {
827                self.nl();
828            }
829            self.write(line);
830        }
831        self
832    }
833
834    pub fn emit(&mut self, x: impl Emit) -> &mut Self {
835        x.emit(self);
836        self
837    }
838
839    pub fn write_if(&mut self, s: &str, b: bool) -> &mut Self {
840        if b && !s.is_empty() {
841            self.cmd(&StrCmd::Write(s.into()))
842        } else {
843            self
844        }
845    }
846
847    pub fn nl_if(&mut self, b: bool) -> &mut Self {
848        if b {
849            self.cmd(&StrCmd::NewLine)
850        } else {
851            self
852        }
853    }
854
855    pub fn push_if(&mut self, s: &str, b: bool) -> &mut Self {
856        if b {
857            self.cmd(&StrCmd::Push(s.into()))
858        } else {
859            self
860        }
861    }
862
863    pub fn pop_if(&mut self, b: bool) -> &mut Self {
864        if b {
865            self.cmd(&StrCmd::Pop)
866        } else {
867            self
868        }
869    }
870
871    pub fn c(mut self, child: &Arc<QTerm>) -> Self {
872        self.child(child);
873        self
874    }
875    pub fn w(mut self, s: &str) -> Self {
876        self.write(s);
877        self
878    }
879    pub fn n(mut self) -> Self {
880        self.nl();
881        self
882    }
883    pub fn p(mut self, s: &str) -> Self {
884        self.push(s);
885        self
886    }
887    pub fn x(mut self) -> Self {
888        self.pop();
889        self
890    }
891    pub fn e(mut self, x: impl Emit) -> Self {
892        self.emit(x);
893        self
894    }
895    pub fn b(self) -> Arc<QTerm> {
896        arc(self.build())
897    }
898}
899
900pub fn qb(tag: &str, index: Index, lang: &str) -> QTermBuilder {
901    QTermBuilder::new(QTermTag::Quote(tag.into(), index, lang.into()))
902}
903pub fn ub(tag: &str, index: Index, lang: &str) -> QTermBuilder {
904    QTermBuilder::new(QTermTag::Unquote(tag.into(), index, lang.into()))
905}
906pub fn tb(tag: &str) -> QTermBuilder {
907    QTermBuilder::new(QTermTag::Tuple(tag.into()))
908}
909
910/**************************************************************/
911
912/// What a child of a variadic node may contribute to its parent's builder:
913/// exactly one term, several, or none.
914///
915/// # Why the impls are all on references
916///
917/// Expanded code calls this as `x.emit(&mut b_);`, where `x` is whatever
918/// expression the author unquoted. Implementing it for `Arc<QTerm>` made that
919/// call **move** `x` — fine when `x` is a freshly built term, fatal when the
920/// author named it and used it twice:
921///
922/// ```text
923/// let name = ident(&format!("pow{n}"));
924/// decls.push(lean↖def ↙name↘ (x : Nat) : Nat := ↙body(n)↘↗);
925/// decls.push(lean↖theorem ↙lemma↘ : ↙name↘ x = x ^ ↑n := by simp [↙name↘]↗);
926/// //                                  ^^^^ E0382: use of moved value
927/// ```
928///
929/// Nothing here needs ownership — every impl only reads — so the impls are on
930/// `&T` instead, and method-call auto-ref makes `x.emit(&mut b_)` borrow. The
931/// generated spelling is unchanged; it just stopped consuming its argument.
932///
933/// This only became reachable when the variadic tables started following the
934/// grammars (#202): with two tags per language, an unquote almost never sat
935/// directly under a variadic node, so the accumulator form was rare.
936pub trait Emit {
937    fn emit(self, builder: &mut QTermBuilder);
938}
939
940impl Emit for &Arc<QTerm> {
941    fn emit(self, builder: &mut QTermBuilder) {
942        builder.child(self);
943    }
944}
945
946impl Emit for &() {
947    fn emit(self, _builder: &mut QTermBuilder) {}
948}
949
950/// A child that contributes several terms — what `←` produces.
951///
952/// The bound is `&T: Emit` rather than `T: Emit` so the elements are borrowed
953/// out of the vector too, keeping the whole chain non-consuming.
954impl<'a, T> Emit for &'a Vec<T>
955where
956    &'a T: Emit,
957{
958    fn emit(self, builder: &mut QTermBuilder) {
959        for item in self {
960            item.emit(builder);
961        }
962    }
963}
964
965impl Emit for &str {
966    fn emit(self, builder: &mut QTermBuilder) {
967        builder.text(self);
968    }
969}
970
971/// Text, as for `&str`. A lone `String` already reached the `&str` impl by
972/// auto-deref; this is for where nothing derefs — the elements of a
973/// `Vec<String>`, which the `&Vec<T>` impl borrows as `&String`. There is no
974/// impl for `String` itself: method resolution would pick it before any
975/// borrow, and the emit would move the string.
976impl Emit for &String {
977    fn emit(self, builder: &mut QTermBuilder) {
978        builder.text(self);
979    }
980}
981
982/// A reference to anything that emits by reference: the elements of a
983/// `Vec<&str>`, `Vec<&String>` or `Vec<&Arc<QTerm>>`, which the `&Vec<T>`
984/// impl borrows once more.
985impl<'a, T: ?Sized> Emit for &&'a T
986where
987    &'a T: Emit,
988{
989    fn emit(self, builder: &mut QTermBuilder) {
990        (*self).emit(builder);
991    }
992}
993
994impl Emit for &StrCmd {
995    fn emit(self, builder: &mut QTermBuilder) {
996        builder.cmd(self);
997    }
998}
999
1000#[allow(unused_macros)]
1001macro_rules! emit {
1002    // WARN: doing `$b.emit(&$e);` will cause double-borrow errors in nested cases
1003    ($b:expr, $e:expr) => {
1004        $e.emit(&mut $b);
1005    };
1006    ($b:expr, $e:expr, $($rest:expr),+) => {
1007        emit!($b, $e);
1008        emit!($b, $($rest),+);
1009    };
1010}
1011
1012/**************************************************************/
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017
1018    #[test]
1019    fn emit() {
1020        let mut b_ = tb("block");
1021        sym("a").emit(&mut b_);
1022        ().emit(&mut b_);
1023        vec![sym("b"), sym("c")].emit(&mut b_);
1024        let qterm = b_.build();
1025
1026        let expected = tb("block").c(&sym("a")).c(&sym("b")).c(&sym("c")).build();
1027        assert_eq!(qterm, expected);
1028    }
1029
1030    /// Emitting a named term must not consume it.
1031    ///
1032    /// This is the shape expanded code produces for a variadic node with an
1033    /// unquoted child, and authors reuse such a binding constantly — `let name
1034    /// = ident(…)` used in both a `def` and the theorem about it. While `Emit`
1035    /// was implemented for `Arc<QTerm>` the emit *moved* it, so the second use
1036    /// was E0382 and the generated program did not compile.
1037    ///
1038    /// It is a compile-time property, so the assertion is that this function
1039    /// builds at all; the equality below just keeps it honest about emitting
1040    /// the same term twice rather than dropping one.
1041    #[test]
1042    fn emit_borrows_rather_than_consuming() {
1043        let name = sym("a");
1044        let mut b_ = tb("block");
1045        name.emit(&mut b_);
1046        // Still usable: the emit above borrowed it.
1047        name.emit(&mut b_);
1048        let terms = vec![sym("b")];
1049        terms.emit(&mut b_);
1050        terms.emit(&mut b_);
1051        assert_eq!(name, sym("a"));
1052
1053        let expected = tb("block")
1054            .c(&sym("a"))
1055            .c(&sym("a"))
1056            .c(&sym("b"))
1057            .c(&sym("b"))
1058            .build();
1059        assert_eq!(b_.build(), expected);
1060    }
1061
1062    #[test]
1063    fn emit_macro() {
1064        let mut b_ = tb("block");
1065        emit!(b_, sym("a"), (), vec![sym("b"), sym("c")]);
1066        let qterm = b_.build();
1067
1068        let expected = tb("block").c(&sym("a")).c(&sym("b")).c(&sym("c")).build();
1069        assert_eq!(qterm, expected);
1070    }
1071
1072    #[test]
1073    fn emit_macro_nested() {
1074        let mut b_ = tb("block");
1075        emit!(b_, sym("a"), {
1076            emit!(b_, sym("b"));
1077            sym("c")
1078        });
1079        let qterm = b_.build();
1080
1081        let expected = tb("block").c(&sym("a")).c(&sym("b")).c(&sym("c")).build();
1082        assert_eq!(qterm, expected);
1083    }
1084
1085    /// A term with `span`s set, nested inside a tuple, survives postcard.
1086    ///
1087    /// This is the guard the `span` fields' "no serde skip" comments ask for.
1088    /// The shared runtime corpus round-trips every shape it builds
1089    /// (`conformance/runtime/cases.json`, issue #192), but those terms are all
1090    /// *constructed*, so their spans are all `None` — and a `None` that is
1091    /// dropped on both ends re-encodes to the same bytes and coparses to the
1092    /// same text, so the corpus cannot see it go. Only a parsed term carries a
1093    /// span, and only Rust can build one, so the check lives here.
1094    ///
1095    /// It has to assert on the spans directly: [`PartialEq`] ignores them by
1096    /// design and `coparse` never renders them, so the two obvious assertions
1097    /// both pass on a term that lost them.
1098    #[test]
1099    fn postcard_round_trip_preserves_spans() {
1100        let inner = qunquote_at("x", 1, "rs", sym("n"), &[HOLE], Some(7..12)).into();
1101        let quoted = qquote_at("q", 0, "py", inner, &[HOLE], Some(3..20)).into();
1102        let term: Arc<QTerm> = tb("block").w("[").c(&quoted).w("]").b();
1103
1104        let bytes = postcard::to_allocvec(&term).expect("serializes");
1105        let back: Arc<QTerm> = postcard::from_bytes(&bytes).expect("deserializes");
1106
1107        assert_eq!(back, term, "round trip changed the tree");
1108        assert_eq!(
1109            back.coparse(),
1110            term.coparse(),
1111            "round trip changed the text"
1112        );
1113        assert_eq!(
1114            postcard::to_allocvec(&back).expect("re-serializes"),
1115            bytes,
1116            "round trip re-serializes to different bytes"
1117        );
1118
1119        // The part neither equality above can see.
1120        let QTerm::Tuple { terms, .. } = &*back else {
1121            panic!("expected a tuple");
1122        };
1123        let QTerm::Quote { span, term, .. } = &*terms[0] else {
1124            panic!("expected a quote");
1125        };
1126        assert_eq!(*span, Some(3..20), "the quote's span was lost");
1127        let QTerm::Unquote { span, .. } = &**term else {
1128            panic!("expected an unquote");
1129        };
1130        assert_eq!(*span, Some(7..12), "the nested unquote's span was lost");
1131    }
1132
1133    /// A separated region puts `, ` between the elements added in it, keeps a
1134    /// separator the author placed, and leaves the rest of the node alone.
1135    #[test]
1136    fn sep_separates_the_elements_of_a_region() {
1137        let elems = vec![sym("a"), sym("b"), sym("c")];
1138        let mut b_ = tb("array_expression");
1139        sym("[").emit(&mut b_);
1140        b_.sep(",");
1141        elems.emit(&mut b_);
1142        b_.end_sep();
1143        sym("]").emit(&mut b_);
1144        let built = b_.b();
1145        assert_eq!(built.coparse(), "[a, b, c]");
1146        // The separator is a child, as the parser would have made it.
1147        let QTerm::Tuple { terms, .. } = &*built else {
1148            panic!("expected a tuple");
1149        };
1150        assert_eq!(terms.len(), 7);
1151        assert_eq!(terms[2], sym(","));
1152
1153        // A newline between two elements lands after the separator.
1154        let mut b_ = tb("arguments");
1155        b_.sep(",");
1156        sym("a").emit(&mut b_);
1157        b_.nl();
1158        sym("b").emit(&mut b_);
1159        assert_eq!(b_.b().coparse(), "a,\nb");
1160
1161        // Separators already there are not doubled.
1162        let mut b_ = tb("arguments");
1163        b_.sep(",");
1164        sym("a").emit(&mut b_);
1165        sym(",").emit(&mut b_);
1166        b_.write(" ");
1167        sym("b").emit(&mut b_);
1168        b_.write(", ");
1169        sym("c").emit(&mut b_);
1170        assert_eq!(b_.b().coparse(), "a, b, c");
1171
1172        // Outside a region, nothing is inserted.
1173        let mut b_ = tb("arguments");
1174        b_.sep(",");
1175        sym("a").emit(&mut b_);
1176        b_.end_sep();
1177        sym("b").emit(&mut b_);
1178        assert_eq!(b_.b().coparse(), "ab");
1179    }
1180
1181    /// Text emitted inside an `align` is laid out at the hole's column: each
1182    /// line break is a newline, which writes the pad. Outside one it is a
1183    /// single write, line breaks and all.
1184    #[test]
1185    fn text_in_an_aligned_splice_keeps_its_column() {
1186        let mut b_ = tb("def");
1187        b_.write("def x := ");
1188        b_.align("         ");
1189        "{ a := 1,\n  b := 2 }".emit(&mut b_);
1190        b_.pop();
1191        assert_eq!(b_.b().coparse(), "def x := { a := 1,\n           b := 2 }");
1192
1193        let mut b_ = tb("def");
1194        b_.write("def x := ");
1195        b_.push("         ");
1196        "{ a := 1,\n  b := 2 }".emit(&mut b_);
1197        b_.pop();
1198        "\nc".emit(&mut b_);
1199        assert_eq!(b_.b().coparse(), "def x := { a := 1,\n  b := 2 }\nc");
1200    }
1201
1202    /// Owned and borrowed strings emit as text wherever a `&str` does, alone
1203    /// or as the elements of a `Vec` — and, like every other emit, without
1204    /// consuming them.
1205    #[test]
1206    fn strings_emit_as_text() {
1207        let s = String::from("a");
1208        let owned = vec![String::from("b"), String::from("c")];
1209        let strs = vec!["d", "e"];
1210        let refs: Vec<&String> = owned.iter().collect();
1211        let terms = [sym("f")];
1212        let term_refs: Vec<&Arc<QTerm>> = terms.iter().collect();
1213
1214        let mut b_ = tb("block");
1215        s.emit(&mut b_);
1216        (&s).emit(&mut b_);
1217        owned.emit(&mut b_);
1218        strs.emit(&mut b_);
1219        refs.emit(&mut b_);
1220        term_refs.emit(&mut b_);
1221        // Still usable: each emit above borrowed.
1222        assert_eq!((s.as_str(), owned.len()), ("a", 2));
1223        assert_eq!(b_.b().coparse(), "aabcdebcf");
1224    }
1225}