Skip to content

Commit 998bf0a

Browse files
author
Daniel Noom
committed
Add note to non-exhaustive match on reference to empty
Rust prints "type `&A` is non-empty" even is A is empty. This is the intended behavior, but can be confusing. This commit adds a note to non-exhaustive pattern errors if they are a reference to something uninhabited. I did not add tests to check that the note is not shown for non-references or inhabited references, because this is already done in other tests. Maybe the added test is superfluous, because `always-inhabited-union-ref` already checks for this case. This does not handle &&Void or &&&void etc. I could add those as special cases as well and ignore people who need quadruple references. Fixes rust-lang#78123
1 parent 18cb4ad commit 998bf0a

File tree

4 files changed

+29
-0
lines changed

4 files changed

+29
-0
lines changed

compiler/rustc_mir_build/src/thir/pattern/check_match.rs

+5
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,11 @@ fn non_exhaustive_match<'p, 'tcx>(
503503
));
504504
}
505505
}
506+
if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
507+
if cx.tcx.is_ty_uninhabited_from(cx.module, sub_ty, cx.param_env) {
508+
err.note("references are always considered inhabited");
509+
}
510+
}
506511
err.emit();
507512
}
508513

src/test/ui/pattern/usefulness/always-inhabited-union-ref.stderr

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ LL | match uninhab_ref() {
66
|
77
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
88
= note: the matched value is of type `&!`
9+
= note: references are always considered inhabited
910

1011
error[E0004]: non-exhaustive patterns: type `Foo` is non-empty
1112
--> $DIR/always-inhabited-union-ref.rs:27:11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
enum A {}
2+
3+
fn f(a: &A) {
4+
match a {} //~ ERROR non-exhaustive patterns: type `&A` is non-empty
5+
}
6+
7+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0004]: non-exhaustive patterns: type `&A` is non-empty
2+
--> $DIR/issue-78123-non-exhaustive-reference.rs:4:11
3+
|
4+
LL | enum A {}
5+
| --------- `A` defined here
6+
...
7+
LL | match a {}
8+
| ^
9+
|
10+
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
11+
= note: the matched value is of type `&A`
12+
= note: references are always considered inhabited
13+
14+
error: aborting due to previous error
15+
16+
For more information about this error, try `rustc --explain E0004`.

0 commit comments

Comments
 (0)