1 //! [`super::usefulness`] explains most of what is happening in this file. As explained there,
2 //! values and patterns are made from constructors applied to fields. This file defines a
3 //! `Constructor` enum, a `Fields` struct, and various operations to manipulate them and convert
4 //! them from/to patterns.
5 //!
6 //! There's one idea that is not detailed in [`super::usefulness`] because the details are not
7 //! needed there: _constructor splitting_.
8 //!
9 //! # Constructor splitting
10 //!
11 //! The idea is as follows: given a constructor `c` and a matrix, we want to specialize in turn
12 //! with all the value constructors that are covered by `c`, and compute usefulness for each.
13 //! Instead of listing all those constructors (which is intractable), we group those value
14 //! constructors together as much as possible. Example:
15 //!
16 //! ```compile_fail,E0004
17 //! match (0, false) {
18 //! (0 ..=100, true) => {} // `p_1`
19 //! (50..=150, false) => {} // `p_2`
20 //! (0 ..=200, _) => {} // `q`
21 //! }
22 //! ```
23 //!
24 //! The naive approach would try all numbers in the range `0..=200`. But we can be a lot more
25 //! clever: `0` and `1` for example will match the exact same rows, and return equivalent
26 //! witnesses. In fact all of `0..50` would. We can thus restrict our exploration to 4
27 //! constructors: `0..50`, `50..=100`, `101..=150` and `151..=200`. That is enough and infinitely
28 //! more tractable.
29 //!
30 //! We capture this idea in a function `split(p_1 ... p_n, c)` which returns a list of constructors
31 //! `c'` covered by `c`. Given such a `c'`, we require that all value ctors `c''` covered by `c'`
32 //! return an equivalent set of witnesses after specializing and computing usefulness.
33 //! In the example above, witnesses for specializing by `c''` covered by `0..50` will only differ
34 //! in their first element.
35 //!
36 //! We usually also ask that the `c'` together cover all of the original `c`. However we allow
37 //! skipping some constructors as long as it doesn't change whether the resulting list of witnesses
38 //! is empty of not. We use this in the wildcard `_` case.
39 //!
40 //! Splitting is implemented in the [`Constructor::split`] function. We don't do splitting for
41 //! or-patterns; instead we just try the alternatives one-by-one. For details on splitting
42 //! wildcards, see [`SplitWildcard`]; for integer ranges, see [`SplitIntRange`]; for slices, see
43 //! [`SplitVarLenSlice`].
44
45 use std::cell::Cell;
46 use std::cmp::{self, max, min, Ordering};
47 use std::fmt;
48 use std::iter::once;
49 use std::ops::RangeInclusive;
50
51 use smallvec::{smallvec, SmallVec};
52
53 use rustc_data_structures::captures::Captures;
54 use rustc_hir::{HirId, RangeEnd};
55 use rustc_index::Idx;
56 use rustc_middle::middle::stability::EvalResult;
57 use rustc_middle::mir;
58 use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange};
59 use rustc_middle::ty::layout::IntegerExt;
60 use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
61 use rustc_session::lint;
62 use rustc_span::{Span, DUMMY_SP};
63 use rustc_target::abi::{FieldIdx, Integer, Size, VariantIdx, FIRST_VARIANT};
64
65 use self::Constructor::*;
66 use self::SliceKind::*;
67
68 use super::compare_const_vals;
69 use super::usefulness::{MatchCheckCtxt, PatCtxt};
70 use crate::errors::{Overlap, OverlappingRangeEndpoints};
71
72 /// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.
expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>>73 fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> {
74 fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) {
75 if let PatKind::Or { pats } = &pat.kind {
76 for pat in pats.iter() {
77 expand(&pat, vec);
78 }
79 } else {
80 vec.push(pat)
81 }
82 }
83
84 let mut pats = Vec::new();
85 expand(pat, &mut pats);
86 pats
87 }
88
89 /// An inclusive interval, used for precise integer exhaustiveness checking.
90 /// `IntRange`s always store a contiguous range. This means that values are
91 /// encoded such that `0` encodes the minimum value for the integer,
92 /// regardless of the signedness.
93 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
94 /// This makes comparisons and arithmetic on interval endpoints much more
95 /// straightforward. See `signed_bias` for details.
96 ///
97 /// `IntRange` is never used to encode an empty range or a "range" that wraps
98 /// around the (offset) space: i.e., `range.lo <= range.hi`.
99 #[derive(Clone, PartialEq, Eq)]
100 pub(crate) struct IntRange {
101 range: RangeInclusive<u128>,
102 /// Keeps the bias used for encoding the range. It depends on the type of the range and
103 /// possibly the pointer size of the current architecture. The algorithm ensures we never
104 /// compare `IntRange`s with different types/architectures.
105 bias: u128,
106 }
107
108 impl IntRange {
109 #[inline]
is_integral(ty: Ty<'_>) -> bool110 fn is_integral(ty: Ty<'_>) -> bool {
111 matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool)
112 }
113
is_singleton(&self) -> bool114 fn is_singleton(&self) -> bool {
115 self.range.start() == self.range.end()
116 }
117
boundaries(&self) -> (u128, u128)118 fn boundaries(&self) -> (u128, u128) {
119 (*self.range.start(), *self.range.end())
120 }
121
122 #[inline]
integral_size_and_signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Size, u128)>123 fn integral_size_and_signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Size, u128)> {
124 match *ty.kind() {
125 ty::Bool => Some((Size::from_bytes(1), 0)),
126 ty::Char => Some((Size::from_bytes(4), 0)),
127 ty::Int(ity) => {
128 let size = Integer::from_int_ty(&tcx, ity).size();
129 Some((size, 1u128 << (size.bits() as u128 - 1)))
130 }
131 ty::Uint(uty) => Some((Integer::from_uint_ty(&tcx, uty).size(), 0)),
132 _ => None,
133 }
134 }
135
136 #[inline]
from_constant<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, value: mir::ConstantKind<'tcx>, ) -> Option<IntRange>137 fn from_constant<'tcx>(
138 tcx: TyCtxt<'tcx>,
139 param_env: ty::ParamEnv<'tcx>,
140 value: mir::ConstantKind<'tcx>,
141 ) -> Option<IntRange> {
142 let ty = value.ty();
143 let (target_size, bias) = Self::integral_size_and_signed_bias(tcx, ty)?;
144 let val = match value {
145 mir::ConstantKind::Ty(c) if let ty::ConstKind::Value(valtree) = c.kind() => {
146 valtree.unwrap_leaf().to_bits(target_size).ok()
147 },
148 // This is a more general form of the previous case.
149 _ => value.try_eval_bits(tcx, param_env, ty),
150 }?;
151
152 let val = val ^ bias;
153 Some(IntRange { range: val..=val, bias })
154 }
155
156 #[inline]
from_range<'tcx>( tcx: TyCtxt<'tcx>, lo: u128, hi: u128, ty: Ty<'tcx>, end: &RangeEnd, ) -> Option<IntRange>157 fn from_range<'tcx>(
158 tcx: TyCtxt<'tcx>,
159 lo: u128,
160 hi: u128,
161 ty: Ty<'tcx>,
162 end: &RangeEnd,
163 ) -> Option<IntRange> {
164 Self::is_integral(ty).then(|| {
165 // Perform a shift if the underlying types are signed,
166 // which makes the interval arithmetic simpler.
167 let bias = IntRange::signed_bias(tcx, ty);
168 let (lo, hi) = (lo ^ bias, hi ^ bias);
169 let offset = (*end == RangeEnd::Excluded) as u128;
170 if lo > hi || (lo == hi && *end == RangeEnd::Excluded) {
171 // This should have been caught earlier by E0030.
172 bug!("malformed range pattern: {}..={}", lo, (hi - offset));
173 }
174 IntRange { range: lo..=(hi - offset), bias }
175 })
176 }
177
178 // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> u128179 fn signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> u128 {
180 match *ty.kind() {
181 ty::Int(ity) => {
182 let bits = Integer::from_int_ty(&tcx, ity).size().bits() as u128;
183 1u128 << (bits - 1)
184 }
185 _ => 0,
186 }
187 }
188
is_subrange(&self, other: &Self) -> bool189 fn is_subrange(&self, other: &Self) -> bool {
190 other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
191 }
192
intersection(&self, other: &Self) -> Option<Self>193 fn intersection(&self, other: &Self) -> Option<Self> {
194 let (lo, hi) = self.boundaries();
195 let (other_lo, other_hi) = other.boundaries();
196 if lo <= other_hi && other_lo <= hi {
197 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), bias: self.bias })
198 } else {
199 None
200 }
201 }
202
suspicious_intersection(&self, other: &Self) -> bool203 fn suspicious_intersection(&self, other: &Self) -> bool {
204 // `false` in the following cases:
205 // 1 ---- // 1 ---------- // 1 ---- // 1 ----
206 // 2 ---------- // 2 ---- // 2 ---- // 2 ----
207 //
208 // The following are currently `false`, but could be `true` in the future (#64007):
209 // 1 --------- // 1 ---------
210 // 2 ---------- // 2 ----------
211 //
212 // `true` in the following cases:
213 // 1 ------- // 1 -------
214 // 2 -------- // 2 -------
215 let (lo, hi) = self.boundaries();
216 let (other_lo, other_hi) = other.boundaries();
217 (lo == other_hi || hi == other_lo) && !self.is_singleton() && !other.is_singleton()
218 }
219
220 /// Only used for displaying the range properly.
to_pat<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Pat<'tcx>221 fn to_pat<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Pat<'tcx> {
222 let (lo, hi) = self.boundaries();
223
224 let bias = self.bias;
225 let (lo, hi) = (lo ^ bias, hi ^ bias);
226
227 let env = ty::ParamEnv::empty().and(ty);
228 let lo_const = mir::ConstantKind::from_bits(tcx, lo, env);
229 let hi_const = mir::ConstantKind::from_bits(tcx, hi, env);
230
231 let kind = if lo == hi {
232 PatKind::Constant { value: lo_const }
233 } else {
234 PatKind::Range(Box::new(PatRange {
235 lo: lo_const,
236 hi: hi_const,
237 end: RangeEnd::Included,
238 }))
239 };
240
241 Pat { ty, span: DUMMY_SP, kind }
242 }
243
244 /// Lint on likely incorrect range patterns (#63987)
lint_overlapping_range_endpoints<'a, 'p: 'a, 'tcx: 'a>( &self, pcx: &PatCtxt<'_, 'p, 'tcx>, pats: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>, column_count: usize, lint_root: HirId, )245 pub(super) fn lint_overlapping_range_endpoints<'a, 'p: 'a, 'tcx: 'a>(
246 &self,
247 pcx: &PatCtxt<'_, 'p, 'tcx>,
248 pats: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
249 column_count: usize,
250 lint_root: HirId,
251 ) {
252 if self.is_singleton() {
253 return;
254 }
255
256 if column_count != 1 {
257 // FIXME: for now, only check for overlapping ranges on simple range
258 // patterns. Otherwise with the current logic the following is detected
259 // as overlapping:
260 // ```
261 // match (0u8, true) {
262 // (0 ..= 125, false) => {}
263 // (125 ..= 255, true) => {}
264 // _ => {}
265 // }
266 // ```
267 return;
268 }
269
270 let overlap: Vec<_> = pats
271 .filter_map(|pat| Some((pat.ctor().as_int_range()?, pat.span())))
272 .filter(|(range, _)| self.suspicious_intersection(range))
273 .map(|(range, span)| Overlap {
274 range: self.intersection(&range).unwrap().to_pat(pcx.cx.tcx, pcx.ty),
275 span,
276 })
277 .collect();
278
279 if !overlap.is_empty() {
280 pcx.cx.tcx.emit_spanned_lint(
281 lint::builtin::OVERLAPPING_RANGE_ENDPOINTS,
282 lint_root,
283 pcx.span,
284 OverlappingRangeEndpoints { overlap, range: pcx.span },
285 );
286 }
287 }
288
289 /// See `Constructor::is_covered_by`
is_covered_by(&self, other: &Self) -> bool290 fn is_covered_by(&self, other: &Self) -> bool {
291 if self.intersection(other).is_some() {
292 // Constructor splitting should ensure that all intersections we encounter are actually
293 // inclusions.
294 assert!(self.is_subrange(other));
295 true
296 } else {
297 false
298 }
299 }
300 }
301
302 /// Note: this is often not what we want: e.g. `false` is converted into the range `0..=0` and
303 /// would be displayed as such. To render properly, convert to a pattern first.
304 impl fmt::Debug for IntRange {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 let (lo, hi) = self.boundaries();
307 let bias = self.bias;
308 let (lo, hi) = (lo ^ bias, hi ^ bias);
309 write!(f, "{}", lo)?;
310 write!(f, "{}", RangeEnd::Included)?;
311 write!(f, "{}", hi)
312 }
313 }
314
315 /// Represents a border between 2 integers. Because the intervals spanning borders must be able to
316 /// cover every integer, we need to be able to represent 2^128 + 1 such borders.
317 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
318 enum IntBorder {
319 JustBefore(u128),
320 AfterMax,
321 }
322
323 /// A range of integers that is partitioned into disjoint subranges. This does constructor
324 /// splitting for integer ranges as explained at the top of the file.
325 ///
326 /// This is fed multiple ranges, and returns an output that covers the input, but is split so that
327 /// the only intersections between an output range and a seen range are inclusions. No output range
328 /// straddles the boundary of one of the inputs.
329 ///
330 /// The following input:
331 /// ```text
332 /// |-------------------------| // `self`
333 /// |------| |----------| |----|
334 /// |-------| |-------|
335 /// ```
336 /// would be iterated over as follows:
337 /// ```text
338 /// ||---|--||-|---|---|---|--|
339 /// ```
340 #[derive(Debug, Clone)]
341 struct SplitIntRange {
342 /// The range we are splitting
343 range: IntRange,
344 /// The borders of ranges we have seen. They are all contained within `range`. This is kept
345 /// sorted.
346 borders: Vec<IntBorder>,
347 }
348
349 impl SplitIntRange {
new(range: IntRange) -> Self350 fn new(range: IntRange) -> Self {
351 SplitIntRange { range, borders: Vec::new() }
352 }
353
354 /// Internal use
to_borders(r: IntRange) -> [IntBorder; 2]355 fn to_borders(r: IntRange) -> [IntBorder; 2] {
356 use IntBorder::*;
357 let (lo, hi) = r.boundaries();
358 let lo = JustBefore(lo);
359 let hi = match hi.checked_add(1) {
360 Some(m) => JustBefore(m),
361 None => AfterMax,
362 };
363 [lo, hi]
364 }
365
366 /// Add ranges relative to which we split.
split(&mut self, ranges: impl Iterator<Item = IntRange>)367 fn split(&mut self, ranges: impl Iterator<Item = IntRange>) {
368 let this_range = &self.range;
369 let included_ranges = ranges.filter_map(|r| this_range.intersection(&r));
370 let included_borders = included_ranges.flat_map(|r| {
371 let borders = Self::to_borders(r);
372 once(borders[0]).chain(once(borders[1]))
373 });
374 self.borders.extend(included_borders);
375 self.borders.sort_unstable();
376 }
377
378 /// Iterate over the contained ranges.
iter(&self) -> impl Iterator<Item = IntRange> + Captures<'_>379 fn iter(&self) -> impl Iterator<Item = IntRange> + Captures<'_> {
380 use IntBorder::*;
381
382 let self_range = Self::to_borders(self.range.clone());
383 // Start with the start of the range.
384 let mut prev_border = self_range[0];
385 self.borders
386 .iter()
387 .copied()
388 // End with the end of the range.
389 .chain(once(self_range[1]))
390 // List pairs of adjacent borders.
391 .map(move |border| {
392 let ret = (prev_border, border);
393 prev_border = border;
394 ret
395 })
396 // Skip duplicates.
397 .filter(|(prev_border, border)| prev_border != border)
398 // Finally, convert to ranges.
399 .map(move |(prev_border, border)| {
400 let range = match (prev_border, border) {
401 (JustBefore(n), JustBefore(m)) if n < m => n..=(m - 1),
402 (JustBefore(n), AfterMax) => n..=u128::MAX,
403 _ => unreachable!(), // Ruled out by the sorting and filtering we did
404 };
405 IntRange { range, bias: self.range.bias }
406 })
407 }
408 }
409
410 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
411 enum SliceKind {
412 /// Patterns of length `n` (`[x, y]`).
413 FixedLen(usize),
414 /// Patterns using the `..` notation (`[x, .., y]`).
415 /// Captures any array constructor of `length >= i + j`.
416 /// In the case where `array_len` is `Some(_)`,
417 /// this indicates that we only care about the first `i` and the last `j` values of the array,
418 /// and everything in between is a wildcard `_`.
419 VarLen(usize, usize),
420 }
421
422 impl SliceKind {
arity(self) -> usize423 fn arity(self) -> usize {
424 match self {
425 FixedLen(length) => length,
426 VarLen(prefix, suffix) => prefix + suffix,
427 }
428 }
429
430 /// Whether this pattern includes patterns of length `other_len`.
covers_length(self, other_len: usize) -> bool431 fn covers_length(self, other_len: usize) -> bool {
432 match self {
433 FixedLen(len) => len == other_len,
434 VarLen(prefix, suffix) => prefix + suffix <= other_len,
435 }
436 }
437 }
438
439 /// A constructor for array and slice patterns.
440 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
441 pub(super) struct Slice {
442 /// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`.
443 array_len: Option<usize>,
444 /// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`.
445 kind: SliceKind,
446 }
447
448 impl Slice {
new(array_len: Option<usize>, kind: SliceKind) -> Self449 fn new(array_len: Option<usize>, kind: SliceKind) -> Self {
450 let kind = match (array_len, kind) {
451 // If the middle `..` is empty, we effectively have a fixed-length pattern.
452 (Some(len), VarLen(prefix, suffix)) if prefix + suffix >= len => FixedLen(len),
453 _ => kind,
454 };
455 Slice { array_len, kind }
456 }
457
arity(self) -> usize458 fn arity(self) -> usize {
459 self.kind.arity()
460 }
461
462 /// See `Constructor::is_covered_by`
is_covered_by(self, other: Self) -> bool463 fn is_covered_by(self, other: Self) -> bool {
464 other.kind.covers_length(self.arity())
465 }
466 }
467
468 /// This computes constructor splitting for variable-length slices, as explained at the top of the
469 /// file.
470 ///
471 /// A slice pattern `[x, .., y]` behaves like the infinite or-pattern `[x, y] | [x, _, y] | [x, _,
472 /// _, y] | ...`. The corresponding value constructors are fixed-length array constructors above a
473 /// given minimum length. We obviously can't list this infinitude of constructors. Thankfully,
474 /// it turns out that for each finite set of slice patterns, all sufficiently large array lengths
475 /// are equivalent.
476 ///
477 /// Let's look at an example, where we are trying to split the last pattern:
478 /// ```
479 /// # fn foo(x: &[bool]) {
480 /// match x {
481 /// [true, true, ..] => {}
482 /// [.., false, false] => {}
483 /// [..] => {}
484 /// }
485 /// # }
486 /// ```
487 /// Here are the results of specialization for the first few lengths:
488 /// ```
489 /// # fn foo(x: &[bool]) { match x {
490 /// // length 0
491 /// [] => {}
492 /// // length 1
493 /// [_] => {}
494 /// // length 2
495 /// [true, true] => {}
496 /// [false, false] => {}
497 /// [_, _] => {}
498 /// // length 3
499 /// [true, true, _ ] => {}
500 /// [_, false, false] => {}
501 /// [_, _, _ ] => {}
502 /// // length 4
503 /// [true, true, _, _ ] => {}
504 /// [_, _, false, false] => {}
505 /// [_, _, _, _ ] => {}
506 /// // length 5
507 /// [true, true, _, _, _ ] => {}
508 /// [_, _, _, false, false] => {}
509 /// [_, _, _, _, _ ] => {}
510 /// # _ => {}
511 /// # }}
512 /// ```
513 ///
514 /// If we went above length 5, we would simply be inserting more columns full of wildcards in the
515 /// middle. This means that the set of witnesses for length `l >= 5` if equivalent to the set for
516 /// any other `l' >= 5`: simply add or remove wildcards in the middle to convert between them.
517 ///
518 /// This applies to any set of slice patterns: there will be a length `L` above which all lengths
519 /// behave the same. This is exactly what we need for constructor splitting. Therefore a
520 /// variable-length slice can be split into a variable-length slice of minimal length `L`, and many
521 /// fixed-length slices of lengths `< L`.
522 ///
523 /// For each variable-length pattern `p` with a prefix of length `plₚ` and suffix of length `slₚ`,
524 /// only the first `plₚ` and the last `slₚ` elements are examined. Therefore, as long as `L` is
525 /// positive (to avoid concerns about empty types), all elements after the maximum prefix length
526 /// and before the maximum suffix length are not examined by any variable-length pattern, and
527 /// therefore can be added/removed without affecting them - creating equivalent patterns from any
528 /// sufficiently-large length.
529 ///
530 /// Of course, if fixed-length patterns exist, we must be sure that our length is large enough to
531 /// miss them all, so we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))`
532 ///
533 /// `max_slice` below will be made to have arity `L`.
534 #[derive(Debug)]
535 struct SplitVarLenSlice {
536 /// If the type is an array, this is its size.
537 array_len: Option<usize>,
538 /// The arity of the input slice.
539 arity: usize,
540 /// The smallest slice bigger than any slice seen. `max_slice.arity()` is the length `L`
541 /// described above.
542 max_slice: SliceKind,
543 }
544
545 impl SplitVarLenSlice {
new(prefix: usize, suffix: usize, array_len: Option<usize>) -> Self546 fn new(prefix: usize, suffix: usize, array_len: Option<usize>) -> Self {
547 SplitVarLenSlice { array_len, arity: prefix + suffix, max_slice: VarLen(prefix, suffix) }
548 }
549
550 /// Pass a set of slices relative to which to split this one.
split(&mut self, slices: impl Iterator<Item = SliceKind>)551 fn split(&mut self, slices: impl Iterator<Item = SliceKind>) {
552 let VarLen(max_prefix_len, max_suffix_len) = &mut self.max_slice else {
553 // No need to split
554 return;
555 };
556 // We grow `self.max_slice` to be larger than all slices encountered, as described above.
557 // For diagnostics, we keep the prefix and suffix lengths separate, but grow them so that
558 // `L = max_prefix_len + max_suffix_len`.
559 let mut max_fixed_len = 0;
560 for slice in slices {
561 match slice {
562 FixedLen(len) => {
563 max_fixed_len = cmp::max(max_fixed_len, len);
564 }
565 VarLen(prefix, suffix) => {
566 *max_prefix_len = cmp::max(*max_prefix_len, prefix);
567 *max_suffix_len = cmp::max(*max_suffix_len, suffix);
568 }
569 }
570 }
571 // We want `L = max(L, max_fixed_len + 1)`, modulo the fact that we keep prefix and
572 // suffix separate.
573 if max_fixed_len + 1 >= *max_prefix_len + *max_suffix_len {
574 // The subtraction can't overflow thanks to the above check.
575 // The new `max_prefix_len` is larger than its previous value.
576 *max_prefix_len = max_fixed_len + 1 - *max_suffix_len;
577 }
578
579 // We cap the arity of `max_slice` at the array size.
580 match self.array_len {
581 Some(len) if self.max_slice.arity() >= len => self.max_slice = FixedLen(len),
582 _ => {}
583 }
584 }
585
586 /// Iterate over the partition of this slice.
iter(&self) -> impl Iterator<Item = Slice> + Captures<'_>587 fn iter(&self) -> impl Iterator<Item = Slice> + Captures<'_> {
588 let smaller_lengths = match self.array_len {
589 // The only admissible fixed-length slice is one of the array size. Whether `max_slice`
590 // is fixed-length or variable-length, it will be the only relevant slice to output
591 // here.
592 Some(_) => 0..0, // empty range
593 // We cover all arities in the range `(self.arity..infinity)`. We split that range into
594 // two: lengths smaller than `max_slice.arity()` are treated independently as
595 // fixed-lengths slices, and lengths above are captured by `max_slice`.
596 None => self.arity..self.max_slice.arity(),
597 };
598 smaller_lengths
599 .map(FixedLen)
600 .chain(once(self.max_slice))
601 .map(move |kind| Slice::new(self.array_len, kind))
602 }
603 }
604
605 /// A value can be decomposed into a constructor applied to some fields. This struct represents
606 /// the constructor. See also `Fields`.
607 ///
608 /// `pat_constructor` retrieves the constructor corresponding to a pattern.
609 /// `specialize_constructor` returns the list of fields corresponding to a pattern, given a
610 /// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
611 /// `Fields`.
612 #[derive(Clone, Debug, PartialEq)]
613 pub(super) enum Constructor<'tcx> {
614 /// The constructor for patterns that have a single constructor, like tuples, struct patterns
615 /// and fixed-length arrays.
616 Single,
617 /// Enum variants.
618 Variant(VariantIdx),
619 /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
620 IntRange(IntRange),
621 /// Ranges of floating-point literal values (`2.0..=5.2`).
622 FloatRange(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>, RangeEnd),
623 /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
624 Str(mir::ConstantKind<'tcx>),
625 /// Array and slice patterns.
626 Slice(Slice),
627 /// Constants that must not be matched structurally. They are treated as black
628 /// boxes for the purposes of exhaustiveness: we must not inspect them, and they
629 /// don't count towards making a match exhaustive.
630 Opaque,
631 /// Fake extra constructor for enums that aren't allowed to be matched exhaustively. Also used
632 /// for those types for which we cannot list constructors explicitly, like `f64` and `str`.
633 NonExhaustive,
634 /// Stands for constructors that are not seen in the matrix, as explained in the documentation
635 /// for [`SplitWildcard`]. The carried `bool` is used for the `non_exhaustive_omitted_patterns`
636 /// lint.
637 Missing { nonexhaustive_enum_missing_real_variants: bool },
638 /// Wildcard pattern.
639 Wildcard,
640 /// Or-pattern.
641 Or,
642 }
643
644 impl<'tcx> Constructor<'tcx> {
is_wildcard(&self) -> bool645 pub(super) fn is_wildcard(&self) -> bool {
646 matches!(self, Wildcard)
647 }
648
is_non_exhaustive(&self) -> bool649 pub(super) fn is_non_exhaustive(&self) -> bool {
650 matches!(self, NonExhaustive)
651 }
652
as_int_range(&self) -> Option<&IntRange>653 fn as_int_range(&self) -> Option<&IntRange> {
654 match self {
655 IntRange(range) => Some(range),
656 _ => None,
657 }
658 }
659
as_slice(&self) -> Option<Slice>660 fn as_slice(&self) -> Option<Slice> {
661 match self {
662 Slice(slice) => Some(*slice),
663 _ => None,
664 }
665 }
666
667 /// Checks if the `Constructor` is a variant and `TyCtxt::eval_stability` returns
668 /// `EvalResult::Deny { .. }`.
669 ///
670 /// This means that the variant has a stdlib unstable feature marking it.
is_unstable_variant(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> bool671 pub(super) fn is_unstable_variant(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> bool {
672 if let Constructor::Variant(idx) = self && let ty::Adt(adt, _) = pcx.ty.kind() {
673 let variant_def_id = adt.variant(*idx).def_id;
674 // Filter variants that depend on a disabled unstable feature.
675 return matches!(
676 pcx.cx.tcx.eval_stability(variant_def_id, None, DUMMY_SP, None),
677 EvalResult::Deny { .. }
678 );
679 }
680 false
681 }
682
683 /// Checks if the `Constructor` is a `Constructor::Variant` with a `#[doc(hidden)]`
684 /// attribute from a type not local to the current crate.
is_doc_hidden_variant(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> bool685 pub(super) fn is_doc_hidden_variant(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> bool {
686 if let Constructor::Variant(idx) = self && let ty::Adt(adt, _) = pcx.ty.kind() {
687 let variant_def_id = adt.variants()[*idx].def_id;
688 return pcx.cx.tcx.is_doc_hidden(variant_def_id) && !variant_def_id.is_local();
689 }
690 false
691 }
692
variant_index_for_adt(&self, adt: ty::AdtDef<'tcx>) -> VariantIdx693 fn variant_index_for_adt(&self, adt: ty::AdtDef<'tcx>) -> VariantIdx {
694 match *self {
695 Variant(idx) => idx,
696 Single => {
697 assert!(!adt.is_enum());
698 FIRST_VARIANT
699 }
700 _ => bug!("bad constructor {:?} for adt {:?}", self, adt),
701 }
702 }
703
704 /// The number of fields for this constructor. This must be kept in sync with
705 /// `Fields::wildcards`.
arity(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> usize706 pub(super) fn arity(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> usize {
707 match self {
708 Single | Variant(_) => match pcx.ty.kind() {
709 ty::Tuple(fs) => fs.len(),
710 ty::Ref(..) => 1,
711 ty::Adt(adt, ..) => {
712 if adt.is_box() {
713 // The only legal patterns of type `Box` (outside `std`) are `_` and box
714 // patterns. If we're here we can assume this is a box pattern.
715 1
716 } else {
717 let variant = &adt.variant(self.variant_index_for_adt(*adt));
718 Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant).count()
719 }
720 }
721 _ => bug!("Unexpected type for `Single` constructor: {:?}", pcx.ty),
722 },
723 Slice(slice) => slice.arity(),
724 Str(..)
725 | FloatRange(..)
726 | IntRange(..)
727 | NonExhaustive
728 | Opaque
729 | Missing { .. }
730 | Wildcard => 0,
731 Or => bug!("The `Or` constructor doesn't have a fixed arity"),
732 }
733 }
734
735 /// Some constructors (namely `Wildcard`, `IntRange` and `Slice`) actually stand for a set of actual
736 /// constructors (like variants, integers or fixed-sized slices). When specializing for these
737 /// constructors, we want to be specialising for the actual underlying constructors.
738 /// Naively, we would simply return the list of constructors they correspond to. We instead are
739 /// more clever: if there are constructors that we know will behave the same wrt the current
740 /// matrix, we keep them grouped. For example, all slices of a sufficiently large length
741 /// will either be all useful or all non-useful with a given matrix.
742 ///
743 /// See the branches for details on how the splitting is done.
744 ///
745 /// This function may discard some irrelevant constructors if this preserves behavior and
746 /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the
747 /// matrix, unless all of them are.
split<'a>( &self, pcx: &PatCtxt<'_, '_, 'tcx>, ctors: impl Iterator<Item = &'a Constructor<'tcx>> + Clone, ) -> SmallVec<[Self; 1]> where 'tcx: 'a,748 pub(super) fn split<'a>(
749 &self,
750 pcx: &PatCtxt<'_, '_, 'tcx>,
751 ctors: impl Iterator<Item = &'a Constructor<'tcx>> + Clone,
752 ) -> SmallVec<[Self; 1]>
753 where
754 'tcx: 'a,
755 {
756 match self {
757 Wildcard => {
758 let mut split_wildcard = SplitWildcard::new(pcx);
759 split_wildcard.split(pcx, ctors);
760 split_wildcard.into_ctors(pcx)
761 }
762 // Fast-track if the range is trivial. In particular, we don't do the overlapping
763 // ranges check.
764 IntRange(ctor_range) if !ctor_range.is_singleton() => {
765 let mut split_range = SplitIntRange::new(ctor_range.clone());
766 let int_ranges = ctors.filter_map(|ctor| ctor.as_int_range());
767 split_range.split(int_ranges.cloned());
768 split_range.iter().map(IntRange).collect()
769 }
770 &Slice(Slice { kind: VarLen(self_prefix, self_suffix), array_len }) => {
771 let mut split_self = SplitVarLenSlice::new(self_prefix, self_suffix, array_len);
772 let slices = ctors.filter_map(|c| c.as_slice()).map(|s| s.kind);
773 split_self.split(slices);
774 split_self.iter().map(Slice).collect()
775 }
776 // Any other constructor can be used unchanged.
777 _ => smallvec![self.clone()],
778 }
779 }
780
781 /// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`.
782 /// For the simple cases, this is simply checking for equality. For the "grouped" constructors,
783 /// this checks for inclusion.
784 // We inline because this has a single call site in `Matrix::specialize_constructor`.
785 #[inline]
is_covered_by<'p>(&self, pcx: &PatCtxt<'_, 'p, 'tcx>, other: &Self) -> bool786 pub(super) fn is_covered_by<'p>(&self, pcx: &PatCtxt<'_, 'p, 'tcx>, other: &Self) -> bool {
787 // This must be kept in sync with `is_covered_by_any`.
788 match (self, other) {
789 // Wildcards cover anything
790 (_, Wildcard) => true,
791 // The missing ctors are not covered by anything in the matrix except wildcards.
792 (Missing { .. } | Wildcard, _) => false,
793
794 (Single, Single) => true,
795 (Variant(self_id), Variant(other_id)) => self_id == other_id,
796
797 (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range),
798 (
799 FloatRange(self_from, self_to, self_end),
800 FloatRange(other_from, other_to, other_end),
801 ) => {
802 match (
803 compare_const_vals(pcx.cx.tcx, *self_to, *other_to, pcx.cx.param_env),
804 compare_const_vals(pcx.cx.tcx, *self_from, *other_from, pcx.cx.param_env),
805 ) {
806 (Some(to), Some(from)) => {
807 (from == Ordering::Greater || from == Ordering::Equal)
808 && (to == Ordering::Less
809 || (other_end == self_end && to == Ordering::Equal))
810 }
811 _ => false,
812 }
813 }
814 (Str(self_val), Str(other_val)) => {
815 // FIXME Once valtrees are available we can directly use the bytes
816 // in the `Str` variant of the valtree for the comparison here.
817 self_val == other_val
818 }
819 (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
820
821 // We are trying to inspect an opaque constant. Thus we skip the row.
822 (Opaque, _) | (_, Opaque) => false,
823 // Only a wildcard pattern can match the special extra constructor.
824 (NonExhaustive, _) => false,
825
826 _ => span_bug!(
827 pcx.span,
828 "trying to compare incompatible constructors {:?} and {:?}",
829 self,
830 other
831 ),
832 }
833 }
834
835 /// Faster version of `is_covered_by` when applied to many constructors. `used_ctors` is
836 /// assumed to be built from `matrix.head_ctors()` with wildcards and opaques filtered out,
837 /// and `self` is assumed to have been split from a wildcard.
is_covered_by_any<'p>( &self, pcx: &PatCtxt<'_, 'p, 'tcx>, used_ctors: &[Constructor<'tcx>], ) -> bool838 fn is_covered_by_any<'p>(
839 &self,
840 pcx: &PatCtxt<'_, 'p, 'tcx>,
841 used_ctors: &[Constructor<'tcx>],
842 ) -> bool {
843 if used_ctors.is_empty() {
844 return false;
845 }
846
847 // This must be kept in sync with `is_covered_by`.
848 match self {
849 // If `self` is `Single`, `used_ctors` cannot contain anything else than `Single`s.
850 Single => !used_ctors.is_empty(),
851 Variant(vid) => used_ctors.iter().any(|c| matches!(c, Variant(i) if i == vid)),
852 IntRange(range) => used_ctors
853 .iter()
854 .filter_map(|c| c.as_int_range())
855 .any(|other| range.is_covered_by(other)),
856 Slice(slice) => used_ctors
857 .iter()
858 .filter_map(|c| c.as_slice())
859 .any(|other| slice.is_covered_by(other)),
860 // This constructor is never covered by anything else
861 NonExhaustive => false,
862 Str(..) | FloatRange(..) | Opaque | Missing { .. } | Wildcard | Or => {
863 span_bug!(pcx.span, "found unexpected ctor in all_ctors: {:?}", self)
864 }
865 }
866 }
867 }
868
869 /// A wildcard constructor that we split relative to the constructors in the matrix, as explained
870 /// at the top of the file.
871 ///
872 /// A constructor that is not present in the matrix rows will only be covered by the rows that have
873 /// wildcards. Thus we can group all of those constructors together; we call them "missing
874 /// constructors". Splitting a wildcard would therefore list all present constructors individually
875 /// (or grouped if they are integers or slices), and then all missing constructors together as a
876 /// group.
877 ///
878 /// However we can go further: since any constructor will match the wildcard rows, and having more
879 /// rows can only reduce the amount of usefulness witnesses, we can skip the present constructors
880 /// and only try the missing ones.
881 /// This will not preserve the whole list of witnesses, but will preserve whether the list is empty
882 /// or not. In fact this is quite natural from the point of view of diagnostics too. This is done
883 /// in `to_ctors`: in some cases we only return `Missing`.
884 #[derive(Debug)]
885 pub(super) struct SplitWildcard<'tcx> {
886 /// Constructors (other than wildcards and opaques) seen in the matrix.
887 matrix_ctors: Vec<Constructor<'tcx>>,
888 /// All the constructors for this type
889 all_ctors: SmallVec<[Constructor<'tcx>; 1]>,
890 }
891
892 impl<'tcx> SplitWildcard<'tcx> {
new<'p>(pcx: &PatCtxt<'_, 'p, 'tcx>) -> Self893 pub(super) fn new<'p>(pcx: &PatCtxt<'_, 'p, 'tcx>) -> Self {
894 debug!("SplitWildcard::new({:?})", pcx.ty);
895 let cx = pcx.cx;
896 let make_range = |start, end| {
897 IntRange(
898 // `unwrap()` is ok because we know the type is an integer.
899 IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included).unwrap(),
900 )
901 };
902 // This determines the set of all possible constructors for the type `pcx.ty`. For numbers,
903 // arrays and slices we use ranges and variable-length slices when appropriate.
904 //
905 // If the `exhaustive_patterns` feature is enabled, we make sure to omit constructors that
906 // are statically impossible. E.g., for `Option<!>`, we do not include `Some(_)` in the
907 // returned list of constructors.
908 // Invariant: this is empty if and only if the type is uninhabited (as determined by
909 // `cx.is_uninhabited()`).
910 let all_ctors = match pcx.ty.kind() {
911 ty::Bool => smallvec![make_range(0, 1)],
912 ty::Array(sub_ty, len) if len.try_eval_target_usize(cx.tcx, cx.param_env).is_some() => {
913 let len = len.eval_target_usize(cx.tcx, cx.param_env) as usize;
914 if len != 0 && cx.is_uninhabited(*sub_ty) {
915 smallvec![]
916 } else {
917 smallvec![Slice(Slice::new(Some(len), VarLen(0, 0)))]
918 }
919 }
920 // Treat arrays of a constant but unknown length like slices.
921 ty::Array(sub_ty, _) | ty::Slice(sub_ty) => {
922 let kind = if cx.is_uninhabited(*sub_ty) { FixedLen(0) } else { VarLen(0, 0) };
923 smallvec![Slice(Slice::new(None, kind))]
924 }
925 ty::Adt(def, substs) if def.is_enum() => {
926 // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
927 // additional "unknown" constructor.
928 // There is no point in enumerating all possible variants, because the user can't
929 // actually match against them all themselves. So we always return only the fictitious
930 // constructor.
931 // E.g., in an example like:
932 //
933 // ```
934 // let err: io::ErrorKind = ...;
935 // match err {
936 // io::ErrorKind::NotFound => {},
937 // }
938 // ```
939 //
940 // we don't want to show every possible IO error, but instead have only `_` as the
941 // witness.
942 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
943
944 let is_exhaustive_pat_feature = cx.tcx.features().exhaustive_patterns;
945
946 // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
947 // as though it had an "unknown" constructor to avoid exposing its emptiness. The
948 // exception is if the pattern is at the top level, because we want empty matches to be
949 // considered exhaustive.
950 let is_secretly_empty =
951 def.variants().is_empty() && !is_exhaustive_pat_feature && !pcx.is_top_level;
952
953 let mut ctors: SmallVec<[_; 1]> = def
954 .variants()
955 .iter_enumerated()
956 .filter(|(_, v)| {
957 // If `exhaustive_patterns` is enabled, we exclude variants known to be
958 // uninhabited.
959 !is_exhaustive_pat_feature
960 || v.inhabited_predicate(cx.tcx, *def).subst(cx.tcx, substs).apply(
961 cx.tcx,
962 cx.param_env,
963 cx.module,
964 )
965 })
966 .map(|(idx, _)| Variant(idx))
967 .collect();
968
969 if is_secretly_empty || is_declared_nonexhaustive {
970 ctors.push(NonExhaustive);
971 }
972 ctors
973 }
974 ty::Char => {
975 smallvec![
976 // The valid Unicode Scalar Value ranges.
977 make_range('\u{0000}' as u128, '\u{D7FF}' as u128),
978 make_range('\u{E000}' as u128, '\u{10FFFF}' as u128),
979 ]
980 }
981 ty::Int(_) | ty::Uint(_)
982 if pcx.ty.is_ptr_sized_integral()
983 && !cx.tcx.features().precise_pointer_size_matching =>
984 {
985 // `usize`/`isize` are not allowed to be matched exhaustively unless the
986 // `precise_pointer_size_matching` feature is enabled. So we treat those types like
987 // `#[non_exhaustive]` enums by returning a special unmatchable constructor.
988 smallvec![NonExhaustive]
989 }
990 &ty::Int(ity) => {
991 let bits = Integer::from_int_ty(&cx.tcx, ity).size().bits() as u128;
992 let min = 1u128 << (bits - 1);
993 let max = min - 1;
994 smallvec![make_range(min, max)]
995 }
996 &ty::Uint(uty) => {
997 let size = Integer::from_uint_ty(&cx.tcx, uty).size();
998 let max = size.truncate(u128::MAX);
999 smallvec![make_range(0, max)]
1000 }
1001 // If `exhaustive_patterns` is disabled and our scrutinee is the never type, we cannot
1002 // expose its emptiness. The exception is if the pattern is at the top level, because we
1003 // want empty matches to be considered exhaustive.
1004 ty::Never if !cx.tcx.features().exhaustive_patterns && !pcx.is_top_level => {
1005 smallvec![NonExhaustive]
1006 }
1007 ty::Never => smallvec![],
1008 _ if cx.is_uninhabited(pcx.ty) => smallvec![],
1009 ty::Adt(..) | ty::Tuple(..) | ty::Ref(..) => smallvec![Single],
1010 // This type is one for which we cannot list constructors, like `str` or `f64`.
1011 _ => smallvec![NonExhaustive],
1012 };
1013
1014 SplitWildcard { matrix_ctors: Vec::new(), all_ctors }
1015 }
1016
1017 /// Pass a set of constructors relative to which to split this one. Don't call twice, it won't
1018 /// do what you want.
split<'a>( &mut self, pcx: &PatCtxt<'_, '_, 'tcx>, ctors: impl Iterator<Item = &'a Constructor<'tcx>> + Clone, ) where 'tcx: 'a,1019 pub(super) fn split<'a>(
1020 &mut self,
1021 pcx: &PatCtxt<'_, '_, 'tcx>,
1022 ctors: impl Iterator<Item = &'a Constructor<'tcx>> + Clone,
1023 ) where
1024 'tcx: 'a,
1025 {
1026 // Since `all_ctors` never contains wildcards, this won't recurse further.
1027 self.all_ctors =
1028 self.all_ctors.iter().flat_map(|ctor| ctor.split(pcx, ctors.clone())).collect();
1029 self.matrix_ctors = ctors.filter(|c| !matches!(c, Wildcard | Opaque)).cloned().collect();
1030 }
1031
1032 /// Whether there are any value constructors for this type that are not present in the matrix.
any_missing(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> bool1033 fn any_missing(&self, pcx: &PatCtxt<'_, '_, 'tcx>) -> bool {
1034 self.iter_missing(pcx).next().is_some()
1035 }
1036
1037 /// Iterate over the constructors for this type that are not present in the matrix.
iter_missing<'a, 'p>( &'a self, pcx: &'a PatCtxt<'a, 'p, 'tcx>, ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'p>1038 pub(super) fn iter_missing<'a, 'p>(
1039 &'a self,
1040 pcx: &'a PatCtxt<'a, 'p, 'tcx>,
1041 ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'p> {
1042 self.all_ctors.iter().filter(move |ctor| !ctor.is_covered_by_any(pcx, &self.matrix_ctors))
1043 }
1044
1045 /// Return the set of constructors resulting from splitting the wildcard. As explained at the
1046 /// top of the file, if any constructors are missing we can ignore the present ones.
into_ctors(self, pcx: &PatCtxt<'_, '_, 'tcx>) -> SmallVec<[Constructor<'tcx>; 1]>1047 fn into_ctors(self, pcx: &PatCtxt<'_, '_, 'tcx>) -> SmallVec<[Constructor<'tcx>; 1]> {
1048 if self.any_missing(pcx) {
1049 // Some constructors are missing, thus we can specialize with the special `Missing`
1050 // constructor, which stands for those constructors that are not seen in the matrix,
1051 // and matches the same rows as any of them (namely the wildcard rows). See the top of
1052 // the file for details.
1053 // However, when all constructors are missing we can also specialize with the full
1054 // `Wildcard` constructor. The difference will depend on what we want in diagnostics.
1055
1056 // If some constructors are missing, we typically want to report those constructors,
1057 // e.g.:
1058 // ```
1059 // enum Direction { N, S, E, W }
1060 // let Direction::N = ...;
1061 // ```
1062 // we can report 3 witnesses: `S`, `E`, and `W`.
1063 //
1064 // However, if the user didn't actually specify a constructor
1065 // in this arm, e.g., in
1066 // ```
1067 // let x: (Direction, Direction, bool) = ...;
1068 // let (_, _, false) = x;
1069 // ```
1070 // we don't want to show all 16 possible witnesses `(<direction-1>, <direction-2>,
1071 // true)` - we are satisfied with `(_, _, true)`. So if all constructors are missing we
1072 // prefer to report just a wildcard `_`.
1073 //
1074 // The exception is: if we are at the top-level, for example in an empty match, we
1075 // sometimes prefer reporting the list of constructors instead of just `_`.
1076 let report_when_all_missing = pcx.is_top_level && !IntRange::is_integral(pcx.ty);
1077 let ctor = if !self.matrix_ctors.is_empty() || report_when_all_missing {
1078 if pcx.is_non_exhaustive {
1079 Missing {
1080 nonexhaustive_enum_missing_real_variants: self
1081 .iter_missing(pcx)
1082 .any(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx))),
1083 }
1084 } else {
1085 Missing { nonexhaustive_enum_missing_real_variants: false }
1086 }
1087 } else {
1088 Wildcard
1089 };
1090 return smallvec![ctor];
1091 }
1092
1093 // All the constructors are present in the matrix, so we just go through them all.
1094 self.all_ctors
1095 }
1096 }
1097
1098 /// A value can be decomposed into a constructor applied to some fields. This struct represents
1099 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
1100 ///
1101 /// This is constructed for a constructor using [`Fields::wildcards()`]. The idea is that
1102 /// [`Fields::wildcards()`] constructs a list of fields where all entries are wildcards, and then
1103 /// given a pattern we fill some of the fields with its subpatterns.
1104 /// In the following example `Fields::wildcards` returns `[_, _, _, _]`. Then in
1105 /// `extract_pattern_arguments` we fill some of the entries, and the result is
1106 /// `[Some(0), _, _, _]`.
1107 /// ```compile_fail,E0004
1108 /// # fn foo() -> [Option<u8>; 4] { [None; 4] }
1109 /// let x: [Option<u8>; 4] = foo();
1110 /// match x {
1111 /// [Some(0), ..] => {}
1112 /// }
1113 /// ```
1114 ///
1115 /// Note that the number of fields of a constructor may not match the fields declared in the
1116 /// original struct/variant. This happens if a private or `non_exhaustive` field is uninhabited,
1117 /// because the code mustn't observe that it is uninhabited. In that case that field is not
1118 /// included in `fields`. For that reason, when you have a `FieldIdx` you must use
1119 /// `index_with_declared_idx`.
1120 #[derive(Debug, Clone, Copy)]
1121 pub(super) struct Fields<'p, 'tcx> {
1122 fields: &'p [DeconstructedPat<'p, 'tcx>],
1123 }
1124
1125 impl<'p, 'tcx> Fields<'p, 'tcx> {
empty() -> Self1126 fn empty() -> Self {
1127 Fields { fields: &[] }
1128 }
1129
singleton(cx: &MatchCheckCtxt<'p, 'tcx>, field: DeconstructedPat<'p, 'tcx>) -> Self1130 fn singleton(cx: &MatchCheckCtxt<'p, 'tcx>, field: DeconstructedPat<'p, 'tcx>) -> Self {
1131 let field: &_ = cx.pattern_arena.alloc(field);
1132 Fields { fields: std::slice::from_ref(field) }
1133 }
1134
from_iter( cx: &MatchCheckCtxt<'p, 'tcx>, fields: impl IntoIterator<Item = DeconstructedPat<'p, 'tcx>>, ) -> Self1135 pub(super) fn from_iter(
1136 cx: &MatchCheckCtxt<'p, 'tcx>,
1137 fields: impl IntoIterator<Item = DeconstructedPat<'p, 'tcx>>,
1138 ) -> Self {
1139 let fields: &[_] = cx.pattern_arena.alloc_from_iter(fields);
1140 Fields { fields }
1141 }
1142
wildcards_from_tys( cx: &MatchCheckCtxt<'p, 'tcx>, tys: impl IntoIterator<Item = Ty<'tcx>>, span: Span, ) -> Self1143 fn wildcards_from_tys(
1144 cx: &MatchCheckCtxt<'p, 'tcx>,
1145 tys: impl IntoIterator<Item = Ty<'tcx>>,
1146 span: Span,
1147 ) -> Self {
1148 Fields::from_iter(cx, tys.into_iter().map(|ty| DeconstructedPat::wildcard(ty, span)))
1149 }
1150
1151 // In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide
1152 // uninhabited fields in order not to reveal the uninhabitedness of the whole variant.
1153 // This lists the fields we keep along with their types.
list_variant_nonhidden_fields<'a>( cx: &'a MatchCheckCtxt<'p, 'tcx>, ty: Ty<'tcx>, variant: &'a VariantDef, ) -> impl Iterator<Item = (FieldIdx, Ty<'tcx>)> + Captures<'a> + Captures<'p>1154 fn list_variant_nonhidden_fields<'a>(
1155 cx: &'a MatchCheckCtxt<'p, 'tcx>,
1156 ty: Ty<'tcx>,
1157 variant: &'a VariantDef,
1158 ) -> impl Iterator<Item = (FieldIdx, Ty<'tcx>)> + Captures<'a> + Captures<'p> {
1159 let ty::Adt(adt, substs) = ty.kind() else { bug!() };
1160 // Whether we must not match the fields of this variant exhaustively.
1161 let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did().is_local();
1162
1163 variant.fields.iter().enumerate().filter_map(move |(i, field)| {
1164 let ty = field.ty(cx.tcx, substs);
1165 // `field.ty()` doesn't normalize after substituting.
1166 let ty = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
1167 let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx);
1168 let is_uninhabited = cx.is_uninhabited(ty);
1169
1170 if is_uninhabited && (!is_visible || is_non_exhaustive) {
1171 None
1172 } else {
1173 Some((FieldIdx::new(i), ty))
1174 }
1175 })
1176 }
1177
1178 /// Creates a new list of wildcard fields for a given constructor. The result must have a
1179 /// length of `constructor.arity()`.
1180 #[instrument(level = "trace")]
wildcards(pcx: &PatCtxt<'_, 'p, 'tcx>, constructor: &Constructor<'tcx>) -> Self1181 pub(super) fn wildcards(pcx: &PatCtxt<'_, 'p, 'tcx>, constructor: &Constructor<'tcx>) -> Self {
1182 let ret = match constructor {
1183 Single | Variant(_) => match pcx.ty.kind() {
1184 ty::Tuple(fs) => Fields::wildcards_from_tys(pcx.cx, fs.iter(), pcx.span),
1185 ty::Ref(_, rty, _) => Fields::wildcards_from_tys(pcx.cx, once(*rty), pcx.span),
1186 ty::Adt(adt, substs) => {
1187 if adt.is_box() {
1188 // The only legal patterns of type `Box` (outside `std`) are `_` and box
1189 // patterns. If we're here we can assume this is a box pattern.
1190 Fields::wildcards_from_tys(pcx.cx, once(substs.type_at(0)), pcx.span)
1191 } else {
1192 let variant = &adt.variant(constructor.variant_index_for_adt(*adt));
1193 let tys = Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant)
1194 .map(|(_, ty)| ty);
1195 Fields::wildcards_from_tys(pcx.cx, tys, pcx.span)
1196 }
1197 }
1198 _ => bug!("Unexpected type for `Single` constructor: {:?}", pcx),
1199 },
1200 Slice(slice) => match *pcx.ty.kind() {
1201 ty::Slice(ty) | ty::Array(ty, _) => {
1202 let arity = slice.arity();
1203 Fields::wildcards_from_tys(pcx.cx, (0..arity).map(|_| ty), pcx.span)
1204 }
1205 _ => bug!("bad slice pattern {:?} {:?}", constructor, pcx),
1206 },
1207 Str(..)
1208 | FloatRange(..)
1209 | IntRange(..)
1210 | NonExhaustive
1211 | Opaque
1212 | Missing { .. }
1213 | Wildcard => Fields::empty(),
1214 Or => {
1215 bug!("called `Fields::wildcards` on an `Or` ctor")
1216 }
1217 };
1218 debug!(?ret);
1219 ret
1220 }
1221
1222 /// Returns the list of patterns.
iter_patterns<'a>( &'a self, ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a>1223 pub(super) fn iter_patterns<'a>(
1224 &'a self,
1225 ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a> {
1226 self.fields.iter()
1227 }
1228 }
1229
1230 /// Values and patterns can be represented as a constructor applied to some fields. This represents
1231 /// a pattern in this form.
1232 /// This also keeps track of whether the pattern has been found reachable during analysis. For this
1233 /// reason we should be careful not to clone patterns for which we care about that. Use
1234 /// `clone_and_forget_reachability` if you're sure.
1235 pub(crate) struct DeconstructedPat<'p, 'tcx> {
1236 ctor: Constructor<'tcx>,
1237 fields: Fields<'p, 'tcx>,
1238 ty: Ty<'tcx>,
1239 span: Span,
1240 reachable: Cell<bool>,
1241 }
1242
1243 impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> {
wildcard(ty: Ty<'tcx>, span: Span) -> Self1244 pub(super) fn wildcard(ty: Ty<'tcx>, span: Span) -> Self {
1245 Self::new(Wildcard, Fields::empty(), ty, span)
1246 }
1247
new( ctor: Constructor<'tcx>, fields: Fields<'p, 'tcx>, ty: Ty<'tcx>, span: Span, ) -> Self1248 pub(super) fn new(
1249 ctor: Constructor<'tcx>,
1250 fields: Fields<'p, 'tcx>,
1251 ty: Ty<'tcx>,
1252 span: Span,
1253 ) -> Self {
1254 DeconstructedPat { ctor, fields, ty, span, reachable: Cell::new(false) }
1255 }
1256
1257 /// Construct a pattern that matches everything that starts with this constructor.
1258 /// For example, if `ctor` is a `Constructor::Variant` for `Option::Some`, we get the pattern
1259 /// `Some(_)`.
wild_from_ctor(pcx: &PatCtxt<'_, 'p, 'tcx>, ctor: Constructor<'tcx>) -> Self1260 pub(super) fn wild_from_ctor(pcx: &PatCtxt<'_, 'p, 'tcx>, ctor: Constructor<'tcx>) -> Self {
1261 let fields = Fields::wildcards(pcx, &ctor);
1262 DeconstructedPat::new(ctor, fields, pcx.ty, pcx.span)
1263 }
1264
1265 /// Clone this value. This method emphasizes that cloning loses reachability information and
1266 /// should be done carefully.
clone_and_forget_reachability(&self) -> Self1267 pub(super) fn clone_and_forget_reachability(&self) -> Self {
1268 DeconstructedPat::new(self.ctor.clone(), self.fields, self.ty, self.span)
1269 }
1270
from_pat(cx: &MatchCheckCtxt<'p, 'tcx>, pat: &Pat<'tcx>) -> Self1271 pub(crate) fn from_pat(cx: &MatchCheckCtxt<'p, 'tcx>, pat: &Pat<'tcx>) -> Self {
1272 let mkpat = |pat| DeconstructedPat::from_pat(cx, pat);
1273 let ctor;
1274 let fields;
1275 match &pat.kind {
1276 PatKind::AscribeUserType { subpattern, .. } => return mkpat(subpattern),
1277 PatKind::Binding { subpattern: Some(subpat), .. } => return mkpat(subpat),
1278 PatKind::Binding { subpattern: None, .. } | PatKind::Wild => {
1279 ctor = Wildcard;
1280 fields = Fields::empty();
1281 }
1282 PatKind::Deref { subpattern } => {
1283 ctor = Single;
1284 fields = Fields::singleton(cx, mkpat(subpattern));
1285 }
1286 PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
1287 match pat.ty.kind() {
1288 ty::Tuple(fs) => {
1289 ctor = Single;
1290 let mut wilds: SmallVec<[_; 2]> =
1291 fs.iter().map(|ty| DeconstructedPat::wildcard(ty, pat.span)).collect();
1292 for pat in subpatterns {
1293 wilds[pat.field.index()] = mkpat(&pat.pattern);
1294 }
1295 fields = Fields::from_iter(cx, wilds);
1296 }
1297 ty::Adt(adt, substs) if adt.is_box() => {
1298 // The only legal patterns of type `Box` (outside `std`) are `_` and box
1299 // patterns. If we're here we can assume this is a box pattern.
1300 // FIXME(Nadrieril): A `Box` can in theory be matched either with `Box(_,
1301 // _)` or a box pattern. As a hack to avoid an ICE with the former, we
1302 // ignore other fields than the first one. This will trigger an error later
1303 // anyway.
1304 // See https://github.com/rust-lang/rust/issues/82772 ,
1305 // explanation: https://github.com/rust-lang/rust/pull/82789#issuecomment-796921977
1306 // The problem is that we can't know from the type whether we'll match
1307 // normally or through box-patterns. We'll have to figure out a proper
1308 // solution when we introduce generalized deref patterns. Also need to
1309 // prevent mixing of those two options.
1310 let pattern = subpatterns.into_iter().find(|pat| pat.field.index() == 0);
1311 let pat = if let Some(pat) = pattern {
1312 mkpat(&pat.pattern)
1313 } else {
1314 DeconstructedPat::wildcard(substs.type_at(0), pat.span)
1315 };
1316 ctor = Single;
1317 fields = Fields::singleton(cx, pat);
1318 }
1319 ty::Adt(adt, _) => {
1320 ctor = match pat.kind {
1321 PatKind::Leaf { .. } => Single,
1322 PatKind::Variant { variant_index, .. } => Variant(variant_index),
1323 _ => bug!(),
1324 };
1325 let variant = &adt.variant(ctor.variant_index_for_adt(*adt));
1326 // For each field in the variant, we store the relevant index into `self.fields` if any.
1327 let mut field_id_to_id: Vec<Option<usize>> =
1328 (0..variant.fields.len()).map(|_| None).collect();
1329 let tys = Fields::list_variant_nonhidden_fields(cx, pat.ty, variant)
1330 .enumerate()
1331 .map(|(i, (field, ty))| {
1332 field_id_to_id[field.index()] = Some(i);
1333 ty
1334 });
1335 let mut wilds: SmallVec<[_; 2]> =
1336 tys.map(|ty| DeconstructedPat::wildcard(ty, pat.span)).collect();
1337 for pat in subpatterns {
1338 if let Some(i) = field_id_to_id[pat.field.index()] {
1339 wilds[i] = mkpat(&pat.pattern);
1340 }
1341 }
1342 fields = Fields::from_iter(cx, wilds);
1343 }
1344 _ => bug!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, pat.ty),
1345 }
1346 }
1347 PatKind::Constant { value } => {
1348 if let Some(int_range) = IntRange::from_constant(cx.tcx, cx.param_env, *value) {
1349 ctor = IntRange(int_range);
1350 fields = Fields::empty();
1351 } else {
1352 match pat.ty.kind() {
1353 ty::Float(_) => {
1354 ctor = FloatRange(*value, *value, RangeEnd::Included);
1355 fields = Fields::empty();
1356 }
1357 ty::Ref(_, t, _) if t.is_str() => {
1358 // We want a `&str` constant to behave like a `Deref` pattern, to be compatible
1359 // with other `Deref` patterns. This could have been done in `const_to_pat`,
1360 // but that causes issues with the rest of the matching code.
1361 // So here, the constructor for a `"foo"` pattern is `&` (represented by
1362 // `Single`), and has one field. That field has constructor `Str(value)` and no
1363 // fields.
1364 // Note: `t` is `str`, not `&str`.
1365 let subpattern =
1366 DeconstructedPat::new(Str(*value), Fields::empty(), *t, pat.span);
1367 ctor = Single;
1368 fields = Fields::singleton(cx, subpattern)
1369 }
1370 // All constants that can be structurally matched have already been expanded
1371 // into the corresponding `Pat`s by `const_to_pat`. Constants that remain are
1372 // opaque.
1373 _ => {
1374 ctor = Opaque;
1375 fields = Fields::empty();
1376 }
1377 }
1378 }
1379 }
1380 &PatKind::Range(box PatRange { lo, hi, end }) => {
1381 let ty = lo.ty();
1382 ctor = if let Some(int_range) = IntRange::from_range(
1383 cx.tcx,
1384 lo.eval_bits(cx.tcx, cx.param_env, lo.ty()),
1385 hi.eval_bits(cx.tcx, cx.param_env, hi.ty()),
1386 ty,
1387 &end,
1388 ) {
1389 IntRange(int_range)
1390 } else {
1391 FloatRange(lo, hi, end)
1392 };
1393 fields = Fields::empty();
1394 }
1395 PatKind::Array { prefix, slice, suffix } | PatKind::Slice { prefix, slice, suffix } => {
1396 let array_len = match pat.ty.kind() {
1397 ty::Array(_, length) => {
1398 Some(length.eval_target_usize(cx.tcx, cx.param_env) as usize)
1399 }
1400 ty::Slice(_) => None,
1401 _ => span_bug!(pat.span, "bad ty {:?} for slice pattern", pat.ty),
1402 };
1403 let kind = if slice.is_some() {
1404 VarLen(prefix.len(), suffix.len())
1405 } else {
1406 FixedLen(prefix.len() + suffix.len())
1407 };
1408 ctor = Slice(Slice::new(array_len, kind));
1409 fields =
1410 Fields::from_iter(cx, prefix.iter().chain(suffix.iter()).map(|p| mkpat(&*p)));
1411 }
1412 PatKind::Or { .. } => {
1413 ctor = Or;
1414 let pats = expand_or_pat(pat);
1415 fields = Fields::from_iter(cx, pats.into_iter().map(mkpat));
1416 }
1417 }
1418 DeconstructedPat::new(ctor, fields, pat.ty, pat.span)
1419 }
1420
to_pat(&self, cx: &MatchCheckCtxt<'p, 'tcx>) -> Pat<'tcx>1421 pub(crate) fn to_pat(&self, cx: &MatchCheckCtxt<'p, 'tcx>) -> Pat<'tcx> {
1422 let is_wildcard = |pat: &Pat<'_>| {
1423 matches!(pat.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild)
1424 };
1425 let mut subpatterns = self.iter_fields().map(|p| Box::new(p.to_pat(cx)));
1426 let kind = match &self.ctor {
1427 Single | Variant(_) => match self.ty.kind() {
1428 ty::Tuple(..) => PatKind::Leaf {
1429 subpatterns: subpatterns
1430 .enumerate()
1431 .map(|(i, pattern)| FieldPat { field: FieldIdx::new(i), pattern })
1432 .collect(),
1433 },
1434 ty::Adt(adt_def, _) if adt_def.is_box() => {
1435 // Without `box_patterns`, the only legal pattern of type `Box` is `_` (outside
1436 // of `std`). So this branch is only reachable when the feature is enabled and
1437 // the pattern is a box pattern.
1438 PatKind::Deref { subpattern: subpatterns.next().unwrap() }
1439 }
1440 ty::Adt(adt_def, substs) => {
1441 let variant_index = self.ctor.variant_index_for_adt(*adt_def);
1442 let variant = &adt_def.variant(variant_index);
1443 let subpatterns = Fields::list_variant_nonhidden_fields(cx, self.ty, variant)
1444 .zip(subpatterns)
1445 .map(|((field, _ty), pattern)| FieldPat { field, pattern })
1446 .collect();
1447
1448 if adt_def.is_enum() {
1449 PatKind::Variant { adt_def: *adt_def, substs, variant_index, subpatterns }
1450 } else {
1451 PatKind::Leaf { subpatterns }
1452 }
1453 }
1454 // Note: given the expansion of `&str` patterns done in `expand_pattern`, we should
1455 // be careful to reconstruct the correct constant pattern here. However a string
1456 // literal pattern will never be reported as a non-exhaustiveness witness, so we
1457 // ignore this issue.
1458 ty::Ref(..) => PatKind::Deref { subpattern: subpatterns.next().unwrap() },
1459 _ => bug!("unexpected ctor for type {:?} {:?}", self.ctor, self.ty),
1460 },
1461 Slice(slice) => {
1462 match slice.kind {
1463 FixedLen(_) => PatKind::Slice {
1464 prefix: subpatterns.collect(),
1465 slice: None,
1466 suffix: Box::new([]),
1467 },
1468 VarLen(prefix, _) => {
1469 let mut subpatterns = subpatterns.peekable();
1470 let mut prefix: Vec<_> = subpatterns.by_ref().take(prefix).collect();
1471 if slice.array_len.is_some() {
1472 // Improves diagnostics a bit: if the type is a known-size array, instead
1473 // of reporting `[x, _, .., _, y]`, we prefer to report `[x, .., y]`.
1474 // This is incorrect if the size is not known, since `[_, ..]` captures
1475 // arrays of lengths `>= 1` whereas `[..]` captures any length.
1476 while !prefix.is_empty() && is_wildcard(prefix.last().unwrap()) {
1477 prefix.pop();
1478 }
1479 while subpatterns.peek().is_some()
1480 && is_wildcard(subpatterns.peek().unwrap())
1481 {
1482 subpatterns.next();
1483 }
1484 }
1485 let suffix: Box<[_]> = subpatterns.collect();
1486 let wild = Pat::wildcard_from_ty(self.ty);
1487 PatKind::Slice {
1488 prefix: prefix.into_boxed_slice(),
1489 slice: Some(Box::new(wild)),
1490 suffix,
1491 }
1492 }
1493 }
1494 }
1495 &Str(value) => PatKind::Constant { value },
1496 &FloatRange(lo, hi, end) => PatKind::Range(Box::new(PatRange { lo, hi, end })),
1497 IntRange(range) => return range.to_pat(cx.tcx, self.ty),
1498 Wildcard | NonExhaustive => PatKind::Wild,
1499 Missing { .. } => bug!(
1500 "trying to convert a `Missing` constructor into a `Pat`; this is probably a bug,
1501 `Missing` should have been processed in `apply_constructors`"
1502 ),
1503 Opaque | Or => {
1504 bug!("can't convert to pattern: {:?}", self)
1505 }
1506 };
1507
1508 Pat { ty: self.ty, span: DUMMY_SP, kind }
1509 }
1510
is_or_pat(&self) -> bool1511 pub(super) fn is_or_pat(&self) -> bool {
1512 matches!(self.ctor, Or)
1513 }
1514
ctor(&self) -> &Constructor<'tcx>1515 pub(super) fn ctor(&self) -> &Constructor<'tcx> {
1516 &self.ctor
1517 }
ty(&self) -> Ty<'tcx>1518 pub(super) fn ty(&self) -> Ty<'tcx> {
1519 self.ty
1520 }
span(&self) -> Span1521 pub(super) fn span(&self) -> Span {
1522 self.span
1523 }
1524
iter_fields<'a>( &'a self, ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a>1525 pub(super) fn iter_fields<'a>(
1526 &'a self,
1527 ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a> {
1528 self.fields.iter_patterns()
1529 }
1530
1531 /// Specialize this pattern with a constructor.
1532 /// `other_ctor` can be different from `self.ctor`, but must be covered by it.
specialize<'a>( &'a self, pcx: &PatCtxt<'_, 'p, 'tcx>, other_ctor: &Constructor<'tcx>, ) -> SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>1533 pub(super) fn specialize<'a>(
1534 &'a self,
1535 pcx: &PatCtxt<'_, 'p, 'tcx>,
1536 other_ctor: &Constructor<'tcx>,
1537 ) -> SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]> {
1538 match (&self.ctor, other_ctor) {
1539 (Wildcard, _) => {
1540 // We return a wildcard for each field of `other_ctor`.
1541 Fields::wildcards(pcx, other_ctor).iter_patterns().collect()
1542 }
1543 (Slice(self_slice), Slice(other_slice))
1544 if self_slice.arity() != other_slice.arity() =>
1545 {
1546 // The only tricky case: two slices of different arity. Since `self_slice` covers
1547 // `other_slice`, `self_slice` must be `VarLen`, i.e. of the form
1548 // `[prefix, .., suffix]`. Moreover `other_slice` is guaranteed to have a larger
1549 // arity. So we fill the middle part with enough wildcards to reach the length of
1550 // the new, larger slice.
1551 match self_slice.kind {
1552 FixedLen(_) => bug!("{:?} doesn't cover {:?}", self_slice, other_slice),
1553 VarLen(prefix, suffix) => {
1554 let (ty::Slice(inner_ty) | ty::Array(inner_ty, _)) = *self.ty.kind() else {
1555 bug!("bad slice pattern {:?} {:?}", self.ctor, self.ty);
1556 };
1557 let prefix = &self.fields.fields[..prefix];
1558 let suffix = &self.fields.fields[self_slice.arity() - suffix..];
1559 let wildcard: &_ = pcx
1560 .cx
1561 .pattern_arena
1562 .alloc(DeconstructedPat::wildcard(inner_ty, pcx.span));
1563 let extra_wildcards = other_slice.arity() - self_slice.arity();
1564 let extra_wildcards = (0..extra_wildcards).map(|_| wildcard);
1565 prefix.iter().chain(extra_wildcards).chain(suffix).collect()
1566 }
1567 }
1568 }
1569 _ => self.fields.iter_patterns().collect(),
1570 }
1571 }
1572
1573 /// We keep track for each pattern if it was ever reachable during the analysis. This is used
1574 /// with `unreachable_spans` to report unreachable subpatterns arising from or patterns.
set_reachable(&self)1575 pub(super) fn set_reachable(&self) {
1576 self.reachable.set(true)
1577 }
is_reachable(&self) -> bool1578 pub(super) fn is_reachable(&self) -> bool {
1579 self.reachable.get()
1580 }
1581
1582 /// Report the spans of subpatterns that were not reachable, if any.
unreachable_spans(&self) -> Vec<Span>1583 pub(super) fn unreachable_spans(&self) -> Vec<Span> {
1584 let mut spans = Vec::new();
1585 self.collect_unreachable_spans(&mut spans);
1586 spans
1587 }
1588
collect_unreachable_spans(&self, spans: &mut Vec<Span>)1589 fn collect_unreachable_spans(&self, spans: &mut Vec<Span>) {
1590 // We don't look at subpatterns if we already reported the whole pattern as unreachable.
1591 if !self.is_reachable() {
1592 spans.push(self.span);
1593 } else {
1594 for p in self.iter_fields() {
1595 p.collect_unreachable_spans(spans);
1596 }
1597 }
1598 }
1599 }
1600
1601 /// This is mostly copied from the `Pat` impl. This is best effort and not good enough for a
1602 /// `Display` impl.
1603 impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1605 // Printing lists is a chore.
1606 let mut first = true;
1607 let mut start_or_continue = |s| {
1608 if first {
1609 first = false;
1610 ""
1611 } else {
1612 s
1613 }
1614 };
1615 let mut start_or_comma = || start_or_continue(", ");
1616
1617 match &self.ctor {
1618 Single | Variant(_) => match self.ty.kind() {
1619 ty::Adt(def, _) if def.is_box() => {
1620 // Without `box_patterns`, the only legal pattern of type `Box` is `_` (outside
1621 // of `std`). So this branch is only reachable when the feature is enabled and
1622 // the pattern is a box pattern.
1623 let subpattern = self.iter_fields().next().unwrap();
1624 write!(f, "box {:?}", subpattern)
1625 }
1626 ty::Adt(..) | ty::Tuple(..) => {
1627 let variant = match self.ty.kind() {
1628 ty::Adt(adt, _) => Some(adt.variant(self.ctor.variant_index_for_adt(*adt))),
1629 ty::Tuple(_) => None,
1630 _ => unreachable!(),
1631 };
1632
1633 if let Some(variant) = variant {
1634 write!(f, "{}", variant.name)?;
1635 }
1636
1637 // Without `cx`, we can't know which field corresponds to which, so we can't
1638 // get the names of the fields. Instead we just display everything as a tuple
1639 // struct, which should be good enough.
1640 write!(f, "(")?;
1641 for p in self.iter_fields() {
1642 write!(f, "{}", start_or_comma())?;
1643 write!(f, "{:?}", p)?;
1644 }
1645 write!(f, ")")
1646 }
1647 // Note: given the expansion of `&str` patterns done in `expand_pattern`, we should
1648 // be careful to detect strings here. However a string literal pattern will never
1649 // be reported as a non-exhaustiveness witness, so we can ignore this issue.
1650 ty::Ref(_, _, mutbl) => {
1651 let subpattern = self.iter_fields().next().unwrap();
1652 write!(f, "&{}{:?}", mutbl.prefix_str(), subpattern)
1653 }
1654 _ => write!(f, "_"),
1655 },
1656 Slice(slice) => {
1657 let mut subpatterns = self.fields.iter_patterns();
1658 write!(f, "[")?;
1659 match slice.kind {
1660 FixedLen(_) => {
1661 for p in subpatterns {
1662 write!(f, "{}{:?}", start_or_comma(), p)?;
1663 }
1664 }
1665 VarLen(prefix_len, _) => {
1666 for p in subpatterns.by_ref().take(prefix_len) {
1667 write!(f, "{}{:?}", start_or_comma(), p)?;
1668 }
1669 write!(f, "{}", start_or_comma())?;
1670 write!(f, "..")?;
1671 for p in subpatterns {
1672 write!(f, "{}{:?}", start_or_comma(), p)?;
1673 }
1674 }
1675 }
1676 write!(f, "]")
1677 }
1678 &FloatRange(lo, hi, end) => {
1679 write!(f, "{}", lo)?;
1680 write!(f, "{}", end)?;
1681 write!(f, "{}", hi)
1682 }
1683 IntRange(range) => write!(f, "{:?}", range), // Best-effort, will render e.g. `false` as `0..=0`
1684 Wildcard | Missing { .. } | NonExhaustive => write!(f, "_ : {:?}", self.ty),
1685 Or => {
1686 for pat in self.iter_fields() {
1687 write!(f, "{}{:?}", start_or_continue(" | "), pat)?;
1688 }
1689 Ok(())
1690 }
1691 Str(value) => write!(f, "{}", value),
1692 Opaque => write!(f, "<constant pattern>"),
1693 }
1694 }
1695 }
1696