You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Vec / transitive-Drop move is a non-destructive copy (collapse-dependent), not real move semantics #607
A move of a transitive-Drop value (e.g. Vec[T] where T needs drop) is lowered as a shallow header copy. Its memory-safety rests on storage-aliasing between source and destination plus drop-deduplication ("collapse"), not on consuming/zeroing the moved-from source. Sound only while exactly one live header of the buffer survives; breaks when a second live header appears.
Evidence
For let h = Holder { values: v } then dropping h: the O0 IR shows the aggregate field shares the source local's storage (no separate field slot, no store-null to the source); the source's emitted drop and the struct's field drop resolve to the same storage and dedup to one with_vec_free. The no-op is an aliasing/dedup accident, not a source-zeroing move. The invariant fails for move-OUT: let m = h.field copies the header into a fresh slot while leaving h.field's slot live → two live headers → double-free. WITH_ENABLE_MIR_VALUE_LOCALS=1 does not rescue this (move-out still double-frees with it on).
Why it matters
Not "exactly as safe as Rust" — safety rests on an aliasing invariant rather than on move consuming its source. Any second live header, or any config that breaks source↔dest aliasing, reintroduces double-frees.
Current mitigation (this release)
The observed move-out double-free (field-move-out / owner_receiver, #605/#606) is closed by consuming the field slot on move-out — zeroing h.field's slot after a consuming read. Sound only with WITH_ENABLE_MIR_VALUE_LOCALS off, because the field slot aliases its source, so zeroing the field zeros the source. The flag is locked off and the dependency is documented at the consume site. A contained, config-gated stopgap, not the foundation.
The real fix
Real move semantics: a move operand of a non-Copy value zeros its source slot, structurally — independent of aliasing or the value-locals flag. Field-move-out falls out as one more move site; the value-locals lock can be removed.
Blast radius
Every move operand of a transitive-Drop value: into-aggregate, binding, call arg, return. The corpus has zero Vec[Drop], so this is floor-blind — an over-zeroing regression (move, then source used again → use-after-null) will not appear in the sweep. Needs a hand-built regression matrix.
Acceptance
Move consumes source on every transitive-Drop move site; matrix all exactly-once / no use-after-null (four cells, move-into-two-owners, borrow + non-consuming-re-read guards, Rc/Arc/Mutex), added as permanent tests; floor/fixpoint green; the value-locals lock and collapse-dependency docs removed.
Notes from the Path (C) reject mitigation (commit rejecting move-out of transitive-Drop struct fields). Two related cases are deliberately not rejected and remain for the real-move fix:
1. Own-Drop fields (type_has_drop_impl(f)). Moving an own-Drop field out of a struct (e.g. a struct W with its own impl Drop, as let m = h.w) double-runs its destructor — the struct's scope-exit drop re-drops the moved-out field. It does not crash a shared RT buffer (no with_vec_free double), so it is milder than the Vec case, but a non-idempotent destructor (refcount decrement, resource release) would still be a correctness bug. The Path (C) reject spares it (!type_has_drop_impl) because rejecting it risked self-build/floor breakage. Real move-operand-zeros-source fixes it uniformly.
2. Iterating a transitive-Drop field (for w in h.vecfield). Compiles — the reject correctly does not fire (iteration is not a field move-out in the let/return/arg sense). But it double-frees the buffer at runtime under the collapse model: the loop materializes copies/consumes the field's buffer while the struct still owns it. Same root as this issue; covered by real move semantics.
Both observed at clean a5-narrow HEAD; independent of the compile-time reject.
Borrow-iteration — for w in &xs / for w in &h.v / h.v.iter()
n/a
unsupported (MIR lowering fails: "AST codegen was removed")
Separate codegen gap; the sound iteration form to build
Swap — swap(&mut h.v, …)
n/a
no safe-With &mut
No action
The pivot (iteration)
Borrow-iteration is not a sound fallback — for w in &vec and .iter() don't compile at all (MIR lowering failure). The only working iteration, the consuming for w in vec, is broken: field iteration double-frees the buffer (crash); whole-local iteration double-drops elements (n→n+1). So iterating a Vec[Drop] is fundamental and broken — it forces #607, not a narrow reject (rejecting all Vec[Drop] iteration would make the type nearly unusable, and the local form is broken anyway).
Crash-class shape
The buffer double-free is exactly a field consume that creates a second live header — move-out, iteration, match-destructure — because field-field headers are notStorageDead-consumed (the collapse), so a second header (the bound copy / iterator / returned value) and the struct's field both free the buffer. Whole-local consume is sound (StorageDead-tracked), confirming this is field-specific, except the element-level double-drop in iteration, which is general (the loop var copies the Drop element). Field reassign is sound (the old value is dropped in place; no second header).
Disposition summary
Move-out: closed (Path C reject).
Match-destructure: the one remaining cleanly rejectable field-consume crash — could fold into the Path C reject as a cheap stopgap.
Sizing: is a sound Vec[Drop] iteration form buyable this release, or #607-scale?
Recon (source reading + throwaway probes, clean a5-narrow @ 5a0594d). Headline: a sound, usable borrow-iteration form already exists and works today for locals.
Mechanism. The iterator protocol exists: VecIter/IntoIter (std), and the for-loop has dedicated arms lower_for_iter_ref (via iter_ref()) and lower_for_iter_place (via iter_place(), VecSlot handles). lower_for_iter_ref binds the loop var as &W using the VEC_GET_REF intrinsic — a borrow, no element copy/move, no drop interaction.
It works today (local):for w in xs.iter_ref(): sum += w.tag over a Vec[W] (W: Drop) → reads fields through &W, each element drops exactly once (count is exact, no double-drop, no crash). This is the sound idiomatic form, available now.
Why my prior probes "failed" to lower:
for w in xs.iter() → the dispatch redirects .iter() to lower_for_vec (by-value), i.e. the double-drop path, not a borrow; and Sema doesn't type the loop var on that form (typed=0 → the w.tag lowering fail). Not the sound form anyway.
for w in &xs → no TY_REF arm in the for-dispatch; it falls through to the generic next() protocol and fails (NK_FOR kind=37). Pure syntax-sugar gap — iter_ref() is the working equivalent.
for w in h.items.iter_ref() (field receiver) → crashes: lowering the field receiver (lower_expr(h.items) + materialize_operand) makes a drop-scheduled copy of the field header (the collapse) → the copy and h.items both free the buffer.
Size: sound borrow-iteration exists for locals at $0. Remaining, all contained (days): (a) &xs sugar = route TY_REF iterables to lower_for_iter_ref + type the loop var; (b) the field-receiver fix = materialize the iter receiver as a borrowed place rather than a drop-scheduled owning copy. No iterator protocol to build — it's there.
Independent of #607?Yes.for w in xs.iter_ref() is a sound iteration form for locals working today, no move-semantics rework required. (Field-receiver iteration needs the contained field-borrow fix.)
Sub-problem 2 — consuming drain (for w in xs) — targeted but #607-adjacent; not required for a sound form
Mechanism.for w in xs → lower_for_vec → VEC_GET copies each element into a reusedelem_local; the loop var is a copy. The copy and the Vec's retained original both drop (and the reused local's earlier copies leak when overwritten) → the irregular n→n+1 double-drop.
To make it a real drain: move each element out of its slot (consume), have the Vec's element-drop skip drained slots (e.g. set len=0 after), and drop the loop var per iteration. The "move element out of a slot" is the element-level analog of move-operand-consumes-source — i.e. #607's core, applied to elements. A targetedVEC_DRAIN-style rework of lower_for_vec (move-out + empty-Vec + per-iter drop) is severable and contained-medium; doing it via the general mechanism is "#607 wearing a for-loop."
Independent of #607? Partially — a targeted Vec-drain is severable, but it is the same consume shape as #607, and crucially it is not needed for a sound iteration form (borrow via iter_ref is the idiomatic sound path). Drain is a separate, lower-urgency operation (explicit vec.drain() in Rust terms).
Summary — cheapest path to a sound Vec[Drop] iteration, and its size
for w in xs.iter_ref() already iterates a Vec[Drop] soundly and usably for locals — $0, ships now. Making it idiomatic and field-capable is contained (days): add the &xs→iter_ref dispatch+typing sugar, and fix the field-receiver header-copy so for w in h.vecfield.iter_ref() borrows in place. Consuming-drain (for w in xs) is a larger, #607-adjacent change and is not required for a sound iteration form — it can wait for #607 (or a separate VEC_DRAIN).
VERDICT (debugger-proven): the mechanical fix double-frees — forced to #607
The mechanical fix (route struct-field drops through the sema-typed path, mir_emit_drop_ptr_for_sema_type, so inline-drop fields — Vec[Drop], [N]Drop, (Drop,..) — are dropped) was implemented and tested at the instruction level. Result: it closes the leak for in-place-built fields but double-frees any field initialized by moving in a value with its own drop (a call result or a named local). Not sound under the current collapse move model.
Both-direction matrix (fix applied, multi-field)
case (struct local, () tail)
result
H{ arr: [W{}, W{}] } — array built in place
2 ✅
H{ pair: (W{}, W{}) } — tuple in place
2 ✅
H2{ a: Vec.new(), b: Vec.new() }; h.a.push; h.b.push — two Vec in place
let v=mkw(); H{ items: v } — Vec field from a named local
panic: invalid free ❌
own-Drop field Wrap{ d: mkD() }
1 ✅ (unchanged)
Vec[Vec[W]]
6 ✅ (unchanged)
POD Vec[i32] field
ok ✅ (unchanged)
Instruction-level proof (lldb on the compiled program)
For let v=mkw(); H{items:v}, breakpoint on with_vec_free: hit count = 2 on the same buffer, second call panics invalid free: pointer is not an allocated payload start. Mechanism: drop(H) now frees items' buffer and the moved-in source v's own drop frees the same buffer — the collapse move-in never canceled v's drop obligation, so both fire.
(An earlier intermediate reading of "1 free / sound" was a measurement artifact: a wrong projection argument made the field-type lookup return 0, so the field was silently not dropped — the leak was merely masked by the source's single free. Correcting the lookup unmasked the double-free. The debugger settled it.)
The mechanical fix and the move-in source-drop are in direct conflict: the in-place cases work precisely because there is no source local; the move-in cases double-free precisely because there is one and its drop isn't canceled. Dropping the field at struct scope-exit is only sound once moving a Drop value into a field consumes (zeros/cancels) the source — which is #607 real consuming move-IN. The leak (under-drop) and this double-free (over-drop) are the two faces of the same missing ownership transfer; you cannot fix one without the other or you flip the bug's direction.
#606/#607 root cause, mapped at the instruction level with the debug allocator + lldb/MIR
The debug allocator (with run --debug-alloc) settled the fork that took four contradictory black-box passes last time — in single runs per case, with block addresses.
Step 1 — the mechanical field_sym fix double-frees (forces #607)
Re-applied the fix (route struct-field drops through the sema-typed mir_emit_drop_ptr_for_sema_type with field_sym) in a throwaway build. The ledger, per case:
So the fix trades under-drops for over-drops → forces #607 (the earlier "with_vec_free hit count 2" was real, not a black-box artifact).
Step 2 — three interacting mechanisms (not one)
(1) Under-drop — drop(struct) never frees an inline-drop field. Codegen.mir_emit_drop_fields_ptr routes fields through the LLVM-typed mir_emit_drop_ptr (registered-drop-fn types only); Vec[Drop]/[N]Drop/(Drop,..) have none → skipped. Fix: the field_sym route through the sema path. Validated: closes the leaks; the floor's A6 red behav_drop_struct_field_move_reinit flips to GREEN.
(2) Move-in over-drop — the consume that cancels the moved-in source's drop is gated wrong. src/MirLower.w:10764, struct-literal lowering:
if self.sema.type_has_drop_impl(f_ty) != 0: // own-Drop only — Vec[W] is false
self.consume_moved_operand(f_op)
MIR of let v=mkw(); H{items:v}: aggregate(fields=[move _2]) moves v in, yet drop(_2) still fires (the ledger: DOUBLE FREE on one block). The exact type_has_drop_impl vs type_needs_drop lever. Proposed fix: change the gate to type_needs_drop. Validated in a throwaway build: closes ALL move-in over-drops (namedlocal_movein, trailing_movein, let v=mkw() → count=0), and the compiler self-builds (no compiler-internal Vec[Drop] construction breaks).
(3) Self-returning-mutator-as-tail over-drop (RESIDUAL — not fixed by (1)+(2)) — inplace_tail still double-frees with no moved-in source. MIR:
call sym18(copy _2.f12, move _7) -> [return: _8 ...] // h.items.push(W) — self-returning
drop(_2); // drop(h) frees the field buffer
_0 = move _8; // run RETURNS _8 = push's return (aliases the buffer)
The self-returning push as the tail expression makes the field's buffer escape as the return value, dropped separately by the caller → double-free once drop(h) also frees it. The floor independently confirms this: the combined (1)+(2) fix introduces exactly one new red — behav_mut_self_field_assign_vec_tail — the self-returning-mutator-tail case.
Blast radius of the proposed (1)+(2) fix (measured, not guessed)
Throwaway build of field_sym + type_needs_drop gate: self-build GREEN; floor 1610/2 — A6 (behav_drop_struct_field_move_reinit) flips RED→GREEN, and exactly one NEW red appears: behav_mut_self_field_assign_vec_tail (mechanism #3). No other regressions. So (1)+(2) are small and validated; #607's remaining work is mechanism #3 — self-returning-mutator ownership when the mutator result is the block tail (must not let the field's buffer escape as a droppable return alias).
Scope
#607 = (1) field_sym route + (2) consume-IN gate type_has_drop_impl→type_needs_drop + (3) self-returning-mutator-tail ownership. (1)+(2) are validated and contained; (3) is the residual substrate work. Whether to take it on this release is a maintainer call. Throwaway reverted; nothing committed. (POD Vec[i32] leak surfaced separately as #608.)
#607 implementation update: (1)+(2) validated; (3) is two language-semantics sub-cases
Implemented and validated with the debug allocator this session. (1) under-drop and (2) move-in over-drop are small, contained, and confirmed exactly-once across the matrix:
(1)Codegen.mir_emit_drop_fields_ptr takes owner_sema_ty and routes each field through the sema-typed mir_emit_drop_ptr_for_sema_type (field name sym via mir_project_field_sema_type); sema-typed caller passes resolved. Closes the leak for Vec[Drop] / [N]Drop / (Drop,…) / nested struct fields (array & tuple verified via drop-count = exactly-once; Vec via the ledger). A6 behav_drop_struct_field_move_reinit flips red→green.
(2)MirLower.w struct-literal consume gate type_has_drop_impl → type_needs_drop (one line; Sema's check_struct_literal move-check already uses type_needs_drop, so they align — no Sema change). Closes every move-in over-drop (named-local / rvalue move-in → exactly-once). Self-build green.
Box[Vec[Drop]] is out of scope — it uses its own mir_emit_box_drop_place path (heap indirection, not an inline field); routing its payload through the sema path opened a separate double-free. Left as a follow-on (its own ownership concern), like POD Vec[i32] buffer never freed at scope exit (debug-allocator finding) #608.
(3) is the residual, and it is two distinct sub-cases — both language-semantics decisions, not localized bug fixes. A field-mutating expression as a function's TAIL yields a value that aliases the field, escapes as the (inferred) return, and is dropped by the caller while drop(struct) also frees it:
(3A) h.items.push() as tail. The self-returning push (it returns the receiver Vec for chaining) on a FIELD receiver yields a Vec aliasing h.items; with the field-drop fix, drop(h) frees it too → double-free (ledger: DOUBLE FREE on one block). cancel_scheduled_value_drop_for_receiver_expr handles a local receiver (xs.push()) by cancelling the local's drop; the field-receiver completion (cancel the base local) over-consumes a multi-field struct — H2{a,b} with h.a.push() as tail LEAKS sibling field b (ledger: drop count 1, leak count=1). Correct fix needs per-field/per-instance consume tracking (cancel only that field's drop), or suppressing the self-return for field receivers.
(3B) self.values = make_values() as tail (behav_mut_self_field_assign_vec_tail). Sema.check_assign (SemaCheck.w:8084) returns the target type (Vec[W]), not Unit — so a no-declared-return fn infers a Vec return from the assignment tail and the MIR double-moves the RHS (_1.f12 = move _3; _0 = move _3): once into the field, once into the return → the return aliases the field → double-free. Clean fix = assignment expressions yield Unit, but that's a broad language-semantics change (any assignment-as-expression).
Both 3A and 3B reduce to: a field-mutating expression's value (push self-return / assignment value) must not escape as a function return aliasing a field that drop(struct) will free. (1)+(2) alone leave exactly these two cases failing the floor (one new red, behav_mut_self_field_assign_vec_tail), so #607 can't land without (3). The fixes are bounded but are language-semantics calls (assignment-expression type; self-returning-push on a field receiver) — surfaced for a decision rather than changed blind. Throwaway reverted; tree clean.
(3B') assign-tail return-inference — an unannotated function whose body tail is an assignment infers Unit, not the assigned field's type (infer_unannotated_function_return_type + a tail_expr_is_assignment helper). This is the targeted version of "assignment yields Unit": it fixes the assign-tail return-aliasing double-free (self.values = mk() no longer makes the fn return a field-aliasing Vec) without the global blast radius — issue99_pointer_exprs stays green, whereas globally Unit-typing check_assign regressed it.
The remaining surface is one foundational capability: per-field move/consume tracking + field-place drop routing. Three places need it, all entangled:
A6 behav_drop_struct_field_move_reinit (self.pair = (W,W)) and B behav_mut_self_field_assign_vec_tail (self.values = mk()): the drop-before-overwrite of the old field value is gated on TY_STRUCT && has_drop_method (lower_assign), so tuple/Vec fields never drop their old value on reassignment → under-drop (A6 count 2 not 4; B leak count 1). Broadening the gate to type_needs_drop is not enough: the emitted drop(field_place) must route through the sema-typed path (the field-place's sema type, mechanism-1-style) or it's a no-op; and it must NOT fire when the field was moved-out (no per-field move tracking exists → over-drop risk).
3A da_vecdrop_inplace_tail (h.items.push() as tail): the self-returning push on a field escapes; per the design call this needs per-field consume (cancel only the escaped field's drop, preserving fluent field chaining h.items.push(a).push(b)). The whole-struct-consume shortcut over-consumes multi-field structs (ledger: sibling-field leak).
All three reduce to: MIR needs per-(local,field) move/consume state, and the scope-exit struct drop + drop-before-overwrite must emit/skip per-field sema-typed drops accordingly. That is a foundational MIR capability (per-field move tracking + partial-struct drop emission), not a localized patch — it onioned (each localized attempt either under-drops, over-drops, or over-consumes, ledger-proven). Per the agreed "STOP if it onions," surfacing the shape for a decision on the substrate investment.
(1)+(2)+(3B') are validated and ready; the substrate (per-field tracking) is the gating piece for A6/B/3A. Throwaway reverted; tree clean.
State verified on clean 4248be3 after reverting the three measurement files (src/CodegenDispatch.w, src/MirLower.w, src/SemaCheck.w). The measurement tree with (1)+(2)+(3B′) cannot ship: test/debug_alloc/da_vecdrop_inplace_tail.w still reports debug-alloc: DOUBLE FREE, so the sequence must land whole or not at all.
Validated pieces recorded:
(1) Sema-typed field-drop routing is necessary: it closes inline-drop field under-drops for Vec[Drop], tuple/array/nested struct field shapes when the field owner sema type is carried.
(2) Struct-literal move-in consume must use transitive type_needs_drop, not only own Drop impls, to avoid source + field double-free.
(3B′) Assignment-tail return aliasing was explored as a targeted return-inference issue, but the remaining field-reassignment/drop-before-overwrite behavior converges on the same missing field substrate.
Final disposition: #607 is gated on a dedicated substrate effort: per-(local,field) move/consume tracking plus sema-typed field-place drops. The substrate must preserve fluent field chaining (h.items.push(a).push(b)), so the cheap “field mutators yield Unit” path is intentionally rejected. Whole-owner consume over-fixes 3A and leaks sibling fields; the debug-allocator multi-field sibling probe proved that.
Clean floor confirmation after reset: file-floor 1610 total / 2 known failures. Failures are test/behavior/behav_drop_struct_field_move_reinit.w (A6 under-drop) and test/compile_errors/err_use_after_move_struct_field.w (A8 not yet rejected). No unexpected floor red was introduced by the measurement closeout.
Next work is a separate substrate session, not Phase 8/#348/#357/#604/#608: build from clean 4248be3 plus the recorded (1)+(2)+(3B′) diffs, use the debug allocator as the oracle from line one, and require the full inline-drop field construction/escape matrix to be exactly-once (leak count=0, no DOUBLE FREE) before commit.
Closed by the commit above: the #607 boundary is lifted. Moving a transitive-Drop field (e.g. Vec[W]) out of a non-Drop struct now works in all consuming positions — let m = h.a, return-tail, explicit return, move self receivers, and destructuring — per spec §2.4 (partial moves from non-Drop types). The niche machinery shipped for A5/Slice-E/A7/A8 already made it sound (static field move + owner partial drop + §2.5 guard); this change removes the rejections and pins the behavior: behav_drop_vec_field_move_out (exact drop counts), da_drop_vec_field_move_out (leak 0, no double free), err_use_after_move_vec_field (use-after-move still rejected), and behav_mut_self_vec_owner_receiver — the original A5 fixture, restored exactly as err_move_out_vec_field_moveself documented it would be. partial move from Drop type (Drop-impl owners, §2.4) remains rejected by design.
Activity
ehartford commentedon Jun 22, 2026
Notes from the Path (C) reject mitigation (commit rejecting move-out of transitive-Drop struct fields). Two related cases are deliberately not rejected and remain for the real-move fix:
1. Own-Drop fields (
type_has_drop_impl(f)). Moving an own-Drop field out of a struct (e.g. a structWwith its ownimpl Drop, aslet m = h.w) double-runs its destructor — the struct's scope-exit drop re-drops the moved-out field. It does not crash a shared RT buffer (nowith_vec_freedouble), so it is milder than the Vec case, but a non-idempotent destructor (refcount decrement, resource release) would still be a correctness bug. The Path (C) reject spares it (!type_has_drop_impl) because rejecting it risked self-build/floor breakage. Real move-operand-zeros-source fixes it uniformly.2. Iterating a transitive-Drop field (
for w in h.vecfield). Compiles — the reject correctly does not fire (iteration is not a field move-out in the let/return/arg sense). But it double-frees the buffer at runtime under the collapse model: the loop materializes copies/consumes the field's buffer while the struct still owns it. Same root as this issue; covered by real move semantics.Both observed at clean
a5-narrowHEAD; independent of the compile-time reject.ehartford commentedon Jun 22, 2026
Collapse-model crash class for
Vec[Drop]— bounded (recon, cleana5-narrow@ 5a0594d)Throwaway probes (
W { slot: *mut i32 }, drop bumps a counter; counts taken after the holding function returns).let m = h.v/return h.v/f(h.v)/move selfbodymatch h: H { v } => …for w in h.vfor w in xsnelems →n+1dropsh.v = newlet m = xsfor w in &xs/for w in &h.v/h.v.iter()swap(&mut h.v, …)&mutThe pivot (iteration)
Borrow-iteration is not a sound fallback —
for w in &vecand.iter()don't compile at all (MIR lowering failure). The only working iteration, the consumingfor w in vec, is broken: field iteration double-frees the buffer (crash); whole-local iteration double-drops elements (n→n+1). So iterating aVec[Drop]is fundamental and broken — it forces #607, not a narrow reject (rejecting allVec[Drop]iteration would make the type nearly unusable, and the local form is broken anyway).Crash-class shape
The buffer double-free is exactly a field consume that creates a second live header — move-out, iteration, match-destructure — because field-field headers are not
StorageDead-consumed (the collapse), so a second header (the bound copy / iterator / returned value) and the struct's field both free the buffer. Whole-local consume is sound (StorageDead-tracked), confirming this is field-specific, except the element-level double-drop in iteration, which is general (the loop var copies theDropelement). Field reassign is sound (the old value is dropped in place; no second header).Disposition summary
&Vec→&W). No conservative reject is acceptable here.The whole-local iteration result refutes the assumption that whole-local iteration is sound — only whole-local consume is
StorageDead-sound.ehartford commentedon Jun 22, 2026
Sizing: is a sound
Vec[Drop]iteration form buyable this release, or #607-scale?Recon (source reading + throwaway probes, clean
a5-narrow@ 5a0594d). Headline: a sound, usable borrow-iteration form already exists and works today for locals.Sub-problem 1 — borrow-iteration — mostly already done; remaining gaps contained (days), not #607-scale
Mechanism. The iterator protocol exists:
VecIter/IntoIter(std), and the for-loop has dedicated armslower_for_iter_ref(viaiter_ref()) andlower_for_iter_place(viaiter_place(),VecSlothandles).lower_for_iter_refbinds the loop var as&Wusing theVEC_GET_REFintrinsic — a borrow, no element copy/move, no drop interaction.It works today (local):
for w in xs.iter_ref(): sum += w.tagover aVec[W](W: Drop) → reads fields through&W, each element drops exactly once (count is exact, no double-drop, no crash). This is the sound idiomatic form, available now.Why my prior probes "failed" to lower:
for w in xs.iter()→ the dispatch redirects.iter()tolower_for_vec(by-value), i.e. the double-drop path, not a borrow; and Sema doesn't type the loop var on that form (typed=0→ thew.taglowering fail). Not the sound form anyway.for w in &xs→ noTY_REFarm in the for-dispatch; it falls through to the genericnext()protocol and fails (NK_FORkind=37). Pure syntax-sugar gap —iter_ref()is the working equivalent.for w in h.items.iter_ref()(field receiver) → crashes: lowering the field receiver (lower_expr(h.items)+materialize_operand) makes a drop-scheduled copy of the field header (the collapse) → the copy andh.itemsboth free the buffer.Size: sound borrow-iteration exists for locals at $0. Remaining, all contained (days): (a)
&xssugar = routeTY_REFiterables tolower_for_iter_ref+ type the loop var; (b) the field-receiver fix = materialize the iter receiver as a borrowed place rather than a drop-scheduled owning copy. No iterator protocol to build — it's there.Independent of #607? Yes.
for w in xs.iter_ref()is a sound iteration form for locals working today, no move-semantics rework required. (Field-receiver iteration needs the contained field-borrow fix.)Sub-problem 2 — consuming drain (
for w in xs) — targeted but #607-adjacent; not required for a sound formMechanism.
for w in xs→lower_for_vec→VEC_GETcopies each element into a reusedelem_local; the loop var is a copy. The copy and the Vec's retained original both drop (and the reused local's earlier copies leak when overwritten) → the irregularn→n+1double-drop.To make it a real drain: move each element out of its slot (consume), have the Vec's element-drop skip drained slots (e.g. set
len=0after), and drop the loop var per iteration. The "move element out of a slot" is the element-level analog of move-operand-consumes-source — i.e. #607's core, applied to elements. A targetedVEC_DRAIN-style rework oflower_for_vec(move-out + empty-Vec + per-iter drop) is severable and contained-medium; doing it via the general mechanism is "#607 wearing a for-loop."Independent of #607? Partially — a targeted Vec-drain is severable, but it is the same consume shape as #607, and crucially it is not needed for a sound iteration form (borrow via
iter_refis the idiomatic sound path). Drain is a separate, lower-urgency operation (explicitvec.drain()in Rust terms).Summary — cheapest path to a sound
Vec[Drop]iteration, and its sizefor w in xs.iter_ref()already iterates aVec[Drop]soundly and usably for locals — $0, ships now. Making it idiomatic and field-capable is contained (days): add the&xs→iter_refdispatch+typing sugar, and fix the field-receiver header-copy sofor w in h.vecfield.iter_ref()borrows in place. Consuming-drain (for w in xs) is a larger, #607-adjacent change and is not required for a sound iteration form — it can wait for #607 (or a separateVEC_DRAIN).ehartford commentedon Jun 23, 2026
VERDICT (debugger-proven): the mechanical fix double-frees — forced to #607
The mechanical fix (route struct-field drops through the sema-typed path,
mir_emit_drop_ptr_for_sema_type, so inline-drop fields —Vec[Drop],[N]Drop,(Drop,..)— are dropped) was implemented and tested at the instruction level. Result: it closes the leak for in-place-built fields but double-frees any field initialized by moving in a value with its own drop (a call result or a named local). Not sound under the current collapse move model.Both-direction matrix (fix applied, multi-field)
()tail)H{ arr: [W{}, W{}] }— array built in placeH{ pair: (W{}, W{}) }— tuple in placeH2{ a: Vec.new(), b: Vec.new() }; h.a.push; h.b.push— two Vec in placeH{ items: mkw() }— Vec field from a call resultOuter{ inner: Inner{ items: mk() } }— nested, call resultlet v=mkw(); H{ items: v }— Vec field from a named localWrap{ d: mkD() }Vec[Vec[W]]Vec[i32]fieldInstruction-level proof (lldb on the compiled program)
For
let v=mkw(); H{items:v}, breakpoint onwith_vec_free: hit count = 2 on the same buffer, second call panicsinvalid free: pointer is not an allocated payload start. Mechanism:drop(H)now freesitems' buffer and the moved-in sourcev's owndropfrees the same buffer — the collapse move-in never canceledv's drop obligation, so both fire.(An earlier intermediate reading of "1 free / sound" was a measurement artifact: a wrong projection argument made the field-type lookup return 0, so the field was silently not dropped — the leak was merely masked by the source's single free. Correcting the lookup unmasked the double-free. The debugger settled it.)
Why it can't be a standalone #606 patch
The mechanical fix and the move-in source-drop are in direct conflict: the in-place cases work precisely because there is no source local; the move-in cases double-free precisely because there is one and its drop isn't canceled. Dropping the field at struct scope-exit is only sound once moving a Drop value into a field consumes (zeros/cancels) the source — which is #607 real consuming move-IN. The leak (under-drop) and this double-free (over-drop) are the two faces of the same missing ownership transfer; you cannot fix one without the other or you flip the bug's direction.
Decision required (release scope) — yours
Vec[Drop]/array/tuple struct fields under-drop at scope exit (sound: no double-free/UAF, just a leak). This is the current behavior.No code shipped; branch clean at
be65f53e. The mechanical-fix patch is reverted. Reproductions above are runnable.ehartford commentedon Jun 23, 2026
#606/#607 root cause, mapped at the instruction level with the debug allocator + lldb/MIR
The debug allocator (
with run --debug-alloc) settled the fork that took four contradictory black-box passes last time — in single runs per case, with block addresses.Step 1 — the mechanical
field_symfix double-frees (forces #607)Re-applied the fix (route struct-field drops through the sema-typed
mir_emit_drop_ptr_for_sema_typewithfield_sym) in a throwaway build. The ledger, per case:taillet_movein(the #606 leak)inplace_trailinginplace_tailnamedlocal_moveintrailing_moveinlet v=mkw(); H{items:v}So the fix trades under-drops for over-drops → forces #607 (the earlier "with_vec_free hit count 2" was real, not a black-box artifact).
Step 2 — three interacting mechanisms (not one)
(1) Under-drop —
drop(struct)never frees an inline-drop field.Codegen.mir_emit_drop_fields_ptrroutes fields through the LLVM-typedmir_emit_drop_ptr(registered-drop-fn types only);Vec[Drop]/[N]Drop/(Drop,..)have none → skipped. Fix: thefield_symroute through the sema path. Validated: closes the leaks; the floor's A6 redbehav_drop_struct_field_move_reinitflips to GREEN.(2) Move-in over-drop — the consume that cancels the moved-in source's drop is gated wrong.
src/MirLower.w:10764, struct-literal lowering:MIR of
let v=mkw(); H{items:v}:aggregate(fields=[move _2])movesvin, yetdrop(_2)still fires (the ledger: DOUBLE FREE on one block). The exacttype_has_drop_implvstype_needs_droplever. Proposed fix: change the gate totype_needs_drop. Validated in a throwaway build: closes ALL move-in over-drops (namedlocal_movein,trailing_movein,let v=mkw()→ count=0), and the compiler self-builds (no compiler-internal Vec[Drop] construction breaks).(3) Self-returning-mutator-as-tail over-drop (RESIDUAL — not fixed by (1)+(2)) —
inplace_tailstill double-frees with no moved-in source. MIR:The self-returning
pushas the tail expression makes the field's buffer escape as the return value, dropped separately by the caller → double-free oncedrop(h)also frees it. The floor independently confirms this: the combined (1)+(2) fix introduces exactly one new red —behav_mut_self_field_assign_vec_tail— the self-returning-mutator-tail case.Blast radius of the proposed (1)+(2) fix (measured, not guessed)
Throwaway build of
field_sym+type_needs_dropgate: self-build GREEN; floor 1610/2 — A6 (behav_drop_struct_field_move_reinit) flips RED→GREEN, and exactly one NEW red appears:behav_mut_self_field_assign_vec_tail(mechanism #3). No other regressions. So (1)+(2) are small and validated; #607's remaining work is mechanism #3 — self-returning-mutator ownership when the mutator result is the block tail (must not let the field's buffer escape as a droppable return alias).Scope
#607 = (1) field_sym route + (2) consume-IN gate
type_has_drop_impl→type_needs_drop+ (3) self-returning-mutator-tail ownership. (1)+(2) are validated and contained; (3) is the residual substrate work. Whether to take it on this release is a maintainer call. Throwaway reverted; nothing committed. (PODVec[i32]leak surfaced separately as #608.)ehartford commentedon Jun 23, 2026
#607 implementation update: (1)+(2) validated; (3) is two language-semantics sub-cases
Implemented and validated with the debug allocator this session. (1) under-drop and (2) move-in over-drop are small, contained, and confirmed exactly-once across the matrix:
Codegen.mir_emit_drop_fields_ptrtakesowner_sema_tyand routes each field through the sema-typedmir_emit_drop_ptr_for_sema_type(field name sym viamir_project_field_sema_type); sema-typed caller passesresolved. Closes the leak forVec[Drop]/[N]Drop/(Drop,…)/ nested struct fields (array & tuple verified via drop-count = exactly-once; Vec via the ledger). A6behav_drop_struct_field_move_reinitflips red→green.MirLower.wstruct-literal consume gatetype_has_drop_impl→type_needs_drop(one line; Sema'scheck_struct_literalmove-check already usestype_needs_drop, so they align — no Sema change). Closes every move-in over-drop (named-local / rvalue move-in → exactly-once). Self-build green.mir_emit_box_drop_placepath (heap indirection, not an inline field); routing its payload through the sema path opened a separate double-free. Left as a follow-on (its own ownership concern), like POD Vec[i32] buffer never freed at scope exit (debug-allocator finding) #608.(3) is the residual, and it is two distinct sub-cases — both language-semantics decisions, not localized bug fixes. A field-mutating expression as a function's TAIL yields a value that aliases the field, escapes as the (inferred) return, and is dropped by the caller while
drop(struct)also frees it:h.items.push()as tail. The self-returningpush(it returns the receiver Vec for chaining) on a FIELD receiver yields a Vec aliasingh.items; with the field-drop fix,drop(h)frees it too → double-free (ledger:DOUBLE FREEon one block).cancel_scheduled_value_drop_for_receiver_exprhandles a local receiver (xs.push()) by cancelling the local's drop; the field-receiver completion (cancel the base local) over-consumes a multi-field struct —H2{a,b}withh.a.push()as tail LEAKS sibling fieldb(ledger: drop count 1,leak count=1). Correct fix needs per-field/per-instance consume tracking (cancel only that field's drop), or suppressing the self-return for field receivers.self.values = make_values()as tail (behav_mut_self_field_assign_vec_tail).Sema.check_assign(SemaCheck.w:8084) returns the target type (Vec[W]), not Unit — so a no-declared-return fn infers aVecreturn from the assignment tail and the MIR double-moves the RHS (_1.f12 = move _3; _0 = move _3): once into the field, once into the return → the return aliases the field → double-free. Clean fix = assignment expressions yield Unit, but that's a broad language-semantics change (any assignment-as-expression).Both 3A and 3B reduce to: a field-mutating expression's value (push self-return / assignment value) must not escape as a function return aliasing a field that
drop(struct)will free. (1)+(2) alone leave exactly these two cases failing the floor (one new red,behav_mut_self_field_assign_vec_tail), so #607 can't land without (3). The fixes are bounded but are language-semantics calls (assignment-expression type; self-returning-push on a field receiver) — surfaced for a decision rather than changed blind. Throwaway reverted; tree clean.ehartford commentedon Jun 23, 2026
#607 implementation: which pieces are solid, and the substrate the rest needs
Continued the implementation with the debug allocator as oracle. Refined map (corrects the earlier one):
Solid and validated (small, localized):
mir_emit_drop_fields_ptrroutes fields through the sema-typed path. Closes the field-drop leak forVec[Drop]/[N]Drop/(Drop,…)/ nested struct fields (ledger / drop-count exactly-once).type_has_drop_impl→type_needs_drop. Closes every move-in double-free.infer_unannotated_function_return_type+ atail_expr_is_assignmenthelper). This is the targeted version of "assignment yields Unit": it fixes the assign-tail return-aliasing double-free (self.values = mk()no longer makes the fn return a field-aliasing Vec) without the global blast radius —issue99_pointer_exprsstays green, whereas globally Unit-typingcheck_assignregressed it.The remaining surface is one foundational capability: per-field move/consume tracking + field-place drop routing. Three places need it, all entangled:
behav_drop_struct_field_move_reinit(self.pair = (W,W)) and Bbehav_mut_self_field_assign_vec_tail(self.values = mk()): the drop-before-overwrite of the old field value is gated onTY_STRUCT && has_drop_method(lower_assign), so tuple/Vec fields never drop their old value on reassignment → under-drop (A6 count 2 not 4; B leak count 1). Broadening the gate totype_needs_dropis not enough: the emitteddrop(field_place)must route through the sema-typed path (the field-place's sema type, mechanism-1-style) or it's a no-op; and it must NOT fire when the field was moved-out (no per-field move tracking exists → over-drop risk).da_vecdrop_inplace_tail(h.items.push()as tail): the self-returning push on a field escapes; per the design call this needs per-field consume (cancel only the escaped field's drop, preserving fluent field chainingh.items.push(a).push(b)). The whole-struct-consume shortcut over-consumes multi-field structs (ledger: sibling-field leak).All three reduce to: MIR needs per-(local,field) move/consume state, and the scope-exit struct drop + drop-before-overwrite must emit/skip per-field sema-typed drops accordingly. That is a foundational MIR capability (per-field move tracking + partial-struct drop emission), not a localized patch — it onioned (each localized attempt either under-drops, over-drops, or over-consumes, ledger-proven). Per the agreed "STOP if it onions," surfacing the shape for a decision on the substrate investment.
(1)+(2)+(3B') are validated and ready; the substrate (per-field tracking) is the gating piece for A6/B/3A. Throwaway reverted; tree clean.
ehartford commentedon Jun 23, 2026
Clean closeout for the #607 measurement session.
State verified on clean 4248be3 after reverting the three measurement files (
src/CodegenDispatch.w,src/MirLower.w,src/SemaCheck.w). The measurement tree with (1)+(2)+(3B′) cannot ship:test/debug_alloc/da_vecdrop_inplace_tail.wstill reportsdebug-alloc: DOUBLE FREE, so the sequence must land whole or not at all.Validated pieces recorded:
Vec[Drop], tuple/array/nested struct field shapes when the field owner sema type is carried.type_needs_drop, not only own Drop impls, to avoid source + field double-free.Final disposition: #607 is gated on a dedicated substrate effort: per-(local,field) move/consume tracking plus sema-typed field-place drops. The substrate must preserve fluent field chaining (
h.items.push(a).push(b)), so the cheap “field mutators yield Unit” path is intentionally rejected. Whole-owner consume over-fixes 3A and leaks sibling fields; the debug-allocator multi-field sibling probe proved that.Clean floor confirmation after reset: file-floor 1610 total / 2 known failures. Failures are
test/behavior/behav_drop_struct_field_move_reinit.w(A6 under-drop) andtest/compile_errors/err_use_after_move_struct_field.w(A8 not yet rejected). No unexpected floor red was introduced by the measurement closeout.Next work is a separate substrate session, not Phase 8/#348/#357/#604/#608: build from clean 4248be3 plus the recorded (1)+(2)+(3B′) diffs, use the debug allocator as the oracle from line one, and require the full inline-drop field construction/escape matrix to be exactly-once (leak count=0, no DOUBLE FREE) before commit.
Loops: sound conditional Drop moves (back-edge + break/continue dataf…
ehartford commentedon Jul 2, 2026
Closed by the commit above: the #607 boundary is lifted. Moving a transitive-Drop field (e.g.
Vec[W]) out of a non-Drop struct now works in all consuming positions —let m = h.a, return-tail, explicitreturn,move selfreceivers, and destructuring — per spec §2.4 (partial moves from non-Drop types). The niche machinery shipped for A5/Slice-E/A7/A8 already made it sound (static field move + owner partial drop + §2.5 guard); this change removes the rejections and pins the behavior:behav_drop_vec_field_move_out(exact drop counts),da_drop_vec_field_move_out(leak 0, no double free),err_use_after_move_vec_field(use-after-move still rejected), andbehav_mut_self_vec_owner_receiver— the original A5 fixture, restored exactly aserr_move_out_vec_field_moveselfdocumented it would be.partial move from Drop type(Drop-impl owners, §2.4) remains rejected by design.Lift #607: transitive-Drop fields move out of non-Drop structs
Codegen: sentinel-guard member drops; null-guard Box/Rc drop paths (#697
test: compile-error lane dispositions per approved rulings