Crates.io | prec |
lib.rs | prec |
version | 1.1.0 |
source | src |
created_at | 2020-09-19 00:31:20.260969 |
updated_at | 2020-12-21 18:44:34.12535 |
description | A generic operator-precedence parser library |
homepage | https://github.com/mcpar-land/prec |
repository | https://github.com/mcpar-land/prec |
max_upload_size | |
id | 290303 |
size | 16,934 |
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
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.