diff --git a/src/ast/val.rs b/src/ast/val.rs index daf5586..8a03729 100644 --- a/src/ast/val.rs +++ b/src/ast/val.rs @@ -10,7 +10,7 @@ pub enum Type { } /// The (immutable) result of evaluating an [`Expr`](super::expr::Expr). -pub trait Val { +pub trait Val : fmt::Display { fn clone(&self) -> Box; fn typ(&self) -> Type; @@ -26,6 +26,14 @@ pub trait Val { fn string(&self) -> Result<&str, TypeError> { Err(TypeError::new(self.typ(), Type::String)) } + + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Ok(s) = self.string() { + write!(f, "[{} {}]", self.typ(), s) + } else { + write!(f, "[{} ??]", self.typ()) + } + } } /// The actual data structure behind [`Val`]. @@ -72,6 +80,12 @@ impl Val for Data { } } +impl fmt::Display for Data { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[bool {}]", self.data) + } +} + impl Val for Data { fn clone(&self) -> Box { Box::new(Data { @@ -88,6 +102,12 @@ impl Val for Data { } } +impl fmt::Display for Data { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[int {}]", self.data) + } +} + impl Val for Data { fn clone(&self) -> Box { Box::new(Data { @@ -104,6 +124,12 @@ impl Val for Data { } } +impl fmt::Display for Data { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[string \"{}\"", self.data) + } +} + pub struct TypeError { pub msg: String, pub actual: Type,