Skip to content

Struct patterns test literal fields; exhaustiveness reads whole patterns (#1388) - #1405

Merged
ehartford merged 1 commit into
mainfrom
fix-1388-struct-pattern-literal-field
Sep 23, 2026
Merged

ehartford merged 1 commit into
mainfrom
fix-1388-struct-pattern-literal-field

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1388. Refs #994 (the check half: an expression-position match over an integer with no catch-all is now rejected), #1389, #1403.

Root cause

MirLower.lower_pattern_match had no NK_PAT_STRUCT branch. A named-field struct pattern fell into the last line of the function, the "Other patterns (struct) are conservatively accepted here" default: self.terminate(TermKind.TK_GOTO, arm_bb, 0, 0, 0) (src/MirLower.w:8843 on 00408eb). No field was tested.

Evidence from a stage2 of origin/main, with lldb on the pattern-kind dispatch: AstPool.kind returns 0x6b (NK_PAT_STRUCT) and control reaches the shared goto tail with w1 = 0 (TK_GOTO) and w2 = 2 (arm_bb). --dump-mir of the repro shows bb0: goto -> bb2, the arm, with no read of _1.x.

The exhaustiveness checker had the same gap one layer up. It checked only top-level bool, sealed-trait and enum-variant names, so match p { Point { x: 0, y } => y } was accepted as a value, and so were Some(5), None over Option[i32] and 0, 1 over i32 (#994). Each of those fell through to an uninitialised result at run time.

Fix

  • MirLower: NK_PAT_STRUCT tests every refutable field sub-pattern, the same way the positional and tuple forms do. Field places carry the field's type, read from the subject, so patterns over generic struct instances also lower (Pair { a, b } over Pair[i32] used to fail with an invalid-MIR ICE). The default branch is now loud: a pattern kind with no test lowering reports an error and marks the function unsupported. It no longer matches every value.
  • Sema: exhaustiveness is now a pattern-matrix usefulness check (Maranget) over whole patterns. It handles bool, enum variants with their payloads, tuples, structs, and bounded integers, which are split into literal/range segments so 0..=127, 128..=255 over u8 counts as exhaustive. Open types (str, floats, u64 and wider) need a catch-all. The error names a witness, e.g. non-exhaustive match on 'Point': `Point { x: 1, .. }` is not covered. D43's missing-arm test (match_has_missing_arm) uses the same answer.
  • Sema: a struct pattern is rejected when the subject is not a struct, when the pattern's type name does not match the subject's type, or when it names a field the subject does not have. Before, an enum subject (Circle { r }) reached codegen untyped.

Matrix (stage1 of this branch)

case result
int literal, negative literal, bool, char/u8, str, range field correct arm
nested struct / tuple / Option in a field; _ field; .. rest; shorthand vs field: binding correct arm
guards, or-patterns across arms, multiple arms falling through, @ binding correct arm
generic struct Pair[i32] correct arm (was ICE)
if let, let-else (let Point { x: 0, y } = p else: return -1) tested
let Point { x: 0, y } = p without else existing refutable error
for Point { x: 0, y } in ps skips non-matching points (the for filter semantics of behav_for_full_patterns; used to bind every point)
comprehension [y for Point { x: 0, y } in ps] still binds every element; pre-existing for every refutable pattern → #1403
enum struct-variant .V { a: 1, b } not in the language (§30.6 ENUM_PAT is positional); a braced pattern on an enum subject is now a Sema error
non-exhaustive: literal field, nested enum field, guard-only coverage, u8 range gap, borrowed subject, struct in tuple, i32, Some(5) compile errors with a witness
exhaustive without _: u8 ranges, (bool, bool), Option[bool] accepted
statement-position partial struct match allowed (§9.7)
slice pattern on a dynamic []i32 was a silent first-arm match; now a loud MIR error (#1389 tracks lowering it)

Fixtures

  • test/behavior/behav_struct_pattern_refutable_fields.w: one stdout line per function, each arm's output distinct.
  • 11 test/compile_errors/ fixtures: literal field, nested enum field, guard, int range, borrowed subject, struct in tuple, i32 (Non-exhaustive expression-position match on integers silently yields zero value #994), Option payload literal, struct-pattern type mismatch, unknown field, enum subject. All fail against stage1 of 00408eb and pass on this branch.

Sweep (before = stage1 of 00408eb, after = stage1 of this branch)

  • check over the 423 files in test/behavior, test/compile_errors and examples that contain a match, a pattern for, or a struct/slice pattern: only the new fixture differs.
  • test over the 34 files with struct or slice patterns: only the new fixtures differ.
  • No existing program changed output. The only program that relied on the bug was behav_for_full_patterns.w, and only while an intermediate version of this change rejected refutable for patterns. That rejection was dropped, and the file keeps its filter semantics.
  • with-stage1 check src/main.w: ok. On the fixture: analyze audit:all 0 violations, --validate-all ok, run --debug-alloc leak count 0.

Iterate tier only (with build :dev). No battery has been run, so this stays a draft.

For Eric

Refutable for patterns filtering, rather than being an error, is existing behavior (behav_for_full_patterns). §9.7 does not say which it should be. This PR keeps the filter.

@ehartford

Copy link
Copy Markdown
Contributor Author

On the open question in the description: the spec already rules it. §13.5 (docs/with-specification.md:6258-6261): "Pattern matching uses the same pattern language as let and match. Irrefutable patterns bind every element. Refutable patterns are allowed; elements that do not match are skipped and iteration continues." So for Point { x: 0, y } in ps filtering is the specified behavior — no ruling needed. #1403 (comprehensions binding every element for a refutable pattern) is the same rule, non-compliant today. Battery queued (alone, with :drop-audit/:move-audit).

…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
@ehartford
ehartford force-pushed the fix-1388-struct-pattern-literal-field branch from 6f01a05 to acaaae9 Compare September 23, 2026 04:26
@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
ehartford marked this pull request as ready for review September 23, 2026 04:26
@ehartford
ehartford merged commit 05b674e into main Sep 23, 2026
@ehartford
ehartford deleted the fix-1388-struct-pattern-literal-field branch September 23, 2026 04:46
ehartford pushed a commit that referenced this pull request Sep 23, 2026
…iews and lower; no more invalid MIR (§9.7, #1389)

`match v: [first, ..] => first` with `v: &Vec[i32]` passed Sema and then
failed: "invalid MIR before codegen: use rvalue does not resolve to a
concrete MIR type" (and "pattern kind 113 has no match-test lowering" once
#1405 made the test path loud). `let [first, ..] = v else: return -1`
failed the same way. A borrowed array (`match a: [x, y, z]` over
`&[3]i32`) and a slice (`[]i32`) failed too.

Root causes:
- SemaCheck.check_pattern (NK_PAT_SLICE) took the element type only from a
  direct TY_ARRAY or TY_SLICE subject. A `&Vec[T]`, `Vec[T]` or `&[N]T`
  subject left every binding typed 0, silently, with no diagnostic.
- MirLower.lower_pattern_match had a length test only for a direct array.
  MirLower.lower_pattern bound elements with `new_field_place(scrutinee,
  i)` on the unshaped subject (a reference, for `&Vec`) and defaulted the
  element type to i32 (`var sp_elem_ty = self.sema.ty_i32`), the invalid
  MIR in the report.

Fix (D27: element access observes). An owned fixed-size array is still
taken apart by value. Any other sequence is observed in place, and each
named element binds as a view `&T`:
- Sema: slice_pattern_seq_elem gives the element type of a borrowed array,
  a slice, or a Vec (owned or borrowed). Its bindings are `&T`. A subject
  that is not a sequence is an error ("a slice pattern requires an array,
  slice or Vec subject, found 'i32'"). exh_slice_always_matches sees
  through the borrow, so a borrowed array is decided by its length the
  same way.
- MIR: a slice or Vec is tested at run time, `len == n` without a rest and
  `len >= n` with one. The length comes from RK_LEN on a copied slice view
  (RK_LEN does not see through a deref, see lower_sequence_place) or from
  VEC_LEN. lower_slice_pattern_views binds head elements by index and tail
  elements at len - k, through an RK_REF of the indexed element (slice),
  VEC_GET_REF (Vec), or an RK_REF of the array element (borrowed array,
  indices known). The i32 default is gone: a subject the binding path
  cannot shape is loud.
- A named rest over a slice or Vec keeps its loud error ("slice rest
  binding for dynamic slices is not implemented yet"). §9.7 binds `rest`
  to the remaining count for fixed-size arrays and uses it as a slice in
  its match example, so which one a dynamic rest binds is not decided.

Matrix (stage1 before -> after; every cell was invalid MIR or a missing
test lowering before):
  &Vec[i32]  match [first, ..] / _           -> 4 -1
  &Vec[i32]  let [first, ..] = v else        -> 4 -1
  Vec[i32]   match [a, .., z] / [_] / _      -> "1 4", "one"
  &[3]i32    match [x, y, z]; let [p, q, r]  -> 6, 1 2 3
  &Vec[str]  match [x, .., y]                -> 3 ab cd (views, no moves)
  []i32      match [a, b] / [a, ..] / [] / _ -> 2 -2 9
  &Vec[i32]  match [] / [_] / _              -> empty one many
  let [first, .., last] = &[6, 0, 1]         -> 6 1
The fixture runs with `leak count=0` under the debug allocator. The
owned-array fixtures (behav_let_else_slice_rest_binding,
err_let_else_slice_rest_unsupported) pass unchanged. `stage1 check
src/main.w`: ok.

Filed: a match that covers every length of a slice or Vec
(`[]`/`[_]`/`[_, ..]`) still demands `_`, so the §9.7 example is rejected
(#1533). The engine treats dynamic slices as open, by design since #1388.

Fixtures: behav_1389_slice_pattern_sequences,
err_1389_slice_pattern_non_sequence, err_1389_vec_rest_binding_unsupported.
ehartford added a commit that referenced this pull request Sep 24, 2026
…iews and lower; no more invalid MIR (§9.7, #1389) (#1578)

`match v: [first, ..] => first` with `v: &Vec[i32]` passed Sema and then
failed: "invalid MIR before codegen: use rvalue does not resolve to a
concrete MIR type" (and "pattern kind 113 has no match-test lowering" once
#1405 made the test path loud). `let [first, ..] = v else: return -1`
failed the same way. A borrowed array (`match a: [x, y, z]` over
`&[3]i32`) and a slice (`[]i32`) failed too.

Root causes:
- SemaCheck.check_pattern (NK_PAT_SLICE) took the element type only from a
  direct TY_ARRAY or TY_SLICE subject. A `&Vec[T]`, `Vec[T]` or `&[N]T`
  subject left every binding typed 0, silently, with no diagnostic.
- MirLower.lower_pattern_match had a length test only for a direct array.
  MirLower.lower_pattern bound elements with `new_field_place(scrutinee,
  i)` on the unshaped subject (a reference, for `&Vec`) and defaulted the
  element type to i32 (`var sp_elem_ty = self.sema.ty_i32`), the invalid
  MIR in the report.

Fix (D27: element access observes). An owned fixed-size array is still
taken apart by value. Any other sequence is observed in place, and each
named element binds as a view `&T`:
- Sema: slice_pattern_seq_elem gives the element type of a borrowed array,
  a slice, or a Vec (owned or borrowed). Its bindings are `&T`. A subject
  that is not a sequence is an error ("a slice pattern requires an array,
  slice or Vec subject, found 'i32'"). exh_slice_always_matches sees
  through the borrow, so a borrowed array is decided by its length the
  same way.
- MIR: a slice or Vec is tested at run time, `len == n` without a rest and
  `len >= n` with one. The length comes from RK_LEN on a copied slice view
  (RK_LEN does not see through a deref, see lower_sequence_place) or from
  VEC_LEN. lower_slice_pattern_views binds head elements by index and tail
  elements at len - k, through an RK_REF of the indexed element (slice),
  VEC_GET_REF (Vec), or an RK_REF of the array element (borrowed array,
  indices known). The i32 default is gone: a subject the binding path
  cannot shape is loud.
- A named rest over a slice or Vec keeps its loud error ("slice rest
  binding for dynamic slices is not implemented yet"). §9.7 binds `rest`
  to the remaining count for fixed-size arrays and uses it as a slice in
  its match example, so which one a dynamic rest binds is not decided.

Matrix (stage1 before -> after; every cell was invalid MIR or a missing
test lowering before):
  &Vec[i32]  match [first, ..] / _           -> 4 -1
  &Vec[i32]  let [first, ..] = v else        -> 4 -1
  Vec[i32]   match [a, .., z] / [_] / _      -> "1 4", "one"
  &[3]i32    match [x, y, z]; let [p, q, r]  -> 6, 1 2 3
  &Vec[str]  match [x, .., y]                -> 3 ab cd (views, no moves)
  []i32      match [a, b] / [a, ..] / [] / _ -> 2 -2 9
  &Vec[i32]  match [] / [_] / _              -> empty one many
  let [first, .., last] = &[6, 0, 1]         -> 6 1
The fixture runs with `leak count=0` under the debug allocator. The
owned-array fixtures (behav_let_else_slice_rest_binding,
err_let_else_slice_rest_unsupported) pass unchanged. `stage1 check
src/main.w`: ok.

Filed: a match that covers every length of a slice or Vec
(`[]`/`[_]`/`[_, ..]`) still demands `_`, so the §9.7 example is rejected
(#1533). The engine treats dynamic slices as open, by design since #1388.

Fixtures: behav_1389_slice_pattern_sequences,
err_1389_slice_pattern_non_sequence, err_1389_vec_rest_binding_unsupported.

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.

Struct pattern ignores a literal field sub-pattern: Point { x: 0, y } matches any x (match and let-else)

1 participant