Repository navigation
Struct patterns test literal fields; exhaustiveness reads whole patterns (#1388) - #1405
Conversation
|
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 |
…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
6f01a05 to
acaaae9
Compare
|
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: |
…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.
…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]>
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_matchhad noNK_PAT_STRUCTbranch. 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.kindreturns0x6b(NK_PAT_STRUCT) and control reaches the shared goto tail withw1 = 0(TK_GOTO) andw2 = 2(arm_bb).--dump-mirof the repro showsbb0: 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 wereSome(5), NoneoverOption[i32]and0, 1overi32(#994). Each of those fell through to an uninitialised result at run time.Fix
NK_PAT_STRUCTtests 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 }overPair[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.0..=127, 128..=255overu8counts as exhaustive. Open types (str, floats,u64and 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.Circle { r }) reached codegen untyped.Matrix (stage1 of this branch)
_field;..rest; shorthand vsfield: binding@bindingPair[i32]if let, let-else (let Point { x: 0, y } = p else: return -1)let Point { x: 0, y } = pwithout elsefor Point { x: 0, y } in psforfilter semantics of behav_for_full_patterns; used to bind every point)[y for Point { x: 0, y } in ps].V { a: 1, b }Some(5)_: u8 ranges,(bool, bool),Option[bool][]i32Fixtures
test/behavior/behav_struct_pattern_refutable_fields.w: one stdout line per function, each arm's output distinct.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)
checkover the 423 files in test/behavior, test/compile_errors and examples that contain amatch, a patternfor, or a struct/slice pattern: only the new fixture differs.testover the 34 files with struct or slice patterns: only the new fixtures differ.forpatterns. That rejection was dropped, and the file keeps its filter semantics.with-stage1 check src/main.w: ok. On the fixture:analyze audit:all0 violations,--validate-allok,run --debug-allocleak count 0.Iterate tier only (
with build :dev). No battery has been run, so this stays a draft.For Eric
Refutable
forpatterns 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.