use gcmodule::Trace;
use std::borrow::Cow;
use std::fmt;
#[derive(Clone)]
pub enum Sexp<V> {
Symbol(Cow<'static, str>),
Compound(Vec<Sexp<V>>),
Inlined(V),
}
impl<V: 'static> Trace for Sexp<V> {
fn is_type_tracked() -> bool {
false
}
fn as_any(&self) -> Option<&dyn std::any::Any> {
Some(self)
}
}
impl<V: fmt::Display> fmt::Display for Sexp<V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_expr(self, f, V::fmt)
}
}
impl<V: fmt::Debug> fmt::Debug for Sexp<V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_expr(self, f, V::fmt)
}
}
fn fmt_expr<V>(
expr: &Sexp<V>,
f: &mut fmt::Formatter,
fmt_inlined: fn(&V, &mut fmt::Formatter) -> fmt::Result,
) -> fmt::Result {
match expr {
Sexp::Symbol(s) => write!(f, "{}", &s)?,
Sexp::Compound(v) => {
write!(f, "(")?;
let mut padding = "";
for expr in v.iter() {
write!(f, "{}", padding)?;
fmt_expr(expr, f, fmt_inlined)?;
padding = " ";
}
write!(f, ")")?;
}
Sexp::Inlined(v) => fmt_inlined(v, f)?,
}
Ok(())
}
#[macro_export]
macro_rules! sexp {
( { $x: expr } ) => { $crate::expr::Sexp::Inlined($crate::value::Value::new($x)) };
( + ) => { $crate::expr::Sexp::Symbol("+".into()) };
( - ) => { $crate::expr::Sexp::Symbol("-".into()) };
( * ) => { $crate::expr::Sexp::Symbol("*".into()) };
( / ) => { $crate::expr::Sexp::Symbol("/".into()) };
( $x: ident ) => { $crate::expr::Sexp::Symbol(stringify!($x).into()) };
( ( $( $x: tt ) * ) ) => {
{
#[allow(unused_mut)]
let mut vec = Vec::new();
$( vec.push(sexp!($x)); )*
$crate::expr::Sexp::Compound(vec)
}
};
( [ $x: tt ] ) => { $crate::expr::Sexp::Symbol($x.into()) };
( $x: expr ) => { sexp!( { $x } ) };
}