Class Optimizer
Formula. A pure function: it reads one program and returns another, and never mutates its input.7+(1+(2*3)) collapses to a single CONST 14.
This is NOT run automatically. Folding discards what the developer wrote. They may have written 2*3 because it is 2 columns by 3 rows and they intend to edit it, and an editor that silently rewrote it as 6 would be eating their work. It is an explicit user action -- a "simplify" button -- reached through GUnit.simplifyFormula().
Parenthesis minimisation is not part of this. The opcode array contains no parentheses to begin with, so Formula.toSource() emits the minimum set on every call and nothing has to be optimised away. See that method.
A SCALE ends foldability of its operand. 10%+5 cannot fold: 10% is not known until evaluation. Nothing here reassociates across a SCALE either -- rewriting 10%*2 as 20% is mathematically valid, since scaling IS multiplication, but it reorders floating-point operations and can change the last bits. The pattern match below is purely local and adjacent, so a SCALE between two constants simply prevents the match.
Why folding is not unconditional
The obvious claim -- that folding is exact because it performs the same operation the runtime would -- is true of the ARITHMETIC and false of the STORAGE. A constant is not a double: it is the integer / decimal-digit-count / decimal triple that a simpleGUnit value uses, which holds at most seven decimal places. So:1/3evaluates to0.3333333333333333but would store as0.3333333. Folding it would silently change the value.0.1+0.2evaluates to0.30000000000000004but would store as0.3.- A result outside the integer range, or one needing a sign on a zero integer part, cannot be represented at all.
7+(1+(2*3)) folds; 1px/3 does not. This is what makes the promise "a folded formula evaluates bit-identically to the unfolded one" actually true.Op.OP_MIN2 and Op.OP_MAX2 need no guard: the result is one of the two operands, so its triple is copied across verbatim and cannot lose anything.
- Author:
- Christopher Mindus
Method Summary
Method Details
fold