Skip to content

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:

  • Pure translates e with translateStmtExpr, so the check-order rules of #374 and #385 apply to it as to any statement. If e can panic, for example on the bound of s[a:] or on a division in a literal, its checks run before the loop through guarded. The panic is the source's panic.
  • The loop runs over the elements of e's value through the shared loop core (lowerLoop), with break and continue.
  • The body may not change x or any local that e reads, and may not hold another loop (countedBodySafe on x and the identifiers of e). x must be a new name, other than _ and the identifiers of e.
  • In the IR, Expr.items evaluates any expression and takes its slice. The interpreter's range case is generalized in the same way.
  • LoopLaw in Proof/Stmt.lean is now pointwise, so a loop's items may depend on the state. items_eval links the items to the value of e.
  • Owned treats range x[a:] as a read of x, like range x, so x stays owned for append.

translate_sound covers the new case, with no new axiom.

Refused ​

  • range over append(…) or an upTo value, which are not pure slice expressions. These fall back to the legacy translator.
  • for i, x := range e and for i := range e over anything but a local slice.
  • A body that changes the element or a local that the range expression reads, return in the body, and nested loops.
  • Certificates: loopLemma refuses 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 package rangeexprs, which has no certificate, shows the output. The certified package ranges stays 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.