4 releases (2 stable)
1.1.0 | Dec 21, 2020 |
---|---|
1.0.0 | Dec 21, 2020 |
0.1.1 | Sep 20, 2020 |
0.1.0 | Sep 19, 2020 |
#2813 in Rust patterns
13KB
250 lines
A generic operator-precedence parser for Rust. You plug your own handler function, token struct, and operator enum, and this crate provides the algorithm.
Simple example is available in int_math.rs
cargo run --example int_math
Example
fn handler(lhs: f64, op: Op, rhs: f64, _ctx: &()) -> Result<f64, ()> {
Ok(match op {
Op::Add => lhs + rhs,
Op::Sub => lhs - rhs,
Op::Mul => lhs * rhs,
Op::Div => lhs / rhs,
Op::Exp => lhs.powf(rhs)
})
}
let climber = Climber::new(
vec![
Rule::new(Op::Add, Assoc::Left) | Rule::new(Op::Sub, Assoc::Right),
Rule::new(Op::Mul, Assoc::Left) | Rule::new(Op::Div, Assoc::Right),
Rule::new(Op::Exp, Assoc::Right)
],
handler
);
// 2 + 2 * 3
// 2 + 6
// 8
let expression = Expression::new(
2.0f64,
vec![
(Op::Add, 2.0f64),
(Op::Mul, 3.0f64)
]
);
assert_eq!(climber.process(&expression, &()).unwrap(), 8.0f64);
This crate is heavily based on the Pest parser's PrecClimber, but is a more generic implementation for non-Pest use.