Debian Codegraph @

debian/missing-sources/winnow/examples/arithmetic/parser_ast.rs

raw
1 use std::fmt;
2 use std::fmt::{Debug, Display, Formatter};
3
4 use std::str::FromStr;
5
6 use winnow::prelude::*;
7 use winnow::Result;
8 use winnow::{
9 ascii::{digit1 as digits, multispace0 as multispaces},
10 combinator::alt,
11 combinator::delimited,
12 combinator::repeat,
13 token::one_of,
14 };
15
16 #[derive(Debug, Clone)]
17 pub(crate) enum Expr {
18 Value(i64),
19 Add(Box<Expr>, Box<Expr>),
20 Sub(Box<Expr>, Box<Expr>),
21 Mul(Box<Expr>, Box<Expr>),
22 Div(Box<Expr>, Box<Expr>),
23 Paren(Box<Expr>),
24 }
25
26 impl Expr {
27 pub(crate) fn eval(&self) -> i64 {
28 match self {
29 Self::Value(v) => *v,
30 Self::Add(lhs, rhs) => lhs.eval() + rhs.eval(),
31 Self::Sub(lhs, rhs) => lhs.eval() - rhs.eval(),
32 Self::Mul(lhs, rhs) => lhs.eval() * rhs.eval(),
33 Self::Div(lhs, rhs) => lhs.eval() / rhs.eval(),
34 Self::Paren(expr) => expr.eval(),
35 }
36 }
37 }
38
39 impl Display for Expr {
40 fn fmt(&self, format: &mut Formatter<'_>) -> fmt::Result {
41 use Expr::{Add, Div, Mul, Paren, Sub, Value};
42 match *self {
43 Value(val) => write!(format, "{val}"),
44 Add(ref left, ref right) => write!(format, "{left} + {right}"),
45 Sub(ref left, ref right) => write!(format, "{left} - {right}"),
46 Mul(ref left, ref right) => write!(format, "{left} * {right}"),
47 Div(ref left, ref right) => write!(format, "{left} / {right}"),
48 Paren(ref expr) => write!(format, "({expr})"),
49 }
50 }
51 }
52
53 pub(crate) fn expr(i: &mut &str) -> Result<Expr> {
54 let init = term.parse_next(i)?;
55
56 repeat(0.., (one_of(['+', '-']), term))
57 .fold(
58 move || init.clone(),
59 |acc, (op, val): (char, Expr)| {
60 if op == '+' {
61 Expr::Add(Box::new(acc), Box::new(val))
62 } else {
63 Expr::Sub(Box::new(acc), Box::new(val))
64 }
65 },
66 )
67 .parse_next(i)
68 }
69
70 pub(crate) fn term(i: &mut &str) -> Result<Expr> {
71 let init = factor.parse_next(i)?;
72
73 repeat(0.., (one_of(['*', '/']), factor))
74 .fold(
75 move || init.clone(),
76 |acc, (op, val): (char, Expr)| {
77 if op == '*' {
78 Expr::Mul(Box::new(acc), Box::new(val))
79 } else {
80 Expr::Div(Box::new(acc), Box::new(val))
81 }
82 },
83 )
84 .parse_next(i)
85 }
86
87 pub(crate) fn factor(i: &mut &str) -> Result<Expr> {
88 delimited(
89 multispaces,
90 alt((digits.try_map(FromStr::from_str).map(Expr::Value), parens)),
91 multispaces,
92 )
93 .parse_next(i)
94 }
95
96 fn parens(i: &mut &str) -> Result<Expr> {
97 delimited("(", expr, ")")
98 .map(|e| Expr::Paren(Box::new(e)))
99 .parse_next(i)
100 }