]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/_match.rs
Let MissingConstructors handle the subtleties of missing constructors
[rust.git] / compiler / rustc_mir_build / src / thir / pattern / _match.rs
1 //! Note: most of the tests relevant to this file can be found (at the time of writing) in
2 //! src/tests/ui/pattern/usefulness.
3 //!
4 //! This file includes the logic for exhaustiveness and usefulness checking for
5 //! pattern-matching. Specifically, given a list of patterns for a type, we can
6 //! tell whether:
7 //! (a) the patterns cover every possible constructor for the type (exhaustiveness)
8 //! (b) each pattern is necessary (usefulness)
9 //!
10 //! The algorithm implemented here is a modified version of the one described in:
11 //! http://moscova.inria.fr/~maranget/papers/warn/index.html
12 //! However, to save future implementors from reading the original paper, we
13 //! summarise the algorithm here to hopefully save time and be a little clearer
14 //! (without being so rigorous).
15 //!
16 //! # Premise
17 //!
18 //! The core of the algorithm revolves about a "usefulness" check. In particular, we
19 //! are trying to compute a predicate `U(P, p)` where `P` is a list of patterns (we refer to this as
20 //! a matrix). `U(P, p)` represents whether, given an existing list of patterns
21 //! `P_1 ..= P_m`, adding a new pattern `p` will be "useful" (that is, cover previously-
22 //! uncovered values of the type).
23 //!
24 //! If we have this predicate, then we can easily compute both exhaustiveness of an
25 //! entire set of patterns and the individual usefulness of each one.
26 //! (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard
27 //! match doesn't increase the number of values we're matching)
28 //! (b) a pattern `P_i` is not useful if `U(P[0..=(i-1), P_i)` is false (i.e., adding a
29 //! pattern to those that have come before it doesn't increase the number of values
30 //! we're matching).
31 //!
32 //! # Core concept
33 //!
34 //! The idea that powers everything that is done in this file is the following: a value is made
35 //! from a constructor applied to some fields. Examples of constructors are `Some`, `None`, `(,)`
36 //! (the 2-tuple constructor), `Foo {..}` (the constructor for a struct `Foo`), and `2` (the
37 //! constructor for the number `2`). Fields are just a (possibly empty) list of values.
38 //!
39 //! Some of the constructors listed above might feel weird: `None` and `2` don't take any
40 //! arguments. This is part of what makes constructors so general: we will consider plain values
41 //! like numbers and string literals to be constructors that take no arguments, also called "0-ary
42 //! constructors"; they are the simplest case of constructors. This allows us to see any value as
43 //! made up from a tree of constructors, each having a given number of children. For example:
44 //! `(None, Ok(0))` is made from 4 different constructors.
45 //!
46 //! This idea can be extended to patterns: a pattern captures a set of possible values, and we can
47 //! describe this set using constructors. For example, `Err(_)` captures all values of the type
48 //! `Result<T, E>` that start with the `Err` constructor (for some choice of `T` and `E`). The
49 //! wildcard `_` captures all values of the given type starting with any of the constructors for
50 //! that type.
51 //!
52 //! We use this to compute whether different patterns might capture a same value. Do the patterns
53 //! `Ok("foo")` and `Err(_)` capture a common value? The answer is no, because the first pattern
54 //! captures only values starting with the `Ok` constructor and the second only values starting
55 //! with the `Err` constructor. Do the patterns `Some(42)` and `Some(1..10)` intersect? They might,
56 //! since they both capture values starting with `Some`. To be certain, we need to dig under the
57 //! `Some` constructor and continue asking the question. This is the main idea behind the
58 //! exhaustiveness algorithm: by looking at patterns constructor-by-constructor, we can efficiently
59 //! figure out if some new pattern might capture a value that hadn't been captured by previous
60 //! patterns.
61 //!
62 //! Constructors are represented by the `Constructor` enum, and its fields by the `Fields` enum.
63 //! Most of the complexity of this file resides in transforming between patterns and
64 //! (`Constructor`, `Fields`) pairs, handling all the special cases correctly.
65 //!
66 //! Caveat: this constructors/fields distinction doesn't quite cover every Rust value. For example
67 //! a value of type `Rc<u64>` doesn't fit this idea very well, nor do various other things.
68 //! However, this idea covers most of the cases that are relevant to exhaustiveness checking.
69 //!
70 //!
71 //! # Algorithm
72 //!
73 //! Recall that `U(P, p)` represents whether, given an existing list of patterns (aka matrix) `P`,
74 //! adding a new pattern `p` will cover previously-uncovered values of the type.
75 //! During the course of the algorithm, the rows of the matrix won't just be individual patterns,
76 //! but rather partially-deconstructed patterns in the form of a list of fields. The paper
77 //! calls those pattern-vectors, and we will call them pattern-stacks. The same holds for the
78 //! new pattern `p`.
79 //!
80 //! For example, say we have the following:
81 //!
82 //! ```
83 //! // x: (Option<bool>, Result<()>)
84 //! match x {
85 //!     (Some(true), _) => {}
86 //!     (None, Err(())) => {}
87 //!     (None, Err(_)) => {}
88 //! }
89 //! ```
90 //!
91 //! Here, the matrix `P` starts as:
92 //!
93 //! ```
94 //! [
95 //!     [(Some(true), _)],
96 //!     [(None, Err(()))],
97 //!     [(None, Err(_))],
98 //! ]
99 //! ```
100 //!
101 //! We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering
102 //! `[(Some(false), _)]`, for instance). In addition, row 3 is not useful, because
103 //! all the values it covers are already covered by row 2.
104 //!
105 //! A list of patterns can be thought of as a stack, because we are mainly interested in the top of
106 //! the stack at any given point, and we can pop or apply constructors to get new pattern-stacks.
107 //! To match the paper, the top of the stack is at the beginning / on the left.
108 //!
109 //! There are two important operations on pattern-stacks necessary to understand the algorithm:
110 //!
111 //! 1. We can pop a given constructor off the top of a stack. This operation is called
112 //!    `specialize`, and is denoted `S(c, p)` where `c` is a constructor (like `Some` or
113 //!    `None`) and `p` a pattern-stack.
114 //!    If the pattern on top of the stack can cover `c`, this removes the constructor and
115 //!    pushes its arguments onto the stack. It also expands OR-patterns into distinct patterns.
116 //!    Otherwise the pattern-stack is discarded.
117 //!    This essentially filters those pattern-stacks whose top covers the constructor `c` and
118 //!    discards the others.
119 //!
120 //!    For example, the first pattern above initially gives a stack `[(Some(true), _)]`. If we
121 //!    pop the tuple constructor, we are left with `[Some(true), _]`, and if we then pop the
122 //!    `Some` constructor we get `[true, _]`. If we had popped `None` instead, we would get
123 //!    nothing back.
124 //!
125 //!    This returns zero or more new pattern-stacks, as follows. We look at the pattern `p_1`
126 //!    on top of the stack, and we have four cases:
127 //!         1.1. `p_1 = c(r_1, .., r_a)`, i.e. the top of the stack has constructor `c`. We
128 //!              push onto the stack the arguments of this constructor, and return the result:
129 //!                 r_1, .., r_a, p_2, .., p_n
130 //!         1.2. `p_1 = c'(r_1, .., r_a')` where `c ≠ c'`. We discard the current stack and
131 //!              return nothing.
132 //!         1.3. `p_1 = _`. We push onto the stack as many wildcards as the constructor `c` has
133 //!              arguments (its arity), and return the resulting stack:
134 //!                 _, .., _, p_2, .., p_n
135 //!         1.4. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting
136 //!              stack:
137 //!                 S(c, (r_1, p_2, .., p_n))
138 //!                 S(c, (r_2, p_2, .., p_n))
139 //!
140 //! 2. We can pop a wildcard off the top of the stack. This is called `S(_, p)`, where `p` is
141 //!    a pattern-stack. Note: the paper calls this `D(p)`.
142 //!    This is used when we know there are missing constructor cases, but there might be
143 //!    existing wildcard patterns, so to check the usefulness of the matrix, we have to check
144 //!    all its *other* components.
145 //!
146 //!    It is computed as follows. We look at the pattern `p_1` on top of the stack,
147 //!    and we have three cases:
148 //!         2.1. `p_1 = c(r_1, .., r_a)`. We discard the current stack and return nothing.
149 //!         2.2. `p_1 = _`. We return the rest of the stack:
150 //!                 p_2, .., p_n
151 //!         2.3. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting
152 //!           stack.
153 //!                 S(_, (r_1, p_2, .., p_n))
154 //!                 S(_, (r_2, p_2, .., p_n))
155 //!
156 //! Note that the OR-patterns are not always used directly in Rust, but are used to derive the
157 //! exhaustive integer matching rules, so they're written here for posterity.
158 //!
159 //! Both those operations extend straightforwardly to a list or pattern-stacks, i.e. a matrix, by
160 //! working row-by-row. Popping a constructor ends up keeping only the matrix rows that start with
161 //! the given constructor, and popping a wildcard keeps those rows that start with a wildcard.
162 //!
163 //!
164 //! The algorithm for computing `U`
165 //! -------------------------------
166 //! The algorithm is inductive (on the number of columns: i.e., components of tuple patterns).
167 //! That means we're going to check the components from left-to-right, so the algorithm
168 //! operates principally on the first component of the matrix and new pattern-stack `p`.
169 //! This algorithm is realised in the `is_useful` function.
170 //!
171 //! Base case. (`n = 0`, i.e., an empty tuple pattern)
172 //!     - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`),
173 //!       then `U(P, p)` is false.
174 //!     - Otherwise, `P` must be empty, so `U(P, p)` is true.
175 //!
176 //! Inductive step. (`n > 0`, i.e., whether there's at least one column
177 //!                  [which may then be expanded into further columns later])
178 //! We're going to match on the top of the new pattern-stack, `p_1`.
179 //!     - If `p_1 == c(r_1, .., r_a)`, i.e. we have a constructor pattern.
180 //! Then, the usefulness of `p_1` can be reduced to whether it is useful when
181 //! we ignore all the patterns in the first column of `P` that involve other constructors.
182 //! This is where `S(c, P)` comes in:
183 //! `U(P, p) := U(S(c, P), S(c, p))`
184 //! This special case is handled in `is_useful_specialized`.
185 //!
186 //! For example, if `P` is:
187 //!
188 //! ```
189 //! [
190 //!     [Some(true), _],
191 //!     [None, 0],
192 //! ]
193 //! ```
194 //!
195 //! and `p` is [Some(false), 0], then we don't care about row 2 since we know `p` only
196 //! matches values that row 2 doesn't. For row 1 however, we need to dig into the
197 //! arguments of `Some` to know whether some new value is covered. So we compute
198 //! `U([[true, _]], [false, 0])`.
199 //!
200 //!   - If `p_1 == _`, then we look at the list of constructors that appear in the first
201 //! component of the rows of `P`:
202 //!   + If there are some constructors that aren't present, then we might think that the
203 //! wildcard `_` is useful, since it covers those constructors that weren't covered
204 //! before.
205 //! That's almost correct, but only works if there were no wildcards in those first
206 //! components. So we need to check that `p` is useful with respect to the rows that
207 //! start with a wildcard, if there are any. This is where `D` comes in:
208 //! `U(P, p) := U(S(_, P), S(_, p))`
209 //!
210 //! For example, if `P` is:
211 //!
212 //! ```
213 //! [
214 //!     [_, true, _],
215 //!     [None, false, 1],
216 //! ]
217 //! ```
218 //!
219 //! and `p` is [_, false, _], the `Some` constructor doesn't appear in `P`. So if we
220 //! only had row 2, we'd know that `p` is useful. However row 1 starts with a
221 //! wildcard, so we need to check whether `U([[true, _]], [false, 1])`.
222 //!
223 //!   + Otherwise, all possible constructors (for the relevant type) are present. In this
224 //! case we must check whether the wildcard pattern covers any unmatched value. For
225 //! that, we can think of the `_` pattern as a big OR-pattern that covers all
226 //! possible constructors. For `Option`, that would mean `_ = None | Some(_)` for
227 //! example. The wildcard pattern is useful in this case if it is useful when
228 //! specialized to one of the possible constructors. So we compute:
229 //! `U(P, p) := ∃(k ϵ constructors) U(S(k, P), S(k, p))`
230 //!
231 //! For example, if `P` is:
232 //!
233 //! ```
234 //! [
235 //!     [Some(true), _],
236 //!     [None, false],
237 //! ]
238 //! ```
239 //!
240 //! and `p` is [_, false], both `None` and `Some` constructors appear in the first
241 //! components of `P`. We will therefore try popping both constructors in turn: we
242 //! compute `U([[true, _]], [_, false])` for the `Some` constructor, and `U([[false]],
243 //! [false])` for the `None` constructor. The first case returns true, so we know that
244 //! `p` is useful for `P`. Indeed, it matches `[Some(false), _]` that wasn't matched
245 //! before.
246 //!
247 //!   - If `p_1 == r_1 | r_2`, then the usefulness depends on each `r_i` separately:
248 //! `U(P, p) := U(P, (r_1, p_2, .., p_n))
249 //!  || U(P, (r_2, p_2, .., p_n))`
250 //!
251 //! Modifications to the algorithm
252 //! ------------------------------
253 //! The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
254 //! example uninhabited types and variable-length slice patterns. These are drawn attention to
255 //! throughout the code below. I'll make a quick note here about how exhaustive integer matching is
256 //! accounted for, though.
257 //!
258 //! Exhaustive integer matching
259 //! ---------------------------
260 //! An integer type can be thought of as a (huge) sum type: 1 | 2 | 3 | ...
261 //! So to support exhaustive integer matching, we can make use of the logic in the paper for
262 //! OR-patterns. However, we obviously can't just treat ranges x..=y as individual sums, because
263 //! they are likely gigantic. So we instead treat ranges as constructors of the integers. This means
264 //! that we have a constructor *of* constructors (the integers themselves). We then need to work
265 //! through all the inductive step rules above, deriving how the ranges would be treated as
266 //! OR-patterns, and making sure that they're treated in the same way even when they're ranges.
267 //! There are really only four special cases here:
268 //! - When we match on a constructor that's actually a range, we have to treat it as if we would
269 //!   an OR-pattern.
270 //!     + It turns out that we can simply extend the case for single-value patterns in
271 //!      `specialize` to either be *equal* to a value constructor, or *contained within* a range
272 //!      constructor.
273 //!     + When the pattern itself is a range, you just want to tell whether any of the values in
274 //!       the pattern range coincide with values in the constructor range, which is precisely
275 //!       intersection.
276 //!   Since when encountering a range pattern for a value constructor, we also use inclusion, it
277 //!   means that whenever the constructor is a value/range and the pattern is also a value/range,
278 //!   we can simply use intersection to test usefulness.
279 //! - When we're testing for usefulness of a pattern and the pattern's first component is a
280 //!   wildcard.
281 //!     + If all the constructors appear in the matrix, we have a slight complication. By default,
282 //!       the behaviour (i.e., a disjunction over specialised matrices for each constructor) is
283 //!       invalid, because we want a disjunction over every *integer* in each range, not just a
284 //!       disjunction over every range. This is a bit more tricky to deal with: essentially we need
285 //!       to form equivalence classes of subranges of the constructor range for which the behaviour
286 //!       of the matrix `P` and new pattern `p` are the same. This is described in more
287 //!       detail in `Constructor::split`.
288 //!     + If some constructors are missing from the matrix, it turns out we don't need to do
289 //!       anything special (because we know none of the integers are actually wildcards: i.e., we
290 //!       can't span wildcards using ranges).
291 use self::Constructor::*;
292 use self::SliceKind::*;
293 use self::Usefulness::*;
294 use self::WitnessPreference::*;
295
296 use rustc_data_structures::captures::Captures;
297 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
298 use rustc_data_structures::sync::OnceCell;
299 use rustc_index::vec::Idx;
300
301 use super::{compare_const_vals, PatternFoldable, PatternFolder};
302 use super::{FieldPat, Pat, PatKind, PatRange};
303
304 use rustc_arena::TypedArena;
305 use rustc_attr::{SignedInt, UnsignedInt};
306 use rustc_hir::def_id::DefId;
307 use rustc_hir::{HirId, RangeEnd};
308 use rustc_middle::mir::interpret::{truncate, ConstValue};
309 use rustc_middle::mir::Field;
310 use rustc_middle::ty::layout::IntegerExt;
311 use rustc_middle::ty::{self, Const, Ty, TyCtxt};
312 use rustc_session::lint;
313 use rustc_span::{Span, DUMMY_SP};
314 use rustc_target::abi::{Integer, Size, VariantIdx};
315
316 use smallvec::{smallvec, SmallVec};
317 use std::cmp::{self, max, min, Ordering};
318 use std::fmt;
319 use std::iter::{FromIterator, IntoIterator};
320 use std::ops::RangeInclusive;
321
322 crate fn expand_pattern<'tcx>(pat: Pat<'tcx>) -> Pat<'tcx> {
323     LiteralExpander.fold_pattern(&pat)
324 }
325
326 struct LiteralExpander;
327
328 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
329     fn fold_pattern(&mut self, pat: &Pat<'tcx>) -> Pat<'tcx> {
330         debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.kind(), pat.kind);
331         match (pat.ty.kind(), &*pat.kind) {
332             (_, &PatKind::Binding { subpattern: Some(ref s), .. }) => s.fold_with(self),
333             (_, &PatKind::AscribeUserType { subpattern: ref s, .. }) => s.fold_with(self),
334             _ => pat.super_fold_with(self),
335         }
336     }
337 }
338
339 impl<'tcx> Pat<'tcx> {
340     pub(super) fn is_wildcard(&self) -> bool {
341         match *self.kind {
342             PatKind::Binding { subpattern: None, .. } | PatKind::Wild => true,
343             _ => false,
344         }
345     }
346 }
347
348 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
349 /// works well.
350 #[derive(Debug, Clone)]
351 crate struct PatStack<'p, 'tcx> {
352     pats: SmallVec<[&'p Pat<'tcx>; 2]>,
353     /// Cache for the constructor of the head
354     head_ctor: OnceCell<Constructor<'tcx>>,
355 }
356
357 impl<'p, 'tcx> PatStack<'p, 'tcx> {
358     crate fn from_pattern(pat: &'p Pat<'tcx>) -> Self {
359         Self::from_vec(smallvec![pat])
360     }
361
362     fn from_vec(vec: SmallVec<[&'p Pat<'tcx>; 2]>) -> Self {
363         PatStack { pats: vec, head_ctor: OnceCell::new() }
364     }
365
366     fn is_empty(&self) -> bool {
367         self.pats.is_empty()
368     }
369
370     fn len(&self) -> usize {
371         self.pats.len()
372     }
373
374     fn head(&self) -> &'p Pat<'tcx> {
375         self.pats[0]
376     }
377
378     fn head_ctor<'a>(&'a self, cx: &MatchCheckCtxt<'p, 'tcx>) -> &'a Constructor<'tcx> {
379         self.head_ctor.get_or_init(|| pat_constructor(cx, self.head()))
380     }
381
382     fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> {
383         self.pats.iter().copied()
384     }
385
386     // If the first pattern is an or-pattern, expand this pattern. Otherwise, return `None`.
387     fn expand_or_pat(&self) -> Option<Vec<Self>> {
388         if self.is_empty() {
389             None
390         } else if let PatKind::Or { pats } = &*self.head().kind {
391             Some(
392                 pats.iter()
393                     .map(|pat| {
394                         let mut new_patstack = PatStack::from_pattern(pat);
395                         new_patstack.pats.extend_from_slice(&self.pats[1..]);
396                         new_patstack
397                     })
398                     .collect(),
399             )
400         } else {
401             None
402         }
403     }
404
405     /// This computes `S(constructor, self)`. See top of the file for explanations.
406     ///
407     /// This is the main specialization step. It expands the pattern
408     /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
409     /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
410     /// Returns `None` if the pattern does not have the given constructor.
411     ///
412     /// OTOH, slice patterns with a subslice pattern (tail @ ..) can be expanded into multiple
413     /// different patterns.
414     /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
415     /// fields filled with wild patterns.
416     ///
417     /// This is roughly the inverse of `Constructor::apply`.
418     fn specialize_constructor(
419         &self,
420         cx: &MatchCheckCtxt<'p, 'tcx>,
421         ctor: &Constructor<'tcx>,
422         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
423         is_my_head_ctor: bool,
424     ) -> Option<PatStack<'p, 'tcx>> {
425         // We return `None` if `ctor` is not covered by `self.head()`. If `ctor` is known to be
426         // derived from `self.head()`, then we don't need to check; otherwise, we check for
427         // constructor inclusion.
428         // Note that this shortcut is also necessary for correctness: a pattern should always be
429         // specializable with its own constructor, even in cases where we refuse to inspect values like
430         // opaque constants.
431         if !is_my_head_ctor && !ctor.is_covered_by(cx, self.head_ctor(cx), self.head().ty) {
432             return None;
433         }
434         let new_fields = ctor_wild_subpatterns.replace_with_pattern_arguments(self.head());
435
436         debug!(
437             "specialize_constructor({:#?}, {:#?}, {:#?}) = {:#?}",
438             self.head(),
439             ctor,
440             ctor_wild_subpatterns,
441             new_fields
442         );
443
444         // We pop the head pattern and push the new fields extracted from the arguments of
445         // `self.head()`.
446         Some(new_fields.push_on_patstack(&self.pats[1..]))
447     }
448 }
449
450 impl<'p, 'tcx> Default for PatStack<'p, 'tcx> {
451     fn default() -> Self {
452         Self::from_vec(smallvec![])
453     }
454 }
455
456 impl<'p, 'tcx> PartialEq for PatStack<'p, 'tcx> {
457     fn eq(&self, other: &Self) -> bool {
458         self.pats == other.pats
459     }
460 }
461
462 impl<'p, 'tcx> FromIterator<&'p Pat<'tcx>> for PatStack<'p, 'tcx> {
463     fn from_iter<T>(iter: T) -> Self
464     where
465         T: IntoIterator<Item = &'p Pat<'tcx>>,
466     {
467         Self::from_vec(iter.into_iter().collect())
468     }
469 }
470
471 /// Depending on the match patterns, the specialization process might be able to use a fast path.
472 /// Tracks whether we can use the fast path and the lookup table needed in those cases.
473 #[derive(Clone, Debug, PartialEq)]
474 enum SpecializationCache {
475     /// Patterns consist of only enum variants.
476     /// Variant patterns does not intersect with each other (in contrast to range patterns),
477     /// so it is possible to precompute the result of `Matrix::specialize_constructor` at a
478     /// lower computational complexity.
479     /// `lookup` is responsible for holding the precomputed result of
480     /// specialization, while `wilds` is used for two purposes: the first one is
481     /// the precomputed result of specialization with a wildcard, and the second is to be used as a
482     /// fallback for `Matrix::specialize_constructor` when it tries to apply a constructor that
483     /// has not been seen in the `Matrix`. See `update_cache` for further explanations.
484     Variants { lookup: FxHashMap<DefId, SmallVec<[usize; 1]>>, wilds: SmallVec<[usize; 1]> },
485     /// Does not belong to the cases above, use the slow path.
486     Incompatible,
487 }
488
489 /// A 2D matrix.
490 #[derive(Clone, PartialEq)]
491 crate struct Matrix<'p, 'tcx> {
492     patterns: Vec<PatStack<'p, 'tcx>>,
493     cache: SpecializationCache,
494 }
495
496 impl<'p, 'tcx> Matrix<'p, 'tcx> {
497     crate fn empty() -> Self {
498         // Use `SpecializationCache::Incompatible` as a placeholder; we will initialize it on the
499         // first call to `push`. See the first half of `update_cache`.
500         Matrix { patterns: vec![], cache: SpecializationCache::Incompatible }
501     }
502
503     /// Pushes a new row to the matrix. If the row starts with an or-pattern, this expands it.
504     crate fn push(&mut self, row: PatStack<'p, 'tcx>) {
505         if let Some(rows) = row.expand_or_pat() {
506             for row in rows {
507                 // We recursively expand the or-patterns of the new rows.
508                 // This is necessary as we might have `0 | (1 | 2)` or e.g., `x @ 0 | x @ (1 | 2)`.
509                 self.push(row)
510             }
511         } else {
512             self.patterns.push(row);
513             self.update_cache(self.patterns.len() - 1);
514         }
515     }
516
517     fn update_cache(&mut self, idx: usize) {
518         let row = &self.patterns[idx];
519         // We don't know which kind of cache could be used until we see the first row; therefore an
520         // empty `Matrix` is initialized with `SpecializationCache::Empty`, then the cache is
521         // assigned the appropriate variant below on the first call to `push`.
522         if self.patterns.is_empty() {
523             self.cache = if row.is_empty() {
524                 SpecializationCache::Incompatible
525             } else {
526                 match *row.head().kind {
527                     PatKind::Variant { .. } => SpecializationCache::Variants {
528                         lookup: FxHashMap::default(),
529                         wilds: SmallVec::new(),
530                     },
531                     // Note: If the first pattern is a wildcard, then all patterns after that is not
532                     // useful. The check is simple enough so we treat it as the same as unsupported
533                     // patterns.
534                     _ => SpecializationCache::Incompatible,
535                 }
536             };
537         }
538         // Update the cache.
539         match &mut self.cache {
540             SpecializationCache::Variants { ref mut lookup, ref mut wilds } => {
541                 let head = row.head();
542                 match *head.kind {
543                     _ if head.is_wildcard() => {
544                         // Per rule 1.3 in the top-level comments, a wildcard pattern is included in
545                         // the result of `specialize_constructor` for *any* `Constructor`.
546                         // We push the wildcard pattern to the precomputed result for constructors
547                         // that we have seen before; results for constructors we have not yet seen
548                         // defaults to `wilds`, which is updated right below.
549                         for (_, v) in lookup.iter_mut() {
550                             v.push(idx);
551                         }
552                         // Per rule 2.1 and 2.2 in the top-level comments, only wildcard patterns
553                         // are included in the result of specialization with a wildcard.
554                         // What we do here is to track the wildcards we have seen; so in addition to
555                         // acting as the precomputed result of specialization with a wildcard, `wilds` also
556                         // serves as the default value of `specialize_constructor` for constructors
557                         // that are not in `lookup`.
558                         wilds.push(idx);
559                     }
560                     PatKind::Variant { adt_def, variant_index, .. } => {
561                         // Handle the cases of rule 1.1 and 1.2 in the top-level comments.
562                         // A variant pattern can only be included in the results of
563                         // `specialize_constructor` for a particular constructor, therefore we are
564                         // using a HashMap to track that.
565                         lookup
566                             .entry(adt_def.variants[variant_index].def_id)
567                             // Default to `wilds` for absent keys. See above for an explanation.
568                             .or_insert_with(|| wilds.clone())
569                             .push(idx);
570                     }
571                     _ => {
572                         self.cache = SpecializationCache::Incompatible;
573                     }
574                 }
575             }
576             SpecializationCache::Incompatible => {}
577         }
578     }
579
580     /// Iterate over the first component of each row
581     fn heads<'a>(&'a self) -> impl Iterator<Item = &'a Pat<'tcx>> + Captures<'p> {
582         self.patterns.iter().map(|r| r.head())
583     }
584
585     /// Iterate over the first constructor of each row
586     fn head_ctors<'a>(
587         &'a self,
588         cx: &'a MatchCheckCtxt<'p, 'tcx>,
589     ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'a> + Captures<'p> {
590         self.patterns.iter().map(move |r| r.head_ctor(cx))
591     }
592
593     /// This computes `S(constructor, self)`. See top of the file for explanations.
594     fn specialize_constructor(
595         &self,
596         cx: &MatchCheckCtxt<'p, 'tcx>,
597         constructor: &Constructor<'tcx>,
598         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
599     ) -> Matrix<'p, 'tcx> {
600         match &self.cache {
601             SpecializationCache::Variants { lookup, wilds } => {
602                 let cached = if let Constructor::Variant(id) = constructor {
603                     lookup
604                         .get(id)
605                         // Default to `wilds` for absent keys. See `update_cache` for an explanation.
606                         .unwrap_or(&wilds)
607                 } else if let Wildcard = constructor {
608                     &wilds
609                 } else {
610                     bug!(
611                         "unexpected constructor encountered while dealing with matrix cache: {:?}",
612                         constructor
613                     );
614                 };
615                 let result: Self = cached
616                     .iter()
617                     .filter_map(|&i| {
618                         self.patterns[i].specialize_constructor(
619                             cx,
620                             constructor,
621                             ctor_wild_subpatterns,
622                             false,
623                         )
624                     })
625                     .collect();
626                 // When debug assertions are enabled, check the results against the "slow path"
627                 // result.
628                 debug_assert_eq!(
629                     result,
630                     Matrix {
631                         patterns: self.patterns.clone(),
632                         cache: SpecializationCache::Incompatible
633                     }
634                     .specialize_constructor(
635                         cx,
636                         constructor,
637                         ctor_wild_subpatterns
638                     )
639                 );
640                 result
641             }
642             SpecializationCache::Incompatible => self
643                 .patterns
644                 .iter()
645                 .filter_map(|r| {
646                     r.specialize_constructor(cx, constructor, ctor_wild_subpatterns, false)
647                 })
648                 .collect(),
649         }
650     }
651 }
652
653 /// Pretty-printer for matrices of patterns, example:
654 ///
655 /// ```text
656 /// +++++++++++++++++++++++++++++
657 /// + _     + []                +
658 /// +++++++++++++++++++++++++++++
659 /// + true  + [First]           +
660 /// +++++++++++++++++++++++++++++
661 /// + true  + [Second(true)]    +
662 /// +++++++++++++++++++++++++++++
663 /// + false + [_]               +
664 /// +++++++++++++++++++++++++++++
665 /// + _     + [_, _, tail @ ..] +
666 /// +++++++++++++++++++++++++++++
667 /// ```
668 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
669     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670         write!(f, "\n")?;
671
672         let Matrix { patterns: m, .. } = self;
673         let pretty_printed_matrix: Vec<Vec<String>> =
674             m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
675
676         let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
677         assert!(m.iter().all(|row| row.len() == column_count));
678         let column_widths: Vec<usize> = (0..column_count)
679             .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
680             .collect();
681
682         let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
683         let br = "+".repeat(total_width);
684         write!(f, "{}\n", br)?;
685         for row in pretty_printed_matrix {
686             write!(f, "+")?;
687             for (column, pat_str) in row.into_iter().enumerate() {
688                 write!(f, " ")?;
689                 write!(f, "{:1$}", pat_str, column_widths[column])?;
690                 write!(f, " +")?;
691             }
692             write!(f, "\n")?;
693             write!(f, "{}\n", br)?;
694         }
695         Ok(())
696     }
697 }
698
699 impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> {
700     fn from_iter<T>(iter: T) -> Self
701     where
702         T: IntoIterator<Item = PatStack<'p, 'tcx>>,
703     {
704         let mut matrix = Matrix::empty();
705         for x in iter {
706             // Using `push` ensures we correctly expand or-patterns.
707             matrix.push(x);
708         }
709         matrix
710     }
711 }
712
713 crate struct MatchCheckCtxt<'a, 'tcx> {
714     crate tcx: TyCtxt<'tcx>,
715     /// The module in which the match occurs. This is necessary for
716     /// checking inhabited-ness of types because whether a type is (visibly)
717     /// inhabited can depend on whether it was defined in the current module or
718     /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
719     /// outside it's module and should not be matchable with an empty match
720     /// statement.
721     crate module: DefId,
722     crate param_env: ty::ParamEnv<'tcx>,
723     crate pattern_arena: &'a TypedArena<Pat<'tcx>>,
724 }
725
726 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
727     fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
728         if self.tcx.features().exhaustive_patterns {
729             self.tcx.is_ty_uninhabited_from(self.module, ty, self.param_env)
730         } else {
731             false
732         }
733     }
734
735     /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
736     crate fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
737         match ty.kind() {
738             ty::Adt(def, ..) => {
739                 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local()
740             }
741             _ => false,
742         }
743     }
744 }
745
746 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
747 enum SliceKind {
748     /// Patterns of length `n` (`[x, y]`).
749     FixedLen(u64),
750     /// Patterns using the `..` notation (`[x, .., y]`).
751     /// Captures any array constructor of `length >= i + j`.
752     /// In the case where `array_len` is `Some(_)`,
753     /// this indicates that we only care about the first `i` and the last `j` values of the array,
754     /// and everything in between is a wildcard `_`.
755     VarLen(u64, u64),
756 }
757
758 impl SliceKind {
759     fn arity(self) -> u64 {
760         match self {
761             FixedLen(length) => length,
762             VarLen(prefix, suffix) => prefix + suffix,
763         }
764     }
765
766     /// Whether this pattern includes patterns of length `other_len`.
767     fn covers_length(self, other_len: u64) -> bool {
768         match self {
769             FixedLen(len) => len == other_len,
770             VarLen(prefix, suffix) => prefix + suffix <= other_len,
771         }
772     }
773
774     /// Returns a collection of slices that spans the values covered by `self`, subtracted by the
775     /// values covered by `other`: i.e., `self \ other` (in set notation).
776     fn subtract(self, other: Self) -> SmallVec<[Self; 1]> {
777         // Remember, `VarLen(i, j)` covers the union of `FixedLen` from `i + j` to infinity.
778         // Naming: we remove the "neg" constructors from the "pos" ones.
779         match self {
780             FixedLen(pos_len) => {
781                 if other.covers_length(pos_len) {
782                     smallvec![]
783                 } else {
784                     smallvec![self]
785                 }
786             }
787             VarLen(pos_prefix, pos_suffix) => {
788                 let pos_len = pos_prefix + pos_suffix;
789                 match other {
790                     FixedLen(neg_len) => {
791                         if neg_len < pos_len {
792                             smallvec![self]
793                         } else {
794                             (pos_len..neg_len)
795                                 .map(FixedLen)
796                                 // We know that `neg_len + 1 >= pos_len >= pos_suffix`.
797                                 .chain(Some(VarLen(neg_len + 1 - pos_suffix, pos_suffix)))
798                                 .collect()
799                         }
800                     }
801                     VarLen(neg_prefix, neg_suffix) => {
802                         let neg_len = neg_prefix + neg_suffix;
803                         if neg_len <= pos_len {
804                             smallvec![]
805                         } else {
806                             (pos_len..neg_len).map(FixedLen).collect()
807                         }
808                     }
809                 }
810             }
811         }
812     }
813 }
814
815 /// A constructor for array and slice patterns.
816 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
817 struct Slice {
818     /// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`.
819     array_len: Option<u64>,
820     /// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`.
821     kind: SliceKind,
822 }
823
824 impl Slice {
825     /// Returns what patterns this constructor covers: either fixed-length patterns or
826     /// variable-length patterns.
827     fn pattern_kind(self) -> SliceKind {
828         match self {
829             Slice { array_len: Some(len), kind: VarLen(prefix, suffix) }
830                 if prefix + suffix == len =>
831             {
832                 FixedLen(len)
833             }
834             _ => self.kind,
835         }
836     }
837
838     /// Returns what values this constructor covers: either values of only one given length, or
839     /// values of length above a given length.
840     /// This is different from `pattern_kind()` because in some cases the pattern only takes into
841     /// account a subset of the entries of the array, but still only captures values of a given
842     /// length.
843     fn value_kind(self) -> SliceKind {
844         match self {
845             Slice { array_len: Some(len), kind: VarLen(_, _) } => FixedLen(len),
846             _ => self.kind,
847         }
848     }
849
850     fn arity(self) -> u64 {
851         self.pattern_kind().arity()
852     }
853
854     /// The exhaustiveness-checking paper does not include any details on
855     /// checking variable-length slice patterns. However, they are matched
856     /// by an infinite collection of fixed-length array patterns.
857     ///
858     /// Checking the infinite set directly would take an infinite amount
859     /// of time. However, it turns out that for each finite set of
860     /// patterns `P`, all sufficiently large array lengths are equivalent:
861     ///
862     /// Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
863     /// to exactly the subset `Pₜ` of `P` can be transformed to a slice
864     /// `sₘ` for each sufficiently-large length `m` that applies to exactly
865     /// the same subset of `P`.
866     ///
867     /// Because of that, each witness for reachability-checking from one
868     /// of the sufficiently-large lengths can be transformed to an
869     /// equally-valid witness from any other length, so we only have
870     /// to check slice lengths from the "minimal sufficiently-large length"
871     /// and below.
872     ///
873     /// Note that the fact that there is a *single* `sₘ` for each `m`
874     /// not depending on the specific pattern in `P` is important: if
875     /// you look at the pair of patterns
876     ///     `[true, ..]`
877     ///     `[.., false]`
878     /// Then any slice of length ≥1 that matches one of these two
879     /// patterns can be trivially turned to a slice of any
880     /// other length ≥1 that matches them and vice-versa - for
881     /// but the slice from length 2 `[false, true]` that matches neither
882     /// of these patterns can't be turned to a slice from length 1 that
883     /// matches neither of these patterns, so we have to consider
884     /// slices from length 2 there.
885     ///
886     /// Now, to see that that length exists and find it, observe that slice
887     /// patterns are either "fixed-length" patterns (`[_, _, _]`) or
888     /// "variable-length" patterns (`[_, .., _]`).
889     ///
890     /// For fixed-length patterns, all slices with lengths *longer* than
891     /// the pattern's length have the same outcome (of not matching), so
892     /// as long as `L` is greater than the pattern's length we can pick
893     /// any `sₘ` from that length and get the same result.
894     ///
895     /// For variable-length patterns, the situation is more complicated,
896     /// because as seen above the precise value of `sₘ` matters.
897     ///
898     /// However, for each variable-length pattern `p` with a prefix of length
899     /// `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
900     /// `slₚ` elements are examined.
901     ///
902     /// Therefore, as long as `L` is positive (to avoid concerns about empty
903     /// types), all elements after the maximum prefix length and before
904     /// the maximum suffix length are not examined by any variable-length
905     /// pattern, and therefore can be added/removed without affecting
906     /// them - creating equivalent patterns from any sufficiently-large
907     /// length.
908     ///
909     /// Of course, if fixed-length patterns exist, we must be sure
910     /// that our length is large enough to miss them all, so
911     /// we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))`
912     ///
913     /// for example, with the above pair of patterns, all elements
914     /// but the first and last can be added/removed, so any
915     /// witness of length ≥2 (say, `[false, false, true]`) can be
916     /// turned to a witness from any other length ≥2.
917     fn split<'p, 'tcx>(
918         self,
919         cx: &MatchCheckCtxt<'p, 'tcx>,
920         matrix: &Matrix<'p, 'tcx>,
921     ) -> SmallVec<[Constructor<'tcx>; 1]> {
922         let (array_len, self_prefix, self_suffix) = match self {
923             Slice { array_len, kind: VarLen(self_prefix, self_suffix) } => {
924                 (array_len, self_prefix, self_suffix)
925             }
926             _ => return smallvec![Slice(self)],
927         };
928
929         let head_ctors = matrix.head_ctors(cx).filter(|c| !c.is_wildcard());
930
931         let mut max_prefix_len = self_prefix;
932         let mut max_suffix_len = self_suffix;
933         let mut max_fixed_len = 0;
934
935         for ctor in head_ctors {
936             if let Slice(slice) = ctor {
937                 match slice.pattern_kind() {
938                     FixedLen(len) => {
939                         max_fixed_len = cmp::max(max_fixed_len, len);
940                     }
941                     VarLen(prefix, suffix) => {
942                         max_prefix_len = cmp::max(max_prefix_len, prefix);
943                         max_suffix_len = cmp::max(max_suffix_len, suffix);
944                     }
945                 }
946             }
947         }
948
949         // For diagnostics, we keep the prefix and suffix lengths separate, so in the case
950         // where `max_fixed_len + 1` is the largest, we adapt `max_prefix_len` accordingly,
951         // so that `L = max_prefix_len + max_suffix_len`.
952         if max_fixed_len + 1 >= max_prefix_len + max_suffix_len {
953             // The subtraction can't overflow thanks to the above check.
954             // The new `max_prefix_len` is also guaranteed to be larger than its previous
955             // value.
956             max_prefix_len = max_fixed_len + 1 - max_suffix_len;
957         }
958
959         match array_len {
960             Some(len) => {
961                 let kind = if max_prefix_len + max_suffix_len < len {
962                     VarLen(max_prefix_len, max_suffix_len)
963                 } else {
964                     FixedLen(len)
965                 };
966                 smallvec![Slice(Slice { array_len, kind })]
967             }
968             None => {
969                 // `ctor` originally covered the range `(self_prefix +
970                 // self_suffix..infinity)`. We now split it into two: lengths smaller than
971                 // `max_prefix_len + max_suffix_len` are treated independently as
972                 // fixed-lengths slices, and lengths above are captured by a final VarLen
973                 // constructor.
974                 let smaller_lengths =
975                     (self_prefix + self_suffix..max_prefix_len + max_suffix_len).map(FixedLen);
976                 let final_slice = VarLen(max_prefix_len, max_suffix_len);
977                 smaller_lengths
978                     .chain(Some(final_slice))
979                     .map(|kind| Slice { array_len, kind })
980                     .map(Slice)
981                     .collect()
982             }
983         }
984     }
985 }
986
987 /// A value can be decomposed into a constructor applied to some fields. This struct represents
988 /// the constructor. See also `Fields`.
989 ///
990 /// `pat_constructor` retrieves the constructor corresponding to a pattern.
991 /// `specialize_constructor` returns the list of fields corresponding to a pattern, given a
992 /// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
993 /// `Fields`.
994 #[derive(Clone, Debug, PartialEq)]
995 enum Constructor<'tcx> {
996     /// The constructor for patterns that have a single constructor, like tuples, struct patterns
997     /// and fixed-length arrays.
998     Single,
999     /// Enum variants.
1000     Variant(DefId),
1001     /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
1002     IntRange(IntRange<'tcx>),
1003     /// Ranges of floating-point literal values (`2.0..=5.2`).
1004     FloatRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
1005     /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
1006     Str(&'tcx ty::Const<'tcx>),
1007     /// Array and slice patterns.
1008     Slice(Slice),
1009     /// Constants that must not be matched structurally. They are treated as black
1010     /// boxes for the purposes of exhaustiveness: we must not inspect them, and they
1011     /// don't count towards making a match exhaustive.
1012     Opaque,
1013     /// Fake extra constructor for enums that aren't allowed to be matched exhaustively.
1014     NonExhaustive,
1015     /// Wildcard pattern.
1016     Wildcard,
1017 }
1018
1019 impl<'tcx> Constructor<'tcx> {
1020     fn is_wildcard(&self) -> bool {
1021         match self {
1022             Wildcard => true,
1023             _ => false,
1024         }
1025     }
1026
1027     fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> VariantIdx {
1028         match *self {
1029             Variant(id) => adt.variant_index_with_id(id),
1030             Single => {
1031                 assert!(!adt.is_enum());
1032                 VariantIdx::new(0)
1033             }
1034             _ => bug!("bad constructor {:?} for adt {:?}", self, adt),
1035         }
1036     }
1037
1038     // Returns the set of constructors covered by `self` but not by
1039     // anything in `other_ctors`.
1040     fn subtract_ctors(&self, other_ctors: &Vec<Constructor<'tcx>>) -> Vec<Constructor<'tcx>> {
1041         if other_ctors.is_empty() {
1042             return vec![self.clone()];
1043         }
1044
1045         match self {
1046             // Those constructors can only match themselves.
1047             Single | Variant(_) | Str(..) | FloatRange(..) => {
1048                 if other_ctors.iter().any(|c| c == self) { vec![] } else { vec![self.clone()] }
1049             }
1050             &Slice(slice) => {
1051                 let mut other_slices = other_ctors
1052                     .iter()
1053                     .filter_map(|c: &Constructor<'_>| match c {
1054                         Slice(slice) => Some(*slice),
1055                         _ => bug!("bad slice pattern constructor {:?}", c),
1056                     })
1057                     .map(Slice::value_kind);
1058
1059                 match slice.value_kind() {
1060                     FixedLen(self_len) => {
1061                         if other_slices.any(|other_slice| other_slice.covers_length(self_len)) {
1062                             vec![]
1063                         } else {
1064                             vec![Slice(slice)]
1065                         }
1066                     }
1067                     kind @ VarLen(..) => {
1068                         let mut remaining_slices = vec![kind];
1069
1070                         // For each used slice, subtract from the current set of slices.
1071                         for other_slice in other_slices {
1072                             remaining_slices = remaining_slices
1073                                 .into_iter()
1074                                 .flat_map(|remaining_slice| remaining_slice.subtract(other_slice))
1075                                 .collect();
1076
1077                             // If the constructors that have been considered so far already cover
1078                             // the entire range of `self`, no need to look at more constructors.
1079                             if remaining_slices.is_empty() {
1080                                 break;
1081                             }
1082                         }
1083
1084                         remaining_slices
1085                             .into_iter()
1086                             .map(|kind| Slice { array_len: slice.array_len, kind })
1087                             .map(Slice)
1088                             .collect()
1089                     }
1090                 }
1091             }
1092             IntRange(self_range) => {
1093                 let mut remaining_ranges = vec![self_range.clone()];
1094                 for other_ctor in other_ctors {
1095                     if let IntRange(other_range) = other_ctor {
1096                         if other_range == self_range {
1097                             // If the `self` range appears directly in a `match` arm, we can
1098                             // eliminate it straight away.
1099                             remaining_ranges = vec![];
1100                         } else {
1101                             // Otherwise explicitly compute the remaining ranges.
1102                             remaining_ranges = other_range.subtract_from(remaining_ranges);
1103                         }
1104
1105                         // If the ranges that have been considered so far already cover the entire
1106                         // range of values, we can return early.
1107                         if remaining_ranges.is_empty() {
1108                             break;
1109                         }
1110                     }
1111                 }
1112
1113                 // Convert the ranges back into constructors.
1114                 remaining_ranges.into_iter().map(IntRange).collect()
1115             }
1116             // This constructor is never covered by anything else
1117             NonExhaustive => vec![NonExhaustive],
1118             Opaque => bug!("found unexpected opaque ctor in all_ctors"),
1119             Wildcard => bug!("found unexpected wildcard ctor in all_ctors"),
1120         }
1121     }
1122
1123     /// Some constructors (namely IntRange and Slice) actually stand for a set of actual
1124     /// constructors (integers and fixed-sized slices). When specializing for these
1125     /// constructors, we want to be specialising for the actual underlying constructors.
1126     /// Naively, we would simply return the list of constructors they correspond to. We instead are
1127     /// more clever: if there are constructors that we know will behave the same wrt the current
1128     /// matrix, we keep them grouped. For example, all slices of a sufficiently large length
1129     /// will either be all useful or all non-useful with a given matrix.
1130     ///
1131     /// See the branches for details on how the splitting is done.
1132     ///
1133     /// This function may discard some irrelevant constructors if this preserves behavior and
1134     /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the
1135     /// matrix, unless all of them are.
1136     ///
1137     /// `hir_id` is `None` when we're evaluating the wildcard pattern. In that case we do not want
1138     /// to lint for overlapping ranges.
1139     fn split<'p>(
1140         &self,
1141         cx: &MatchCheckCtxt<'p, 'tcx>,
1142         pcx: PatCtxt<'tcx>,
1143         matrix: &Matrix<'p, 'tcx>,
1144         hir_id: Option<HirId>,
1145     ) -> SmallVec<[Self; 1]> {
1146         debug!("Constructor::split({:#?}, {:#?})", self, matrix);
1147
1148         match self {
1149             // Fast-track if the range is trivial. In particular, we don't do the overlapping
1150             // ranges check.
1151             IntRange(ctor_range)
1152                 if ctor_range.treat_exhaustively(cx.tcx) && !ctor_range.is_singleton() =>
1153             {
1154                 ctor_range.split(cx, pcx, matrix, hir_id)
1155             }
1156             Slice(slice @ Slice { kind: VarLen(..), .. }) => slice.split(cx, matrix),
1157             // Any other constructor can be used unchanged.
1158             _ => smallvec![self.clone()],
1159         }
1160     }
1161
1162     /// Returns whether `self` is covered by `other`, ie whether `self` is a subset of `other`. For
1163     /// the simple cases, this is simply checking for equality. For the "grouped" constructors,
1164     /// this checks for inclusion.
1165     fn is_covered_by<'p>(
1166         &self,
1167         cx: &MatchCheckCtxt<'p, 'tcx>,
1168         other: &Constructor<'tcx>,
1169         ty: Ty<'tcx>,
1170     ) -> bool {
1171         match (self, other) {
1172             // Wildcards cover anything
1173             (_, Wildcard) => true,
1174             // Wildcards are only covered by wildcards
1175             (Wildcard, _) => false,
1176
1177             (Single, Single) => true,
1178             (Variant(self_id), Variant(other_id)) => self_id == other_id,
1179
1180             (IntRange(self_range), IntRange(other_range)) => {
1181                 if self_range.intersection(cx.tcx, other_range).is_some() {
1182                     // Constructor splitting should ensure that all intersections we encounter
1183                     // are actually inclusions.
1184                     assert!(self_range.is_subrange(other_range));
1185                     true
1186                 } else {
1187                     false
1188                 }
1189             }
1190             (
1191                 FloatRange(self_from, self_to, self_end),
1192                 FloatRange(other_from, other_to, other_end),
1193             ) => {
1194                 match (
1195                     compare_const_vals(cx.tcx, self_to, other_to, cx.param_env, ty),
1196                     compare_const_vals(cx.tcx, self_from, other_from, cx.param_env, ty),
1197                 ) {
1198                     (Some(to), Some(from)) => {
1199                         (from == Ordering::Greater || from == Ordering::Equal)
1200                             && (to == Ordering::Less
1201                                 || (other_end == self_end && to == Ordering::Equal))
1202                     }
1203                     _ => false,
1204                 }
1205             }
1206             (Str(self_val), Str(other_val)) => {
1207                 // FIXME: there's probably a more direct way of comparing for equality
1208                 match compare_const_vals(cx.tcx, self_val, other_val, cx.param_env, ty) {
1209                     Some(comparison) => comparison == Ordering::Equal,
1210                     None => false,
1211                 }
1212             }
1213
1214             (Slice(self_slice), Slice(other_slice)) => {
1215                 other_slice.pattern_kind().covers_length(self_slice.arity())
1216             }
1217
1218             // We are trying to inspect an opaque constant. Thus we skip the row.
1219             (Opaque, _) | (_, Opaque) => false,
1220             // Only a wildcard pattern can match the special extra constructor.
1221             (NonExhaustive, _) => false,
1222
1223             _ => bug!("trying to compare incompatible constructors {:?} and {:?}", self, other),
1224         }
1225     }
1226
1227     /// Apply a constructor to a list of patterns, yielding a new pattern. `pats`
1228     /// must have as many elements as this constructor's arity.
1229     ///
1230     /// This is roughly the inverse of `specialize_constructor`.
1231     ///
1232     /// Examples:
1233     /// `self`: `Constructor::Single`
1234     /// `ty`: `(u32, u32, u32)`
1235     /// `pats`: `[10, 20, _]`
1236     /// returns `(10, 20, _)`
1237     ///
1238     /// `self`: `Constructor::Variant(Option::Some)`
1239     /// `ty`: `Option<bool>`
1240     /// `pats`: `[false]`
1241     /// returns `Some(false)`
1242     fn apply<'p>(
1243         &self,
1244         cx: &MatchCheckCtxt<'p, 'tcx>,
1245         ty: Ty<'tcx>,
1246         fields: Fields<'p, 'tcx>,
1247     ) -> Pat<'tcx> {
1248         let mut subpatterns = fields.all_patterns();
1249
1250         let pat = match self {
1251             Single | Variant(_) => match ty.kind() {
1252                 ty::Adt(..) | ty::Tuple(..) => {
1253                     let subpatterns = subpatterns
1254                         .enumerate()
1255                         .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
1256                         .collect();
1257
1258                     if let ty::Adt(adt, substs) = ty.kind() {
1259                         if adt.is_enum() {
1260                             PatKind::Variant {
1261                                 adt_def: adt,
1262                                 substs,
1263                                 variant_index: self.variant_index_for_adt(adt),
1264                                 subpatterns,
1265                             }
1266                         } else {
1267                             PatKind::Leaf { subpatterns }
1268                         }
1269                     } else {
1270                         PatKind::Leaf { subpatterns }
1271                     }
1272                 }
1273                 ty::Ref(..) => PatKind::Deref { subpattern: subpatterns.next().unwrap() },
1274                 ty::Slice(_) | ty::Array(..) => bug!("bad slice pattern {:?} {:?}", self, ty),
1275                 _ => PatKind::Wild,
1276             },
1277             Slice(slice) => match slice.pattern_kind() {
1278                 FixedLen(_) => {
1279                     PatKind::Slice { prefix: subpatterns.collect(), slice: None, suffix: vec![] }
1280                 }
1281                 VarLen(prefix, _) => {
1282                     let mut prefix: Vec<_> = subpatterns.by_ref().take(prefix as usize).collect();
1283                     if slice.array_len.is_some() {
1284                         // Improves diagnostics a bit: if the type is a known-size array, instead
1285                         // of reporting `[x, _, .., _, y]`, we prefer to report `[x, .., y]`.
1286                         // This is incorrect if the size is not known, since `[_, ..]` captures
1287                         // arrays of lengths `>= 1` whereas `[..]` captures any length.
1288                         while !prefix.is_empty() && prefix.last().unwrap().is_wildcard() {
1289                             prefix.pop();
1290                         }
1291                     }
1292                     let suffix: Vec<_> = if slice.array_len.is_some() {
1293                         // Same as above.
1294                         subpatterns.skip_while(Pat::is_wildcard).collect()
1295                     } else {
1296                         subpatterns.collect()
1297                     };
1298                     let wild = Pat::wildcard_from_ty(ty);
1299                     PatKind::Slice { prefix, slice: Some(wild), suffix }
1300                 }
1301             },
1302             &Str(value) => PatKind::Constant { value },
1303             &FloatRange(lo, hi, end) => PatKind::Range(PatRange { lo, hi, end }),
1304             IntRange(range) => return range.to_pat(cx.tcx),
1305             NonExhaustive => PatKind::Wild,
1306             Opaque => bug!("we should not try to apply an opaque constructor"),
1307             Wildcard => bug!("we should not try to apply a wildcard constructor"),
1308         };
1309
1310         Pat { ty, span: DUMMY_SP, kind: Box::new(pat) }
1311     }
1312 }
1313
1314 /// Some fields need to be explicitly hidden away in certain cases; see the comment above the
1315 /// `Fields` struct. This struct represents such a potentially-hidden field. When a field is hidden
1316 /// we still keep its type around.
1317 #[derive(Debug, Copy, Clone)]
1318 enum FilteredField<'p, 'tcx> {
1319     Kept(&'p Pat<'tcx>),
1320     Hidden(Ty<'tcx>),
1321 }
1322
1323 impl<'p, 'tcx> FilteredField<'p, 'tcx> {
1324     fn kept(self) -> Option<&'p Pat<'tcx>> {
1325         match self {
1326             FilteredField::Kept(p) => Some(p),
1327             FilteredField::Hidden(_) => None,
1328         }
1329     }
1330
1331     fn to_pattern(self) -> Pat<'tcx> {
1332         match self {
1333             FilteredField::Kept(p) => p.clone(),
1334             FilteredField::Hidden(ty) => Pat::wildcard_from_ty(ty),
1335         }
1336     }
1337 }
1338
1339 /// A value can be decomposed into a constructor applied to some fields. This struct represents
1340 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
1341 ///
1342 /// If a private or `non_exhaustive` field is uninhabited, the code mustn't observe that it is
1343 /// uninhabited. For that, we filter these fields out of the matrix. This is subtle because we
1344 /// still need to have those fields back when going to/from a `Pat`. Most of this is handled
1345 /// automatically in `Fields`, but when constructing or deconstructing `Fields` you need to be
1346 /// careful. As a rule, when going to/from the matrix, use the filtered field list; when going
1347 /// to/from `Pat`, use the full field list.
1348 /// This filtering is uncommon in practice, because uninhabited fields are rarely used, so we avoid
1349 /// it when possible to preserve performance.
1350 #[derive(Debug, Clone)]
1351 enum Fields<'p, 'tcx> {
1352     /// Lists of patterns that don't contain any filtered fields.
1353     /// `Slice` and `Vec` behave the same; the difference is only to avoid allocating and
1354     /// triple-dereferences when possible. Frankly this is premature optimization, I (Nadrieril)
1355     /// have not measured if it really made a difference.
1356     Slice(&'p [Pat<'tcx>]),
1357     Vec(SmallVec<[&'p Pat<'tcx>; 2]>),
1358     /// Patterns where some of the fields need to be hidden. `kept_count` caches the number of
1359     /// non-hidden fields.
1360     Filtered {
1361         fields: SmallVec<[FilteredField<'p, 'tcx>; 2]>,
1362         kept_count: usize,
1363     },
1364 }
1365
1366 impl<'p, 'tcx> Fields<'p, 'tcx> {
1367     fn empty() -> Self {
1368         Fields::Slice(&[])
1369     }
1370
1371     /// Construct a new `Fields` from the given pattern. Must not be used if the pattern is a field
1372     /// of a struct/tuple/variant.
1373     fn from_single_pattern(pat: &'p Pat<'tcx>) -> Self {
1374         Fields::Slice(std::slice::from_ref(pat))
1375     }
1376
1377     /// Convenience; internal use.
1378     fn wildcards_from_tys(
1379         cx: &MatchCheckCtxt<'p, 'tcx>,
1380         tys: impl IntoIterator<Item = Ty<'tcx>>,
1381     ) -> Self {
1382         let wilds = tys.into_iter().map(Pat::wildcard_from_ty);
1383         let pats = cx.pattern_arena.alloc_from_iter(wilds);
1384         Fields::Slice(pats)
1385     }
1386
1387     /// Creates a new list of wildcard fields for a given constructor.
1388     fn wildcards(
1389         cx: &MatchCheckCtxt<'p, 'tcx>,
1390         constructor: &Constructor<'tcx>,
1391         ty: Ty<'tcx>,
1392     ) -> Self {
1393         let wildcard_from_ty = |ty| &*cx.pattern_arena.alloc(Pat::wildcard_from_ty(ty));
1394
1395         let ret = match constructor {
1396             Single | Variant(_) => match ty.kind() {
1397                 ty::Tuple(ref fs) => {
1398                     Fields::wildcards_from_tys(cx, fs.into_iter().map(|ty| ty.expect_ty()))
1399                 }
1400                 ty::Ref(_, rty, _) => Fields::from_single_pattern(wildcard_from_ty(rty)),
1401                 ty::Adt(adt, substs) => {
1402                     if adt.is_box() {
1403                         // Use T as the sub pattern type of Box<T>.
1404                         Fields::from_single_pattern(wildcard_from_ty(substs.type_at(0)))
1405                     } else {
1406                         let variant = &adt.variants[constructor.variant_index_for_adt(adt)];
1407                         // Whether we must not match the fields of this variant exhaustively.
1408                         let is_non_exhaustive =
1409                             variant.is_field_list_non_exhaustive() && !adt.did.is_local();
1410                         let field_tys = variant.fields.iter().map(|field| field.ty(cx.tcx, substs));
1411                         // In the following cases, we don't need to filter out any fields. This is
1412                         // the vast majority of real cases, since uninhabited fields are uncommon.
1413                         let has_no_hidden_fields = (adt.is_enum() && !is_non_exhaustive)
1414                             || !field_tys.clone().any(|ty| cx.is_uninhabited(ty));
1415
1416                         if has_no_hidden_fields {
1417                             Fields::wildcards_from_tys(cx, field_tys)
1418                         } else {
1419                             let mut kept_count = 0;
1420                             let fields = variant
1421                                 .fields
1422                                 .iter()
1423                                 .map(|field| {
1424                                     let ty = field.ty(cx.tcx, substs);
1425                                     let is_visible = adt.is_enum()
1426                                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1427                                     let is_uninhabited = cx.is_uninhabited(ty);
1428
1429                                     // In the cases of either a `#[non_exhaustive]` field list
1430                                     // or a non-public field, we hide uninhabited fields in
1431                                     // order not to reveal the uninhabitedness of the whole
1432                                     // variant.
1433                                     if is_uninhabited && (!is_visible || is_non_exhaustive) {
1434                                         FilteredField::Hidden(ty)
1435                                     } else {
1436                                         kept_count += 1;
1437                                         FilteredField::Kept(wildcard_from_ty(ty))
1438                                     }
1439                                 })
1440                                 .collect();
1441                             Fields::Filtered { fields, kept_count }
1442                         }
1443                     }
1444                 }
1445                 _ => Fields::empty(),
1446             },
1447             Slice(slice) => match *ty.kind() {
1448                 ty::Slice(ty) | ty::Array(ty, _) => {
1449                     let arity = slice.arity();
1450                     Fields::wildcards_from_tys(cx, (0..arity).map(|_| ty))
1451                 }
1452                 _ => bug!("bad slice pattern {:?} {:?}", constructor, ty),
1453             },
1454             Str(..) | FloatRange(..) | IntRange(..) | NonExhaustive | Opaque | Wildcard => {
1455                 Fields::empty()
1456             }
1457         };
1458         debug!("Fields::wildcards({:?}, {:?}) = {:#?}", constructor, ty, ret);
1459         ret
1460     }
1461
1462     /// Returns the number of patterns from the viewpoint of match-checking, i.e. excluding hidden
1463     /// fields. This is what we want in most cases in this file, the only exception being
1464     /// conversion to/from `Pat`.
1465     fn len(&self) -> usize {
1466         match self {
1467             Fields::Slice(pats) => pats.len(),
1468             Fields::Vec(pats) => pats.len(),
1469             Fields::Filtered { kept_count, .. } => *kept_count,
1470         }
1471     }
1472
1473     /// Returns the complete list of patterns, including hidden fields.
1474     fn all_patterns(self) -> impl Iterator<Item = Pat<'tcx>> {
1475         let pats: SmallVec<[_; 2]> = match self {
1476             Fields::Slice(pats) => pats.iter().cloned().collect(),
1477             Fields::Vec(pats) => pats.into_iter().cloned().collect(),
1478             Fields::Filtered { fields, .. } => {
1479                 // We don't skip any fields here.
1480                 fields.into_iter().map(|p| p.to_pattern()).collect()
1481             }
1482         };
1483         pats.into_iter()
1484     }
1485
1486     /// Overrides some of the fields with the provided patterns. Exactly like
1487     /// `replace_fields_indexed`, except that it takes `FieldPat`s as input.
1488     fn replace_with_fieldpats(
1489         &self,
1490         new_pats: impl IntoIterator<Item = &'p FieldPat<'tcx>>,
1491     ) -> Self {
1492         self.replace_fields_indexed(
1493             new_pats.into_iter().map(|pat| (pat.field.index(), &pat.pattern)),
1494         )
1495     }
1496
1497     /// Overrides some of the fields with the provided patterns. This is used when a pattern
1498     /// defines some fields but not all, for example `Foo { field1: Some(_), .. }`: here we start with a
1499     /// `Fields` that is just one wildcard per field of the `Foo` struct, and override the entry
1500     /// corresponding to `field1` with the pattern `Some(_)`. This is also used for slice patterns
1501     /// for the same reason.
1502     fn replace_fields_indexed(
1503         &self,
1504         new_pats: impl IntoIterator<Item = (usize, &'p Pat<'tcx>)>,
1505     ) -> Self {
1506         let mut fields = self.clone();
1507         if let Fields::Slice(pats) = fields {
1508             fields = Fields::Vec(pats.iter().collect());
1509         }
1510
1511         match &mut fields {
1512             Fields::Vec(pats) => {
1513                 for (i, pat) in new_pats {
1514                     pats[i] = pat
1515                 }
1516             }
1517             Fields::Filtered { fields, .. } => {
1518                 for (i, pat) in new_pats {
1519                     if let FilteredField::Kept(p) = &mut fields[i] {
1520                         *p = pat
1521                     }
1522                 }
1523             }
1524             Fields::Slice(_) => unreachable!(),
1525         }
1526         fields
1527     }
1528
1529     /// Replaces contained fields with the given filtered list of patterns, e.g. taken from the
1530     /// matrix. There must be `len()` patterns in `pats`.
1531     fn replace_fields(
1532         &self,
1533         cx: &MatchCheckCtxt<'p, 'tcx>,
1534         pats: impl IntoIterator<Item = Pat<'tcx>>,
1535     ) -> Self {
1536         let pats: &[_] = cx.pattern_arena.alloc_from_iter(pats);
1537
1538         match self {
1539             Fields::Filtered { fields, kept_count } => {
1540                 let mut pats = pats.iter();
1541                 let mut fields = fields.clone();
1542                 for f in &mut fields {
1543                     if let FilteredField::Kept(p) = f {
1544                         // We take one input pattern for each `Kept` field, in order.
1545                         *p = pats.next().unwrap();
1546                     }
1547                 }
1548                 Fields::Filtered { fields, kept_count: *kept_count }
1549             }
1550             _ => Fields::Slice(pats),
1551         }
1552     }
1553
1554     /// Replaces contained fields with the arguments of the given pattern. Only use on a pattern
1555     /// that is compatible with the constructor used to build `self`.
1556     /// This is meant to be used on the result of `Fields::wildcards()`. The idea is that
1557     /// `wildcards` constructs a list of fields where all entries are wildcards, and the pattern
1558     /// provided to this function fills some of the fields with non-wildcards.
1559     /// In the following example `Fields::wildcards` would return `[_, _, _, _]`. If we call
1560     /// `replace_with_pattern_arguments` on it with the pattern, the result will be `[Some(0), _,
1561     /// _, _]`.
1562     /// ```rust
1563     /// let x: [Option<u8>; 4] = foo();
1564     /// match x {
1565     ///     [Some(0), ..] => {}
1566     /// }
1567     /// ```
1568     fn replace_with_pattern_arguments(&self, pat: &'p Pat<'tcx>) -> Self {
1569         match pat.kind.as_ref() {
1570             PatKind::Deref { subpattern } => Self::from_single_pattern(subpattern),
1571             PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
1572                 self.replace_with_fieldpats(subpatterns)
1573             }
1574             PatKind::Array { prefix, suffix, .. } | PatKind::Slice { prefix, suffix, .. } => {
1575                 // Number of subpatterns for the constructor
1576                 let ctor_arity = self.len();
1577
1578                 // Replace the prefix and the suffix with the given patterns, leaving wildcards in
1579                 // the middle if there was a subslice pattern `..`.
1580                 let prefix = prefix.iter().enumerate();
1581                 let suffix =
1582                     suffix.iter().enumerate().map(|(i, p)| (ctor_arity - suffix.len() + i, p));
1583                 self.replace_fields_indexed(prefix.chain(suffix))
1584             }
1585             _ => self.clone(),
1586         }
1587     }
1588
1589     fn push_on_patstack(self, stack: &[&'p Pat<'tcx>]) -> PatStack<'p, 'tcx> {
1590         let pats: SmallVec<_> = match self {
1591             Fields::Slice(pats) => pats.iter().chain(stack.iter().copied()).collect(),
1592             Fields::Vec(mut pats) => {
1593                 pats.extend_from_slice(stack);
1594                 pats
1595             }
1596             Fields::Filtered { fields, .. } => {
1597                 // We skip hidden fields here
1598                 fields.into_iter().filter_map(|p| p.kept()).chain(stack.iter().copied()).collect()
1599             }
1600         };
1601         PatStack::from_vec(pats)
1602     }
1603 }
1604
1605 #[derive(Clone, Debug)]
1606 crate enum Usefulness<'tcx> {
1607     /// Carries a list of unreachable subpatterns. Used only in the presence of or-patterns.
1608     Useful(Vec<Span>),
1609     /// Carries a list of witnesses of non-exhaustiveness.
1610     UsefulWithWitness(Vec<Witness<'tcx>>),
1611     NotUseful,
1612 }
1613
1614 impl<'tcx> Usefulness<'tcx> {
1615     fn new_useful(preference: WitnessPreference) -> Self {
1616         match preference {
1617             ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1618             LeaveOutWitness => Useful(vec![]),
1619         }
1620     }
1621
1622     fn is_useful(&self) -> bool {
1623         match *self {
1624             NotUseful => false,
1625             _ => true,
1626         }
1627     }
1628
1629     fn apply_constructor<'p>(
1630         self,
1631         cx: &MatchCheckCtxt<'p, 'tcx>,
1632         ctor: &Constructor<'tcx>,
1633         ty: Ty<'tcx>,
1634         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1635     ) -> Self {
1636         match self {
1637             UsefulWithWitness(witnesses) => UsefulWithWitness(
1638                 witnesses
1639                     .into_iter()
1640                     .map(|witness| witness.apply_constructor(cx, &ctor, ty, ctor_wild_subpatterns))
1641                     .collect(),
1642             ),
1643             x => x,
1644         }
1645     }
1646
1647     fn apply_wildcard<'p>(
1648         self,
1649         cx: &MatchCheckCtxt<'p, 'tcx>,
1650         pcx: PatCtxt<'tcx>,
1651         missing_ctors: MissingConstructors<'tcx>,
1652     ) -> Self {
1653         match self {
1654             UsefulWithWitness(witnesses) => {
1655                 let new_patterns = missing_ctors.report_patterns(cx, pcx);
1656                 UsefulWithWitness(
1657                     witnesses
1658                         .into_iter()
1659                         .flat_map(|witness| {
1660                             new_patterns.iter().map(move |pat| {
1661                                 let mut witness = witness.clone();
1662                                 witness.0.push(pat.clone());
1663                                 witness
1664                             })
1665                         })
1666                         .collect(),
1667                 )
1668             }
1669             x => x,
1670         }
1671     }
1672 }
1673
1674 #[derive(Copy, Clone, Debug)]
1675 crate enum WitnessPreference {
1676     ConstructWitness,
1677     LeaveOutWitness,
1678 }
1679
1680 #[derive(Copy, Clone, Debug)]
1681 struct PatCtxt<'tcx> {
1682     ty: Ty<'tcx>,
1683     span: Span,
1684 }
1685
1686 /// A witness of non-exhaustiveness for error reporting, represented
1687 /// as a list of patterns (in reverse order of construction) with
1688 /// wildcards inside to represent elements that can take any inhabitant
1689 /// of the type as a value.
1690 ///
1691 /// A witness against a list of patterns should have the same types
1692 /// and length as the pattern matched against. Because Rust `match`
1693 /// is always against a single pattern, at the end the witness will
1694 /// have length 1, but in the middle of the algorithm, it can contain
1695 /// multiple patterns.
1696 ///
1697 /// For example, if we are constructing a witness for the match against
1698 ///
1699 /// ```
1700 /// struct Pair(Option<(u32, u32)>, bool);
1701 ///
1702 /// match (p: Pair) {
1703 ///    Pair(None, _) => {}
1704 ///    Pair(_, false) => {}
1705 /// }
1706 /// ```
1707 ///
1708 /// We'll perform the following steps:
1709 /// 1. Start with an empty witness
1710 ///     `Witness(vec![])`
1711 /// 2. Push a witness `Some(_)` against the `None`
1712 ///     `Witness(vec![Some(_)])`
1713 /// 3. Push a witness `true` against the `false`
1714 ///     `Witness(vec![Some(_), true])`
1715 /// 4. Apply the `Pair` constructor to the witnesses
1716 ///     `Witness(vec![Pair(Some(_), true)])`
1717 ///
1718 /// The final `Pair(Some(_), true)` is then the resulting witness.
1719 #[derive(Clone, Debug)]
1720 crate struct Witness<'tcx>(Vec<Pat<'tcx>>);
1721
1722 impl<'tcx> Witness<'tcx> {
1723     crate fn single_pattern(self) -> Pat<'tcx> {
1724         assert_eq!(self.0.len(), 1);
1725         self.0.into_iter().next().unwrap()
1726     }
1727
1728     /// Constructs a partial witness for a pattern given a list of
1729     /// patterns expanded by the specialization step.
1730     ///
1731     /// When a pattern P is discovered to be useful, this function is used bottom-up
1732     /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
1733     /// of values, V, where each value in that set is not covered by any previously
1734     /// used patterns and is covered by the pattern P'. Examples:
1735     ///
1736     /// left_ty: tuple of 3 elements
1737     /// pats: [10, 20, _]           => (10, 20, _)
1738     ///
1739     /// left_ty: struct X { a: (bool, &'static str), b: usize}
1740     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
1741     fn apply_constructor<'p>(
1742         mut self,
1743         cx: &MatchCheckCtxt<'p, 'tcx>,
1744         ctor: &Constructor<'tcx>,
1745         ty: Ty<'tcx>,
1746         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1747     ) -> Self {
1748         let pat = {
1749             let len = self.0.len();
1750             let arity = ctor_wild_subpatterns.len();
1751             let pats = self.0.drain((len - arity)..).rev();
1752             let fields = ctor_wild_subpatterns.replace_fields(cx, pats);
1753             ctor.apply(cx, ty, fields)
1754         };
1755
1756         self.0.push(pat);
1757
1758         self
1759     }
1760 }
1761
1762 /// This determines the set of all possible constructors of a pattern matching
1763 /// values of type `left_ty`. For vectors, this would normally be an infinite set
1764 /// but is instead bounded by the maximum fixed length of slice patterns in
1765 /// the column of patterns being analyzed.
1766 ///
1767 /// We make sure to omit constructors that are statically impossible. E.g., for
1768 /// `Option<!>`, we do not include `Some(_)` in the returned list of constructors.
1769 /// Invariant: this returns an empty `Vec` if and only if the type is uninhabited (as determined by
1770 /// `cx.is_uninhabited()`).
1771 fn all_constructors<'a, 'tcx>(
1772     cx: &MatchCheckCtxt<'a, 'tcx>,
1773     pcx: PatCtxt<'tcx>,
1774 ) -> Vec<Constructor<'tcx>> {
1775     debug!("all_constructors({:?})", pcx.ty);
1776     let make_range = |start, end| {
1777         IntRange(
1778             // `unwrap()` is ok because we know the type is an integer.
1779             IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included, pcx.span)
1780                 .unwrap(),
1781         )
1782     };
1783     match *pcx.ty.kind() {
1784         ty::Bool => vec![make_range(0, 1)],
1785         ty::Array(ref sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => {
1786             let len = len.eval_usize(cx.tcx, cx.param_env);
1787             if len != 0 && cx.is_uninhabited(sub_ty) {
1788                 vec![]
1789             } else {
1790                 vec![Slice(Slice { array_len: Some(len), kind: VarLen(0, 0) })]
1791             }
1792         }
1793         // Treat arrays of a constant but unknown length like slices.
1794         ty::Array(ref sub_ty, _) | ty::Slice(ref sub_ty) => {
1795             let kind = if cx.is_uninhabited(sub_ty) { FixedLen(0) } else { VarLen(0, 0) };
1796             vec![Slice(Slice { array_len: None, kind })]
1797         }
1798         ty::Adt(def, substs) if def.is_enum() => {
1799             let ctors: Vec<_> = if cx.tcx.features().exhaustive_patterns {
1800                 // If `exhaustive_patterns` is enabled, we exclude variants known to be
1801                 // uninhabited.
1802                 def.variants
1803                     .iter()
1804                     .filter(|v| {
1805                         !v.uninhabited_from(cx.tcx, substs, def.adt_kind(), cx.param_env)
1806                             .contains(cx.tcx, cx.module)
1807                     })
1808                     .map(|v| Variant(v.def_id))
1809                     .collect()
1810             } else {
1811                 def.variants.iter().map(|v| Variant(v.def_id)).collect()
1812             };
1813
1814             // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
1815             // additional "unknown" constructor.
1816             // There is no point in enumerating all possible variants, because the user can't
1817             // actually match against them all themselves. So we always return only the fictitious
1818             // constructor.
1819             // E.g., in an example like:
1820             //
1821             // ```
1822             //     let err: io::ErrorKind = ...;
1823             //     match err {
1824             //         io::ErrorKind::NotFound => {},
1825             //     }
1826             // ```
1827             //
1828             // we don't want to show every possible IO error, but instead have only `_` as the
1829             // witness.
1830             let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
1831
1832             // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
1833             // as though it had an "unknown" constructor to avoid exposing its emptyness. Note that
1834             // an empty match will still be considered exhaustive because that case is handled
1835             // separately in `check_match`.
1836             let is_secretly_empty =
1837                 def.variants.is_empty() && !cx.tcx.features().exhaustive_patterns;
1838
1839             if is_secretly_empty || is_declared_nonexhaustive { vec![NonExhaustive] } else { ctors }
1840         }
1841         ty::Char => {
1842             vec![
1843                 // The valid Unicode Scalar Value ranges.
1844                 make_range('\u{0000}' as u128, '\u{D7FF}' as u128),
1845                 make_range('\u{E000}' as u128, '\u{10FFFF}' as u128),
1846             ]
1847         }
1848         ty::Int(_) | ty::Uint(_)
1849             if pcx.ty.is_ptr_sized_integral()
1850                 && !cx.tcx.features().precise_pointer_size_matching =>
1851         {
1852             // `usize`/`isize` are not allowed to be matched exhaustively unless the
1853             // `precise_pointer_size_matching` feature is enabled. So we treat those types like
1854             // `#[non_exhaustive]` enums by returning a special unmatcheable constructor.
1855             vec![NonExhaustive]
1856         }
1857         ty::Int(ity) => {
1858             let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128;
1859             let min = 1u128 << (bits - 1);
1860             let max = min - 1;
1861             vec![make_range(min, max)]
1862         }
1863         ty::Uint(uty) => {
1864             let size = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size();
1865             let max = truncate(u128::MAX, size);
1866             vec![make_range(0, max)]
1867         }
1868         _ => {
1869             if cx.is_uninhabited(pcx.ty) {
1870                 vec![]
1871             } else {
1872                 vec![Single]
1873             }
1874         }
1875     }
1876 }
1877
1878 /// An inclusive interval, used for precise integer exhaustiveness checking.
1879 /// `IntRange`s always store a contiguous range. This means that values are
1880 /// encoded such that `0` encodes the minimum value for the integer,
1881 /// regardless of the signedness.
1882 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
1883 /// This makes comparisons and arithmetic on interval endpoints much more
1884 /// straightforward. See `signed_bias` for details.
1885 ///
1886 /// `IntRange` is never used to encode an empty range or a "range" that wraps
1887 /// around the (offset) space: i.e., `range.lo <= range.hi`.
1888 #[derive(Clone, Debug)]
1889 struct IntRange<'tcx> {
1890     range: RangeInclusive<u128>,
1891     ty: Ty<'tcx>,
1892     span: Span,
1893 }
1894
1895 impl<'tcx> IntRange<'tcx> {
1896     #[inline]
1897     fn is_integral(ty: Ty<'_>) -> bool {
1898         match ty.kind() {
1899             ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool => true,
1900             _ => false,
1901         }
1902     }
1903
1904     fn is_singleton(&self) -> bool {
1905         self.range.start() == self.range.end()
1906     }
1907
1908     fn boundaries(&self) -> (u128, u128) {
1909         (*self.range.start(), *self.range.end())
1910     }
1911
1912     /// Don't treat `usize`/`isize` exhaustively unless the `precise_pointer_size_matching` feature
1913     /// is enabled.
1914     fn treat_exhaustively(&self, tcx: TyCtxt<'tcx>) -> bool {
1915         !self.ty.is_ptr_sized_integral() || tcx.features().precise_pointer_size_matching
1916     }
1917
1918     #[inline]
1919     fn integral_size_and_signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'_>) -> Option<(Size, u128)> {
1920         match *ty.kind() {
1921             ty::Bool => Some((Size::from_bytes(1), 0)),
1922             ty::Char => Some((Size::from_bytes(4), 0)),
1923             ty::Int(ity) => {
1924                 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1925                 Some((size, 1u128 << (size.bits() as u128 - 1)))
1926             }
1927             ty::Uint(uty) => Some((Integer::from_attr(&tcx, UnsignedInt(uty)).size(), 0)),
1928             _ => None,
1929         }
1930     }
1931
1932     #[inline]
1933     fn from_const(
1934         tcx: TyCtxt<'tcx>,
1935         param_env: ty::ParamEnv<'tcx>,
1936         value: &Const<'tcx>,
1937         span: Span,
1938     ) -> Option<IntRange<'tcx>> {
1939         if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) {
1940             let ty = value.ty;
1941             let val = (|| {
1942                 if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val {
1943                     // For this specific pattern we can skip a lot of effort and go
1944                     // straight to the result, after doing a bit of checking. (We
1945                     // could remove this branch and just fall through, which
1946                     // is more general but much slower.)
1947                     if let Ok(bits) = scalar.to_bits_or_ptr(target_size, &tcx) {
1948                         return Some(bits);
1949                     }
1950                 }
1951                 // This is a more general form of the previous case.
1952                 value.try_eval_bits(tcx, param_env, ty)
1953             })()?;
1954             let val = val ^ bias;
1955             Some(IntRange { range: val..=val, ty, span })
1956         } else {
1957             None
1958         }
1959     }
1960
1961     #[inline]
1962     fn from_range(
1963         tcx: TyCtxt<'tcx>,
1964         lo: u128,
1965         hi: u128,
1966         ty: Ty<'tcx>,
1967         end: &RangeEnd,
1968         span: Span,
1969     ) -> Option<IntRange<'tcx>> {
1970         if Self::is_integral(ty) {
1971             // Perform a shift if the underlying types are signed,
1972             // which makes the interval arithmetic simpler.
1973             let bias = IntRange::signed_bias(tcx, ty);
1974             let (lo, hi) = (lo ^ bias, hi ^ bias);
1975             let offset = (*end == RangeEnd::Excluded) as u128;
1976             if lo > hi || (lo == hi && *end == RangeEnd::Excluded) {
1977                 // This should have been caught earlier by E0030.
1978                 bug!("malformed range pattern: {}..={}", lo, (hi - offset));
1979             }
1980             Some(IntRange { range: lo..=(hi - offset), ty, span })
1981         } else {
1982             None
1983         }
1984     }
1985
1986     fn from_ctor<'a>(ctor: &'a Constructor<'tcx>) -> Option<&'a IntRange<'tcx>> {
1987         match ctor {
1988             IntRange(range) => Some(range),
1989             _ => None,
1990         }
1991     }
1992
1993     // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
1994     fn signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> u128 {
1995         match *ty.kind() {
1996             ty::Int(ity) => {
1997                 let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128;
1998                 1u128 << (bits - 1)
1999             }
2000             _ => 0,
2001         }
2002     }
2003
2004     /// Returns a collection of ranges that spans the values covered by `ranges`, subtracted
2005     /// by the values covered by `self`: i.e., `ranges \ self` (in set notation).
2006     fn subtract_from(&self, ranges: Vec<IntRange<'tcx>>) -> Vec<IntRange<'tcx>> {
2007         let mut remaining_ranges = vec![];
2008         let ty = self.ty;
2009         let span = self.span;
2010         let (lo, hi) = self.boundaries();
2011         for subrange in ranges {
2012             let (subrange_lo, subrange_hi) = subrange.range.into_inner();
2013             if lo > subrange_hi || subrange_lo > hi {
2014                 // The pattern doesn't intersect with the subrange at all,
2015                 // so the subrange remains untouched.
2016                 remaining_ranges.push(IntRange { range: subrange_lo..=subrange_hi, ty, span });
2017             } else {
2018                 if lo > subrange_lo {
2019                     // The pattern intersects an upper section of the
2020                     // subrange, so a lower section will remain.
2021                     remaining_ranges.push(IntRange { range: subrange_lo..=(lo - 1), ty, span });
2022                 }
2023                 if hi < subrange_hi {
2024                     // The pattern intersects a lower section of the
2025                     // subrange, so an upper section will remain.
2026                     remaining_ranges.push(IntRange { range: (hi + 1)..=subrange_hi, ty, span });
2027                 }
2028             }
2029         }
2030         remaining_ranges
2031     }
2032
2033     fn is_subrange(&self, other: &Self) -> bool {
2034         other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
2035     }
2036
2037     fn intersection(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Option<Self> {
2038         let ty = self.ty;
2039         let (lo, hi) = self.boundaries();
2040         let (other_lo, other_hi) = other.boundaries();
2041         if self.treat_exhaustively(tcx) {
2042             if lo <= other_hi && other_lo <= hi {
2043                 let span = other.span;
2044                 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty, span })
2045             } else {
2046                 None
2047             }
2048         } else {
2049             // If the range should not be treated exhaustively, fallback to checking for inclusion.
2050             if self.is_subrange(other) { Some(self.clone()) } else { None }
2051         }
2052     }
2053
2054     fn suspicious_intersection(&self, other: &Self) -> bool {
2055         // `false` in the following cases:
2056         // 1     ----      // 1  ----------   // 1 ----        // 1       ----
2057         // 2  ----------   // 2     ----      // 2       ----  // 2 ----
2058         //
2059         // The following are currently `false`, but could be `true` in the future (#64007):
2060         // 1 ---------       // 1     ---------
2061         // 2     ----------  // 2 ----------
2062         //
2063         // `true` in the following cases:
2064         // 1 -------          // 1       -------
2065         // 2       --------   // 2 -------
2066         let (lo, hi) = self.boundaries();
2067         let (other_lo, other_hi) = other.boundaries();
2068         lo == other_hi || hi == other_lo
2069     }
2070
2071     fn to_pat(&self, tcx: TyCtxt<'tcx>) -> Pat<'tcx> {
2072         let (lo, hi) = self.boundaries();
2073
2074         let bias = IntRange::signed_bias(tcx, self.ty);
2075         let (lo, hi) = (lo ^ bias, hi ^ bias);
2076
2077         let ty = ty::ParamEnv::empty().and(self.ty);
2078         let lo_const = ty::Const::from_bits(tcx, lo, ty);
2079         let hi_const = ty::Const::from_bits(tcx, hi, ty);
2080
2081         let kind = if lo == hi {
2082             PatKind::Constant { value: lo_const }
2083         } else {
2084             PatKind::Range(PatRange { lo: lo_const, hi: hi_const, end: RangeEnd::Included })
2085         };
2086
2087         // This is a brand new pattern, so we don't reuse `self.span`.
2088         Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(kind) }
2089     }
2090
2091     /// For exhaustive integer matching, some constructors are grouped within other constructors
2092     /// (namely integer typed values are grouped within ranges). However, when specialising these
2093     /// constructors, we want to be specialising for the underlying constructors (the integers), not
2094     /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
2095     /// mean creating a separate constructor for every single value in the range, which is clearly
2096     /// impractical. However, observe that for some ranges of integers, the specialisation will be
2097     /// identical across all values in that range (i.e., there are equivalence classes of ranges of
2098     /// constructors based on their `U(S(c, P), S(c, p))` outcome). These classes are grouped by
2099     /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
2100     /// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
2101     /// change.
2102     /// Our solution, therefore, is to split the range constructor into subranges at every single point
2103     /// the group of intersecting patterns changes (using the method described below).
2104     /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
2105     /// on actual integers. The nice thing about this is that the number of subranges is linear in the
2106     /// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't
2107     /// need to be worried about matching over gargantuan ranges.
2108     ///
2109     /// Essentially, given the first column of a matrix representing ranges, looking like the following:
2110     ///
2111     /// |------|  |----------| |-------|    ||
2112     ///    |-------| |-------|            |----| ||
2113     ///       |---------|
2114     ///
2115     /// We split the ranges up into equivalence classes so the ranges are no longer overlapping:
2116     ///
2117     /// |--|--|||-||||--||---|||-------|  |-|||| ||
2118     ///
2119     /// The logic for determining how to split the ranges is fairly straightforward: we calculate
2120     /// boundaries for each interval range, sort them, then create constructors for each new interval
2121     /// between every pair of boundary points. (This essentially sums up to performing the intuitive
2122     /// merging operation depicted above.)
2123     fn split<'p>(
2124         &self,
2125         cx: &MatchCheckCtxt<'p, 'tcx>,
2126         pcx: PatCtxt<'tcx>,
2127         matrix: &Matrix<'p, 'tcx>,
2128         hir_id: Option<HirId>,
2129     ) -> SmallVec<[Constructor<'tcx>; 1]> {
2130         let ty = pcx.ty;
2131
2132         /// Represents a border between 2 integers. Because the intervals spanning borders
2133         /// must be able to cover every integer, we need to be able to represent
2134         /// 2^128 + 1 such borders.
2135         #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2136         enum Border {
2137             JustBefore(u128),
2138             AfterMax,
2139         }
2140
2141         // A function for extracting the borders of an integer interval.
2142         fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
2143             let (lo, hi) = r.range.into_inner();
2144             let from = Border::JustBefore(lo);
2145             let to = match hi.checked_add(1) {
2146                 Some(m) => Border::JustBefore(m),
2147                 None => Border::AfterMax,
2148             };
2149             vec![from, to].into_iter()
2150         }
2151
2152         // Collect the span and range of all the intersecting ranges to lint on likely
2153         // incorrect range patterns. (#63987)
2154         let mut overlaps = vec![];
2155         let row_len = matrix.patterns.get(0).map(|r| r.len()).unwrap_or(0);
2156         // `borders` is the set of borders between equivalence classes: each equivalence
2157         // class lies between 2 borders.
2158         let row_borders = matrix
2159             .head_ctors(cx)
2160             .filter_map(|ctor| IntRange::from_ctor(ctor))
2161             .filter_map(|range| {
2162                 let intersection = self.intersection(cx.tcx, &range);
2163                 let should_lint = self.suspicious_intersection(&range);
2164                 if let (Some(range), 1, true) = (&intersection, row_len, should_lint) {
2165                     // FIXME: for now, only check for overlapping ranges on simple range
2166                     // patterns. Otherwise with the current logic the following is detected
2167                     // as overlapping:
2168                     //   match (10u8, true) {
2169                     //    (0 ..= 125, false) => {}
2170                     //    (126 ..= 255, false) => {}
2171                     //    (0 ..= 255, true) => {}
2172                     //  }
2173                     overlaps.push(range.clone());
2174                 }
2175                 intersection
2176             })
2177             .flat_map(range_borders);
2178         let self_borders = range_borders(self.clone());
2179         let mut borders: Vec<_> = row_borders.chain(self_borders).collect();
2180         borders.sort_unstable();
2181
2182         self.lint_overlapping_patterns(cx.tcx, hir_id, ty, overlaps);
2183
2184         // We're going to iterate through every adjacent pair of borders, making sure that
2185         // each represents an interval of nonnegative length, and convert each such
2186         // interval into a constructor.
2187         borders
2188             .array_windows()
2189             .filter_map(|&pair| match pair {
2190                 [Border::JustBefore(n), Border::JustBefore(m)] => {
2191                     if n < m {
2192                         Some(n..=(m - 1))
2193                     } else {
2194                         None
2195                     }
2196                 }
2197                 [Border::JustBefore(n), Border::AfterMax] => Some(n..=u128::MAX),
2198                 [Border::AfterMax, _] => None,
2199             })
2200             .map(|range| IntRange { range, ty, span: pcx.span })
2201             .map(IntRange)
2202             .collect()
2203     }
2204
2205     fn lint_overlapping_patterns(
2206         &self,
2207         tcx: TyCtxt<'tcx>,
2208         hir_id: Option<HirId>,
2209         ty: Ty<'tcx>,
2210         overlaps: Vec<IntRange<'tcx>>,
2211     ) {
2212         if let (true, Some(hir_id)) = (!overlaps.is_empty(), hir_id) {
2213             tcx.struct_span_lint_hir(
2214                 lint::builtin::OVERLAPPING_PATTERNS,
2215                 hir_id,
2216                 self.span,
2217                 |lint| {
2218                     let mut err = lint.build("multiple patterns covering the same range");
2219                     err.span_label(self.span, "overlapping patterns");
2220                     for int_range in overlaps {
2221                         // Use the real type for user display of the ranges:
2222                         err.span_label(
2223                             int_range.span,
2224                             &format!(
2225                                 "this range overlaps on `{}`",
2226                                 IntRange { range: int_range.range, ty, span: DUMMY_SP }.to_pat(tcx),
2227                             ),
2228                         );
2229                     }
2230                     err.emit();
2231                 },
2232             );
2233         }
2234     }
2235 }
2236
2237 /// Ignore spans when comparing, they don't carry semantic information as they are only for lints.
2238 impl<'tcx> std::cmp::PartialEq for IntRange<'tcx> {
2239     fn eq(&self, other: &Self) -> bool {
2240         self.range == other.range && self.ty == other.ty
2241     }
2242 }
2243
2244 // A struct to compute a set of constructors equivalent to `all_ctors \ used_ctors`.
2245 struct MissingConstructors<'tcx> {
2246     all_ctors: Vec<Constructor<'tcx>>,
2247     used_ctors: Vec<Constructor<'tcx>>,
2248     is_top_level: bool,
2249 }
2250
2251 impl<'tcx> MissingConstructors<'tcx> {
2252     fn new<'p>(
2253         cx: &MatchCheckCtxt<'p, 'tcx>,
2254         pcx: PatCtxt<'tcx>,
2255         matrix: &Matrix<'p, 'tcx>,
2256         is_top_level: bool,
2257     ) -> Self {
2258         let used_ctors: Vec<Constructor<'_>> =
2259             matrix.head_ctors(cx).cloned().filter(|c| !c.is_wildcard()).collect();
2260         let all_ctors = all_constructors(cx, pcx);
2261
2262         MissingConstructors { all_ctors, used_ctors, is_top_level }
2263     }
2264
2265     fn into_inner(self) -> (Vec<Constructor<'tcx>>, Vec<Constructor<'tcx>>) {
2266         (self.all_ctors, self.used_ctors)
2267     }
2268
2269     fn is_empty(&self) -> bool {
2270         self.iter().next().is_none()
2271     }
2272
2273     /// Iterate over all_ctors \ used_ctors
2274     fn iter<'a>(&'a self) -> impl Iterator<Item = Constructor<'tcx>> + Captures<'a> {
2275         self.all_ctors.iter().flat_map(move |req_ctor| req_ctor.subtract_ctors(&self.used_ctors))
2276     }
2277
2278     /// List the patterns corresponding to the missing constructors. In some cases, instead of
2279     /// listing all constructors of a given type, we prefer to simply report a wildcard.
2280     fn report_patterns<'p>(
2281         &self,
2282         cx: &MatchCheckCtxt<'p, 'tcx>,
2283         pcx: PatCtxt<'tcx>,
2284     ) -> SmallVec<[Pat<'tcx>; 1]> {
2285         // There are 2 ways we can report a witness here.
2286         // Commonly, we can report all the "free"
2287         // constructors as witnesses, e.g., if we have:
2288         //
2289         // ```
2290         //     enum Direction { N, S, E, W }
2291         //     let Direction::N = ...;
2292         // ```
2293         //
2294         // we can report 3 witnesses: `S`, `E`, and `W`.
2295         //
2296         // However, there is a case where we don't want
2297         // to do this and instead report a single `_` witness:
2298         // if the user didn't actually specify a constructor
2299         // in this arm, e.g., in
2300         //
2301         // ```
2302         //     let x: (Direction, Direction, bool) = ...;
2303         //     let (_, _, false) = x;
2304         // ```
2305         //
2306         // we don't want to show all 16 possible witnesses
2307         // `(<direction-1>, <direction-2>, true)` - we are
2308         // satisfied with `(_, _, true)`. In this case,
2309         // `used_ctors` is empty.
2310         // The exception is: if we are at the top-level, for example in an empty match, we
2311         // sometimes prefer reporting the list of constructors instead of just `_`.
2312         let report_when_all_missing = self.is_top_level && !IntRange::is_integral(pcx.ty);
2313         if self.used_ctors.is_empty() && !report_when_all_missing {
2314             // All constructors are unused. Report only a wildcard
2315             // rather than each individual constructor.
2316             smallvec![Pat::wildcard_from_ty(pcx.ty)]
2317         } else {
2318             // Construct for each missing constructor a "wild" version of this
2319             // constructor, that matches everything that can be built with
2320             // it. For example, if `ctor` is a `Constructor::Variant` for
2321             // `Option::Some`, we get the pattern `Some(_)`.
2322             self.iter()
2323                 .map(|missing_ctor| {
2324                     let fields = Fields::wildcards(cx, &missing_ctor, pcx.ty);
2325                     missing_ctor.apply(cx, pcx.ty, fields)
2326                 })
2327                 .collect()
2328         }
2329     }
2330 }
2331
2332 impl<'tcx> fmt::Debug for MissingConstructors<'tcx> {
2333     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2334         let ctors: Vec<_> = self.iter().collect();
2335         write!(f, "{:?}", ctors)
2336     }
2337 }
2338
2339 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html.
2340 /// The algorithm from the paper has been modified to correctly handle empty
2341 /// types. The changes are:
2342 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
2343 ///       continue to recurse over columns.
2344 ///   (1) all_constructors will only return constructors that are statically
2345 ///       possible. E.g., it will only return `Ok` for `Result<T, !>`.
2346 ///
2347 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
2348 /// to a set of such vectors `m` - this is defined as there being a set of
2349 /// inputs that will match `v` but not any of the sets in `m`.
2350 ///
2351 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
2352 ///
2353 /// This is used both for reachability checking (if a pattern isn't useful in
2354 /// relation to preceding patterns, it is not reachable) and exhaustiveness
2355 /// checking (if a wildcard pattern is useful in relation to a matrix, the
2356 /// matrix isn't exhaustive).
2357 ///
2358 /// `is_under_guard` is used to inform if the pattern has a guard. If it
2359 /// has one it must not be inserted into the matrix. This shouldn't be
2360 /// relied on for soundness.
2361 crate fn is_useful<'p, 'tcx>(
2362     cx: &MatchCheckCtxt<'p, 'tcx>,
2363     matrix: &Matrix<'p, 'tcx>,
2364     v: &PatStack<'p, 'tcx>,
2365     witness_preference: WitnessPreference,
2366     hir_id: HirId,
2367     is_under_guard: bool,
2368     is_top_level: bool,
2369 ) -> Usefulness<'tcx> {
2370     let Matrix { patterns: rows, .. } = matrix;
2371     debug!("is_useful({:#?}, {:#?})", matrix, v);
2372
2373     // The base case. We are pattern-matching on () and the return value is
2374     // based on whether our matrix has a row or not.
2375     // NOTE: This could potentially be optimized by checking rows.is_empty()
2376     // first and then, if v is non-empty, the return value is based on whether
2377     // the type of the tuple we're checking is inhabited or not.
2378     if v.is_empty() {
2379         return if rows.is_empty() {
2380             Usefulness::new_useful(witness_preference)
2381         } else {
2382             NotUseful
2383         };
2384     };
2385
2386     assert!(rows.iter().all(|r| r.len() == v.len()));
2387
2388     // If the first pattern is an or-pattern, expand it.
2389     if let Some(vs) = v.expand_or_pat() {
2390         // We need to push the already-seen patterns into the matrix in order to detect redundant
2391         // branches like `Some(_) | Some(0)`. We also keep track of the unreachable subpatterns.
2392         let mut matrix = matrix.clone();
2393         // `Vec` of all the unreachable branches of the current or-pattern.
2394         let mut unreachable_branches = Vec::new();
2395         // Subpatterns that are unreachable from all branches. E.g. in the following case, the last
2396         // `true` is unreachable only from one branch, so it is overall reachable.
2397         //
2398         // ```
2399         // match (true, true) {
2400         //     (true, true) => {}
2401         //     (false | true, false | true) => {}
2402         // }
2403         // ```
2404         let mut unreachable_subpats = FxHashSet::default();
2405         // Whether any branch at all is useful.
2406         let mut any_is_useful = false;
2407
2408         for v in vs {
2409             let res = is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
2410             match res {
2411                 Useful(pats) => {
2412                     if !any_is_useful {
2413                         any_is_useful = true;
2414                         // Initialize with the first set of unreachable subpatterns encountered.
2415                         unreachable_subpats = pats.into_iter().collect();
2416                     } else {
2417                         // Keep the patterns unreachable from both this and previous branches.
2418                         unreachable_subpats =
2419                             pats.into_iter().filter(|p| unreachable_subpats.contains(p)).collect();
2420                     }
2421                 }
2422                 NotUseful => unreachable_branches.push(v.head().span),
2423                 UsefulWithWitness(_) => {
2424                     bug!("Encountered or-pat in `v` during exhaustiveness checking")
2425                 }
2426             }
2427             // If pattern has a guard don't add it to the matrix
2428             if !is_under_guard {
2429                 matrix.push(v);
2430             }
2431         }
2432         if any_is_useful {
2433             // Collect all the unreachable patterns.
2434             unreachable_branches.extend(unreachable_subpats);
2435             return Useful(unreachable_branches);
2436         } else {
2437             return NotUseful;
2438         }
2439     }
2440
2441     // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476).
2442     let ty = matrix.heads().next().map(|r| r.ty).unwrap_or(v.head().ty);
2443     let pcx = PatCtxt { ty, span: v.head().span };
2444
2445     debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v.head());
2446
2447     let constructor = v.head_ctor(cx);
2448     let ret = if !constructor.is_wildcard() {
2449         debug!("is_useful - expanding constructor: {:#?}", constructor);
2450         constructor
2451             .split(cx, pcx, matrix, Some(hir_id))
2452             .into_iter()
2453             .map(|c| {
2454                 is_useful_specialized(
2455                     cx,
2456                     matrix,
2457                     v,
2458                     c,
2459                     pcx.ty,
2460                     witness_preference,
2461                     hir_id,
2462                     is_under_guard,
2463                 )
2464             })
2465             .find(|result| result.is_useful())
2466             .unwrap_or(NotUseful)
2467     } else {
2468         debug!("is_useful - expanding wildcard");
2469
2470         // `missing_ctors` is the set of constructors from the same type as the
2471         // first column of `matrix` that are matched only by wildcard patterns
2472         // from the first column.
2473         //
2474         // Therefore, if there is some pattern that is unmatched by `matrix`,
2475         // it will still be unmatched if the first constructor is replaced by
2476         // any of the constructors in `missing_ctors`
2477
2478         // Missing constructors are those that are not matched by any non-wildcard patterns in the
2479         // current column. We only fully construct them on-demand, because they're rarely used and
2480         // can be big.
2481         let missing_ctors = MissingConstructors::new(cx, pcx, matrix, is_top_level);
2482
2483         debug!("is_useful_missing_ctors.empty()={:#?}", missing_ctors.is_empty(),);
2484
2485         if missing_ctors.is_empty() {
2486             let (all_ctors, _) = missing_ctors.into_inner();
2487             all_ctors
2488                 .into_iter()
2489                 .flat_map(|ctor| ctor.split(cx, pcx, matrix, None))
2490                 .map(|c| {
2491                     is_useful_specialized(
2492                         cx,
2493                         matrix,
2494                         v,
2495                         c,
2496                         pcx.ty,
2497                         witness_preference,
2498                         hir_id,
2499                         is_under_guard,
2500                     )
2501                 })
2502                 .find(|result| result.is_useful())
2503                 .unwrap_or(NotUseful)
2504         } else {
2505             let ctor_wild_subpatterns = Fields::empty();
2506             let matrix = matrix.specialize_constructor(cx, &constructor, &ctor_wild_subpatterns);
2507             // Unwrap is ok: v can always be specialized with its own constructor.
2508             let v =
2509                 v.specialize_constructor(cx, &constructor, &ctor_wild_subpatterns, true).unwrap();
2510             let usefulness =
2511                 is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
2512
2513             usefulness.apply_wildcard(cx, pcx, missing_ctors)
2514         }
2515     };
2516     debug!("is_useful::returns({:#?}, {:#?}) = {:?}", matrix, v, ret);
2517     ret
2518 }
2519
2520 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied
2521 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
2522 fn is_useful_specialized<'p, 'tcx>(
2523     cx: &MatchCheckCtxt<'p, 'tcx>,
2524     matrix: &Matrix<'p, 'tcx>,
2525     v: &PatStack<'p, 'tcx>,
2526     ctor: Constructor<'tcx>,
2527     ty: Ty<'tcx>,
2528     witness_preference: WitnessPreference,
2529     hir_id: HirId,
2530     is_under_guard: bool,
2531 ) -> Usefulness<'tcx> {
2532     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, ty);
2533
2534     // We cache the result of `Fields::wildcards` because it is used a lot.
2535     let ctor_wild_subpatterns = Fields::wildcards(cx, &ctor, ty);
2536     let matrix = matrix.specialize_constructor(cx, &ctor, &ctor_wild_subpatterns);
2537     v.specialize_constructor(cx, &ctor, &ctor_wild_subpatterns, true)
2538         .map(|v| is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false))
2539         .map(|u| u.apply_constructor(cx, &ctor, ty, &ctor_wild_subpatterns))
2540         .unwrap_or(NotUseful)
2541 }
2542
2543 /// Determines the constructor that the given pattern can be specialized to.
2544 /// Returns `None` in case of a catch-all, which can't be specialized.
2545 fn pat_constructor<'p, 'tcx>(
2546     cx: &MatchCheckCtxt<'p, 'tcx>,
2547     pat: &'p Pat<'tcx>,
2548 ) -> Constructor<'tcx> {
2549     match *pat.kind {
2550         PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern`
2551         PatKind::Binding { .. } | PatKind::Wild => Wildcard,
2552         PatKind::Leaf { .. } | PatKind::Deref { .. } => Single,
2553         PatKind::Variant { adt_def, variant_index, .. } => {
2554             Variant(adt_def.variants[variant_index].def_id)
2555         }
2556         PatKind::Constant { value } => {
2557             if let Some(int_range) = IntRange::from_const(cx.tcx, cx.param_env, value, pat.span) {
2558                 IntRange(int_range)
2559             } else {
2560                 match value.ty.kind() {
2561                     ty::Float(_) => FloatRange(value, value, RangeEnd::Included),
2562                     ty::Ref(_, t, _) if t.is_str() => Str(value),
2563                     // All constants that can be structurally matched have already been expanded
2564                     // into the corresponding `Pat`s by `const_to_pat`. Constants that remain are
2565                     // opaque.
2566                     _ => Opaque,
2567                 }
2568             }
2569         }
2570         PatKind::Range(PatRange { lo, hi, end }) => {
2571             let ty = lo.ty;
2572             if let Some(int_range) = IntRange::from_range(
2573                 cx.tcx,
2574                 lo.eval_bits(cx.tcx, cx.param_env, lo.ty),
2575                 hi.eval_bits(cx.tcx, cx.param_env, hi.ty),
2576                 ty,
2577                 &end,
2578                 pat.span,
2579             ) {
2580                 IntRange(int_range)
2581             } else {
2582                 FloatRange(lo, hi, end)
2583             }
2584         }
2585         PatKind::Array { ref prefix, ref slice, ref suffix }
2586         | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
2587             let array_len = match pat.ty.kind() {
2588                 ty::Array(_, length) => Some(length.eval_usize(cx.tcx, cx.param_env)),
2589                 ty::Slice(_) => None,
2590                 _ => span_bug!(pat.span, "bad ty {:?} for slice pattern", pat.ty),
2591             };
2592             let prefix = prefix.len() as u64;
2593             let suffix = suffix.len() as u64;
2594             let kind =
2595                 if slice.is_some() { VarLen(prefix, suffix) } else { FixedLen(prefix + suffix) };
2596             Slice(Slice { array_len, kind })
2597         }
2598         PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."),
2599     }
2600 }