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