Skip to content

Fix #1317: a for binding borrows the iterated place for the whole loop - #1333

Merged
ehartford merged 3 commits into
mainfrom
fix-1317-loop-binding-borrow
Sep 22, 2026
Merged

ehartford merged 3 commits into
mainfrom
fix-1317-loop-binding-borrow

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Stacked on #1327 — GitHub stack (base fix-1297-field-view-origin; retarget to main once #1327 merges).

Fixes #1317.

What changed

  • for e in xs registers a SHARED borrow of the iterated place with e as its ref (§21.1 rule 1, §3.4, D22/D27/D44), through the same check_borrow_create_direct / check_mutation_against_views path as let e = xs.get(0). xs.push/clear/remove(..), xs = .., m.insert(..) in the body are rejected: "cannot mutate xs while e is a live view into it", with a note that the loop reads the place again on its next iteration.
  • The borrow is keyed on the field path (self.items), not the root, so for e in self.items: self.count += 1 and for e in xs: other.push(e.clone()) stay accepted. A mut fn call on self inside for e in self.items is still a conflict, matching the existing let e = self.items.get(0); self.bump(); use e rule.
  • The loop view does not expire at a lexical last use (the next iteration reads it), except when the mutation is directly followed by return or an unlabeled break of that same loop. In that case no iteration follows, so find-then-grow and find-then-clear check (Rust's NLL accepts the same thing). continue, a labeled break, and an inner loop's break still conflict.
  • Index iteration is not affected: for i in 0..xs.len(): xs.push(..), a bounded while i < xs.len(), and reading xs[j] in the iteration that pushes all bind an i32, not a view. A Copy-element for x in xs binds no view either. Its MIR reads the length once and fetches each element by index from the current buffer, so there is nothing to dangle.

Tests (stage1 from with build :dev)

New, all pass:

  • rejected: err_for_binding_iterable_{push,clear,remove}, err_for_binding_self_field_push, err_for_pattern_binding_map_insert, err_for_binding_mutate_then_continue, err_for_binding_inner_loop_break
  • accepted: behav_for_binding_disjoint_mutation, behav_for_binding_mutate_then_exit (also leak count=0 under run --debug-alloc), behav_for_index_loop_mutates_collection

Existing tests still pass: err_view_of_local_*, every err_*ephemeral*, behav_for_*, behav_view_*, behav_typed_let_borrows_place. Every test/debug_alloc/*.w checks, and the map and consuming-iteration cells report leak count=0 under run --debug-alloc.

Sweep

  • with-stage1 check src/main.w: ok.
  • A With scanner over every .w with a for … in under src, lib, rt, build, tools, examples and test (458 files) looked for a body that mutates or assigns its own iterable. It found only the new fixtures.
  • I checked with stage1 the 68 tools/, examples/ and lib/std candidates that contain for loops. None gets a Mutating the iterated collection inside for x in xs is accepted (no live-view diagnostic for the loop binding) #1317 diagnostic. 21 fail with the same errors under the pinned seed: implicit-main tools under check, stale tools, and impl duplicates in stdlib modules that are checked alone.
  • Corpora: lib/std/{re,zl,c_algorithms,tommyds}/bundle.w all check (rc=0) under stage1. None of the four bundles and nothing under test/corpora/ has a for statement, so the rule cannot reach migrated C. The test/corpora/c_algorithms/programs/* modules import std.calg_testing.*, which only exists once the build assembles it, so they cannot be checked on their own.

The battery (:fixpoint/:test) has not run on this branch yet. The PR stays a draft until it passes.

@ehartford
ehartford changed the base branch from fix-1297-field-view-origin to main September 22, 2026 19:45
@ehartford
ehartford force-pushed the fix-1317-loop-binding-borrow branch from 7728099 to 1e35df8 Compare September 22, 2026 20:45
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, rebased on ae609cd): build ok, :fixpoint ok, :move-audit ok, :test red.

Reds: behav_distinct_compat (main, fixed by #1339); err_no_std_alloc_async_leak, err_no_std_await_leak, err_unit_elision_unconstrained_generic (main, fixed by #1340); and err_for_binding_iterable_clear — this PR's own fixture.

The loop-lifetime borrow does not hold. for e in xs: print(e.key); xs.clear() checks ok, and so does xs.push(..) with no later use of e; err_for_binding_iterable_push passes only because it reads e.key after the push, which the old lexical last-use rule already rejects. lldb: register_for_binding_borrow runs, but check_mutation_against_views never reaches for_view_binding_depth — one of the loop's early continues (place, kind, ref_sym, disjoint paths) drops the borrow. Stays draft; fix in progress.

@ehartford

Copy link
Copy Markdown
Contributor Author

Fixed at a49c865 — and the root cause is on main, not in this PR's rule: check_fn_body_with_sig_at cleared the whole borrow table at body entry. When the first call of a generic function checks its body mid-caller (check_call → check_generic_call → check_fn_body_concrete → check_fn_body_with_sig_at), the caller's live borrows were deleted. Since #1325 made print generic, the first print(x) of each type erased every live view in the calling function — so let e = xs.get(0); print(e.key); xs.push(..); print(e.key) checks ok on main (v0.15.2.1 before #1325 rejects it). Evidence: lldb function breakpoints — the row added by register_for_binding_borrow is removed by remove_borrow_at under that chain; check_mutation_against_views then sees an empty table.

Fix: save the caller's borrow table (8 columns) and loop-view bindings at body entry, check the body on empty tables, restore after pop_scope. New fixtures: err_for_binding_push_body_tail, err_for_binding_mutate_then_statement, err_view_live_across_generic_instantiation. Check sweep (1132 behavior, 860 compile_errors, examples, 43 UAT fixtures) fixed-vs-unfixed: only those fixtures change. Re-battery queued.

Eric Hartford added 3 commits September 22, 2026 18:32
… `for e in xs: xs.push(..)` is rejected as the live-view mutation it is (#1317)

Fixes #1317.

`for e in xs` is `xs.iter()` (§13, D44) and `e` is a view into `xs`
(§3.4), but check_for registered no borrow for the binding, so
`xs.push(..)`, `xs.clear()`, `xs.remove(0)` and `m.insert(..)` inside the
body compiled and the next iteration read the reallocated or shifted
buffer through `e` — the same use-after-free §21.1 rule 1 already
rejects for `let e = xs.get(0); xs.push(..); use e`.

register_for_binding_borrow records a SHARED borrow keyed on the field
path of the iterated place (for_iterated_place: the place itself, or the
receiver of a spelled `@[iter_of_self]` call such as `xs.iter()` /
`m.keys()`), with the binding as its ref, through the same
check_borrow_create_direct / check_mutation_against_views mechanism the
let-bound views use. Keying on the path, not the root, keeps
`for e in self.items: self.count += 1` accepted (disjoint paths) while
`self.items.push(..)` conflicts. A pattern binding (`for (k, v) in m`)
registers the same borrow for each of its ephemeral bindings.

The borrow never expires at a lexical last use of the binding: the loop
reads the place again on its next iteration, so check_mutation_against_views
keeps a borrow whose ref is in for_view_binding_syms (a stack check_for
maintains) and adds a note saying so. It expires with the loop's scope.

record_pattern_view_bindings now walks pattern_binding_syms, the one
pattern-binding collector both paths use, and for_iterable_yields_views'
method tail is factored into iter_of_self_call_receiver.

Rejected (new fixtures): push, clear, remove on the iterated Vec, push on
`self.items`, insert on the iterated map. Accepted
(behav_for_binding_disjoint_mutation): `self.count += e.n`, pushing the
element's clone onto another Vec, `for e in xs.iter()`, mutating `xs`
after the loop. `with check src/main.w`, tools/*.w and examples/ compile
under the rule; a scan of src/, lib/, rt/, build/, tools/, examples/ and
test/ for a `for` whose body mutates its own iterable found no site. A
Copy-element loop (`for i in idxs: idxs.push(..)`) binds no view and is
not covered here.
…inding's view; index loops stay accepted (#1317)

The loop-binding borrow never expires at a lexical last use, because the
next iteration reads the iterated place again. When the mutation's next
statement is `return`, or an unlabeled `break` of the very `for` that
binds the view (loop_depth equals the body's depth recorded in
for_view_binding_depths), no iteration follows: find-then-grow and
find-then-clear are sound and now check, as Rust's NLL accepts them.
The borrow is kept, not removed, since other paths through the body may
still loop. `continue`, a labeled break, and a break of an inner loop
still conflict (new fixtures).

behav_for_index_loop_mutates_collection pins what migrated C does: a
range over `xs.len()` pushing onto `xs`, a bounded `while` over an index,
and reading `xs[j]` in the iteration that pushes (as the argument, through
a Copy-annotated binding, and through a view dead before the push). The
binding is an i32, not a view, so the rule does not reach them. An
unannotated `let v = zs[j]` used as the pushed argument is rejected by the
existing D27 let-view rule (seed and stage1 alike), not by this change.
…nstead of wiping them — `print(e.key)` erased the `for` binding's borrow of `xs` (#1317)

Root cause: check_fn_body_with_sig_at (src/SemaCheck.w) opened every body
with `while self.borrow_kinds.len() > 0: self.remove_borrow_at(...)`,
treating the borrow table as free at body entry. It is not: the first call
of a generic function reaches it mid-body, through check_call ->
check_generic_call -> check_fn_body_concrete -> check_fn_body_with_sig_at,
while the caller's rows are live. check_fn_body_concrete saves the
caller's scope-stack family but not the borrow columns, so the caller's
borrows were discarded. Since #1325 made print generic
(print[T: Display](v: &T)), the first `print(x)` of each T erased every
live view of the calling body.

Evidence (lldb, with-stage2 check err_for_binding_iterable_clear.w,
function breakpoints): register_for_binding_borrow -> check_borrow_create_direct
appended the row; the next remove_borrow_at hit came from
check_fn_body_with_sig_at <- check_fn_body_concrete <- check_generic_call
<- check_call (the body's `print(e.key)`); check_mutation_against_views
then ran on an empty table, so for_view_binding_depth was never reached.
The same wipe accepted `let e = xs.get(0); print(e.key); xs.push(..);
print(e.key)`, which the installed v0.15.2.1 (before print was generic)
rejects.

Fix: set the caller's borrow columns and loop view bindings aside at body
entry and restore them after the body's pop_scope; the body's own rows
die with it. borrow_path_data is append-only, so saved path indices stay
valid.

Fixtures: err_for_binding_push_body_tail (push as the body tail, no later
use of `e`), err_for_binding_mutate_then_statement (clear, then a
non-exiting statement), err_view_live_across_generic_instantiation (a
let view across the first call of a local generic fn). All three, and
err_for_binding_iterable_clear, checked ok before this change.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, rebased on main 8c859a7, c0ff515 — force-pushed so the PR is the tested tree): build ok, :fixpoint ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok.

@ehartford
ehartford force-pushed the fix-1317-loop-binding-borrow branch from a49c865 to c0ff515 Compare September 22, 2026 23:01
@ehartford
ehartford marked this pull request as ready for review September 22, 2026 23:01
@ehartford
ehartford merged commit dd5caac into main Sep 22, 2026
@ehartford
ehartford deleted the fix-1317-loop-binding-borrow branch September 24, 2026 16:54
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.

Mutating the iterated collection inside for x in xs is accepted (no live-view diagnostic for the loop binding)

1 participant