use crate::lang::Arity;
use crate::prelude::*;
use crate::qterm::QTerm;
use crate::term::CmdOrHole;
use std::borrow::Cow;
use std::fmt::Debug;
use std::sync::Arc;
pub const LIFT: &str = "__LIFT__";
pub const REDUCE: &str = "__REDUCE__";
pub const EMIT: &str = "__EMIT__";
pub const TYPE: &str = "__TYPE__";
pub const NAME: &str = "__NAME__";
pub fn spawn_spelling(
host: &str,
lang: &str,
spell: impl FnOnce(&str) -> String,
) -> Result<String> {
if !crate::machine::has_spec(lang) {
miette::bail!(
"no machine is registered for {lang:?}, so `{lang}⟨M⟩` gives {host} nothing to \
spawn; quilt knows: {}",
crate::machine::REGISTERED_SPECS.join(", ")
);
}
Ok(spell(lang))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prelude {
pub text: Cow<'static, str>,
pub markers: Vec<Cow<'static, str>>,
}
impl Prelude {
pub fn new(
text: impl Into<Cow<'static, str>>,
markers: impl IntoIterator<Item = &'static str>,
) -> Self {
Prelude {
text: text.into(),
markers: markers.into_iter().map(Cow::Borrowed).collect(),
}
}
#[must_use]
pub fn present_in(&self, src: &str) -> bool {
self.markers.iter().any(|m| src.contains(&**m))
}
}
#[cfg(feature = "parse")]
#[must_use]
pub fn with_prelude(body: &str, prelude: &str, lang: &str) -> String {
let line_comment = crate::langs::line_comment(lang).unwrap_or("//");
let at = prelude_offset(body, line_comment);
let (before, after) = body.split_at(at);
if after.is_empty() {
format!("{before}{prelude}\n")
} else {
format!("{before}{prelude}\n\n{after}")
}
}
#[cfg(feature = "parse")]
fn prelude_offset(body: &str, line_comment: &str) -> usize {
let mut at = 0;
let mut rest = body;
while !rest.is_empty() {
let line_end = rest.find('\n').map_or(rest.len(), |i| i + 1);
let line = rest[..line_end].trim_end();
let take = if line.is_empty() || line.starts_with(line_comment) {
line_end
} else if line.starts_with("#![") {
match attribute_end(rest) {
Some(end) => end,
None => break,
}
} else if at == 0 && line.starts_with("#!") {
line_end } else {
break;
};
at += take;
rest = &rest[take..];
}
at
}
#[cfg(feature = "parse")]
fn attribute_end(s: &str) -> Option<usize> {
let mut depth = 0usize;
for (i, c) in s.char_indices() {
match c {
'[' => depth += 1,
']' => {
depth -= 1;
if depth == 0 {
let after = i + c.len_utf8();
return Some(s[after..].find('\n').map_or(s.len(), |j| after + j + 1));
}
}
_ => {}
}
}
None
}
#[derive(Debug, Clone)]
pub enum Piece {
Text(Box<str>),
NewLine,
Push(Box<str>),
Pop,
Hole(Arc<QTerm>),
}
#[must_use]
pub fn no_repr(repr: crate::qterm::Repr) -> miette::Report {
miette!(
"this host has no {repr} quotes yet: only `⟨cst⟩` (the default) is implemented \
for it — TypeScript has all three"
)
}
#[derive(Debug, Clone, Copy, Default)]
pub enum OuterKind {
#[default]
None,
Emit,
Splice,
}
pub trait MetaLanguage {
fn expand_quote(
&self,
lang1: &str,
tag: &str,
i: Index,
lang2: &str,
qterm: &Arc<QTerm>,
cmds: &[CmdOrHole],
) -> Result<Arc<QTerm>>;
fn expand_unquote(
&self,
lang1: &str,
tag: &str,
i: Index,
lang2: &str,
qterm: &Arc<QTerm>,
cmds: &[CmdOrHole],
) -> Result<Arc<QTerm>>;
fn expand_tuple(
&self,
lang1: &str,
tag: &str,
qterms: &[Arc<QTerm>],
cmds: &[CmdOrHole],
arity: Arity, ) -> Result<Arc<QTerm>>;
fn wrap_child(&self, qterm: Arc<QTerm>, _okind: OuterKind) -> Result<Arc<QTerm>> {
Ok(qterm)
}
fn wrap_separated(&self, qterm: Arc<QTerm>, _sep: &str) -> Result<Arc<QTerm>> {
Ok(qterm)
}
fn pattern_tag(&self) -> Option<&'static str> {
None
}
fn pattern_binding(&self, terms: &[Arc<QTerm>]) -> Option<(usize, usize)> {
let _ = terms;
None
}
fn pattern_var(&self, name: &str) -> Result<Arc<QTerm>> {
let _ = name;
Err(miette!(
"this meta-language does not support pattern matching"
))
}
fn pattern_let(
&self,
names: &[Box<str>],
pattern: &Arc<QTerm>,
value: &Arc<QTerm>,
) -> Result<(Arc<QTerm>, Arc<QTerm>)> {
let _ = (names, pattern, value);
Err(miette!(
"this meta-language does not support pattern matching"
))
}
#[inline]
fn lift_str(&self, target: &str) -> Result<&'static str> {
let _ = target;
Ok(LIFT)
}
#[inline]
fn reduce_str(&self, target: &str) -> Result<&'static str> {
let _ = target;
Ok(REDUCE)
}
#[inline]
fn reduce_method_str(&self, target: &str) -> Result<&'static str> {
miette::bail!(
"this meta-language has no machine-eval spelling for `{target}↓(…)` in method position"
)
}
#[inline]
fn emit_str(&self) -> Result<&'static str> {
Ok(EMIT)
}
fn lift_str_in(&self, target: &str, repr: crate::qterm::Repr) -> Result<&'static str> {
match repr {
crate::qterm::Repr::Cst => self.lift_str(target),
_ => Err(no_repr(repr)),
}
}
fn emit_str_in(&self, repr: crate::qterm::Repr) -> Result<&'static str> {
match repr {
crate::qterm::Repr::Cst => self.emit_str(),
_ => Err(no_repr(repr)),
}
}
fn expand_flat(
&self,
repr: crate::qterm::Repr,
lang2: &str,
pieces: &[Piece],
) -> Result<Arc<QTerm>> {
let _ = (lang2, pieces);
Err(no_repr(repr))
}
#[inline]
fn type_str(&self) -> Result<&'static str> {
Ok(TYPE)
}
#[inline]
fn name_str(&self) -> Result<&'static str> {
Ok(NAME)
}
#[inline]
fn type_method_str(&self) -> Result<&'static str> {
miette::bail!("this meta-language has no type-of spelling for `⟨T⟩(…)` in method position")
}
#[inline]
fn spawn_str(&self, lang: &str) -> Result<String> {
miette::bail!(
"this meta-language has no spelling for `{lang}⟨M⟩`: it has no runtime to hold a \
machine handle. Drive the machine from a host that does (rust, python), or wait on \
the `quilt machine serve` daemon (issue #268)"
)
}
#[inline]
fn prelude(&self, targets: &[&str]) -> Option<Prelude> {
let _ = targets;
None
}
}
impl MetaLanguage for Box<dyn MetaLanguage> {
fn expand_quote(
&self,
lang1: &str,
tag: &str,
i: Index,
lang2: &str,
qterm: &Arc<QTerm>,
cmds: &[CmdOrHole],
) -> Result<Arc<QTerm>> {
(**self).expand_quote(lang1, tag, i, lang2, qterm, cmds)
}
fn expand_unquote(
&self,
lang1: &str,
tag: &str,
i: Index,
lang2: &str,
qterm: &Arc<QTerm>,
cmds: &[CmdOrHole],
) -> Result<Arc<QTerm>> {
(**self).expand_unquote(lang1, tag, i, lang2, qterm, cmds)
}
fn expand_tuple(
&self,
lang1: &str,
tag: &str,
qterms: &[Arc<QTerm>],
cmds: &[CmdOrHole],
arity: Arity, ) -> Result<Arc<QTerm>> {
(**self).expand_tuple(lang1, tag, qterms, cmds, arity)
}
fn wrap_child(&self, qterm: Arc<QTerm>, okind: OuterKind) -> Result<Arc<QTerm>> {
(**self).wrap_child(qterm, okind)
}
fn wrap_separated(&self, qterm: Arc<QTerm>, sep: &str) -> Result<Arc<QTerm>> {
(**self).wrap_separated(qterm, sep)
}
fn pattern_tag(&self) -> Option<&'static str> {
(**self).pattern_tag()
}
fn pattern_binding(&self, terms: &[Arc<QTerm>]) -> Option<(usize, usize)> {
(**self).pattern_binding(terms)
}
fn pattern_var(&self, name: &str) -> Result<Arc<QTerm>> {
(**self).pattern_var(name)
}
fn pattern_let(
&self,
names: &[Box<str>],
pattern: &Arc<QTerm>,
value: &Arc<QTerm>,
) -> Result<(Arc<QTerm>, Arc<QTerm>)> {
(**self).pattern_let(names, pattern, value)
}
fn lift_str(&self, target: &str) -> Result<&'static str> {
(**self).lift_str(target)
}
fn reduce_str(&self, target: &str) -> Result<&'static str> {
(**self).reduce_str(target)
}
fn reduce_method_str(&self, target: &str) -> Result<&'static str> {
(**self).reduce_method_str(target)
}
fn emit_str(&self) -> Result<&'static str> {
(**self).emit_str()
}
fn lift_str_in(&self, target: &str, repr: crate::qterm::Repr) -> Result<&'static str> {
(**self).lift_str_in(target, repr)
}
fn emit_str_in(&self, repr: crate::qterm::Repr) -> Result<&'static str> {
(**self).emit_str_in(repr)
}
fn expand_flat(
&self,
repr: crate::qterm::Repr,
lang2: &str,
pieces: &[Piece],
) -> Result<Arc<QTerm>> {
(**self).expand_flat(repr, lang2, pieces)
}
fn type_str(&self) -> Result<&'static str> {
(**self).type_str()
}
fn name_str(&self) -> Result<&'static str> {
(**self).name_str()
}
fn type_method_str(&self) -> Result<&'static str> {
(**self).type_method_str()
}
fn spawn_str(&self, lang: &str) -> Result<String> {
(**self).spawn_str(lang)
}
fn prelude(&self, targets: &[&str]) -> Option<Prelude> {
(**self).prelude(targets)
}
}
#[cfg(all(test, feature = "parse"))]
mod tests {
use super::*;
#[test]
fn a_prelude_goes_after_the_header() {
let at = |body: &str, comment: &str, item: &str| {
assert_eq!(
prelude_offset(body, comment),
body.find(item).unwrap(),
"{body:?}"
);
};
at("fn main() {}\n", "//", "fn");
at("//! docs\n//! more\n\nfn main() {}\n", "//", "fn");
at("#!/usr/bin/env quilt\nfn main() {}\n", "//", "fn");
at("fn main() {}\n#!/usr/bin/env quilt\n", "//", "fn");
at("#![allow(dead_code)]\nfn f() {}\n", "//", "fn");
at("#![allow(\n dead_code\n)]\nfn f() {}\n", "//", "fn");
at("#![allow(\nfn f() {}\n", "//", "#![");
at("#!/usr/bin/env quilt\n# hi\nx = 1\n", "#", "x =");
}
}