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