Skip to content

Fix #1302: a match on a place observes it; only a pattern that binds an owned value consumes the subject - #1314

Merged
ehartford merged 2 commits into
mainfrom
fix-1302-match-field-move
Sep 22, 2026
Merged

ehartford merged 2 commits into
mainfrom
fix-1302-match-field-move

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1302.

Symptom

match self.field: (and x.field, a nested field, an element, a plain local, if let, let-else) on a non-Copy enum moved the subject out of its place, reset the place to all-zero, and dropped the value in the arms. The next match decoded the sentinel as variant 0 of variant 0 (Some(.LBrace)), so the corruption read as a plausible stale token. Sema never flagged it: the later show(&x) compiled.

Root cause (tool evidence)

with check q5.w --dump-mir, P.outer before:

_4 = move _1.cur;            // MirLower.lower_match: lower_expr(scrutinee) → lazy OK_MOVE, materialize_operand copies it
_6 = discriminant(_4);
...
_1.cur = const zst(ty137);   // consume_moved_operand → queue_field_move_reset
...
_8 = move _4; drop(_8)       // the `_` arm's A7 drop local

Sema's check_match_expr never marks a match subject consumed at all, while lower_match unconditionally materializes it and cancels its drops — the two phases disagreed (Sema: observe; MIR: consume). --validate-all / --validate-ownership both say ok on that MIR: it is a well-formed move + reset, so no validator can see the contract mismatch (noted below).

After: _5 = discriminant(_1.cur), the field untouched, no reset, no drop.

Rule (spec §2.2 D32, §9.7 D22/D27)

A pattern is structural projection, not an owned demand. One predicate, one home — Sema.pattern_binds_owned_value: an arm consumes its subject only when it binds a non-Copy value by value (or is the #1272 Drop disarm). A consuming arm marks the subject before its body: a local becomes moved (§2.2 flow rules govern later uses), a field is the D32 implicit-field-move error with its move/.clone() fix-its, a temporary or explicit move subject needs nothing. Sema records the verdict (consuming_pattern_subjects); MirLower reads it and matches a non-consumed, non-Copy, by-value place in place; _/.. on an observed subject move nothing.

Evidence

  • Issue repro prints false false (was false true); subject matrix (mut fn / fn receiver, local, nested, element, if-let, let-else, Copy payload, move) runs with --debug-alloc: leak count=0.
  • New tests: behav_match_place_observes, da_match_place_observes, err_match_field_binds_owned (D32 on a by-value payload binding out of a field), err_match_local_consumed_then_used (use-after-move on the local). Sema: a pattern never skips a destructor — destructuring a Drop value errors outside the type's own move fn, total inside it (#1272) #1291's four pattern tests and behav_match_returning_arm_move still pass.
  • with check src/main.w clean; src/main build green; :move-audit green; :drop-audit green; :cli-selfhost-build-w-tests green.
  • The only population the new rule rejected: the generated workspace fixtures in build/selfhost.w and build/pcre2.w, which bound decls/command/message/done out of envelope.message — a field of a let local, the exact silent field move D32 forbids. Second commit applies the diagnostic's own fix-it (var + match move envelope.message), mechanically via with -p.

Open points

  • :examples-tests is red on examples/fizzbuzz.w ("match expression of type str cannot produce &str"). Reproduced with the installed pre-fix compiler; the expression is a Copy tuple temporary with no owned bindings, outside every path this change touches. Verifying on a clean origin/main build before un-drafting.
  • The bootstrap stage1 binary's --validate-all on the 20-line repro ran 15 min at 7 GB RSS (release binary: 0.07 s). Filed separately.
  • No validator can flag "MIR consumed a place Sema did not mark consumed"; the Sema verdict map now makes that a single source of truth, but an analyze audit joining consuming_pattern_subjects against MIR move operands on pattern subjects would close the class.

Eric Hartford added 2 commits September 22, 2026 11:10
…an owned value consumes the subject

`match self.cur:` on a non-Copy enum field moved the field into a scratch
temp, reset it to all-zero, and dropped it in the arms; the next match
decoded the sentinel as variant 0 of variant 0 (`Some(.LBrace)`). The same
lowering consumed a local subject (`match x` twice read the sentinel the
second time), `x.field`, nested fields, elements, `if let` and `let-else`.

Root cause (MirLower.lower_match, `--dump-mir` of the issue's repro):
`lower_expr(scrutinee)` lowers a place subject to a lazy `OK_MOVE _1.cur`
and `materialize_operand` assigns it into `_4`, whose assign_operand_to_place
→ consume_moved_operand queues the field reset (`_1.cur = const zst`); the
`_` arm then moves `_4` into a drop local. Sema's check_match_expr never
marked the subject consumed at all, so the two phases disagreed: Sema
observed, MIR consumed, and no validator can see that (validate-all and
validate-ownership both say ok — the MIR is a well-formed move + reset).

Rule (§2.2 D32, §9.7 D22/D27): a pattern is structural projection. One
predicate in one home: Sema.pattern_binds_owned_value — an arm CONSUMES its
subject only when it binds a non-Copy value by value (or is the #1272 disarm
of a Drop type). A consuming arm marks the subject before its body: a local
becomes moved (§2.2 flow rules govern later uses), a field is the D32
implicit-field-move error with its `move`/`.clone()` fix-its, a temporary or
explicit `move` subject needs nothing. Sema records the verdict in
consuming_pattern_subjects; MirLower reads it and matches a non-consumed,
non-Copy, by-value place (local, field chain, element) IN PLACE — no temp,
no reset, no cancelled drop — and `_`/`..` on an observed subject move
nothing into drop locals. The flag wraps only each match's own pattern
lowering so a nested match on a temporary keeps its payload drops.

After: `_5 = discriminant(_1.cur)` and the field is untouched; the subject
matrix (mut fn / fn receiver, local, nested field, element, if-let, let-else,
Copy payload binding, `move` subject) runs clean under --debug-alloc.

Tests: behav_match_place_observes (twice-in-a-row matches on every subject
shape still see the variant; `move` transfers exactly once, counted by
Drop), da_match_place_observes (leak count=0 with str payloads),
err_match_field_binds_owned (D32 on a by-value payload binding out of a
field), err_match_local_consumed_then_used (use-after-move on the local).
…ove envelope.message`)

The generated workspace-API fixtures (build/selfhost.w) and the pcre2
cohesive check bind non-Copy payloads (`decls`, `command`, `message`,
`done`) out of `envelope.message`, a field of a `let` local — the implicit
field move §2.2 (D32) forbids, which the match lowering let through
silently until #1302. Apply the diagnostic's own fix-it: a `var` base and
the explicit `move` subject. Mechanical (`with -p` over both files).
@ehartford
ehartford marked this pull request as ready for review September 22, 2026 15:30
@ehartford

Copy link
Copy Markdown
Contributor Author

Verified the :examples-tests red is pre-existing: a clean origin/main (bbb9c5b) stage1 built in a separate worktree fails examples/fizzbuzz.w with the same match expression of type strcannot produce&str`` at 7:23. Un-drafting; that example is tracked separately.

@ehartford
ehartford merged commit e9544d5 into main Sep 22, 2026
@ehartford
ehartford deleted the fix-1302-match-field-move branch September 22, 2026 16:25
ehartford added a commit that referenced this pull request Sep 22, 2026
…g (release-only segfault); da_match_place_observes never allocated (#1322)

* ComptimeTransform: own the texts taken from intern.resolve — the derive generators held a view across interning

`out/release/bin/with check test/behavior/derive_enum_debug_clone.w`
segfaulted (rc 139, no output); the same test passed on the stage1 built
by the pinned seed, so main went red only in the battery (behavior-tests
lane, release binary) after #1311 and #1314 merged.

Root cause (lldb on the cffb1cb release binary, frame
Sema.ct_generate_debug_derive +1432):

    ->  ldp x8, x9, [x20]        ; x20 = [sp+0x28], the `type_name` &str
        ...
        bl  with_str_concat_n    ; type_name ++ ".debug_str"
    EXC_BAD_ACCESS address == x20; x27 (the live symbol_texts buffer)
    is in another region; the page under x20 reads as zeros.

`InternPool.resolve` returns `&str`, a view into `symbol_texts: Vec[str]`
(InternPool.w:136). Every generator bound it — `let type_name =
intern.resolve(type_name_sym)` — then interned new texts
(`ct_build_string_lit`, `intern.intern`) before its last use, so the
table grew, the old buffer was freed, and the tail read through the
dangling view. Which compiler generation lowers that `let` as a true
D27 view (the current one) versus a header copy (the older seed) is
the "layout" that made it release-only; which derives run in one
module is what made the growth land inside this function.

Fix: own the text at every such binding (17 sites, one `with -p`
rewrite: `intern.resolve(sym).clone()`), the same spelling
SemaDecl.w:907 already uses for its own pool text. No generator logic
changes.

Evidence: the rebuilt release binary compiles and passes
derive_enum_debug_clone.w and the derive/match suites; :move-audit and
:drop-audit ran on the batch (results in the PR).

* da_match_place_observes: build the str payloads at runtime so the allocator report exists

The fixture's payloads were all-literal `++` chains (`"one" ++ "two"`),
which MirLower.try_fold_literal_str_concat folds to one constant
(`_1 = const "sym…"` in --dump-mir), so the program never allocated,
`with_debug_alloc_report_leaks` returned before printing (dbg_base == 0),
and the lane failed on `want: 'leak count=0'` with no report line to
read. The match-observes rule under test was never exercised over heap
payloads, which is the point of the fixture.

A two-parameter helper (`fn heap(a: str, b: str): a ++ b`) keeps every
asserted length and produces a runtime concat (`str_concat_n` in the
MIR); `run --debug-alloc` now prints `leak count=0` and the lane driver
passes the fixture.

---------

Co-authored-by: Eric Hartford <[email protected]>
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.

match self.field: on a non-Copy enum field moves the field out and blanks it (patterns are projection, not owned demand)

1 participant