-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpr.rs
62 lines (60 loc) · 2.21 KB
/
expr.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// generated by: cargo run --bin generate_ast src
use crate::token::{Literal, Token};
#[derive(Debug, PartialEq)]
pub enum Expr {
Binary {
lhs: Box<Expr>,
operator: Box<Token>,
rhs: Box<Expr>,
},
Ternary {
lhs: Box<Expr>,
lho: Box<Token>,
mhs: Box<Expr>,
rho: Box<Token>,
rhs: Box<Expr>,
},
Grouping {
expression: Box<Expr>,
},
Literal {
value: Box<Literal>,
},
Unary {
operator: Box<Token>,
operand: Box<Expr>,
},
}
impl Expr {
pub fn accept<R>(&self, visitor: &mut dyn ExprVisitor<R>) -> R {
match self {
Expr::Binary { lhs, operator, rhs } => visitor.visit_binary(lhs, operator, rhs),
Expr::Ternary { lhs, lho, mhs, rho, rhs } => visitor.visit_ternary(lhs, lho, mhs, rho, rhs),
Expr::Grouping { expression } => visitor.visit_grouping(expression),
Expr::Literal { value } => visitor.visit_literal(value),
Expr::Unary { operator, operand } => visitor.visit_unary(operator, operand),
}
}
pub fn new_binary(lhs: Expr, operator: Token, rhs: Expr) -> Expr {
Expr::Binary { lhs: Box::new(lhs), operator: Box::new(operator), rhs: Box::new(rhs) }
}
pub fn new_ternary(lhs: Expr, lho: Token, mhs: Expr, rho: Token, rhs: Expr) -> Expr {
Expr::Ternary { lhs: Box::new(lhs), lho: Box::new(lho), mhs: Box::new(mhs), rho: Box::new(rho), rhs: Box::new(rhs) }
}
pub fn new_grouping(expression: Expr) -> Expr {
Expr::Grouping { expression: Box::new(expression) }
}
pub fn new_literal(value: Literal) -> Expr {
Expr::Literal { value: Box::new(value) }
}
pub fn new_unary(operator: Token, operand: Expr) -> Expr {
Expr::Unary { operator: Box::new(operator), operand: Box::new(operand) }
}
}
pub trait ExprVisitor<R> {
fn visit_binary(&mut self, lhs: &Expr, operator: &Token, rhs: &Expr) -> R;
fn visit_ternary(&mut self, lhs: &Expr, lho: &Token, mhs: &Expr, rho: &Token, rhs: &Expr) -> R;
fn visit_grouping(&mut self, expression: &Expr) -> R;
fn visit_literal(&mut self, value: &Literal) -> R;
fn visit_unary(&mut self, operator: &Token, operand: &Expr) -> R;
}