Finalisation de l'interpreteur d'expressions.

This commit is contained in:
2024-05-20 23:17:46 +02:00
parent 48507617e5
commit 3e27109d2a
4 changed files with 184 additions and 53 deletions

View File

@@ -1,4 +1,4 @@
use crate::expr::{Binary, Expr, ExprVisitor, Grouping, Literal, Unary, VisitableExpr};
use crate::expr::{Binary, Expr, ExprVisitor, Grouping, Literal, Unary};
pub struct ASTPrinter {
pub(crate) depth: u32
@@ -10,18 +10,18 @@ impl ASTPrinter {
}
}
impl ExprVisitor for ASTPrinter {
impl ExprVisitor<()> for ASTPrinter {
fn visit_binary(&mut self, b: &Binary) {
println!("{}BINARY",self.ast_tab());
println!("{}op='{}'", self.ast_tab(), b.operator.lexeme);
println!("{}left=(", self.ast_tab());
self.depth+=1;
b.left.accept(self);
self.visit_expr(&*b.left);
self.depth-=1;
println!("{})", self.ast_tab());
println!("{}right=(", self.ast_tab());
self.depth+=1;
b.right.accept(self);
self.visit_expr(&*b.right);
self.depth-=1;
println!("{})", self.ast_tab());
}
@@ -29,7 +29,7 @@ impl ExprVisitor for ASTPrinter {
fn visit_grouping(&mut self, g: &Grouping) {
println!("{}GROUPING(", self.ast_tab());
self.depth+=1;
g.expression.accept(self);
self.visit_expr(&*g.expression);
self.depth-=1;
print!(") ");
}
@@ -46,17 +46,17 @@ impl ExprVisitor for ASTPrinter {
fn visit_unary(&mut self, u: &Unary) {
println!("{}UNARY(op='{}'", self.ast_tab(), u.operator.lexeme);
self.depth+=1;
u.right.accept(self);
self.visit_expr(&*u.right);
self.depth-=1;
print!(") ");
}
fn visit_expr(&mut self, e: &Expr) {
match e {
Expr::BinaryExpr(b) => { b.accept(self); }
Expr::GroupingExpr(g) => { g.accept(self); }
Expr::LiteralExpr(l) => { l.accept(self); }
Expr::UnaryExpr(u) => { u.accept(self); }
Expr::BinaryExpr(b) => { self.visit_binary(b); }
Expr::GroupingExpr(g) => { self.visit_grouping(g); }
Expr::LiteralExpr(l) => { self.visit_literal(l); }
Expr::UnaryExpr(u) => { self.visit_unary(u); }
}
}
}