Expr

Enum Expr 

Source
pub enum Expr {
Show 17 variants Const(f64), Var(VarRef), Add(Box<Expr>, Box<Expr>), Mul(Box<Expr>, Box<Expr>), Sub(Box<Expr>, Box<Expr>), Div(Box<Expr>, Box<Expr>), Abs(Box<Expr>), Pow(Box<Expr>, i64), PowFloat(Box<Expr>, f64), PowExpr(Box<Expr>, Box<Expr>), Exp(Box<Expr>), Ln(Box<Expr>), Sqrt(Box<Expr>), Sin(Box<Expr>), Cos(Box<Expr>), Neg(Box<Expr>), Cached(Box<Expr>, Option<f64>),
}
Expand description

An expression tree node representing mathematical operations.

This enum represents different types of mathematical expressions that can be:

  • JIT compiled into machine code using Cranelift
  • Symbolically differentiated to compute derivatives
  • Simplified using algebraic rules
  • Modified by inserting replacement expressions

The expression tree is built recursively using Box for nested expressions.

Variants§

§

Const(f64)

A constant floating point value

§

Var(VarRef)

A reference to a variable

§

Add(Box<Expr>, Box<Expr>)

Addition of two expressions

§

Mul(Box<Expr>, Box<Expr>)

Multiplication of two expressions

§

Sub(Box<Expr>, Box<Expr>)

Subtraction of two expressions

§

Div(Box<Expr>, Box<Expr>)

Division of two expressions

§

Abs(Box<Expr>)

Absolute value of an expression

§

Pow(Box<Expr>, i64)

Exponentiation of an expression by an integer constant

§

PowFloat(Box<Expr>, f64)

Exponentiation of an expression by a floating point constant

§

PowExpr(Box<Expr>, Box<Expr>)

Exponentiation of an expression by another expression

§

Exp(Box<Expr>)

Exponential function of an expression

§

Ln(Box<Expr>)

Natural logarithm of an expression

§

Sqrt(Box<Expr>)

Square root of an expression

§

Sin(Box<Expr>)

Sine of an expression (argument in radians)

§

Cos(Box<Expr>)

Cosine of an expression (argument in radians)

§

Neg(Box<Expr>)

Negation of an expression

§

Cached(Box<Expr>, Option<f64>)

Cached expression with optional pre-computed value

Implementations§

Source§

impl Expr

Source

pub fn pre_evaluate(&self, var_cache: &mut HashMap<String, f64>) -> Box<Expr>

Pre-evaluates constants and caches variable loads for improved performance

Source

pub fn derivative(&self, with_respect_to: &str) -> Box<Expr>

Computes the symbolic derivative of this expression with respect to a variable.

Recursively applies the rules of differentiation to build a new expression tree representing the derivative. The rules implemented are:

  • d/dx(c) = 0 for constants
  • d/dx(x) = 1 for the variable we’re differentiating with respect to
  • d/dx(y) = 0 for other variables
  • Sum rule: d/dx(f + g) = df/dx + dg/dx
  • Product rule: d/dx(f * g) = f * dg/dx + g * df/dx
  • Quotient rule: d/dx(f/g) = (g * df/dx - f * dg/dx) / g^2
  • Chain rule for abs: d/dx|f| = f/|f| * df/dx
  • Power rule: d/dx(f^n) = n * f^(n-1) * df/dx
  • Chain rule for exp: d/dx(e^f) = e^f * df/dx
  • Chain rule for ln: d/dx(ln(f)) = 1/f * df/dx
  • Chain rule for sqrt: d/dx(sqrt(f)) = 1/(2*sqrt(f)) * df/dx
  • Negation: d/dx(-f) = -(df/dx)
§Arguments
  • with_respect_to - The name of the variable to differentiate with respect to
§Returns

A new expression tree representing the derivative

Source

pub fn simplify(&self) -> Box<Expr>

Simplifies the expression by folding constants and applying basic algebraic rules.

This method performs several types of algebraic simplifications:

§Constant Folding
  • Evaluates constant expressions: 2 + 3 → 5
  • Simplifies operations with special constants: x * 0 → 0
§Identity Rules
  • Additive identity: x + 0 → x
  • Multiplicative identity: x * 1 → x
  • Division identity: x / 1 → x
  • Division by self: x / x → 1
§Exponent Rules
  • Zero exponent: x^0 → 1 (except when x = 0)
  • First power: x^1 → x
  • Nested exponents: (x^a)^b → x^(a*b)
§Special Function Simplification
  • Absolute value: |-3| → 3, ||x|| → |x|
  • Double negation: -(-x) → x
  • Evaluates constant special functions: ln(1) → 0
§Expression Caching
  • Caches repeated subexpressions to avoid redundant computation
  • Preserves existing cached values
§Returns

A new simplified expression tree

Source

pub fn insert<F>(&self, predicate: F, replacement: &Expr) -> Box<Expr>
where F: Fn(&Expr) -> bool + Clone,

Inserts an expression by replacing nodes that match a predicate.

Recursively traverses the expression tree and replaces any nodes that match the given predicate with the replacement expression. This allows for targeted modifications of the expression tree.

§Arguments
  • predicate - A closure that determines which nodes to replace
  • replacement - The expression to insert where the predicate matches
§Returns

A new expression tree with the replacements applied

Source

pub fn flatten(&self) -> FlattenedExpr

Converts expression tree to flattened linear operations for efficient evaluation.

This optimization eliminates:

  • Tree traversal overhead
  • Function call overhead
  • Memory allocation in hot path
  • Variable lookup overhead

The result is a linear sequence of stack-based operations that can be executed with minimal overhead.

Source

pub fn codegen_flattened( &self, builder: &mut FunctionBuilder<'_>, module: &mut dyn Module, ) -> Result<Value, EquationError>

Generates ultra-optimized linear code from flattened operations.

This eliminates all function call overhead by generating a single linear sequence of optimal instructions with direct register allocation.

Trait Implementations§

Source§

impl Clone for Expr

Source§

fn clone(&self) -> Expr

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Expr

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Expr

Implements string formatting for expressions.

This implementation converts expressions to their standard mathematical notation:

  • Constants are formatted as numbers
  • Variables are formatted as their names
  • Binary operations (+,-,*,/) are wrapped in parentheses
  • Functions (exp, ln, sqrt) use function call notation
  • Absolute value uses |x| notation
  • Exponents use ^
  • Negation uses - prefix
  • Cached expressions display their underlying expression
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Expr

Source§

fn eq(&self, other: &Expr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Expr

Auto Trait Implementations§

§

impl Freeze for Expr

§

impl RefUnwindSafe for Expr

§

impl Send for Expr

§

impl Sync for Expr

§

impl Unpin for Expr

§

impl UnwindSafe for Expr

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.