Skip to main content

quilt/langs/text/
lang.rs

1//! Plain text: quote an arbitrary fragment with no language-specific parsing.
2//!
3//! Text has no grammar, so "parsing" is just recording the literal runs and the
4//! holes between them. The resulting term is a single `text` tuple whose `cmds`
5//! interleave the writes and the holes, which is exactly what serialization
6//! needs and nothing more.
7//!
8//! This used to be four `todo!()`s — so `text↖…↗` panicked rather than erroring,
9//! the last of the panics issue #11 set out to remove. The conformance battery
10//! (#144) treats a panic as a hard failure for every language including the
11//! unsupported cases, which is what surfaced it.
12
13use crate::lang::{Arity, Comments, FlatNode, Hole, InnerKind, Language, LanguagePost};
14use crate::prelude::*;
15use crate::qterm::QTerm;
16use crate::term::CmdOrHole;
17use miette::bail;
18
19/**************************************************************/
20
21/// The tag every text fragment carries. Text has no node kinds, so one tag is
22/// the whole vocabulary.
23pub const TEXT_TAG: &str = "text";
24
25/// Flatten `code` into the `cmds` sequence of a `text` tuple, counting holes.
26fn build(code: &[FlatNode]) -> (Vec<CmdOrHole>, usize) {
27    let mut cmds = Vec::with_capacity(code.len());
28    let mut holes = 0;
29    for node in code {
30        match node {
31            FlatNode::Str(s) => cmds.push(cmd(write(s))),
32            FlatNode::NewLine => cmds.push(cmd(NL)),
33            FlatNode::Hole | FlatNode::Splice => {
34                cmds.push(HOLE);
35                holes += 1;
36            }
37        }
38    }
39    (cmds, holes)
40}
41
42#[derive(Default)]
43pub struct TextLanguage;
44
45impl Language for TextLanguage {
46    type Post = TextLanguagePost;
47
48    fn parse_pre(&mut self, _ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
49        Ok(TextLanguagePost::new(code))
50    }
51
52    /// A text fragment is an opaque run of characters — never a statement or an
53    /// item, so hosts splice it as a value.
54    fn typ(&self, _tag: &str) -> InnerKind {
55        InnerKind::Expr
56    }
57
58    /// Text has no nesting, so it accepts as many spliced children as the
59    /// author writes holes for.
60    fn arity(&self, _tag: &str) -> Arity {
61        Arity::Variadic
62    }
63}
64
65#[derive(Debug)]
66pub struct TextLanguagePost {
67    cmds: Box<[CmdOrHole]>,
68    holes: Box<[Hole]>,
69}
70
71impl TextLanguagePost {
72    fn new(code: &[FlatNode]) -> Self {
73        let (cmds, n) = build(code);
74        let holes = (0..n)
75            .map(|_| Hole {
76                otag: TEXT_TAG.into(),
77                // Anything can be spliced into text; the host decides how the
78                // child renders, so we impose no kind.
79                ikind: None,
80                prefix: Box::default(),
81            })
82            .collect();
83        Self {
84            cmds: cmds.into(),
85            holes,
86        }
87    }
88}
89
90impl LanguagePost for TextLanguagePost {
91    fn holes(&self) -> &[Hole] {
92        &self.holes
93    }
94
95    fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
96        if plugs.len() != self.holes.len() {
97            bail!(
98                "text: expected {} spliced term(s), got {}",
99                self.holes.len(),
100                plugs.len()
101            );
102        }
103        Ok(crate::qterm::tuple(TEXT_TAG, plugs, &self.cmds))
104    }
105}
106
107impl Comments for TextLanguage {
108    /// Plain text has no comment syntax, so every spelling would corrupt the
109    /// output rather than annotate it.
110    const LINE: Option<&'static str> = None;
111}
112
113/**************************************************************/
114
115#[derive(Default)]
116pub struct DynTextLanguage;
117
118impl Language for DynTextLanguage {
119    type Post = Box<dyn LanguagePost>;
120
121    fn parse_pre(&mut self, _ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
122        Ok(bx(TextLanguagePost::new(code)))
123    }
124
125    fn typ(&self, _tag: &str) -> InnerKind {
126        InnerKind::Expr
127    }
128
129    fn arity(&self, _tag: &str) -> Arity {
130        Arity::Variadic
131    }
132}
133
134/**************************************************************/
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use crate::lang::flat_nodes;
140    use crate::term::{STerm as _, Term as _};
141
142    #[test]
143    fn roundtrips_literal_text() -> Result<()> {
144        let mut lang = TextLanguage;
145        let term = lang.parse(&flat_nodes("hello, world"))?;
146        assert_eq!(term.coparse(), "hello, world");
147        assert_eq!(term.tag(), crate::qterm::QTermTag::tuple(TEXT_TAG));
148        Ok(())
149    }
150
151    #[test]
152    fn roundtrips_multiline_text() -> Result<()> {
153        let mut lang = TextLanguage;
154        let src = "line one\nline two\n\nline four";
155        assert_eq!(lang.parse(&flat_nodes(src))?.coparse(), src);
156        Ok(())
157    }
158
159    #[test]
160    fn splices_holes_in_order() -> Result<()> {
161        let mut lang = TextLanguage;
162        let code = [
163            FlatNode::Str("a="),
164            FlatNode::Hole,
165            FlatNode::Str(" b="),
166            FlatNode::Hole,
167        ];
168        let term = lang.parse_with(&code, &[leaf(TEXT_TAG, "1"), leaf(TEXT_TAG, "2")])?;
169        assert_eq!(term.coparse(), "a=1 b=2");
170        Ok(())
171    }
172
173    /// The stub used to `todo!()`; a wrong plug count must be an error.
174    #[test]
175    fn wrong_plug_count_is_an_error() -> Result<()> {
176        let mut lang = TextLanguage;
177        let post = lang.parse_pre(None, &[FlatNode::Hole])?;
178        let err = post.parse_post(&[]).unwrap_err();
179        assert!(err.to_string().contains("expected 1"), "{err}");
180        Ok(())
181    }
182}