Skip to content

Commit e0fde9b

Browse files
authored
Unrolled build for #144171
Rollup merge of #144171 - Nadrieril:exhaustive-witnesses, r=davidtwco pattern_analysis: add option to get a full set of witnesses This adds an option to the rustc_pattern_analysis machinery to have it report a complete set of patterns when a match is non-exhaustive (by default we only guarantee to report _some_ missing patterns). This is for use in rust-analyzer. Leaving as draft until I'm sure this is what r-a needs. r? ghost
2 parents f32b232 + af07c08 commit e0fde9b

File tree

7 files changed

+161
-21
lines changed

7 files changed

+161
-21
lines changed

compiler/rustc_pattern_analysis/src/constructor.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -950,9 +950,7 @@ impl<Cx: PatCx> Constructor<Cx> {
950950
}
951951
}
952952
Never => write!(f, "!")?,
953-
Wildcard | Missing | NonExhaustive | Hidden | PrivateUninhabited => {
954-
write!(f, "_ : {:?}", ty)?
955-
}
953+
Wildcard | Missing | NonExhaustive | Hidden | PrivateUninhabited => write!(f, "_")?,
956954
}
957955
Ok(())
958956
}

compiler/rustc_pattern_analysis/src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@ pub trait PatCx: Sized + fmt::Debug {
5757

5858
fn is_exhaustive_patterns_feature_on(&self) -> bool;
5959

60+
/// Whether to ensure the non-exhaustiveness witnesses we report for a complete set. This is
61+
/// `false` by default to avoid some exponential blowup cases such as
62+
/// <https://github.com/rust-lang/rust/issues/118437>.
63+
fn exhaustive_witnesses(&self) -> bool {
64+
false
65+
}
66+
6067
/// The number of fields for this constructor.
6168
fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;
6269

compiler/rustc_pattern_analysis/src/usefulness.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -994,7 +994,8 @@ impl<Cx: PatCx> PlaceInfo<Cx> {
994994
if !missing_ctors.is_empty() && !report_individual_missing_ctors {
995995
// Report `_` as missing.
996996
missing_ctors = vec![Constructor::Wildcard];
997-
} else if missing_ctors.iter().any(|c| c.is_non_exhaustive()) {
997+
} else if missing_ctors.iter().any(|c| c.is_non_exhaustive()) && !cx.exhaustive_witnesses()
998+
{
998999
// We need to report a `_` anyway, so listing other constructors would be redundant.
9991000
// `NonExhaustive` is displayed as `_` just like `Wildcard`, but it will be picked
10001001
// up by diagnostics to add a note about why `_` is required here.
@@ -1747,7 +1748,9 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>(
17471748
// `ctor` is *irrelevant* if there's another constructor in `split_ctors` that matches
17481749
// strictly fewer rows. In that case we can sometimes skip it. See the top of the file for
17491750
// details.
1750-
let ctor_is_relevant = matches!(ctor, Constructor::Missing) || missing_ctors.is_empty();
1751+
let ctor_is_relevant = matches!(ctor, Constructor::Missing)
1752+
|| missing_ctors.is_empty()
1753+
|| mcx.tycx.exhaustive_witnesses();
17511754
let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant)?;
17521755
let mut witnesses = ensure_sufficient_stack(|| {
17531756
compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix)

compiler/rustc_pattern_analysis/tests/common/mod.rs

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![allow(dead_code, unreachable_pub)]
12
use rustc_pattern_analysis::constructor::{
23
Constructor, ConstructorSet, IntRange, MaybeInfiniteInt, RangeEnd, VariantVisibility,
34
};
@@ -22,8 +23,10 @@ fn init_tracing() {
2223
.try_init();
2324
}
2425

26+
pub(super) const UNIT: Ty = Ty::Tuple(&[]);
27+
pub(super) const NEVER: Ty = Ty::Enum(&[]);
28+
2529
/// A simple set of types.
26-
#[allow(dead_code)]
2730
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2831
pub(super) enum Ty {
2932
/// Booleans
@@ -38,6 +41,8 @@ pub(super) enum Ty {
3841
BigStruct { arity: usize, ty: &'static Ty },
3942
/// A enum with `arity` variants of type `ty`.
4043
BigEnum { arity: usize, ty: &'static Ty },
44+
/// Like `Enum` but non-exhaustive.
45+
NonExhaustiveEnum(&'static [Ty]),
4146
}
4247

4348
/// The important logic.
@@ -47,7 +52,7 @@ impl Ty {
4752
match (ctor, *self) {
4853
(Struct, Ty::Tuple(tys)) => tys.iter().copied().collect(),
4954
(Struct, Ty::BigStruct { arity, ty }) => (0..arity).map(|_| *ty).collect(),
50-
(Variant(i), Ty::Enum(tys)) => vec![tys[*i]],
55+
(Variant(i), Ty::Enum(tys) | Ty::NonExhaustiveEnum(tys)) => vec![tys[*i]],
5156
(Variant(_), Ty::BigEnum { ty, .. }) => vec![*ty],
5257
(Bool(..) | IntRange(..) | NonExhaustive | Missing | Wildcard, _) => vec![],
5358
_ => panic!("Unexpected ctor {ctor:?} for type {self:?}"),
@@ -61,6 +66,7 @@ impl Ty {
6166
Ty::Enum(tys) => tys.iter().all(|ty| ty.is_empty()),
6267
Ty::BigStruct { arity, ty } => arity != 0 && ty.is_empty(),
6368
Ty::BigEnum { arity, ty } => arity == 0 || ty.is_empty(),
69+
Ty::NonExhaustiveEnum(..) => false,
6470
}
6571
}
6672

@@ -90,6 +96,19 @@ impl Ty {
9096
.collect(),
9197
non_exhaustive: false,
9298
},
99+
Ty::NonExhaustiveEnum(tys) => ConstructorSet::Variants {
100+
variants: tys
101+
.iter()
102+
.map(|ty| {
103+
if ty.is_empty() {
104+
VariantVisibility::Empty
105+
} else {
106+
VariantVisibility::Visible
107+
}
108+
})
109+
.collect(),
110+
non_exhaustive: true,
111+
},
93112
Ty::BigEnum { arity: 0, .. } => ConstructorSet::NoConstructors,
94113
Ty::BigEnum { arity, ty } => {
95114
let vis = if ty.is_empty() {
@@ -113,7 +132,9 @@ impl Ty {
113132
match (*self, ctor) {
114133
(Ty::Tuple(..), _) => Ok(()),
115134
(Ty::BigStruct { .. }, _) => write!(f, "BigStruct"),
116-
(Ty::Enum(..), Constructor::Variant(i)) => write!(f, "Enum::Variant{i}"),
135+
(Ty::Enum(..) | Ty::NonExhaustiveEnum(..), Constructor::Variant(i)) => {
136+
write!(f, "Enum::Variant{i}")
137+
}
117138
(Ty::BigEnum { .. }, Constructor::Variant(i)) => write!(f, "BigEnum::Variant{i}"),
118139
_ => write!(f, "{:?}::{:?}", self, ctor),
119140
}
@@ -126,10 +147,11 @@ pub(super) fn compute_match_usefulness<'p>(
126147
ty: Ty,
127148
scrut_validity: PlaceValidity,
128149
complexity_limit: usize,
150+
exhaustive_witnesses: bool,
129151
) -> Result<UsefulnessReport<'p, Cx>, ()> {
130152
init_tracing();
131153
rustc_pattern_analysis::usefulness::compute_match_usefulness(
132-
&Cx,
154+
&Cx { exhaustive_witnesses },
133155
arms,
134156
ty,
135157
scrut_validity,
@@ -138,7 +160,9 @@ pub(super) fn compute_match_usefulness<'p>(
138160
}
139161

140162
#[derive(Debug)]
141-
pub(super) struct Cx;
163+
pub(super) struct Cx {
164+
exhaustive_witnesses: bool,
165+
}
142166

143167
/// The context for pattern analysis. Forwards anything interesting to `Ty` methods.
144168
impl PatCx for Cx {
@@ -153,6 +177,10 @@ impl PatCx for Cx {
153177
false
154178
}
155179

180+
fn exhaustive_witnesses(&self) -> bool {
181+
self.exhaustive_witnesses
182+
}
183+
156184
fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize {
157185
ty.sub_tys(ctor).len()
158186
}
@@ -219,16 +247,18 @@ macro_rules! pats {
219247
// Entrypoint
220248
// Parse `type; ..`
221249
($ty:expr; $($rest:tt)*) => {{
222-
#[allow(unused_imports)]
250+
#[allow(unused)]
223251
use rustc_pattern_analysis::{
224252
constructor::{Constructor, IntRange, MaybeInfiniteInt, RangeEnd},
225-
pat::DeconstructedPat,
253+
pat::{DeconstructedPat, IndexedPat},
226254
};
227255
let ty = $ty;
228256
// The heart of the macro is designed to push `IndexedPat`s into a `Vec`, so we work around
229257
// that.
258+
#[allow(unused)]
230259
let sub_tys = ::std::iter::repeat(&ty);
231-
let mut vec = Vec::new();
260+
#[allow(unused)]
261+
let mut vec: Vec<IndexedPat<_>> = Vec::new();
232262
pats!(@ctor(vec:vec, sub_tys:sub_tys, idx:0) $($rest)*);
233263
vec.into_iter().map(|ipat| ipat.pat).collect::<Vec<_>>()
234264
}};
@@ -263,6 +293,8 @@ macro_rules! pats {
263293
let ctor = Constructor::Wildcard;
264294
pats!(@pat($($args)*, ctor:ctor) $($rest)*)
265295
}};
296+
// Nothing
297+
(@ctor($($args:tt)*)) => {};
266298

267299
// Integers and int ranges
268300
(@ctor($($args:tt)*) $($start:literal)?..$end:literal $($rest:tt)*) => {{

compiler/rustc_pattern_analysis/tests/complexity.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ fn check(patterns: &[DeconstructedPat<Cx>], complexity_limit: usize) -> Result<(
1616
let ty = *patterns[0].ty();
1717
let arms: Vec<_> =
1818
patterns.iter().map(|pat| MatchArm { pat, has_guard: false, arm_data: () }).collect();
19-
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, complexity_limit)
19+
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, complexity_limit, false)
2020
.map(|_report| ())
2121
}
2222

compiler/rustc_pattern_analysis/tests/exhaustiveness.rs

Lines changed: 106 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,30 @@ use rustc_pattern_analysis::usefulness::PlaceValidity;
1111
mod common;
1212

1313
/// Analyze a match made of these patterns.
14-
fn check(patterns: Vec<DeconstructedPat<Cx>>) -> Vec<WitnessPat<Cx>> {
15-
let ty = *patterns[0].ty();
14+
fn run(
15+
ty: Ty,
16+
patterns: Vec<DeconstructedPat<Cx>>,
17+
exhaustive_witnesses: bool,
18+
) -> Vec<WitnessPat<Cx>> {
1619
let arms: Vec<_> =
1720
patterns.iter().map(|pat| MatchArm { pat, has_guard: false, arm_data: () }).collect();
18-
let report =
19-
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, usize::MAX)
20-
.unwrap();
21+
let report = compute_match_usefulness(
22+
arms.as_slice(),
23+
ty,
24+
PlaceValidity::ValidOnly,
25+
usize::MAX,
26+
exhaustive_witnesses,
27+
)
28+
.unwrap();
2129
report.non_exhaustiveness_witnesses
2230
}
2331

32+
/// Analyze a match made of these patterns. Panics if there are no patterns
33+
fn check(patterns: Vec<DeconstructedPat<Cx>>) -> Vec<WitnessPat<Cx>> {
34+
let ty = *patterns[0].ty();
35+
run(ty, patterns, true)
36+
}
37+
2438
#[track_caller]
2539
fn assert_exhaustive(patterns: Vec<DeconstructedPat<Cx>>) {
2640
let witnesses = check(patterns);
@@ -35,6 +49,26 @@ fn assert_non_exhaustive(patterns: Vec<DeconstructedPat<Cx>>) {
3549
assert!(!witnesses.is_empty())
3650
}
3751

52+
use WhichWitnesses::*;
53+
enum WhichWitnesses {
54+
AllOfThem,
55+
OnlySome,
56+
}
57+
58+
#[track_caller]
59+
/// We take the type as input to support empty matches.
60+
fn assert_witnesses(
61+
which: WhichWitnesses,
62+
ty: Ty,
63+
patterns: Vec<DeconstructedPat<Cx>>,
64+
expected: Vec<&str>,
65+
) {
66+
let exhaustive_wit = matches!(which, AllOfThem);
67+
let witnesses = run(ty, patterns, exhaustive_wit);
68+
let witnesses: Vec<_> = witnesses.iter().map(|w| format!("{w:?}")).collect();
69+
assert_eq!(witnesses, expected)
70+
}
71+
3872
#[test]
3973
fn test_int_ranges() {
4074
let ty = Ty::U8;
@@ -59,6 +93,8 @@ fn test_int_ranges() {
5993

6094
#[test]
6195
fn test_nested() {
96+
// enum E { A(bool), B(bool) }
97+
// ty = (E, E)
6298
let ty = Ty::BigStruct { arity: 2, ty: &Ty::BigEnum { arity: 2, ty: &Ty::Bool } };
6399
assert_non_exhaustive(pats!(ty;
64100
Struct(Variant.0, _),
@@ -78,10 +114,74 @@ fn test_nested() {
78114
));
79115
}
80116

117+
#[test]
118+
fn test_witnesses() {
119+
// TY = Option<bool>
120+
const TY: Ty = Ty::Enum(&[Ty::Bool, UNIT]);
121+
// ty = (Option<bool>, Option<bool>)
122+
let ty = Ty::Tuple(&[TY, TY]);
123+
assert_witnesses(AllOfThem, ty, vec![], vec!["(_, _)"]);
124+
assert_witnesses(
125+
OnlySome,
126+
ty,
127+
pats!(ty;
128+
(Variant.0(false), Variant.0(false)),
129+
),
130+
vec!["(Enum::Variant1(_), _)"],
131+
);
132+
assert_witnesses(
133+
AllOfThem,
134+
ty,
135+
pats!(ty;
136+
(Variant.0(false), Variant.0(false)),
137+
),
138+
vec![
139+
"(Enum::Variant0(false), Enum::Variant0(true))",
140+
"(Enum::Variant0(false), Enum::Variant1(_))",
141+
"(Enum::Variant0(true), _)",
142+
"(Enum::Variant1(_), _)",
143+
],
144+
);
145+
assert_witnesses(
146+
OnlySome,
147+
ty,
148+
pats!(ty;
149+
(_, Variant.0(false)),
150+
),
151+
vec!["(_, Enum::Variant1(_))"],
152+
);
153+
assert_witnesses(
154+
AllOfThem,
155+
ty,
156+
pats!(ty;
157+
(_, Variant.0(false)),
158+
),
159+
vec!["(_, Enum::Variant0(true))", "(_, Enum::Variant1(_))"],
160+
);
161+
162+
let ty = Ty::NonExhaustiveEnum(&[UNIT, UNIT, UNIT]);
163+
assert_witnesses(
164+
OnlySome,
165+
ty,
166+
pats!(ty;
167+
Variant.0,
168+
),
169+
vec!["_"],
170+
);
171+
assert_witnesses(
172+
AllOfThem,
173+
ty,
174+
pats!(ty;
175+
Variant.0,
176+
),
177+
vec!["Enum::Variant1(_)", "Enum::Variant2(_)", "_"],
178+
);
179+
}
180+
81181
#[test]
82182
fn test_empty() {
83183
// `TY = Result<bool, !>`
84-
const TY: Ty = Ty::Enum(&[Ty::Bool, Ty::Enum(&[])]);
184+
const TY: Ty = Ty::Enum(&[Ty::Bool, NEVER]);
85185
assert_exhaustive(pats!(TY;
86186
Variant.0,
87187
));

compiler/rustc_pattern_analysis/tests/intersection.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ fn check(patterns: Vec<DeconstructedPat<Cx>>) -> Vec<Vec<usize>> {
1616
let arms: Vec<_> =
1717
patterns.iter().map(|pat| MatchArm { pat, has_guard: false, arm_data: () }).collect();
1818
let report =
19-
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, usize::MAX)
19+
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, usize::MAX, false)
2020
.unwrap();
2121
report.arm_intersections.into_iter().map(|bitset| bitset.iter().collect()).collect()
2222
}

0 commit comments

Comments
 (0)