Skip to content

D32: a field reaching an owned if/match/?? join, block tail or break value is an implicit field move (#1395) - #1416

Closed
ehartford wants to merge 4 commits into
mainfrom
fix-1395-field-move-through-branch
Closed

ehartford wants to merge 4 commits into
mainfrom
fix-1395-field-move-through-branch

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1395.

The governing rule

The branch value is an owned demand, not a view, whenever the join has an owned arm — so the program is rejected.

  • §2.2 (D32): "A field never moves out implicitly — anywhere, in any context. The only way to vacate a field is the explicit move place.field, and only through a mutable path (a var base, or the receiver of a mut fn). ... An implicit field move is a compile error at the move site, with fix-its offering both intents: move place.field to vacate ... or place.field.clone() to keep the base whole. ... This rule is uniform over owned locals, receivers, and every other base; there is no flow condition and no type condition."
  • §3.8 / D27 ruling 3: "A binding names what's there; an annotation demands what it says: an unannotated let binds the view unchanged, while a typed binding is an owned-value demand (D22 §6.2, D27). This is uniform across field projections and collection element access." So let p = self.field binds a view, and today it does.
  • §3.8 join rules: "2. If an enclosing expected type or any reaching expression independently establishes an owned result type J, the join result is J. ... A single owned expression is sufficient" and "5. A reference to a non-Copy value cannot satisfy an owned demand; producing an independent value requires an explicit owning operation such as clone."
  • D22 ruling §5.1 lists if let, let ... else, and pattern bindings among the positions that preserve reference identity; none of them turns an owned join into a view.

In let path = if c: self.p else: "", the "" arm makes the result an owned str (rule 2). So self.p is under an owned demand (rule 5), which is an implicit field move (§2.2). The element spelling already works this way: let x = if c: v[0] else: "" is rejected ("if would need to copy a str").

Root cause

  • Sema. mark_moved_if_consumed is the D32 funnel (SemaCheck.w). It gets the consumed expression, which here is the if/match/block node, and never looks at the arms. check_let (SemaCheck.w, the else: self.mark_moved_if_consumed(value) branch) passes it the NK_IF_EXPR, and the funnel falls through without reporting anything.
  • MirLower. lower_expr's NK_FIELD_ACCESS arm then emits OK_MOVE of the field place (return self.body.new_operand(OperandKind.OK_MOVE, place)).
  • Inferred returns. check_fn_body_with_sig_at guarded its tail check with ret_type == 0. For an unannotated fn the signature still reads Unit at that point, so mut fn r(c: bool): if c: self.p else: "" was never checked. Confirmed in lldb: with a breakpoint on Sema.check_returned_field_move, S.r never reached it.

Fix

  • A new helper, d32_check_owned_value_field, peels a value down to what it yields (block tail, grouping, unsafe/comptime) and feeds a bare non-Copy field into the existing funnel. The result is D32's error with its move/.clone() fix-its, or D22 §13.6's borrowed-field error through a view.
  • It is called on each arm of an owned if join, owned match join and owned ?? join, and on break values. mark_moved_if_consumed calls it on a consumed block.
  • The inferred-return tail check now keys on has_ret_annotation.
error: a field never moves out implicitly (§2.2, D32)
 --> test/compile_errors/err_d32_field_move_if_arm_mut_recv.w:10:41
10 |         let path = if self.p.len() > 0: self.p else: ""
   |                                         ^^^^^^
   = help: write `move self.p` to vacate the field (reset-on-move leaves an empty value, §2.5.1), or `self.p.clone()` to keep the owner whole

Matrix (420 programs, run --debug-alloc, before → after)

Axes:

  • Field type: str, Vec[i32], a struct with a str field, and i32 (Copy)
  • Base: mut fn receiver, read fn receiver, owned param, var local, let local
  • Shape: plain let, typed let, if with an owned arm, if with two field arms, typed if, match, block arm, block expression, loop/break, nested self.a.b, nested plain, ??, unwrap_or, consuming argument, if as argument, assignment, receiver (if …).clone(), direct return, return through if, inferred return, return through match

Before:

After:

  • Every non-Copy cell except plain let x = base.p / let x = base.a.b is a compile error:
    • D32 on mut fn receivers, owned params and locals.
    • D22 §13.6 through &self.
  • The plain-let cells still run, bind a view, and leave the field intact.
  • All 105 i32 cells are unchanged (ok).
  • Direct return self.p and typed let were already errors, and the new errors have the same shape.

Sites repaired (commit 1, valid under the old rule too)

Sweep:

  • with-stage1 check src/main.w (the compiler plus embedded std).
  • check of every file under lib/, rt/, tools/, build/ (including build/release_uat_fixtures/) and examples/, plus build.w.
  • All 2,822 test/ files.

Repairs:

  • .clone() (28 compiler sites, 2 in std.build). Includes Sema.record_named_type_with_pub, Sema.record_displaced_fn, the embed_file check and MirLower's two src intrinsics, all on current_module_path, plus root_dir, target_name, source paths and diagnostic facts.
  • var + move where the owner dies right after:
    • ComptimeEval's control-signal value and write_binary bytes.
    • The raw-slot takes in std.collections (binary_heap, hash_index, sorted_vec, trie) and behav_generic_drop_only_use. These hid (*slot).value inside unsafe { }; the unwrapped spelling was already the D32 error.
  • derive(Builder): the generated build now rebinds the consumed builder to a var and vacates each ?? operand, the same way the SoA push already does. spec_ss11_8_derive_builder passes.
  • No UAT fixture, example or blog program hit the diagnostic.

Evidence (iterate tier + audits, no battery)

  • :dev green; with-stage1 check src/main.w → ok.
  • tools/move_audit.w has 58 new field cells (FIELD-ERR verdict). With stage1 vs the pinned seed: 73 cells, 0 vs-expected FAIL. The 42 DIFFs are exactly the new error cells, all of which the seed accepted silently.
  • tools/drop_audit.w, stage1 vs the seed: 136 cells, 0 non-PASS, 0 regressions.
  • New fixtures:
    • 7 in test/compile_errors/ (if/match arm, ??, block tail, break value, inferred return, read-receiver D22).
    • test/behavior/behav_d32_field_join_fixits.w, which runs both fix-it spellings and the view binding.
  • Affected behavior/spec tests run green on stage1 under --debug-alloc: collections, derive builder, std.build, D32 fixtures.

Known limits, filed

@ehartford
ehartford force-pushed the fix-1395-field-move-through-branch branch from a7e6fd0 to 6085fd3 Compare September 23, 2026 03:11
Eric Hartford added 4 commits September 22, 2026 23:53
…eads whole patterns (#1388)

`Point { x: 0, y }` matched any `x` in match, if let, let-else and `for`:
MirLower.lower_pattern_match had no NK_PAT_STRUCT branch, so a named-field
struct pattern fell into the final "conservatively accepted" default,
`self.terminate(TermKind.TK_GOTO, arm_bb, 0, 0, 0)` — no test of any field.
Observed on a stage2 of origin/main: AstPool.kind = 0x6b (NK_PAT_STRUCT) reaches
the shared goto tail with w1 = TK_GOTO, w2 = arm_bb (bb2); --dump-mir of the
repro shows `bb0: goto -> bb2` with no read of `_1.x`.

MirLower:
- NK_PAT_STRUCT tests every refutable field sub-pattern, as the positional
  and tuple forms do; field places carry the field's type (read from the
  subject, so generic struct instances lower — `Pair { a, b }` over
  `Pair[i32]` was an invalid-MIR ICE).
- The default is loud: a pattern kind with no test lowering reports and
  marks the function unsupported instead of matching every value. A slice
  pattern over a dynamic slice (`match s: [] => ...` on `[]i32`), which also
  took the first arm silently, now fails there (#1389).

Sema (§9.7, expression-position matches must be exhaustive):
- Exhaustiveness is a pattern-matrix usefulness check (Maranget) over the
  whole pattern: bool, enum variants with their payloads, tuples, structs,
  bounded integers split into literal/range segments; str, floats and wider
  types need a catch-all. It names a witness: "non-exhaustive match on
  'Point': `Point { x: 1, .. }` is not covered". `Some(5), None` no longer
  counts as exhaustive over Option[i32], nor `0, 1` over i32 (#994's check
  half); `0..=127, 128..=255` over u8 does. D43's missing-arm test uses the
  same answer.
- A struct pattern requires a struct subject, names the subject's type, and
  names only its fields; an enum subject (`Circle { r }`) reached codegen
  untyped.

A refutable `for` pattern keeps its filter semantics (behav_for_full_patterns);
with the lowering fixed, `for Point { x: 0, y } in ps` now skips points whose
x is not 0. Comprehension clauses never test their pattern at all — filed as
#1403.

Sweep: `check` over the 423 test/examples files that contain a match, a
pattern `for` or a struct/slice pattern, and `test` over the 34 with struct or
slice patterns, stage1 of this branch against stage1 of 00408eb: no existing
program changed result; only the new fixtures differ.

Fixes #1388
…1380)

Route: silent wrong value, a move the checker never modeled — MIR dump,
then the checker's own move trace (WITH_DEBUG_MOVE), then the branch.

`let p = if c: a else: b; let q = if c: a else: b` compiled and printed
`[xy] []`, leak count 0.

Evidence (installed v0.15.2.1, repro r.w):
- `--dump-mir`, main: `bb3: _9 = move _1; _1 = const zst(ty16)` and
  `bb4: _9 = move _2; _2 = const zst(ty16)` for the first `if`; the second
  `if` moves the blanked `_1`/`_2` again (`bb6: _11 = move _1`). MirLower's
  lower_if moves an arm's whole-binding tail into the join temp; only
  projected place reads join as a view (#747 03g: `operand_is_view_read`
  requires `place_proj_counts > 0`).
- `WITH_DEBUG_MOVE=1 with check`: `let p = a` logs `[move] sym=a`; the
  `if` version logs no move for `a` or `b`.

Exact line: SemaCheck.check_if_expr (and check_match_expr) check a value
arm through check_expr_value_context and never mark its tail consumed; the
consumer's mark_moved_if_consumed(value) then sees NK_IF_EXPR / NK_MATCH
and does nothing. So Sema's move state never recorded what MIR does.

Fix (§2.2): mark_arm_tail_consumed marks a value arm's whole-binding tail
(through blocks and parens) consumed in the arm's own move state, before
the branch merge — exactly what `let p = a` does. Only a binding that
outlives the arm is marked (§29.8 forbids shadowing, so a live name is the
outer one). The second read is now "use of moved value"; in a loop,
"moved inside a loop". This is the issue's first option. The other (a view
join for whole bindings) would change MIR's ownership, not only the
checker, and is Eric's call.

Every place the new rule rejected in the tree was reading a value the
program had already moved — each a real bug, fixed here:
- CImport ci_translate_anon_record_cursor: `raw_name` moved into
  `actual_name`, so a named field of anonymous-record type inside an
  anonymous record came out as `anon_0` (`o.mid.deep` did not resolve;
  test/behavior/behav_c_import_nested_anon_record_field_name.w, which
  fails on the seed). Clone.
- CImport ci_translate_macros: `offsetof_result` and `cast_expr_result`
  were moved before the branches that re-read them, so the offsetof
  `c_int` branch and the "expression translation" fallback never ran.
  Running them would be wrong (offsetof is size_t, which clang's semantic
  type already gives; the fallback typed `{ .a = 3 }` as a `c_int` global,
  breaking behav_c_import_macro_probe_recovery). Removed, with the
  extern-var pre-scans and ci_expr_references_var that only fed them:
  behavior unchanged.
- ComptimeEval: effect_tool_identity moved `resolved` into the cache key,
  so a tool's identity was always `<exe>:unresolved`, never its sha256;
  glob moved `pattern` (error text lost it) and `rel_file` (a glob based at
  `.` returned "" for every match). Clone.
- BundleInterfaceEmit: `trait_name` moved into the export name, so the
  impl row (and the bundle fingerprint) had an empty trait field. Clone.
- Codegen.declare_function_at_inner: `sema_name_str` / `parsed_name` moved
  into `name_str` / `alias_text`; later reads saw "". Behavior-neutral
  (Backend hands Codegen the Sema pool, so the recovered alias and
  effective name are the same text). Clone.
- std.build tool actions (scratch dir error text) and
  build/release_publish.w (every provenance sidecar after the first said
  `builder=unknown`). Clone.

Matrix (installed v0.15.2.1 vs stage1): if / else-if / match × arm is an
owned str / Vec local, a param, a block tail; consumer is let, assign, call
arg, struct field, method receiver, `++`/f-string; then-used-after, in a
loop, diverging other arm, cloned arms, last use. Before: every
used-after cell compiled and read "" (or Vec len 0); after: each is "use
of moved value" (the loop cell "moved inside a loop"), cloned and last-use
cells compile and print the text. Field arms (`if c: x.s else: y.s`) are
not whole bindings and are unchanged here: MIR treats them as a view join
and still blanks the field — #1409.

Sweep: every file under test/ examples/ lib/ tools/ build/ with a
candidate arm shape (655 files) checked with stage1; the only new
diagnostics were the sites above. `with-stage1 check src/main.w` ok;
`:stage2` (stage1 builds stage2 and the pcre2/zlib/tommyds/c_algorithms
bundles) green; stage2 checks src/main.w. c_import behavior tests: 0
regressions (the six stage1 failures fail the same on main's stage1).
move-audit (stage1 vs seed): 15 cells, 0 FAIL, 0 DIFF.

Fixtures: test/compile_errors/err_if_arm_moves_binding.w,
err_match_arm_moves_binding.w, err_if_arm_move_in_loop.w,
err_if_arm_moved_by_observer.w; test/behavior/behav_if_arm_binding_join.w,
behav_c_import_nested_anon_record_field_name.w.

Ownership (move checking) change: batch alone.

Fixes #1380.
…er whole, var + move to vacate

A field that reaches an owned `if`/`match`/`??` join, a block tail or a
break value was an implicit field move the D32 funnel never saw (#1395).
Every site the fixed compiler reports in src/, lib/ and test/, respelled
with the fix-it the D32 error offers:

- `.clone()` where the owner stays whole: Sema's current_module_path in
  record_named_type_with_pub / record_displaced_fn / embed_file / MirLower's
  src intrinsics (a `mut fn` blanked it mid-collection — the #1350 bug),
  ProjectConfig/Compilation root_dir, CImport bail location, ComptimeEval
  target_name/final_output/location, Codegen analysis_query,
  CodegenDispatch source paths, Frontend source_dir, Analysis diag facts,
  BuildGraph target.entry, std.build ToolFs target_name.
- `var` + `move` where the owner dies right after: ComptimeEval's
  control-signal value and write_binary bytes; the raw-slot takes in
  std.collections (binary_heap, hash_index, sorted_vec, trie) and
  behav_generic_drop_only_use, which hid `(*slot).value` in `unsafe { }`
  (the unwrapped spelling was already the D32 error).
- derive(Builder)'s generated `build` rebinds the consumed builder to a
  `var` and vacates each `??` operand explicitly, as the SoA push does.

Every spelling is valid under the current rule, so this lands first.
…s an implicit field move (#1395)

§2.2 (D32): "A field never moves out implicitly — anywhere, in any
context." §3.8's join rules make every arm of an `if`/`match`/`??` whose
result is owned an owned-value demand (rules 2 and 5: "A reference to a
non-Copy value cannot satisfy an owned demand; producing an independent
value requires an explicit owning operation such as clone"). Only an
unannotated `let x = place.field` binds a view.

Root cause: the D32 funnel (mark_moved_if_consumed) is reached with the
consumed expression — the `if`/`match`/block node — and never looked at
the arms, so `let path = if c: self.p else: ""` passed check while
MirLower's lower_expr NK_FIELD_ACCESS arm emitted OK_MOVE of the field
place: a `mut fn` reset the receiver's field to "" (the #1350 symptom), a
read `fn` byte-copied a Vec field that both owners then freed. The
inferred-return tail check never fired either: check_fn_body keyed it on
`ret_type == 0`, but an unannotated fn's signature still reads Unit there.

Now the if- and match-join, `??`, and break-value sites check each arm of
an owned result, and a consumed block checks its tail, through one helper
(d32_check_owned_value_field) that feeds the existing funnel: D32's error
with its `move`/`.clone()` fix-its, or D22 §13.6's borrowed-field error
through a view. The inferred-return tail check keys on the annotation.

move_audit gains 58 field cells (str/Vec x mut fn/read fn/owned local x
plain, if, match, ??, block, break, argument, inferred return, clone,
move); the baseline accepted all 42 error cells. An all-field join with no
owned anchor is rejected too, where §3.8 rule 3 would bind a view — the
safe direction, filed as #1408.

Fixes #1395.
@ehartford

Copy link
Copy Markdown
Contributor Author

Batch battery Y (seed-driven, NEW seed, with :drop-audit/:move-audit) on main 977e667 + #1405 → #1410 → #1416 → #1422 → #1360 (head 1c7fdee, including the #1410/#1416 and #1422/#1398 merge resolutions): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok; :test red on one lane only — debug-alloc-tests: da_option_filter_observes_payload DOUBLE FREE at its chain case, m.filter(..).map((v) => v.len()): the .map is #1424, main's regression from #1398, fixed by #1425 (batch X2; verified: the #1424 repros run clean on X2's build). Branches now hold exactly the tested chain; merge after #1425, in order #1405, #1410, #1416, #1422, #1360.

@ehartford

Copy link
Copy Markdown
Contributor Author

Landed on main via #1360's squash merge (e1d6cdb): #1360's branch was the tip of the batch-Y chain (#1405 → #1410 → #1416 → #1422 → #1360), so its squash carried every Y commit. Verified: each Y commit's patch is present on main (reverse-applies, or — for #1410, whose hunks #1416 later edited — every file matches the tested chain tip except lines from later merges). Nothing left to merge here.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

D32: an if/else arm naming a mut-receiver field moves it out silently (field blanked, no diagnostic)

1 participant