rust-bakery / nom

Rust parser combinator framework
MIT License
9.48k stars 806 forks source link

Boost spirit x3 like semantic actions #985

Closed technic closed 5 years ago

technic commented 5 years ago

Hi, Thanks a lot for the library. I have a question: what would be a better way to define custom combinators? In the boost spirit library one can have "semantic actions", that is allowing user of the parser rules to define what to do with the data later. For example, I want to define something like separated_pair that would only accept only: as separator and check that the first value in the pair is surrounded by quotes. Currently I wrote this rule by combining existing functions/macros, now how to move it to a function to abstract details from the user and benefit from code reusing?

Thanks

technic commented 5 years ago

You can also think of pom where I can define some parser rule and call convert(...) to extract the value in a way I need later.

Geal commented 5 years ago

you can define new combinators as a function that takes a parser. As an example, here is map, which takes a parser and a function, and applies that function to the parser's result if successful:

pub fn map<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
where
  F: Fn(I) -> IResult<I, O1, E>,
  G: Fn(O1) -> O2,
{
  move |input: I| {
    let (input, o1) = first(input)?;
    Ok((input, second(o1)))
  }
}
technic commented 5 years ago

This looks quite verbose, could you give the overview about other libraries? Is it because nom is function based instead of trait/struct based?