applySumPredicate tries to compute the result of sum(m..n, predicate) at compile time. Returns (result, true) if optimization is possible, (0, false) otherwise. Supported predicates: - # (identity): result = sum - # * k (multiply by constant): result = k * sum - k * # (multiply by constant): result
(sum, count int, predicateArg Node)
| 111 | // - k + # (add constant): result = sum + count * k |
| 112 | // - # - k (subtract constant): result = sum - count * k |
| 113 | func applySumPredicate(sum, count int, predicateArg Node) (int, bool) { |
| 114 | predicate, ok := predicateArg.(*PredicateNode) |
| 115 | if !ok { |
| 116 | return 0, false |
| 117 | } |
| 118 | |
| 119 | // Case 1: # (identity) - just return the sum |
| 120 | if pointer, ok := predicate.Node.(*PointerNode); ok && pointer.Name == "" { |
| 121 | return sum, true |
| 122 | } |
| 123 | |
| 124 | // Case 2: Binary operations with pointer and constant |
| 125 | binary, ok := predicate.Node.(*BinaryNode) |
| 126 | if !ok { |
| 127 | return 0, false |
| 128 | } |
| 129 | |
| 130 | pointer, constant, pointerOnLeft := extractPointerAndConstantWithPosition(binary) |
| 131 | if pointer == nil || constant == nil { |
| 132 | return 0, false |
| 133 | } |
| 134 | |
| 135 | switch binary.Operator { |
| 136 | case "*": |
| 137 | // # * k or k * # => k * sum |
| 138 | return constant.Value * sum, true |
| 139 | case "+": |
| 140 | // # + k or k + # => sum + count * k |
| 141 | return sum + count*constant.Value, true |
| 142 | case "-": |
| 143 | if pointerOnLeft { |
| 144 | // # - k => sum - count * k |
| 145 | return sum - count*constant.Value, true |
| 146 | } |
| 147 | // k - # => count * k - sum |
| 148 | return count*constant.Value - sum, true |
| 149 | } |
| 150 | |
| 151 | return 0, false |
| 152 | } |
| 153 | |
| 154 | // extractPointerAndConstantWithPosition extracts pointer (#) and integer constant from a binary node. |
| 155 | // Returns (pointer, constant, pointerOnLeft) or (nil, nil, false) if not matching the expected pattern. |
no test coverage detected
searching dependent graphs…