forked from kevinmehall/rust-peg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmetic_infix_ast.rs
34 lines (30 loc) · 1.02 KB
/
arithmetic_infix_ast.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
extern crate peg;
peg::parser!( grammar arithmetic() for str {
rule ident() -> &'input str = $(['a'..='z']+)
rule haskell_op() -> String = "`" i:ident() "`" [' '|'\n']* { i.to_owned() }
rule plus() = "+" [' '|'\n']*
pub rule expression() -> InfixAst = precedence!{
x:(@) plus() y:@ { InfixAst::Add(Box::new(x), Box::new(y)) }
--
x:(@) op:haskell_op() y:@ { InfixAst::Op(op, Box::new(x), Box::new(y)) }
--
i:ident() [' '|'\n']* { InfixAst::Ident(i.to_owned()) }
}
});
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum InfixAst {
Ident(String),
Add(Box<InfixAst>, Box<InfixAst>),
Op(String, Box<InfixAst>, Box<InfixAst>)
}
fn main(){
assert_eq!(arithmetic::expression("a + b `x` c").unwrap(),
InfixAst::Add(
Box::new(InfixAst::Ident("a".to_owned())),
Box::new(InfixAst::Op("x".to_owned(),
Box::new(InfixAst::Ident("b".to_owned())),
Box::new(InfixAst::Ident("c".to_owned()))
))
)
)
}