rust/tests/ui/closures/2229_closure_analysis
bors f8463896a9 Auto merge of #150681 - meithecatte:always-discriminate, r=JonathanBrouwer,Nadrieril
Make operational semantics of pattern matching independent of crate and module

The question of "when does matching an enum against a pattern of one of its variants read its discriminant" is currently an underspecified part of the language, causing weird behavior around borrowck, drop order, and UB.

Of course, in the common cases, the discriminant must be read to distinguish the variant of the enum, but currently the following exceptions are implemented:

1. If the enum has only one variant, we currently skip the discriminant read.
     - This has the advantage that single-variant enums behave the same way as structs in this regard.
     - However, it means that if the discriminant exists in the layout, we can't say that this discriminant being invalid is UB. This makes me particularly uneasy in its interactions with niches – consider the following example ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=5904a6155cbdd39af4a2e7b1d32a9b1a)), where miri currently doesn't detect any UB (because the semantics don't specify any):

        <details><summary>Example 1</summary>

        ```rust
        #![allow(dead_code)]
        use core::mem::{size_of, transmute};
        
        #[repr(u8)]
        enum Inner {
            X(u8),
        }
        
        enum Outer {
            A(Inner),
            B(u8),
        }
        
        fn f(x: &Inner) {
            match x {
                Inner::X(v) => {
                    println!("{v}");
                }
            }
        }
        
        fn main() {
            assert_eq!(size_of::<Inner>(), 2);
            assert_eq!(size_of::<Outer>(), 2);
            let x = Outer::B(42);
            let y = &x;
            f(unsafe { transmute(y) });
        }
        ```

      </details>

2. For the purpose of the above, enums with marked with `#[non_exhaustive]` are always considered to have multiple variants when observed from foreign crates, but the actual number of variants is considered in the current crate.
    - This means that whether code has UB can depend on which crate it is in: https://github.com/rust-lang/rust/issues/147722
    - In another case of `#[non_exhaustive]` affecting the runtime semantics, its presence or absence can change what gets captured by a closure, and by extension, the drop order: https://github.com/rust-lang/rust/issues/147722#issuecomment-3674554872
    - Also at the above link, there is an example where removing `#[non_exhaustive]` can cause borrowck to suddenly start failing in another crate.
3. Moreover, we currently make a more specific check: we only read the discriminant if there is more than one *inhabited* variant in the enum.
    - This means that the semantics can differ between `foo<!>`, and a copy of `foo` where `T` was manually replaced with `!`: rust-lang/rust#146803
    - Moreover, due to the privacy rules for inhabitedness, it means that the semantics of code can depend on the *module* in which it is located.
    - Additionally, this inhabitedness rule is even uglier due to the fact that closure capture analysis needs to happen before we can determine whether types are uninhabited, which means that whether the discriminant read happens has a different answer specifically for capture analysis.
    - For the two above points, see the following example ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=a07d8a3ec0b31953942e96e2130476d9)):

        <details><summary>Example 2</summary>

        ```rust
        #![allow(unused)]
        
        mod foo {
            enum Never {}
            struct PrivatelyUninhabited(Never);
            pub enum A {
                V(String, String),
                Y(PrivatelyUninhabited),
            }
            
            fn works(mut x: A) {
                let a = match x {
                    A::V(ref mut a, _) => a,
                    _ => unreachable!(),
                };
                
                let b = match x {
                    A::V(_, ref mut b) => b,
                    _ => unreachable!(),
                };
            
                a.len(); b.len();
            }
            
            fn fails(mut x: A) {
                let mut f = || match x {
                    A::V(ref mut a, _) => (),
                    _ => unreachable!(),
                };
                
                let mut g = || match x {
                    A::V(_, ref mut b) => (),
                    _ => unreachable!(),
                };
            
                f(); g();
            }
        }
        
        use foo::A;
        
        fn fails(mut x: A) {
            let a = match x {
                A::V(ref mut a, _) => a,
                _ => unreachable!(),
            };
            
            let b = match x {
                A::V(_, ref mut b) => b,
                _ => unreachable!(),
            };
        
            a.len(); b.len();
        }
        
        
        fn fails2(mut x: A) {
            let mut f = || match x {
                A::V(ref mut a, _) => (),
                _ => unreachable!(),
            };
            
            let mut g = || match x {
                A::V(_, ref mut b) => (),
                _ => unreachable!(),
            };
        
            f(); g();
        }
        ```

        </details>

In light of the above, and following the discussion at rust-lang/rust#138961 and rust-lang/rust#147722, this PR ~~makes it so that, operationally, matching on an enum *always* reads its discriminant.~~ introduces the following changes to this behavior:

 - matching on a `#[non_exhaustive]` enum will always introduce a discriminant read, regardless of whether the enum is from an external crate
 - uninhabited variants now count just like normal ones, and don't get skipped in the checks

As per the discussion below, the resolution for point (1) above is that it should land as part of a separate PR, so that the subtler decision can be more carefully considered.

Note that this is a breaking change, due to the aforementioned changes in borrow checking behavior, new UB (or at least UB newly detected by miri), as well as drop order around closure captures. However, it seems to me that the combination of this PR with rust-lang/rust#138961 should have smaller real-world impact than rust-lang/rust#138961 by itself.

Fixes rust-lang/rust#142394 
Fixes rust-lang/rust#146590
Fixes rust-lang/rust#146803 (though already marked as duplicate)
Fixes parts of rust-lang/rust#147722
Fixes rust-lang/miri#4778

r? @Nadrieril @RalfJung 

@rustbot label +A-closures +A-patterns +T-opsem +T-lang
2026-02-14 12:53:09 +00:00
..
diagnostics Do not mention -Zmacro-backtrace for std macros that are a wrapper around a compiler intrinsic 2026-01-26 17:34:31 +00:00
match match in closure: capture non_exhaustive even if defined in current crate 2026-01-15 18:35:11 +01:00
migrations Gate 2018 UI tests 2025-11-27 14:13:58 -05:00
optimization Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
run_pass ExprUseVisitor: properly report discriminant reads 2025-12-17 20:47:47 +01:00
array_subslice.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
array_subslice.stderr More accurate mutability suggestion 2024-07-04 05:36:34 +00:00
arrays-completely-captured.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
arrays-completely-captured.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
bad-pattern.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
bad-pattern.stderr Trim suggestion parts to the subset that is purely additive 2025-02-14 00:44:10 -08:00
by_value.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
by_value.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-analysis-1.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
capture-analysis-1.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-analysis-2.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
capture-analysis-2.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-analysis-3.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
capture-analysis-3.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-analysis-4.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
capture-analysis-4.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-disjoint-field-struct.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
capture-disjoint-field-struct.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-disjoint-field-tuple.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
capture-disjoint-field-tuple.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
capture-enum-field.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
capture-enums.rs capture-enums.rs: get rid of feature gate noise 2026-01-15 17:24:35 +01:00
capture-enums.stderr capture-enums.rs: get rid of feature gate noise 2026-01-15 17:24:35 +01:00
deep-multilevel-struct.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
deep-multilevel-struct.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
deep-multilevel-tuple.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
deep-multilevel-tuple.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
deref-mut-in-pattern.rs Add more variations from the PR thread 2025-12-17 20:47:48 +01:00
destructure_patterns.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
destructure_patterns.stderr Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
feature-gate-capture_disjoint_fields.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
feature-gate-capture_disjoint_fields.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
filter-on-struct-member.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
filter-on-struct-member.stderr Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
issue-87378.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
issue-87378.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
issue-88118-2.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
issue-88118-2.stderr Remove hir::Guard 2024-01-05 10:56:59 +00:00
issue-88476.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
issue-88476.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
issue-89606.rs replace //@ compile-flags: --edition with //@ edition 2025-04-10 09:56:37 +02:00
issue-90465.fixed Gate 2018 UI tests 2025-11-27 14:13:58 -05:00
issue-90465.rs Gate 2018 UI tests 2025-11-27 14:13:58 -05:00
issue-90465.stderr Gate 2018 UI tests 2025-11-27 14:13:58 -05:00
issue-92724-needsdrop-query-cycle.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
issue-118144.rs chore: fix some typos 2024-12-31 15:11:18 +08:00
issue-118144.stderr Trim suggestion parts to the subset that is purely additive 2025-02-14 00:44:10 -08:00
issue_88118.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
move_closure.rs UI tests: add missing diagnostic kinds where possible 2025-04-08 23:06:31 +03:00
move_closure.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
multilevel-path-1.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
multilevel-path-1.stderr Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
multilevel-path-2.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
multilevel-path-2.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
nested-closure.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
nested-closure.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
only-inhabited-variant-stable.rs Avoid using #[derive] in test 2025-12-17 20:47:48 +01:00
only-inhabited-variant-stable.stderr Avoid using #[derive] in test 2025-12-17 20:47:48 +01:00
only-inhabited-variant.exhaustive_patterns.stderr ExprUseVisitor: properly report discriminant reads 2025-12-17 20:47:47 +01:00
only-inhabited-variant.normal.stderr ExprUseVisitor: properly report discriminant reads 2025-12-17 20:47:47 +01:00
only-inhabited-variant.rs ExprUseVisitor: properly report discriminant reads 2025-12-17 20:47:47 +01:00
path-with-array-access.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
path-with-array-access.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
preserve_field_drop_order.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
preserve_field_drop_order.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
preserve_field_drop_order2.rs replace //@ compile-flags: --edition with //@ edition 2025-04-10 09:56:37 +02:00
preserve_field_drop_order2.twenty_eighteen.run.stdout Move /src/test to /tests 2023-01-11 09:32:08 +00:00
preserve_field_drop_order2.twenty_twentyone.run.stdout Move /src/test to /tests 2023-01-11 09:32:08 +00:00
repr_packed.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
repr_packed.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
simple-struct-min-capture.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
simple-struct-min-capture.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
unique-borrows-are-invariant-1.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
unique-borrows-are-invariant-1.stderr Show number in error message even for one error 2023-11-24 19:15:52 +01:00
unique-borrows-are-invariant-2.rs [AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
unique-borrows-are-invariant-2.stderr Show number in error message even for one error 2023-11-24 19:15:52 +01:00
unresolvable-upvar-issue-87987.rs Add some notes and test some more pattern variants 2025-01-24 23:49:04 +11:00
unsafe_ptr.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
unsafe_ptr.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00
wild_patterns.rs Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
wild_patterns.stderr Filter empty lines, comments and delimiters from previous to last multiline span rendering 2024-12-12 23:36:27 +00:00