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/calculon

Requires: 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 functionssin, cos, sqrt, log, abs, ceil, floor, round, min, max, pow
  • ConstantsPI and E pre-defined, register your own
  • Percentage calculations — Context-aware: 100 + 10% = 110, not 100.1
  • Custom functions — Implement FunctionInterface to 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:

  1. Lexer — Tokenizes the input string into meaningful tokens
  2. Parser — Builds an Abstract Syntax Tree respecting operator precedence
  3. AST Nodes — Typed representation of the expression structure
  4. Evaluator — Traverses the tree using the Visitor pattern, resolving values

Performance

Benchmarked on real-world expressions:

Expression TypeOperations/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?
Calculon — PHP Libraries & Tools — Open Source | qoliber Docs