diff --git a/src/ast.rs b/src/ast.rs index 245a09b..52c7f49 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -204,3 +204,44 @@ impl UnaryOp { Spanned::new(Self::Invert, span) } } + +impl Ast { + pub fn print_rpn(&self) -> String { + self.0.print_rpn() + } +} + +impl Expr { + fn print_rpn(&self) -> String { + match self { + Expr::Binary { left, op, right } => { + let left = left.print_rpn(); + let right = right.print_rpn(); + let op_str = match op.as_ref() { + BinaryOp::Eq => "==", + BinaryOp::NotEq => "!=", + BinaryOp::Greater => ">", + BinaryOp::GreaterEq => ">=", + BinaryOp::Less => "<", + BinaryOp::LessEq => "<=", + BinaryOp::Add => "+", + BinaryOp::Sub => "-", + BinaryOp::Mult => "*", + BinaryOp::Div => "/", + }; + format!("({op_str} {left} {right})") + } + Expr::Grouping { inner } => format!("({})", inner.print_rpn()), + Expr::Literal { lit } => match lit.as_ref() { + Literal::String(s) => format!("\"{s}\""), + Literal::Number(n) => format!("{n}"), + Literal::Bool(b) => format!("{b}"), + Literal::Nil => "nil".to_string(), + }, + Expr::Unary { op, expr } => match op.as_ref() { + UnaryOp::Negative => format!("(- {})", expr.print_rpn()), + UnaryOp::Invert => format!("(! {})", expr.print_rpn()), + }, + } + } +} diff --git a/src/runners/repl.rs b/src/runners/repl.rs index 092dd15..e3ae67e 100644 --- a/src/runners/repl.rs +++ b/src/runners/repl.rs @@ -58,7 +58,8 @@ pub fn run_repl() -> Result<()> { prompt()?; continue; }; - dbg!(&ast); + //dbg!(&ast); + println!("{}", ast.print_rpn()); let final_value = match interpret(&ast) { Ok(value) => value,