Rust Nom How to use ? in parsers

357 Views Asked by At

It's the first time I have used a parser combinator, so maybe I just have a misunderstanding about how I should use a parser combinator.

I have the following code which works in general:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fd53125d3ed874b5e70f3aaae32e2e94

The problem is, I don't understand how I can get rid of the .unwrap() in my parse_method and parse_url functions and use the ? operator instead. I have already read https://github.com/rust-bakery/nom/blob/main/doc/error_management.md but absolutely don't understand how to apply it in this case.

I think I have to create a custom Error Enum and implement the ParseError trait. I tried that, but without any success. Unfortunately, the nom crate does not have many examples, and the ones that are there never use the ? operator.

This leads me to think that I misunderstood how I should use a parser combinator. Is the idea that I just parse the parts and assemble the parts later where I do not return IResult or is the idea that I should use .map_err and return noms own error types? I am really lost. Any help is appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

Use map_res combinator:

fn parse_method(input: &[u8]) -> IResult<&[u8], Method> {
    let (input, method) = map_res(
        terminated(take_till(is_space), multispace0),
        Method::from_bytes,
    )(input)?;

    Ok((input, method))
}

In general, you should prefer using combinators over manually successively calling parsers: full example