Skip to content

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

Description

@eignnx

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)
}

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions