]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/diagnostics/match_check/deconstruct_pat.rs
internal: Normalize field type after substituting
[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::{infer::normalize, 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     pub(super) fn is_unstable_variant(&self, _pcx: PatCtxt<'_, '_>) -> bool {
336         false //FIXME: implement this
337     }
338
339     pub(super) fn is_doc_hidden_variant(&self, _pcx: PatCtxt<'_, '_>) -> bool {
340         false //FIXME: implement this
341     }
342
343     fn variant_id_for_adt(&self, adt: hir_def::AdtId) -> VariantId {
344         match *self {
345             Variant(id) => id.into(),
346             Single => {
347                 assert!(!matches!(adt, hir_def::AdtId::EnumId(_)));
348                 match adt {
349                     hir_def::AdtId::EnumId(_) => unreachable!(),
350                     hir_def::AdtId::StructId(id) => id.into(),
351                     hir_def::AdtId::UnionId(id) => id.into(),
352                 }
353             }
354             _ => panic!("bad constructor {:?} for adt {:?}", self, adt),
355         }
356     }
357
358     /// The number of fields for this constructor. This must be kept in sync with
359     /// `Fields::wildcards`.
360     pub(super) fn arity(&self, pcx: PatCtxt<'_, '_>) -> usize {
361         match self {
362             Single | Variant(_) => match *pcx.ty.kind(Interner) {
363                 TyKind::Tuple(arity, ..) => arity,
364                 TyKind::Ref(..) => 1,
365                 TyKind::Adt(adt, ..) => {
366                     if adt_is_box(adt.0, pcx.cx) {
367                         // The only legal patterns of type `Box` (outside `std`) are `_` and box
368                         // patterns. If we're here we can assume this is a box pattern.
369                         1
370                     } else {
371                         let variant = self.variant_id_for_adt(adt.0);
372                         Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant).count()
373                     }
374                 }
375                 _ => {
376                     never!("Unexpected type for `Single` constructor: {:?}", pcx.ty);
377                     0
378                 }
379             },
380             Slice(slice) => slice.arity(),
381             Str(..)
382             | FloatRange(..)
383             | IntRange(..)
384             | NonExhaustive
385             | Opaque
386             | Missing { .. }
387             | Wildcard => 0,
388             Or => {
389                 never!("The `Or` constructor doesn't have a fixed arity");
390                 0
391             }
392         }
393     }
394
395     /// Some constructors (namely `Wildcard`, `IntRange` and `Slice`) actually stand for a set of actual
396     /// constructors (like variants, integers or fixed-sized slices). When specializing for these
397     /// constructors, we want to be specialising for the actual underlying constructors.
398     /// Naively, we would simply return the list of constructors they correspond to. We instead are
399     /// more clever: if there are constructors that we know will behave the same wrt the current
400     /// matrix, we keep them grouped. For example, all slices of a sufficiently large length
401     /// will either be all useful or all non-useful with a given matrix.
402     ///
403     /// See the branches for details on how the splitting is done.
404     ///
405     /// This function may discard some irrelevant constructors if this preserves behavior and
406     /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the
407     /// matrix, unless all of them are.
408     pub(super) fn split<'a>(
409         &self,
410         pcx: PatCtxt<'_, '_>,
411         ctors: impl Iterator<Item = &'a Constructor> + Clone,
412     ) -> SmallVec<[Self; 1]> {
413         match self {
414             Wildcard => {
415                 let mut split_wildcard = SplitWildcard::new(pcx);
416                 split_wildcard.split(pcx, ctors);
417                 split_wildcard.into_ctors(pcx)
418             }
419             // Fast-track if the range is trivial. In particular, we don't do the overlapping
420             // ranges check.
421             IntRange(ctor_range) if !ctor_range.is_singleton() => {
422                 let mut split_range = SplitIntRange::new(ctor_range.clone());
423                 let int_ranges = ctors.filter_map(|ctor| ctor.as_int_range());
424                 split_range.split(int_ranges.cloned());
425                 split_range.iter().map(IntRange).collect()
426             }
427             Slice(_) => unimplemented!(),
428             // Any other constructor can be used unchanged.
429             _ => smallvec![self.clone()],
430         }
431     }
432
433     /// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`.
434     /// For the simple cases, this is simply checking for equality. For the "grouped" constructors,
435     /// this checks for inclusion.
436     // We inline because this has a single call site in `Matrix::specialize_constructor`.
437     #[inline]
438     pub(super) fn is_covered_by(&self, _pcx: PatCtxt<'_, '_>, other: &Self) -> bool {
439         // This must be kept in sync with `is_covered_by_any`.
440         match (self, other) {
441             // Wildcards cover anything
442             (_, Wildcard) => true,
443             // The missing ctors are not covered by anything in the matrix except wildcards.
444             (Missing { .. } | Wildcard, _) => false,
445
446             (Single, Single) => true,
447             (Variant(self_id), Variant(other_id)) => self_id == other_id,
448
449             (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range),
450             (FloatRange(..), FloatRange(..)) => {
451                 unimplemented!()
452             }
453             (Str(..), Str(..)) => {
454                 unimplemented!()
455             }
456             (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
457
458             // We are trying to inspect an opaque constant. Thus we skip the row.
459             (Opaque, _) | (_, Opaque) => false,
460             // Only a wildcard pattern can match the special extra constructor.
461             (NonExhaustive, _) => false,
462
463             _ => {
464                 never!("trying to compare incompatible constructors {:?} and {:?}", self, other);
465                 // Continue with 'whatever is covered' supposed to result in false no-error diagnostic.
466                 true
467             }
468         }
469     }
470
471     /// Faster version of `is_covered_by` when applied to many constructors. `used_ctors` is
472     /// assumed to be built from `matrix.head_ctors()` with wildcards filtered out, and `self` is
473     /// assumed to have been split from a wildcard.
474     fn is_covered_by_any(&self, _pcx: PatCtxt<'_, '_>, used_ctors: &[Constructor]) -> bool {
475         if used_ctors.is_empty() {
476             return false;
477         }
478
479         // This must be kept in sync with `is_covered_by`.
480         match self {
481             // If `self` is `Single`, `used_ctors` cannot contain anything else than `Single`s.
482             Single => !used_ctors.is_empty(),
483             Variant(_) => used_ctors.iter().any(|c| c == self),
484             IntRange(range) => used_ctors
485                 .iter()
486                 .filter_map(|c| c.as_int_range())
487                 .any(|other| range.is_covered_by(other)),
488             Slice(slice) => used_ctors
489                 .iter()
490                 .filter_map(|c| c.as_slice())
491                 .any(|other| slice.is_covered_by(other)),
492             // This constructor is never covered by anything else
493             NonExhaustive => false,
494             Str(..) | FloatRange(..) | Opaque | Missing { .. } | Wildcard | Or => {
495                 never!("found unexpected ctor in all_ctors: {:?}", self);
496                 true
497             }
498         }
499     }
500 }
501
502 /// A wildcard constructor that we split relative to the constructors in the matrix, as explained
503 /// at the top of the file.
504 ///
505 /// A constructor that is not present in the matrix rows will only be covered by the rows that have
506 /// wildcards. Thus we can group all of those constructors together; we call them "missing
507 /// constructors". Splitting a wildcard would therefore list all present constructors individually
508 /// (or grouped if they are integers or slices), and then all missing constructors together as a
509 /// group.
510 ///
511 /// However we can go further: since any constructor will match the wildcard rows, and having more
512 /// rows can only reduce the amount of usefulness witnesses, we can skip the present constructors
513 /// and only try the missing ones.
514 /// This will not preserve the whole list of witnesses, but will preserve whether the list is empty
515 /// or not. In fact this is quite natural from the point of view of diagnostics too. This is done
516 /// in `to_ctors`: in some cases we only return `Missing`.
517 #[derive(Debug)]
518 pub(super) struct SplitWildcard {
519     /// Constructors seen in the matrix.
520     matrix_ctors: Vec<Constructor>,
521     /// All the constructors for this type
522     all_ctors: SmallVec<[Constructor; 1]>,
523 }
524
525 impl SplitWildcard {
526     pub(super) fn new(pcx: PatCtxt<'_, '_>) -> Self {
527         let cx = pcx.cx;
528         let make_range = |start, end, scalar| IntRange(IntRange::from_range(start, end, scalar));
529
530         // Unhandled types are treated as non-exhaustive. Being explicit here instead of falling
531         // to catchall arm to ease further implementation.
532         let unhandled = || smallvec![NonExhaustive];
533
534         // This determines the set of all possible constructors for the type `pcx.ty`. For numbers,
535         // arrays and slices we use ranges and variable-length slices when appropriate.
536         //
537         // If the `exhaustive_patterns` feature is enabled, we make sure to omit constructors that
538         // are statically impossible. E.g., for `Option<!>`, we do not include `Some(_)` in the
539         // returned list of constructors.
540         // Invariant: this is empty if and only if the type is uninhabited (as determined by
541         // `cx.is_uninhabited()`).
542         let all_ctors = match pcx.ty.kind(Interner) {
543             TyKind::Scalar(Scalar::Bool) => smallvec![make_range(0, 1, Scalar::Bool)],
544             // TyKind::Array(..) if ... => unhandled(),
545             TyKind::Array(..) | TyKind::Slice(..) => unhandled(),
546             &TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ..) => {
547                 let enum_data = cx.db.enum_data(enum_id);
548
549                 // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
550                 // additional "unknown" constructor.
551                 // There is no point in enumerating all possible variants, because the user can't
552                 // actually match against them all themselves. So we always return only the fictitious
553                 // constructor.
554                 // E.g., in an example like:
555                 //
556                 // ```
557                 //     let err: io::ErrorKind = ...;
558                 //     match err {
559                 //         io::ErrorKind::NotFound => {},
560                 //     }
561                 // ```
562                 //
563                 // we don't want to show every possible IO error, but instead have only `_` as the
564                 // witness.
565                 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
566
567                 let is_exhaustive_pat_feature = cx.feature_exhaustive_patterns();
568
569                 // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
570                 // as though it had an "unknown" constructor to avoid exposing its emptiness. The
571                 // exception is if the pattern is at the top level, because we want empty matches to be
572                 // considered exhaustive.
573                 let is_secretly_empty = enum_data.variants.is_empty()
574                     && !is_exhaustive_pat_feature
575                     && !pcx.is_top_level;
576
577                 let mut ctors: SmallVec<[_; 1]> = enum_data
578                     .variants
579                     .iter()
580                     .filter(|&(_, _v)| {
581                         // If `exhaustive_patterns` is enabled, we exclude variants known to be
582                         // uninhabited.
583                         let is_uninhabited = is_exhaustive_pat_feature
584                             && unimplemented!("after MatchCheckCtx.feature_exhaustive_patterns()");
585                         !is_uninhabited
586                     })
587                     .map(|(local_id, _)| Variant(EnumVariantId { parent: enum_id, local_id }))
588                     .collect();
589
590                 if is_secretly_empty || is_declared_nonexhaustive {
591                     ctors.push(NonExhaustive);
592                 }
593                 ctors
594             }
595             TyKind::Scalar(Scalar::Char) => unhandled(),
596             TyKind::Scalar(Scalar::Int(..) | Scalar::Uint(..)) => unhandled(),
597             TyKind::Never if !cx.feature_exhaustive_patterns() && !pcx.is_top_level => {
598                 smallvec![NonExhaustive]
599             }
600             TyKind::Never => SmallVec::new(),
601             _ if cx.is_uninhabited(pcx.ty) => SmallVec::new(),
602             TyKind::Adt(..) | TyKind::Tuple(..) | TyKind::Ref(..) => smallvec![Single],
603             // This type is one for which we cannot list constructors, like `str` or `f64`.
604             _ => smallvec![NonExhaustive],
605         };
606
607         SplitWildcard { matrix_ctors: Vec::new(), all_ctors }
608     }
609
610     /// Pass a set of constructors relative to which to split this one. Don't call twice, it won't
611     /// do what you want.
612     pub(super) fn split<'a>(
613         &mut self,
614         pcx: PatCtxt<'_, '_>,
615         ctors: impl Iterator<Item = &'a Constructor> + Clone,
616     ) {
617         // Since `all_ctors` never contains wildcards, this won't recurse further.
618         self.all_ctors =
619             self.all_ctors.iter().flat_map(|ctor| ctor.split(pcx, ctors.clone())).collect();
620         self.matrix_ctors = ctors.filter(|c| !c.is_wildcard()).cloned().collect();
621     }
622
623     /// Whether there are any value constructors for this type that are not present in the matrix.
624     fn any_missing(&self, pcx: PatCtxt<'_, '_>) -> bool {
625         self.iter_missing(pcx).next().is_some()
626     }
627
628     /// Iterate over the constructors for this type that are not present in the matrix.
629     pub(super) fn iter_missing<'a, 'p>(
630         &'a self,
631         pcx: PatCtxt<'a, 'p>,
632     ) -> impl Iterator<Item = &'a Constructor> + Captures<'p> {
633         self.all_ctors.iter().filter(move |ctor| !ctor.is_covered_by_any(pcx, &self.matrix_ctors))
634     }
635
636     /// Return the set of constructors resulting from splitting the wildcard. As explained at the
637     /// top of the file, if any constructors are missing we can ignore the present ones.
638     fn into_ctors(self, pcx: PatCtxt<'_, '_>) -> SmallVec<[Constructor; 1]> {
639         if self.any_missing(pcx) {
640             // Some constructors are missing, thus we can specialize with the special `Missing`
641             // constructor, which stands for those constructors that are not seen in the matrix,
642             // and matches the same rows as any of them (namely the wildcard rows). See the top of
643             // the file for details.
644             // However, when all constructors are missing we can also specialize with the full
645             // `Wildcard` constructor. The difference will depend on what we want in diagnostics.
646
647             // If some constructors are missing, we typically want to report those constructors,
648             // e.g.:
649             // ```
650             //     enum Direction { N, S, E, W }
651             //     let Direction::N = ...;
652             // ```
653             // we can report 3 witnesses: `S`, `E`, and `W`.
654             //
655             // However, if the user didn't actually specify a constructor
656             // in this arm, e.g., in
657             // ```
658             //     let x: (Direction, Direction, bool) = ...;
659             //     let (_, _, false) = x;
660             // ```
661             // we don't want to show all 16 possible witnesses `(<direction-1>, <direction-2>,
662             // true)` - we are satisfied with `(_, _, true)`. So if all constructors are missing we
663             // prefer to report just a wildcard `_`.
664             //
665             // The exception is: if we are at the top-level, for example in an empty match, we
666             // sometimes prefer reporting the list of constructors instead of just `_`.
667             let report_when_all_missing = pcx.is_top_level && !IntRange::is_integral(pcx.ty);
668             let ctor = if !self.matrix_ctors.is_empty() || report_when_all_missing {
669                 if pcx.is_non_exhaustive {
670                     Missing {
671                         nonexhaustive_enum_missing_real_variants: self
672                             .iter_missing(pcx)
673                             .any(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx))),
674                     }
675                 } else {
676                     Missing { nonexhaustive_enum_missing_real_variants: false }
677                 }
678             } else {
679                 Wildcard
680             };
681             return smallvec![ctor];
682         }
683
684         // All the constructors are present in the matrix, so we just go through them all.
685         self.all_ctors
686     }
687 }
688
689 /// A value can be decomposed into a constructor applied to some fields. This struct represents
690 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
691 ///
692 /// This is constructed for a constructor using [`Fields::wildcards()`]. The idea is that
693 /// [`Fields::wildcards()`] constructs a list of fields where all entries are wildcards, and then
694 /// given a pattern we fill some of the fields with its subpatterns.
695 /// In the following example `Fields::wildcards` returns `[_, _, _, _]`. Then in
696 /// `extract_pattern_arguments` we fill some of the entries, and the result is
697 /// `[Some(0), _, _, _]`.
698 /// ```rust
699 /// let x: [Option<u8>; 4] = foo();
700 /// match x {
701 ///     [Some(0), ..] => {}
702 /// }
703 /// ```
704 ///
705 /// Note that the number of fields of a constructor may not match the fields declared in the
706 /// original struct/variant. This happens if a private or `non_exhaustive` field is uninhabited,
707 /// because the code mustn't observe that it is uninhabited. In that case that field is not
708 /// included in `fields`. For that reason, when you have a `mir::Field` you must use
709 /// `index_with_declared_idx`.
710 #[derive(Clone, Copy)]
711 pub(super) struct Fields<'p> {
712     fields: &'p [DeconstructedPat<'p>],
713 }
714
715 impl<'p> Fields<'p> {
716     fn empty() -> Self {
717         Fields { fields: &[] }
718     }
719
720     fn singleton(cx: &MatchCheckCtx<'_, 'p>, field: DeconstructedPat<'p>) -> Self {
721         let field = cx.pattern_arena.alloc(field);
722         Fields { fields: std::slice::from_ref(field) }
723     }
724
725     pub(super) fn from_iter(
726         cx: &MatchCheckCtx<'_, 'p>,
727         fields: impl IntoIterator<Item = DeconstructedPat<'p>>,
728     ) -> Self {
729         let fields: &[_] = cx.pattern_arena.alloc_extend(fields);
730         Fields { fields }
731     }
732
733     fn wildcards_from_tys(cx: &MatchCheckCtx<'_, 'p>, tys: impl IntoIterator<Item = Ty>) -> Self {
734         Fields::from_iter(cx, tys.into_iter().map(DeconstructedPat::wildcard))
735     }
736
737     // In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide
738     // uninhabited fields in order not to reveal the uninhabitedness of the whole variant.
739     // This lists the fields we keep along with their types.
740     fn list_variant_nonhidden_fields<'a>(
741         cx: &'a MatchCheckCtx<'a, 'p>,
742         ty: &'a Ty,
743         variant: VariantId,
744     ) -> impl Iterator<Item = (LocalFieldId, Ty)> + Captures<'a> + Captures<'p> {
745         let (adt, substs) = ty.as_adt().unwrap();
746
747         let adt_is_local = variant.module(cx.db.upcast()).krate() == cx.module.krate();
748         // Whether we must not match the fields of this variant exhaustively.
749         let is_non_exhaustive = is_field_list_non_exhaustive(variant, cx) && !adt_is_local;
750
751         let visibility = cx.db.field_visibilities(variant);
752         let field_ty = cx.db.field_types(variant);
753         let fields_len = variant.variant_data(cx.db.upcast()).fields().len() as u32;
754
755         (0..fields_len).map(|idx| LocalFieldId::from_raw(idx.into())).filter_map(move |fid| {
756             let ty = field_ty[fid].clone().substitute(Interner, substs);
757             let ty = normalize(cx.db, cx.body, ty);
758             let is_visible = matches!(adt, hir_def::AdtId::EnumId(..))
759                 || visibility[fid].is_visible_from(cx.db.upcast(), cx.module);
760             let is_uninhabited = cx.is_uninhabited(&ty);
761
762             if is_uninhabited && (!is_visible || is_non_exhaustive) {
763                 None
764             } else {
765                 Some((fid, ty))
766             }
767         })
768     }
769
770     /// Creates a new list of wildcard fields for a given constructor. The result must have a
771     /// length of `constructor.arity()`.
772     pub(crate) fn wildcards(
773         cx: &MatchCheckCtx<'_, 'p>,
774         ty: &Ty,
775         constructor: &Constructor,
776     ) -> Self {
777         let ret = match constructor {
778             Single | Variant(_) => match ty.kind(Interner) {
779                 TyKind::Tuple(_, substs) => {
780                     let tys = substs.iter(Interner).map(|ty| ty.assert_ty_ref(Interner));
781                     Fields::wildcards_from_tys(cx, tys.cloned())
782                 }
783                 TyKind::Ref(.., rty) => Fields::wildcards_from_tys(cx, once(rty.clone())),
784                 &TyKind::Adt(AdtId(adt), ref substs) => {
785                     if adt_is_box(adt, cx) {
786                         // The only legal patterns of type `Box` (outside `std`) are `_` and box
787                         // patterns. If we're here we can assume this is a box pattern.
788                         let subst_ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
789                         Fields::wildcards_from_tys(cx, once(subst_ty))
790                     } else {
791                         let variant = constructor.variant_id_for_adt(adt);
792                         let tys = Fields::list_variant_nonhidden_fields(cx, ty, variant)
793                             .map(|(_, ty)| ty);
794                         Fields::wildcards_from_tys(cx, tys)
795                     }
796                 }
797                 ty_kind => {
798                     never!("Unexpected type for `Single` constructor: {:?}", ty_kind);
799                     Fields::wildcards_from_tys(cx, once(ty.clone()))
800                 }
801             },
802             Slice(..) => {
803                 unimplemented!()
804             }
805             Str(..)
806             | FloatRange(..)
807             | IntRange(..)
808             | NonExhaustive
809             | Opaque
810             | Missing { .. }
811             | Wildcard => Fields::empty(),
812             Or => {
813                 never!("called `Fields::wildcards` on an `Or` ctor");
814                 Fields::empty()
815             }
816         };
817         ret
818     }
819
820     /// Returns the list of patterns.
821     pub(super) fn iter_patterns<'a>(
822         &'a self,
823     ) -> impl Iterator<Item = &'p DeconstructedPat<'p>> + Captures<'a> {
824         self.fields.iter()
825     }
826 }
827
828 /// Values and patterns can be represented as a constructor applied to some fields. This represents
829 /// a pattern in this form.
830 /// This also keeps track of whether the pattern has been found reachable during analysis. For this
831 /// reason we should be careful not to clone patterns for which we care about that. Use
832 /// `clone_and_forget_reachability` if you're sure.
833 pub(crate) struct DeconstructedPat<'p> {
834     ctor: Constructor,
835     fields: Fields<'p>,
836     ty: Ty,
837     reachable: Cell<bool>,
838 }
839
840 impl<'p> DeconstructedPat<'p> {
841     pub(super) fn wildcard(ty: Ty) -> Self {
842         Self::new(Wildcard, Fields::empty(), ty)
843     }
844
845     pub(super) fn new(ctor: Constructor, fields: Fields<'p>, ty: Ty) -> Self {
846         DeconstructedPat { ctor, fields, ty, reachable: Cell::new(false) }
847     }
848
849     /// Construct a pattern that matches everything that starts with this constructor.
850     /// For example, if `ctor` is a `Constructor::Variant` for `Option::Some`, we get the pattern
851     /// `Some(_)`.
852     pub(super) fn wild_from_ctor(pcx: PatCtxt<'_, 'p>, ctor: Constructor) -> Self {
853         let fields = Fields::wildcards(pcx.cx, pcx.ty, &ctor);
854         DeconstructedPat::new(ctor, fields, pcx.ty.clone())
855     }
856
857     /// Clone this value. This method emphasizes that cloning loses reachability information and
858     /// should be done carefully.
859     pub(super) fn clone_and_forget_reachability(&self) -> Self {
860         DeconstructedPat::new(self.ctor.clone(), self.fields, self.ty.clone())
861     }
862
863     pub(crate) fn from_pat(cx: &MatchCheckCtx<'_, 'p>, pat: &Pat) -> Self {
864         let mkpat = |pat| DeconstructedPat::from_pat(cx, pat);
865         let ctor;
866         let fields;
867         match pat.kind.as_ref() {
868             PatKind::Binding { subpattern: Some(subpat) } => return mkpat(subpat),
869             PatKind::Binding { subpattern: None } | PatKind::Wild => {
870                 ctor = Wildcard;
871                 fields = Fields::empty();
872             }
873             PatKind::Deref { subpattern } => {
874                 ctor = Single;
875                 fields = Fields::singleton(cx, mkpat(subpattern));
876             }
877             PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
878                 match pat.ty.kind(Interner) {
879                     TyKind::Tuple(_, substs) => {
880                         ctor = Single;
881                         let mut wilds: SmallVec<[_; 2]> = substs
882                             .iter(Interner)
883                             .map(|arg| arg.assert_ty_ref(Interner).clone())
884                             .map(DeconstructedPat::wildcard)
885                             .collect();
886                         for pat in subpatterns {
887                             let idx: u32 = pat.field.into_raw().into();
888                             wilds[idx as usize] = mkpat(&pat.pattern);
889                         }
890                         fields = Fields::from_iter(cx, wilds)
891                     }
892                     TyKind::Adt(adt, substs) if adt_is_box(adt.0, cx) => {
893                         // The only legal patterns of type `Box` (outside `std`) are `_` and box
894                         // patterns. If we're here we can assume this is a box pattern.
895                         // FIXME(Nadrieril): A `Box` can in theory be matched either with `Box(_,
896                         // _)` or a box pattern. As a hack to avoid an ICE with the former, we
897                         // ignore other fields than the first one. This will trigger an error later
898                         // anyway.
899                         // See https://github.com/rust-lang/rust/issues/82772 ,
900                         // explanation: https://github.com/rust-lang/rust/pull/82789#issuecomment-796921977
901                         // The problem is that we can't know from the type whether we'll match
902                         // normally or through box-patterns. We'll have to figure out a proper
903                         // solution when we introduce generalized deref patterns. Also need to
904                         // prevent mixing of those two options.
905                         let pat =
906                             subpatterns.iter().find(|pat| pat.field.into_raw() == 0u32.into());
907                         let field = if let Some(pat) = pat {
908                             mkpat(&pat.pattern)
909                         } else {
910                             let ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
911                             DeconstructedPat::wildcard(ty)
912                         };
913                         ctor = Single;
914                         fields = Fields::singleton(cx, field)
915                     }
916                     &TyKind::Adt(adt, _) => {
917                         ctor = match pat.kind.as_ref() {
918                             PatKind::Leaf { .. } => Single,
919                             PatKind::Variant { enum_variant, .. } => Variant(*enum_variant),
920                             _ => {
921                                 never!();
922                                 Wildcard
923                             }
924                         };
925                         let variant = ctor.variant_id_for_adt(adt.0);
926                         let fields_len = variant.variant_data(cx.db.upcast()).fields().len();
927                         // For each field in the variant, we store the relevant index into `self.fields` if any.
928                         let mut field_id_to_id: Vec<Option<usize>> = vec![None; fields_len];
929                         let tys = Fields::list_variant_nonhidden_fields(cx, &pat.ty, variant)
930                             .enumerate()
931                             .map(|(i, (fid, ty))| {
932                                 let field_idx: u32 = fid.into_raw().into();
933                                 field_id_to_id[field_idx as usize] = Some(i);
934                                 ty
935                             });
936                         let mut wilds: SmallVec<[_; 2]> =
937                             tys.map(DeconstructedPat::wildcard).collect();
938                         for pat in subpatterns {
939                             let field_idx: u32 = pat.field.into_raw().into();
940                             if let Some(i) = field_id_to_id[field_idx as usize] {
941                                 wilds[i] = mkpat(&pat.pattern);
942                             }
943                         }
944                         fields = Fields::from_iter(cx, wilds);
945                     }
946                     _ => {
947                         never!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, &pat.ty);
948                         ctor = Wildcard;
949                         fields = Fields::empty();
950                     }
951                 }
952             }
953             &PatKind::LiteralBool { value } => {
954                 ctor = IntRange(IntRange::from_bool(value));
955                 fields = Fields::empty();
956             }
957             PatKind::Or { .. } => {
958                 ctor = Or;
959                 let pats: SmallVec<[_; 2]> = expand_or_pat(pat).into_iter().map(mkpat).collect();
960                 fields = Fields::from_iter(cx, pats)
961             }
962         }
963         DeconstructedPat::new(ctor, fields, pat.ty.clone())
964     }
965
966     // // FIXME(iDawer): implement reporting of noncovered patterns
967     // pub(crate) fn to_pat(&self, _cx: &MatchCheckCtx<'_, 'p>) -> Pat {
968     //     Pat { ty: self.ty.clone(), kind: PatKind::Wild.into() }
969     // }
970
971     pub(super) fn is_or_pat(&self) -> bool {
972         matches!(self.ctor, Or)
973     }
974
975     pub(super) fn ctor(&self) -> &Constructor {
976         &self.ctor
977     }
978
979     pub(super) fn ty(&self) -> &Ty {
980         &self.ty
981     }
982
983     pub(super) fn iter_fields<'a>(&'a self) -> impl Iterator<Item = &'a DeconstructedPat<'a>> + 'a {
984         self.fields.iter_patterns()
985     }
986
987     /// Specialize this pattern with a constructor.
988     /// `other_ctor` can be different from `self.ctor`, but must be covered by it.
989     pub(super) fn specialize<'a>(
990         &'a self,
991         cx: &MatchCheckCtx<'_, 'p>,
992         other_ctor: &Constructor,
993     ) -> SmallVec<[&'p DeconstructedPat<'p>; 2]> {
994         match (&self.ctor, other_ctor) {
995             (Wildcard, _) => {
996                 // We return a wildcard for each field of `other_ctor`.
997                 Fields::wildcards(cx, &self.ty, other_ctor).iter_patterns().collect()
998             }
999             (Slice(self_slice), Slice(other_slice))
1000                 if self_slice.arity() != other_slice.arity() =>
1001             {
1002                 unimplemented!()
1003             }
1004             _ => self.fields.iter_patterns().collect(),
1005         }
1006     }
1007
1008     /// We keep track for each pattern if it was ever reachable during the analysis. This is used
1009     /// with `unreachable_spans` to report unreachable subpatterns arising from or patterns.
1010     pub(super) fn set_reachable(&self) {
1011         self.reachable.set(true)
1012     }
1013     pub(super) fn is_reachable(&self) -> bool {
1014         self.reachable.get()
1015     }
1016 }
1017
1018 fn is_field_list_non_exhaustive(variant_id: VariantId, cx: &MatchCheckCtx<'_, '_>) -> bool {
1019     let attr_def_id = match variant_id {
1020         VariantId::EnumVariantId(id) => id.into(),
1021         VariantId::StructId(id) => id.into(),
1022         VariantId::UnionId(id) => id.into(),
1023     };
1024     cx.db.attrs(attr_def_id).by_key("non_exhaustive").exists()
1025 }
1026
1027 fn adt_is_box(adt: hir_def::AdtId, cx: &MatchCheckCtx<'_, '_>) -> bool {
1028     use hir_def::lang_item::LangItemTarget;
1029     match cx.db.lang_item(cx.module.krate(), SmolStr::new_inline("owned_box")) {
1030         Some(LangItemTarget::StructId(box_id)) => adt == box_id.into(),
1031         _ => false,
1032     }
1033 }