rust-parser-combinator/src/choice.rs

20 lines
567 B
Rust
Raw Normal View History

2024-01-26 00:07:52 -08:00
use crate::Parser;
2024-01-26 22:01:21 -08:00
pub fn choice<'a, I, O, E>(parsers: &'a [&'a dyn Parser<I, O, E>]) -> impl Parser<I, O, E> + 'a {
move |mut input: I| {
2024-01-26 00:07:52 -08:00
//TODO need a more principled way to return an error when no choices work
let mut err = None;
for parser in parsers.iter() {
2024-01-26 22:01:21 -08:00
match parser.parse(input) {
2024-01-26 00:07:52 -08:00
Ok(res) => return Ok(res),
2024-01-26 22:01:21 -08:00
Err((e, rest)) => {
2024-01-26 00:07:52 -08:00
err = Some(e);
2024-01-26 22:01:21 -08:00
input = rest;
2024-01-26 00:07:52 -08:00
}
}
}
2024-01-26 22:01:21 -08:00
Err((err.unwrap(), input))
2024-01-26 00:07:52 -08:00
}
}