Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions optimizer/sum_range.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ func (*sumRange) Visit(node *Node) {
m := from.Value
n := to.Value
if n >= m {
count := n - m + 1
// Use the arithmetic series formula: (n - m + 1) * (m + n) / 2
sum := count * (m + n) / 2
sum, count := rangeSum(m, n)

if len(sumBuiltin.Arguments) == 1 {
// sum(m..n)
Expand Down Expand Up @@ -47,8 +45,7 @@ func (*sumRange) Visit(node *Node) {
m := from.Value
n := to.Value
if n >= m {
// Use the arithmetic series formula: (n - m + 1) * (m + n) / 2
sum := (n - m + 1) * (m + n) / 2
sum, _ := rangeSum(m, n)

// Check for optional initialValue (3rd argument)
if len(reduceBuiltin.Arguments) == 3 {
Expand All @@ -67,6 +64,19 @@ func (*sumRange) Visit(node *Node) {
}
}

// rangeSum computes the sum of integers in [m, n] (for n >= m) and the element
// count in two's complement int arithmetic without overflowing before dividing by 2.
func rangeSum(m, n int) (int, int) {
diff := uint(n) - uint(m)
count := diff + 1
if diff&1 == 1 {
halfCount := (diff >> 1) + 1
return int(halfCount * (uint(m) + uint(n))), int(count)
}
halfSum := uint(m) + (diff >> 1)
return int(count * halfSum), int(count)
}

// isPointerPlusAcc checks if the node represents `# + #acc` pattern
func isPointerPlusAcc(node Node) bool {
predicate, ok := node.(*PredicateNode)
Expand Down
80 changes: 80 additions & 0 deletions optimizer/sum_range_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package optimizer_test

import (
"fmt"
"math"
"testing"

"github.com/expr-lang/expr"
Expand Down Expand Up @@ -246,6 +248,84 @@ func TestOptimize_reduce_range_reversed_errors(t *testing.T) {
require.Error(t, err, "reduce on empty range should error")
}

func TestOptimize_sum_range_overflow(t *testing.T) {
halfMax := math.MaxInt/2 + 1
thirdMax := math.MaxInt / 3

tests := []struct {
name string
code string
want int
}{
{
name: "single element m+n overflows int",
code: fmt.Sprintf("sum(%d..%d)", halfMax, halfMax),
want: halfMax,
},
{
name: "two elements summing to MaxInt",
code: fmt.Sprintf("sum(%d..%d)", halfMax-1, halfMax),
want: math.MaxInt,
},
{
name: "two negative elements summing to -MaxInt",
code: fmt.Sprintf("sum(%d..%d)", -halfMax, -halfMax+1),
want: -math.MaxInt,
},
{
name: "three elements count*(m+n) overflows int",
code: fmt.Sprintf("sum(%d..%d)", thirdMax-1, thirdMax+1),
want: 3 * thirdMax,
},
{
name: "two elements wrapping int sum matches unoptimized",
code: fmt.Sprintf("sum(%d..%d)", halfMax, halfMax+1),
want: halfMax + (halfMax + 1),
},
{
name: "sum with predicate on large range",
code: fmt.Sprintf("sum(%d..%d, # - 1)", halfMax-1, halfMax),
want: math.MaxInt - 2,
},
{
name: "reduce sum without initial value",
code: fmt.Sprintf("reduce(%d..%d, # + #acc)", halfMax-1, halfMax),
want: math.MaxInt,
},
{
name: "reduce sum with initial value",
code: fmt.Sprintf("reduce(%d..%d, # + #acc, -1)", halfMax-1, halfMax),
want: math.MaxInt - 1,
},
{
name: "negative odd-length range",
code: "sum(-5..-3)",
want: -12,
},
{
name: "zero-crossing even-length range",
code: "sum(-5..6)",
want: 6,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
optimized, err := expr.Compile(tt.code)
require.NoError(t, err)
got, err := expr.Run(optimized, nil)
require.NoError(t, err)
assert.Equal(t, tt.want, got)

unoptimized, err := expr.Compile(tt.code, expr.Optimize(false))
require.NoError(t, err)
wantUnopt, err := expr.Run(unoptimized, nil)
require.NoError(t, err)
assert.Equal(t, wantUnopt, got)
})
}
}

func BenchmarkSumRange_Optimized(b *testing.B) {
program, err := expr.Compile(`sum(1..100)`)
require.NoError(b, err)
Expand Down