Open dashed opened 7 years ago
I might settle on a higher-order function as follows:
fn on_error<I: Input, T, E, F, V, G>(i: I, f: F, g: G) -> ParseResult<I, T, V>
where F: FnOnce(I) -> ParseResult<I, T, E>,
G: FnOnce(E, &I) -> V {
match f(i).into_inner() {
(i, Ok(t)) => i.ret(t),
(i, Err(e)) => {
let err_val = g(e, &i);
i.err(err_val)
}
}
}
Usage:
fn some_parser<I: U8Input>(i: InputPosition<I, CurrentPosition>)
-> ESParseResult<InputPosition<I, CurrentPosition>, ()> {
parse!{i;
let var = on_error(
|i| string(i, b"var"),
|_err, i| {
let loc = i.position();
ParseError::Expected(loc, "Expected var keyword.".to_string())
}
);
// ...
ret {()}
}
}
That looks pretty good, when I have the time I will see if I can include something like that in Chomp proper. Would be useful to have a higher-order function and/or error type to carry position-information for errors.
I have a usecase where I'd like to somehow pass
numbering::InputPosition::position
to anError
type as a way of reporting parsing errors at a location (e.g. line/column location).The issue is that I'm unable to access
numbering::InputPosition::position
from withinchomp::types::ParseResult::map_err
function.I adapted
map_err
intomap_err2
as follows: https://github.com/dashed/chomp/commit/3f1998b1d06394ed5b1a8c765230371b6a4f4533This enables me to do this:
I'd love to hear any feedback on this, especially for any better alternative approaches. 👍
Appendix
CurrentPosition
type for reference: