| 1 | extern crate peg; |
| 2 | |
| 3 | peg::parser!( grammar arithmetic() for str { |
| 4 | rule ident() -> &'input str = $(['a'..='z']+) |
| 5 | rule haskell_op() -> String = "`" i:ident() "`" [' '|'\n']* { i.to_owned() } |
| 6 | rule plus() = "+" [' '|'\n']* |
| 7 | |
| 8 | pub rule expression() -> InfixAst = precedence!{ |
| 9 | x:(@) plus() y:@ { InfixAst::Add(Box::new(x), Box::new(y)) } |
| 10 | -- |
| 11 | x:(@) op:haskell_op() y:@ { InfixAst::Op(op, Box::new(x), Box::new(y)) } |
| 12 | -- |
| 13 | i:ident() [' '|'\n']* { InfixAst::Ident(i.to_owned()) } |
| 14 | } |
| 15 | }); |
| 16 | |
| 17 | #[derive(Debug, PartialEq, Eq, Clone)] |
| 18 | pub enum InfixAst { |
| 19 | Ident(String), |
| 20 | Add(Box<InfixAst>, Box<InfixAst>), |
| 21 | Op(String, Box<InfixAst>, Box<InfixAst>) |
| 22 | } |
| 23 | |
| 24 | fn main(){ |
| 25 | assert_eq!(arithmetic::expression("a + b `x` c").unwrap(), |
| 26 | InfixAst::Add( |
| 27 | Box::new(InfixAst::Ident("a".to_owned())), |
| 28 | Box::new(InfixAst::Op("x".to_owned(), |
| 29 | Box::new(InfixAst::Ident("b".to_owned())), |
| 30 | Box::new(InfixAst::Ident("c".to_owned())) |
| 31 | )) |
| 32 | ) |
| 33 | ) |
| 34 | } |