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