2022-07-24 14:49:02 -05:00
|
|
|
use ordered_float::OrderedFloat;
|
|
|
|
use std::{
|
|
|
|
borrow::Cow,
|
|
|
|
fmt::{Display, Write},
|
|
|
|
};
|
|
|
|
|
|
|
|
/// A Wisp AST
|
|
|
|
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
|
|
|
pub enum Expr<'a> {
|
|
|
|
List(Vec<Self>),
|
|
|
|
Vector(Vec<Self>),
|
|
|
|
Map(Vec<(Self, Self)>),
|
|
|
|
Symbol(Cow<'a, str>),
|
|
|
|
Keyword(Cow<'a, str>),
|
|
|
|
Number(OrderedFloat<f64>),
|
|
|
|
String(Cow<'a, str>),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Display for Expr<'a> {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
Self::List(list) => write_seq(f, list, "(", ")"),
|
|
|
|
Self::Vector(vec) => write_seq(f, vec, "[", "]"),
|
2022-07-24 14:56:44 -05:00
|
|
|
Self::Map(map) => write_seq(f, map.iter().map(|(k, v)| format!("{k} {v}")), "[", "]"),
|
2022-07-24 14:49:02 -05:00
|
|
|
Self::Symbol(sym) => write!(f, "{sym}"),
|
|
|
|
Self::Keyword(kw) => write!(f, ":{kw}"),
|
|
|
|
Self::Number(n) => write!(f, "{n}"),
|
|
|
|
Self::String(s) => write!(f, "\"{s}\""),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-24 14:56:20 -05:00
|
|
|
fn write_seq(
|
2022-07-24 14:49:02 -05:00
|
|
|
f: &mut impl Write,
|
|
|
|
iterable: impl IntoIterator<Item = impl Display>,
|
|
|
|
delimiter_left: &str,
|
|
|
|
delimiter_right: &str,
|
|
|
|
) -> std::fmt::Result {
|
|
|
|
let mut iter = iterable.into_iter();
|
|
|
|
write!(f, "{delimiter_left}")?;
|
|
|
|
if let Some(x) = iter.next() {
|
|
|
|
write!(f, "{x}")?;
|
|
|
|
}
|
|
|
|
for x in iter {
|
|
|
|
write!(f, " {x}")?;
|
|
|
|
}
|
|
|
|
write!(f, "{delimiter_right}")
|
|
|
|
}
|