■ parser! 매크로를 사용해 사칙 연산 계산기를 만드는 방법을 보여준다.
▶ Cargo.toml
1 2 3 4 5 6 7 8 9 |
[package] name = "test_project" version = "0.1.0" edition = "2021" [dependencies] peg = "0.8" |
▶ src/main.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 |
peg::parser! ( grammar calc() for str { pub rule eval() -> i64 = expr() rule expr() -> i64 = left_value : term() "+" right_value : expr() { left_value + right_value } / left_value : term() "-" right_value : expr() { left_value - right_value } / term() rule term() -> i64 = left_value : value() "*" right_value : term() { left_value * right_value } / left_value : value() "/" right_value : term() { left_value / right_value } / value : value() rule value() -> i64 = number() / "(" value : expr() ")" { value } rule number() -> i64 = value : $(['0'..='9']+) { value.parse().unwrap() } } ); fn main() { println!("{}", calc::eval("10+20*30").unwrap()); println!("{}", calc::eval("(10+20)*30").unwrap()); println!("{}", calc::eval("10/20-30").unwrap()); } |