Skip to main content

egui_pop_core/slider/
expr.rs

1//! What a slider's typed entry accepts: a number or a simple expression,
2//! written as the user's locale writes numbers, with an optional unit
3//! after it.
4//!
5//! - Numbers take a point or a comma as the decimal separator; when a
6//!   text has both, the last one is the decimal separator and the other
7//!   groups thousands (`1,234.5`, `1.234,5`). Spaces, no-break spaces and
8//!   apostrophes before three digits group thousands (`1 234,5`,
9//!   `1’234.5`).
10//! - Operators: `+ - * /`, `^` (power, right-associative), parentheses,
11//!   a sign before any term. `x` is the slider's current value.
12//! - What follows the expression is a unit and is ignored (`1.5 EV`,
13//!   `+3%`); a text that starts with neither a number, a sign, `x` nor a
14//!   parenthesis is not a value.
15//!
16//! ```
17//! use egui_pop_core::slider::expr::eval;
18//!
19//! assert_eq!(eval("1,5 EV", 0.0), Some(1.5));
20//! assert_eq!(eval("x * 2", 0.25), Some(0.5));
21//! assert_eq!(eval("(1 + 2) ^ 2 - 1", 0.0), Some(8.0));
22//! assert_eq!(eval("1 234,5", 0.0), Some(1234.5));
23//! assert_eq!(eval("EV", 0.0), None);
24//! assert_eq!(eval("1/0", 0.0), None);
25//! ```
26
27/// The value of `text`, `x` being `current`; `None` when it is not a
28/// value or not finite.
29pub fn eval(text: &str, current: f64) -> Option<f64> {
30    let normal = normalise(text);
31    let mut p = Parser {
32        s: normal.as_bytes(),
33        at: 0,
34        x: current,
35    };
36    let v = p.expr()?;
37    p.space();
38    // Whatever is left is a unit: it must not look like more expression.
39    match p.peek() {
40        None => {}
41        Some(c) if c.is_ascii_digit() || b"+-*/^(.".contains(&c) => return None,
42        Some(_) => {}
43    }
44    v.is_finite().then_some(v)
45}
46
47/// The text with one decimal separator (`.`) and no group separators.
48fn normalise(text: &str) -> String {
49    let t = text.trim();
50    let (point, comma) = (t.rfind('.'), t.rfind(','));
51    // The decimal separator is the last of `.` and `,`; the other groups.
52    let (decimal, group) = match (point, comma) {
53        (Some(p), Some(c)) if c > p => (',', '.'),
54        (Some(_), Some(_)) => ('.', ','),
55        (None, Some(_)) => (',', '.'),
56        _ => ('.', ','),
57    };
58    let chars: Vec<char> = t.chars().collect();
59    let mut out = String::with_capacity(t.len());
60    for (i, &c) in chars.iter().enumerate() {
61        // A group separator sits between a digit and exactly three.
62        let digit_before = i > 0 && chars[i - 1].is_ascii_digit();
63        let three_after = chars.len() > i + 3
64            && chars[i + 1..=i + 3].iter().all(char::is_ascii_digit)
65            && !chars.get(i + 4).is_some_and(char::is_ascii_digit);
66        let grouping = matches!(c, ' ' | '\u{a0}' | '\u{202f}' | '\'' | '’');
67        if c == decimal {
68            out.push('.');
69        } else if (c == group || grouping) && digit_before && three_after {
70            // A group separator between digits: dropped.
71        } else {
72            out.push(c);
73        }
74    }
75    out
76}
77
78struct Parser<'a> {
79    s: &'a [u8],
80    at: usize,
81    x: f64,
82}
83
84impl Parser<'_> {
85    fn space(&mut self) {
86        while self.peek().is_some_and(|c| c.is_ascii_whitespace()) {
87            self.at += 1;
88        }
89    }
90
91    fn peek(&self) -> Option<u8> {
92        self.s.get(self.at).copied()
93    }
94
95    /// The next byte after spaces, consumed when it is one of `ops`.
96    fn op(&mut self, ops: &[u8]) -> Option<u8> {
97        let save = self.at;
98        self.space();
99        match self.peek() {
100            Some(c) if ops.contains(&c) => {
101                self.at += 1;
102                Some(c)
103            }
104            _ => {
105                self.at = save;
106                None
107            }
108        }
109    }
110
111    fn expr(&mut self) -> Option<f64> {
112        let mut v = self.term()?;
113        while let Some(op) = self.op(b"+-") {
114            let rhs = self.term()?;
115            v = if op == b'+' { v + rhs } else { v - rhs };
116        }
117        Some(v)
118    }
119
120    fn term(&mut self) -> Option<f64> {
121        let mut v = self.unary()?;
122        while let Some(op) = self.op(b"*/") {
123            let rhs = self.unary()?;
124            v = if op == b'*' { v * rhs } else { v / rhs };
125        }
126        Some(v)
127    }
128
129    fn unary(&mut self) -> Option<f64> {
130        match self.op(b"+-") {
131            Some(b'-') => Some(-self.unary()?),
132            Some(_) => self.unary(),
133            None => self.power(),
134        }
135    }
136
137    fn power(&mut self) -> Option<f64> {
138        let base = self.atom()?;
139        if self.op(b"^").is_some() {
140            let exp = self.unary()?;
141            return Some(base.powf(exp));
142        }
143        Some(base)
144    }
145
146    fn atom(&mut self) -> Option<f64> {
147        self.space();
148        match self.peek()? {
149            b'(' => {
150                self.at += 1;
151                let v = self.expr()?;
152                self.op(b")")?;
153                Some(v)
154            }
155            b'x' | b'X' => {
156                self.at += 1;
157                Some(self.x)
158            }
159            c if c.is_ascii_digit() || c == b'.' => {
160                let start = self.at;
161                while self.peek().is_some_and(|c| c.is_ascii_digit() || c == b'.') {
162                    self.at += 1;
163                }
164                std::str::from_utf8(&self.s[start..self.at])
165                    .ok()?
166                    .parse()
167                    .ok()
168            }
169            _ => None,
170        }
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::eval;
177
178    #[test]
179    fn numbers_in_any_locale() {
180        assert_eq!(eval("1,5 EV", 0.0), Some(1.5));
181        assert_eq!(eval(" -0.25", 0.0), Some(-0.25));
182        assert_eq!(eval("+3%", 0.0), Some(3.0));
183        assert_eq!(eval("1,234.5", 0.0), Some(1234.5));
184        assert_eq!(eval("1.234,5", 0.0), Some(1234.5));
185        assert_eq!(eval("1\u{202f}234,5", 0.0), Some(1234.5));
186        assert_eq!(eval("12’000 K", 0.0), Some(12000.0));
187        assert_eq!(eval("EV", 0.0), None);
188        assert_eq!(eval("", 0.0), None);
189    }
190
191    #[test]
192    fn expressions() {
193        assert_eq!(eval("1 + 2 * 3", 0.0), Some(7.0));
194        assert_eq!(eval("(1 + 2) * 3", 0.0), Some(9.0));
195        assert_eq!(eval("2 ^ 3 ^ 2", 0.0), Some(512.0));
196        assert_eq!(eval("-2 ^ 2", 0.0), Some(-4.0));
197        assert_eq!(eval("x / 2 EV", 3.0), Some(1.5));
198        assert_eq!(eval("x - 1", 0.5), Some(-0.5));
199        assert_eq!(eval("1 / 0", 0.0), None);
200        assert_eq!(eval("(1 + 2", 0.0), None);
201        assert_eq!(eval("2 3", 0.0), None);
202    }
203}