Skip to content

Lower sum(range) to closed-form arithmetic - #536

Merged
godofecht merged 13 commits into
mainfrom
feat/sum-range-closed-form
Aug 18, 2026
Merged

godofecht merged 13 commits into
mainfrom
feat/sum-range-closed-form

Conversation

@godofecht

@godofecht godofecht commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #475.

Adds an exclusive-end RangeExpression AST boundary for range-aware builtins and teaches sum(...) to recognize start..end / start..end step step without changing ordinary function-call, for, or slice parsing. sum(range) is immediately desugared to existing arithmetic/comparison/if-expression AST, so C and MLIR backends require no range-specific codegen.

Literal ranges fold immediately during parsing: sum(0..1000 step 3) becomes the literal 166833. Runtime-bound ranges lower to O(1) closed-form arithmetic, support positive and negative steps and non-zero starts, return zero for empty direction/runtime zero step, and reject a literal zero step at compile time.

Integration coverage compiles generated C, asserts the runtime-bound sum function contains no for/while, executes positive/descending/empty/runtime-zero cases, and separately asserts parse-time literal folding. Focused regression, Python tests, arithmetic safety, parser/pipeline fuzz, lint, security and examples are green; tier-2 is the remaining broad corpus gate.

The RangeExpression node is intentionally separate from ForStatement; #476 can generalize expression-range parsing/algebra on the same AST without changing loop representation.

@godofecht

Copy link
Copy Markdown
Contributor Author

Reviewed this while clearing the issue backlog. The design holds up and CI is green, including tier-2, so the "remaining broad corpus gate" line in the description is now satisfied. Two correctness problems survive it, both reproduced by execution against a hand-written loop.

1. The runtime path overflows where the loop does not

_sum_for_count builds count * (2*start + (count-1)*step) / 2. That intermediate is exactly twice the true sum, so it wraps once the real answer passes 2^30, even though i32 holds up to 2^31-1. The loop form computes the same answer without ever forming the doubled value.

function loop_sum(limit: i32, stride: i32) -> i32 {
    let mut total: i32 = 0
    let mut n: i32 = 0
    while n < limit {
        total = total + n
        n = n + stride
    }
    return total
}

function closed_sum(limit: i32, stride: i32) -> i32 {
    return sum(0..limit step stride)
}

function main() -> i32 {
    printf("closed=%d looped=%d\n", closed_sum(54773, 1), loop_sum(54773, 1))
    return 0
}
closed=-647470270 looped=1500013378

1500013378 fits in i32 with room to spare. The doubled intermediate, 3000026756, does not.

The literal path is unaffected, since _constant_range_sum folds in Python integers. sum(0..54773 step 1) folds to 1500013378 correctly. Only runtime-bound ranges are wrong, which is also why the existing tests miss it: runtime(0, 1000, 3) and friends all stay under 2^30.

A fix that keeps everything in i32 is to halve before multiplying, picking the side that is known even. When count is even use (count/2) * (2*start + (count-1)*step); when it is odd, (count-1)*step and 2*start are both even, so count * ((2*start + (count-1)*step)/2) is exact. Neither branch forms the doubled product.

2. Range bounds are evaluated more than once

The lowering shares the start, end and step AST nodes across every position in the generated expression, so a bound with side effects runs repeatedly. A for loop over the same range evaluates each bound once.

let mut end_calls: i32 = 0
let mut step_calls: i32 = 0
let mut start_calls: i32 = 0

function an_end(v: i32) -> i32 { end_calls = end_calls + 1 return v }
function a_step(v: i32) -> i32 { step_calls = step_calls + 1 return v }
function a_start(v: i32) -> i32 { start_calls = start_calls + 1 return v }

function main() -> i32 {
    let total: i32 = sum(a_start(0)..an_end(1000) step a_step(3))
    printf("total=%d start=%d end=%d step=%d\n", total, start_calls, end_calls, step_calls)
    return 0
}
total=166833 start=4 end=3 step=8

The value is right. The call counts are not.

Part of this is also plain duplicated work: _count_positive is rebuilt inside _sum_for_count, so the taken branch runs two FLOW_CHECKED_DIV operations where one would do.

Lowering sum(a..b step c) to a call into a generated helper taking the three bounds would fix this and the overflow together. The bounds evaluate once at the call site, and inside the helper they are ordinary locals, so the closed form can compute count once and branch on its parity using statements rather than nested if-expressions. It does cost the parser a declaration, which is a step away from the "desugar to existing AST only" constraint in the description, so it is your call.

What is right

Verified working: zero-length ranges, descending ranges, a runtime zero step returning 0 rather than dividing by zero (the C ternary short-circuits, so the divide is never reached), and the literal fold. sum(0..-10 step -1) gives -45. The compile-time rejection of a literal zero step works.

Happy to implement either fix if you want it. Flagging rather than pushing to your branch.

godofecht and others added 2 commits August 18, 2026 22:21
Both were reported on this PR and both are reproduced by execution against a
hand-written loop over the same range.

Overflow. `_sum_for_count` built `n * (2a + (n-1)d) / 2`, so the intermediate
was exactly twice the answer and wrapped once the real sum passed 2^30, even
though i32 reaches 2^31-1. A loop computing the same sum does not overflow
there, so the closed form was wrong precisely where it was most useful:

    sum(0..54773 step 1)    loop 1500013378    closed -647470270

One of the two factors is always even: when n is even, n/2 is exact; when n is
odd, both 2a and (n-1)d are even, so the bracket is. Halving whichever one is
even keeps every intermediate inside the range of the result.

Repeated evaluation. The lowering shared the start, end and step AST nodes
across every position in the generated expression, so a bound with a side
effect ran many times. A `for` loop over the same range evaluates each once.

    sum(a_start(0)..an_end(1000) step a_step(3))
    before   start 4   end 3   step 8

Fixing the overflow with an if-expression made this worse rather than better,
because the parity split duplicates the bracket: 5, 4 and 11. So the lowering
now goes through one helper function per module instead of being inlined at
the call site. The bounds become its three arguments and are evaluated once
each, and having a body means the count lives in a local, so the parity split
costs one branch instead of a second copy of the arithmetic.

    after    start 1   end 1   step 1

The helper is written as Flow source and parsed, rather than assembled node by
node, because the body is the clearest statement of the identity and it reads
next to the comment explaining why the arithmetic is arranged this way. It is
appended to the module only when something used it.

Literal folding is unchanged: sum(0..1000 step 3) is still the literal 166833
at parse time.

Both bugs have regression tests that compile and run the program and compare
against a loop. Unit 1512 passed; the 17 integration failures are the same
ones present without this change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@godofecht
godofecht marked this pull request as ready for review August 18, 2026 21:52
@godofecht

Copy link
Copy Markdown
Contributor Author

Both bugs I reported above are fixed on this branch, and each now has a regression test that compiles and runs the program and compares against a hand-written loop.

Overflow

n * (2a + (n-1)d) / 2 built an intermediate of exactly twice the answer, so it wrapped once the real sum passed 2^30 even though i32 reaches 2^31-1:

sum(0..54773 step 1)    loop 1500013378    closed -647470270

One of the two factors is always even: when n is even, n/2 is exact; when n is odd, both 2a and (n-1)d are even, so the bracket is. Halving whichever one is even keeps every intermediate inside the range of the result.

big   closed=1500013378 looped=1500013378
small closed=166833     looped=166833
desc  closed=-45        looped=-45
empty closed=0
zero  closed=0

Repeated evaluation, and why the first fix made it worse

The lowering shared the start, end and step AST nodes across every position in the generated expression, so a bound with a side effect ran many times:

sum(a_start(0)..an_end(1000) step a_step(3))
before             start 4   end 3   step 8
after overflow fix start 5   end 4   step 11

Fixing the overflow with an if-expression made it worse, because the parity split duplicates the bracket. Trading one bug for a worse version of another is not a fix, so the lowering now goes through one helper function per module rather than being inlined at each call site:

after              start 1   end 1   step 1

The bounds become the helper's three arguments and are evaluated exactly once, as a for loop over the same range would. Having a body also means the count lives in a local, so the parity split costs one branch instead of a second copy of the arithmetic — the generated C is smaller than before, not larger.

The helper is written as Flow source and parsed rather than assembled node by node: the body is the clearest statement of the identity, and it sits next to the comment explaining why the arithmetic is arranged that way. It is appended to the module only when something used it.

Unchanged

Literal folding still happens at parse time: sum(0..1000 step 3) is the literal 166833. Descending ranges, empty ranges, a runtime zero step returning 0, and the compile-time rejection of a literal zero step all behave as before, and your three original tests still pass.

Validation

  • Unit suite 1512 passed
  • The 17 integration failures are the same set present without this change; I checked by stashing it
  • ruff check src clean

This also unblocks #476, which builds on the RangeExpression node.

@godofecht
godofecht merged commit 9ed5c04 into main Aug 18, 2026
18 checks passed
@godofecht
godofecht deleted the feat/sum-range-closed-form branch August 18, 2026 22:03
godofecht added a commit that referenced this pull request Aug 19, 2026
Two ranges compose with `|` and `&` inside `sum(...)`:

    sum(0..1000 step 3 | 0..1000 step 5)   # 233168
    sum(0..1000 step 3 & 0..1000 step 5)   # 33165

The intersection of two arithmetic progressions is itself an arithmetic
progression, found by CRT: the stride is the lcm of the two strides and the
first common element comes from a modular inverse. Union follows from
inclusion-exclusion, sum(A) + sum(B) - sum(A & B), so both reduce to the
closed form that #536 already applied to a single range.

Literal bounds fold to one constant at parse time, at any depth, by
distributing `&` over `|` into a union of progressions and running
inclusion-exclusion over the subsets. Runtime bounds lower to one helper
call carrying all six bounds, so each bound expression is evaluated exactly
once; the helper works in i64 so the lcm and the modular inverse cannot
overflow on the way to an i32 result.

Negative literal bounds now fold too. `-7` is unary minus over a literal, not
a negative literal, so `sum(10..0 step -3)` previously fell through to the
runtime helper.

Range bounds parse at equality precedence rather than as full expressions, so
a following `|` or `&` reads as range algebra instead of as a bitwise
operator on the step. Outside `sum(...)` both operators keep their bitwise
meaning, and `sum(0..n - 1 step 2)` still subtracts.

Limits, stated in the docs and enforced with a message rather than silently:
eight ranges when folded, one operator between two ranges at runtime, and
ranges are still not values.

Tests compare against the actual element sets rather than hand-computed
constants: the unit tests against Python's `set`, the integration tests
against a brute-force loop in compiled Flow over 500 mixed-sign parameter
sets. `sum` had no spec entry at all, so this adds one.

Closes #476
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add sum(range) builtin that lowers to closed-form arithmetic series

1 participant