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