@@ 11,68 11,71 @@ fn eval(op: &Operator, n1: i64, n2: i64) -> i64 {
Operator('-') => n1 - n2,
Operator('*') => n1 * n2,
Operator('/') => n1 / n2,
- _ => { panic!("Bad op: {:?}", op); }
+ _ => {
+ panic!("Bad op: {:?}", op);
+ }
}
}
peg::parser!(
- grammar calc_parser() for str {
- rule number() -> i64
- = n:$(['0'..='9']+) {
- ? n.parse().or(Err("bad num"))
- }
+grammar calc_parser() for str {
+ rule number() -> i64
+ = n:$(['0'..='9']+) {
+ ? n.parse().or(Err("bad num"))
+ }
- rule whitespace() = quiet!{[' ']*}
+ rule whitespace() = quiet!{[' ']*}
- rule operator() -> Operator
- = op:$(['*' | '/' | '+' | '-']) { Operator(op.chars().nth(0).unwrap()) }
+ rule operator() -> Operator
+ = op:$(['*' | '/' | '+' | '-']) { Operator(op.chars().next().unwrap()) }
- rule paren() -> i64
- = "(" whitespace() n:calculate() whitespace() ")" { n }
+ rule paren() -> i64
+ = "(" whitespace() n:calculate() whitespace() ")" { n }
- rule factor() -> i64
- =
- n:number() { n }
- /
- n:paren() { n }
+ rule factor() -> i64
+ =
+ n:number() { n }
+ /
+ n:paren() { n }
- rule term() -> i64
- =
- n1:factor() whitespace() op:operator() whitespace() n2:factor() {
- eval(&op, n1, n2)
- }
- /
- n:factor() { n }
+ rule term() -> i64
+ =
+ n1:factor() whitespace() op:operator() whitespace() n2:factor() {
+ eval(&op, n1, n2)
+ }
+ /
+ n:factor() { n }
- pub rule calculate() -> i64
- =
- n1:term() whitespace() op:operator() whitespace() n2:term() {
- eval(&op, n1, n2)
- }
- /
- n:term() { n }
+ pub rule calculate() -> i64
+ =
+ n1:term() whitespace() op:operator() whitespace() n2:term() {
+ eval(&op, n1, n2)
}
- );
+ /
+ n:term() { n }
+}
+);
fn main() {
- loop {
- println!("Enter an expression, or 'END' to quit: ");
- let mut input = String::new();
- io::stdin().read_line(&mut input)
- .expect("Error reading input!");
+ loop {
+ println!("Enter an expression, or 'END' to quit: ");
+ let mut input = String::new();
+ io::stdin()
+ .read_line(&mut input)
+ .expect("Error reading input!");
- let input = input.as_str().trim();
+ let input = input.as_str().trim();
- if input == "END" {
- break;
- }
+ if input == "END" {
+ break;
+ }
- let answer = calc_parser::calculate(input);
- match answer {
- Ok(v) => println!("Answer: {:?}", v),
- Err(e) => println!("Calculation error: {:?}", e),
+ let answer = calc_parser::calculate(input);
+ match answer {
+ Ok(v) => println!("Answer: {:?}", v),
+ Err(e) => println!("Calculation error: {:?}", e),
+ }
}
- }
}
#[test]