Skip to main content

hypervox_expr/
lib.rs

1//! Math expression parser, compiler, and CSE engine.
2//!
3//! Parses string expressions (e.g. `"sin(x)*cos(y)"`) into an AST ([`Node`]),
4//! applies constant folding ([`Node::pre_eval`]),
5//! common-subexpression elimination ([`Node::cse`]),
6//! and compiles to closures ([`Node::compile`] / [`Node::compile_multi`])
7//! for fast repeated evaluation over N-dimensional grids.
8//! Variable names are resolved through the [`VarMap`] trait.
9
10use std::{
11    fmt::{Debug, Display},
12    str::FromStr,
13};
14
15mod errors;
16mod index_set;
17mod node;
18mod parse;
19
20pub use errors::{ArithIndexSetTryFromError, Error, LexerErrorKind, ParseErrorKind};
21pub use index_set::{ArithIndexSet, ArithRangeFrom, ArithRangeIter, IndexSet, IndexSetIter};
22pub use node::{CompiledExpr, CompiledExprMulti, InvariantGroup, Node};
23pub use parse::{parse, parse_with_ext, validate, validate_with_ext};
24
25/// Trait for resolving variable names in expressions.
26/// Implementors define variable aliases and the indexed-variable naming scheme.
27pub trait VarMap {
28    /// Number of dimensions.
29    fn ndim(&self) -> usize;
30
31    /// Resolve a variable alias (e.g. "x", "y", "z") to a dimension index.
32    fn resolve_alias(&self, name: &str) -> Option<usize>;
33
34    /// Primary variable prefix used for indexed variables (e.g. "x0", "x1", ..).
35    fn primary_prefix(&self) -> &str;
36}
37
38macro_rules! define_f0 {
39    ($($variant:ident => $str:literal = $body:expr),* $(,)?) => {
40        /// Constants (PI, E).
41        #[derive(Debug, Clone, Copy)]
42        pub enum F0 {
43            $($variant,)*
44        }
45        impl F0 {
46            /// Evaluate the constant as an f64.
47            ///
48            /// # Examples
49            /// ```
50            /// # use hypervox_expr::F0;
51            /// let pi = F0::PI.to_num();
52            /// assert!((pi - std::f64::consts::PI).abs() < 1e-15);
53            /// ```
54            pub const fn to_num(self) -> f64 {
55                match self {
56                    $(Self::$variant => $body,)*
57                }
58            }
59            /// All constant names for display.
60            pub const NAMES: &'static [&'static str] = &[$($str,)*];
61        }
62        impl FromStr for F0 {
63            type Err = String;
64            fn from_str(s: &str) -> Result<Self, Self::Err> {
65                match s {
66                    $($str => Ok(Self::$variant),)*
67                    _ => Err(format!("unknown const '{s}'")),
68                }
69            }
70        }
71    };
72}
73
74macro_rules! define_f1 {
75    ($($variant:ident => $str:literal = $body:expr),* $(,)?) => {
76        /// Single-argument math functions.
77        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
78        pub enum F1 {
79            $($variant,)*
80        }
81        impl F1 {
82            /// Resolve to a function pointer.
83            ///
84            /// # Examples
85            /// ```
86            /// # use hypervox_expr::F1;
87            /// let f = F1::Sin.to_fn();
88            /// assert!((f(1.0) - 1.0_f64.sin()).abs() < 1e-15);
89            /// ```
90            #[inline]
91            pub const fn to_fn(self) -> fn(f64) -> f64 {
92                match self {
93                    $(Self::$variant => $body,)*
94                }
95            }
96            /// All function names for display.
97            pub const NAMES: &'static [&'static str] = &[$($str,)*];
98        }
99        impl FromStr for F1 {
100            type Err = String;
101            fn from_str(s: &str) -> Result<Self, Self::Err> {
102                match s {
103                    $($str => Ok(Self::$variant),)*
104                    _ => Err(format!("unknown function '{s}'")),
105                }
106            }
107        }
108    };
109}
110
111macro_rules! define_f2 {
112    ($($variant:ident => $str:literal = $body:expr),* $(,)?) => {
113        /// Two-argument math functions (atan2, pow).
114        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
115        pub enum F2 {
116            $($variant,)*
117        }
118        impl F2 {
119            /// Resolve to a function pointer.
120            ///
121            /// # Examples
122            /// ```
123            /// # use hypervox_expr::F2;
124            /// let atan2 = F2::Atan2.to_fn();
125            /// assert_eq!(atan2(0.0, 1.0), 0.0);
126            /// ```
127            #[inline]
128            pub const fn to_fn(self) -> fn(f64, f64) -> f64 {
129                match self {
130                    $(Self::$variant => $body,)*
131                }
132            }
133            /// All function names for display.
134            pub const NAMES: &'static [&'static str] = &[$($str,)*];
135        }
136        impl FromStr for F2 {
137            type Err = String;
138            fn from_str(s: &str) -> Result<Self, Self::Err> {
139                match s {
140                    $($str => Ok(Self::$variant),)*
141                    _ => Err(format!("unknown function '{s}'")),
142                }
143            }
144        }
145    };
146}
147
148define_f0! {
149    PI => "PI" = std::f64::consts::PI,
150    E => "E" = std::f64::consts::E,
151}
152
153define_f1! {
154    Sin => "sin" = f64::sin,
155    Cos => "cos" = f64::cos,
156    Tan => "tan" = f64::tan,
157    Asin => "asin" = f64::asin,
158    Acos => "acos" = f64::acos,
159    Atan => "atan" = f64::atan,
160    Sinh => "sinh" = f64::sinh,
161    Cosh => "cosh" = f64::cosh,
162    Tanh => "tanh" = f64::tanh,
163    Sqrt => "sqrt" = f64::sqrt,
164    Cbrt => "cbrt" = f64::cbrt,
165    Exp => "exp" = f64::exp,
166    Ln => "ln" = f64::ln,
167    Log10 => "log10" = f64::log10,
168    Log2 => "log2" = f64::log2,
169    Floor => "floor" = f64::floor,
170    Ceil => "ceil" = f64::ceil,
171    Round => "round" = f64::round,
172    Trunc => "trunc" = f64::trunc,
173    Abs => "abs" = f64::abs,
174}
175
176define_f2! {
177    Atan2 => "atan2" = f64::atan2,
178    Pow => "pow" = |a, b| {
179        if a == 0.0_f64 && b == 0.0_f64 {
180            1.0_f64
181        } else {
182            let exp_int = b as i32;
183            if f64::from(exp_int) == b {
184                a.powi(exp_int)
185            } else {
186                a.powf(b)
187            }
188        }
189    },
190}
191
192/// Return a comma-separated list of available constant names.
193///
194/// # Examples
195/// ```
196/// # use hypervox_expr::f0_list;
197/// let list = f0_list();
198/// assert!(list.contains("PI"));
199/// ```
200#[must_use]
201pub fn f0_list() -> String {
202    F0::NAMES.join(", ")
203}
204
205/// Return a comma-separated list of available single-argument function names.
206///
207/// # Examples
208/// ```
209/// # use hypervox_expr::f1_list;
210/// let list = f1_list();
211/// assert!(list.contains("sin"));
212/// ```
213#[must_use]
214pub fn f1_list() -> String {
215    F1::NAMES.join(", ")
216}
217
218/// Return a comma-separated list of available two-argument function names.
219///
220/// # Examples
221/// ```
222/// # use hypervox_expr::f2_list;
223/// let list = f2_list();
224/// assert!(list.contains("atan2"));
225/// ```
226#[must_use]
227pub fn f2_list() -> String {
228    F2::NAMES.join(", ")
229}
230
231/// Trait for custom constants.
232pub trait ExtF0: Debug + Clone + PartialEq {
233    /// Evaluate the constant as an f64.
234    fn to_num(&self) -> f64;
235
236    /// All constant names for display.
237    fn names(&self) -> &[&str];
238
239    /// List all constant names.
240    ///
241    /// The default implementation returns the elements of [`Self::names`] separated by commas.
242    fn list(&self) -> String {
243        self.names().join(", ")
244    }
245}
246
247/// Trait for custom single-argument functions.
248pub trait ExtF1: Debug + Clone + PartialEq {
249    /// Resolve to a function pointer.
250    fn to_fn(&self) -> fn(f64) -> f64;
251
252    /// All function names for display.
253    fn names(&self) -> &[&str];
254
255    /// List all function names.
256    ///
257    /// The default implementation returns the elements of [`Self::names`] separated by commas.
258    fn list(&self) -> String {
259        self.names().join(", ")
260    }
261}
262
263/// Trait for custom two-argument functions.
264pub trait ExtF2: Debug + Clone + PartialEq {
265    /// Resolve to a function pointer.
266    fn to_fn(&self) -> fn(f64, f64) -> f64;
267
268    /// All function names for display.
269    fn names(&self) -> &[&str];
270
271    /// List all function names.
272    ///
273    /// The default implementation returns the elements of [`Self::names`] separated by commas.
274    fn list(&self) -> String {
275        self.names().join(", ")
276    }
277}
278
279/// Define a custom-constants enum implementing [`ExtF0`] and [`FromStr`].
280///
281/// # Examples
282/// ```
283/// use hypervox_expr::ExtF0;
284/// hypervox_expr::define_ext_f0!(MyF0, MyConst => "my_const" = 42.0);
285/// assert_eq!(MyF0::MyConst.to_num(), 42.0);
286/// ```
287#[macro_export]
288macro_rules! define_ext_f0 {
289    ($enum_name:ident) => {
290        define_ext_f0!($enum_name,);
291    };
292    ($enum_name:ident, $($variant:ident => $str:literal = $body:expr),* $(,)?) => {
293        /// Constants.
294        #[expect(clippy::derive_partial_eq_without_eq)]
295        #[derive(Debug, Clone, Copy, PartialEq)]
296        pub enum $enum_name {
297            $($variant,)*
298        }
299        impl hypervox_expr::ExtF0 for $enum_name {
300            /// Evaluate the constant as an f64.
301            fn to_num(&self) -> f64 {
302                match *self {
303                    $(Self::$variant => $body,)*
304                }
305            }
306            /// All constant names for display.
307            fn names(&self) -> &[&str] {
308                &[$($str,)*]
309            }
310        }
311        impl std::str::FromStr for $enum_name {
312            type Err = String;
313            fn from_str(s: &str) -> Result<Self, Self::Err> {
314                match s {
315                    $($str => Ok(Self::$variant),)*
316                    _ => Err(format!("unknown const '{s}'")),
317                }
318            }
319        }
320    };
321}
322
323/// Define custom single-argument functions implementing [`ExtF1`] and [`FromStr`].
324///
325/// # Examples
326/// ```
327/// use hypervox_expr::ExtF1;
328/// hypervox_expr::define_ext_f1!(MyF1, Cube => "cube" = |x| x * x * x);
329/// assert_eq!(MyF1::Cube.to_fn()(3.0), 27.0);
330/// ```
331#[macro_export]
332macro_rules! define_ext_f1 {
333    ($enum_name:ident) => {
334        define_ext_f1!($enum_name,);
335    };
336    ($enum_name:ident, $($variant:ident => $str:literal = $body:expr),* $(,)?) => {
337        /// Single-argument math functions.
338        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
339        pub enum $enum_name {
340            $($variant,)*
341        }
342        impl hypervox_expr::ExtF1 for $enum_name {
343            /// Resolve to a function pointer.
344            #[inline]
345            fn to_fn(&self) -> fn(f64) -> f64 {
346                match *self {
347                    $(Self::$variant => $body,)*
348                }
349            }
350            /// All function names for display.
351            fn names(&self) -> &[&str] {
352                &[$($str,)*]
353            }
354        }
355        impl std::str::FromStr for $enum_name {
356            type Err = String;
357            fn from_str(s: &str) -> Result<Self, Self::Err> {
358                match s {
359                    $($str => Ok(Self::$variant),)*
360                    _ => Err(format!("unknown function '{s}'")),
361                }
362            }
363        }
364    };
365}
366
367/// Define custom two-argument functions implementing [`ExtF2`] and [`FromStr`].
368///
369/// # Examples
370/// ```
371/// use hypervox_expr::ExtF2;
372/// hypervox_expr::define_ext_f2!(MyF2, Hypot => "hypot" = |x, y| x.hypot(y));
373/// assert_eq!(MyF2::Hypot.to_fn()(3.0, 4.0), 5.0);
374/// ```
375#[macro_export]
376macro_rules! define_ext_f2 {
377    ($enum_name:ident) => {
378        define_ext_f2!($enum_name,);
379    };
380    ($enum_name:ident, $($variant:ident => $str:literal = $body:expr),* $(,)?) => {
381        /// Two-argument math functions (atan2, pow).
382        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
383        pub enum $enum_name {
384            $($variant,)*
385        }
386        impl hypervox_expr::ExtF2 for $enum_name {
387            /// Resolve to a function pointer.
388            #[inline]
389            fn to_fn(&self) -> fn(f64, f64) -> f64 {
390                match *self {
391                    $(Self::$variant => $body,)*
392                }
393            }
394            /// All function names for display.
395            fn names(&self) -> &[&str] {
396                &[$($str,)*]
397            }
398        }
399        impl std::str::FromStr for $enum_name {
400            type Err = String;
401            fn from_str(s: &str) -> Result<Self, Self::Err> {
402                match s {
403                    $($str => Ok(Self::$variant),)*
404                    _ => Err(format!("unknown function '{s}'")),
405                }
406            }
407        }
408    };
409}
410
411/// Zero-variant placeholder type for when no external functions/constants are used.
412///
413/// Acts as the default type parameter for [`Node`], [`parse`], and [`validate`]
414/// so that the regular API requires no generics.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum NoExtF {}
417
418impl ExtF0 for NoExtF {
419    fn to_num(&self) -> f64 {
420        unreachable!("NoExtF should never be called")
421    }
422    fn names(&self) -> &[&str] {
423        unreachable!("NoExtF should never be called")
424    }
425}
426
427impl ExtF1 for NoExtF {
428    fn to_fn(&self) -> fn(f64) -> f64 {
429        unreachable!("NoExtF should never be called")
430    }
431    fn names(&self) -> &[&str] {
432        unreachable!("NoExtF should never be called")
433    }
434}
435
436impl ExtF2 for NoExtF {
437    fn to_fn(&self) -> fn(f64, f64) -> f64 {
438        unreachable!("NoExtF should never be called")
439    }
440    fn names(&self) -> &[&str] {
441        unreachable!("NoExtF should never be called")
442    }
443}
444
445impl FromStr for NoExtF {
446    type Err = String;
447    fn from_str(_s: &str) -> Result<Self, Self::Err> {
448        Err(String::from("no external constants or functions defined"))
449    }
450}
451
452/// Token produced by the lexer and consumed by the Pratt parser.
453#[derive(Debug, Clone, PartialEq)]
454pub enum LexerToken {
455    Num(f64),
456    Ident(String),
457    Plus,
458    Minus,
459    Star,
460    Slash,
461    Caret,
462    Percent,
463    Pipe,
464    LParen,
465    RParen,
466    Comma,
467    Eof,
468}
469
470impl Display for LexerToken {
471    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
472        match self {
473            Self::Num(v) => write!(f, "{v}"),
474            Self::Ident(s) => write!(f, "'{s}'"),
475            Self::Plus => write!(f, "'+'"),
476            Self::Minus => write!(f, "'-'"),
477            Self::Star => write!(f, "'*'"),
478            Self::Slash => write!(f, "'/'"),
479            Self::Caret => write!(f, "'^'"),
480            Self::Percent => write!(f, "'%'"),
481            Self::Pipe => write!(f, "'|'"),
482            Self::LParen => write!(f, "'('"),
483            Self::RParen => write!(f, "')'"),
484            Self::Comma => write!(f, "','"),
485            Self::Eof => write!(f, "end of expression"),
486        }
487    }
488}
489
490/// Fused multiply-add that respects the `fma` feature flag.
491///
492/// Computes `self * b + c`. When the `fma` feature is enabled this maps to the
493/// hardware fused multiply-add (`mul_add`), preserving a single rounding step;
494/// otherwise it falls back to the separate multiply-then-add operations.
495///
496/// Implemented for `f32` and `f64`
497pub trait CondMulAdd {
498    #[expect(clippy::min_ident_chars)]
499    #[must_use]
500    fn cond_mul_add(self, b: Self, c: Self) -> Self;
501}
502
503#[cfg(feature = "fma")]
504impl CondMulAdd for f64 {
505    #[inline]
506    #[expect(clippy::disallowed_methods)]
507    fn cond_mul_add(self, b: Self, c: Self) -> Self {
508        self.mul_add(b, c)
509    }
510}
511
512#[cfg(not(feature = "fma"))]
513impl CondMulAdd for f64 {
514    #[inline]
515    #[expect(clippy::suboptimal_flops)]
516    fn cond_mul_add(self, b: Self, c: Self) -> Self {
517        self * b + c
518    }
519}
520
521#[cfg(feature = "fma")]
522impl CondMulAdd for f32 {
523    #[inline]
524    #[expect(clippy::disallowed_methods)]
525    fn cond_mul_add(self, b: Self, c: Self) -> Self {
526        self.mul_add(b, c)
527    }
528}
529
530#[cfg(not(feature = "fma"))]
531impl CondMulAdd for f32 {
532    #[inline]
533    #[expect(clippy::suboptimal_flops)]
534    fn cond_mul_add(self, b: Self, c: Self) -> Self {
535        self * b + c
536    }
537}