Skip to main content

cauchy_ode/math_expr/
parser.rs

1// SPDX-License-Identifier: BSL-1.0
2// Distributed under the Boost Software License, Version 1.0.
3// See LICENSE or https://www.boost.org/LICENSE_1_0.txt.
4
5use super::MathExpr;
6use num_traits::Float;
7use std::error::Error;
8use std::fmt::{Debug, Display, Formatter};
9use std::marker::PhantomData;
10use std::str::FromStr;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct ParseError {
14    pub position: usize,
15    pub message: String,
16}
17
18impl Display for ParseError {
19    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
20        write!(
21            formatter,
22            "parse error at byte {}: {}",
23            self.position, self.message
24        )
25    }
26}
27
28impl Error for ParseError {}
29
30impl<'a, T> MathExpr<'a, T>
31where
32    T: Float + Debug + FromStr,
33{
34    pub fn parse(input: &'a str) -> Result<Self, ParseError> {
35        let mut parser = Parser::<T>::new(input);
36        let expression = parser.parse_expression()?;
37        parser.skip_whitespace();
38
39        if parser.is_at_end() {
40            Ok(expression)
41        } else {
42            Err(parser.error("unexpected trailing input"))
43        }
44    }
45}
46
47struct Parser<'a, T> {
48    input: &'a str,
49    position: usize,
50    marker: PhantomData<T>,
51}
52
53impl<'a, T> Parser<'a, T>
54where
55    T: Float + Debug + FromStr,
56{
57    fn new(input: &'a str) -> Self {
58        Self {
59            input,
60            position: 0,
61            marker: PhantomData,
62        }
63    }
64
65    fn parse_expression(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
66        self.parse_addition()
67    }
68
69    fn parse_addition(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
70        let mut expression = self.parse_multiplication()?;
71
72        loop {
73            if self.consume_symbol('+') {
74                expression = MathExpr::new_add(expression, self.parse_multiplication()?);
75            } else if self.consume_symbol('-') {
76                expression = MathExpr::new_subtract(expression, self.parse_multiplication()?);
77            } else {
78                return Ok(expression);
79            }
80        }
81    }
82
83    fn parse_multiplication(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
84        let mut expression = self.parse_unary()?;
85
86        loop {
87            if self.consume_symbol('*') {
88                expression = MathExpr::new_multiply(expression, self.parse_unary()?);
89            } else if self.consume_symbol('/') {
90                expression = MathExpr::new_divide(expression, self.parse_unary()?);
91            } else {
92                return Ok(expression);
93            }
94        }
95    }
96
97    fn parse_unary(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
98        if self.consume_symbol('-') {
99            Ok(MathExpr::new_negate(self.parse_unary()?))
100        } else {
101            self.parse_power()
102        }
103    }
104
105    fn parse_power(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
106        let base = self.parse_primary()?;
107
108        if self.consume_symbol('^') {
109            let exponent = self.parse_unary()?;
110            Ok(MathExpr::new_power(base, exponent))
111        } else {
112            Ok(base)
113        }
114    }
115
116    fn parse_primary(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
117        self.skip_whitespace();
118
119        if self.consume_symbol('(') {
120            let expression = self.parse_expression()?;
121            self.expect_symbol(')')?;
122            return Ok(expression);
123        }
124
125        match self.peek_char() {
126            Some(character) if character.is_ascii_digit() || character == '.' => {
127                self.parse_number()
128            }
129            Some(character) if character.is_alphabetic() || character == '_' => self.parse_name(),
130            Some(character) => Err(self.error(format!("unexpected character '{character}'"))),
131            None => Err(self.error("expected an expression")),
132        }
133    }
134
135    fn parse_number(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
136        self.parse_number_value().map(MathExpr::new_const)
137    }
138
139    fn parse_number_value(&mut self) -> Result<T, ParseError> {
140        self.skip_whitespace();
141        let start = self.position;
142        self.consume_digits();
143
144        if self.peek_char() == Some('.') {
145            self.advance_char();
146            self.consume_digits();
147        }
148
149        if matches!(self.peek_char(), Some('e' | 'E')) {
150            self.advance_char();
151            if matches!(self.peek_char(), Some('+' | '-')) {
152                self.advance_char();
153            }
154
155            let exponent_start = self.position;
156            self.consume_digits();
157            if exponent_start == self.position {
158                return Err(self.error("expected digits after the exponent"));
159            }
160        }
161
162        let token = &self.input[start..self.position];
163        token.parse::<T>().map_err(|_| ParseError {
164            position: start,
165            message: format!("invalid number '{token}'"),
166        })
167    }
168
169    fn parse_name(&mut self) -> Result<MathExpr<'a, T>, ParseError> {
170        let start = self.position;
171        self.advance_char();
172
173        while matches!(self.peek_char(), Some(character) if character.is_alphanumeric() || character == '_')
174        {
175            self.advance_char();
176        }
177
178        let name = &self.input[start..self.position];
179        self.skip_whitespace();
180
181        if self.consume_symbol('(') {
182            if name == "iif" {
183                let check = self.parse_expression()?;
184                self.expect_symbol(',')?;
185                let if_less_than_zero = self.parse_expression()?;
186                self.expect_symbol(',')?;
187                let otherwise = self.parse_expression()?;
188                self.expect_symbol(')')?;
189
190                return Ok(MathExpr::new_iif(check, if_less_than_zero, otherwise));
191            }
192
193            let operand = self.parse_expression()?;
194            self.expect_symbol(')')?;
195
196            return match name {
197                "sin" => Ok(MathExpr::new_sin(operand)),
198                "cos" => Ok(MathExpr::new_cos(operand)),
199                "tan" => Ok(MathExpr::new_tan(operand)),
200                "asin" => Ok(MathExpr::new_asin(operand)),
201                "acos" => Ok(MathExpr::new_acos(operand)),
202                "atan" => Ok(MathExpr::new_atan(operand)),
203                "sinh" => Ok(MathExpr::new_sinh(operand)),
204                "cosh" => Ok(MathExpr::new_cosh(operand)),
205                "tanh" => Ok(MathExpr::new_tanh(operand)),
206                "sign" => Ok(MathExpr::new_sign(operand)),
207                "abs" => Ok(MathExpr::new_abs(operand)),
208                "exp" => Ok(MathExpr::new_exp(operand)),
209                "sqrt" => Ok(MathExpr::new_sqrt(operand)),
210                "log" => Ok(MathExpr::new_log(operand)),
211                "log10" => Ok(MathExpr::new_log10(operand)),
212                _ => Err(ParseError {
213                    position: start,
214                    message: format!("unknown function '{name}'"),
215                }),
216            };
217        }
218
219        if let Ok(value) = name.parse::<T>() {
220            Ok(MathExpr::new_const(value))
221        } else {
222            Ok(MathExpr::new_var(name))
223        }
224    }
225
226    fn consume_digits(&mut self) {
227        while matches!(self.peek_char(), Some(character) if character.is_ascii_digit()) {
228            self.advance_char();
229        }
230    }
231
232    fn consume_symbol(&mut self, expected: char) -> bool {
233        self.skip_whitespace();
234        if self.peek_char() == Some(expected) {
235            self.advance_char();
236            true
237        } else {
238            false
239        }
240    }
241
242    fn expect_symbol(&mut self, expected: char) -> Result<(), ParseError> {
243        if self.consume_symbol(expected) {
244            Ok(())
245        } else {
246            Err(self.error(format!("expected '{expected}'")))
247        }
248    }
249
250    fn skip_whitespace(&mut self) {
251        while matches!(self.peek_char(), Some(character) if character.is_whitespace()) {
252            self.advance_char();
253        }
254    }
255
256    fn peek_char(&self) -> Option<char> {
257        self.input[self.position..].chars().next()
258    }
259
260    fn advance_char(&mut self) {
261        if let Some(character) = self.peek_char() {
262            self.position += character.len_utf8();
263        }
264    }
265
266    fn is_at_end(&self) -> bool {
267        self.position == self.input.len()
268    }
269
270    fn error(&self, message: impl Into<String>) -> ParseError {
271        ParseError {
272            position: self.position,
273            message: message.into(),
274        }
275    }
276}