Repository navigation
Description
Borrow checker Rule 7: implicit drop is a use (§21.1)
Summary
§21.1 Rule 7 requires that the implicit destructor call inserted at scope exit be treated as a use of the dropped variable for borrow-checking purposes, so a container holding &x cannot outlive x to its own drop point. No drop-as-use analysis exists today. The rule is currently masked by a stronger blanket ban — references cannot be stored in generic containers at all — but the spec'd ephemeral-container model (§22.1 Rule 7) explicitly allows Vec[&T] as a local, and as soon as that lands, drop-as-use becomes load-bearing for soundness.
Spec
§21.1 Rule 7 (docs/with-specification.md:10563-10580):
Implicit drop is a use. When a variable implementing
Dropgoes out of scope, its implicit destructor call is treated as a use of that variable for borrow-checking purposes.
var v: Vec[&i32] = Vec.new()
var x = 5
v.push(&x)
// End of scope: x drops first, then v drops.
// v.drop() accesses &x, but x is already freed!
// Rejected: v's implicit drop uses &x after x is destroyed.
The compiler inserts implicit drop points at scope exit in reverse declaration order. Each drop point is a "use" of the variable being dropped, extending the borrow lifetime through the destructor.
Related: §22.1 Rule 7 (ephemeral Vec[T] with ephemeral T is usable as a local), §22.3 Diagnostic Contract (every rejection must report origin, violation, later use, and a remedy).
Current state
- No drop-as-use analysis exists anywhere in sema. Borrow state is tracked in the
borrow_places/borrow_kinds/borrow_refs/borrow_path_*/borrow_creation_nodesparallel vectors (seeSema.check_borrow_create_direct,src/SemaCheck.w:~11811), and expiry is last-explicit-use scanning viaSema.expire_dead_borrows_in_block(called fromcheck_block,src/SemaCheck.w:4388,4409). Scope-exit drops are invisible to this machinery. - Masking ban:
src/SemaCheck.w:4497-4498rejects ref-bearing container bindings outright incheck_let_binding:
self.emit_error("ephemeral references cannot be stored in generic containers", node)(gated bytype_expr_is_collection_with_ref). So the spec example cannot be written today — requirement verdict21.1.1.10: "vacuous via stored-ref ban". Note this ban itself contradicts §22.1 Rule 7, which allows ephemeral containers as locals (the parser-token collection pattern); lifting it is tracked under the ephemeral-container work (First-class allocators: real Arena/FrameArena/Pool, Vec.new_in, ephemeral virality (§8.3) #437/Make stdlib guards and borrowed-data iterators canonically ephemeral (§5.3) #477/Make ephemerality provenance-tracked and modular #362). - Drop points already exist in MIR, in the right order:
MirBuildermaintains a drop stack (drop_local_ids/drop_kinds,src/MirLower.w:43,180-187) and emits drops by iterating it from the end (reverse declaration order) inpop_scope_with_goto(src/MirLower.w:345-358),pop_scope_inline(:379),emit_drops_for_break(:410),emit_drops_for_return(:448). But MIR lowering runs after sema accepts the program; the borrow checker is AST-level, so Rule 7 must be modeled in sema, mirroring the same reverse order.
Root cause: borrow lifetimes end at the last syntactic use; the synthetic use that the destructor represents is never registered.
Implementation plan
- Track what a binding's drop will use. In sema, maintain per-binding "held borrow origins": when a borrow is registered whose destination is a container/aggregate binding (e.g.
v.push(&x),v.insert(k, &x), struct literal with ref field assigned into a Drop-implementing local), record(container_sym -> origin_sym)pairs. The existing view-dep machinery is the right substrate:binding_view_dep_*(src/Sema.w:523-525) andrecord_call_view_origins(src/SemaCheck.w:4931) already propagate argument origins through calls; extend themut selfreceiver path so a call that stores anEFF_ESCAPE_VIEWargument into the receiver appends the argument's origin syms to the receiver binding's dep list. Use orderedVec[i32]lists keyed by symbol (no unordered-map iteration — fixpoint determinism). - Simulate scope-exit drops in
check_block/pop_scope. At block exit (src/SemaCheck.w:check_block, just beforeself.pop_scope()at:4417), walk the scope's bindings in reverse declaration order. For each binding whose type implementsDrop(or is a builtin owning container) and has a non-empty held-origin list: for each origin sym, if the origin is declared in the same scope at a later position (i.e. its drop has already been simulated) — or more generally, if the origin's scope ends at or before the container's drop point — report a Rule 7 violation. Bindings declared in inner scopes that were already popped also qualify (origin died earlier). - Early-exit paths.
return/break/continue/gotoalso run drops (MirLoweremit_drops_for_returnetc.). The sema-side check in step 2 keyed on declaration order is path-insensitive and conservative-correct for these, since the relative drop order of two locals in the same scope is the same on every exit path. - Diagnostic per §22.3 (three locations + remedy), following the existing labeled-diagnostic precedent at
src/SemaCheck.w:11797-11809(Diagnostic.err+add_label):- primary: the container's implicit drop point (block end / function end span), text e.g.
implicit drop of `v` uses `&x` after `x` is destroyed (§21.1 Rule 7); - label 1:
borrow ofxstored here(thev.push(&x)site, fromborrow_creation_nodes/dep recording); - label 2:
`x` is dropped first here — declared after `v`(origin's decl or scope-end); - help:
declarevafterx, or clear/copy out ofvbefore scope exit.
- primary: the container's implicit drop point (block end / function end span), text e.g.
- Ordering interplay: none of this changes MIR lowering,
rt/, orLink.w— sema-only, so no bootstrap hazard. Land it gated to types that can actually hold borrows once the container ban is lifted; until then the check is exercised through struct-with-ref Drop types if those are representable, otherwise it ships together with the ephemeral-container enablement and its tests.
Edge cases:
- Container declared after the origin (
var x = 5; var v ...; v.push(&x)) is legal: v drops first, x still alive — must not be rejected (this is the precision bar; false rejection is compiler debt). - Re-binding/clearing:
v.clear()or reassignment ofvbefore scope exit does not remove recorded deps under the conservative model; acceptable for v1, note as precision debt. - Drop-implementing struct with
&Tfield behaves identically (deps recorded at struct-literal construction).
Test plan
(These require ephemeral containers or a ref-holding Drop type to be expressible; sequence after the #437/#362 enablement or write against whichever surface lands first.)
test/compile_errors/:
err_drop_use_after_origin.w— the exact spec example (var v: Vec[&i32]; var x = 5; v.push(&x)),//! expect-check-fail: implicit drop.err_drop_use_after_origin_inner_scope.w— origin declared in an inner block, pushed into outer container; rejected.err_drop_use_after_origin_struct_field.w— Drop-implementing struct holding&xdeclared beforex.
test/spec/:
spec_ss21_1_rule7_drop_order_safe.w(//! expect-stdout: ok) — container declared after the origin: accepted and runs (positive precision case).spec_ss21_1_rule7_early_return.w— same-scope ordering violation also detected in a function exited via earlyreturn.
Diagnostic-shape assertion: at least one test asserts the multi-label output (origin site + drop-order note + remedy) per §22.3, via //! expect-stderr fragments if the harness supports it, otherwise documented in the test header.
Acceptance criteria
- The §21.1 Rule 7 spec example is rejected with a three-location diagnostic naming the stored borrow, the origin's earlier drop, and the container's implicit drop, plus a remedy.
- Reversed declaration order (origin first) is accepted — no false rejection.
- Early-exit paths (return/break) get the same verdicts as normal scope exit.
- Verdicts are deterministic across builds (ordered Vec-based dep storage only).
-
with build && with build :fixpoint && with build :testpass;with build :test-greenrecorded.
Dependencies
- First-class allocators: real Arena/FrameArena/Pool, Vec.new_in, ephemeral virality (§8.3) #437 (first-class allocators / ephemeral virality) and Make stdlib guards and borrowed-data iterators canonically ephemeral (§5.3) #477 (canonically ephemeral guards/iterators) — provide the ephemeral-container surface that unmasks this rule; the
src/SemaCheck.w:4497container ban is lifted under that work. - Make ephemerality provenance-tracked and modular #362 (provenance-tracked ephemerality) — supplies the binding-dep substrate this check extends.
- Tests: drop order coverage (§20, §21) #495 (drop order tests) — establishes the reverse-declaration-order behavior this analysis mirrors.
- Bug: Drop expression temporaries are never dropped (§2.4) #430 (drop expression temporaries) — adjacent drop-correctness bug; temporaries that never drop would silently weaken Rule 7 coverage for temporary containers.
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 21.1.1.10, 21.1.1.12.
Activity
ehartford commentedon Jun 12, 2026
Implemented in caf98d9. Scope exit now treats implicit Drop as a use for §21.1 Rule 7, records Drop-value view dependencies through initializers/reassignments and struct literals, and diagnoses Drop values that retain a borrow of a binding destroyed earlier. Added positive and negative coverage. Verification passed: with build, with build :fixpoint, with build :test, and with build :test-green.