quiltlang 0.6.0

Quilt, a polyglot metaprogramming language: source code with arrow-bracket syntax for embedding and manipulating code fragments of other languages at code-generation time.
Documentation
use crate::prelude::*;
use crate::{
    strcmd::{PrefixWriter, StrCmd},
    validate::Validate,
};
use miette::IntoDiagnostic;
use serde::{Deserialize, Serialize};
use std::{io::Write, sync::Arc};

/**************************************************************/

pub trait Term: Sized {
    type Tag;

    fn tag(&self) -> Self::Tag;
    fn children(&self) -> impl Iterator<Item = &Self>;
    fn len(&self) -> usize {
        self.children().count()
    }
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
    fn get(&self, i: usize) -> Option<&Self> {
        self.children().nth(i)
    }
}

/**************************************************************/

pub struct ArcTerm<T: Clone> {
    tag: T,
    children: Box<[Arc<Self>]>,
}

impl<T: Clone> Term for ArcTerm<T> {
    type Tag = T;

    fn tag(&self) -> Self::Tag {
        self.tag.clone()
    }

    fn children(&self) -> impl Iterator<Item = &Self> {
        self.children.iter().map(|x| x.as_ref())
    }

    fn len(&self) -> usize {
        self.children.len()
    }

    fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

impl<T: Clone> Term for Arc<ArcTerm<T>> {
    type Tag = T;

    fn tag(&self) -> Self::Tag {
        self.tag.clone()
    }

    fn children(&self) -> impl Iterator<Item = &Self> {
        self.children.iter()
    }

    fn len(&self) -> usize {
        self.children.len()
    }

    fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

/**************************************************************/

pub trait STerm: Term {
    fn write<W: Write>(&self, writer: &mut PrefixWriter<'_, W>);

    fn coparse(&self) -> String {
        let mut buf = Vec::new();
        let mut writer = PrefixWriter::new(&mut buf);
        self.write(&mut writer);
        String::from_utf8(buf).unwrap()
    }

    /// Render as `.quilt` **source** rather than as target output: a Quilt
    /// glyph sitting in content is written `\`-escaped, the way it has to be
    /// spelled for the result to parse back to the same term.
    ///
    /// This is the inverse of parsing, and [`Self::coparse`] is not: a term is
    /// written twice in this project, once as the file it came from and once as
    /// the code it generates, and the two disagree exactly on glyphs. `↑` in
    /// generated Lean is a coercion and must stay bare; the same `↑` in the
    /// `.quilt` file it was written in is the lift operator unless it carries a
    /// `\`. `coparse` kept the second reading for both, so any source with an
    /// escaped glyph did not survive a round trip — and for `←` and `⟨` did not
    /// even re-parse (#223).
    ///
    /// Use this for anything that renders a *parsed, unexpanded* term back to a
    /// file; use [`Self::coparse`] for expander output.
    fn coparse_quilt(&self) -> String {
        let mut buf = Vec::new();
        let mut writer = PrefixWriter::quilt(&mut buf);
        self.write(&mut writer);
        String::from_utf8(buf).unwrap()
    }

    fn dump(&self, filename: &str) -> Result<()> {
        let mut file = std::fs::File::create(filename).into_diagnostic()?;
        let mut writer = PrefixWriter::new(&mut file);
        self.write(&mut writer);
        Ok(())
    }

    fn dump_with_cmds(&self, filename: &str, prefix: &[StrCmd], suffix: &[StrCmd]) -> Result<()> {
        let mut file = std::fs::File::create(filename).into_diagnostic()?;
        let mut writer = PrefixWriter::new(&mut file);
        for cmd in prefix {
            writer.interpret(cmd);
        }
        self.write(&mut writer);
        for cmd in suffix {
            writer.interpret(cmd);
        }
        Ok(())
    }
}

/**************************************************************/

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CmdOrHole {
    Cmd(StrCmd),
    Hole,
}

pub fn cmd(cmd: StrCmd) -> CmdOrHole {
    CmdOrHole::Cmd(cmd)
}
pub fn hole() -> CmdOrHole {
    CmdOrHole::Hole
}

pub const HOLE: CmdOrHole = CmdOrHole::Hole;

/// Whether the `Push` at `cmds[k]` aligns a splice to its column: a push, the
/// hole, then the pop. A language whose layout is column-sensitive wraps each
/// one-line splice in exactly that (`TSProvider::align_splices`, #301), and
/// nothing else puts a hole straight after a push — a quoted line break pushes
/// its indent and then writes the newline. Expanded code spells such a push
/// `align` rather than `push`, so that host text spliced there is laid out at
/// the hole's column as a term is (#310; see `QTermBuilder::align`).
#[must_use]
pub fn is_aligned_splice(cmds: &[CmdOrHole], k: usize) -> bool {
    matches!(
        cmds.get(k..k + 3),
        Some([
            CmdOrHole::Cmd(StrCmd::Push(_)),
            CmdOrHole::Hole,
            CmdOrHole::Cmd(StrCmd::Pop)
        ])
    )
}

#[derive(Debug, Clone)]
pub struct ArcSTerm<T> {
    tag: T,
    children: Box<[Arc<Self>]>,
    cmds: Box<[CmdOrHole]>,
}

impl<T: Clone> Term for ArcSTerm<T> {
    type Tag = T;

    fn tag(&self) -> Self::Tag {
        self.tag.clone()
    }

    fn children(&self) -> impl Iterator<Item = &Self> {
        self.children.iter().map(|x| x.as_ref())
    }

    fn len(&self) -> usize {
        self.children.len()
    }

    fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

impl<T: Clone> Term for Arc<ArcSTerm<T>> {
    type Tag = T;

    fn tag(&self) -> Self::Tag {
        self.tag.clone()
    }

    fn children(&self) -> impl Iterator<Item = &Self> {
        self.children.iter()
    }

    fn len(&self) -> usize {
        self.children.len()
    }

    fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

impl<T: Clone> STerm for ArcSTerm<T> {
    fn write<W: Write>(&self, writer: &mut PrefixWriter<'_, W>) {
        let mut children = self.children.iter();
        for cmd in &self.cmds {
            match cmd {
                CmdOrHole::Cmd(cmd) => writer.interpret(cmd),
                CmdOrHole::Hole => children.next().unwrap().write(writer),
            }
        }
    }
}

impl<T> Validate for ArcSTerm<T> {
    type Error = miette::Error;

    fn validate(self) -> Result<Self, Self::Error> {
        let mut depth: u32 = 0;
        let mut holes = 0;
        for cmd in &self.cmds {
            match cmd {
                CmdOrHole::Cmd(cmd) => match cmd {
                    StrCmd::Push(_) => depth += 1,
                    StrCmd::Pop => {
                        if depth == 0 {
                            miette::bail!("running stack depth below 0");
                        }
                        depth -= 1;
                    }
                    _ => (),
                },
                CmdOrHole::Hole => {
                    holes += 1;
                }
            }
        }
        if depth != 0 {
            miette::bail!("total stack depth not 0");
        }
        if holes != self.children.len() {
            miette::bail!("number of holes does not match number of children");
        }
        Ok(self)
    }
}

pub struct ArcSTermBuilder<T> {
    tag: T,
    children: Vec<Arc<ArcSTerm<T>>>,
    cmds: Vec<CmdOrHole>,
}

impl<T> ArcSTermBuilder<T> {
    pub fn new(tag: T) -> Self {
        Self {
            tag,
            children: Vec::new(),
            cmds: Vec::new(),
        }
    }

    pub fn child(mut self, child: &Arc<ArcSTerm<T>>) -> Self {
        self.cmds.push(CmdOrHole::Hole);
        self.children.push(child.clone());
        self
    }

    pub fn cmd(mut self, cmd: StrCmd) -> Self {
        self.cmds.push(CmdOrHole::Cmd(cmd));
        self
    }

    pub fn build(self) -> ArcSTerm<T> {
        ArcSTerm {
            tag: self.tag,
            children: self.children.into_boxed_slice(),
            cmds: self.cmds.into_boxed_slice(),
        }
    }

    // convenience methods

    pub fn write(self, s: &str) -> Self {
        self.cmd(StrCmd::Write(s.into()))
    }

    pub fn newline(self) -> Self {
        self.cmd(StrCmd::NewLine)
    }

    pub fn push(self, s: &str) -> Self {
        self.cmd(StrCmd::Push(s.into()))
    }

    pub fn pop(self) -> Self {
        self.cmd(StrCmd::Pop)
    }

    pub fn c(self, child: &Arc<ArcSTerm<T>>) -> Self {
        self.child(child)
    }

    pub fn w(self, s: &str) -> Self {
        self.write(s)
    }

    pub fn n(self) -> Self {
        self.newline()
    }

    pub fn p(self, s: &str) -> Self {
        self.push(s)
    }

    pub fn x(self) -> Self {
        self.pop()
    }

    pub fn b(self) -> ArcSTerm<T> {
        self.build()
    }
}

/**************************************************************/

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sterm() -> miette::Result<()> {
        let sterm = ArcSTermBuilder::new(()).w("foo").b().v()?;
        let sterm = arc(sterm);
        let sterm = ArcSTermBuilder::new(())
            .c(&sterm)
            .p(">>> ")
            .n()
            .c(&sterm)
            .x()
            .n()
            .c(&sterm)
            .b()
            .v()?;

        let mut buf = std::io::BufWriter::new(Vec::new());
        let mut writer = PrefixWriter::new(&mut buf);
        sterm.write(&mut writer);
        let bytes = buf.into_inner().unwrap();
        let s = String::from_utf8(bytes).unwrap();
        println!("{s}");

        Ok(())
    }
}