]> git.lizzy.rs Git - rust.git/blobdiff - src/librustc_mir/hair/pattern/_match.rs
Extract constructor application as a Constructor method
[rust.git] / src / librustc_mir / hair / pattern / _match.rs
index d3e5f28f92fef680fb799abb6250125636af602f..093df57087cbe7ec6f19e151bb1329c4873c561e 100644 (file)
 /// (without being so rigorous).
 ///
 /// The core of the algorithm revolves about a "usefulness" check. In particular, we
-/// are trying to compute a predicate `U(P, p_{m + 1})` where `P` is a list of patterns
-/// of length `m` for a compound (product) type with `n` components (we refer to this as
-/// a matrix). `U(P, p_{m + 1})` represents whether, given an existing list of patterns
-/// `p_1 ..= p_m`, adding a new pattern will be "useful" (that is, cover previously-
+/// are trying to compute a predicate `U(P, p)` where `P` is a list of patterns (we refer to this as
+/// a matrix). `U(P, p)` represents whether, given an existing list of patterns
+/// `P_1 ..= P_m`, adding a new pattern `p` will be "useful" (that is, cover previously-
 /// uncovered values of the type).
 ///
 /// If we have this predicate, then we can easily compute both exhaustiveness of an
 /// entire set of patterns and the individual usefulness of each one.
 /// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard
 /// match doesn't increase the number of values we're matching)
-/// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e., adding a
+/// (b) a pattern `P_i` is not useful if `U(P[0..=(i-1), P_i)` is false (i.e., adding a
 /// pattern to those that have come before it doesn't increase the number of values
 /// we're matching).
 ///
+/// During the course of the algorithm, the rows of the matrix won't just be individual patterns,
+/// but rather partially-deconstructed patterns in the form of a list of patterns. The paper
+/// calls those pattern-vectors, and we will call them pattern-stacks. The same holds for the
+/// new pattern `p`.
+///
 /// For example, say we have the following:
 /// ```
 ///     // x: (Option<bool>, Result<()>)
 ///         (None, Err(_)) => {}
 ///     }
 /// ```
-/// Here, the matrix `P` is 3 x 2 (rows x columns).
+/// Here, the matrix `P` starts as:
 /// [
-///     [Some(true), _],
-///     [None, Err(())],
-///     [None, Err(_)],
+///     [(Some(true), _)],
+///     [(None, Err(()))],
+///     [(None, Err(_))],
 /// ]
 /// We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering
-/// `[Some(false), _]`, for instance). In addition, row 3 is not useful, because
+/// `[(Some(false), _)]`, for instance). In addition, row 3 is not useful, because
 /// all the values it covers are already covered by row 2.
 ///
-/// To compute `U`, we must have two other concepts.
-///     1. `S(c, P)` is a "specialized matrix", where `c` is a constructor (like `Some` or
-///        `None`). You can think of it as filtering `P` to just the rows whose *first* pattern
-///        can cover `c` (and expanding OR-patterns into distinct patterns), and then expanding
-///        the constructor into all of its components.
-///        The specialization of a row vector is computed by `specialize`.
+/// A list of patterns can be thought of as a stack, because we are mainly interested in the top of
+/// the stack at any given point, and we can pop or apply constructors to get new pattern-stacks.
+/// To match the paper, the top of the stack is at the beginning / on the left.
+///
+/// There are two important operations on pattern-stacks necessary to understand the algorithm:
+///     1. We can pop a given constructor off the top of a stack. This operation is called
+///        `specialize`, and is denoted `S(c, p)` where `c` is a constructor (like `Some` or
+///        `None`) and `p` a pattern-stack.
+///        If the pattern on top of the stack can cover `c`, this removes the constructor and
+///        pushes its arguments onto the stack. It also expands OR-patterns into distinct patterns.
+///        Otherwise the pattern-stack is discarded.
+///        This essentially filters those pattern-stacks whose top covers the constructor `c` and
+///        discards the others.
+///
+///        For example, the first pattern above initially gives a stack `[(Some(true), _)]`. If we
+///        pop the tuple constructor, we are left with `[Some(true), _]`, and if we then pop the
+///        `Some` constructor we get `[true, _]`. If we had popped `None` instead, we would get
+///        nothing back.
+///
+///        This returns zero or more new pattern-stacks, as follows. We look at the pattern `p_1`
+///        on top of the stack, and we have four cases:
+///             1.1. `p_1 = c(r_1, .., r_a)`, i.e. the top of the stack has constructor `c`. We
+///                  push onto the stack the arguments of this constructor, and return the result:
+///                     r_1, .., r_a, p_2, .., p_n
+///             1.2. `p_1 = c'(r_1, .., r_a')` where `c ≠ c'`. We discard the current stack and
+///                  return nothing.
+///             1.3. `p_1 = _`. We push onto the stack as many wildcards as the constructor `c` has
+///                  arguments (its arity), and return the resulting stack:
+///                     _, .., _, p_2, .., p_n
+///             1.4. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting
+///                  stack:
+///                     S(c, (r_1, p_2, .., p_n))
+///                     S(c, (r_2, p_2, .., p_n))
+///
+///     2. We can pop a wildcard off the top of the stack. This is called `D(p)`, where `p` is
+///        a pattern-stack.
+///        This is used when we know there are missing constructor cases, but there might be
+///        existing wildcard patterns, so to check the usefulness of the matrix, we have to check
+///        all its *other* components.
 ///
-///        It is computed as follows. For each row `p_i` of P, we have four cases:
-///             1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `S(c, P)` has a corresponding row:
-///                     r_1, .., r_a, p_(i,2), .., p_(i,n)
-///             1.2. `p_(i,1) = c'(r_1, .., r_a')` where `c ≠ c'`. Then `S(c, P)` has no
-///                  corresponding row.
-///             1.3. `p_(i,1) = _`. Then `S(c, P)` has a corresponding row:
-///                     _, .., _, p_(i,2), .., p_(i,n)
-///             1.4. `p_(i,1) = r_1 | r_2`. Then `S(c, P)` has corresponding rows inlined from:
-///                     S(c, (r_1, p_(i,2), .., p_(i,n)))
-///                     S(c, (r_2, p_(i,2), .., p_(i,n)))
+///        It is computed as follows. We look at the pattern `p_1` on top of the stack,
+///        and we have three cases:
+///             1.1. `p_1 = c(r_1, .., r_a)`. We discard the current stack and return nothing.
+///             1.2. `p_1 = _`. We return the rest of the stack:
+///                     p_2, .., p_n
+///             1.3. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting
+///               stack.
+///                     D((r_1, p_2, .., p_n))
+///                     D((r_2, p_2, .., p_n))
 ///
-///     2. `D(P)` is a "default matrix". This is used when we know there are missing
-///        constructor cases, but there might be existing wildcard patterns, so to check the
-///        usefulness of the matrix, we have to check all its *other* components.
-///        The default matrix is computed inline in `is_useful`.
+///     Note that the OR-patterns are not always used directly in Rust, but are used to derive the
+///     exhaustive integer matching rules, so they're written here for posterity.
 ///
-///         It is computed as follows. For each row `p_i` of P, we have three cases:
-///             1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `D(P)` has no corresponding row.
-///             1.2. `p_(i,1) = _`. Then `D(P)` has a corresponding row:
-///                     p_(i,2), .., p_(i,n)
-///             1.3. `p_(i,1) = r_1 | r_2`. Then `D(P)` has corresponding rows inlined from:
-///                     D((r_1, p_(i,2), .., p_(i,n)))
-///                     D((r_2, p_(i,2), .., p_(i,n)))
+/// Both those operations extend straightforwardly to a list or pattern-stacks, i.e. a matrix, by
+/// working row-by-row. Popping a constructor ends up keeping only the matrix rows that start with
+/// the given constructor, and popping a wildcard keeps those rows that start with a wildcard.
 ///
-///     Note that the OR-patterns are not always used directly in Rust, but are used to derive
-///     the exhaustive integer matching rules, so they're written here for posterity.
 ///
 /// The algorithm for computing `U`
 /// -------------------------------
 /// The algorithm is inductive (on the number of columns: i.e., components of tuple patterns).
 /// That means we're going to check the components from left-to-right, so the algorithm
-/// operates principally on the first component of the matrix and new pattern `p_{m + 1}`.
+/// operates principally on the first component of the matrix and new pattern-stack `p`.
 /// This algorithm is realised in the `is_useful` function.
 ///
 /// Base case. (`n = 0`, i.e., an empty tuple pattern)
 ///     - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`),
-///       then `U(P, p_{m + 1})` is false.
-///     - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true.
+///       then `U(P, p)` is false.
+///     - Otherwise, `P` must be empty, so `U(P, p)` is true.
 ///
 /// Inductive step. (`n > 0`, i.e., whether there's at least one column
 ///                  [which may then be expanded into further columns later])
-///     We're going to match on the new pattern, `p_{m + 1}`.
-///         - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern.
-///           Thus, the usefulness of `p_{m + 1}` can be reduced to whether it is useful when
-///           we ignore all the patterns in `P` that involve other constructors. This is where
-///           `S(c, P)` comes in:
-///           `U(P, p_{m + 1}) := U(S(c, P), S(c, p_{m + 1}))`
+///     We're going to match on the top of the new pattern-stack, `p_1`.
+///         - If `p_1 == c(r_1, .., r_a)`, i.e. we have a constructor pattern.
+///           Then, the usefulness of `p_1` can be reduced to whether it is useful when
+///           we ignore all the patterns in the first column of `P` that involve other constructors.
+///           This is where `S(c, P)` comes in:
+///           `U(P, p) := U(S(c, P), S(c, p))`
 ///           This special case is handled in `is_useful_specialized`.
-///         - If `p_{m + 1} == _`, then we have two more cases:
-///             + All the constructors of the first component of the type exist within
-///               all the rows (after having expanded OR-patterns). In this case:
-///               `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))`
-///               I.e., the pattern `p_{m + 1}` is only useful when all the constructors are
-///               present *if* its later components are useful for the respective constructors
-///               covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`).
-///             + Some constructors are not present in the existing rows (after having expanded
-///               OR-patterns). However, there might be wildcard patterns (`_`) present. Thus, we
-///               are only really concerned with the other patterns leading with wildcards. This is
-///               where `D` comes in:
-///               `U(P, p_{m + 1}) := U(D(P), p_({m + 1},2), ..,  p_({m + 1},n))`
-///         - If `p_{m + 1} == r_1 | r_2`, then the usefulness depends on each separately:
-///           `U(P, p_{m + 1}) := U(P, (r_1, p_({m + 1},2), .., p_({m + 1},n)))
-///                            || U(P, (r_2, p_({m + 1},2), .., p_({m + 1},n)))`
+///
+///           For example, if `P` is:
+///           [
+///               [Some(true), _],
+///               [None, 0],
+///           ]
+///           and `p` is [Some(false), 0], then we don't care about row 2 since we know `p` only
+///           matches values that row 2 doesn't. For row 1 however, we need to dig into the
+///           arguments of `Some` to know whether some new value is covered. So we compute
+///           `U([[true, _]], [false, 0])`.
+///
+///         - If `p_1 == _`, then we look at the list of constructors that appear in the first
+///               component of the rows of `P`:
+///             + If there are some constructors that aren't present, then we might think that the
+///               wildcard `_` is useful, since it covers those constructors that weren't covered
+///               before.
+///               That's almost correct, but only works if there were no wildcards in those first
+///               components. So we need to check that `p` is useful with respect to the rows that
+///               start with a wildcard, if there are any. This is where `D` comes in:
+///               `U(P, p) := U(D(P), D(p))`
+///
+///               For example, if `P` is:
+///               [
+///                   [_, true, _],
+///                   [None, false, 1],
+///               ]
+///               and `p` is [_, false, _], the `Some` constructor doesn't appear in `P`. So if we
+///               only had row 2, we'd know that `p` is useful. However row 1 starts with a
+///               wildcard, so we need to check whether `U([[true, _]], [false, 1])`.
+///
+///             + Otherwise, all possible constructors (for the relevant type) are present. In this
+///               case we must check whether the wildcard pattern covers any unmatched value. For
+///               that, we can think of the `_` pattern as a big OR-pattern that covers all
+///               possible constructors. For `Option`, that would mean `_ = None | Some(_)` for
+///               example. The wildcard pattern is useful in this case if it is useful when
+///               specialized to one of the possible constructors. So we compute:
+///               `U(P, p) := ∃(k ϵ constructors) U(S(k, P), S(k, p))`
+///
+///               For example, if `P` is:
+///               [
+///                   [Some(true), _],
+///                   [None, false],
+///               ]
+///               and `p` is [_, false], both `None` and `Some` constructors appear in the first
+///               components of `P`. We will therefore try popping both constructors in turn: we
+///               compute U([[true, _]], [_, false]) for the `Some` constructor, and U([[false]],
+///               [false]) for the `None` constructor. The first case returns true, so we know that
+///               `p` is useful for `P`. Indeed, it matches `[Some(false), _]` that wasn't matched
+///               before.
+///
+///         - If `p_1 == r_1 | r_2`, then the usefulness depends on each `r_i` separately:
+///           `U(P, p) := U(P, (r_1, p_2, .., p_n))
+///                    || U(P, (r_2, p_2, .., p_n))`
 ///
 /// Modifications to the algorithm
 /// ------------------------------
 /// The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
 /// example uninhabited types and variable-length slice patterns. These are drawn attention to
-/// throughout the code below. I'll make a quick note here about how exhaustive integer matching
-/// is accounted for, though.
+/// throughout the code below. I'll make a quick note here about how exhaustive integer matching is
+/// accounted for, though.
 ///
 /// Exhaustive integer matching
 /// ---------------------------
 ///       invalid, because we want a disjunction over every *integer* in each range, not just a
 ///       disjunction over every range. This is a bit more tricky to deal with: essentially we need
 ///       to form equivalence classes of subranges of the constructor range for which the behaviour
-///       of the matrix `P` and new pattern `p_{m + 1}` are the same. This is described in more
+///       of the matrix `P` and new pattern `p` are the same. This is described in more
 ///       detail in `split_grouped_constructors`.
 ///     + If some constructors are missing from the matrix, it turns out we don't need to do
 ///       anything special (because we know none of the integers are actually wildcards: i.e., we
 use rustc::lint;
 use rustc::mir::interpret::{truncate, AllocId, ConstValue, Pointer, Scalar};
 use rustc::mir::Field;
+use rustc::util::captures::Captures;
 use rustc::util::common::ErrorReported;
 
 use syntax::attr::{SignedInt, UnsignedInt};
@@ -276,18 +343,119 @@ fn is_wildcard(&self) -> bool {
     }
 }
 
-/// A 2D matrix. Nx1 matrices are very common, which is why `SmallVec[_; 2]`
-/// works well for each row.
-pub struct Matrix<'p, 'tcx>(Vec<SmallVec<[&'p Pat<'tcx>; 2]>>);
+/// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
+/// works well.
+#[derive(Debug, Clone)]
+pub struct PatStack<'p, 'tcx>(SmallVec<[&'p Pat<'tcx>; 2]>);
+
+impl<'p, 'tcx> PatStack<'p, 'tcx> {
+    pub fn from_pattern(pat: &'p Pat<'tcx>) -> Self {
+        PatStack(smallvec![pat])
+    }
+
+    fn from_vec(vec: SmallVec<[&'p Pat<'tcx>; 2]>) -> Self {
+        PatStack(vec)
+    }
+
+    fn from_slice(s: &[&'p Pat<'tcx>]) -> Self {
+        PatStack(SmallVec::from_slice(s))
+    }
+
+    fn is_empty(&self) -> bool {
+        self.0.is_empty()
+    }
+
+    fn len(&self) -> usize {
+        self.0.len()
+    }
+
+    fn head(&self) -> &'p Pat<'tcx> {
+        self.0[0]
+    }
+
+    fn to_tail(&self) -> Self {
+        PatStack::from_slice(&self.0[1..])
+    }
+
+    fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> {
+        self.0.iter().map(|p| *p)
+    }
+
+    /// This computes `D(self)`. See top of the file for explanations.
+    fn specialize_wildcard(&self) -> Option<Self> {
+        if self.head().is_wildcard() { Some(self.to_tail()) } else { None }
+    }
+
+    /// This computes `S(constructor, self)`. See top of the file for explanations.
+    fn specialize_constructor<'a, 'q>(
+        &self,
+        cx: &mut MatchCheckCtxt<'a, 'tcx>,
+        constructor: &Constructor<'tcx>,
+        wild_patterns: &[&'q Pat<'tcx>],
+    ) -> Option<PatStack<'q, 'tcx>>
+    where
+        'a: 'q,
+        'p: 'q,
+    {
+        specialize(cx, self, constructor, wild_patterns)
+    }
+}
+
+impl<'p, 'tcx> Default for PatStack<'p, 'tcx> {
+    fn default() -> Self {
+        PatStack(smallvec![])
+    }
+}
+
+impl<'p, 'tcx> FromIterator<&'p Pat<'tcx>> for PatStack<'p, 'tcx> {
+    fn from_iter<T>(iter: T) -> Self
+    where
+        T: IntoIterator<Item = &'p Pat<'tcx>>,
+    {
+        PatStack(iter.into_iter().collect())
+    }
+}
+
+/// A 2D matrix.
+pub struct Matrix<'p, 'tcx>(Vec<PatStack<'p, 'tcx>>);
 
 impl<'p, 'tcx> Matrix<'p, 'tcx> {
     pub fn empty() -> Self {
         Matrix(vec![])
     }
 
-    pub fn push(&mut self, row: SmallVec<[&'p Pat<'tcx>; 2]>) {
+    pub fn push(&mut self, row: PatStack<'p, 'tcx>) {
         self.0.push(row)
     }
+
+    /// Iterate over the first component of each row
+    fn heads<'a>(&'a self) -> impl Iterator<Item = &'a Pat<'tcx>> + Captures<'p> {
+        self.0.iter().map(|r| r.head())
+    }
+
+    /// This computes `D(self)`. See top of the file for explanations.
+    fn specialize_wildcard(&self) -> Self {
+        self.0.iter().filter_map(|r| r.specialize_wildcard()).collect()
+    }
+
+    /// This computes `S(constructor, self)`. See top of the file for explanations.
+    fn specialize_constructor<'a, 'q>(
+        &self,
+        cx: &mut MatchCheckCtxt<'a, 'tcx>,
+        constructor: &Constructor<'tcx>,
+        wild_patterns: &[&'q Pat<'tcx>],
+    ) -> Matrix<'q, 'tcx>
+    where
+        'a: 'q,
+        'p: 'q,
+    {
+        Matrix(
+            self.0
+                .iter()
+                .filter_map(|r| r.specialize_constructor(cx, constructor, wild_patterns))
+                .collect(),
+        )
+    }
 }
 
 /// Pretty-printer for matrices of patterns, example:
@@ -333,10 +501,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     }
 }
 
-impl<'p, 'tcx> FromIterator<SmallVec<[&'p Pat<'tcx>; 2]>> for Matrix<'p, 'tcx> {
+impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> {
     fn from_iter<T>(iter: T) -> Self
     where
-        T: IntoIterator<Item = SmallVec<[&'p Pat<'tcx>; 2]>>,
+        T: IntoIterator<Item = PatStack<'p, 'tcx>>,
     {
         Matrix(iter.into_iter().collect())
     }
@@ -473,6 +641,100 @@ fn display(&self, tcx: TyCtxt<'tcx>) -> String {
             _ => bug!("bad constructor being displayed: `{:?}", self),
         }
     }
+
+    fn wildcard_subpatterns<'a>(
+        &self,
+        cx: &MatchCheckCtxt<'a, 'tcx>,
+        ty: Ty<'tcx>,
+    ) -> Vec<Pat<'tcx>> {
+        constructor_sub_pattern_tys(cx, self, ty)
+            .into_iter()
+            .map(|ty| Pat { ty, span: DUMMY_SP, kind: box PatKind::Wild })
+            .collect()
+    }
+
+    /// This computes the arity of a constructor. The arity of a constructor
+    /// is how many subpattern patterns of that constructor should be expanded to.
+    ///
+    /// For instance, a tuple pattern `(_, 42, Some([]))` has the arity of 3.
+    /// A struct pattern's arity is the number of fields it contains, etc.
+    fn arity<'a>(&self, cx: &MatchCheckCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> u64 {
+        debug!("Constructor::arity({:#?}, {:?})", self, ty);
+        match ty.kind {
+            ty::Tuple(ref fs) => fs.len() as u64,
+            ty::Slice(..) | ty::Array(..) => match *self {
+                Slice(length) => length,
+                ConstantValue(..) => 0,
+                _ => bug!("bad slice pattern {:?} {:?}", self, ty),
+            },
+            ty::Ref(..) => 1,
+            ty::Adt(adt, _) => {
+                adt.variants[self.variant_index_for_adt(cx, adt)].fields.len() as u64
+            }
+            _ => 0,
+        }
+    }
+
+    /// Apply a constructor to a list of patterns, yielding a new pattern. `pats`
+    /// must have as many elements as this constructor's arity.
+    ///
+    /// Examples:
+    /// self: Single
+    /// ty: tuple of 3 elements
+    /// pats: [10, 20, _]           => (10, 20, _)
+    ///
+    /// self: Option::Some
+    /// ty: Option<bool>
+    /// pats: [false]  => Some(false)
+    fn apply<'a>(
+        &self,
+        cx: &MatchCheckCtxt<'a, 'tcx>,
+        ty: Ty<'tcx>,
+        pats: impl IntoIterator<Item = Pat<'tcx>>,
+    ) -> Pat<'tcx> {
+        let mut pats = pats.into_iter();
+        let pat = match ty.kind {
+            ty::Adt(..) | ty::Tuple(..) => {
+                let pats = pats
+                    .enumerate()
+                    .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
+                    .collect();
+
+                if let ty::Adt(adt, substs) = ty.kind {
+                    if adt.is_enum() {
+                        PatKind::Variant {
+                            adt_def: adt,
+                            substs,
+                            variant_index: self.variant_index_for_adt(cx, adt),
+                            subpatterns: pats,
+                        }
+                    } else {
+                        PatKind::Leaf { subpatterns: pats }
+                    }
+                } else {
+                    PatKind::Leaf { subpatterns: pats }
+                }
+            }
+
+            ty::Ref(..) => PatKind::Deref { subpattern: pats.nth(0).unwrap() },
+
+            ty::Slice(_) | ty::Array(..) => {
+                PatKind::Slice { prefix: pats.collect(), slice: None, suffix: vec![] }
+            }
+
+            _ => match *self {
+                ConstantValue(value, _) => PatKind::Constant { value },
+                ConstantRange(lo, hi, ty, end, _) => PatKind::Range(PatRange {
+                    lo: ty::Const::from_bits(cx.tcx, lo, ty::ParamEnv::empty().and(ty)),
+                    hi: ty::Const::from_bits(cx.tcx, hi, ty::ParamEnv::empty().and(ty)),
+                    end,
+                }),
+                _ => PatKind::Wild,
+            },
+        };
+
+        Pat { ty, span: DUMMY_SP, kind: Box::new(pat) }
+    }
 }
 
 #[derive(Clone, Debug)]
@@ -551,12 +813,7 @@ fn push_wild_constructor<'a>(
         ctor: &Constructor<'tcx>,
         ty: Ty<'tcx>,
     ) -> Self {
-        let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
-        self.0.extend(sub_pattern_tys.into_iter().map(|ty| Pat {
-            ty,
-            span: DUMMY_SP,
-            kind: box PatKind::Wild,
-        }));
+        self.0.extend(ctor.wildcard_subpatterns(cx, ty));
         self.apply_constructor(cx, ctor, ty)
     }
 
@@ -579,53 +836,14 @@ fn apply_constructor<'a>(
         ctor: &Constructor<'tcx>,
         ty: Ty<'tcx>,
     ) -> Self {
-        let arity = constructor_arity(cx, ctor, ty);
+        let arity = ctor.arity(cx, ty);
         let pat = {
             let len = self.0.len() as u64;
-            let mut pats = self.0.drain((len - arity) as usize..).rev();
-
-            match ty.kind {
-                ty::Adt(..) | ty::Tuple(..) => {
-                    let pats = pats
-                        .enumerate()
-                        .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
-                        .collect();
-
-                    if let ty::Adt(adt, substs) = ty.kind {
-                        if adt.is_enum() {
-                            PatKind::Variant {
-                                adt_def: adt,
-                                substs,
-                                variant_index: ctor.variant_index_for_adt(cx, adt),
-                                subpatterns: pats,
-                            }
-                        } else {
-                            PatKind::Leaf { subpatterns: pats }
-                        }
-                    } else {
-                        PatKind::Leaf { subpatterns: pats }
-                    }
-                }
-
-                ty::Ref(..) => PatKind::Deref { subpattern: pats.nth(0).unwrap() },
-
-                ty::Slice(_) | ty::Array(..) => {
-                    PatKind::Slice { prefix: pats.collect(), slice: None, suffix: vec![] }
-                }
-
-                _ => match *ctor {
-                    ConstantValue(value, _) => PatKind::Constant { value },
-                    ConstantRange(lo, hi, ty, end, _) => PatKind::Range(PatRange {
-                        lo: ty::Const::from_bits(cx.tcx, lo, ty::ParamEnv::empty().and(ty)),
-                        hi: ty::Const::from_bits(cx.tcx, hi, ty::ParamEnv::empty().and(ty)),
-                        end,
-                    }),
-                    _ => PatKind::Wild,
-                },
-            }
+            let pats = self.0.drain((len - arity) as usize..).rev();
+            ctor.apply(cx, ty, pats)
         };
 
-        self.0.push(Pat { ty, span: DUMMY_SP, kind: Box::new(pat) });
+        self.0.push(pat);
 
         self
     }
@@ -1059,41 +1277,17 @@ fn suspicious_intersection(&self, other: &Self) -> bool {
     }
 }
 
-// A request for missing constructor data in terms of either:
-// - whether or not there any missing constructors; or
-// - the actual set of missing constructors.
-#[derive(PartialEq)]
-enum MissingCtorsInfo {
-    Emptiness,
-    Ctors,
-}
-
-// Used by `compute_missing_ctors`.
-#[derive(Debug, PartialEq)]
-enum MissingCtors<'tcx> {
-    Empty,
-    NonEmpty,
-
-    // Note that the Vec can be empty.
-    Ctors(Vec<Constructor<'tcx>>),
-}
-
-// When `info` is `MissingCtorsInfo::Ctors`, compute a set of constructors
-// equivalent to `all_ctors \ used_ctors`. When `info` is
-// `MissingCtorsInfo::Emptiness`, just determines if that set is empty or not.
-// (The split logic gives a performance win, because we always need to know if
-// the set is empty, but we rarely need the full set, and it can be expensive
-// to compute the full set.)
-fn compute_missing_ctors<'tcx>(
-    info: MissingCtorsInfo,
+type MissingConstructors<'a, 'tcx, F> =
+    std::iter::FlatMap<std::slice::Iter<'a, Constructor<'tcx>>, Vec<Constructor<'tcx>>, F>;
+// Compute a set of constructors equivalent to `all_ctors \ used_ctors`. This
+// returns an iterator, so that we only construct the whole set if needed.
+fn compute_missing_ctors<'a, 'tcx>(
     tcx: TyCtxt<'tcx>,
     param_env: ty::ParamEnv<'tcx>,
-    all_ctors: &Vec<Constructor<'tcx>>,
-    used_ctors: &Vec<Constructor<'tcx>>,
-) -> MissingCtors<'tcx> {
-    let mut missing_ctors = vec![];
-
-    for req_ctor in all_ctors {
+    all_ctors: &'a Vec<Constructor<'tcx>>,
+    used_ctors: &'a Vec<Constructor<'tcx>>,
+) -> MissingConstructors<'a, 'tcx, impl FnMut(&'a Constructor<'tcx>) -> Vec<Constructor<'tcx>>> {
+    all_ctors.iter().flat_map(move |req_ctor| {
         let mut refined_ctors = vec![req_ctor.clone()];
         for used_ctor in used_ctors {
             if used_ctor == req_ctor {
@@ -1107,32 +1301,19 @@ fn compute_missing_ctors<'tcx>(
             }
 
             // If the constructor patterns that have been considered so far
-            // already cover the entire range of values, then we the
+            // already cover the entire range of values, then we know the
             // constructor is not missing, and we can move on to the next one.
             if refined_ctors.is_empty() {
                 break;
             }
         }
+
         // If a constructor has not been matched, then it is missing.
         // We add `refined_ctors` instead of `req_ctor`, because then we can
         // provide more detailed error information about precisely which
         // ranges have been omitted.
-        if info == MissingCtorsInfo::Emptiness {
-            if !refined_ctors.is_empty() {
-                // The set is non-empty; return early.
-                return MissingCtors::NonEmpty;
-            }
-        } else {
-            missing_ctors.extend(refined_ctors);
-        }
-    }
-
-    if info == MissingCtorsInfo::Emptiness {
-        // If we reached here, the set is empty.
-        MissingCtors::Empty
-    } else {
-        MissingCtors::Ctors(missing_ctors)
-    }
+        refined_ctors
+    })
 }
 
 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html.
@@ -1160,7 +1341,7 @@ fn compute_missing_ctors<'tcx>(
 pub fn is_useful<'p, 'a, 'tcx>(
     cx: &mut MatchCheckCtxt<'a, 'tcx>,
     matrix: &Matrix<'p, 'tcx>,
-    v: &[&Pat<'tcx>],
+    v: &PatStack<'_, 'tcx>,
     witness: WitnessPreference,
     hir_id: HirId,
 ) -> Usefulness<'tcx> {
@@ -1185,11 +1366,11 @@ pub fn is_useful<'p, 'a, 'tcx>(
 
     assert!(rows.iter().all(|r| r.len() == v.len()));
 
-    let (ty, span) = rows
-        .iter()
-        .map(|r| (r[0].ty, r[0].span))
+    let (ty, span) = matrix
+        .heads()
+        .map(|r| (r.ty, r.span))
         .find(|(ty, _)| !ty.references_error())
-        .unwrap_or((v[0].ty, v[0].span));
+        .unwrap_or((v.head().ty, v.head().span));
     let pcx = PatCtxt {
         // TyErr is used to represent the type of wildcard patterns matching
         // against inaccessible (private) fields of structs, so that we won't
@@ -1211,13 +1392,13 @@ pub fn is_useful<'p, 'a, 'tcx>(
         // introducing uninhabited patterns for inaccessible fields. We
         // need to figure out how to model that.
         ty,
-        max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0]))),
+        max_slice_length: max_slice_length(cx, matrix.heads().chain(Some(v.head()))),
         span,
     };
 
-    debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
+    debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v.head());
 
-    if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
+    if let Some(constructors) = pat_constructors(cx, v.head(), pcx) {
         debug!("is_useful - expanding constructors: {:#?}", constructors);
         split_grouped_constructors(
             cx.tcx,
@@ -1235,10 +1416,8 @@ pub fn is_useful<'p, 'a, 'tcx>(
     } else {
         debug!("is_useful - expanding wildcard");
 
-        let used_ctors: Vec<Constructor<'_>> = rows
-            .iter()
-            .flat_map(|row| pat_constructors(cx, row[0], pcx).unwrap_or(vec![]))
-            .collect();
+        let used_ctors: Vec<Constructor<'_>> =
+            matrix.heads().flat_map(|p| pat_constructors(cx, p, pcx).unwrap_or(vec![])).collect();
         debug!("used_ctors = {:#?}", used_ctors);
         // `all_ctors` are all the constructors for the given type, which
         // should all be represented (or caught with the wild pattern `_`).
@@ -1265,22 +1444,19 @@ pub fn is_useful<'p, 'a, 'tcx>(
         // needed for that case.
 
         // Missing constructors are those that are not matched by any
-        // non-wildcard patterns in the current column. We always determine if
-        // the set is empty, but we only fully construct them on-demand,
-        // because they're rarely used and can be big.
-        let cheap_missing_ctors = compute_missing_ctors(
-            MissingCtorsInfo::Emptiness,
-            cx.tcx,
-            cx.param_env,
-            &all_ctors,
-            &used_ctors,
-        );
+        // non-wildcard patterns in the current column. To determine if
+        // the set is empty, we can check that `.peek().is_none()`, so
+        // we only fully construct them on-demand, because they're rarely used and can be big.
+        let mut missing_ctors =
+            compute_missing_ctors(cx.tcx, cx.param_env, &all_ctors, &used_ctors).peekable();
 
         let is_privately_empty = all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
         let is_declared_nonexhaustive = cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
         debug!(
-            "cheap_missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
-            cheap_missing_ctors, is_privately_empty, is_declared_nonexhaustive
+            "missing_ctors.empty()={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
+            missing_ctors.peek().is_none(),
+            is_privately_empty,
+            is_declared_nonexhaustive
         );
 
         // For privately empty and non-exhaustive enums, we work as if there were an "extra"
@@ -1289,7 +1465,8 @@ pub fn is_useful<'p, 'a, 'tcx>(
             || is_declared_nonexhaustive
             || (pcx.ty.is_ptr_sized_integral() && !cx.tcx.features().precise_pointer_size_matching);
 
-        if cheap_missing_ctors == MissingCtors::Empty && !is_non_exhaustive {
+        if missing_ctors.peek().is_none() && !is_non_exhaustive {
+            drop(missing_ctors); // It was borrowing `all_ctors`, which we want to move.
             split_grouped_constructors(
                 cx.tcx,
                 cx.param_env,
@@ -1304,13 +1481,9 @@ pub fn is_useful<'p, 'a, 'tcx>(
             .find(|result| result.is_useful())
             .unwrap_or(NotUseful)
         } else {
-            let matrix = rows
-                .iter()
-                .filter_map(|r| {
-                    if r[0].is_wildcard() { Some(SmallVec::from_slice(&r[1..])) } else { None }
-                })
-                .collect();
-            match is_useful(cx, &matrix, &v[1..], witness, hir_id) {
+            let matrix = matrix.specialize_wildcard();
+            let v = v.to_tail();
+            match is_useful(cx, &matrix, &v, witness, hir_id) {
                 UsefulWithWitness(pats) => {
                     let cx = &*cx;
                     // In this case, there's at least one "free"
@@ -1371,28 +1544,18 @@ pub fn is_useful<'p, 'a, 'tcx>(
                             })
                             .collect()
                     } else {
-                        let expensive_missing_ctors = compute_missing_ctors(
-                            MissingCtorsInfo::Ctors,
-                            cx.tcx,
-                            cx.param_env,
-                            &all_ctors,
-                            &used_ctors,
-                        );
-                        if let MissingCtors::Ctors(missing_ctors) = expensive_missing_ctors {
-                            pats.into_iter()
-                                .flat_map(|witness| {
-                                    missing_ctors.iter().map(move |ctor| {
-                                        // Extends the witness with a "wild" version of this
-                                        // constructor, that matches everything that can be built with
-                                        // it. For example, if `ctor` is a `Constructor::Variant` for
-                                        // `Option::Some`, this pushes the witness for `Some(_)`.
-                                        witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
-                                    })
+                        let missing_ctors: Vec<_> = missing_ctors.collect();
+                        pats.into_iter()
+                            .flat_map(|witness| {
+                                missing_ctors.iter().map(move |ctor| {
+                                    // Extends the witness with a "wild" version of this
+                                    // constructor, that matches everything that can be built with
+                                    // it. For example, if `ctor` is a `Constructor::Variant` for
+                                    // `Option::Some`, this pushes the witness for `Some(_)`.
+                                    witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
                                 })
-                                .collect()
-                        } else {
-                            bug!("cheap missing ctors")
-                        }
+                            })
+                            .collect()
                     };
                     UsefulWithWitness(new_witnesses)
                 }
@@ -1406,21 +1569,19 @@ pub fn is_useful<'p, 'a, 'tcx>(
 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
 fn is_useful_specialized<'p, 'a, 'tcx>(
     cx: &mut MatchCheckCtxt<'a, 'tcx>,
-    &Matrix(ref m): &Matrix<'p, 'tcx>,
-    v: &[&Pat<'tcx>],
+    matrix: &Matrix<'p, 'tcx>,
+    v: &PatStack<'_, 'tcx>,
     ctor: Constructor<'tcx>,
     lty: Ty<'tcx>,
     witness: WitnessPreference,
     hir_id: HirId,
 ) -> Usefulness<'tcx> {
     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
-    let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
-    let wild_patterns_owned: Vec<_> =
-        sub_pat_tys.iter().map(|ty| Pat { ty, span: DUMMY_SP, kind: box PatKind::Wild }).collect();
+
+    let wild_patterns_owned = ctor.wildcard_subpatterns(cx, lty);
     let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
-    let matrix =
-        Matrix(m.iter().filter_map(|r| specialize(cx, &r, &ctor, &wild_patterns)).collect());
-    match specialize(cx, v, &ctor, &wild_patterns) {
+    let matrix = matrix.specialize_constructor(cx, &ctor, &wild_patterns);
+    match v.specialize_constructor(cx, &ctor, &wild_patterns) {
         Some(v) => match is_useful(cx, &matrix, &v, witness, hir_id) {
             UsefulWithWitness(witnesses) => UsefulWithWitness(
                 witnesses
@@ -1480,26 +1641,6 @@ fn pat_constructors<'tcx>(
     }
 }
 
-/// This computes the arity of a constructor. The arity of a constructor
-/// is how many subpattern patterns of that constructor should be expanded to.
-///
-/// For instance, a tuple pattern `(_, 42, Some([]))` has the arity of 3.
-/// A struct pattern's arity is the number of fields it contains, etc.
-fn constructor_arity(cx: &MatchCheckCtxt<'a, 'tcx>, ctor: &Constructor<'tcx>, ty: Ty<'tcx>) -> u64 {
-    debug!("constructor_arity({:#?}, {:?})", ctor, ty);
-    match ty.kind {
-        ty::Tuple(ref fs) => fs.len() as u64,
-        ty::Slice(..) | ty::Array(..) => match *ctor {
-            Slice(length) => length,
-            ConstantValue(..) => 0,
-            _ => bug!("bad slice pattern {:?} {:?}", ctor, ty),
-        },
-        ty::Ref(..) => 1,
-        ty::Adt(adt, _) => adt.variants[ctor.variant_index_for_adt(cx, adt)].fields.len() as u64,
-        _ => 0,
-    }
-}
-
 /// This computes the types of the sub patterns that a constructor should be
 /// expanded to.
 ///
@@ -1676,7 +1817,7 @@ fn split_grouped_constructors<'p, 'tcx>(
     tcx: TyCtxt<'tcx>,
     param_env: ty::ParamEnv<'tcx>,
     ctors: Vec<Constructor<'tcx>>,
-    &Matrix(ref m): &Matrix<'p, 'tcx>,
+    matrix: &Matrix<'p, 'tcx>,
     ty: Ty<'tcx>,
     span: Span,
     hir_id: Option<HirId>,
@@ -1718,10 +1859,11 @@ fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
                 let mut overlaps = vec![];
                 // `borders` is the set of borders between equivalence classes: each equivalence
                 // class lies between 2 borders.
-                let row_borders = m
+                let row_borders = matrix
+                    .0
                     .iter()
                     .flat_map(|row| {
-                        IntRange::from_pat(tcx, param_env, row[0]).map(|r| (r, row.len()))
+                        IntRange::from_pat(tcx, param_env, row.head()).map(|r| (r, row.len()))
                     })
                     .flat_map(|(range, row_len)| {
                         let intersection = ctor_range.intersection(&range);
@@ -1867,7 +2009,7 @@ fn patterns_for_variant<'p, 'a: 'p, 'tcx>(
     subpatterns: &'p [FieldPat<'tcx>],
     wild_patterns: &[&'p Pat<'tcx>],
     is_non_exhaustive: bool,
-) -> SmallVec<[&'p Pat<'tcx>; 2]> {
+) -> PatStack<'p, 'tcx> {
     let mut result = SmallVec::from_slice(wild_patterns);
 
     for subpat in subpatterns {
@@ -1877,7 +2019,7 @@ fn patterns_for_variant<'p, 'a: 'p, 'tcx>(
     }
 
     debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
-    result
+    PatStack::from_vec(result)
 }
 
 /// This is the main specialization step. It expands the first pattern in the given row
@@ -1888,20 +2030,20 @@ fn patterns_for_variant<'p, 'a: 'p, 'tcx>(
 /// different patterns.
 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
 /// fields filled with wild patterns.
-fn specialize<'p, 'a: 'p, 'tcx>(
+fn specialize<'p, 'a: 'p, 'q: 'p, 'tcx>(
     cx: &mut MatchCheckCtxt<'a, 'tcx>,
-    r: &[&'p Pat<'tcx>],
+    r: &PatStack<'q, 'tcx>,
     constructor: &Constructor<'tcx>,
     wild_patterns: &[&'p Pat<'tcx>],
-) -> Option<SmallVec<[&'p Pat<'tcx>; 2]>> {
-    let pat = &r[0];
+) -> Option<PatStack<'p, 'tcx>> {
+    let pat = r.head();
 
-    let head = match *pat.kind {
+    let new_head = match *pat.kind {
         PatKind::AscribeUserType { ref subpattern, .. } => {
-            specialize(cx, ::std::slice::from_ref(&subpattern), constructor, wild_patterns)
+            specialize(cx, &PatStack::from_pattern(subpattern), constructor, wild_patterns)
         }
 
-        PatKind::Binding { .. } | PatKind::Wild => Some(SmallVec::from_slice(wild_patterns)),
+        PatKind::Binding { .. } | PatKind::Wild => Some(PatStack::from_slice(wild_patterns)),
 
         PatKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
             let ref variant = adt_def.variants[variant_index];
@@ -1915,7 +2057,7 @@ fn specialize<'p, 'a: 'p, 'tcx>(
             Some(patterns_for_variant(cx, subpatterns, wild_patterns, false))
         }
 
-        PatKind::Deref { ref subpattern } => Some(smallvec![subpattern]),
+        PatKind::Deref { ref subpattern } => Some(PatStack::from_pattern(subpattern)),
 
         PatKind::Constant { value } if constructor.is_slice() => {
             // We extract an `Option` for the pointer because slices of zero
@@ -1985,7 +2127,7 @@ fn specialize<'p, 'a: 'p, 'tcx>(
                         let (pat_lo, pat_hi) = pat.range.into_inner();
                         let (ctor_lo, ctor_hi) = ctor.range.into_inner();
                         assert!(pat_lo <= ctor_lo && ctor_hi <= pat_hi);
-                        smallvec![]
+                        PatStack::default()
                     }),
                     _ => None,
                 }
@@ -1996,7 +2138,7 @@ fn specialize<'p, 'a: 'p, 'tcx>(
                 // range so intersection actually devolves into being covered
                 // by the pattern.
                 match constructor_covered_by_range(cx.tcx, cx.param_env, constructor, pat) {
-                    Ok(true) => Some(smallvec![]),
+                    Ok(true) => Some(PatStack::default()),
                     Ok(false) | Err(ErrorReported) => None,
                 }
             }
@@ -2038,7 +2180,7 @@ fn specialize<'p, 'a: 'p, 'tcx>(
                     suffix,
                     cx.param_env,
                 ) {
-                    Ok(true) => Some(smallvec![]),
+                    Ok(true) => Some(PatStack::default()),
                     Ok(false) => None,
                     Err(ErrorReported) => None,
                 }
@@ -2050,10 +2192,11 @@ fn specialize<'p, 'a: 'p, 'tcx>(
             bug!("support for or-patterns has not been fully implemented yet.");
         }
     };
-    debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
+    debug!("specialize({:#?}, {:#?}) = {:#?}", r.head(), wild_patterns, new_head);
 
-    head.map(|mut head| {
-        head.extend_from_slice(&r[1..]);
-        head
+    new_head.map(|head| {
+        let mut head = head.0;
+        head.extend_from_slice(&r.0[1..]);
+        PatStack::from_vec(head)
     })
 }