]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/_match.rs
Handle ranges of float consistently
[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 variant_index_for_adt<'a>(
838         &self,
839         cx: &MatchCheckCtxt<'a, 'tcx>,
840         adt: &'tcx ty::AdtDef,
841     ) -> VariantIdx {
842         match *self {
843             Variant(id) => adt.variant_index_with_id(id),
844             Single => {
845                 assert!(!adt.is_enum());
846                 VariantIdx::new(0)
847             }
848             ConstantValue(c) => cx
849                 .tcx
850                 .destructure_const(cx.param_env.and(c))
851                 .variant
852                 .expect("destructed const of adt without variant id"),
853             _ => bug!("bad constructor {:?} for adt {:?}", self, adt),
854         }
855     }
856
857     // Returns the set of constructors covered by `self` but not by
858     // anything in `other_ctors`.
859     fn subtract_ctors(&self, other_ctors: &Vec<Constructor<'tcx>>) -> Vec<Constructor<'tcx>> {
860         if other_ctors.is_empty() {
861             return vec![self.clone()];
862         }
863
864         match self {
865             // Those constructors can only match themselves.
866             Single | Variant(_) | ConstantValue(..) | FloatRange(..) => {
867                 if other_ctors.iter().any(|c| c == self) { vec![] } else { vec![self.clone()] }
868             }
869             &Slice(slice) => {
870                 let mut other_slices = other_ctors
871                     .iter()
872                     .filter_map(|c: &Constructor<'_>| match c {
873                         Slice(slice) => Some(*slice),
874                         _ => bug!("bad slice pattern constructor {:?}", c),
875                     })
876                     .map(Slice::value_kind);
877
878                 match slice.value_kind() {
879                     FixedLen(self_len) => {
880                         if other_slices.any(|other_slice| other_slice.covers_length(self_len)) {
881                             vec![]
882                         } else {
883                             vec![Slice(slice)]
884                         }
885                     }
886                     kind @ VarLen(..) => {
887                         let mut remaining_slices = vec![kind];
888
889                         // For each used slice, subtract from the current set of slices.
890                         for other_slice in other_slices {
891                             remaining_slices = remaining_slices
892                                 .into_iter()
893                                 .flat_map(|remaining_slice| remaining_slice.subtract(other_slice))
894                                 .collect();
895
896                             // If the constructors that have been considered so far already cover
897                             // the entire range of `self`, no need to look at more constructors.
898                             if remaining_slices.is_empty() {
899                                 break;
900                             }
901                         }
902
903                         remaining_slices
904                             .into_iter()
905                             .map(|kind| Slice { array_len: slice.array_len, kind })
906                             .map(Slice)
907                             .collect()
908                     }
909                 }
910             }
911             IntRange(self_range) => {
912                 let mut remaining_ranges = vec![self_range.clone()];
913                 for other_ctor in other_ctors {
914                     if let IntRange(other_range) = other_ctor {
915                         if other_range == self_range {
916                             // If the `self` range appears directly in a `match` arm, we can
917                             // eliminate it straight away.
918                             remaining_ranges = vec![];
919                         } else {
920                             // Otherwise explicitly compute the remaining ranges.
921                             remaining_ranges = other_range.subtract_from(remaining_ranges);
922                         }
923
924                         // If the ranges that have been considered so far already cover the entire
925                         // range of values, we can return early.
926                         if remaining_ranges.is_empty() {
927                             break;
928                         }
929                     }
930                 }
931
932                 // Convert the ranges back into constructors.
933                 remaining_ranges.into_iter().map(IntRange).collect()
934             }
935             // This constructor is never covered by anything else
936             NonExhaustive => vec![NonExhaustive],
937         }
938     }
939
940     /// Apply a constructor to a list of patterns, yielding a new pattern. `pats`
941     /// must have as many elements as this constructor's arity.
942     ///
943     /// This is roughly the inverse of `specialize_one_pattern`.
944     ///
945     /// Examples:
946     /// `self`: `Constructor::Single`
947     /// `ty`: `(u32, u32, u32)`
948     /// `pats`: `[10, 20, _]`
949     /// returns `(10, 20, _)`
950     ///
951     /// `self`: `Constructor::Variant(Option::Some)`
952     /// `ty`: `Option<bool>`
953     /// `pats`: `[false]`
954     /// returns `Some(false)`
955     fn apply<'p>(
956         &self,
957         cx: &MatchCheckCtxt<'p, 'tcx>,
958         ty: Ty<'tcx>,
959         fields: Fields<'p, 'tcx>,
960     ) -> Pat<'tcx> {
961         let mut subpatterns = fields.all_patterns();
962
963         let pat = match self {
964             Single | Variant(_) => match ty.kind() {
965                 ty::Adt(..) | ty::Tuple(..) => {
966                     let subpatterns = subpatterns
967                         .enumerate()
968                         .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
969                         .collect();
970
971                     if let ty::Adt(adt, substs) = ty.kind() {
972                         if adt.is_enum() {
973                             PatKind::Variant {
974                                 adt_def: adt,
975                                 substs,
976                                 variant_index: self.variant_index_for_adt(cx, adt),
977                                 subpatterns,
978                             }
979                         } else {
980                             PatKind::Leaf { subpatterns }
981                         }
982                     } else {
983                         PatKind::Leaf { subpatterns }
984                     }
985                 }
986                 ty::Ref(..) => PatKind::Deref { subpattern: subpatterns.next().unwrap() },
987                 ty::Slice(_) | ty::Array(..) => bug!("bad slice pattern {:?} {:?}", self, ty),
988                 _ => PatKind::Wild,
989             },
990             Slice(slice) => match slice.pattern_kind() {
991                 FixedLen(_) => {
992                     PatKind::Slice { prefix: subpatterns.collect(), slice: None, suffix: vec![] }
993                 }
994                 VarLen(prefix, _) => {
995                     let mut prefix: Vec<_> = subpatterns.by_ref().take(prefix as usize).collect();
996                     if slice.array_len.is_some() {
997                         // Improves diagnostics a bit: if the type is a known-size array, instead
998                         // of reporting `[x, _, .., _, y]`, we prefer to report `[x, .., y]`.
999                         // This is incorrect if the size is not known, since `[_, ..]` captures
1000                         // arrays of lengths `>= 1` whereas `[..]` captures any length.
1001                         while !prefix.is_empty() && prefix.last().unwrap().is_wildcard() {
1002                             prefix.pop();
1003                         }
1004                     }
1005                     let suffix: Vec<_> = if slice.array_len.is_some() {
1006                         // Same as above.
1007                         subpatterns.skip_while(Pat::is_wildcard).collect()
1008                     } else {
1009                         subpatterns.collect()
1010                     };
1011                     let wild = Pat::wildcard_from_ty(ty);
1012                     PatKind::Slice { prefix, slice: Some(wild), suffix }
1013                 }
1014             },
1015             &ConstantValue(value) => PatKind::Constant { value },
1016             &FloatRange(lo, hi, end) => PatKind::Range(PatRange { lo, hi, end }),
1017             IntRange(range) => return range.to_pat(cx.tcx),
1018             NonExhaustive => PatKind::Wild,
1019         };
1020
1021         Pat { ty, span: DUMMY_SP, kind: Box::new(pat) }
1022     }
1023
1024     /// Like `apply`, but where all the subpatterns are wildcards `_`.
1025     fn apply_wildcards<'a>(&self, cx: &MatchCheckCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> Pat<'tcx> {
1026         self.apply(cx, ty, Fields::wildcards(cx, self, ty))
1027     }
1028 }
1029
1030 /// Some fields need to be explicitly hidden away in certain cases; see the comment above the
1031 /// `Fields` struct. This struct represents such a potentially-hidden field. When a field is hidden
1032 /// we still keep its type around.
1033 #[derive(Debug, Copy, Clone)]
1034 enum FilteredField<'p, 'tcx> {
1035     Kept(&'p Pat<'tcx>),
1036     Hidden(Ty<'tcx>),
1037 }
1038
1039 impl<'p, 'tcx> FilteredField<'p, 'tcx> {
1040     fn kept(self) -> Option<&'p Pat<'tcx>> {
1041         match self {
1042             FilteredField::Kept(p) => Some(p),
1043             FilteredField::Hidden(_) => None,
1044         }
1045     }
1046
1047     fn to_pattern(self) -> Pat<'tcx> {
1048         match self {
1049             FilteredField::Kept(p) => p.clone(),
1050             FilteredField::Hidden(ty) => Pat::wildcard_from_ty(ty),
1051         }
1052     }
1053 }
1054
1055 /// A value can be decomposed into a constructor applied to some fields. This struct represents
1056 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
1057 ///
1058 /// If a private or `non_exhaustive` field is uninhabited, the code mustn't observe that it is
1059 /// uninhabited. For that, we filter these fields out of the matrix. This is subtle because we
1060 /// still need to have those fields back when going to/from a `Pat`. Most of this is handled
1061 /// automatically in `Fields`, but when constructing or deconstructing `Fields` you need to be
1062 /// careful. As a rule, when going to/from the matrix, use the filtered field list; when going
1063 /// to/from `Pat`, use the full field list.
1064 /// This filtering is uncommon in practice, because uninhabited fields are rarely used, so we avoid
1065 /// it when possible to preserve performance.
1066 #[derive(Debug, Clone)]
1067 enum Fields<'p, 'tcx> {
1068     /// Lists of patterns that don't contain any filtered fields.
1069     /// `Slice` and `Vec` behave the same; the difference is only to avoid allocating and
1070     /// triple-dereferences when possible. Frankly this is premature optimization, I (Nadrieril)
1071     /// have not measured if it really made a difference.
1072     Slice(&'p [Pat<'tcx>]),
1073     Vec(SmallVec<[&'p Pat<'tcx>; 2]>),
1074     /// Patterns where some of the fields need to be hidden. `kept_count` caches the number of
1075     /// non-hidden fields.
1076     Filtered {
1077         fields: SmallVec<[FilteredField<'p, 'tcx>; 2]>,
1078         kept_count: usize,
1079     },
1080 }
1081
1082 impl<'p, 'tcx> Fields<'p, 'tcx> {
1083     fn empty() -> Self {
1084         Fields::Slice(&[])
1085     }
1086
1087     /// Construct a new `Fields` from the given pattern. Must not be used if the pattern is a field
1088     /// of a struct/tuple/variant.
1089     fn from_single_pattern(pat: &'p Pat<'tcx>) -> Self {
1090         Fields::Slice(std::slice::from_ref(pat))
1091     }
1092
1093     /// Convenience; internal use.
1094     fn wildcards_from_tys(
1095         cx: &MatchCheckCtxt<'p, 'tcx>,
1096         tys: impl IntoIterator<Item = Ty<'tcx>>,
1097     ) -> Self {
1098         let wilds = tys.into_iter().map(Pat::wildcard_from_ty);
1099         let pats = cx.pattern_arena.alloc_from_iter(wilds);
1100         Fields::Slice(pats)
1101     }
1102
1103     /// Creates a new list of wildcard fields for a given constructor.
1104     fn wildcards(
1105         cx: &MatchCheckCtxt<'p, 'tcx>,
1106         constructor: &Constructor<'tcx>,
1107         ty: Ty<'tcx>,
1108     ) -> Self {
1109         let wildcard_from_ty = |ty| &*cx.pattern_arena.alloc(Pat::wildcard_from_ty(ty));
1110
1111         let ret = match constructor {
1112             Single | Variant(_) => match ty.kind() {
1113                 ty::Tuple(ref fs) => {
1114                     Fields::wildcards_from_tys(cx, fs.into_iter().map(|ty| ty.expect_ty()))
1115                 }
1116                 ty::Ref(_, rty, _) => Fields::from_single_pattern(wildcard_from_ty(rty)),
1117                 ty::Adt(adt, substs) => {
1118                     if adt.is_box() {
1119                         // Use T as the sub pattern type of Box<T>.
1120                         Fields::from_single_pattern(wildcard_from_ty(substs.type_at(0)))
1121                     } else {
1122                         let variant = &adt.variants[constructor.variant_index_for_adt(cx, adt)];
1123                         // Whether we must not match the fields of this variant exhaustively.
1124                         let is_non_exhaustive =
1125                             variant.is_field_list_non_exhaustive() && !adt.did.is_local();
1126                         let field_tys = variant.fields.iter().map(|field| field.ty(cx.tcx, substs));
1127                         // In the following cases, we don't need to filter out any fields. This is
1128                         // the vast majority of real cases, since uninhabited fields are uncommon.
1129                         let has_no_hidden_fields = (adt.is_enum() && !is_non_exhaustive)
1130                             || !field_tys.clone().any(|ty| cx.is_uninhabited(ty));
1131
1132                         if has_no_hidden_fields {
1133                             Fields::wildcards_from_tys(cx, field_tys)
1134                         } else {
1135                             let mut kept_count = 0;
1136                             let fields = variant
1137                                 .fields
1138                                 .iter()
1139                                 .map(|field| {
1140                                     let ty = field.ty(cx.tcx, substs);
1141                                     let is_visible = adt.is_enum()
1142                                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1143                                     let is_uninhabited = cx.is_uninhabited(ty);
1144
1145                                     // In the cases of either a `#[non_exhaustive]` field list
1146                                     // or a non-public field, we hide uninhabited fields in
1147                                     // order not to reveal the uninhabitedness of the whole
1148                                     // variant.
1149                                     if is_uninhabited && (!is_visible || is_non_exhaustive) {
1150                                         FilteredField::Hidden(ty)
1151                                     } else {
1152                                         kept_count += 1;
1153                                         FilteredField::Kept(wildcard_from_ty(ty))
1154                                     }
1155                                 })
1156                                 .collect();
1157                             Fields::Filtered { fields, kept_count }
1158                         }
1159                     }
1160                 }
1161                 _ => Fields::empty(),
1162             },
1163             Slice(slice) => match *ty.kind() {
1164                 ty::Slice(ty) | ty::Array(ty, _) => {
1165                     let arity = slice.arity();
1166                     Fields::wildcards_from_tys(cx, (0..arity).map(|_| ty))
1167                 }
1168                 _ => bug!("bad slice pattern {:?} {:?}", constructor, ty),
1169             },
1170             ConstantValue(..) | FloatRange(..) | IntRange(..) | NonExhaustive => Fields::empty(),
1171         };
1172         debug!("Fields::wildcards({:?}, {:?}) = {:#?}", constructor, ty, ret);
1173         ret
1174     }
1175
1176     /// Returns the number of patterns from the viewpoint of match-checking, i.e. excluding hidden
1177     /// fields. This is what we want in most cases in this file, the only exception being
1178     /// conversion to/from `Pat`.
1179     fn len(&self) -> usize {
1180         match self {
1181             Fields::Slice(pats) => pats.len(),
1182             Fields::Vec(pats) => pats.len(),
1183             Fields::Filtered { kept_count, .. } => *kept_count,
1184         }
1185     }
1186
1187     /// Returns the complete list of patterns, including hidden fields.
1188     fn all_patterns(self) -> impl Iterator<Item = Pat<'tcx>> {
1189         let pats: SmallVec<[_; 2]> = match self {
1190             Fields::Slice(pats) => pats.iter().cloned().collect(),
1191             Fields::Vec(pats) => pats.into_iter().cloned().collect(),
1192             Fields::Filtered { fields, .. } => {
1193                 // We don't skip any fields here.
1194                 fields.into_iter().map(|p| p.to_pattern()).collect()
1195             }
1196         };
1197         pats.into_iter()
1198     }
1199
1200     /// Overrides some of the fields with the provided patterns. Exactly like
1201     /// `replace_fields_indexed`, except that it takes `FieldPat`s as input.
1202     fn replace_with_fieldpats(
1203         &self,
1204         new_pats: impl IntoIterator<Item = &'p FieldPat<'tcx>>,
1205     ) -> Self {
1206         self.replace_fields_indexed(
1207             new_pats.into_iter().map(|pat| (pat.field.index(), &pat.pattern)),
1208         )
1209     }
1210
1211     /// Overrides some of the fields with the provided patterns. This is used when a pattern
1212     /// defines some fields but not all, for example `Foo { field1: Some(_), .. }`: here we start with a
1213     /// `Fields` that is just one wildcard per field of the `Foo` struct, and override the entry
1214     /// corresponding to `field1` with the pattern `Some(_)`. This is also used for slice patterns
1215     /// for the same reason.
1216     fn replace_fields_indexed(
1217         &self,
1218         new_pats: impl IntoIterator<Item = (usize, &'p Pat<'tcx>)>,
1219     ) -> Self {
1220         let mut fields = self.clone();
1221         if let Fields::Slice(pats) = fields {
1222             fields = Fields::Vec(pats.iter().collect());
1223         }
1224
1225         match &mut fields {
1226             Fields::Vec(pats) => {
1227                 for (i, pat) in new_pats {
1228                     pats[i] = pat
1229                 }
1230             }
1231             Fields::Filtered { fields, .. } => {
1232                 for (i, pat) in new_pats {
1233                     if let FilteredField::Kept(p) = &mut fields[i] {
1234                         *p = pat
1235                     }
1236                 }
1237             }
1238             Fields::Slice(_) => unreachable!(),
1239         }
1240         fields
1241     }
1242
1243     /// Replaces contained fields with the given filtered list of patterns, e.g. taken from the
1244     /// matrix. There must be `len()` patterns in `pats`.
1245     fn replace_fields(
1246         &self,
1247         cx: &MatchCheckCtxt<'p, 'tcx>,
1248         pats: impl IntoIterator<Item = Pat<'tcx>>,
1249     ) -> Self {
1250         let pats: &[_] = cx.pattern_arena.alloc_from_iter(pats);
1251
1252         match self {
1253             Fields::Filtered { fields, kept_count } => {
1254                 let mut pats = pats.iter();
1255                 let mut fields = fields.clone();
1256                 for f in &mut fields {
1257                     if let FilteredField::Kept(p) = f {
1258                         // We take one input pattern for each `Kept` field, in order.
1259                         *p = pats.next().unwrap();
1260                     }
1261                 }
1262                 Fields::Filtered { fields, kept_count: *kept_count }
1263             }
1264             _ => Fields::Slice(pats),
1265         }
1266     }
1267
1268     fn push_on_patstack(self, stack: &[&'p Pat<'tcx>]) -> PatStack<'p, 'tcx> {
1269         let pats: SmallVec<_> = match self {
1270             Fields::Slice(pats) => pats.iter().chain(stack.iter().copied()).collect(),
1271             Fields::Vec(mut pats) => {
1272                 pats.extend_from_slice(stack);
1273                 pats
1274             }
1275             Fields::Filtered { fields, .. } => {
1276                 // We skip hidden fields here
1277                 fields.into_iter().filter_map(|p| p.kept()).chain(stack.iter().copied()).collect()
1278             }
1279         };
1280         PatStack::from_vec(pats)
1281     }
1282 }
1283
1284 #[derive(Clone, Debug)]
1285 crate enum Usefulness<'tcx> {
1286     /// Carries a list of unreachable subpatterns. Used only in the presence of or-patterns.
1287     Useful(Vec<Span>),
1288     /// Carries a list of witnesses of non-exhaustiveness.
1289     UsefulWithWitness(Vec<Witness<'tcx>>),
1290     NotUseful,
1291 }
1292
1293 impl<'tcx> Usefulness<'tcx> {
1294     fn new_useful(preference: WitnessPreference) -> Self {
1295         match preference {
1296             ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1297             LeaveOutWitness => Useful(vec![]),
1298         }
1299     }
1300
1301     fn is_useful(&self) -> bool {
1302         match *self {
1303             NotUseful => false,
1304             _ => true,
1305         }
1306     }
1307
1308     fn apply_constructor<'p>(
1309         self,
1310         cx: &MatchCheckCtxt<'p, 'tcx>,
1311         ctor: &Constructor<'tcx>,
1312         ty: Ty<'tcx>,
1313         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1314     ) -> Self {
1315         match self {
1316             UsefulWithWitness(witnesses) => UsefulWithWitness(
1317                 witnesses
1318                     .into_iter()
1319                     .map(|witness| witness.apply_constructor(cx, &ctor, ty, ctor_wild_subpatterns))
1320                     .collect(),
1321             ),
1322             x => x,
1323         }
1324     }
1325
1326     fn apply_wildcard(self, ty: Ty<'tcx>) -> Self {
1327         match self {
1328             UsefulWithWitness(witnesses) => {
1329                 let wild = Pat::wildcard_from_ty(ty);
1330                 UsefulWithWitness(
1331                     witnesses
1332                         .into_iter()
1333                         .map(|mut witness| {
1334                             witness.0.push(wild.clone());
1335                             witness
1336                         })
1337                         .collect(),
1338                 )
1339             }
1340             x => x,
1341         }
1342     }
1343
1344     fn apply_missing_ctors(
1345         self,
1346         cx: &MatchCheckCtxt<'_, 'tcx>,
1347         ty: Ty<'tcx>,
1348         missing_ctors: &MissingConstructors<'tcx>,
1349     ) -> Self {
1350         match self {
1351             UsefulWithWitness(witnesses) => {
1352                 let new_patterns: Vec<_> =
1353                     missing_ctors.iter().map(|ctor| ctor.apply_wildcards(cx, ty)).collect();
1354                 // Add the new patterns to each witness
1355                 UsefulWithWitness(
1356                     witnesses
1357                         .into_iter()
1358                         .flat_map(|witness| {
1359                             new_patterns.iter().map(move |pat| {
1360                                 let mut witness = witness.clone();
1361                                 witness.0.push(pat.clone());
1362                                 witness
1363                             })
1364                         })
1365                         .collect(),
1366                 )
1367             }
1368             x => x,
1369         }
1370     }
1371 }
1372
1373 #[derive(Copy, Clone, Debug)]
1374 crate enum WitnessPreference {
1375     ConstructWitness,
1376     LeaveOutWitness,
1377 }
1378
1379 #[derive(Copy, Clone, Debug)]
1380 struct PatCtxt<'tcx> {
1381     ty: Ty<'tcx>,
1382     span: Span,
1383 }
1384
1385 /// A witness of non-exhaustiveness for error reporting, represented
1386 /// as a list of patterns (in reverse order of construction) with
1387 /// wildcards inside to represent elements that can take any inhabitant
1388 /// of the type as a value.
1389 ///
1390 /// A witness against a list of patterns should have the same types
1391 /// and length as the pattern matched against. Because Rust `match`
1392 /// is always against a single pattern, at the end the witness will
1393 /// have length 1, but in the middle of the algorithm, it can contain
1394 /// multiple patterns.
1395 ///
1396 /// For example, if we are constructing a witness for the match against
1397 /// ```
1398 /// struct Pair(Option<(u32, u32)>, bool);
1399 ///
1400 /// match (p: Pair) {
1401 ///    Pair(None, _) => {}
1402 ///    Pair(_, false) => {}
1403 /// }
1404 /// ```
1405 ///
1406 /// We'll perform the following steps:
1407 /// 1. Start with an empty witness
1408 ///     `Witness(vec![])`
1409 /// 2. Push a witness `Some(_)` against the `None`
1410 ///     `Witness(vec![Some(_)])`
1411 /// 3. Push a witness `true` against the `false`
1412 ///     `Witness(vec![Some(_), true])`
1413 /// 4. Apply the `Pair` constructor to the witnesses
1414 ///     `Witness(vec![Pair(Some(_), true)])`
1415 ///
1416 /// The final `Pair(Some(_), true)` is then the resulting witness.
1417 #[derive(Clone, Debug)]
1418 crate struct Witness<'tcx>(Vec<Pat<'tcx>>);
1419
1420 impl<'tcx> Witness<'tcx> {
1421     crate fn single_pattern(self) -> Pat<'tcx> {
1422         assert_eq!(self.0.len(), 1);
1423         self.0.into_iter().next().unwrap()
1424     }
1425
1426     /// Constructs a partial witness for a pattern given a list of
1427     /// patterns expanded by the specialization step.
1428     ///
1429     /// When a pattern P is discovered to be useful, this function is used bottom-up
1430     /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
1431     /// of values, V, where each value in that set is not covered by any previously
1432     /// used patterns and is covered by the pattern P'. Examples:
1433     ///
1434     /// left_ty: tuple of 3 elements
1435     /// pats: [10, 20, _]           => (10, 20, _)
1436     ///
1437     /// left_ty: struct X { a: (bool, &'static str), b: usize}
1438     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
1439     fn apply_constructor<'p>(
1440         mut self,
1441         cx: &MatchCheckCtxt<'p, 'tcx>,
1442         ctor: &Constructor<'tcx>,
1443         ty: Ty<'tcx>,
1444         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1445     ) -> Self {
1446         let pat = {
1447             let len = self.0.len();
1448             let arity = ctor_wild_subpatterns.len();
1449             let pats = self.0.drain((len - arity)..).rev();
1450             let fields = ctor_wild_subpatterns.replace_fields(cx, pats);
1451             ctor.apply(cx, ty, fields)
1452         };
1453
1454         self.0.push(pat);
1455
1456         self
1457     }
1458 }
1459
1460 /// This determines the set of all possible constructors of a pattern matching
1461 /// values of type `left_ty`. For vectors, this would normally be an infinite set
1462 /// but is instead bounded by the maximum fixed length of slice patterns in
1463 /// the column of patterns being analyzed.
1464 ///
1465 /// We make sure to omit constructors that are statically impossible. E.g., for
1466 /// `Option<!>`, we do not include `Some(_)` in the returned list of constructors.
1467 /// Invariant: this returns an empty `Vec` if and only if the type is uninhabited (as determined by
1468 /// `cx.is_uninhabited()`).
1469 fn all_constructors<'a, 'tcx>(
1470     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1471     pcx: PatCtxt<'tcx>,
1472 ) -> Vec<Constructor<'tcx>> {
1473     debug!("all_constructors({:?})", pcx.ty);
1474     let make_range = |start, end| {
1475         IntRange(
1476             // `unwrap()` is ok because we know the type is an integer.
1477             IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included, pcx.span)
1478                 .unwrap(),
1479         )
1480     };
1481     match *pcx.ty.kind() {
1482         ty::Bool => vec![make_range(0, 1)],
1483         ty::Array(ref sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => {
1484             let len = len.eval_usize(cx.tcx, cx.param_env);
1485             if len != 0 && cx.is_uninhabited(sub_ty) {
1486                 vec![]
1487             } else {
1488                 vec![Slice(Slice { array_len: Some(len), kind: VarLen(0, 0) })]
1489             }
1490         }
1491         // Treat arrays of a constant but unknown length like slices.
1492         ty::Array(ref sub_ty, _) | ty::Slice(ref sub_ty) => {
1493             let kind = if cx.is_uninhabited(sub_ty) { FixedLen(0) } else { VarLen(0, 0) };
1494             vec![Slice(Slice { array_len: None, kind })]
1495         }
1496         ty::Adt(def, substs) if def.is_enum() => {
1497             let ctors: Vec<_> = if cx.tcx.features().exhaustive_patterns {
1498                 // If `exhaustive_patterns` is enabled, we exclude variants known to be
1499                 // uninhabited.
1500                 def.variants
1501                     .iter()
1502                     .filter(|v| {
1503                         !v.uninhabited_from(cx.tcx, substs, def.adt_kind(), cx.param_env)
1504                             .contains(cx.tcx, cx.module)
1505                     })
1506                     .map(|v| Variant(v.def_id))
1507                     .collect()
1508             } else {
1509                 def.variants.iter().map(|v| Variant(v.def_id)).collect()
1510             };
1511
1512             // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
1513             // additional "unknown" constructor.
1514             // There is no point in enumerating all possible variants, because the user can't
1515             // actually match against them all themselves. So we always return only the fictitious
1516             // constructor.
1517             // E.g., in an example like:
1518             // ```
1519             //     let err: io::ErrorKind = ...;
1520             //     match err {
1521             //         io::ErrorKind::NotFound => {},
1522             //     }
1523             // ```
1524             // we don't want to show every possible IO error, but instead have only `_` as the
1525             // witness.
1526             let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
1527
1528             // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
1529             // as though it had an "unknown" constructor to avoid exposing its emptyness. Note that
1530             // an empty match will still be considered exhaustive because that case is handled
1531             // separately in `check_match`.
1532             let is_secretly_empty =
1533                 def.variants.is_empty() && !cx.tcx.features().exhaustive_patterns;
1534
1535             if is_secretly_empty || is_declared_nonexhaustive { vec![NonExhaustive] } else { ctors }
1536         }
1537         ty::Char => {
1538             vec![
1539                 // The valid Unicode Scalar Value ranges.
1540                 make_range('\u{0000}' as u128, '\u{D7FF}' as u128),
1541                 make_range('\u{E000}' as u128, '\u{10FFFF}' as u128),
1542             ]
1543         }
1544         ty::Int(_) | ty::Uint(_)
1545             if pcx.ty.is_ptr_sized_integral()
1546                 && !cx.tcx.features().precise_pointer_size_matching =>
1547         {
1548             // `usize`/`isize` are not allowed to be matched exhaustively unless the
1549             // `precise_pointer_size_matching` feature is enabled. So we treat those types like
1550             // `#[non_exhaustive]` enums by returning a special unmatcheable constructor.
1551             vec![NonExhaustive]
1552         }
1553         ty::Int(ity) => {
1554             let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128;
1555             let min = 1u128 << (bits - 1);
1556             let max = min - 1;
1557             vec![make_range(min, max)]
1558         }
1559         ty::Uint(uty) => {
1560             let size = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size();
1561             let max = truncate(u128::MAX, size);
1562             vec![make_range(0, max)]
1563         }
1564         _ => {
1565             if cx.is_uninhabited(pcx.ty) {
1566                 vec![]
1567             } else {
1568                 vec![Single]
1569             }
1570         }
1571     }
1572 }
1573
1574 /// An inclusive interval, used for precise integer exhaustiveness checking.
1575 /// `IntRange`s always store a contiguous range. This means that values are
1576 /// encoded such that `0` encodes the minimum value for the integer,
1577 /// regardless of the signedness.
1578 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
1579 /// This makes comparisons and arithmetic on interval endpoints much more
1580 /// straightforward. See `signed_bias` for details.
1581 ///
1582 /// `IntRange` is never used to encode an empty range or a "range" that wraps
1583 /// around the (offset) space: i.e., `range.lo <= range.hi`.
1584 #[derive(Clone, Debug)]
1585 struct IntRange<'tcx> {
1586     range: RangeInclusive<u128>,
1587     ty: Ty<'tcx>,
1588     span: Span,
1589 }
1590
1591 impl<'tcx> IntRange<'tcx> {
1592     #[inline]
1593     fn is_integral(ty: Ty<'_>) -> bool {
1594         match ty.kind() {
1595             ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool => true,
1596             _ => false,
1597         }
1598     }
1599
1600     fn is_singleton(&self) -> bool {
1601         self.range.start() == self.range.end()
1602     }
1603
1604     fn boundaries(&self) -> (u128, u128) {
1605         (*self.range.start(), *self.range.end())
1606     }
1607
1608     /// Don't treat `usize`/`isize` exhaustively unless the `precise_pointer_size_matching` feature
1609     /// is enabled.
1610     fn treat_exhaustively(&self, tcx: TyCtxt<'tcx>) -> bool {
1611         !self.ty.is_ptr_sized_integral() || tcx.features().precise_pointer_size_matching
1612     }
1613
1614     #[inline]
1615     fn integral_size_and_signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'_>) -> Option<(Size, u128)> {
1616         match *ty.kind() {
1617             ty::Bool => Some((Size::from_bytes(1), 0)),
1618             ty::Char => Some((Size::from_bytes(4), 0)),
1619             ty::Int(ity) => {
1620                 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1621                 Some((size, 1u128 << (size.bits() as u128 - 1)))
1622             }
1623             ty::Uint(uty) => Some((Integer::from_attr(&tcx, UnsignedInt(uty)).size(), 0)),
1624             _ => None,
1625         }
1626     }
1627
1628     #[inline]
1629     fn from_const(
1630         tcx: TyCtxt<'tcx>,
1631         param_env: ty::ParamEnv<'tcx>,
1632         value: &Const<'tcx>,
1633         span: Span,
1634     ) -> Option<IntRange<'tcx>> {
1635         if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) {
1636             let ty = value.ty;
1637             let val = (|| {
1638                 if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val {
1639                     // For this specific pattern we can skip a lot of effort and go
1640                     // straight to the result, after doing a bit of checking. (We
1641                     // could remove this branch and just fall through, which
1642                     // is more general but much slower.)
1643                     if let Ok(bits) = scalar.to_bits_or_ptr(target_size, &tcx) {
1644                         return Some(bits);
1645                     }
1646                 }
1647                 // This is a more general form of the previous case.
1648                 value.try_eval_bits(tcx, param_env, ty)
1649             })()?;
1650             let val = val ^ bias;
1651             Some(IntRange { range: val..=val, ty, span })
1652         } else {
1653             None
1654         }
1655     }
1656
1657     #[inline]
1658     fn from_range(
1659         tcx: TyCtxt<'tcx>,
1660         lo: u128,
1661         hi: u128,
1662         ty: Ty<'tcx>,
1663         end: &RangeEnd,
1664         span: Span,
1665     ) -> Option<IntRange<'tcx>> {
1666         if Self::is_integral(ty) {
1667             // Perform a shift if the underlying types are signed,
1668             // which makes the interval arithmetic simpler.
1669             let bias = IntRange::signed_bias(tcx, ty);
1670             let (lo, hi) = (lo ^ bias, hi ^ bias);
1671             let offset = (*end == RangeEnd::Excluded) as u128;
1672             if lo > hi || (lo == hi && *end == RangeEnd::Excluded) {
1673                 // This should have been caught earlier by E0030.
1674                 bug!("malformed range pattern: {}..={}", lo, (hi - offset));
1675             }
1676             Some(IntRange { range: lo..=(hi - offset), ty, span })
1677         } else {
1678             None
1679         }
1680     }
1681
1682     fn from_pat(
1683         tcx: TyCtxt<'tcx>,
1684         param_env: ty::ParamEnv<'tcx>,
1685         pat: &Pat<'tcx>,
1686     ) -> Option<IntRange<'tcx>> {
1687         match pat_constructor(tcx, param_env, pat)? {
1688             IntRange(range) => Some(range),
1689             _ => None,
1690         }
1691     }
1692
1693     // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
1694     fn signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> u128 {
1695         match *ty.kind() {
1696             ty::Int(ity) => {
1697                 let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128;
1698                 1u128 << (bits - 1)
1699             }
1700             _ => 0,
1701         }
1702     }
1703
1704     /// Returns a collection of ranges that spans the values covered by `ranges`, subtracted
1705     /// by the values covered by `self`: i.e., `ranges \ self` (in set notation).
1706     fn subtract_from(&self, ranges: Vec<IntRange<'tcx>>) -> Vec<IntRange<'tcx>> {
1707         let mut remaining_ranges = vec![];
1708         let ty = self.ty;
1709         let span = self.span;
1710         let (lo, hi) = self.boundaries();
1711         for subrange in ranges {
1712             let (subrange_lo, subrange_hi) = subrange.range.into_inner();
1713             if lo > subrange_hi || subrange_lo > hi {
1714                 // The pattern doesn't intersect with the subrange at all,
1715                 // so the subrange remains untouched.
1716                 remaining_ranges.push(IntRange { range: subrange_lo..=subrange_hi, ty, span });
1717             } else {
1718                 if lo > subrange_lo {
1719                     // The pattern intersects an upper section of the
1720                     // subrange, so a lower section will remain.
1721                     remaining_ranges.push(IntRange { range: subrange_lo..=(lo - 1), ty, span });
1722                 }
1723                 if hi < subrange_hi {
1724                     // The pattern intersects a lower section of the
1725                     // subrange, so an upper section will remain.
1726                     remaining_ranges.push(IntRange { range: (hi + 1)..=subrange_hi, ty, span });
1727                 }
1728             }
1729         }
1730         remaining_ranges
1731     }
1732
1733     fn is_subrange(&self, other: &Self) -> bool {
1734         other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
1735     }
1736
1737     fn intersection(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Option<Self> {
1738         let ty = self.ty;
1739         let (lo, hi) = self.boundaries();
1740         let (other_lo, other_hi) = other.boundaries();
1741         if self.treat_exhaustively(tcx) {
1742             if lo <= other_hi && other_lo <= hi {
1743                 let span = other.span;
1744                 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty, span })
1745             } else {
1746                 None
1747             }
1748         } else {
1749             // If the range should not be treated exhaustively, fallback to checking for inclusion.
1750             if self.is_subrange(other) { Some(self.clone()) } else { None }
1751         }
1752     }
1753
1754     fn suspicious_intersection(&self, other: &Self) -> bool {
1755         // `false` in the following cases:
1756         // 1     ----      // 1  ----------   // 1 ----        // 1       ----
1757         // 2  ----------   // 2     ----      // 2       ----  // 2 ----
1758         //
1759         // The following are currently `false`, but could be `true` in the future (#64007):
1760         // 1 ---------       // 1     ---------
1761         // 2     ----------  // 2 ----------
1762         //
1763         // `true` in the following cases:
1764         // 1 -------          // 1       -------
1765         // 2       --------   // 2 -------
1766         let (lo, hi) = self.boundaries();
1767         let (other_lo, other_hi) = other.boundaries();
1768         lo == other_hi || hi == other_lo
1769     }
1770
1771     fn to_pat(&self, tcx: TyCtxt<'tcx>) -> Pat<'tcx> {
1772         let (lo, hi) = self.boundaries();
1773
1774         let bias = IntRange::signed_bias(tcx, self.ty);
1775         let (lo, hi) = (lo ^ bias, hi ^ bias);
1776
1777         let ty = ty::ParamEnv::empty().and(self.ty);
1778         let lo_const = ty::Const::from_bits(tcx, lo, ty);
1779         let hi_const = ty::Const::from_bits(tcx, hi, ty);
1780
1781         let kind = if lo == hi {
1782             PatKind::Constant { value: lo_const }
1783         } else {
1784             PatKind::Range(PatRange { lo: lo_const, hi: hi_const, end: RangeEnd::Included })
1785         };
1786
1787         // This is a brand new pattern, so we don't reuse `self.span`.
1788         Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(kind) }
1789     }
1790 }
1791
1792 /// Ignore spans when comparing, they don't carry semantic information as they are only for lints.
1793 impl<'tcx> std::cmp::PartialEq for IntRange<'tcx> {
1794     fn eq(&self, other: &Self) -> bool {
1795         self.range == other.range && self.ty == other.ty
1796     }
1797 }
1798
1799 // A struct to compute a set of constructors equivalent to `all_ctors \ used_ctors`.
1800 struct MissingConstructors<'tcx> {
1801     all_ctors: Vec<Constructor<'tcx>>,
1802     used_ctors: Vec<Constructor<'tcx>>,
1803 }
1804
1805 impl<'tcx> MissingConstructors<'tcx> {
1806     fn new(all_ctors: Vec<Constructor<'tcx>>, used_ctors: Vec<Constructor<'tcx>>) -> Self {
1807         MissingConstructors { all_ctors, used_ctors }
1808     }
1809
1810     fn into_inner(self) -> (Vec<Constructor<'tcx>>, Vec<Constructor<'tcx>>) {
1811         (self.all_ctors, self.used_ctors)
1812     }
1813
1814     fn is_empty(&self) -> bool {
1815         self.iter().next().is_none()
1816     }
1817     /// Whether this contains all the constructors for the given type or only a
1818     /// subset.
1819     fn all_ctors_are_missing(&self) -> bool {
1820         self.used_ctors.is_empty()
1821     }
1822
1823     /// Iterate over all_ctors \ used_ctors
1824     fn iter<'a>(&'a self) -> impl Iterator<Item = Constructor<'tcx>> + Captures<'a> {
1825         self.all_ctors.iter().flat_map(move |req_ctor| req_ctor.subtract_ctors(&self.used_ctors))
1826     }
1827 }
1828
1829 impl<'tcx> fmt::Debug for MissingConstructors<'tcx> {
1830     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831         let ctors: Vec<_> = self.iter().collect();
1832         write!(f, "{:?}", ctors)
1833     }
1834 }
1835
1836 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html.
1837 /// The algorithm from the paper has been modified to correctly handle empty
1838 /// types. The changes are:
1839 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
1840 ///       continue to recurse over columns.
1841 ///   (1) all_constructors will only return constructors that are statically
1842 ///       possible. E.g., it will only return `Ok` for `Result<T, !>`.
1843 ///
1844 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
1845 /// to a set of such vectors `m` - this is defined as there being a set of
1846 /// inputs that will match `v` but not any of the sets in `m`.
1847 ///
1848 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
1849 ///
1850 /// This is used both for reachability checking (if a pattern isn't useful in
1851 /// relation to preceding patterns, it is not reachable) and exhaustiveness
1852 /// checking (if a wildcard pattern is useful in relation to a matrix, the
1853 /// matrix isn't exhaustive).
1854 ///
1855 /// `is_under_guard` is used to inform if the pattern has a guard. If it
1856 /// has one it must not be inserted into the matrix. This shouldn't be
1857 /// relied on for soundness.
1858 crate fn is_useful<'p, 'tcx>(
1859     cx: &mut MatchCheckCtxt<'p, 'tcx>,
1860     matrix: &Matrix<'p, 'tcx>,
1861     v: &PatStack<'p, 'tcx>,
1862     witness_preference: WitnessPreference,
1863     hir_id: HirId,
1864     is_under_guard: bool,
1865     is_top_level: bool,
1866 ) -> Usefulness<'tcx> {
1867     let Matrix { patterns: rows, .. } = matrix;
1868     debug!("is_useful({:#?}, {:#?})", matrix, v);
1869
1870     // The base case. We are pattern-matching on () and the return value is
1871     // based on whether our matrix has a row or not.
1872     // NOTE: This could potentially be optimized by checking rows.is_empty()
1873     // first and then, if v is non-empty, the return value is based on whether
1874     // the type of the tuple we're checking is inhabited or not.
1875     if v.is_empty() {
1876         return if rows.is_empty() {
1877             Usefulness::new_useful(witness_preference)
1878         } else {
1879             NotUseful
1880         };
1881     };
1882
1883     assert!(rows.iter().all(|r| r.len() == v.len()));
1884
1885     // If the first pattern is an or-pattern, expand it.
1886     if let Some(vs) = v.expand_or_pat() {
1887         // We need to push the already-seen patterns into the matrix in order to detect redundant
1888         // branches like `Some(_) | Some(0)`. We also keep track of the unreachable subpatterns.
1889         let mut matrix = matrix.clone();
1890         // `Vec` of all the unreachable branches of the current or-pattern.
1891         let mut unreachable_branches = Vec::new();
1892         // Subpatterns that are unreachable from all branches. E.g. in the following case, the last
1893         // `true` is unreachable only from one branch, so it is overall reachable.
1894         // ```
1895         // match (true, true) {
1896         //     (true, true) => {}
1897         //     (false | true, false | true) => {}
1898         // }
1899         // ```
1900         let mut unreachable_subpats = FxHashSet::default();
1901         // Whether any branch at all is useful.
1902         let mut any_is_useful = false;
1903
1904         for v in vs {
1905             let res = is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
1906             match res {
1907                 Useful(pats) => {
1908                     if !any_is_useful {
1909                         any_is_useful = true;
1910                         // Initialize with the first set of unreachable subpatterns encountered.
1911                         unreachable_subpats = pats.into_iter().collect();
1912                     } else {
1913                         // Keep the patterns unreachable from both this and previous branches.
1914                         unreachable_subpats =
1915                             pats.into_iter().filter(|p| unreachable_subpats.contains(p)).collect();
1916                     }
1917                 }
1918                 NotUseful => unreachable_branches.push(v.head().span),
1919                 UsefulWithWitness(_) => {
1920                     bug!("Encountered or-pat in `v` during exhaustiveness checking")
1921                 }
1922             }
1923             // If pattern has a guard don't add it to the matrix
1924             if !is_under_guard {
1925                 matrix.push(v);
1926             }
1927         }
1928         if any_is_useful {
1929             // Collect all the unreachable patterns.
1930             unreachable_branches.extend(unreachable_subpats);
1931             return Useful(unreachable_branches);
1932         } else {
1933             return NotUseful;
1934         }
1935     }
1936
1937     // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476).
1938     let ty = matrix.heads().next().map(|r| r.ty).unwrap_or(v.head().ty);
1939     let pcx = PatCtxt { ty, span: v.head().span };
1940
1941     debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v.head());
1942
1943     let ret = if let Some(constructor) = pat_constructor(cx.tcx, cx.param_env, v.head()) {
1944         debug!("is_useful - expanding constructor: {:#?}", constructor);
1945         split_grouped_constructors(
1946             cx.tcx,
1947             cx.param_env,
1948             pcx,
1949             vec![constructor],
1950             matrix,
1951             pcx.span,
1952             Some(hir_id),
1953         )
1954         .into_iter()
1955         .map(|c| {
1956             is_useful_specialized(
1957                 cx,
1958                 matrix,
1959                 v,
1960                 c,
1961                 pcx.ty,
1962                 witness_preference,
1963                 hir_id,
1964                 is_under_guard,
1965             )
1966         })
1967         .find(|result| result.is_useful())
1968         .unwrap_or(NotUseful)
1969     } else {
1970         debug!("is_useful - expanding wildcard");
1971
1972         let used_ctors: Vec<Constructor<'_>> =
1973             matrix.heads().filter_map(|p| pat_constructor(cx.tcx, cx.param_env, p)).collect();
1974         debug!("is_useful_used_ctors = {:#?}", used_ctors);
1975         // `all_ctors` are all the constructors for the given type, which
1976         // should all be represented (or caught with the wild pattern `_`).
1977         let all_ctors = all_constructors(cx, pcx);
1978         debug!("is_useful_all_ctors = {:#?}", all_ctors);
1979
1980         // `missing_ctors` is the set of constructors from the same type as the
1981         // first column of `matrix` that are matched only by wildcard patterns
1982         // from the first column.
1983         //
1984         // Therefore, if there is some pattern that is unmatched by `matrix`,
1985         // it will still be unmatched if the first constructor is replaced by
1986         // any of the constructors in `missing_ctors`
1987
1988         // Missing constructors are those that are not matched by any non-wildcard patterns in the
1989         // current column. We only fully construct them on-demand, because they're rarely used and
1990         // can be big.
1991         let missing_ctors = MissingConstructors::new(all_ctors, used_ctors);
1992
1993         debug!("is_useful_missing_ctors.empty()={:#?}", missing_ctors.is_empty(),);
1994
1995         if missing_ctors.is_empty() {
1996             let (all_ctors, _) = missing_ctors.into_inner();
1997             split_grouped_constructors(cx.tcx, cx.param_env, pcx, all_ctors, matrix, DUMMY_SP, None)
1998                 .into_iter()
1999                 .map(|c| {
2000                     is_useful_specialized(
2001                         cx,
2002                         matrix,
2003                         v,
2004                         c,
2005                         pcx.ty,
2006                         witness_preference,
2007                         hir_id,
2008                         is_under_guard,
2009                     )
2010                 })
2011                 .find(|result| result.is_useful())
2012                 .unwrap_or(NotUseful)
2013         } else {
2014             let matrix = matrix.specialize_wildcard();
2015             let v = v.to_tail();
2016             let usefulness =
2017                 is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
2018
2019             // In this case, there's at least one "free"
2020             // constructor that is only matched against by
2021             // wildcard patterns.
2022             //
2023             // There are 2 ways we can report a witness here.
2024             // Commonly, we can report all the "free"
2025             // constructors as witnesses, e.g., if we have:
2026             //
2027             // ```
2028             //     enum Direction { N, S, E, W }
2029             //     let Direction::N = ...;
2030             // ```
2031             //
2032             // we can report 3 witnesses: `S`, `E`, and `W`.
2033             //
2034             // However, there is a case where we don't want
2035             // to do this and instead report a single `_` witness:
2036             // if the user didn't actually specify a constructor
2037             // in this arm, e.g., in
2038             // ```
2039             //     let x: (Direction, Direction, bool) = ...;
2040             //     let (_, _, false) = x;
2041             // ```
2042             // we don't want to show all 16 possible witnesses
2043             // `(<direction-1>, <direction-2>, true)` - we are
2044             // satisfied with `(_, _, true)`. In this case,
2045             // `used_ctors` is empty.
2046             // The exception is: if we are at the top-level, for example in an empty match, we
2047             // sometimes prefer reporting the list of constructors instead of just `_`.
2048             let report_ctors_rather_than_wildcard = is_top_level && !IntRange::is_integral(pcx.ty);
2049             if missing_ctors.all_ctors_are_missing() && !report_ctors_rather_than_wildcard {
2050                 // All constructors are unused. Add a wild pattern
2051                 // rather than each individual constructor.
2052                 usefulness.apply_wildcard(pcx.ty)
2053             } else {
2054                 // Construct for each missing constructor a "wild" version of this
2055                 // constructor, that matches everything that can be built with
2056                 // it. For example, if `ctor` is a `Constructor::Variant` for
2057                 // `Option::Some`, we get the pattern `Some(_)`.
2058                 usefulness.apply_missing_ctors(cx, pcx.ty, &missing_ctors)
2059             }
2060         }
2061     };
2062     debug!("is_useful::returns({:#?}, {:#?}) = {:?}", matrix, v, ret);
2063     ret
2064 }
2065
2066 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied
2067 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
2068 fn is_useful_specialized<'p, 'tcx>(
2069     cx: &mut MatchCheckCtxt<'p, 'tcx>,
2070     matrix: &Matrix<'p, 'tcx>,
2071     v: &PatStack<'p, 'tcx>,
2072     ctor: Constructor<'tcx>,
2073     ty: Ty<'tcx>,
2074     witness_preference: WitnessPreference,
2075     hir_id: HirId,
2076     is_under_guard: bool,
2077 ) -> Usefulness<'tcx> {
2078     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, ty);
2079
2080     // We cache the result of `Fields::wildcards` because it is used a lot.
2081     let ctor_wild_subpatterns = Fields::wildcards(cx, &ctor, ty);
2082     let matrix = matrix.specialize_constructor(cx, &ctor, &ctor_wild_subpatterns);
2083     v.specialize_constructor(cx, &ctor, &ctor_wild_subpatterns)
2084         .map(|v| is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false))
2085         .map(|u| u.apply_constructor(cx, &ctor, ty, &ctor_wild_subpatterns))
2086         .unwrap_or(NotUseful)
2087 }
2088
2089 /// Determines the constructor that the given pattern can be specialized to.
2090 /// Returns `None` in case of a catch-all, which can't be specialized.
2091 fn pat_constructor<'tcx>(
2092     tcx: TyCtxt<'tcx>,
2093     param_env: ty::ParamEnv<'tcx>,
2094     pat: &Pat<'tcx>,
2095 ) -> Option<Constructor<'tcx>> {
2096     match *pat.kind {
2097         PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern`
2098         PatKind::Binding { .. } | PatKind::Wild => None,
2099         PatKind::Leaf { .. } | PatKind::Deref { .. } => Some(Single),
2100         PatKind::Variant { adt_def, variant_index, .. } => {
2101             Some(Variant(adt_def.variants[variant_index].def_id))
2102         }
2103         PatKind::Constant { value } => {
2104             if let Some(int_range) = IntRange::from_const(tcx, param_env, value, pat.span) {
2105                 Some(IntRange(int_range))
2106             } else {
2107                 match value.ty.kind() {
2108                     ty::Float(_) => Some(FloatRange(value, value, RangeEnd::Included)),
2109                     _ => Some(ConstantValue(value)),
2110                 }
2111             }
2112         }
2113         PatKind::Range(PatRange { lo, hi, end }) => {
2114             let ty = lo.ty;
2115             if let Some(int_range) = IntRange::from_range(
2116                 tcx,
2117                 lo.eval_bits(tcx, param_env, lo.ty),
2118                 hi.eval_bits(tcx, param_env, hi.ty),
2119                 ty,
2120                 &end,
2121                 pat.span,
2122             ) {
2123                 Some(IntRange(int_range))
2124             } else {
2125                 Some(FloatRange(lo, hi, end))
2126             }
2127         }
2128         PatKind::Array { ref prefix, ref slice, ref suffix }
2129         | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
2130             let array_len = match pat.ty.kind() {
2131                 ty::Array(_, length) => Some(length.eval_usize(tcx, param_env)),
2132                 ty::Slice(_) => None,
2133                 _ => span_bug!(pat.span, "bad ty {:?} for slice pattern", pat.ty),
2134             };
2135             let prefix = prefix.len() as u64;
2136             let suffix = suffix.len() as u64;
2137             let kind =
2138                 if slice.is_some() { VarLen(prefix, suffix) } else { FixedLen(prefix + suffix) };
2139             Some(Slice(Slice { array_len, kind }))
2140         }
2141         PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."),
2142     }
2143 }
2144
2145 /// For exhaustive integer matching, some constructors are grouped within other constructors
2146 /// (namely integer typed values are grouped within ranges). However, when specialising these
2147 /// constructors, we want to be specialising for the underlying constructors (the integers), not
2148 /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
2149 /// mean creating a separate constructor for every single value in the range, which is clearly
2150 /// impractical. However, observe that for some ranges of integers, the specialisation will be
2151 /// identical across all values in that range (i.e., there are equivalence classes of ranges of
2152 /// constructors based on their `is_useful_specialized` outcome). These classes are grouped by
2153 /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
2154 /// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
2155 /// change.
2156 /// Our solution, therefore, is to split the range constructor into subranges at every single point
2157 /// the group of intersecting patterns changes (using the method described below).
2158 /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
2159 /// on actual integers. The nice thing about this is that the number of subranges is linear in the
2160 /// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't
2161 /// need to be worried about matching over gargantuan ranges.
2162 ///
2163 /// Essentially, given the first column of a matrix representing ranges, looking like the following:
2164 ///
2165 /// |------|  |----------| |-------|    ||
2166 ///    |-------| |-------|            |----| ||
2167 ///       |---------|
2168 ///
2169 /// We split the ranges up into equivalence classes so the ranges are no longer overlapping:
2170 ///
2171 /// |--|--|||-||||--||---|||-------|  |-|||| ||
2172 ///
2173 /// The logic for determining how to split the ranges is fairly straightforward: we calculate
2174 /// boundaries for each interval range, sort them, then create constructors for each new interval
2175 /// between every pair of boundary points. (This essentially sums up to performing the intuitive
2176 /// merging operation depicted above.)
2177 ///
2178 /// `hir_id` is `None` when we're evaluating the wildcard pattern, do not lint for overlapping in
2179 /// ranges that case.
2180 ///
2181 /// This also splits variable-length slices into fixed-length slices.
2182 fn split_grouped_constructors<'p, 'tcx>(
2183     tcx: TyCtxt<'tcx>,
2184     param_env: ty::ParamEnv<'tcx>,
2185     pcx: PatCtxt<'tcx>,
2186     ctors: Vec<Constructor<'tcx>>,
2187     matrix: &Matrix<'p, 'tcx>,
2188     span: Span,
2189     hir_id: Option<HirId>,
2190 ) -> Vec<Constructor<'tcx>> {
2191     let ty = pcx.ty;
2192     let mut split_ctors = Vec::with_capacity(ctors.len());
2193     debug!("split_grouped_constructors({:#?}, {:#?})", matrix, ctors);
2194
2195     for ctor in ctors.into_iter() {
2196         match ctor {
2197             IntRange(ctor_range) if ctor_range.treat_exhaustively(tcx) => {
2198                 // Fast-track if the range is trivial. In particular, don't do the overlapping
2199                 // ranges check.
2200                 if ctor_range.is_singleton() {
2201                     split_ctors.push(IntRange(ctor_range));
2202                     continue;
2203                 }
2204
2205                 /// Represents a border between 2 integers. Because the intervals spanning borders
2206                 /// must be able to cover every integer, we need to be able to represent
2207                 /// 2^128 + 1 such borders.
2208                 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2209                 enum Border {
2210                     JustBefore(u128),
2211                     AfterMax,
2212                 }
2213
2214                 // A function for extracting the borders of an integer interval.
2215                 fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
2216                     let (lo, hi) = r.range.into_inner();
2217                     let from = Border::JustBefore(lo);
2218                     let to = match hi.checked_add(1) {
2219                         Some(m) => Border::JustBefore(m),
2220                         None => Border::AfterMax,
2221                     };
2222                     vec![from, to].into_iter()
2223                 }
2224
2225                 // Collect the span and range of all the intersecting ranges to lint on likely
2226                 // incorrect range patterns. (#63987)
2227                 let mut overlaps = vec![];
2228                 // `borders` is the set of borders between equivalence classes: each equivalence
2229                 // class lies between 2 borders.
2230                 let row_borders = matrix
2231                     .patterns
2232                     .iter()
2233                     .flat_map(|row| {
2234                         IntRange::from_pat(tcx, param_env, row.head()).map(|r| (r, row.len()))
2235                     })
2236                     .flat_map(|(range, row_len)| {
2237                         let intersection = ctor_range.intersection(tcx, &range);
2238                         let should_lint = ctor_range.suspicious_intersection(&range);
2239                         if let (Some(range), 1, true) = (&intersection, row_len, should_lint) {
2240                             // FIXME: for now, only check for overlapping ranges on simple range
2241                             // patterns. Otherwise with the current logic the following is detected
2242                             // as overlapping:
2243                             //   match (10u8, true) {
2244                             //    (0 ..= 125, false) => {}
2245                             //    (126 ..= 255, false) => {}
2246                             //    (0 ..= 255, true) => {}
2247                             //  }
2248                             overlaps.push(range.clone());
2249                         }
2250                         intersection
2251                     })
2252                     .flat_map(range_borders);
2253                 let ctor_borders = range_borders(ctor_range.clone());
2254                 let mut borders: Vec<_> = row_borders.chain(ctor_borders).collect();
2255                 borders.sort_unstable();
2256
2257                 lint_overlapping_patterns(tcx, hir_id, ctor_range, ty, overlaps);
2258
2259                 // We're going to iterate through every adjacent pair of borders, making sure that
2260                 // each represents an interval of nonnegative length, and convert each such
2261                 // interval into a constructor.
2262                 split_ctors.extend(
2263                     borders
2264                         .array_windows()
2265                         .filter_map(|&pair| match pair {
2266                             [Border::JustBefore(n), Border::JustBefore(m)] => {
2267                                 if n < m {
2268                                     Some(IntRange { range: n..=(m - 1), ty, span })
2269                                 } else {
2270                                     None
2271                                 }
2272                             }
2273                             [Border::JustBefore(n), Border::AfterMax] => {
2274                                 Some(IntRange { range: n..=u128::MAX, ty, span })
2275                             }
2276                             [Border::AfterMax, _] => None,
2277                         })
2278                         .map(IntRange),
2279                 );
2280             }
2281             Slice(Slice { array_len, kind: VarLen(self_prefix, self_suffix) }) => {
2282                 // The exhaustiveness-checking paper does not include any details on
2283                 // checking variable-length slice patterns. However, they are matched
2284                 // by an infinite collection of fixed-length array patterns.
2285                 //
2286                 // Checking the infinite set directly would take an infinite amount
2287                 // of time. However, it turns out that for each finite set of
2288                 // patterns `P`, all sufficiently large array lengths are equivalent:
2289                 //
2290                 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
2291                 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
2292                 // `sₘ` for each sufficiently-large length `m` that applies to exactly
2293                 // the same subset of `P`.
2294                 //
2295                 // Because of that, each witness for reachability-checking from one
2296                 // of the sufficiently-large lengths can be transformed to an
2297                 // equally-valid witness from any other length, so we only have
2298                 // to check slice lengths from the "minimal sufficiently-large length"
2299                 // and below.
2300                 //
2301                 // Note that the fact that there is a *single* `sₘ` for each `m`
2302                 // not depending on the specific pattern in `P` is important: if
2303                 // you look at the pair of patterns
2304                 //     `[true, ..]`
2305                 //     `[.., false]`
2306                 // Then any slice of length ≥1 that matches one of these two
2307                 // patterns can be trivially turned to a slice of any
2308                 // other length ≥1 that matches them and vice-versa - for
2309                 // but the slice from length 2 `[false, true]` that matches neither
2310                 // of these patterns can't be turned to a slice from length 1 that
2311                 // matches neither of these patterns, so we have to consider
2312                 // slices from length 2 there.
2313                 //
2314                 // Now, to see that that length exists and find it, observe that slice
2315                 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
2316                 // "variable-length" patterns (`[_, .., _]`).
2317                 //
2318                 // For fixed-length patterns, all slices with lengths *longer* than
2319                 // the pattern's length have the same outcome (of not matching), so
2320                 // as long as `L` is greater than the pattern's length we can pick
2321                 // any `sₘ` from that length and get the same result.
2322                 //
2323                 // For variable-length patterns, the situation is more complicated,
2324                 // because as seen above the precise value of `sₘ` matters.
2325                 //
2326                 // However, for each variable-length pattern `p` with a prefix of length
2327                 // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
2328                 // `slₚ` elements are examined.
2329                 //
2330                 // Therefore, as long as `L` is positive (to avoid concerns about empty
2331                 // types), all elements after the maximum prefix length and before
2332                 // the maximum suffix length are not examined by any variable-length
2333                 // pattern, and therefore can be added/removed without affecting
2334                 // them - creating equivalent patterns from any sufficiently-large
2335                 // length.
2336                 //
2337                 // Of course, if fixed-length patterns exist, we must be sure
2338                 // that our length is large enough to miss them all, so
2339                 // we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))`
2340                 //
2341                 // for example, with the above pair of patterns, all elements
2342                 // but the first and last can be added/removed, so any
2343                 // witness of length ≥2 (say, `[false, false, true]`) can be
2344                 // turned to a witness from any other length ≥2.
2345
2346                 let mut max_prefix_len = self_prefix;
2347                 let mut max_suffix_len = self_suffix;
2348                 let mut max_fixed_len = 0;
2349
2350                 let head_ctors =
2351                     matrix.heads().filter_map(|pat| pat_constructor(tcx, param_env, pat));
2352                 for ctor in head_ctors {
2353                     if let Slice(slice) = ctor {
2354                         match slice.pattern_kind() {
2355                             FixedLen(len) => {
2356                                 max_fixed_len = cmp::max(max_fixed_len, len);
2357                             }
2358                             VarLen(prefix, suffix) => {
2359                                 max_prefix_len = cmp::max(max_prefix_len, prefix);
2360                                 max_suffix_len = cmp::max(max_suffix_len, suffix);
2361                             }
2362                         }
2363                     }
2364                 }
2365
2366                 // For diagnostics, we keep the prefix and suffix lengths separate, so in the case
2367                 // where `max_fixed_len + 1` is the largest, we adapt `max_prefix_len` accordingly,
2368                 // so that `L = max_prefix_len + max_suffix_len`.
2369                 if max_fixed_len + 1 >= max_prefix_len + max_suffix_len {
2370                     // The subtraction can't overflow thanks to the above check.
2371                     // The new `max_prefix_len` is also guaranteed to be larger than its previous
2372                     // value.
2373                     max_prefix_len = max_fixed_len + 1 - max_suffix_len;
2374                 }
2375
2376                 match array_len {
2377                     Some(len) => {
2378                         let kind = if max_prefix_len + max_suffix_len < len {
2379                             VarLen(max_prefix_len, max_suffix_len)
2380                         } else {
2381                             FixedLen(len)
2382                         };
2383                         split_ctors.push(Slice(Slice { array_len, kind }));
2384                     }
2385                     None => {
2386                         // `ctor` originally covered the range `(self_prefix +
2387                         // self_suffix..infinity)`. We now split it into two: lengths smaller than
2388                         // `max_prefix_len + max_suffix_len` are treated independently as
2389                         // fixed-lengths slices, and lengths above are captured by a final VarLen
2390                         // constructor.
2391                         split_ctors.extend(
2392                             (self_prefix + self_suffix..max_prefix_len + max_suffix_len)
2393                                 .map(|len| Slice(Slice { array_len, kind: FixedLen(len) })),
2394                         );
2395                         split_ctors.push(Slice(Slice {
2396                             array_len,
2397                             kind: VarLen(max_prefix_len, max_suffix_len),
2398                         }));
2399                     }
2400                 }
2401             }
2402             // Any other constructor can be used unchanged.
2403             _ => split_ctors.push(ctor),
2404         }
2405     }
2406
2407     debug!("split_grouped_constructors(..)={:#?}", split_ctors);
2408     split_ctors
2409 }
2410
2411 fn lint_overlapping_patterns<'tcx>(
2412     tcx: TyCtxt<'tcx>,
2413     hir_id: Option<HirId>,
2414     ctor_range: IntRange<'tcx>,
2415     ty: Ty<'tcx>,
2416     overlaps: Vec<IntRange<'tcx>>,
2417 ) {
2418     if let (true, Some(hir_id)) = (!overlaps.is_empty(), hir_id) {
2419         tcx.struct_span_lint_hir(
2420             lint::builtin::OVERLAPPING_PATTERNS,
2421             hir_id,
2422             ctor_range.span,
2423             |lint| {
2424                 let mut err = lint.build("multiple patterns covering the same range");
2425                 err.span_label(ctor_range.span, "overlapping patterns");
2426                 for int_range in overlaps {
2427                     // Use the real type for user display of the ranges:
2428                     err.span_label(
2429                         int_range.span,
2430                         &format!(
2431                             "this range overlaps on `{}`",
2432                             IntRange { range: int_range.range, ty, span: DUMMY_SP }.to_pat(tcx),
2433                         ),
2434                     );
2435                 }
2436                 err.emit();
2437             },
2438         );
2439     }
2440 }
2441
2442 /// This is the main specialization step. It expands the pattern
2443 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
2444 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
2445 /// Returns `None` if the pattern does not have the given constructor.
2446 ///
2447 /// OTOH, slice patterns with a subslice pattern (tail @ ..) can be expanded into multiple
2448 /// different patterns.
2449 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
2450 /// fields filled with wild patterns.
2451 ///
2452 /// This is roughly the inverse of `Constructor::apply`.
2453 fn specialize_one_pattern<'p, 'tcx>(
2454     cx: &mut MatchCheckCtxt<'p, 'tcx>,
2455     pat: &'p Pat<'tcx>,
2456     constructor: &Constructor<'tcx>,
2457     ctor_wild_subpatterns: &Fields<'p, 'tcx>,
2458 ) -> Option<Fields<'p, 'tcx>> {
2459     if let NonExhaustive = constructor {
2460         // Only a wildcard pattern can match the special extra constructor
2461         if !pat.is_wildcard() {
2462             return None;
2463         }
2464         return Some(Fields::empty());
2465     }
2466
2467     let result = match *pat.kind {
2468         PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern`
2469
2470         PatKind::Binding { .. } | PatKind::Wild => Some(ctor_wild_subpatterns.clone()),
2471
2472         PatKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
2473             let variant = &adt_def.variants[variant_index];
2474             if constructor != &Variant(variant.def_id) {
2475                 return None;
2476             }
2477             Some(ctor_wild_subpatterns.replace_with_fieldpats(subpatterns))
2478         }
2479
2480         PatKind::Leaf { ref subpatterns } => {
2481             Some(ctor_wild_subpatterns.replace_with_fieldpats(subpatterns))
2482         }
2483
2484         PatKind::Deref { ref subpattern } => Some(Fields::from_single_pattern(subpattern)),
2485
2486         PatKind::Constant { .. } | PatKind::Range { .. } => {
2487             match constructor {
2488                 Single => {}
2489                 IntRange(ctor) => {
2490                     let pat = IntRange::from_pat(cx.tcx, cx.param_env, pat)?;
2491                     ctor.intersection(cx.tcx, &pat)?;
2492                     // Constructor splitting should ensure that all intersections we encounter
2493                     // are actually inclusions.
2494                     assert!(ctor.is_subrange(&pat));
2495                 }
2496                 FloatRange(ctor_from, ctor_to, ctor_end) => {
2497                     let (pat_from, pat_to, pat_end, ty) = match *pat.kind {
2498                         PatKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
2499                         PatKind::Range(PatRange { lo, hi, end }) => (lo, hi, end, lo.ty),
2500                         _ => unreachable!(), // This is ensured by the branch we're in
2501                     };
2502                     let to = compare_const_vals(cx.tcx, ctor_to, pat_to, cx.param_env, ty)?;
2503                     let from = compare_const_vals(cx.tcx, ctor_from, pat_from, cx.param_env, ty)?;
2504                     let intersects = (from == Ordering::Greater || from == Ordering::Equal)
2505                         && (to == Ordering::Less
2506                             || (pat_end == *ctor_end && to == Ordering::Equal));
2507                     if !intersects {
2508                         return None;
2509                     }
2510                 }
2511                 ConstantValue(ctor_value) => {
2512                     let pat_value = match *pat.kind {
2513                         PatKind::Constant { value } => value,
2514                         _ => span_bug!(
2515                             pat.span,
2516                             "unexpected range pattern {:?} for constant value ctor",
2517                             pat
2518                         ),
2519                     };
2520
2521                     // FIXME: there's probably a more direct way of comparing for equality
2522                     if compare_const_vals(cx.tcx, ctor_value, pat_value, cx.param_env, pat.ty)?
2523                         != Ordering::Equal
2524                     {
2525                         return None;
2526                     }
2527                 }
2528                 _ => {
2529                     span_bug!(pat.span, "unexpected pattern {:?} with ctor {:?}", pat, constructor)
2530                 }
2531             }
2532             Some(Fields::empty())
2533         }
2534
2535         PatKind::Array { ref prefix, ref slice, ref suffix }
2536         | PatKind::Slice { ref prefix, ref slice, ref suffix } => match *constructor {
2537             Slice(_) => {
2538                 // Number of subpatterns for this pattern
2539                 let pat_len = prefix.len() + suffix.len();
2540                 // Number of subpatterns for this constructor
2541                 let arity = ctor_wild_subpatterns.len();
2542
2543                 if (slice.is_none() && arity != pat_len) || pat_len > arity {
2544                     return None;
2545                 }
2546
2547                 // Replace the prefix and the suffix with the given patterns, leaving wildcards in
2548                 // the middle if there was a subslice pattern `..`.
2549                 let prefix = prefix.iter().enumerate();
2550                 let suffix = suffix.iter().enumerate().map(|(i, p)| (arity - suffix.len() + i, p));
2551                 Some(ctor_wild_subpatterns.replace_fields_indexed(prefix.chain(suffix)))
2552             }
2553             _ => span_bug!(pat.span, "unexpected ctor {:?} for slice pat", constructor),
2554         },
2555
2556         PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."),
2557     };
2558     debug!(
2559         "specialize({:#?}, {:#?}, {:#?}) = {:#?}",
2560         pat, constructor, ctor_wild_subpatterns, result
2561     );
2562
2563     result
2564 }