OptimizeExpression applies boolean algebra simplifications to a ConditionNode tree, returning an equivalent but potentially simpler and shorter expression. Rules applied (bottom-up, fixpoint iteration): Constant folding: !true → false, !false → true Double negation: !!A → A Boolean i
(node ConditionNode)
| 36 | // performed so the optimizer always terminates in O(n * maxOptimizationPasses) |
| 37 | // time relative to the number of nodes in the tree. |
| 38 | func OptimizeExpression(node ConditionNode) ConditionNode { |
| 39 | if node == nil { |
| 40 | return nil |
| 41 | } |
| 42 | |
| 43 | const maxOptimizationPasses = 10 |
| 44 | |
| 45 | current := node |
| 46 | for pass := range maxOptimizationPasses { |
| 47 | next := optimizeNode(current) |
| 48 | // Stop early when the rendered form has stabilised (fixed point). |
| 49 | if next.Render() == current.Render() { |
| 50 | expressionOptimizerLog.Printf("Expression stabilised after %d pass(es)", pass+1) |
| 51 | break |
| 52 | } |
| 53 | current = next |
| 54 | } |
| 55 | return current |
| 56 | } |
| 57 | |
| 58 | // optimizeNode performs a single bottom-up optimisation pass over the tree. |
| 59 | // It recurses into children first so that simplifications at lower levels can |