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