Skip to main content

quilt/
term.rs

1use crate::prelude::*;
2use crate::{
3    strcmd::{PrefixWriter, StrCmd},
4    validate::Validate,
5};
6use miette::IntoDiagnostic;
7use serde::{Deserialize, Serialize};
8use std::{io::Write, sync::Arc};
9
10/**************************************************************/
11
12pub trait Term: Sized {
13    type Tag;
14
15    fn tag(&self) -> Self::Tag;
16    fn children(&self) -> impl Iterator<Item = &Self>;
17    fn len(&self) -> usize {
18        self.children().count()
19    }
20    fn is_empty(&self) -> bool {
21        self.len() == 0
22    }
23    fn get(&self, i: usize) -> Option<&Self> {
24        self.children().nth(i)
25    }
26}
27
28/**************************************************************/
29
30pub struct ArcTerm<T: Clone> {
31    tag: T,
32    children: Box<[Arc<Self>]>,
33}
34
35impl<T: Clone> Term for ArcTerm<T> {
36    type Tag = T;
37
38    fn tag(&self) -> Self::Tag {
39        self.tag.clone()
40    }
41
42    fn children(&self) -> impl Iterator<Item = &Self> {
43        self.children.iter().map(|x| x.as_ref())
44    }
45
46    fn len(&self) -> usize {
47        self.children.len()
48    }
49
50    fn is_empty(&self) -> bool {
51        self.children.is_empty()
52    }
53}
54
55impl<T: Clone> Term for Arc<ArcTerm<T>> {
56    type Tag = T;
57
58    fn tag(&self) -> Self::Tag {
59        self.tag.clone()
60    }
61
62    fn children(&self) -> impl Iterator<Item = &Self> {
63        self.children.iter()
64    }
65
66    fn len(&self) -> usize {
67        self.children.len()
68    }
69
70    fn is_empty(&self) -> bool {
71        self.children.is_empty()
72    }
73}
74
75/**************************************************************/
76
77pub trait STerm: Term {
78    fn write<W: Write>(&self, writer: &mut PrefixWriter<'_, W>);
79
80    fn coparse(&self) -> String {
81        let mut buf = Vec::new();
82        let mut writer = PrefixWriter::new(&mut buf);
83        self.write(&mut writer);
84        String::from_utf8(buf).unwrap()
85    }
86
87    /// Render as `.quilt` **source** rather than as target output: a Quilt
88    /// glyph sitting in content is written `\`-escaped, the way it has to be
89    /// spelled for the result to parse back to the same term.
90    ///
91    /// This is the inverse of parsing, and [`Self::coparse`] is not: a term is
92    /// written twice in this project, once as the file it came from and once as
93    /// the code it generates, and the two disagree exactly on glyphs. `↑` in
94    /// generated Lean is a coercion and must stay bare; the same `↑` in the
95    /// `.quilt` file it was written in is the lift operator unless it carries a
96    /// `\`. `coparse` kept the second reading for both, so any source with an
97    /// escaped glyph did not survive a round trip — and for `←` and `⟨` did not
98    /// even re-parse (#223).
99    ///
100    /// Use this for anything that renders a *parsed, unexpanded* term back to a
101    /// file; use [`Self::coparse`] for expander output.
102    fn coparse_quilt(&self) -> String {
103        let mut buf = Vec::new();
104        let mut writer = PrefixWriter::quilt(&mut buf);
105        self.write(&mut writer);
106        String::from_utf8(buf).unwrap()
107    }
108
109    fn dump(&self, filename: &str) -> Result<()> {
110        let mut file = std::fs::File::create(filename).into_diagnostic()?;
111        let mut writer = PrefixWriter::new(&mut file);
112        self.write(&mut writer);
113        Ok(())
114    }
115
116    fn dump_with_cmds(&self, filename: &str, prefix: &[StrCmd], suffix: &[StrCmd]) -> Result<()> {
117        let mut file = std::fs::File::create(filename).into_diagnostic()?;
118        let mut writer = PrefixWriter::new(&mut file);
119        for cmd in prefix {
120            writer.interpret(cmd);
121        }
122        self.write(&mut writer);
123        for cmd in suffix {
124            writer.interpret(cmd);
125        }
126        Ok(())
127    }
128}
129
130/**************************************************************/
131
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub enum CmdOrHole {
134    Cmd(StrCmd),
135    Hole,
136}
137
138pub fn cmd(cmd: StrCmd) -> CmdOrHole {
139    CmdOrHole::Cmd(cmd)
140}
141pub fn hole() -> CmdOrHole {
142    CmdOrHole::Hole
143}
144
145pub const HOLE: CmdOrHole = CmdOrHole::Hole;
146
147/// Whether the `Push` at `cmds[k]` aligns a splice to its column: a push, the
148/// hole, then the pop. A language whose layout is column-sensitive wraps each
149/// one-line splice in exactly that (`TSProvider::align_splices`, #301), and
150/// nothing else puts a hole straight after a push — a quoted line break pushes
151/// its indent and then writes the newline. Expanded code spells such a push
152/// `align` rather than `push`, so that host text spliced there is laid out at
153/// the hole's column as a term is (#310; see `QTermBuilder::align`).
154#[must_use]
155pub fn is_aligned_splice(cmds: &[CmdOrHole], k: usize) -> bool {
156    matches!(
157        cmds.get(k..k + 3),
158        Some([
159            CmdOrHole::Cmd(StrCmd::Push(_)),
160            CmdOrHole::Hole,
161            CmdOrHole::Cmd(StrCmd::Pop)
162        ])
163    )
164}
165
166#[derive(Debug, Clone)]
167pub struct ArcSTerm<T> {
168    tag: T,
169    children: Box<[Arc<Self>]>,
170    cmds: Box<[CmdOrHole]>,
171}
172
173impl<T: Clone> Term for ArcSTerm<T> {
174    type Tag = T;
175
176    fn tag(&self) -> Self::Tag {
177        self.tag.clone()
178    }
179
180    fn children(&self) -> impl Iterator<Item = &Self> {
181        self.children.iter().map(|x| x.as_ref())
182    }
183
184    fn len(&self) -> usize {
185        self.children.len()
186    }
187
188    fn is_empty(&self) -> bool {
189        self.children.is_empty()
190    }
191}
192
193impl<T: Clone> Term for Arc<ArcSTerm<T>> {
194    type Tag = T;
195
196    fn tag(&self) -> Self::Tag {
197        self.tag.clone()
198    }
199
200    fn children(&self) -> impl Iterator<Item = &Self> {
201        self.children.iter()
202    }
203
204    fn len(&self) -> usize {
205        self.children.len()
206    }
207
208    fn is_empty(&self) -> bool {
209        self.children.is_empty()
210    }
211}
212
213impl<T: Clone> STerm for ArcSTerm<T> {
214    fn write<W: Write>(&self, writer: &mut PrefixWriter<'_, W>) {
215        let mut children = self.children.iter();
216        for cmd in &self.cmds {
217            match cmd {
218                CmdOrHole::Cmd(cmd) => writer.interpret(cmd),
219                CmdOrHole::Hole => children.next().unwrap().write(writer),
220            }
221        }
222    }
223}
224
225impl<T> Validate for ArcSTerm<T> {
226    type Error = miette::Error;
227
228    fn validate(self) -> Result<Self, Self::Error> {
229        let mut depth: u32 = 0;
230        let mut holes = 0;
231        for cmd in &self.cmds {
232            match cmd {
233                CmdOrHole::Cmd(cmd) => match cmd {
234                    StrCmd::Push(_) => depth += 1,
235                    StrCmd::Pop => {
236                        if depth == 0 {
237                            miette::bail!("running stack depth below 0");
238                        }
239                        depth -= 1;
240                    }
241                    _ => (),
242                },
243                CmdOrHole::Hole => {
244                    holes += 1;
245                }
246            }
247        }
248        if depth != 0 {
249            miette::bail!("total stack depth not 0");
250        }
251        if holes != self.children.len() {
252            miette::bail!("number of holes does not match number of children");
253        }
254        Ok(self)
255    }
256}
257
258pub struct ArcSTermBuilder<T> {
259    tag: T,
260    children: Vec<Arc<ArcSTerm<T>>>,
261    cmds: Vec<CmdOrHole>,
262}
263
264impl<T> ArcSTermBuilder<T> {
265    pub fn new(tag: T) -> Self {
266        Self {
267            tag,
268            children: Vec::new(),
269            cmds: Vec::new(),
270        }
271    }
272
273    pub fn child(mut self, child: &Arc<ArcSTerm<T>>) -> Self {
274        self.cmds.push(CmdOrHole::Hole);
275        self.children.push(child.clone());
276        self
277    }
278
279    pub fn cmd(mut self, cmd: StrCmd) -> Self {
280        self.cmds.push(CmdOrHole::Cmd(cmd));
281        self
282    }
283
284    pub fn build(self) -> ArcSTerm<T> {
285        ArcSTerm {
286            tag: self.tag,
287            children: self.children.into_boxed_slice(),
288            cmds: self.cmds.into_boxed_slice(),
289        }
290    }
291
292    // convenience methods
293
294    pub fn write(self, s: &str) -> Self {
295        self.cmd(StrCmd::Write(s.into()))
296    }
297
298    pub fn newline(self) -> Self {
299        self.cmd(StrCmd::NewLine)
300    }
301
302    pub fn push(self, s: &str) -> Self {
303        self.cmd(StrCmd::Push(s.into()))
304    }
305
306    pub fn pop(self) -> Self {
307        self.cmd(StrCmd::Pop)
308    }
309
310    pub fn c(self, child: &Arc<ArcSTerm<T>>) -> Self {
311        self.child(child)
312    }
313
314    pub fn w(self, s: &str) -> Self {
315        self.write(s)
316    }
317
318    pub fn n(self) -> Self {
319        self.newline()
320    }
321
322    pub fn p(self, s: &str) -> Self {
323        self.push(s)
324    }
325
326    pub fn x(self) -> Self {
327        self.pop()
328    }
329
330    pub fn b(self) -> ArcSTerm<T> {
331        self.build()
332    }
333}
334
335/**************************************************************/
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn sterm() -> miette::Result<()> {
343        let sterm = ArcSTermBuilder::new(()).w("foo").b().v()?;
344        let sterm = arc(sterm);
345        let sterm = ArcSTermBuilder::new(())
346            .c(&sterm)
347            .p(">>> ")
348            .n()
349            .c(&sterm)
350            .x()
351            .n()
352            .c(&sterm)
353            .b()
354            .v()?;
355
356        let mut buf = std::io::BufWriter::new(Vec::new());
357        let mut writer = PrefixWriter::new(&mut buf);
358        sterm.write(&mut writer);
359        let bytes = buf.into_inner().unwrap();
360        let s = String::from_utf8(bytes).unwrap();
361        println!("{s}");
362
363        Ok(())
364    }
365}