2 min readMar 29, 2026by jakub
Calculon
Calculon is a mathematical expression parser and evaluator for PHP, built on a proper AST (Abstract Syntax Tree) architecture. Named after the melodramatic acting robot from Futurama, it combines serious functionality with entertaining error messages.
Use it whenever you need to evaluate user-provided mathematical formulas safely — pricing rules, discount calculations, shipping cost formulas, or any scenario where business users need to define their own calculations without touching PHP code.
GitHub: qoliber/calculon
Installation
Bash
composer require qoliber/calculonRequires: PHP 8.1+
Key Features
- Safe evaluation — User-provided expressions are parsed into an AST and evaluated without
eval(). No code injection possible. - Variables — Pass runtime values into expressions:
price * quantity * (1 - discount) - Built-in functions —
sin,cos,sqrt,log,abs,ceil,floor,round,min,max,pow - Constants —
PIandEpre-defined, register your own - Percentage calculations — Context-aware:
100 + 10%=110, not100.1 - Custom functions — Implement
FunctionInterfaceto add domain-specific functions (tax calculation, currency conversion, margin formulas) - Validation — Validate expressions without evaluating them, useful for form validation
- Variable extraction — Automatically discover which variables a formula requires
Architecture
Clean four-stage pipeline:
- Lexer — Tokenizes the input string into meaningful tokens
- Parser — Builds an Abstract Syntax Tree respecting operator precedence
- AST Nodes — Typed representation of the expression structure
- Evaluator — Traverses the tree using the Visitor pattern, resolving values
Performance
Benchmarked on real-world expressions:
| Expression Type | Operations/sec |
|---|---|
| Simple arithmetic | ~350,000 |
| Variables + functions | ~171,000 |
| Complex e-commerce formulas | ~57,000 |
Quality
- 192 unit tests, 495 assertions
- 100% code coverage
- 97% mutation score (Infection)
- PHPStan level 8
License
MIT License
Was this page helpful?