Mise en place formelle du visiteur et séparation de l'affichage d'un arbre syntaxique abstrait (AST).
This commit is contained in:
42
src/astprinter.rs
Normal file
42
src/astprinter.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use crate::expr::{Binary, Expr, ExprVisitor, Grouping, Literal, Unary, VisitableExpr};
|
||||
|
||||
pub struct ASTPrinter;
|
||||
|
||||
impl ExprVisitor for ASTPrinter {
|
||||
fn visit_binary(&self, b: &Binary) {
|
||||
print!("( {}", b.operator.literal);
|
||||
b.left.accept(self);
|
||||
b.right.accept(self);
|
||||
print!(")");
|
||||
}
|
||||
|
||||
fn visit_grouping(&self, g: &Grouping) {
|
||||
print!("( group ");
|
||||
g.expression.accept(self);
|
||||
print!(")");
|
||||
}
|
||||
|
||||
fn visit_literal(&self, l: &Literal) {
|
||||
match l {
|
||||
Literal::LiteralNumber(i) => print!("{}", i),
|
||||
Literal::LiteralString(s) => print!("{}", s),
|
||||
Literal::LiteralBool(b) => print!("{}", b),
|
||||
Literal::LiteralNil => print!("nil"),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_unary(&self, u: &Unary) {
|
||||
print!("( {}", u.operator.literal);
|
||||
u.right.accept(self);
|
||||
print!(")");
|
||||
}
|
||||
|
||||
fn visit_expr(&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); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user