Debian Codegraph @

third_party/rust/winnow/examples/arithmetic/parser.rs

raw
1 use std::str::FromStr;
2
3 use winnow::prelude::*;
4 use winnow::Result;
5 use winnow::{
6 ascii::{digit1 as digits, multispace0 as multispaces},
7 combinator::alt,
8 combinator::delimited,
9 combinator::repeat,
10 token::one_of,
11 };
12
13 // Parser definition
14
15 pub(crate) fn expr(i: &mut &str) -> Result<i64> {
16 let init = term.parse_next(i)?;
17
18 repeat(0.., (one_of(['+', '-']), term))
19 .fold(
20 move || init,
21 |acc, (op, val): (char, i64)| {
22 if op == '+' {
23 acc + val
24 } else {
25 acc - val
26 }
27 },
28 )
29 .parse_next(i)
30 }
31
32 // We read an initial factor and for each time we find
33 // a * or / operator followed by another factor, we do
34 // the math by folding everything
35 pub(crate) fn term(i: &mut &str) -> Result<i64> {
36 let init = factor.parse_next(i)?;
37
38 repeat(0.., (one_of(['*', '/']), factor))
39 .fold(
40 move || init,
41 |acc, (op, val): (char, i64)| {
42 if op == '*' {
43 acc * val
44 } else {
45 acc / val
46 }
47 },
48 )
49 .parse_next(i)
50 }
51
52 // We transform an integer string into a i64, ignoring surrounding whitespace
53 // We look for a digit suite, and try to convert it.
54 // If either str::from_utf8 or FromStr::from_str fail,
55 // we fallback to the parens parser defined above
56 pub(crate) fn factor(i: &mut &str) -> Result<i64> {
57 delimited(
58 multispaces,
59 alt((digits.try_map(FromStr::from_str), parens)),
60 multispaces,
61 )
62 .parse_next(i)
63 }
64
65 // We parse any expr surrounded by parens, ignoring all whitespace around those
66 fn parens(i: &mut &str) -> Result<i64> {
67 delimited('(', expr, ')').parse_next(i)
68 }