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