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