Skip to content

Commit

Permalink
docs(examples): generic parse combinator in arithmetic
Browse files Browse the repository at this point in the history
  • Loading branch information
guissalustiano committed Aug 5, 2024
1 parent 43b3c53 commit ac15d7c
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions examples/arithmetic/parser.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::str::FromStr;

use winnow::error::ParserError;
use winnow::prelude::*;
use winnow::{
ascii::{digit1 as digits, multispace0 as multispaces},
Expand Down Expand Up @@ -53,12 +54,17 @@ fn term(i: &mut &str) -> PResult<i64> {
// If either str::from_utf8 or FromStr::from_str fail,
// we fallback to the parens parser defined above
fn factor(i: &mut &str) -> PResult<i64> {
delimited(
multispaces,
alt((digits.try_map(FromStr::from_str), parens)),
multispaces,
)
.parse_next(i)
escape_spaces(alt((digits.try_map(FromStr::from_str), parens))).parse_next(i)
}

// A generic combinator with remove the surrounding whitespaces from a combinator
fn escape_spaces<'a, Output, Error>(
parser: impl Parser<&'a str, Output, Error>,
) -> impl Parser<&'a str, Output, Error>
where
Error: ParserError<&'a str>,
{
delimited(multispaces, parser, multispaces)
}

// We parse any expr surrounded by parens, ignoring all whitespace around those
Expand Down

0 comments on commit ac15d7c

Please sign in to comment.