use std::marker::PhantomData;
use miette::{bail, Result};
use crate::lang::Arity;
use crate::meta::OuterKind;
use crate::prelude::{Index, *};
use crate::{meta::MetaLanguage, qterm::QTerm, term::CmdOrHole};
pub trait Holds {
const NAME: &'static str;
const ANNO: &'static str;
}
pub struct HoldMetaLanguage<H: Holds>(PhantomData<H>);
impl<H: Holds> Default for HoldMetaLanguage<H> {
fn default() -> Self {
HoldMetaLanguage(PhantomData)
}
}
fn hold(name: &str, tag: &str, terms: &[Arc<QTerm>], cmds: &[CmdOrHole]) -> Result<Arc<QTerm>> {
let holes = cmds.iter().filter(|c| matches!(c, CmdOrHole::Hole)).count();
if holes != terms.len() {
bail!(
"{name} can't hold a {tag:?} node: {holes} hole(s) for {} child term(s)",
terms.len()
);
}
Ok(tuple(tag, terms, cmds))
}
impl<H: Holds> MetaLanguage for HoldMetaLanguage<H> {
fn expand_quote(
&self,
_lang1: &str,
tag: &str,
_i: Index,
_lang2: &str,
qterm: &Arc<QTerm>,
cmds: &[CmdOrHole],
) -> Result<Arc<QTerm>> {
hold(H::NAME, tag, std::slice::from_ref(qterm), cmds)
}
fn expand_unquote(
&self,
_lang1: &str,
tag: &str,
_i: Index,
_lang2: &str,
qterm: &Arc<QTerm>,
cmds: &[CmdOrHole],
) -> Result<Arc<QTerm>> {
hold(H::NAME, tag, std::slice::from_ref(qterm), cmds)
}
fn expand_tuple(
&self,
_lang1: &str,
tag: &str,
qterms: &[Arc<QTerm>],
cmds: &[CmdOrHole],
_arity: Arity,
) -> Result<Arc<QTerm>> {
hold(H::NAME, tag, qterms, cmds)
}
fn wrap_child(&self, qterm: Arc<QTerm>, _okind: OuterKind) -> Result<Arc<QTerm>> {
Ok(qterm)
}
fn lift_str(&self, target: &str) -> Result<&'static str> {
bail!(
"{} can't lift `↑` into {target:?}: it holds code rather than building it, so \
there is no expression for a lift to be — quote {} from a real host \
(`{}↖ … ↗` in a `.rs.quilt` or `.py.quilt` file) and lift there",
H::NAME,
H::NAME,
H::ANNO
)
}
fn reduce_str(&self, target: &str) -> Result<&'static str> {
bail!(
"{} can't reduce `{target}↓`: it holds code rather than running it, so there is \
no runtime to evaluate a fragment with — reduce in a real host that quotes \
`{}↖ … ↗`",
H::NAME,
H::ANNO
)
}
fn emit_str(&self) -> Result<&'static str> {
bail!(
"{} can't emit `←`: it holds code rather than building it, so there is no `b_` \
accumulator to emit into — emit in a real host that quotes `{}↖ … ↗`",
H::NAME,
H::ANNO
)
}
fn type_str(&self) -> Result<&'static str> {
bail!(
"{} has no type for `⟨T⟩`: it has no type syntax — drop the annotation",
H::NAME
)
}
fn name_str(&self) -> Result<&'static str> {
bail!(
"{} has no spelling for `⟨N⟩`: a name in {} is already its own text, so the \
operator would be the identity — drop it",
H::NAME,
H::NAME
)
}
}