Repository navigation
Lower sum(range) to closed-form arithmetic - #536
Conversation
|
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
1500013378 fits in i32 with room to spare. The doubled intermediate, 3000026756, does not. The literal path is unaffected, since A fix that keeps everything in i32 is to halve before multiplying, picking the side that is known even. When 2. Range bounds are evaluated more than onceThe lowering shares the The value is right. The call counts are not. Part of this is also plain duplicated work: Lowering What is rightVerified 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. Happy to implement either fix if you want it. Flagging rather than pushing to your branch. |
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]>
|
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
One of the two factors is always even: when Repeated evaluation, and why the first fix made it worseThe lowering shared the 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: The bounds become the helper's three arguments and are evaluated exactly once, as a 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. UnchangedLiteral folding still happens at parse time: Validation
This also unblocks #476, which builds on the |
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
Closes #475.
Adds an exclusive-end
RangeExpressionAST boundary for range-aware builtins and teachessum(...)to recognizestart..end/start..end step stepwithout 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 literal166833. 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
RangeExpressionnode is intentionally separate fromForStatement; #476 can generalize expression-range parsing/algebra on the same AST without changing loop representation.