From a653a6602fe5ae5eb4739755db7b34bc92ecdadf Mon Sep 17 00:00:00 2001 From: Cody Date: Sun, 29 Jan 2023 20:58:04 -0600 Subject: More stuffs --- src/ast/display.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/ast/display.rs (limited to 'src/ast/display.rs') diff --git a/src/ast/display.rs b/src/ast/display.rs new file mode 100644 index 0000000..25b4d23 --- /dev/null +++ b/src/ast/display.rs @@ -0,0 +1,45 @@ +use std::fmt::Display; + +use super::{Expression, Statement, Value}; + +impl<'a> Display for Statement<'a> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{{")?; + let value = match self { + Statement::Val { + identifier, + initializer, + } => format!("val {} {}", identifier.lexeme, initializer), + Statement::Var { + identifier, + initializer, + } => format!("var {} {}", identifier.lexeme, initializer), + Statement::Expression { expr } => expr.to_string(), + }; + write!(f, "{value}")?; + write!(f, "}}")?; + + Ok(()) + } +} + +impl<'a> Display for Expression<'a> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "(")?; + let value = match self { + Expression::Literal(value) => value.0.to_string(), + Expression::Unary { expr, .. } => format!("+ {}", expr), + Expression::Binary { lhs, rhs, .. } => format!("+ {lhs} {rhs}"), + }; + write!(f, "{value}")?; + write!(f, ")")?; + + Ok(()) + } +} + +impl Display for Value { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} -- cgit v1.2.3