Skip to content

Commit 7931ee6

Browse files
committed
Only lint ranges that really overlap
1 parent 8e104e2 commit 7931ee6

File tree

6 files changed

+131
-111
lines changed

6 files changed

+131
-111
lines changed

compiler/rustc_pattern_analysis/src/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,9 @@ pub fn analyze_match<'p, 'tcx>(
121121
let pat_column = PatternColumn::new(arms);
122122

123123
// Lint ranges that overlap on their endpoints, which is likely a mistake.
124-
lint_overlapping_range_endpoints(cx, &pat_column);
124+
if !report.overlapping_range_endpoints.is_empty() {
125+
lint_overlapping_range_endpoints(cx, &report.overlapping_range_endpoints);
126+
}
125127

126128
// Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
127129
// `if let`s. Only run if the match is exhaustive otherwise the error is redundant.

compiler/rustc_pattern_analysis/src/lints.rs

+1-82
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
1-
use smallvec::SmallVec;
2-
3-
use rustc_data_structures::captures::Captures;
4-
use rustc_middle::ty;
51
use rustc_session::lint;
62
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
73

8-
use crate::constructor::MaybeInfiniteInt;
94
use crate::errors::{
105
self, NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Uncovered,
116
};
127
use crate::rustc::{
138
self, Constructor, DeconstructedPat, MatchArm, MatchCtxt, PlaceCtxt, RevealedTy,
149
RustcMatchCheckCtxt, SplitConstructorSet, WitnessPat,
1510
};
16-
use crate::usefulness::OverlappingRanges;
1711

1812
/// A column of patterns in the matrix, where a column is the intuitive notion of "subpatterns that
1913
/// inspect the same subvalue/place".
@@ -56,10 +50,6 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
5650
pcx.ctors_for_ty().split(pcx, column_ctors)
5751
}
5852

59-
fn iter(&self) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'_> {
60-
self.patterns.iter().copied()
61-
}
62-
6353
/// Does specialization: given a constructor, this takes the patterns from the column that match
6454
/// the constructor, and outputs their fields.
6555
/// This returns one column per field of the constructor. They usually all have the same length
@@ -205,81 +195,10 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
205195
}
206196
}
207197

208-
/// Traverse the patterns to warn the user about ranges that overlap on their endpoints.
209-
#[instrument(level = "debug", skip(cx))]
210-
pub(crate) fn collect_overlapping_range_endpoints<'a, 'p, 'tcx>(
211-
cx: MatchCtxt<'a, 'p, 'tcx>,
212-
column: &PatternColumn<'p, 'tcx>,
213-
overlapping_range_endpoints: &mut Vec<rustc::OverlappingRanges<'p, 'tcx>>,
214-
) {
215-
let Some(ty) = column.head_ty() else {
216-
return;
217-
};
218-
let pcx = &PlaceCtxt::new_dummy(cx, ty);
219-
220-
let set = column.analyze_ctors(pcx);
221-
222-
if matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_)) {
223-
// If two ranges overlapped, the split set will contain their intersection as a singleton.
224-
let split_int_ranges = set.present.iter().filter_map(|c| c.as_int_range());
225-
for overlap_range in split_int_ranges.clone() {
226-
if overlap_range.is_singleton() {
227-
let overlap: MaybeInfiniteInt = overlap_range.lo;
228-
// Ranges that look like `lo..=overlap`.
229-
let mut prefixes: SmallVec<[_; 1]> = Default::default();
230-
// Ranges that look like `overlap..=hi`.
231-
let mut suffixes: SmallVec<[_; 1]> = Default::default();
232-
// Iterate on patterns that contained `overlap`.
233-
for pat in column.iter() {
234-
let Constructor::IntRange(this_range) = pat.ctor() else { continue };
235-
if this_range.is_singleton() {
236-
// Don't lint when one of the ranges is a singleton.
237-
continue;
238-
}
239-
if this_range.lo == overlap {
240-
// `this_range` looks like `overlap..=this_range.hi`; it overlaps with any
241-
// ranges that look like `lo..=overlap`.
242-
if !prefixes.is_empty() {
243-
overlapping_range_endpoints.push(OverlappingRanges {
244-
pat,
245-
overlaps_on: *overlap_range,
246-
overlaps_with: prefixes.as_slice().to_vec(),
247-
});
248-
}
249-
suffixes.push(pat)
250-
} else if this_range.hi == overlap.plus_one() {
251-
// `this_range` looks like `this_range.lo..=overlap`; it overlaps with any
252-
// ranges that look like `overlap..=hi`.
253-
if !suffixes.is_empty() {
254-
overlapping_range_endpoints.push(OverlappingRanges {
255-
pat,
256-
overlaps_on: *overlap_range,
257-
overlaps_with: suffixes.as_slice().to_vec(),
258-
});
259-
}
260-
prefixes.push(pat)
261-
}
262-
}
263-
}
264-
}
265-
} else {
266-
// Recurse into the fields.
267-
for ctor in set.present {
268-
for col in column.specialize(pcx, &ctor) {
269-
collect_overlapping_range_endpoints(cx, &col, overlapping_range_endpoints);
270-
}
271-
}
272-
}
273-
}
274-
275-
#[instrument(level = "debug", skip(cx))]
276198
pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
277199
cx: MatchCtxt<'a, 'p, 'tcx>,
278-
column: &PatternColumn<'p, 'tcx>,
200+
overlapping_range_endpoints: &[rustc::OverlappingRanges<'p, 'tcx>],
279201
) {
280-
let mut overlapping_range_endpoints = Vec::new();
281-
collect_overlapping_range_endpoints(cx, column, &mut overlapping_range_endpoints);
282-
283202
let rcx = cx.tycx;
284203
for overlap in overlapping_range_endpoints {
285204
let overlap_as_pat = rcx.hoist_pat_range(&overlap.overlaps_on, overlap.pat.ty());

compiler/rustc_pattern_analysis/src/usefulness.rs

+108-3
Original file line numberDiff line numberDiff line change
@@ -1333,6 +1333,83 @@ impl<Cx: TypeCx> WitnessMatrix<Cx> {
13331333
}
13341334
}
13351335

1336+
/// Collect ranges that overlap like `lo..=overlap`/`overlap..=hi`. Must be called during
1337+
/// exhaustiveness checking, if we find a singleton range after constructor splitting. This reuses
1338+
/// row intersection information to only detect ranges that truly overlap.
1339+
///
1340+
/// If two ranges overlapped, the split set will contain their intersection as a singleton.
1341+
/// Specialization will then select rows that match the overlap, and exhaustiveness will compute
1342+
/// which rows have an intersection that includes the overlap. That gives us all the info we need to
1343+
/// compute overlapping ranges without false positives.
1344+
///
1345+
/// We can however get false negatives because exhaustiveness does not explore all cases. See the
1346+
/// section on relevancy at the top of the file.
1347+
fn collect_overlapping_range_endpoints<'p, Cx: TypeCx>(
1348+
overlap_range: IntRange,
1349+
matrix: &Matrix<'p, Cx>,
1350+
specialized_matrix: &Matrix<'p, Cx>,
1351+
overlapping_range_endpoints: &mut Vec<OverlappingRanges<'p, Cx>>,
1352+
) {
1353+
let overlap = overlap_range.lo;
1354+
// Ranges that look like `lo..=overlap`.
1355+
let mut prefixes: SmallVec<[_; 1]> = Default::default();
1356+
// Ranges that look like `overlap..=hi`.
1357+
let mut suffixes: SmallVec<[_; 1]> = Default::default();
1358+
// Iterate on patterns that contained `overlap`. We iterate on `specialized_matrix` which
1359+
// contains only rows that matched the current `ctor` as well as accurate intersection
1360+
// information. It doesn't contain the column that contains the range; that can be found in
1361+
// `matrix`.
1362+
for (child_row_id, child_row) in specialized_matrix.rows().enumerate() {
1363+
let pat = matrix.rows[child_row.parent_row].head();
1364+
let Constructor::IntRange(this_range) = pat.ctor() else { continue };
1365+
// Don't lint when one of the ranges is a singleton.
1366+
if this_range.is_singleton() {
1367+
continue;
1368+
}
1369+
if this_range.lo == overlap {
1370+
// `this_range` looks like `overlap..=this_range.hi`; it overlaps with any
1371+
// ranges that look like `lo..=overlap`.
1372+
if !prefixes.is_empty() {
1373+
let overlaps_with: Vec<_> = prefixes
1374+
.iter()
1375+
.filter(|&&(other_child_row_id, _)| {
1376+
child_row.intersects.contains(other_child_row_id)
1377+
})
1378+
.map(|&(_, pat)| pat)
1379+
.collect();
1380+
if !overlaps_with.is_empty() {
1381+
overlapping_range_endpoints.push(OverlappingRanges {
1382+
pat,
1383+
overlaps_on: overlap_range,
1384+
overlaps_with,
1385+
});
1386+
}
1387+
}
1388+
suffixes.push((child_row_id, pat))
1389+
} else if this_range.hi == overlap.plus_one() {
1390+
// `this_range` looks like `this_range.lo..=overlap`; it overlaps with any
1391+
// ranges that look like `overlap..=hi`.
1392+
if !suffixes.is_empty() {
1393+
let overlaps_with: Vec<_> = suffixes
1394+
.iter()
1395+
.filter(|&&(other_child_row_id, _)| {
1396+
child_row.intersects.contains(other_child_row_id)
1397+
})
1398+
.map(|&(_, pat)| pat)
1399+
.collect();
1400+
if !overlaps_with.is_empty() {
1401+
overlapping_range_endpoints.push(OverlappingRanges {
1402+
pat,
1403+
overlaps_on: overlap_range,
1404+
overlaps_with,
1405+
});
1406+
}
1407+
}
1408+
prefixes.push((child_row_id, pat))
1409+
}
1410+
}
1411+
}
1412+
13361413
/// The core of the algorithm.
13371414
///
13381415
/// This recursively computes witnesses of the non-exhaustiveness of `matrix` (if any). Also tracks
@@ -1351,6 +1428,7 @@ impl<Cx: TypeCx> WitnessMatrix<Cx> {
13511428
fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
13521429
mcx: MatchCtxt<'a, 'p, Cx>,
13531430
matrix: &mut Matrix<'p, Cx>,
1431+
overlapping_range_endpoints: &mut Vec<OverlappingRanges<'p, Cx>>,
13541432
is_top_level: bool,
13551433
) -> WitnessMatrix<Cx> {
13561434
debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
@@ -1430,7 +1508,12 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14301508
let ctor_is_relevant = matches!(ctor, Constructor::Missing) || missing_ctors.is_empty();
14311509
let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant);
14321510
let mut witnesses = ensure_sufficient_stack(|| {
1433-
compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix, false)
1511+
compute_exhaustiveness_and_usefulness(
1512+
mcx,
1513+
&mut spec_matrix,
1514+
overlapping_range_endpoints,
1515+
false,
1516+
)
14341517
});
14351518

14361519
// Transform witnesses for `spec_matrix` into witnesses for `matrix`.
@@ -1452,6 +1535,21 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14521535
}
14531536
}
14541537
}
1538+
1539+
// Detect ranges that overlap on their endpoints.
1540+
if let Constructor::IntRange(overlap_range) = ctor {
1541+
if overlap_range.is_singleton()
1542+
&& spec_matrix.rows.len() >= 2
1543+
&& spec_matrix.rows.iter().any(|row| !row.intersects.is_empty())
1544+
{
1545+
collect_overlapping_range_endpoints(
1546+
overlap_range,
1547+
matrix,
1548+
&spec_matrix,
1549+
overlapping_range_endpoints,
1550+
);
1551+
}
1552+
}
14551553
}
14561554

14571555
// Record usefulness in the patterns.
@@ -1492,6 +1590,7 @@ pub struct UsefulnessReport<'p, Cx: TypeCx> {
14921590
/// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
14931591
/// exhaustiveness.
14941592
pub non_exhaustiveness_witnesses: Vec<WitnessPat<Cx>>,
1593+
pub overlapping_range_endpoints: Vec<OverlappingRanges<'p, Cx>>,
14951594
}
14961595

14971596
/// Computes whether a match is exhaustive and which of its arms are useful.
@@ -1502,8 +1601,14 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
15021601
scrut_ty: Cx::Ty,
15031602
scrut_validity: ValidityConstraint,
15041603
) -> UsefulnessReport<'p, Cx> {
1604+
let mut overlapping_range_endpoints = Vec::new();
15051605
let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
1506-
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix, true);
1606+
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(
1607+
cx,
1608+
&mut matrix,
1609+
&mut overlapping_range_endpoints,
1610+
true,
1611+
);
15071612

15081613
let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
15091614
let arm_usefulness: Vec<_> = arms
@@ -1520,5 +1625,5 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
15201625
(arm, usefulness)
15211626
})
15221627
.collect();
1523-
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
1628+
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses, overlapping_range_endpoints }
15241629
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// check-pass
2+
fn main() {
3+
match (0i8, 0i8) {
4+
(0, _) => {}
5+
(..=-1, ..=0) => {}
6+
(1.., 0..) => {}
7+
(1.., ..=-1) | (..=-1, 1..) => {}
8+
}
9+
}

tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,25 @@ fn main() {
4444
match (0u8, true) {
4545
(0..=10, true) => {}
4646
(10..20, true) => {} //~ ERROR multiple patterns overlap on their endpoints
47-
(10..20, false) => {} //~ ERROR multiple patterns overlap on their endpoints
47+
(10..20, false) => {}
4848
_ => {}
4949
}
5050
match (true, 0u8) {
5151
(true, 0..=10) => {}
5252
(true, 10..20) => {} //~ ERROR multiple patterns overlap on their endpoints
53-
(false, 10..20) => {} //~ ERROR multiple patterns overlap on their endpoints
53+
(false, 10..20) => {}
5454
_ => {}
5555
}
5656
match Some(0u8) {
5757
Some(0..=10) => {}
5858
Some(10..20) => {} //~ ERROR multiple patterns overlap on their endpoints
5959
_ => {}
6060
}
61+
62+
// The lint has false negatives when we skip some cases because of relevancy.
63+
match (true, true, 0u8) {
64+
(true, _, 0..=10) => {}
65+
(_, true, 10..20) => {}
66+
_ => {}
67+
}
6168
}

tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.stderr

+1-23
Original file line numberDiff line numberDiff line change
@@ -84,17 +84,6 @@ LL | (10..20, true) => {}
8484
|
8585
= note: you likely meant to write mutually exclusive ranges
8686

87-
error: multiple patterns overlap on their endpoints
88-
--> $DIR/overlapping_range_endpoints.rs:47:10
89-
|
90-
LL | (0..=10, true) => {}
91-
| ------ this range overlaps on `10_u8`...
92-
LL | (10..20, true) => {}
93-
LL | (10..20, false) => {}
94-
| ^^^^^^ ... with this range
95-
|
96-
= note: you likely meant to write mutually exclusive ranges
97-
9887
error: multiple patterns overlap on their endpoints
9988
--> $DIR/overlapping_range_endpoints.rs:52:16
10089
|
@@ -105,17 +94,6 @@ LL | (true, 10..20) => {}
10594
|
10695
= note: you likely meant to write mutually exclusive ranges
10796

108-
error: multiple patterns overlap on their endpoints
109-
--> $DIR/overlapping_range_endpoints.rs:53:17
110-
|
111-
LL | (true, 0..=10) => {}
112-
| ------ this range overlaps on `10_u8`...
113-
LL | (true, 10..20) => {}
114-
LL | (false, 10..20) => {}
115-
| ^^^^^^ ... with this range
116-
|
117-
= note: you likely meant to write mutually exclusive ranges
118-
11997
error: multiple patterns overlap on their endpoints
12098
--> $DIR/overlapping_range_endpoints.rs:58:14
12199
|
@@ -126,5 +104,5 @@ LL | Some(10..20) => {}
126104
|
127105
= note: you likely meant to write mutually exclusive ranges
128106

129-
error: aborting due to 12 previous errors
107+
error: aborting due to 10 previous errors
130108

0 commit comments

Comments
 (0)