Debian Codegraph @

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

raw
1 use std::fmt;
2 use std::fmt::{Debug, Display, Formatter};
3
4 use winnow::prelude::*;
5 use winnow::Result;
6 use winnow::{
7 ascii::{digit1 as digits, multispace0 as multispaces},
8 combinator::alt,
9 combinator::dispatch,
10 combinator::eof,
11 combinator::fail,
12 combinator::opt,
13 combinator::peek,
14 combinator::repeat,
15 combinator::{delimited, preceded, terminated},
16 error::ContextError,
17 stream::TokenSlice,
18 token::any,
19 token::literal,
20 token::one_of,
21 token::take_till,
22 };
23
24 /// Lex and parse
25 #[allow(dead_code)]
26 pub(crate) fn expr2(i: &mut &str) -> Result<Expr> {
27 let tokens = tokens.parse_next(i)?;
28 let mut tokens = Tokens::new(&tokens);
29 expr.parse_next(&mut tokens)
30 }
31
32 #[derive(Clone, Debug, PartialEq, Eq)]
33 pub(crate) struct Token<'s> {
34 kind: TokenKind,
35 raw: &'s str,
36 }
37
38 impl PartialEq<TokenKind> for Token<'_> {
39 fn eq(&self, other: &TokenKind) -> bool {
40 self.kind == *other
41 }
42 }
43
44 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
45 pub(crate) enum TokenKind {
46 Value,
47 Oper(Oper),
48 OpenParen,
49 CloseParen,
50 Unknown,
51 Eof,
52 }
53
54 impl<'i> Parser<Tokens<'i>, &'i Token<'i>, ContextError> for TokenKind {
55 fn parse_next(&mut self, input: &mut Tokens<'i>) -> Result<&'i Token<'i>> {
56 literal(*self).parse_next(input).map(|t| &t[0])
57 }
58 }
59
60 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
61 pub(crate) enum Oper {
62 Add,
63 Sub,
64 Mul,
65 Div,
66 }
67
68 impl winnow::stream::ContainsToken<&'_ Token<'_>> for TokenKind {
69 #[inline(always)]
70 fn contains_token(&self, token: &'_ Token<'_>) -> bool {
71 *self == token.kind
72 }
73 }
74
75 impl winnow::stream::ContainsToken<&'_ Token<'_>> for &'_ [TokenKind] {
76 #[inline]
77 fn contains_token(&self, token: &'_ Token<'_>) -> bool {
78 self.iter().any(|t| *t == token.kind)
79 }
80 }
81
82 impl<const LEN: usize> winnow::stream::ContainsToken<&'_ Token<'_>> for &'_ [TokenKind; LEN] {
83 #[inline]
84 fn contains_token(&self, token: &'_ Token<'_>) -> bool {
85 self.iter().any(|t| *t == token.kind)
86 }
87 }
88
89 impl<const LEN: usize> winnow::stream::ContainsToken<&'_ Token<'_>> for [TokenKind; LEN] {
90 #[inline]
91 fn contains_token(&self, token: &'_ Token<'_>) -> bool {
92 self.iter().any(|t| *t == token.kind)
93 }
94 }
95
96 /// Lex tokens
97 ///
98 /// See [`expr`] to parse the tokens
99 pub(crate) fn tokens<'s>(i: &mut &'s str) -> Result<Vec<Token<'s>>> {
100 let mut tokens: Vec<_> =
101 preceded(multispaces, repeat(1.., terminated(token, multispaces))).parse_next(i)?;
102 if let Some(eof) = opt(eof.map(|raw| Token {
103 kind: TokenKind::Eof,
104 raw,
105 }))
106 .parse_next(i)?
107 {
108 tokens.push(eof);
109 }
110 Ok(tokens)
111 }
112
113 fn token<'s>(i: &mut &'s str) -> Result<Token<'s>> {
114 dispatch! {peek(any);
115 '0'..='9' => digits.value(TokenKind::Value),
116 '(' => '('.value(TokenKind::OpenParen),
117 ')' => ')'.value(TokenKind::CloseParen),
118 '+' => '+'.value(TokenKind::Oper(Oper::Add)),
119 '-' => '-'.value(TokenKind::Oper(Oper::Sub)),
120 '*' => '*'.value(TokenKind::Oper(Oper::Mul)),
121 '/' => '/'.value(TokenKind::Oper(Oper::Div)),
122 ' '| '\t'| '\r'| '\n' => fail,
123 _ => take_till(.., ('0'..='9', '(', ')', '+', '-', '*', '/')).value(TokenKind::Unknown),
124 }
125 .with_taken()
126 .map(|(kind, raw)| Token { kind, raw })
127 .parse_next(i)
128 }
129
130 #[derive(Debug, Clone)]
131 pub(crate) enum Expr {
132 Value(i64),
133 Add(Box<Expr>, Box<Expr>),
134 Sub(Box<Expr>, Box<Expr>),
135 Mul(Box<Expr>, Box<Expr>),
136 Div(Box<Expr>, Box<Expr>),
137 Paren(Box<Expr>),
138 }
139
140 impl Expr {
141 pub(crate) fn eval(&self) -> i64 {
142 match self {
143 Self::Value(v) => *v,
144 Self::Add(lhs, rhs) => lhs.eval() + rhs.eval(),
145 Self::Sub(lhs, rhs) => lhs.eval() - rhs.eval(),
146 Self::Mul(lhs, rhs) => lhs.eval() * rhs.eval(),
147 Self::Div(lhs, rhs) => lhs.eval() / rhs.eval(),
148 Self::Paren(expr) => expr.eval(),
149 }
150 }
151 }
152
153 impl Display for Expr {
154 fn fmt(&self, format: &mut Formatter<'_>) -> fmt::Result {
155 use Expr::{Add, Div, Mul, Paren, Sub, Value};
156 match *self {
157 Value(val) => write!(format, "{val}"),
158 Add(ref left, ref right) => write!(format, "{left} + {right}"),
159 Sub(ref left, ref right) => write!(format, "{left} - {right}"),
160 Mul(ref left, ref right) => write!(format, "{left} * {right}"),
161 Div(ref left, ref right) => write!(format, "{left} / {right}"),
162 Paren(ref expr) => write!(format, "({expr})"),
163 }
164 }
165 }
166
167 pub(crate) type Tokens<'i> = TokenSlice<'i, Token<'i>>;
168
169 /// Parse the tokens lexed in [`tokens`]
170 pub(crate) fn expr(i: &mut Tokens<'_>) -> Result<Expr> {
171 let init = term.parse_next(i)?;
172
173 let expr = repeat(
174 0..,
175 (
176 one_of([TokenKind::Oper(Oper::Add), TokenKind::Oper(Oper::Sub)]),
177 term,
178 ),
179 )
180 .fold(
181 move || init.clone(),
182 |acc, (op, val): (&Token<'_>, Expr)| {
183 if op.kind == TokenKind::Oper(Oper::Add) {
184 Expr::Add(Box::new(acc), Box::new(val))
185 } else {
186 Expr::Sub(Box::new(acc), Box::new(val))
187 }
188 },
189 )
190 .parse_next(i)?;
191
192 opt(TokenKind::Eof).parse_next(i)?;
193
194 Ok(expr)
195 }
196
197 pub(crate) fn term(i: &mut Tokens<'_>) -> Result<Expr> {
198 let init = factor.parse_next(i)?;
199
200 repeat(
201 0..,
202 (
203 one_of([TokenKind::Oper(Oper::Mul), TokenKind::Oper(Oper::Div)]),
204 factor,
205 ),
206 )
207 .fold(
208 move || init.clone(),
209 |acc, (op, val): (&Token<'_>, Expr)| {
210 if op.kind == TokenKind::Oper(Oper::Mul) {
211 Expr::Mul(Box::new(acc), Box::new(val))
212 } else {
213 Expr::Div(Box::new(acc), Box::new(val))
214 }
215 },
216 )
217 .parse_next(i)
218 }
219
220 pub(crate) fn factor(i: &mut Tokens<'_>) -> Result<Expr> {
221 alt((
222 TokenKind::Value.try_map(|t: &Token<'_>| t.raw.parse::<i64>().map(Expr::Value)),
223 parens,
224 ))
225 .parse_next(i)
226 }
227
228 fn parens(i: &mut Tokens<'_>) -> Result<Expr> {
229 delimited(TokenKind::OpenParen, expr, TokenKind::CloseParen)
230 .map(|e| Expr::Paren(Box::new(e)))
231 .parse_next(i)
232 }