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.
6 //! There's one idea that is not detailed in [`super::usefulness`] because the details are not
7 //! needed there: _constructor splitting_.
9 //! # Constructor splitting
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:
17 //! match (0, false) {
18 //! (0 ..=100, true) => {} // `p_1`
19 //! (50..=150, false) => {} // `p_2`
20 //! (0 ..=200, _) => {} // `q`
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
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.
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.
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`].
51 use hir_def::{EnumVariantId, HasModule, LocalFieldId, VariantId};
52 use smallvec::{smallvec, SmallVec};
56 use crate::{AdtId, Interner, Scalar, Ty, TyExt, TyKind};
59 usefulness::{helper::Captures, MatchCheckCtx, PatCtxt},
63 use self::Constructor::*;
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() {
77 let mut pats = Vec::new();
78 expand(pat, &mut pats);
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 {}
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.
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>,
104 fn is_integral(ty: &Ty) -> bool {
107 TyKind::Scalar(Scalar::Char | Scalar::Int(_) | Scalar::Uint(_) | Scalar::Bool)
111 fn is_singleton(&self) -> bool {
112 self.range.start() == self.range.end()
115 fn boundaries(&self) -> (u128, u128) {
116 (*self.range.start(), *self.range.end())
120 fn from_bool(value: bool) -> IntRange {
121 let val = value as u128;
122 IntRange { range: val..=val }
126 fn from_range(lo: u128, hi: u128, scalar_ty: Scalar) -> IntRange {
128 Scalar::Bool => IntRange { range: lo..=hi },
129 _ => unimplemented!(),
133 fn is_subrange(&self, other: &Self) -> bool {
134 other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
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) })
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
152 assert!(self.is_subrange(other));
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)]
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.
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.
175 /// The following input:
177 /// |-------------------------| // `self`
178 /// |------| |----------| |----|
179 /// |-------| |-------|
181 /// would be iterated over as follows:
183 /// ||---|--||-|---|---|---|--|
185 #[derive(Debug, Clone)]
186 struct SplitIntRange {
187 /// The range we are splitting
189 /// The borders of ranges we have seen. They are all contained within `range`. This is kept
191 borders: Vec<IntBorder>,
195 fn new(range: IntRange) -> Self {
196 SplitIntRange { range, borders: Vec::new() }
200 fn to_borders(r: IntRange) -> [IntBorder; 2] {
202 let (lo, hi) = r.boundaries();
203 let lo = JustBefore(lo);
204 let hi = match hi.checked_add(1) {
205 Some(m) => JustBefore(m),
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]))
219 self.borders.extend(included_borders);
220 self.borders.sort_unstable();
223 /// Iterate over the contained ranges.
224 fn iter(&self) -> impl Iterator<Item = IntRange> + '_ {
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];
233 // End with the end of the range.
234 .chain(once(self_range[1]))
235 // List pairs of adjacent borders.
237 let ret = (prev_border, border);
238 prev_border = border;
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
255 /// A constructor for array and slice patterns.
256 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
257 pub(super) struct Slice {
258 _unimplemented: Void,
262 fn arity(self) -> usize {
266 /// See `Constructor::is_covered_by`
267 fn is_covered_by(self, _other: Self) -> bool {
268 unimplemented!() // never called as Slice contains Void
272 /// A value can be decomposed into a constructor applied to some fields. This struct represents
273 /// the constructor. See also `Fields`.
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
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.
286 Variant(EnumVariantId),
287 /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
289 /// Ranges of floating-point literal values (`2.0..=5.2`).
291 /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
293 /// Array and slice patterns.
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.
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`.
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`
305 Missing { nonexhaustive_enum_missing_real_variants: bool },
306 /// Wildcard pattern.
313 pub(super) fn is_wildcard(&self) -> bool {
314 matches!(self, Wildcard)
317 pub(super) fn is_non_exhaustive(&self) -> bool {
318 matches!(self, NonExhaustive)
321 fn as_int_range(&self) -> Option<&IntRange> {
323 IntRange(range) => Some(range),
328 fn as_slice(&self) -> Option<Slice> {
330 Slice(slice) => Some(*slice),
335 fn variant_id_for_adt(&self, adt: hir_def::AdtId) -> VariantId {
337 Variant(id) => id.into(),
339 assert!(!matches!(adt, hir_def::AdtId::EnumId(_)));
341 hir_def::AdtId::EnumId(_) => unreachable!(),
342 hir_def::AdtId::StructId(id) => id.into(),
343 hir_def::AdtId::UnionId(id) => id.into(),
346 _ => panic!("bad constructor {:?} for adt {:?}", self, adt),
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 {
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.
363 let variant = self.variant_id_for_adt(adt.0);
364 Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant).count()
368 never!("Unexpected type for `Single` constructor: {:?}", pcx.ty);
372 Slice(slice) => slice.arity(),
381 never!("The `Or` constructor doesn't have a fixed arity");
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.
395 /// See the branches for details on how the splitting is done.
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>(
402 pcx: PatCtxt<'_, '_>,
403 ctors: impl Iterator<Item = &'a Constructor> + Clone,
404 ) -> SmallVec<[Self; 1]> {
407 let mut split_wildcard = SplitWildcard::new(pcx);
408 split_wildcard.split(pcx, ctors);
409 split_wildcard.into_ctors(pcx)
411 // Fast-track if the range is trivial. In particular, we don't do the overlapping
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()
419 Slice(_) => unimplemented!(),
420 // Any other constructor can be used unchanged.
421 _ => smallvec![self.clone()],
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`.
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,
438 (Single, Single) => true,
439 (Variant(self_id), Variant(other_id)) => self_id == other_id,
441 (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range),
442 (FloatRange(..), FloatRange(..)) => {
445 (Str(..), Str(..)) => {
448 (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
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,
456 never!("trying to compare incompatible constructors {:?} and {:?}", self, other);
457 // Continue with 'whatever is covered' supposed to result in false no-error diagnostic.
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() {
471 // This must be kept in sync with `is_covered_by`.
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
478 .filter_map(|c| c.as_int_range())
479 .any(|other| range.is_covered_by(other)),
480 Slice(slice) => used_ctors
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);
494 /// A wildcard constructor that we split relative to the constructors in the matrix, as explained
495 /// at the top of the file.
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
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`.
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]>,
518 pub(super) fn new(pcx: PatCtxt<'_, '_>) -> Self {
520 let make_range = |start, end, scalar| IntRange(IntRange::from_range(start, end, scalar));
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];
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.
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);
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
546 // E.g., in an example like:
549 // let err: io::ErrorKind = ...;
551 // io::ErrorKind::NotFound => {},
555 // we don't want to show every possible IO error, but instead have only `_` as the
557 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
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;
567 if is_secretly_empty {
568 smallvec![NonExhaustive]
569 } else if is_declared_nonexhaustive {
573 .map(|(local_id, ..)| Variant(EnumVariantId { parent: enum_id, local_id }))
574 .chain(Some(NonExhaustive))
576 } else if cx.feature_exhaustive_patterns() {
577 unimplemented!() // see MatchCheckCtx.feature_exhaustive_patterns()
582 .map(|(local_id, ..)| Variant(EnumVariantId { parent: enum_id, local_id }))
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]
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],
598 SplitWildcard { matrix_ctors: Vec::new(), all_ctors }
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>(
605 pcx: PatCtxt<'_, '_>,
606 ctors: impl Iterator<Item = &'a Constructor> + Clone,
608 // Since `all_ctors` never contains wildcards, this won't recurse further.
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();
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()
619 /// Iterate over the constructors for this type that are not present in the matrix.
620 pub(super) fn iter_missing<'a, 'p>(
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))
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.
638 // If some constructors are missing, we typically want to report those constructors,
641 // enum Direction { N, S, E, W }
642 // let Direction::N = ...;
644 // we can report 3 witnesses: `S`, `E`, and `W`.
646 // However, if the user didn't actually specify a constructor
647 // in this arm, e.g., in
649 // let x: (Direction, Direction, bool) = ...;
650 // let (_, _, false) = x;
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 `_`.
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 {
662 nonexhaustive_enum_missing_real_variants: self
664 .filter(|c| !c.is_non_exhaustive())
669 Missing { nonexhaustive_enum_missing_real_variants: false }
674 return smallvec![ctor];
677 // All the constructors are present in the matrix, so we just go through them all.
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`.
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), _, _, _]`.
692 /// let x: [Option<u8>; 4] = foo();
694 /// [Some(0), ..] => {}
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>],
708 impl<'p> Fields<'p> {
710 Fields { fields: &[] }
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) }
718 pub(super) fn from_iter(
719 cx: &MatchCheckCtx<'_, 'p>,
720 fields: impl IntoIterator<Item = DeconstructedPat<'p>>,
722 let fields: &[_] = cx.pattern_arena.alloc_extend(fields);
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))
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>,
737 ) -> impl Iterator<Item = (LocalFieldId, Ty)> + Captures<'a> + Captures<'p> {
738 let (adt, substs) = ty.as_adt().unwrap();
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;
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;
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);
755 if is_uninhabited && (!is_visible || is_non_exhaustive) {
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>,
768 constructor: &Constructor,
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())
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))
784 let variant = constructor.variant_id_for_adt(adt);
785 let tys = Fields::list_variant_nonhidden_fields(cx, ty, variant)
787 Fields::wildcards_from_tys(cx, tys)
791 never!("Unexpected type for `Single` constructor: {:?}", ty_kind);
792 Fields::wildcards_from_tys(cx, once(ty.clone()))
804 | Wildcard => Fields::empty(),
806 never!("called `Fields::wildcards` on an `Or` ctor");
813 /// Returns the list of patterns.
814 pub(super) fn iter_patterns<'a>(
816 ) -> impl Iterator<Item = &'p DeconstructedPat<'p>> + Captures<'a> {
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> {
830 reachable: Cell<bool>,
833 impl<'p> DeconstructedPat<'p> {
834 pub(super) fn wildcard(ty: Ty) -> Self {
835 Self::new(Wildcard, Fields::empty(), ty)
838 pub(super) fn new(ctor: Constructor, fields: Fields<'p>, ty: Ty) -> Self {
839 DeconstructedPat { ctor, fields, ty, reachable: Cell::new(false) }
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
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())
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())
856 pub(crate) fn from_pat(cx: &MatchCheckCtx<'_, 'p>, pat: &Pat) -> Self {
857 let mkpat = |pat| DeconstructedPat::from_pat(cx, pat);
860 match pat.kind.as_ref() {
861 PatKind::Binding { subpattern: Some(subpat) } => return mkpat(subpat),
862 PatKind::Binding { subpattern: None } | PatKind::Wild => {
864 fields = Fields::empty();
866 PatKind::Deref { subpattern } => {
868 fields = Fields::singleton(cx, mkpat(subpattern));
870 PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
871 match pat.ty.kind(Interner) {
872 TyKind::Tuple(_, substs) => {
874 let mut wilds: SmallVec<[_; 2]> = substs
876 .map(|arg| arg.assert_ty_ref(Interner).clone())
877 .map(DeconstructedPat::wildcard)
879 for pat in subpatterns {
880 let idx: u32 = pat.field.into_raw().into();
881 wilds[idx as usize] = mkpat(&pat.pattern);
883 fields = Fields::from_iter(cx, wilds)
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
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.
899 subpatterns.iter().find(|pat| pat.field.into_raw() == 0u32.into());
900 let field = if let Some(pat) = pat {
903 let ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
904 DeconstructedPat::wildcard(ty)
907 fields = Fields::singleton(cx, field)
909 &TyKind::Adt(adt, _) => {
910 ctor = match pat.kind.as_ref() {
911 PatKind::Leaf { .. } => Single,
912 PatKind::Variant { enum_variant, .. } => Variant(*enum_variant),
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)
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);
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);
937 fields = Fields::from_iter(cx, wilds);
940 never!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, &pat.ty);
942 fields = Fields::empty();
946 &PatKind::LiteralBool { value } => {
947 ctor = IntRange(IntRange::from_bool(value));
948 fields = Fields::empty();
950 PatKind::Or { .. } => {
952 let pats: SmallVec<[_; 2]> = expand_or_pat(pat).into_iter().map(mkpat).collect();
953 fields = Fields::from_iter(cx, pats)
956 DeconstructedPat::new(ctor, fields, pat.ty.clone())
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() }
964 pub(super) fn is_or_pat(&self) -> bool {
965 matches!(self.ctor, Or)
968 pub(super) fn ctor(&self) -> &Constructor {
972 pub(super) fn ty(&self) -> &Ty {
976 pub(super) fn iter_fields<'a>(&'a self) -> impl Iterator<Item = &'a DeconstructedPat<'a>> + 'a {
977 self.fields.iter_patterns()
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>(
984 cx: &MatchCheckCtx<'_, 'p>,
985 other_ctor: &Constructor,
986 ) -> SmallVec<[&'p DeconstructedPat<'p>; 2]> {
987 match (&self.ctor, other_ctor) {
989 // We return a wildcard for each field of `other_ctor`.
990 Fields::wildcards(cx, &self.ty, other_ctor).iter_patterns().collect()
992 (Slice(self_slice), Slice(other_slice))
993 if self_slice.arity() != other_slice.arity() =>
997 _ => self.fields.iter_patterns().collect(),
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)
1006 pub(super) fn is_reachable(&self) -> bool {
1007 self.reachable.get()
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(),
1017 cx.db.attrs(attr_def_id).by_key("non_exhaustive").exists()
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(),