■ 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 |
peg::parser! ( grammar calc() for str { pub rule eval() -> i64 = term() rule term() -> i64 = v1 : num() "+" v2 : num() { v1 + v2 } rule num() -> i64 = value : $(['0'..='9']+) { value.parse().unwrap() } } ); fn main() { println!("2+5={}", calc::eval("2+5").unwrap()); println!("8+2={}", calc::eval("8+2").unwrap()); println!("200+50={}", calc::eval("200+50").unwrap()); } /* 2+5=7 8+2=10 200+50=250 */ |