Repository navigation
Description
Summary
Drop values produced mid-expression are never dropped, and — worse — moving a named Drop local does not unschedule its scope-exit drop, so plain moves double-drop. MirLower schedules drops for named let bindings only; result temporaries created by new_temp are never entered into the drop-scope stack, and the existing cancel_scheduled_value_drop_for_local mechanism is invoked only at a handful of ad-hoc sites. This is a leak-grade and double-free-grade correctness bug in the core ownership model (§2.4): both halves must be fixed together because the fix for temporaries (drop at statement end) is only sound once move handoff reliably cancels the source's pending drop.
Spec
§2.4 Destructors and defer (normative):
- "Drop on expression temporaries: Temporaries created within an expression are dropped at the end of the enclosing statement. This frees intermediate resources automatically." (
let c = process(combine(a, b))— combine's result is dropped after process reads it; onlycsurvives.) — req IDs 2.4.1.9, 2.4.1.10. - "Drop order within a scope is reverse declaration order."
- "Partial moves from Drop types are forbidden in normal code."
§3.8 Auto-Referencing (call modes, spec v7.1): a plain T parameter consumes — the argument is moved into the callee; a &T parameter borrows. Consequently: a by-value non-Copy argument is owned (and dropped) by the callee; an auto-ref'd temporary must outlive the call and is dropped by the caller at statement end.
§14.7 Task[T]: a Task in statement position is intentional fire-and-forget detachment (gated by must-observe + detach-safety; currently E0801). Statement-temp dropping must not cancel detached tasks — Task disposition is #350's contract, not the generic temp rule.
Current state
All claims re-verified against 1c5258007a362fcd8c7a145b3e9c3be4c84ac47d (probes run with out/bin/with-stage2).
Drop infrastructure in src/MirLower.w:
- Drop-scope stack
drop_local_ids/drop_kinds/drop_scope_starts(MirBuilder fields, lines 43-45),push_scope(line 179),schedule_drop(line 186). emit_drop_entry(line 272) dispatches onDropKind(Mir.w:313-320:DK_VALUE,DK_STORAGE,DK_TASK_DETACHED,DK_TASK_EPHEMERAL,DK_WITH_GUARD,DK_WITH_GUARD_MUT,DK_ASYNC_SCOPE,DK_THREAD_SCOPE).- Scope exit emits entries in reverse push order:
pop_scope_with_goto(line 345) /pop_scope_inline(line 379). lower_let_binding(line 3333) schedulesDK_VALUEfor non-Copy named lets (line ~3356); forlet _ = exprit skips scheduling and emits an immediateemit_drop_entry+ StorageDead (lines ~3366-3371).- A cancellation mechanism exists:
cancel_scheduled_value_drop_for_local(line 245, downgrades the entry toDK_STORAGE;drop_kind_owns_valueline 239) — but it is invoked only ad hoc: returns (lower_returnline 4812), value-position block tails (line 3538 inlower_block_mode), enum-accessor receivers (line 6450), record-update bases (line ~7370),std.drop(inlower_std_drop_call, line 5638), async/thread scope locals (lines 8523/8554). It is not invoked for: plainlet b = amoves, by-value call arguments, orlet _ = named_local. - Result temporaries:
lower_call(line 5547) and its variants (lower_call_with_operand_args,lower_call_redirected,lower_call_with_arg_nodes,lower_call_with_receiver_operand) createnew_temp(ret_type)+TK_CALLand return anOK_MOVEoperand for non-Copy results — the temp is never registered anywhere.lower_expr_discard(line 3426) throws the operand away (let _ = result) without a Drop. The materialize-as-temp fallback inlower_expr_place(line ~3326) andlower_auto_ref_call_arg(line 5713, refs a place that may be such a temp) likewise never drop. - Codegen treats
OK_MOVEidentically toOK_COPY(load/copy; e.g.CodegenDispatch.w:3514), andStmtKind.Dropunconditionally runs drop glue (CodegenDispatch.w:3477). There are no drop flags; correctness must be established statically in MirLower.
Observed behavior (trace-printing Drop impl; each line is the full trace):
| Program shape | Observed | Verdict |
|---|---|---|
let a = make("A"); let b = a |
[drop A][drop A] at scope exit |
double-drop (move does not unschedule a) |
let t = make("T"); let _ = t |
[drop T][drop T] |
double-drop (immediate _ drop + t's scheduled drop) |
bare statement make("S") |
no drop ever | leak |
let n = make("M").id.len() |
no drop ever | leak (receiver temp) |
peek(make("P")) with peek(r: &R) |
no drop ever | leak (auto-ref'd temp) |
if make("C").id.len() > 0: |
no drop ever | leak (condition temp) |
consume(make("V")) with consume(r: R) |
[in-consume][drop V] |
correct — callee drops by-value temp arg |
let a = make("L"); consume(a) |
[in-consume][drop L] … [drop L] |
double-drop (callee + caller scope exit) |
if c: take(move a) (explicit move) |
true path: [drop A]…[drop A]; false path: [drop A] |
double-drop on moved path; no drop-flag machinery |
let s = make("F").id |
compiles; R temp never dropped | sema gap: partial move from a Drop temporary is not rejected (§2.4 forbids it; err_partial_move_drop_field.w only covers named bases) |
return make(..) / tail-position move |
single drop in caller | correct (cancel sites at 3538/4812) |
var h = make("1"); h = make("2") |
[drop 1] at reassignment |
correct (lower_assign line ~3245) |
| three locals at scope exit | [drop c][drop b][drop a] |
correct reverse order |
Sema context: statement-position Task values are currently rejected with E0801: unused Task value (SemaCheck.w:4384-4387), so no Task reaches lower_expr_discard today; #350 will change that to fire-and-forget — the temp machinery must leave Task-typed (and async/thread-scope) results alone.
Implementation plan
Phase 1 — statement-temp tracking and unconditional move handoff (fixes every row above except the conditional-move row):
- Data structure (
src/MirLower.w, MirBuilder): addstmt_temp_locals: Vec[i32]plusstmt_temp_starts: Vec[i32](a stack of statement frames — frames nest because statements contain blocks/if-expressions). Vec-based and append-only within a frame → deterministic, fixpoint-safe (no map iteration).push_stmt_temp_frame(): pushstmt_temp_locals.len()ontostmt_temp_starts.flush_stmt_temp_frame(): emitStmtKind.Drop+StorageDeadfor surviving entries in reverse registration order (matches scope-exit convention), then pop to the frame start. Entries cancelled by handoff are marked (set local id negative or parallel kind vec) and skipped.register_stmt_temp(local_id, ty): no-op whensema.is_copy(ty) != 0, when the frame stack is empty, or whentyis a Task / async-scope / thread-scope type (disposition belongs to Implement position-based Task disposition semantics #350 and the DK_TASK_* kinds; dropping must not cancel detached tasks).
- Frame placement: in
lower_block_mode(line 3475) wrap each statement in the loop with push/flush; also wrap the tail expression whenwant_result == 0. For value-position tails, temps feeding the result must NOT be flushed before the result moves out — register them into the enclosing frame instead (flush after the block's value has been assigned). - Registration sites: call
register_stmt_tempwhere owned non-Copy result temps are created: the fivelower_call*result temps (lines 5547/5551ff/5602ff/5622ff/5564ff), thelower_expr_placematerialize fallback (~3326),materialize_operand(1545) when it allocates, and struct/enum literal temps if they materialize through the same fallback. The auto-ref case (lower_auto_ref_call_arg, 5713) needs no extra work once the fallback registers the referent temp — the ref temp itself is Copy. - Move handoff (the let-
_and double-drop fix): introduceconsume_moved_operand(operand_id)— if the operand isOK_MOVEover an unprojected place (mir_place_plain_local), cancel the source's pending drop in both tables:cancel_scheduled_value_drop_for_local(scope stack) and the stmt-temp frame. Call it at the ownership-transfer choke points:assign_operand_to_place(line 2414) — coverslet b = a,varreassignment RHS,let _ = t(the immediate drop at 3366 then becomes the only drop), struct-literal field moves, return-value assignment into_0.- by-value argument positions: in
lower_call_arg(line ~5679 tail) and the receiver/arg pushes oflower_method_call/lower_call_with_receiver_operand, after the operand is built and only when the parameter mode is by-value (not the auto-ref/auto-deref early returns). Callee drops the value (verified above), so the caller's scheduled drop must die — this also fixesconsume(a)with and without explicitmove.
Restriction: only cancel when the source local's scheduled entry belongs to the current innermost scope nesting being lowered on an unconditional path (see Phase 2); for Phase 1, track thedrop_local_idslength at each branch entry and refuse to cancel entries scheduled outside the current conditional context — emit the conservative behavior below instead.
- Condition position: lower
if/whileconditions into a bool temp, flush the condition's temp frame, then emit theSwitchIntterminator — temps die "at the end of the enclosing statement" before either branch runs, and on every loop iteration. - Partial move from Drop temporaries (
make("F").id): in SemaCheck's partial-move check (the one behindtest/compile_errors/err_partial_move_drop_field.w), extend the base-place analysis to rvalue/temporary bases whose type implements Drop; reuse the existing message:partial move from Drop type. Until then this construct silently leaks the remaining fields. - No silent fallback: if a registered temp's type has no resolvable drop glue at codegen, that is already handled by
mir_emit_drop_ptr; do not special-case. If lowering cannot decide a context (e.g. operand neither moved nor registered), prefer emitting the Drop — a double-drop is loud in tests; a leak is silent.
Phase 2 — conditional moves (drop flags):
8. When consume_moved_operand fires for a local whose drop entry was scheduled in an outer scope than the current conditional context (the if c: take(move a) row), introduce a deterministic drop-flag local (i1, named by source local id, not pointer order): StorageLive + init 1 at schedule point, set 0 at the move, and replace the scope-exit Drop with a flag-guarded diamond (SwitchInt → Drop → join). This mirrors Rust's drop elaboration but stays inside MirLower's existing block machinery. Until Phase 2 lands, Phase 1 must keep current behavior for that shape (documented known-broken) or, preferably, emit a sema error for conditionally-moved Drop locals — coordinate with #444 (Rule 7: implicit drop is a use), which touches the same analysis.
Bootstrap note: this is compiler-only (MirLower/SemaCheck); no rt/Link/seed changes. The compiler itself is full of non-Copy temps, so expect stage2 behavior shifts — run the full chain and with build :fixpoint after each step; the reverse-order flush and deterministic flag naming are what keep stage2 == stage3.
Test plan
Trace-based matrix asserting exact drop sequences, modeled on test/spec/spec_ss02_4_by_value_drop.w (global TRACE string appended in Drop.drop).
test/spec/spec_ss02_4_expression_temporaries.w (//! expect-stdout per-case):
- discarded call statement
make("S")→ exactly[drop S]at statement end, before the next statement's trace marker; - method chain
make("M").id.len()→[drop M]at statement end; - nested
process(combine(a,b))(spec's own example) → combine-temp dropped after process returns, before statement end; onlycsurvives to scope exit; - auto-ref'd temp
peek(make("P"))→[in-peek][drop P]then|stmt-endmarker; - by-value temp
consume(make("V"))→[in-consume][drop V]exactly once; - condition
if make("C").id.len() > 0:→[drop C]before the then-branch marker; same in awhilecondition across two iterations; - tail return
pass_through()→ exactly one drop, in the caller; - multiple temps in one statement → dropped in deterministic reverse creation order.
test/spec/spec_ss02_4_move_handoff.w:
let a = make("A"); let b = a→ exactly one[drop A];let t = make("T"); let _ = t→ exactly one[drop T], at thelet _statement, not scope exit;let a = make("L"); consume(a)andconsume(move a)→ exactly one drop, inside the callee;- record update / struct literal field move of a non-Drop wrapper → no double drop;
- Phase 2:
if c: take(move a)→ exactly one drop on both arms (or, if the sema-error route is taken, atest/compile_errors/err_conditional_move_drop.wwith//! expect-check-fail).
test/compile_errors/err_partial_move_from_drop_temp.w (//! expect-check-fail: partial move from Drop type): let s = make("F").id.
Task non-interaction (after #350; until then keep as compile-error test): statement-position Task expression must not receive a generic temp Drop/cancel — assert via a spawned task that completes after the statement.
Regression: spec_ss02_4_*.w, behav_drop*.w, errdefer_*, err_eff_escape_no_move.w (until #372 changes it), and the full suite — the compiler bootstrap itself is the biggest consumer of temp-drop semantics.
Acceptance criteria
- All eight leak rows in the table above produce exactly one drop at the spec'd point (statement end), verified by exact-trace tests.
- All three double-drop rows produce exactly one drop;
let _ = tdrops at thelet _statement. - Drop order within a statement and at scope exit is deterministic (reverse creation/declaration order) — no map-iteration ordering anywhere in the new code.
- Partial move from a Drop temporary is a compile error naming the type.
- Statement-position Task handling is untouched (E0801 still fires pre-Implement position-based Task disposition semantics #350; no cancel/drop emitted for task-typed discards).
- Conditional-move shape is either correct via drop flags (Phase 2) or loudly rejected — never silently double-dropped.
-
with build && with build :fixpoint && with build :testpass.
Dependencies
- Tests: drop semantics coverage (§2) #496 (drop-semantics test coverage) — shares the trace harness; Tests: drop semantics coverage (§2) #496's tests must be green before/with this change.
- Borrow checker Rule 7: implicit drop is a use (§21.1) #444 (borrow checker Rule 7: implicit drop is a use) — same conditional-move analysis; coordinate Phase 2.
- Implement position-based Task disposition semantics #350 (position-based Task disposition) — defines what statement-position Task discards lower to; this issue must only avoid touching them.
- Remove the move x/copy x acknowledgment requirement for consuming arguments #372 (remove move/copy ack) — its test updates touch the same call-mode fixtures.
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 2.4.1.10, 2.4.1.9.
Activity
Requirements triage campaign: checkbox, verdict, and issue-link every…
Enforce §3.8 by-value consume for Drop-impl arguments
ehartford commentedon Jun 12, 2026
Implemented in 1c9926d. Expression temporaries that own non-Copy values are now tracked in deterministic statement frames and dropped at statement end; condition temporaries flush before branch dispatch. Ownership handoff through assignment, return, let _, and by-value call arguments cancels pending caller-side drops. Conditional moves of Drop locals now fail loudly until drop-state flags exist, avoiding the former false-path leak. Added exact-trace positive coverage and negative tests for Drop-temporary partial moves and conditional Drop moves. Verification passed: build, fixpoint, full test suite, and test-green.
ehartford commentedon Jun 12, 2026
Re-investigated against 89ad31a (post-#562 slice 1). The issue's table is still live, line numbers have shifted, one bug moved, and the severity ordering inverted: with reuse-after-move now rejected by sema, the remaining reachable shapes in legal programs are 3 double-frees and 6 leaks.
Double-drop grade (expected 1 drop, observed 2):
let a = make(); consume(a)— no reuse: callee drops the moved-in value, then bb1 runs the caller's scheduleddrop(_1)again (MIR confirmed:call sym(move _1)thendrop(_1)).let b = a— no reuse ofa: both locals drop.let t = make(); let _ = t: immediate_drop +t's scheduled drop.Leak grade (expected 1, observed 0): bare-statement temp
make(); receiver tempmake().id.len(); auto-ref'd temppeek(make()); condition tempif make().id.len() > 0:; partial move from a Drop temporary (make().id— sema's partial-move check only covers named bases); and a new one:if c: take(move a)on the false path — commit a339f7f's NK_MOVE_ARG cancel (MirLower.w:8905-8908) runs unconditionally at lowering time, so the true path is now correct but the not-taken path leaks. The bug moved; it didn't die.Root cause (5 Whys): drop obligations are created only at named let bindings (
schedule_drop, MirLower.w:3842) and discharged unconditionally at scope exit;OK_MOVEcarries no obligation transfer and codegen has no drop flags, so cancellation must be static — butcancel_scheduled_value_drop_for_local(MirLower.w:258) is invoked only at ~10 ad-hoc sites (returns, tasks, record update, explicit move…), not at the two generic ownership-transfer choke points:assign_operand_to_place(MirLower.w:2466) and the by-value tail oflower_call_arg(MirLower.w:6196). And no statement-temp drop points exist at all (lower_expr_discardthrows the OK_MOVE away, MirLower.w:3925). MirLower has no drop elaboration; the side-stack is mutated only when someone remembers.Spec §2.4 is explicit on both counts: "Temporaries created within an expression are dropped at the end of the enclosing statement" (spec :417-419) and reverse-declaration drop order (:404).
Fix plan (three independently-green commits, in this order):
consume_moved_operandhelper invoked fromassign_operand_to_placeand the by-valuelower_call_argtail + method arg paths; guard it to cancel only entries scheduled in the current unconditional lowering context (else leave the drop — loud double-drop beats silent leak); fold the unguarded :8907 NK_MOVE_ARG cancel into the same helper, fixing the new false-path leak.lower_block_mode, registered at the fivelower_call*temp sites; flush condition frames before SwitchInt; exclude Task types (Implement position-based Task disposition semantics #350's domain).Risks: drop order determinism (Vec-only, no map iteration), and the bootstrap itself is the biggest consumer of temp semantics — full chain + fixpoint per commit.
Apply the conditional-move rule to explicit move arguments