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