Appearance
Go: for _, x := range e over a slice expression
Date: 2026-12-05
Context
The proved path accepted range only over a local slice. Ranging over a literal, s[a:], s[:] or a call sent the whole function to the legacy translator, which has no proof.
Decision
The proved path accepts for _, x := range e when e is any pure expression of a slice type. Go evaluates e once, before the loop, and so does the output:
PuretranslatesewithtranslateStmtExpr, so the check-order rules of #374 and #385 apply to it as to any statement. Ifecan panic, for example on the bound ofs[a:]or on a division in a literal, its checks run before the loop throughguarded. The panic is the source's panic.- The loop runs over the elements of
e's value through the shared loop core (lowerLoop), withbreakandcontinue. - The body may not change
xor any local thatereads, and may not hold another loop (countedBodySafeonxand the identifiers ofe).xmust be a new name, other than_and the identifiers ofe. - In the IR,
Expr.itemsevaluates any expression and takes its slice. The interpreter's range case is generalized in the same way. LoopLawinProof/Stmt.leanis now pointwise, so a loop's items may depend on the state.items_evallinks the items to the value ofe.Ownedtreatsrange x[a:]as a read ofx, likerange x, soxstays owned forappend.
translate_sound covers the new case, with no new axiom.
Refused
rangeoverappend(…)or anupTovalue, which are not pure slice expressions. These fall back to the legacy translator.for i, x := range eandfor i := range eover anything but a local slice.- A body that changes the element or a local that the range expression reads,
returnin the body, and nested loops. - Certificates:
loopLemmarefuses a range over anything but a local, an index range or a literal list. The message is "a range loop over a slice expression other than a local has no certificate yet". The corpus packagerangeexprs, which has no certificate, shows the output. The certified packagerangesstays fully certified.
Testing
tests/go/Range.lean has checks, panics and refusals. The differential generator now sometimes writes range s[k:] and range s[:].
This page is docs/decisions/2026-12-05-go-range-expr.md at commit 5f1d031.
