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