Skip to content

Borrow checker Rule 7: implicit drop is a use (§21.1) #444

Closed

Description

@ehartford

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 Drop goes 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_nodes parallel vectors (see Sema.check_borrow_create_direct, src/SemaCheck.w:~11811), and expiry is last-explicit-use scanning via Sema.expire_dead_borrows_in_block (called from check_block, src/SemaCheck.w:4388, 4409). Scope-exit drops are invisible to this machinery.
  • Masking ban: src/SemaCheck.w:4497-4498 rejects ref-bearing container bindings outright in check_let_binding:
    self.emit_error("ephemeral references cannot be stored in generic containers", node) (gated by type_expr_is_collection_with_ref). So the spec example cannot be written today — requirement verdict 21.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: MirBuilder maintains 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) in pop_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

  1. 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) and record_call_view_origins (src/SemaCheck.w:4931) already propagate argument origins through calls; extend the mut self receiver path so a call that stores an EFF_ESCAPE_VIEW argument into the receiver appends the argument's origin syms to the receiver binding's dep list. Use ordered Vec[i32] lists keyed by symbol (no unordered-map iteration — fixpoint determinism).
  2. Simulate scope-exit drops in check_block/pop_scope. At block exit (src/SemaCheck.w:check_block, just before self.pop_scope() at :4417), walk the scope's bindings in reverse declaration order. For each binding whose type implements Drop (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).
  3. Early-exit paths. return/break/continue/goto also run drops (MirLower emit_drops_for_return etc.). 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.
  4. 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 of x stored here (the v.push(&x) site, from borrow_creation_nodes/dep recording);
    • label 2: `x` is dropped first here — declared after `v` (origin's decl or scope-end);
    • help: declare vafterx, or clear/copy out of v before scope exit.
  5. Ordering interplay: none of this changes MIR lowering, rt/, or Link.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 of v before scope exit does not remove recorded deps under the conservative model; acceptable for v1, note as precision debt.
  • Drop-implementing struct with &T field 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 &x declared before x.

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 early return.

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 :test pass; with build :test-green recorded.

Dependencies

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 21.1.1.10, 21.1.1.12.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions