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::{infer::normalize, 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 pub(super) fn is_unstable_variant(&self, _pcx: PatCtxt<'_, '_>) -> bool {
336 false //FIXME: implement this
339 pub(super) fn is_doc_hidden_variant(&self, _pcx: PatCtxt<'_, '_>) -> bool {
340 false //FIXME: implement this
343 fn variant_id_for_adt(&self, adt: hir_def::AdtId) -> VariantId {
345 Variant(id) => id.into(),
347 assert!(!matches!(adt, hir_def::AdtId::EnumId(_)));
349 hir_def::AdtId::EnumId(_) => unreachable!(),
350 hir_def::AdtId::StructId(id) => id.into(),
351 hir_def::AdtId::UnionId(id) => id.into(),
354 _ => panic!("bad constructor {:?} for adt {:?}", self, adt),
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 {
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.
371 let variant = self.variant_id_for_adt(adt.0);
372 Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant).count()
376 never!("Unexpected type for `Single` constructor: {:?}", pcx.ty);
380 Slice(slice) => slice.arity(),
389 never!("The `Or` constructor doesn't have a fixed arity");
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.
403 /// See the branches for details on how the splitting is done.
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>(
410 pcx: PatCtxt<'_, '_>,
411 ctors: impl Iterator<Item = &'a Constructor> + Clone,
412 ) -> SmallVec<[Self; 1]> {
415 let mut split_wildcard = SplitWildcard::new(pcx);
416 split_wildcard.split(pcx, ctors);
417 split_wildcard.into_ctors(pcx)
419 // Fast-track if the range is trivial. In particular, we don't do the overlapping
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()
427 Slice(_) => unimplemented!(),
428 // Any other constructor can be used unchanged.
429 _ => smallvec![self.clone()],
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`.
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,
446 (Single, Single) => true,
447 (Variant(self_id), Variant(other_id)) => self_id == other_id,
449 (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range),
450 (FloatRange(..), FloatRange(..)) => {
453 (Str(..), Str(..)) => {
456 (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
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,
464 never!("trying to compare incompatible constructors {:?} and {:?}", self, other);
465 // Continue with 'whatever is covered' supposed to result in false no-error diagnostic.
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() {
479 // This must be kept in sync with `is_covered_by`.
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
486 .filter_map(|c| c.as_int_range())
487 .any(|other| range.is_covered_by(other)),
488 Slice(slice) => used_ctors
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);
502 /// A wildcard constructor that we split relative to the constructors in the matrix, as explained
503 /// at the top of the file.
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
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`.
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]>,
526 pub(super) fn new(pcx: PatCtxt<'_, '_>) -> Self {
528 let make_range = |start, end, scalar| IntRange(IntRange::from_range(start, end, scalar));
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];
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.
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);
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
554 // E.g., in an example like:
557 // let err: io::ErrorKind = ...;
559 // io::ErrorKind::NotFound => {},
563 // we don't want to show every possible IO error, but instead have only `_` as the
565 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
567 let is_exhaustive_pat_feature = cx.feature_exhaustive_patterns();
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;
577 let mut ctors: SmallVec<[_; 1]> = enum_data
581 // If `exhaustive_patterns` is enabled, we exclude variants known to be
583 let is_uninhabited = is_exhaustive_pat_feature
584 && unimplemented!("after MatchCheckCtx.feature_exhaustive_patterns()");
587 .map(|(local_id, _)| Variant(EnumVariantId { parent: enum_id, local_id }))
590 if is_secretly_empty || is_declared_nonexhaustive {
591 ctors.push(NonExhaustive);
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]
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],
607 SplitWildcard { matrix_ctors: Vec::new(), all_ctors }
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>(
614 pcx: PatCtxt<'_, '_>,
615 ctors: impl Iterator<Item = &'a Constructor> + Clone,
617 // Since `all_ctors` never contains wildcards, this won't recurse further.
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();
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()
628 /// Iterate over the constructors for this type that are not present in the matrix.
629 pub(super) fn iter_missing<'a, 'p>(
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))
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.
647 // If some constructors are missing, we typically want to report those constructors,
650 // enum Direction { N, S, E, W }
651 // let Direction::N = ...;
653 // we can report 3 witnesses: `S`, `E`, and `W`.
655 // However, if the user didn't actually specify a constructor
656 // in this arm, e.g., in
658 // let x: (Direction, Direction, bool) = ...;
659 // let (_, _, false) = x;
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 `_`.
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 {
671 nonexhaustive_enum_missing_real_variants: self
673 .any(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx))),
676 Missing { nonexhaustive_enum_missing_real_variants: false }
681 return smallvec![ctor];
684 // All the constructors are present in the matrix, so we just go through them all.
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`.
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), _, _, _]`.
699 /// let x: [Option<u8>; 4] = foo();
701 /// [Some(0), ..] => {}
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>],
715 impl<'p> Fields<'p> {
717 Fields { fields: &[] }
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) }
725 pub(super) fn from_iter(
726 cx: &MatchCheckCtx<'_, 'p>,
727 fields: impl IntoIterator<Item = DeconstructedPat<'p>>,
729 let fields: &[_] = cx.pattern_arena.alloc_extend(fields);
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))
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>,
744 ) -> impl Iterator<Item = (LocalFieldId, Ty)> + Captures<'a> + Captures<'p> {
745 let (adt, substs) = ty.as_adt().unwrap();
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;
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;
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);
762 if is_uninhabited && (!is_visible || is_non_exhaustive) {
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>,
775 constructor: &Constructor,
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())
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))
791 let variant = constructor.variant_id_for_adt(adt);
792 let tys = Fields::list_variant_nonhidden_fields(cx, ty, variant)
794 Fields::wildcards_from_tys(cx, tys)
798 never!("Unexpected type for `Single` constructor: {:?}", ty_kind);
799 Fields::wildcards_from_tys(cx, once(ty.clone()))
811 | Wildcard => Fields::empty(),
813 never!("called `Fields::wildcards` on an `Or` ctor");
820 /// Returns the list of patterns.
821 pub(super) fn iter_patterns<'a>(
823 ) -> impl Iterator<Item = &'p DeconstructedPat<'p>> + Captures<'a> {
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> {
837 reachable: Cell<bool>,
840 impl<'p> DeconstructedPat<'p> {
841 pub(super) fn wildcard(ty: Ty) -> Self {
842 Self::new(Wildcard, Fields::empty(), ty)
845 pub(super) fn new(ctor: Constructor, fields: Fields<'p>, ty: Ty) -> Self {
846 DeconstructedPat { ctor, fields, ty, reachable: Cell::new(false) }
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
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())
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())
863 pub(crate) fn from_pat(cx: &MatchCheckCtx<'_, 'p>, pat: &Pat) -> Self {
864 let mkpat = |pat| DeconstructedPat::from_pat(cx, pat);
867 match pat.kind.as_ref() {
868 PatKind::Binding { subpattern: Some(subpat) } => return mkpat(subpat),
869 PatKind::Binding { subpattern: None } | PatKind::Wild => {
871 fields = Fields::empty();
873 PatKind::Deref { subpattern } => {
875 fields = Fields::singleton(cx, mkpat(subpattern));
877 PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
878 match pat.ty.kind(Interner) {
879 TyKind::Tuple(_, substs) => {
881 let mut wilds: SmallVec<[_; 2]> = substs
883 .map(|arg| arg.assert_ty_ref(Interner).clone())
884 .map(DeconstructedPat::wildcard)
886 for pat in subpatterns {
887 let idx: u32 = pat.field.into_raw().into();
888 wilds[idx as usize] = mkpat(&pat.pattern);
890 fields = Fields::from_iter(cx, wilds)
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
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.
906 subpatterns.iter().find(|pat| pat.field.into_raw() == 0u32.into());
907 let field = if let Some(pat) = pat {
910 let ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
911 DeconstructedPat::wildcard(ty)
914 fields = Fields::singleton(cx, field)
916 &TyKind::Adt(adt, _) => {
917 ctor = match pat.kind.as_ref() {
918 PatKind::Leaf { .. } => Single,
919 PatKind::Variant { enum_variant, .. } => Variant(*enum_variant),
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)
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);
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);
944 fields = Fields::from_iter(cx, wilds);
947 never!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, &pat.ty);
949 fields = Fields::empty();
953 &PatKind::LiteralBool { value } => {
954 ctor = IntRange(IntRange::from_bool(value));
955 fields = Fields::empty();
957 PatKind::Or { .. } => {
959 let pats: SmallVec<[_; 2]> = expand_or_pat(pat).into_iter().map(mkpat).collect();
960 fields = Fields::from_iter(cx, pats)
963 DeconstructedPat::new(ctor, fields, pat.ty.clone())
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() }
971 pub(super) fn is_or_pat(&self) -> bool {
972 matches!(self.ctor, Or)
975 pub(super) fn ctor(&self) -> &Constructor {
979 pub(super) fn ty(&self) -> &Ty {
983 pub(super) fn iter_fields<'a>(&'a self) -> impl Iterator<Item = &'a DeconstructedPat<'a>> + 'a {
984 self.fields.iter_patterns()
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>(
991 cx: &MatchCheckCtx<'_, 'p>,
992 other_ctor: &Constructor,
993 ) -> SmallVec<[&'p DeconstructedPat<'p>; 2]> {
994 match (&self.ctor, other_ctor) {
996 // We return a wildcard for each field of `other_ctor`.
997 Fields::wildcards(cx, &self.ty, other_ctor).iter_patterns().collect()
999 (Slice(self_slice), Slice(other_slice))
1000 if self_slice.arity() != other_slice.arity() =>
1004 _ => self.fields.iter_patterns().collect(),
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)
1013 pub(super) fn is_reachable(&self) -> bool {
1014 self.reachable.get()
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(),
1024 cx.db.attrs(attr_def_id).by_key("non_exhaustive").exists()
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(),