prec

Crates.ioprec
lib.rsprec
version1.1.0
sourcesrc
created_at2020-09-19 00:31:20.260969
updated_at2020-12-21 18:44:34.12535
descriptionA generic operator-precedence parser library
homepagehttps://github.com/mcpar-land/prec
repositoryhttps://github.com/mcpar-land/prec
max_upload_size
id290303
size16,934
John (mcpar-land)

documentation

https://docs.rs/prec

README

Crates.io

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.

Commit count: 14

cargo fmt