math and logic formula parser and evaluator
Dentaku is a parser and evaluator for a mathematical and logical formula language that allows run-time binding of values to variables referenced in the formulas. It is intended to safely evaluate untrusted expressions without opening security holes.
Dentaku supports Ruby 3.2 and newer, tracking Ruby's own maintenance policy: when a Ruby version reaches end-of-life, it may be dropped from the supported compatibility contract in the next major or minor release. Older Rubies may continue to work, but are not tested.
New code should target the lowest supported Ruby version, currently Ruby 3.2.
This is probably simplest to illustrate in code:
calculator = Dentaku::Calculator.new
calculator.evaluate('10 * 2')
#=> 20Okay, not terribly exciting. But what if you want to have a reference to a variable, and evaluate it at run-time? Here's how that would look:
calculator.evaluate('kiwi + 5', kiwi: 2)
#=> 7To enter a case sensitive mode, just pass an option to the calculator instance:
calculator.evaluate('Kiwi + 5', Kiwi: -2, kiwi: 2)
#=> 7
calculator = Dentaku::Calculator.new(case_sensitive: true)
calculator.evaluate('Kiwi + 5', Kiwi: -2, kiwi: 2)
#=> 3You can also store the variable values in the calculator's memory and then evaluate expressions against those stored values:
calculator.store(peaches: 15)
calculator.evaluate('peaches - 5')
#=> 10
calculator.evaluate('peaches >= 15')
#=> trueFor maximum CS geekery, bind is an alias of store.
Dentaku understands precedence order and using parentheses to group expressions to ensure proper evaluation:
calculator.evaluate('5 + 3 * 2')
#=> 11
calculator.evaluate('(5 + 3) * 2')
#=> 16The evaluate method will return nil if there is an error in the formula.
If this is not the desired behavior, use evaluate!, which will raise an
exception.
calculator.evaluate('10 * x')
#=> nil
calculator.evaluate!('10 * x')
Dentaku::UnboundVariableError: Dentaku::UnboundVariableErrorDentaku has built-in functions (including if, not, min, max, sum, and
round) and the ability to define custom functions (see below). Functions
generally work like their counterparts in Excel:
calculator.evaluate('SUM(1, 1, 2, 3, 5, 8)')
#=> 20
calculator.evaluate('if (pears 10
calculator.evaluate('if (pears 20round can be called with or without the number of decimal places:
calculator.evaluate('round(8.2)')
#=> 8
calculator.evaluate('round(8.2759, 2)')
#=> 8.28round follows rounding rules, while roundup and rounddown are ceil and
floor, respectively.
If you're too lazy to be building calculator objects, there's a shortcut just for you:
Dentaku('plums * 1.5', plums: 2)
#=> 3.0The flexibility and safety of Dentaku don't come without a price. Tokenizing a string, parsing to an AST, and then evaluating that AST are about 2 orders of magnitude slower than doing the same math in pure Ruby!
The good news is that most of the time is spent in the tokenization and parsing phases, so if performance is a concern, you can enable AST caching:
Dentaku.enable_ast_cache!Caching can also be controlled per calculator, overriding the module-level setting:
calculator = Dentaku::Calculator.new(cache_ast: true)After this, Dentaku will cache the AST of each formula that it evaluates, so subsequent evaluations (even with different values for variables) will be much faster -- closer to 4x native Ruby speed. As usual, these benchmarks should be considered rough estimates, and you should measure with representative formulas from your application. Also, if new formulas are constantly introduced to your application, AST caching will consume more memory with each new formula.
Dentaku treats formulas as pure: a subexpression may be evaluated zero, one,
or more than one time (for example, a guard position may be evaluated once
during dependency analysis and again during evaluation), so custom functions
should not rely on side effects or call counts. Functions that fall outside
this contract -- reading external state, performing I/O, or returning
different values across calls -- must be registered with volatile: true
(see EXTERNAL FUNCTIONS below). Volatile functions are never invoked during
dependency analysis; in guard positions this means no branch can be pruned,
so all branches count as dependencies and evaluate! requires variables
from every branch to be bound.
Logical constructs short-circuit. IF and CASE only evaluate the branch
that is taken, and AND / OR resolve as soon as one operand decides the
result. An unbound variable raises Dentaku::UnboundVariableError only when
its value is actually needed:
calculator.evaluate!('a OR b', a: true) #=> true
calculator.evaluate!('a OR b', a: false) #=> raises Dentaku::UnboundVariableErrorTwo methods answer two different questions about a formula's inputs:
calculator.dependencies(expression, context) reports the identifiers a
formula still needs, given what is already known. It is resolution-aware:
guard positions (IF predicates, CASE switches, AND / OR operands)
whose own dependencies are already satisfied are evaluated -- executing any
(non-volatile) functions they contain -- in order to prune branches that
cannot be taken.
calculator.identifiers(expression) reports every identifier the formula
could ever reference, regardless of branching. It is purely syntactic:
nothing is evaluated, no functions run (volatile or not), and stored
variables are not subtracted. Use it to statically list a formula's
possible inputs, e.g. to tell users what values they may need to supply.
calculator.dependencies('IF(x > 5, y, z)', x: 7) #=> ["y"]
calculator.identifiers('IF(x > 5, y, z)') #=> ["x", "y", "z"]Because unused operands are never checked at evaluation time, a misspelled
identifier on a branch that is not taken will not be reported; use
identifiers for static validation.
Context keys prefixed with a double underscore (e.g. __evaluation_mode)
are reserved for internal use.
Math: +, -, *, /, %, ^, |, &, >
Also, all functions from Ruby's Math module, including SIN, COS, TAN, etc.
Comparison: ``, =, <>, !=, =,
Logic: IF, AND, OR, XOR, NOT, SWITCH
Numeric: MIN, MAX, SUM, AVG, COUNT, ROUND, ROUNDDOWN, ROUNDUP, ABS, INTERCEPT
Selections: CASE (syntax see spec)
String: LEFT, RIGHT, MID, LEN, FIND, SUBSTITUTE, CONCAT, CONTAINS
Collection: MAP, FILTER, ALL, ANY, PLUCK
If your formulas rely on one another, they may need to be resolved in a particular order. For example:
calc = Dentaku::Calculator.new
calc.store(monthly_income: 50)
need_to_compute = {
income_taxes: "annual_income / 5",
annual_income: "monthly_income * 12"
}In the example, annual_income needs to be computed (and stored) before
income_taxes.
Dentaku provides two methods to help resolve formulas in order:
Pass a (string) expression to Dependencies and get back a list of variables (as
:symbols) that are required for the expression. Dependencies also takes
into account variables already (explicitly) stored into the calculator.
calc.dependencies("monthly_income * 12")
#=> []
# (since monthly_income is in memory)
calc.dependencies("annual_income / 5")
#=> [:annual_income]Have Dentaku figure out the order in which your formulas need to be evaluated.
Pass in a hash of {eventual_variable_name: "expression"} to solve! and
have Dentaku resolve dependencies (using TSort) for you.
Raises TSort::Cyclic when a valid expression order cannot be found.
calc = Dentaku::Calculator.new
calc.store(monthly_income: 50)
need_to_compute = {
income_taxes: "annual_income / 5",
annual_income: "monthly_income * 12"
}
calc.solve!(need_to_compute)
#=> {annual_income: 600, income_taxes: 120}
calc.solve!(
make_money: "have_money",
have_money: "make_money"
}
#=> raises TSort::Cyclicsolve! will also raise an exception if any of the formulas in the set cannot
be evaluated (e.g. raise ZeroDivisionError). The non-bang solve method will
find as many solutions as possible and return the symbol :undefined for the
problem formulas.
If your expressions grow long or complex, you may add inline comments for future reference. This is particularly useful if you save your expressions in a model.
calculator.evaluate('kiwi + 5 /* This is a comment */', kiwi: 2)
#=> 7Comments can be single or multi-line. The following are also valid.
/*
* This is a multi-line comment
*/
/*
This is another type of multi-line comment
*/I don't know everything, so I might not have implemented all the functions you need. Please implement your favorites and send a pull request! Okay, so maybe that's not feasible because:
NOW()Whatever your reasons, Dentaku supports adding functions at runtime. To add a function, you'll need to specify a name, a return type, and a lambda that accepts all function arguments and returns the result value.
Here's an example of adding a function named POW that implements
exponentiation.
> c = Dentaku::Calculator.new
> c.add_function(:pow, :numeric, ->(mantissa, exponent) { mantissa ** exponent })
> c.evaluate('POW(3,2)')
#=> 9
> c.evaluate('POW(2,3)')
#=> 8Here's an example of adding a variadic function:
> c = Dentaku::Calculator.new
> c.add_function(:max, :numeric, ->(*args) { args.max })
> c.evaluate 'MAX(8,6,7,5,3,0,9)'
#=> 9(However both of these are already built-in -- the ^ operator and the MAX
function)
Functions can be added individually using Calculator#add_function, or en masse using Calculator#add_functions.
The second argument is the function's declared return type. It is used at
parse time to decide whether a call to the function is a valid operand of an
arithmetic operator -- only :numeric, :integer, :array, and nil are
accepted there. Declaring anything else means the function cannot be used in
arithmetic:
> c = Dentaku::Calculator.new
> c.add_function(:label, :string, ->(x) { "item#{x}" })
> c.evaluate!('label(1)')
#=> "item1"
> c.evaluate!("label(1) = 'item1'") # comparison: type is not consulted
#=> true
> c.evaluate!('label(1) + 1') # arithmetic: rejected at parse time
#=> Dentaku::ParseError: Dentaku::AST::Addition requires operands that are
# numeric or compatible types, not stringThe type is a declaration, not a guarantee: Dentaku does not coerce the return
value and does not check it at runtime. Declaring :numeric for a function
that actually returns a String defers the failure to whatever consumes it:
> c.add_function(:mislabeled, :numeric, ->(x) { "item#{x}" })
> c.evaluate!('mislabeled(1) + 1')
#=> Dentaku::ArgumentError: String input 'item1' is not coercible to numericSo the type only has an observable effect when the result feeds an arithmetic operator. A function used standalone, in comparisons, or as a function argument behaves the same whatever type is declared -- which is why an incorrect type can go unno
No open issues yet, or sync has not completed.