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