]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/diagnostics/match_check/deconstruct_pat.rs
internal: Sync match checking algorithm with rustc
[rust.git] / crates / hir_ty / src / diagnostics / match_check / 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 //! ```
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`].
43
44 use std::{
45     cell::Cell,
46     cmp::{max, min},
47     iter::once,
48     ops::RangeInclusive,
49 };
50
51 use hir_def::{EnumVariantId, HasModule, LocalFieldId, VariantId};
52 use smallvec::{smallvec, SmallVec};
53 use stdx::never;
54 use syntax::SmolStr;
55
56 use crate::{AdtId, Interner, Scalar, Ty, TyExt, TyKind};
57
58 use super::{
59     usefulness::{helper::Captures, MatchCheckCtx, PatCtxt},
60     Pat, PatKind,
61 };
62
63 use self::Constructor::*;
64
65 /// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.
66 fn expand_or_pat(pat: &Pat) -> Vec<&Pat> {
67     fn expand<'p>(pat: &'p Pat, vec: &mut Vec<&'p Pat>) {
68         if let PatKind::Or { pats } = pat.kind.as_ref() {
69             for pat in pats {
70                 expand(pat, vec);
71             }
72         } else {
73             vec.push(pat)
74         }
75     }
76
77     let mut pats = Vec::new();
78     expand(pat, &mut pats);
79     pats
80 }
81
82 /// [Constructor] uses this in umimplemented variants.
83 /// It allows porting match expressions from upstream algorithm without losing semantics.
84 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
85 pub(super) enum Void {}
86
87 /// An inclusive interval, used for precise integer exhaustiveness checking.
88 /// `IntRange`s always store a contiguous range. This means that values are
89 /// encoded such that `0` encodes the minimum value for the integer,
90 /// regardless of the signedness.
91 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
92 /// This makes comparisons and arithmetic on interval endpoints much more
93 /// straightforward. See `signed_bias` for details.
94 ///
95 /// `IntRange` is never used to encode an empty range or a "range" that wraps
96 /// around the (offset) space: i.e., `range.lo <= range.hi`.
97 #[derive(Clone, Debug, PartialEq, Eq)]
98 pub(super) struct IntRange {
99     range: RangeInclusive<u128>,
100 }
101
102 impl IntRange {
103     #[inline]
104     fn is_integral(ty: &Ty) -> bool {
105         matches!(
106             ty.kind(Interner),
107             TyKind::Scalar(Scalar::Char | Scalar::Int(_) | Scalar::Uint(_) | Scalar::Bool)
108         )
109     }
110
111     fn is_singleton(&self) -> bool {
112         self.range.start() == self.range.end()
113     }
114
115     fn boundaries(&self) -> (u128, u128) {
116         (*self.range.start(), *self.range.end())
117     }
118
119     #[inline]
120     fn from_bool(value: bool) -> IntRange {
121         let val = value as u128;
122         IntRange { range: val..=val }
123     }
124
125     #[inline]
126     fn from_range(lo: u128, hi: u128, scalar_ty: Scalar) -> IntRange {
127         match scalar_ty {
128             Scalar::Bool => IntRange { range: lo..=hi },
129             _ => unimplemented!(),
130         }
131     }
132
133     fn is_subrange(&self, other: &Self) -> bool {
134         other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
135     }
136
137     fn intersection(&self, other: &Self) -> Option<Self> {
138         let (lo, hi) = self.boundaries();
139         let (other_lo, other_hi) = other.boundaries();
140         if lo <= other_hi && other_lo <= hi {
141             Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi) })
142         } else {
143             None
144         }
145     }
146
147     /// See `Constructor::is_covered_by`
148     fn is_covered_by(&self, other: &Self) -> bool {
149         if self.intersection(other).is_some() {
150             // Constructor splitting should ensure that all intersections we encounter are actually
151             // inclusions.
152             assert!(self.is_subrange(other));
153             true
154         } else {
155             false
156         }
157     }
158 }
159
160 /// Represents a border between 2 integers. Because the intervals spanning borders must be able to
161 /// cover every integer, we need to be able to represent 2^128 + 1 such borders.
162 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
163 enum IntBorder {
164     JustBefore(u128),
165     AfterMax,
166 }
167
168 /// A range of integers that is partitioned into disjoint subranges. This does constructor
169 /// splitting for integer ranges as explained at the top of the file.
170 ///
171 /// This is fed multiple ranges, and returns an output that covers the input, but is split so that
172 /// the only intersections between an output range and a seen range are inclusions. No output range
173 /// straddles the boundary of one of the inputs.
174 ///
175 /// The following input:
176 /// ```
177 ///   |-------------------------| // `self`
178 /// |------|  |----------|   |----|
179 ///    |-------| |-------|
180 /// ```
181 /// would be iterated over as follows:
182 /// ```
183 ///   ||---|--||-|---|---|---|--|
184 /// ```
185 #[derive(Debug, Clone)]
186 struct SplitIntRange {
187     /// The range we are splitting
188     range: IntRange,
189     /// The borders of ranges we have seen. They are all contained within `range`. This is kept
190     /// sorted.
191     borders: Vec<IntBorder>,
192 }
193
194 impl SplitIntRange {
195     fn new(range: IntRange) -> Self {
196         SplitIntRange { range, borders: Vec::new() }
197     }
198
199     /// Internal use
200     fn to_borders(r: IntRange) -> [IntBorder; 2] {
201         use IntBorder::*;
202         let (lo, hi) = r.boundaries();
203         let lo = JustBefore(lo);
204         let hi = match hi.checked_add(1) {
205             Some(m) => JustBefore(m),
206             None => AfterMax,
207         };
208         [lo, hi]
209     }
210
211     /// Add ranges relative to which we split.
212     fn split(&mut self, ranges: impl Iterator<Item = IntRange>) {
213         let this_range = &self.range;
214         let included_ranges = ranges.filter_map(|r| this_range.intersection(&r));
215         let included_borders = included_ranges.flat_map(|r| {
216             let borders = Self::to_borders(r);
217             once(borders[0]).chain(once(borders[1]))
218         });
219         self.borders.extend(included_borders);
220         self.borders.sort_unstable();
221     }
222
223     /// Iterate over the contained ranges.
224     fn iter(&self) -> impl Iterator<Item = IntRange> + '_ {
225         use IntBorder::*;
226
227         let self_range = Self::to_borders(self.range.clone());
228         // Start with the start of the range.
229         let mut prev_border = self_range[0];
230         self.borders
231             .iter()
232             .copied()
233             // End with the end of the range.
234             .chain(once(self_range[1]))
235             // List pairs of adjacent borders.
236             .map(move |border| {
237                 let ret = (prev_border, border);
238                 prev_border = border;
239                 ret
240             })
241             // Skip duplicates.
242             .filter(|(prev_border, border)| prev_border != border)
243             // Finally, convert to ranges.
244             .map(|(prev_border, border)| {
245                 let range = match (prev_border, border) {
246                     (JustBefore(n), JustBefore(m)) if n < m => n..=(m - 1),
247                     (JustBefore(n), AfterMax) => n..=u128::MAX,
248                     _ => unreachable!(), // Ruled out by the sorting and filtering we did
249                 };
250                 IntRange { range }
251             })
252     }
253 }
254
255 /// A constructor for array and slice patterns.
256 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
257 pub(super) struct Slice {
258     _unimplemented: Void,
259 }
260
261 impl Slice {
262     fn arity(self) -> usize {
263         unimplemented!()
264     }
265
266     /// See `Constructor::is_covered_by`
267     fn is_covered_by(self, _other: Self) -> bool {
268         unimplemented!() // never called as Slice contains Void
269     }
270 }
271
272 /// A value can be decomposed into a constructor applied to some fields. This struct represents
273 /// the constructor. See also `Fields`.
274 ///
275 /// `pat_constructor` retrieves the constructor corresponding to a pattern.
276 /// `specialize_constructor` returns the list of fields corresponding to a pattern, given a
277 /// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
278 /// `Fields`.
279 #[allow(dead_code)]
280 #[derive(Clone, Debug, PartialEq)]
281 pub(super) enum Constructor {
282     /// The constructor for patterns that have a single constructor, like tuples, struct patterns
283     /// and fixed-length arrays.
284     Single,
285     /// Enum variants.
286     Variant(EnumVariantId),
287     /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
288     IntRange(IntRange),
289     /// Ranges of floating-point literal values (`2.0..=5.2`).
290     FloatRange(Void),
291     /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
292     Str(Void),
293     /// Array and slice patterns.
294     Slice(Slice),
295     /// Constants that must not be matched structurally. They are treated as black
296     /// boxes for the purposes of exhaustiveness: we must not inspect them, and they
297     /// don't count towards making a match exhaustive.
298     Opaque,
299     /// Fake extra constructor for enums that aren't allowed to be matched exhaustively. Also used
300     /// for those types for which we cannot list constructors explicitly, like `f64` and `str`.
301     NonExhaustive,
302     /// Stands for constructors that are not seen in the matrix, as explained in the documentation
303     /// for [`SplitWildcard`]. The carried `bool` is used for the `non_exhaustive_omitted_patterns`
304     /// lint.
305     Missing { nonexhaustive_enum_missing_real_variants: bool },
306     /// Wildcard pattern.
307     Wildcard,
308     /// Or-pattern.
309     Or,
310 }
311
312 impl Constructor {
313     pub(super) fn is_wildcard(&self) -> bool {
314         matches!(self, Wildcard)
315     }
316
317     pub(super) fn is_non_exhaustive(&self) -> bool {
318         matches!(self, NonExhaustive)
319     }
320
321     fn as_int_range(&self) -> Option<&IntRange> {
322         match self {
323             IntRange(range) => Some(range),
324             _ => None,
325         }
326     }
327
328     fn as_slice(&self) -> Option<Slice> {
329         match self {
330             Slice(slice) => Some(*slice),
331             _ => None,
332         }
333     }
334
335     fn variant_id_for_adt(&self, adt: hir_def::AdtId) -> VariantId {
336         match *self {
337             Variant(id) => id.into(),
338             Single => {
339                 assert!(!matches!(adt, hir_def::AdtId::EnumId(_)));
340                 match adt {
341                     hir_def::AdtId::EnumId(_) => unreachable!(),
342                     hir_def::AdtId::StructId(id) => id.into(),
343                     hir_def::AdtId::UnionId(id) => id.into(),
344                 }
345             }
346             _ => panic!("bad constructor {:?} for adt {:?}", self, adt),
347         }
348     }
349
350     /// The number of fields for this constructor. This must be kept in sync with
351     /// `Fields::wildcards`.
352     pub(super) fn arity(&self, pcx: PatCtxt<'_, '_>) -> usize {
353         match self {
354             Single | Variant(_) => match *pcx.ty.kind(Interner) {
355                 TyKind::Tuple(arity, ..) => arity,
356                 TyKind::Ref(..) => 1,
357                 TyKind::Adt(adt, ..) => {
358                     if adt_is_box(adt.0, pcx.cx) {
359                         // The only legal patterns of type `Box` (outside `std`) are `_` and box
360                         // patterns. If we're here we can assume this is a box pattern.
361                         1
362                     } else {
363                         let variant = self.variant_id_for_adt(adt.0);
364                         Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant).count()
365                     }
366                 }
367                 _ => {
368                     never!("Unexpected type for `Single` constructor: {:?}", pcx.ty);
369                     0
370                 }
371             },
372             Slice(slice) => slice.arity(),
373             Str(..)
374             | FloatRange(..)
375             | IntRange(..)
376             | NonExhaustive
377             | Opaque
378             | Missing { .. }
379             | Wildcard => 0,
380             Or => {
381                 never!("The `Or` constructor doesn't have a fixed arity");
382                 0
383             }
384         }
385     }
386
387     /// Some constructors (namely `Wildcard`, `IntRange` and `Slice`) actually stand for a set of actual
388     /// constructors (like variants, integers or fixed-sized slices). When specializing for these
389     /// constructors, we want to be specialising for the actual underlying constructors.
390     /// Naively, we would simply return the list of constructors they correspond to. We instead are
391     /// more clever: if there are constructors that we know will behave the same wrt the current
392     /// matrix, we keep them grouped. For example, all slices of a sufficiently large length
393     /// will either be all useful or all non-useful with a given matrix.
394     ///
395     /// See the branches for details on how the splitting is done.
396     ///
397     /// This function may discard some irrelevant constructors if this preserves behavior and
398     /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the
399     /// matrix, unless all of them are.
400     pub(super) fn split<'a>(
401         &self,
402         pcx: PatCtxt<'_, '_>,
403         ctors: impl Iterator<Item = &'a Constructor> + Clone,
404     ) -> SmallVec<[Self; 1]> {
405         match self {
406             Wildcard => {
407                 let mut split_wildcard = SplitWildcard::new(pcx);
408                 split_wildcard.split(pcx, ctors);
409                 split_wildcard.into_ctors(pcx)
410             }
411             // Fast-track if the range is trivial. In particular, we don't do the overlapping
412             // ranges check.
413             IntRange(ctor_range) if !ctor_range.is_singleton() => {
414                 let mut split_range = SplitIntRange::new(ctor_range.clone());
415                 let int_ranges = ctors.filter_map(|ctor| ctor.as_int_range());
416                 split_range.split(int_ranges.cloned());
417                 split_range.iter().map(IntRange).collect()
418             }
419             Slice(_) => unimplemented!(),
420             // Any other constructor can be used unchanged.
421             _ => smallvec![self.clone()],
422         }
423     }
424
425     /// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`.
426     /// For the simple cases, this is simply checking for equality. For the "grouped" constructors,
427     /// this checks for inclusion.
428     // We inline because this has a single call site in `Matrix::specialize_constructor`.
429     #[inline]
430     pub(super) fn is_covered_by(&self, _pcx: PatCtxt<'_, '_>, other: &Self) -> bool {
431         // This must be kept in sync with `is_covered_by_any`.
432         match (self, other) {
433             // Wildcards cover anything
434             (_, Wildcard) => true,
435             // The missing ctors are not covered by anything in the matrix except wildcards.
436             (Missing { .. } | Wildcard, _) => false,
437
438             (Single, Single) => true,
439             (Variant(self_id), Variant(other_id)) => self_id == other_id,
440
441             (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range),
442             (FloatRange(..), FloatRange(..)) => {
443                 unimplemented!()
444             }
445             (Str(..), Str(..)) => {
446                 unimplemented!()
447             }
448             (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
449
450             // We are trying to inspect an opaque constant. Thus we skip the row.
451             (Opaque, _) | (_, Opaque) => false,
452             // Only a wildcard pattern can match the special extra constructor.
453             (NonExhaustive, _) => false,
454
455             _ => {
456                 never!("trying to compare incompatible constructors {:?} and {:?}", self, other);
457                 // Continue with 'whatever is covered' supposed to result in false no-error diagnostic.
458                 true
459             }
460         }
461     }
462
463     /// Faster version of `is_covered_by` when applied to many constructors. `used_ctors` is
464     /// assumed to be built from `matrix.head_ctors()` with wildcards filtered out, and `self` is
465     /// assumed to have been split from a wildcard.
466     fn is_covered_by_any(&self, _pcx: PatCtxt<'_, '_>, used_ctors: &[Constructor]) -> bool {
467         if used_ctors.is_empty() {
468             return false;
469         }
470
471         // This must be kept in sync with `is_covered_by`.
472         match self {
473             // If `self` is `Single`, `used_ctors` cannot contain anything else than `Single`s.
474             Single => !used_ctors.is_empty(),
475             Variant(_) => used_ctors.iter().any(|c| c == self),
476             IntRange(range) => used_ctors
477                 .iter()
478                 .filter_map(|c| c.as_int_range())
479                 .any(|other| range.is_covered_by(other)),
480             Slice(slice) => used_ctors
481                 .iter()
482                 .filter_map(|c| c.as_slice())
483                 .any(|other| slice.is_covered_by(other)),
484             // This constructor is never covered by anything else
485             NonExhaustive => false,
486             Str(..) | FloatRange(..) | Opaque | Missing { .. } | Wildcard | Or => {
487                 never!("found unexpected ctor in all_ctors: {:?}", self);
488                 true
489             }
490         }
491     }
492 }
493
494 /// A wildcard constructor that we split relative to the constructors in the matrix, as explained
495 /// at the top of the file.
496 ///
497 /// A constructor that is not present in the matrix rows will only be covered by the rows that have
498 /// wildcards. Thus we can group all of those constructors together; we call them "missing
499 /// constructors". Splitting a wildcard would therefore list all present constructors individually
500 /// (or grouped if they are integers or slices), and then all missing constructors together as a
501 /// group.
502 ///
503 /// However we can go further: since any constructor will match the wildcard rows, and having more
504 /// rows can only reduce the amount of usefulness witnesses, we can skip the present constructors
505 /// and only try the missing ones.
506 /// This will not preserve the whole list of witnesses, but will preserve whether the list is empty
507 /// or not. In fact this is quite natural from the point of view of diagnostics too. This is done
508 /// in `to_ctors`: in some cases we only return `Missing`.
509 #[derive(Debug)]
510 pub(super) struct SplitWildcard {
511     /// Constructors seen in the matrix.
512     matrix_ctors: Vec<Constructor>,
513     /// All the constructors for this type
514     all_ctors: SmallVec<[Constructor; 1]>,
515 }
516
517 impl SplitWildcard {
518     pub(super) fn new(pcx: PatCtxt<'_, '_>) -> Self {
519         let cx = pcx.cx;
520         let make_range = |start, end, scalar| IntRange(IntRange::from_range(start, end, scalar));
521
522         // Unhandled types are treated as non-exhaustive. Being explicit here instead of falling
523         // to catchall arm to ease further implementation.
524         let unhandled = || smallvec![NonExhaustive];
525
526         // This determines the set of all possible constructors for the type `pcx.ty`. For numbers,
527         // arrays and slices we use ranges and variable-length slices when appropriate.
528         //
529         // If the `exhaustive_patterns` feature is enabled, we make sure to omit constructors that
530         // are statically impossible. E.g., for `Option<!>`, we do not include `Some(_)` in the
531         // returned list of constructors.
532         // Invariant: this is empty if and only if the type is uninhabited (as determined by
533         // `cx.is_uninhabited()`).
534         let all_ctors = match pcx.ty.kind(Interner) {
535             TyKind::Scalar(Scalar::Bool) => smallvec![make_range(0, 1, Scalar::Bool)],
536             // TyKind::Array(..) if ... => unhandled(),
537             TyKind::Array(..) | TyKind::Slice(..) => unhandled(),
538             &TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ..) => {
539                 let enum_data = cx.db.enum_data(enum_id);
540
541                 // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
542                 // additional "unknown" constructor.
543                 // There is no point in enumerating all possible variants, because the user can't
544                 // actually match against them all themselves. So we always return only the fictitious
545                 // constructor.
546                 // E.g., in an example like:
547                 //
548                 // ```
549                 //     let err: io::ErrorKind = ...;
550                 //     match err {
551                 //         io::ErrorKind::NotFound => {},
552                 //     }
553                 // ```
554                 //
555                 // we don't want to show every possible IO error, but instead have only `_` as the
556                 // witness.
557                 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
558
559                 // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
560                 // as though it had an "unknown" constructor to avoid exposing its emptiness. The
561                 // exception is if the pattern is at the top level, because we want empty matches to be
562                 // considered exhaustive.
563                 let is_secretly_empty = enum_data.variants.is_empty()
564                     && !cx.feature_exhaustive_patterns()
565                     && !pcx.is_top_level;
566
567                 if is_secretly_empty {
568                     smallvec![NonExhaustive]
569                 } else if is_declared_nonexhaustive {
570                     enum_data
571                         .variants
572                         .iter()
573                         .map(|(local_id, ..)| Variant(EnumVariantId { parent: enum_id, local_id }))
574                         .chain(Some(NonExhaustive))
575                         .collect()
576                 } else if cx.feature_exhaustive_patterns() {
577                     unimplemented!() // see MatchCheckCtx.feature_exhaustive_patterns()
578                 } else {
579                     enum_data
580                         .variants
581                         .iter()
582                         .map(|(local_id, ..)| Variant(EnumVariantId { parent: enum_id, local_id }))
583                         .collect()
584                 }
585             }
586             TyKind::Scalar(Scalar::Char) => unhandled(),
587             TyKind::Scalar(Scalar::Int(..) | Scalar::Uint(..)) => unhandled(),
588             TyKind::Never if !cx.feature_exhaustive_patterns() && !pcx.is_top_level => {
589                 smallvec![NonExhaustive]
590             }
591             TyKind::Never => SmallVec::new(),
592             _ if cx.is_uninhabited(pcx.ty) => SmallVec::new(),
593             TyKind::Adt(..) | TyKind::Tuple(..) | TyKind::Ref(..) => smallvec![Single],
594             // This type is one for which we cannot list constructors, like `str` or `f64`.
595             _ => smallvec![NonExhaustive],
596         };
597
598         SplitWildcard { matrix_ctors: Vec::new(), all_ctors }
599     }
600
601     /// Pass a set of constructors relative to which to split this one. Don't call twice, it won't
602     /// do what you want.
603     pub(super) fn split<'a>(
604         &mut self,
605         pcx: PatCtxt<'_, '_>,
606         ctors: impl Iterator<Item = &'a Constructor> + Clone,
607     ) {
608         // Since `all_ctors` never contains wildcards, this won't recurse further.
609         self.all_ctors =
610             self.all_ctors.iter().flat_map(|ctor| ctor.split(pcx, ctors.clone())).collect();
611         self.matrix_ctors = ctors.filter(|c| !c.is_wildcard()).cloned().collect();
612     }
613
614     /// Whether there are any value constructors for this type that are not present in the matrix.
615     fn any_missing(&self, pcx: PatCtxt<'_, '_>) -> bool {
616         self.iter_missing(pcx).next().is_some()
617     }
618
619     /// Iterate over the constructors for this type that are not present in the matrix.
620     pub(super) fn iter_missing<'a, 'p>(
621         &'a self,
622         pcx: PatCtxt<'a, 'p>,
623     ) -> impl Iterator<Item = &'a Constructor> + Captures<'p> {
624         self.all_ctors.iter().filter(move |ctor| !ctor.is_covered_by_any(pcx, &self.matrix_ctors))
625     }
626
627     /// Return the set of constructors resulting from splitting the wildcard. As explained at the
628     /// top of the file, if any constructors are missing we can ignore the present ones.
629     fn into_ctors(self, pcx: PatCtxt<'_, '_>) -> SmallVec<[Constructor; 1]> {
630         if self.any_missing(pcx) {
631             // Some constructors are missing, thus we can specialize with the special `Missing`
632             // constructor, which stands for those constructors that are not seen in the matrix,
633             // and matches the same rows as any of them (namely the wildcard rows). See the top of
634             // the file for details.
635             // However, when all constructors are missing we can also specialize with the full
636             // `Wildcard` constructor. The difference will depend on what we want in diagnostics.
637
638             // If some constructors are missing, we typically want to report those constructors,
639             // e.g.:
640             // ```
641             //     enum Direction { N, S, E, W }
642             //     let Direction::N = ...;
643             // ```
644             // we can report 3 witnesses: `S`, `E`, and `W`.
645             //
646             // However, if the user didn't actually specify a constructor
647             // in this arm, e.g., in
648             // ```
649             //     let x: (Direction, Direction, bool) = ...;
650             //     let (_, _, false) = x;
651             // ```
652             // we don't want to show all 16 possible witnesses `(<direction-1>, <direction-2>,
653             // true)` - we are satisfied with `(_, _, true)`. So if all constructors are missing we
654             // prefer to report just a wildcard `_`.
655             //
656             // The exception is: if we are at the top-level, for example in an empty match, we
657             // sometimes prefer reporting the list of constructors instead of just `_`.
658             let report_when_all_missing = pcx.is_top_level && !IntRange::is_integral(pcx.ty);
659             let ctor = if !self.matrix_ctors.is_empty() || report_when_all_missing {
660                 if pcx.is_non_exhaustive {
661                     Missing {
662                         nonexhaustive_enum_missing_real_variants: self
663                             .iter_missing(pcx)
664                             .filter(|c| !c.is_non_exhaustive())
665                             .next()
666                             .is_some(),
667                     }
668                 } else {
669                     Missing { nonexhaustive_enum_missing_real_variants: false }
670                 }
671             } else {
672                 Wildcard
673             };
674             return smallvec![ctor];
675         }
676
677         // All the constructors are present in the matrix, so we just go through them all.
678         self.all_ctors
679     }
680 }
681
682 /// A value can be decomposed into a constructor applied to some fields. This struct represents
683 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
684 ///
685 /// This is constructed for a constructor using [`Fields::wildcards()`]. The idea is that
686 /// [`Fields::wildcards()`] constructs a list of fields where all entries are wildcards, and then
687 /// given a pattern we fill some of the fields with its subpatterns.
688 /// In the following example `Fields::wildcards` returns `[_, _, _, _]`. Then in
689 /// `extract_pattern_arguments` we fill some of the entries, and the result is
690 /// `[Some(0), _, _, _]`.
691 /// ```rust
692 /// let x: [Option<u8>; 4] = foo();
693 /// match x {
694 ///     [Some(0), ..] => {}
695 /// }
696 /// ```
697 ///
698 /// Note that the number of fields of a constructor may not match the fields declared in the
699 /// original struct/variant. This happens if a private or `non_exhaustive` field is uninhabited,
700 /// because the code mustn't observe that it is uninhabited. In that case that field is not
701 /// included in `fields`. For that reason, when you have a `mir::Field` you must use
702 /// `index_with_declared_idx`.
703 #[derive(Clone, Copy)]
704 pub(super) struct Fields<'p> {
705     fields: &'p [DeconstructedPat<'p>],
706 }
707
708 impl<'p> Fields<'p> {
709     fn empty() -> Self {
710         Fields { fields: &[] }
711     }
712
713     fn singleton(cx: &MatchCheckCtx<'_, 'p>, field: DeconstructedPat<'p>) -> Self {
714         let field = cx.pattern_arena.alloc(field);
715         Fields { fields: std::slice::from_ref(field) }
716     }
717
718     pub(super) fn from_iter(
719         cx: &MatchCheckCtx<'_, 'p>,
720         fields: impl IntoIterator<Item = DeconstructedPat<'p>>,
721     ) -> Self {
722         let fields: &[_] = cx.pattern_arena.alloc_extend(fields);
723         Fields { fields }
724     }
725
726     fn wildcards_from_tys(cx: &MatchCheckCtx<'_, 'p>, tys: impl IntoIterator<Item = Ty>) -> Self {
727         Fields::from_iter(cx, tys.into_iter().map(DeconstructedPat::wildcard))
728     }
729
730     // In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide
731     // uninhabited fields in order not to reveal the uninhabitedness of the whole variant.
732     // This lists the fields we keep along with their types.
733     fn list_variant_nonhidden_fields<'a>(
734         cx: &'a MatchCheckCtx<'a, 'p>,
735         ty: &'a Ty,
736         variant: VariantId,
737     ) -> impl Iterator<Item = (LocalFieldId, Ty)> + Captures<'a> + Captures<'p> {
738         let (adt, substs) = ty.as_adt().unwrap();
739
740         let adt_is_local = variant.module(cx.db.upcast()).krate() == cx.module.krate();
741         // Whether we must not match the fields of this variant exhaustively.
742         let is_non_exhaustive = is_field_list_non_exhaustive(variant, cx) && !adt_is_local;
743
744         let visibility = cx.db.field_visibilities(variant);
745         let field_ty = cx.db.field_types(variant);
746         let fields_len = variant.variant_data(cx.db.upcast()).fields().len() as u32;
747
748         (0..fields_len).map(|idx| LocalFieldId::from_raw(idx.into())).filter_map(move |fid| {
749             // TODO check ty has been normalized
750             let ty = field_ty[fid].clone().substitute(Interner, substs);
751             let is_visible = matches!(adt, hir_def::AdtId::EnumId(..))
752                 || visibility[fid].is_visible_from(cx.db.upcast(), cx.module);
753             let is_uninhabited = cx.is_uninhabited(&ty);
754
755             if is_uninhabited && (!is_visible || is_non_exhaustive) {
756                 None
757             } else {
758                 Some((fid, ty))
759             }
760         })
761     }
762
763     /// Creates a new list of wildcard fields for a given constructor. The result must have a
764     /// length of `constructor.arity()`.
765     pub(crate) fn wildcards(
766         cx: &MatchCheckCtx<'_, 'p>,
767         ty: &Ty,
768         constructor: &Constructor,
769     ) -> Self {
770         let ret = match constructor {
771             Single | Variant(_) => match ty.kind(Interner) {
772                 TyKind::Tuple(_, substs) => {
773                     let tys = substs.iter(Interner).map(|ty| ty.assert_ty_ref(Interner));
774                     Fields::wildcards_from_tys(cx, tys.cloned())
775                 }
776                 TyKind::Ref(.., rty) => Fields::wildcards_from_tys(cx, once(rty.clone())),
777                 &TyKind::Adt(AdtId(adt), ref substs) => {
778                     if adt_is_box(adt, cx) {
779                         // The only legal patterns of type `Box` (outside `std`) are `_` and box
780                         // patterns. If we're here we can assume this is a box pattern.
781                         let subst_ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
782                         Fields::wildcards_from_tys(cx, once(subst_ty))
783                     } else {
784                         let variant = constructor.variant_id_for_adt(adt);
785                         let tys = Fields::list_variant_nonhidden_fields(cx, ty, variant)
786                             .map(|(_, ty)| ty);
787                         Fields::wildcards_from_tys(cx, tys)
788                     }
789                 }
790                 ty_kind => {
791                     never!("Unexpected type for `Single` constructor: {:?}", ty_kind);
792                     Fields::wildcards_from_tys(cx, once(ty.clone()))
793                 }
794             },
795             Slice(..) => {
796                 unimplemented!()
797             }
798             Str(..)
799             | FloatRange(..)
800             | IntRange(..)
801             | NonExhaustive
802             | Opaque
803             | Missing { .. }
804             | Wildcard => Fields::empty(),
805             Or => {
806                 never!("called `Fields::wildcards` on an `Or` ctor");
807                 Fields::empty()
808             }
809         };
810         ret
811     }
812
813     /// Returns the list of patterns.
814     pub(super) fn iter_patterns<'a>(
815         &'a self,
816     ) -> impl Iterator<Item = &'p DeconstructedPat<'p>> + Captures<'a> {
817         self.fields.iter()
818     }
819 }
820
821 /// Values and patterns can be represented as a constructor applied to some fields. This represents
822 /// a pattern in this form.
823 /// This also keeps track of whether the pattern has been foundreachable during analysis. For this
824 /// reason we should be careful not to clone patterns for which we care about that. Use
825 /// `clone_and_forget_reachability` is you're sure.
826 pub(crate) struct DeconstructedPat<'p> {
827     ctor: Constructor,
828     fields: Fields<'p>,
829     ty: Ty,
830     reachable: Cell<bool>,
831 }
832
833 impl<'p> DeconstructedPat<'p> {
834     pub(super) fn wildcard(ty: Ty) -> Self {
835         Self::new(Wildcard, Fields::empty(), ty)
836     }
837
838     pub(super) fn new(ctor: Constructor, fields: Fields<'p>, ty: Ty) -> Self {
839         DeconstructedPat { ctor, fields, ty, reachable: Cell::new(false) }
840     }
841
842     /// Construct a pattern that matches everything that starts with this constructor.
843     /// For example, if `ctor` is a `Constructor::Variant` for `Option::Some`, we get the pattern
844     /// `Some(_)`.
845     pub(super) fn wild_from_ctor(pcx: PatCtxt<'_, 'p>, ctor: Constructor) -> Self {
846         let fields = Fields::wildcards(pcx.cx, pcx.ty, &ctor);
847         DeconstructedPat::new(ctor, fields, pcx.ty.clone())
848     }
849
850     /// Clone this value. This method emphasizes that cloning loses reachability information and
851     /// should be done carefully.
852     pub(super) fn clone_and_forget_reachability(&self) -> Self {
853         DeconstructedPat::new(self.ctor.clone(), self.fields, self.ty.clone())
854     }
855
856     pub(crate) fn from_pat(cx: &MatchCheckCtx<'_, 'p>, pat: &Pat) -> Self {
857         let mkpat = |pat| DeconstructedPat::from_pat(cx, pat);
858         let ctor;
859         let fields;
860         match pat.kind.as_ref() {
861             PatKind::Binding { subpattern: Some(subpat) } => return mkpat(subpat),
862             PatKind::Binding { subpattern: None } | PatKind::Wild => {
863                 ctor = Wildcard;
864                 fields = Fields::empty();
865             }
866             PatKind::Deref { subpattern } => {
867                 ctor = Single;
868                 fields = Fields::singleton(cx, mkpat(subpattern));
869             }
870             PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
871                 match pat.ty.kind(Interner) {
872                     TyKind::Tuple(_, substs) => {
873                         ctor = Single;
874                         let mut wilds: SmallVec<[_; 2]> = substs
875                             .iter(Interner)
876                             .map(|arg| arg.assert_ty_ref(Interner).clone())
877                             .map(DeconstructedPat::wildcard)
878                             .collect();
879                         for pat in subpatterns {
880                             let idx: u32 = pat.field.into_raw().into();
881                             wilds[idx as usize] = mkpat(&pat.pattern);
882                         }
883                         fields = Fields::from_iter(cx, wilds)
884                     }
885                     TyKind::Adt(adt, substs) if adt_is_box(adt.0, cx) => {
886                         // The only legal patterns of type `Box` (outside `std`) are `_` and box
887                         // patterns. If we're here we can assume this is a box pattern.
888                         // FIXME(Nadrieril): A `Box` can in theory be matched either with `Box(_,
889                         // _)` or a box pattern. As a hack to avoid an ICE with the former, we
890                         // ignore other fields than the first one. This will trigger an error later
891                         // anyway.
892                         // See https://github.com/rust-lang/rust/issues/82772 ,
893                         // explanation: https://github.com/rust-lang/rust/pull/82789#issuecomment-796921977
894                         // The problem is that we can't know from the type whether we'll match
895                         // normally or through box-patterns. We'll have to figure out a proper
896                         // solution when we introduce generalized deref patterns. Also need to
897                         // prevent mixing of those two options.
898                         let pat =
899                             subpatterns.iter().find(|pat| pat.field.into_raw() == 0u32.into());
900                         let field = if let Some(pat) = pat {
901                             mkpat(&pat.pattern)
902                         } else {
903                             let ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
904                             DeconstructedPat::wildcard(ty)
905                         };
906                         ctor = Single;
907                         fields = Fields::singleton(cx, field)
908                     }
909                     &TyKind::Adt(adt, _) => {
910                         ctor = match pat.kind.as_ref() {
911                             PatKind::Leaf { .. } => Single,
912                             PatKind::Variant { enum_variant, .. } => Variant(*enum_variant),
913                             _ => {
914                                 never!();
915                                 Wildcard
916                             }
917                         };
918                         let variant = ctor.variant_id_for_adt(adt.0);
919                         let fields_len = variant.variant_data(cx.db.upcast()).fields().len();
920                         // For each field in the variant, we store the relevant index into `self.fields` if any.
921                         let mut field_id_to_id: Vec<Option<usize>> = vec![None; fields_len];
922                         let tys = Fields::list_variant_nonhidden_fields(cx, &pat.ty, variant)
923                             .enumerate()
924                             .map(|(i, (fid, ty))| {
925                                 let field_idx: u32 = fid.into_raw().into();
926                                 field_id_to_id[field_idx as usize] = Some(i);
927                                 ty
928                             });
929                         let mut wilds: SmallVec<[_; 2]> =
930                             tys.map(DeconstructedPat::wildcard).collect();
931                         for pat in subpatterns {
932                             let field_idx: u32 = pat.field.into_raw().into();
933                             if let Some(i) = field_id_to_id[field_idx as usize] {
934                                 wilds[i] = mkpat(&pat.pattern);
935                             }
936                         }
937                         fields = Fields::from_iter(cx, wilds);
938                     }
939                     _ => {
940                         never!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, &pat.ty);
941                         ctor = Wildcard;
942                         fields = Fields::empty();
943                     }
944                 }
945             }
946             &PatKind::LiteralBool { value } => {
947                 ctor = IntRange(IntRange::from_bool(value));
948                 fields = Fields::empty();
949             }
950             PatKind::Or { .. } => {
951                 ctor = Or;
952                 let pats: SmallVec<[_; 2]> = expand_or_pat(pat).into_iter().map(mkpat).collect();
953                 fields = Fields::from_iter(cx, pats)
954             }
955         }
956         DeconstructedPat::new(ctor, fields, pat.ty.clone())
957     }
958
959     // // FIXME(iDawer): implement reporting of noncovered patterns
960     // pub(crate) fn to_pat(&self, _cx: &MatchCheckCtx<'_, 'p>) -> Pat {
961     //     Pat { ty: self.ty.clone(), kind: PatKind::Wild.into() }
962     // }
963
964     pub(super) fn is_or_pat(&self) -> bool {
965         matches!(self.ctor, Or)
966     }
967
968     pub(super) fn ctor(&self) -> &Constructor {
969         &self.ctor
970     }
971
972     pub(super) fn ty(&self) -> &Ty {
973         &self.ty
974     }
975
976     pub(super) fn iter_fields<'a>(&'a self) -> impl Iterator<Item = &'a DeconstructedPat<'a>> + 'a {
977         self.fields.iter_patterns()
978     }
979
980     /// Specialize this pattern with a constructor.
981     /// `other_ctor` can be different from `self.ctor`, but must be covered by it.
982     pub(super) fn specialize<'a>(
983         &'a self,
984         cx: &MatchCheckCtx<'_, 'p>,
985         other_ctor: &Constructor,
986     ) -> SmallVec<[&'p DeconstructedPat<'p>; 2]> {
987         match (&self.ctor, other_ctor) {
988             (Wildcard, _) => {
989                 // We return a wildcard for each field of `other_ctor`.
990                 Fields::wildcards(cx, &self.ty, other_ctor).iter_patterns().collect()
991             }
992             (Slice(self_slice), Slice(other_slice))
993                 if self_slice.arity() != other_slice.arity() =>
994             {
995                 unimplemented!()
996             }
997             _ => self.fields.iter_patterns().collect(),
998         }
999     }
1000
1001     /// We keep track for each pattern if it was ever reachable during the analysis. This is used
1002     /// with `unreachable_spans` to report unreachable subpatterns arising from or patterns.
1003     pub(super) fn set_reachable(&self) {
1004         self.reachable.set(true)
1005     }
1006     pub(super) fn is_reachable(&self) -> bool {
1007         self.reachable.get()
1008     }
1009 }
1010
1011 fn is_field_list_non_exhaustive(variant_id: VariantId, cx: &MatchCheckCtx<'_, '_>) -> bool {
1012     let attr_def_id = match variant_id {
1013         VariantId::EnumVariantId(id) => id.into(),
1014         VariantId::StructId(id) => id.into(),
1015         VariantId::UnionId(id) => id.into(),
1016     };
1017     cx.db.attrs(attr_def_id).by_key("non_exhaustive").exists()
1018 }
1019
1020 fn adt_is_box(adt: hir_def::AdtId, cx: &MatchCheckCtx<'_, '_>) -> bool {
1021     use hir_def::lang_item::LangItemTarget;
1022     match cx.db.lang_item(cx.module.krate(), SmolStr::new_inline("owned_box")) {
1023         Some(LangItemTarget::StructId(box_id)) => adt == box_id.into(),
1024         _ => false,
1025     }
1026 }