Skip to content

Migration: enforce spec §3.8 by-value consume for all non-Copy types #564

Closed

Description

@ehartford

Background

Spec §3.8 (v7.0/v7.1, b18ffc4): "A plain T parameter consumes: the argument is moved into the callee (copied, for Copy types), and the caller's binding is invalidated." MirLower implements this (OK_MOVE + callee drop). Sema does not — it invalidates only when the callee's body-inferred effects carry EFF_CONSUME|EFF_ESCAPE_VALUE.

#562 landed the first slice: unconditional consume enforcement for arguments whose type has a user drop impl — the cases where the sema/MIR disagreement is an observable double-drop today.

Why the rest is a migration, not a fix

Enabling the full rule (all non-Copy types) surfaces 9,194 "use of moved value" errors, including the embedded stdlib (std/cfg/stackify.w, 136) and generated code (out/gen/main.w, 368). Top offenders:

2222 src/CCodegen.w        1708 src/CImport.w        368 out/gen/main.w
2190 src/CodegenDispatch.w  388 src/ComptimeEval.w   292 src/SemaCheck.w
 280 src/CiPrint.w          246 src/Mir.w            228 src/BuildGraphOps.w
 ... 35 files total

The codebase predates the §3.8 model and is built on the by-value share idiom: heap-indirected handle structs (InternPool { state: *mut … }, CfgGraph, codegen contexts) passed by value with copies sharing state, plus read-only data params (TypeKey) passed by value.

Migration direction

The codebase already has the right pattern in places — impl Copy for AstPool (src/Ast.w:465) declares a shared handle truthfully Copy, which the spec rule then exempts. The migration is:

  1. Handle types (struct wrapping *mut State, bitwise copy = share): add impl Copy. Verify any Copy-impl field rules permit it; restructure to the state: *mut pattern where a type holds Vecs directly but relies on share semantics (e.g. CfgGraph).
  2. Read-only data params (e.g. type_key_to_string(key: TypeKey)): switch to &T — auto-ref means call sites don't change — or impl Copy where the type is all-Copy fields.
  3. Genuine consumes: leave as-is; callers that reuse after must copy or restructure.
  4. Stdlib (lib/std, embedded std/cfg/stackify.w) and the c_import/migrator generators need the same treatment before the gate can widen.
  5. Flip the slice-1 gate in Sema.check_call / propagate_method_call_param_effects (search "§3.8" in src/SemaCheck.w) from "arg type has drop impl" to all non-Copy types, per spec. Also extend slice 1's drop-impl test to transitive drop glue (struct containing a Drop field) if the full flip doesn't land soon.

Suggested sequencing: one commit per subsystem (each passing build/fixpoint/test), gate flip last.

Related

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Deep scoping pass (against 89ad31a) — the migration is much smaller than the raw error count suggested, and now has a concrete commit plan.

    Real size: 9,194 raw errors deduplicate to 3,485 unique sites (each reported ~2-3× across stage compiles), and ~85% trace to ~15 types. Receivers never consume — every flagged self was passed positionally to a free function. The unit of work is non-receiver by-value params.

    Top offenders and dispositions:

    sites type disposition
    1588 MirBody (60+ direct Vec fields) &T (~243 params: CCodegen 139, CodegenDispatch 83, …)
    333+249+32 CiTypePool/CiExprPool/CiStmtPool (wrap *mut State) impl Copy — one line each, truthful
    212 BuildGraphTarget &T (44 params)
    114 ComptimeValue (i32/i64/str only — all Copy fields) impl Copy (legal today, verified)
    61 Sema &T (only 33 non-receiver byval params)
    18+11 StackifyGraph/StackifyContext (stdlib) method-ize: free fns already take mut self: StackifyGraph positionally

    Verified facts: Copy-impl field validation exists and is enforced (SemaDecl.w:1616-1642: all fields must be Copy, no Drop) — probed: impl Copy on a Vec-field struct is rejected, on a *mut State wrapper accepted. T→&T flips are signature-only (auto-borrow; no call-site edits). With has no safe &mut T and &Vec is read-only, so callee-mutated by-value params need restructure, not &T.

    Genuine restructures (3 clusters): visiting: HashMap[i32,i32] in SemaCheck (mutated + recursive → move into Sema state), MirSuspendCheck bit-Vec helpers (~50 sites → wrapper with mut self), stackify free fns → real methods. Bonus: the comment at src/Mir.w:415 documents the by-value share idiom is already a latent realloc-aliasing hazard — the &T migration removes real bugs, not just diagnostics.

    out/gen/main.w is just src/main.w with the version substituted (build/compiler.w:692) — fix src/main.w, no generator change.

    Sequencing (each commit passes build+fixpoint; no behavior change until the final flip):

    1. Handle-struct impl Copy (CiTypePool/CiExprPool/CiStmtPool/CiDeclPool/DepOrderAccum/foundation-InternPool/COut) — ~26% of sites.
    2. Plain-data impl Copy (ComptimeValue, CiValueExprIR, CiProjectSymbol, LockEntry, TypeKey/ValueKey, StackifyTarget, CXCursor/CXType/CXString, …).
      3-7. &T flips, one subsystem per commit (MirBody in CCodegen; in CodegenDispatch; Mir/MirLower/Codegen; BuildGraph*/main.w; Lsp/Comptime/CImport tail).
    3. The 3 restructure clusters.
    4. Flip the gate: replace the two has_drop_method guards (search "§3.8" in SemaCheck.w) with is_copy(arg_ty) == 0, keep the extern/c_import exemption. Dry-run the flip in a worktree after phases 1-2 and 3-7 to measure the shrinking remainder.

    Estimate: ~18 impl Copy one-liners + ~400 signature flips + 3 restructures.

  2. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Phase checkpoint — measurement after C1-C6 (worktree dry-run of the gate flip at d1b97fe):

    Raw "use of moved value" errors: 9,194 → 953 (~90% cleared).

    Landed: C1 impl Copy for 7 *mut-state handles (794fdfb), C2 impl Copy for 16 all-Copy-field data structs (a2c4557), C3 CCodegen MirBody→&MirBody ×139 (8a43f51), C4 CodegenDispatch ×83 + mir_call_context (1345044), C5 Mir dump/validate helpers ×13 (45832aa), C6 BuildGraph family ×~50 (d1b97fe).

    Remainder (top): SemaCheck 148 (the visiting HashMap cluster + Sema passes), main.w 87, CodegenDispatch 77, Mir 73, ComptimeEval 73, stackify 64, Compilation 63, MirSuspendCheck 62 (bit-Vec cluster), Lsp 60, MirLower 51, BorrowCfg 49 (CfgGraph).

    Two discoveries constrain the rest:

    Adjusted plan: C8 restructure clusters next (visiting→Sema state, MirSuspendCheck bit-Vec wrapper, stackify methods — none involve &T, so #568 doesn't constrain them). The remaining read-only by-value passes get fixed at gate-flip time as loud sema errors (copy/&T per site), or post-#568 as flips.

  3. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Checkpoint 2 — C8a (stackify stdlib cluster) landed in 13b64cc: the three positional-mut self free-fn mutators are real methods now, and the read-only analyses take &StackifyGraph (one more #567 blind-spot crossing — dfs_post as a method arg — surfaced only at stage2 codegen).

    Landed so far: C1 (794fdfb), C2 (a2c4557), C3 (8a43f51), C4 (1345044), C5 (45832aa), C6 (d1b97fe), C8a (13b64cc). Remainder at last measurement: 953 raw errors (from 9,194).

    Remaining, in suggested order:

    1. C8 cluster 2 — MirSuspendCheck bit-Vec helpers (62 sites): wrap the dataflow bit Vecs in a small struct with mut self methods.
    2. C8 cluster 1 — the visiting: HashMap[i32,i32] cycle-detection params (5 Sema fns, 104 call sites). Design note before implementing: moving visiting into Sema state requires proving may_suspend/creates_ephemeral_task queries never nest (a shared field would corrupt a nested query's cycle state where today's per-call fresh maps are immune). If nesting is possible, the alternative is keeping the param but passing & + an interior-mutability-free redesign (visited set rebuilt per level), or a small *mut-state handle struct (the AstPool pattern) that is truthfully Copy.
    3. BorrowCfg CfgGraph (49 sites): build_expr(graph, pool, node) mutates through bitwise share — method-ize like stackify (same shape, same fix).
    4. Miscompile: auto-ref of mut self receiver passed to &T parameter corrupts memory #568-blocked tail — read-only Sema/MirModule/by-value flips in Lsp/Comptime/Compilation/main.w: deferred until Miscompile: auto-ref of mut self receiver passed to &T parameter corrupts memory #568 is fixed, since self.sema-style receiver-rooted call sites are the silent-miscompile shape.
    5. C9 gate flip — after the above, flip the two has_drop_method guards (search "§3.8" in SemaCheck.w) to is_copy(...) == 0, fix the residual loud errors per site (copy/&T), keep the extern/c_import exemption.

    Fixing #567 first would make every remaining phase dramatically cheaper (sema-located errors instead of one-per-build codegen failures), and #568 is the soundness gate for the tail. Recommend those two before resuming.

  4. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Done — the gate is flipped at full strength in 1f9ec56 and the migration is complete.

    Final state: a plain T parameter consumes any non-Copy argument per spec §3.8 (Copy types are copied; extern/c_import callees exempt). The flipped compiler validates its own sources, the runtime, the stdlib, and the full test suite — build, fixpoint, all 8 unit-test targets, CLI-selfhost, migrator, emit-C — green and pushed; seed and installed compiler updated.

    Journey: 9,194 raw violations → 0, across phases C1-C9 plus the unplanned discoveries the migration forced into the open:

    Remaining related work lives in: #576, #577, #573 (chained-receiver double-visit), #574 (comptime field-iteration segv), #575 (raw-allocation view-origin design question), and the distinct-type tightening noted in #567.

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