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