#parser #nom

nom-recursive

Extension of nom to handle left recursion

4 releases (breaking)

0.4.0 Aug 31, 2021
0.3.0 Nov 26, 2020
0.2.0 Apr 1, 2020
0.1.1 Aug 15, 2019

#26 in #nom

Download history 118/week @ 2021-07-05 117/week @ 2021-07-12 120/week @ 2021-07-19 84/week @ 2021-07-26 98/week @ 2021-08-02 136/week @ 2021-08-09 84/week @ 2021-08-16 146/week @ 2021-08-23 159/week @ 2021-08-30 68/week @ 2021-09-06 121/week @ 2021-09-13 71/week @ 2021-09-20 69/week @ 2021-09-27 66/week @ 2021-10-04 61/week @ 2021-10-11 112/week @ 2021-10-18

447 downloads per month
Used in 7 crates (via sv-parser-parser)

MIT/Apache

7KB
113 lines

nom-recursive

Extension of nom to handle left recursion.

Actions Status Crates.io Docs.rs

Requirement

nom must be 5.0.0 or later. nom-recursive can be applied to function-style parser only.

The input type of nom parser must implement HasRecursiveInfo trait. Therefore &str and &[u8] can't be used. You can define a wrapper type of &str or &[u8] and implement HasRecursiveInfo.

Alternatively you can use nom_locate::LocatedSpan<T, RecursiveInfo>. This implements HasRecursiveInfo in this crate.

Usage

[dependencies]
nom-recursive = "0.4.0"

Example

use nom::branch::*;
use nom::character::complete::*;
use nom::IResult;
use nom_locate::LocatedSpan;
use nom_recursive::{recursive_parser, RecursiveInfo};

// Input type must implement trait HasRecursiveInfo
// nom_locate::LocatedSpan<T, RecursiveInfo> implements it.
type Span<'a> = LocatedSpan<&'a str, RecursiveInfo>;

pub fn expr(s: Span) -> IResult<Span, String> {
    alt((expr_binary, term))(s)
}

// Apply recursive_parser by custom attribute
#[recursive_parser]
pub fn expr_binary(s: Span) -> IResult<Span, String> {
    let (s, x) = expr(s)?;
    let (s, y) = char('+')(s)?;
    let (s, z) = expr(s)?;
    let ret = format!("{}{}{}", x, y, z);
    Ok((s, ret))
}

pub fn term(s: Span) -> IResult<Span, String> {
    let (s, x) = char('1')(s)?;
    Ok((s, x.to_string()))
}

fn main() {
    let ret = expr(LocatedSpan::new_extra("1+1", RecursiveInfo::new()));
    println!("{:?}", ret.unwrap().1);
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~1.2–1.7MB
~37K SLoC