rust-parser-combinator/src/choice.rs
2024-01-26 22:01:21 -08:00

20 lines
567 B
Rust

use crate::Parser;
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| {
//TODO need a more principled way to return an error when no choices work
let mut err = None;
for parser in parsers.iter() {
match parser.parse(input) {
Ok(res) => return Ok(res),
Err((e, rest)) => {
err = Some(e);
input = rest;
}
}
}
Err((err.unwrap(), input))
}
}