| 1 |
extern crate peg; |
| 2 |
use peg::parser; |
| 3 |
|
| 4 |
#[derive(Clone, PartialEq, Eq, Debug)] |
| 5 |
pub enum Expression { |
| 6 |
Number(i64), |
| 7 |
Sum(Box<Expression>, Box<Expression>), |
| 8 |
Product(Box<Expression>, Box<Expression>), |
| 9 |
} |
| 10 |
|
| 11 |
parser!{ |
| 12 |
|
| 13 |
grammar arithmetic() for str { |
| 14 |
|
| 15 |
|
| 16 |
pub rule expression() -> Expression |
| 17 |
= sum() |
| 18 |
|
| 19 |
rule _ = [' ' | '\n']* |
| 20 |
|
| 21 |
rule sum() -> Expression |
| 22 |
= l:product() _ "+" _ r:product() { Expression::Sum(Box::new(l), Box::new(r)) } |
| 23 |
/ product() |
| 24 |
|
| 25 |
rule product() -> Expression |
| 26 |
= l:atom() _ "*" _ r:atom() { Expression::Product(Box::new(l), Box::new(r)) } |
| 27 |
/ atom() |
| 28 |
|
| 29 |
rule atom() -> Expression |
| 30 |
= number() |
| 31 |
/ "(" _ v:sum() _ ")" { v } |
| 32 |
|
| 33 |
rule number() -> Expression |
| 34 |
= n:$(['0'..='9']+) { Expression::Number(n.parse().unwrap()) } |
| 35 |
}} |
| 36 |
|
| 37 |
fn main() { |
| 38 |
assert_eq!(arithmetic::expression("1+1"), Ok(Expression::Sum( |
| 39 |
Box::new(Expression::Number(1)), |
| 40 |
Box::new(Expression::Number(1))) |
| 41 |
)); |
| 42 |
assert_eq!(arithmetic::expression("5*5"), Ok(Expression::Product( |
| 43 |
Box::new(Expression::Number(5)), |
| 44 |
Box::new(Expression::Number(5))) |
| 45 |
)); |
| 46 |
assert_eq!(arithmetic::expression("2+3*4"), Ok(Expression::Sum( |
| 47 |
Box::new(Expression::Number(2)), |
| 48 |
Box::new(Expression::Product( |
| 49 |
Box::new(Expression::Number(3)), |
| 50 |
Box::new(Expression::Number(4)) |
| 51 |
)), |
| 52 |
))); |
| 53 |
assert_eq!(arithmetic::expression("(2+3) * 4"), Ok(Expression::Product( |
| 54 |
Box::new(Expression::Sum( |
| 55 |
Box::new(Expression::Number(2)), |
| 56 |
Box::new(Expression::Number(3)), |
| 57 |
)), |
| 58 |
Box::new(Expression::Number(4)) |
| 59 |
))); |
| 60 |
assert!(arithmetic::expression("(22+)+1").is_err()); |
| 61 |
assert!(arithmetic::expression("1++1").is_err()); |
| 62 |
assert!(arithmetic::expression("3)+1").is_err()); |
| 63 |
} |