Skip to content

Commit

Permalink
example: pratt expression parser
Browse files Browse the repository at this point in the history
  • Loading branch information
39555 committed Nov 17, 2024
1 parent f218911 commit b9e799d
Show file tree
Hide file tree
Showing 4 changed files with 432 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,17 @@ required-features = ["alloc"]
name = "string"
required-features = ["alloc"]

[[example]]
name = "pratt"
required-features = ["std"]


[[bench]]
name = "pratt"
path = "examples/pratt/bench.rs"
harness = false
required-features = ["std"]

[[bench]]
name = "arithmetic"
path = "examples/arithmetic/bench.rs"
Expand Down
16 changes: 16 additions & 0 deletions examples/pratt/bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
mod parser;

use criterion::black_box;
use winnow::prelude::*;

fn pratt(c: &mut criterion::Criterion) {
let i =
"a = 2*-2 / ( &**foo.a->p! -+1) + 3^1 / 4 == 1 * (2 - 7 + 567 *12 /2) + 3*(1+2*( 45 /2))";
parser::pratt_parser.parse(i).expect("should parse");
c.bench_function("pratt_parser", |b| {
b.iter(|| black_box(parser::pratt_parser.parse(i).unwrap()));
});
}

criterion::criterion_group!(benches, pratt);
criterion::criterion_main!(benches);
44 changes: 44 additions & 0 deletions examples/pratt/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use winnow::prelude::*;

mod parser;

fn main() -> Result<(), lexopt::Error> {
let args = Args::parse()?;

let input = args.input.as_deref().unwrap_or("1 + 1");
match parser::pratt_parser.parse(input) {
Ok(result) => {
println!("{result}");
}
Err(err) => {
println!("FAILED");
println!("{err}");
}
}

Ok(())
}

#[derive(Default)]
struct Args {
input: Option<String>,
}

impl Args {
fn parse() -> Result<Self, lexopt::Error> {
use lexopt::prelude::*;

let mut res = Args::default();

let mut args = lexopt::Parser::from_env();
while let Some(arg) = args.next()? {
match arg {
Value(input) => {
res.input = Some(input.string()?);
}
_ => return Err(arg.unexpected()),
}
}
Ok(res)
}
}
Loading

0 comments on commit b9e799d

Please sign in to comment.