Mise en place formelle du visiteur et séparation de l'affichage d'un arbre syntaxique abstrait (AST).
This commit is contained in:
59
src/expr.rs
59
src/expr.rs
@@ -29,53 +29,44 @@ pub enum Expr {
|
||||
UnaryExpr(Unary),
|
||||
}
|
||||
|
||||
pub trait Visitable {
|
||||
fn visit(&self);
|
||||
pub trait ExprVisitor {
|
||||
fn visit_binary(&self, b: &Binary);
|
||||
fn visit_grouping(&self, g: &Grouping);
|
||||
fn visit_literal(&self, l: &Literal);
|
||||
fn visit_unary(&self, u: &Unary);
|
||||
fn visit_expr(&self, e: &Expr);
|
||||
}
|
||||
|
||||
impl Visitable for Binary {
|
||||
fn visit(&self) {
|
||||
print!("( {}",&self.operator.literal);
|
||||
&self.left.visit();
|
||||
&self.right.visit();
|
||||
print!(")");
|
||||
pub trait VisitableExpr {
|
||||
fn accept(&self, visitor: &impl ExprVisitor);
|
||||
}
|
||||
|
||||
impl VisitableExpr for Binary {
|
||||
fn accept(&self, visitor: &impl ExprVisitor) {
|
||||
visitor.visit_binary(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitable for Grouping {
|
||||
fn visit(&self) {
|
||||
print!("( group ");
|
||||
&self.expression.visit();
|
||||
print!(")");
|
||||
impl VisitableExpr for Grouping {
|
||||
fn accept(&self, visitor: &impl ExprVisitor) {
|
||||
visitor.visit_grouping(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitable for Literal {
|
||||
fn visit(&self) {
|
||||
match &self {
|
||||
Literal::LiteralNumber(i) => print!("{}", i),
|
||||
Literal::LiteralString(s) => print!("{}", s),
|
||||
Literal::LiteralBool(b) => print!("{}", b),
|
||||
Literal::LiteralNil => print!("nil"),
|
||||
}
|
||||
impl VisitableExpr for Literal {
|
||||
fn accept(&self, visitor: &impl ExprVisitor) {
|
||||
visitor.visit_literal(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitable for Unary {
|
||||
fn visit(&self) {
|
||||
print!("( {}",&self.operator.literal);
|
||||
&self.right.visit();
|
||||
print!(")");
|
||||
impl VisitableExpr for Unary {
|
||||
fn accept(&self, visitor: &impl ExprVisitor) {
|
||||
visitor.visit_unary(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitable for Expr {
|
||||
fn visit(&self) {
|
||||
match &self {
|
||||
Expr::BinaryExpr(b) => { b.visit(); }
|
||||
Expr::GroupingExpr(g) => { g.visit(); }
|
||||
Expr::LiteralExpr(l) => { l.visit(); }
|
||||
Expr::UnaryExpr(u) => { u.visit(); }
|
||||
}
|
||||
impl VisitableExpr for Expr {
|
||||
fn accept(&self, visitor: &impl ExprVisitor) {
|
||||
visitor.visit_expr(self);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user