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