Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wrapping fn for Fn(&str) -> IResult<&str, T> parsers #55

Open
eignnx opened this issue Apr 4, 2020 · 2 comments
Open

Add wrapping fn for Fn(&str) -> IResult<&str, T> parsers #55

eignnx opened this issue Apr 4, 2020 · 2 comments

Comments

@eignnx
Copy link

eignnx commented Apr 4, 2020

As far as I can tell, some nom parsers (like re_find!) aren't generic enough, and must accept &str input. This means you can't pass them a LocatedSpan.

It would be nice if there were a function that accepted one of those parsers and "lifted" it into a LocatedSpan -> LocatedSpan parser.

Here's as far as I got trying to implement this function:

type Span<'a> = LocatedSpan<&'a str>;

fn wrap<'input, T>(
    parser: impl Fn(&'input str) -> IResult<&'input str, T>,
) -> impl Fn(Span<'input>) -> IResult<Span<'input>, T> {
    |input: Span<'input>| {
        let (rest, pos) = position(input)?;
        // In the following line, how do we map the error?
        let (rest, res) = parser(rest.fragment()).map_err(|e| e)?;
        let rest = unsafe {
            // How should the offset and line be updated here?
            Span::new_from_raw_offset(pos.location_offset(), pos.location_line(), rest, ())
        };
        Ok((rest, res))
    }

The end result is that this function could be used like so:

fn some_parser(input: Span) -> IResult<Span, Whatever> {
    let re = |input: &str| re_find!(input, "<some regex here>");
    wrap(re)(input)
}
@rljacobson
Copy link

Is this still relevant in nom 6.0.0-alpha1? It might be easier just to wait for the new version of nom.

@MTRNord
Copy link

MTRNord commented Aug 2, 2023

Any update on this? The string example from nom sadly doesnt work with nom_locate :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants