val: implement Display
This commit is contained in:
parent
fbffb0f6ea
commit
4cc7d17c99
1 changed files with 27 additions and 1 deletions
|
@ -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<dyn Val>;
|
||||
|
||||
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<bool> {
|
|||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Data<bool> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "[bool {}]", self.data)
|
||||
}
|
||||
}
|
||||
|
||||
impl Val for Data<i64> {
|
||||
fn clone(&self) -> Box<dyn Val> {
|
||||
Box::new(Data {
|
||||
|
@ -88,6 +102,12 @@ impl Val for Data<i64> {
|
|||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Data<i64> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "[int {}]", self.data)
|
||||
}
|
||||
}
|
||||
|
||||
impl Val for Data<String> {
|
||||
fn clone(&self) -> Box<dyn Val> {
|
||||
Box::new(Data {
|
||||
|
@ -104,6 +124,12 @@ impl Val for Data<String> {
|
|||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Data<String> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "[string \"{}\"", self.data)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TypeError {
|
||||
pub msg: String,
|
||||
pub actual: Type,
|
||||
|
|
Loading…
Reference in a new issue