expr-solver
A mathematical expression evaluator library written in Rust with support for custom functions, constants, and bytecode compilation.
Features
- Mathematical expressions - Arithmetic, comparisons, and built-in functions
- 128-bit decimal precision - No floating-point errors using
rust_decimal - Custom symbols - Register your own constants and functions
- Rich error messages - Syntax errors with source location highlighting
- Bytecode compilation - Compile expressions to portable binary format
- Stack-based VM - Efficient execution on a virtual machine
How It Works
Classic compiler pipeline with type-safe state transitions:
Input → Lexer → Parser → Compiler → Program<Compiled>
↓ link
Program<Linked> → Execute
The Program type uses Rust's type system to enforce correct usage at compile time. You cannot execute an unlinked program, and you cannot link a program twice.
Usage
As a Library
Add this to your Cargo.toml:
[]
= "1.1.0"
As a binary
Add this to your Cargo.toml:
[]
= "1.1.0"
Quick Evaluation
use eval;
// Simple one-liner
let result = eval.unwrap;
assert_eq!;
// With built-in functions
let result = eval.unwrap;
Custom Symbols
use ;
use dec;
let mut table = stdlib;
table.add_const.unwrap;
table.add_func.unwrap;
let result = eval_with_table.unwrap;
assert_eq!;
Compile Once, Execute Many Times
use ;
use dec;
// Compile expression
let program = load.unwrap;
// Execute with different values
let mut table = new;
table.add_const.unwrap;
table.add_const.unwrap;
let linked = program.link.unwrap;
let result = linked.execute.unwrap; // 25
Precision
Uses 128-bit Decimal arithmetic for exact decimal calculations without floating-point errors.
Built-in Functions
| Category | Functions |
|---|---|
| Arithmetic | abs, sign, floor, ceil, round, trunc, fract, mod, clamp |
| Trig | sin, cos, tan, asin, acos, atan, atan2 |
| Hyperbolic | sinh, cosh, tanh* |
| Exp/Log | sqrt, cbrt, pow, exp, exp2, log, log2, log10, hypot |
| Variadic | min, max, sum, avg (1+ args) |
| Special | if(cond, then, else) |
* Uses f64 internally, may have minor precision differences
Built-in Constants
pi, e, tau, ln2, ln10, sqrt2
All names are case-insensitive.
Operators
Arithmetic: +, -, *, /, ^ (power), ! (factorial), unary -
Comparison: ==, !=, <, <=, >, >= (returns 1 or 0)
Grouping: ( )
Command Line Usage
# Evaluate an expression
# Use the -e flag
# Define custom constants
# Compile to binary
# Execute compiled binary
# View assembly
# List available functions and constants
Testing
Run the test suite:
# Run all tests
License
This project is licensed under the MIT License.