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