Skip to content

Commit 2327f2e

Browse files
committed
Only lint ranges that really overlap
1 parent b391c66 commit 2327f2e

File tree

6 files changed

+132
-111
lines changed

6 files changed

+132
-111
lines changed

compiler/rustc_pattern_analysis/src/lib.rs

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

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

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

compiler/rustc_pattern_analysis/src/lints.rs

+2-82
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
1-
use smallvec::SmallVec;
2-
3-
use rustc_data_structures::captures::Captures;
4-
use rustc_middle::ty::{self, Ty};
1+
use rustc_middle::ty::Ty;
52
use rustc_session::lint;
63
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
74

8-
use crate::constructor::MaybeInfiniteInt;
95
use crate::errors::{
106
self, NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Uncovered,
117
};
128
use crate::rustc::{
139
self, Constructor, DeconstructedPat, MatchArm, MatchCtxt, PlaceCtxt, RustcMatchCheckCtxt,
1410
SplitConstructorSet, WitnessPat,
1511
};
16-
use crate::usefulness::OverlappingRanges;
1712
use crate::TypeCx;
1813

1914
/// A column of patterns in the matrix, where a column is the intuitive notion of "subpatterns that
@@ -63,10 +58,6 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
6358
pcx.ctors_for_ty().split(pcx, column_ctors)
6459
}
6560

66-
fn iter(&self) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'_> {
67-
self.patterns.iter().copied()
68-
}
69-
7061
/// Does specialization: given a constructor, this takes the patterns from the column that match
7162
/// the constructor, and outputs their fields.
7263
/// This returns one column per field of the constructor. They usually all have the same length
@@ -211,81 +202,10 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
211202
}
212203
}
213204

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

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

14301513
// Transform witnesses for `spec_matrix` into witnesses for `matrix`.
@@ -1446,6 +1529,21 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
14461529
}
14471530
}
14481531
}
1532+
1533+
// Detect ranges that overlap on their endpoints.
1534+
if let Constructor::IntRange(overlap_range) = ctor {
1535+
if overlap_range.is_singleton()
1536+
&& spec_matrix.rows.len() >= 2
1537+
&& spec_matrix.rows.iter().any(|row| !row.intersects.is_empty())
1538+
{
1539+
collect_overlapping_range_endpoints(
1540+
overlap_range,
1541+
matrix,
1542+
&spec_matrix,
1543+
overlapping_range_endpoints,
1544+
);
1545+
}
1546+
}
14491547
}
14501548

14511549
// Record usefulness in the patterns.
@@ -1486,6 +1584,7 @@ pub struct UsefulnessReport<'p, Cx: TypeCx> {
14861584
/// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
14871585
/// exhaustiveness.
14881586
pub non_exhaustiveness_witnesses: Vec<WitnessPat<Cx>>,
1587+
pub overlapping_range_endpoints: Vec<OverlappingRanges<'p, Cx>>,
14891588
}
14901589

14911590
/// Computes whether a match is exhaustive and which of its arms are useful.
@@ -1496,8 +1595,14 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
14961595
scrut_ty: Cx::Ty,
14971596
scrut_validity: ValidityConstraint,
14981597
) -> UsefulnessReport<'p, Cx> {
1598+
let mut overlapping_range_endpoints = Vec::new();
14991599
let mut matrix = Matrix::new(cx.wildcard_arena, arms, scrut_ty, scrut_validity);
1500-
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix, true);
1600+
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(
1601+
cx,
1602+
&mut matrix,
1603+
&mut overlapping_range_endpoints,
1604+
true,
1605+
);
15011606

15021607
let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
15031608
let arm_usefulness: Vec<_> = arms
@@ -1514,5 +1619,5 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
15141619
(arm, usefulness)
15151620
})
15161621
.collect();
1517-
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
1622+
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses, overlapping_range_endpoints }
15181623
}
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)