Skip to content

Go condition-only loops that count ​

Status: accepted · Date: 2026-11-30

Go has no while; for cond { … } takes its place. A general condition loop has no termination measure, so the proved path refused all of them. This record accepts the common counting shape and proves it through the existing counted loop.

The decision ​

  • The interpreter (tolean/Go/Spec/Eval.lean) and the translator (tolean/Go/Translate/Pure.lean) accept for i < b { ss; i++ } when the body ends with i++, ss does not write i, the body has no continue at any depth, and b does not read i.
  • Eval.whileForm rewrites such a loop as for i' := i; i' < b; i'++ { i = i'; ss; i++ }, where i' is Eval.whileIndex i. The counter i is an outer local, so it keeps its last value after the loop, as in Go: the bound after a normal end, the value at the break after a break. The trailing i++ matters only on the last iteration, where it sets i to the bound.
  • The interpreter runs this loop over Go.upTo i b, with b evaluated once. That is exact, because the body cannot change i before its trailing i++ nor what b reads, so the condition at each test is i_0 + k < b.
  • execStmt_while (tolean/Go/Proof/Stmt.lean) proves that the interpreter gives the same result for the loop and for its rewrite, and the statement proof reuses the counted-loop proof on the rewrite through sim_congr.

Refused ​

  • continue in the body: it would skip i++, so the loop is not the counted one.
  • Other conditions (<=, >, !=, compound tests), other updates, or a body that does not end with i++.
  • A body that writes i elsewhere or changes what b reads, and a bound that reads i.
  • A return in the body, and nested loops, as for counted loops.
  • Counters of other integer types, as for counted loops.
  • for { … } and every other condition loop: no measure.

The fresh name i' exists because the loop law forbids shadowing; a local named i' cannot exist in Go source, so it never collides.

This page is docs/decisions/2026-11-30-go-condition-loops.md at commit 5f1d031.