1//! As explained in [`crate::usefulness`], values and patterns are made from constructors applied to
2//! fields. This file defines a `Constructor` enum and various operations to manipulate them.
3//!
4//! There are two important bits of core logic in this file: constructor inclusion and constructor
5//! splitting. Constructor inclusion, i.e. whether a constructor is included in/covered by another,
6//! is straightforward and defined in [`Constructor::is_covered_by`].
7//!
8//! Constructor splitting is mentioned in [`crate::usefulness`] but not detailed. We describe it
9//! precisely here.
10//!
11//!
12//!
13//! # Constructor grouping and splitting
14//!
15//! As explained in the corresponding section in [`crate::usefulness`], to make usefulness tractable
16//! we need to group together constructors that have the same effect when they are used to
17//! specialize the matrix.
18//!
19//! Example:
20//! ```compile_fail,E0004
21//! match (0, false) {
22//! (0 ..=100, true) => {}
23//! (50..=150, false) => {}
24//! (0 ..=200, _) => {}
25//! }
26//! ```
27//!
28//! In this example we can restrict specialization to 5 cases: `0..50`, `50..=100`, `101..=150`,
29//! `151..=200` and `200..`.
30//!
31//! In [`crate::usefulness`], we had said that `specialize` only takes value-only constructors. We
32//! now relax this restriction: we allow `specialize` to take constructors like `0..50` as long as
33//! we're careful to only do that with constructors that make sense. For example, `specialize(0..50,
34//! (0..=100, true))` is sensible, but `specialize(50..=200, (0..=100, true))` is not.
35//!
36//! Constructor splitting looks at the constructors in the first column of the matrix and constructs
37//! such a sensible set of constructors. Formally, we want to find a smallest disjoint set of
38//! constructors:
39//! - Whose union covers the whole type, and
40//! - That have no non-trivial intersection with any of the constructors in the column (i.e. they're
41//! each either disjoint with or covered by any given column constructor).
42//!
43//! We compute this in two steps: first [`PatCx::ctors_for_ty`] determines the
44//! set of all possible constructors for the type. Then [`ConstructorSet::split`] looks at the
45//! column of constructors and splits the set into groups accordingly. The precise invariants of
46//! [`ConstructorSet::split`] is described in [`SplitConstructorSet`].
47//!
48//! Constructor splitting has two interesting special cases: integer range splitting (see
49//! [`IntRange::split`]) and slice splitting (see [`Slice::split`]).
50//!
51//!
52//!
53//! # The `Missing` constructor
54//!
55//! We detail a special case of constructor splitting that is a bit subtle. Take the following:
56//!
57//! ```
58//! enum Direction { North, South, East, West }
59//! # let wind = (Direction::North, 0u8);
60//! match wind {
61//! (Direction::North, 50..) => {}
62//! (_, _) => {}
63//! }
64//! ```
65//!
66//! Here we expect constructor splitting to output two cases: `North`, and "everything else". This
67//! "everything else" is represented by [`Constructor::Missing`]. Unlike other constructors, it's a
68//! bit contextual: to know the exact list of constructors it represents we have to look at the
69//! column. In practice however we don't need to, because by construction it only matches rows that
70//! have wildcards. This is how this constructor is special: the only constructor that covers it is
71//! `Wildcard`.
72//!
73//! The only place where we care about which constructors `Missing` represents is in diagnostics
74//! (see `crate::usefulness::WitnessMatrix::apply_constructor`).
75//!
76//! We choose whether to specialize with `Missing` in
77//! `crate::usefulness::compute_exhaustiveness_and_usefulness`.
78//!
79//!
80//!
81//! ## Empty types, empty constructors, and the `exhaustive_patterns` feature
82//!
83//! An empty type is a type that has no valid value, like `!`, `enum Void {}`, or `Result<!, !>`.
84//! They require careful handling.
85//!
86//! First, for soundness reasons related to the possible existence of invalid values, by default we
87//! don't treat empty types as empty. We force them to be matched with wildcards. Except if the
88//! `exhaustive_patterns` feature is turned on, in which case we do treat them as empty. And also
89//! except if the type has no constructors (like `enum Void {}` but not like `Result<!, !>`), we
90//! specifically allow `match void {}` to be exhaustive. There are additionally considerations of
91//! place validity that are handled in `crate::usefulness`. Yes this is a bit tricky.
92//!
93//! The second thing is that regardless of the above, it is always allowed to use all the
94//! constructors of a type. For example, all the following is ok:
95//!
96//! ```rust,ignore(example)
97//! # #![feature(exhaustive_patterns)]
98//! fn foo(x: Option<!>) {
99//! match x {
100//! None => {}
101//! Some(_) => {}
102//! }
103//! }
104//! fn bar(x: &[!]) -> u32 {
105//! match x {
106//! [] => 1,
107//! [_] => 2,
108//! [_, _] => 3,
109//! }
110//! }
111//! ```
112//!
113//! Moreover, take the following:
114//!
115//! ```rust
116//! # #![feature(exhaustive_patterns)]
117//! # let x = None::<!>;
118//! match x {
119//! None => {}
120//! }
121//! ```
122//!
123//! On a normal type, we would identify `Some` as missing and tell the user. If `x: Option<!>`
124//! however (and `exhaustive_patterns` is on), it's ok to omit `Some`. When listing the constructors
125//! of a type, we must therefore track which can be omitted.
126//!
127//! Let's call "empty" a constructor that matches no valid value for the type, like `Some` for the
128//! type `Option<!>`. What this all means is that `ConstructorSet` must know which constructors are
129//! empty. The difference between empty and nonempty constructors is that empty constructors need
130//! not be present for the match to be exhaustive.
131//!
132//! A final remark: empty constructors of arity 0 break specialization, we must avoid them. The
133//! reason is that if we specialize by them, nothing remains to witness the emptiness; the rest of
134//! the algorithm can't distinguish them from a nonempty constructor. The only known case where this
135//! could happen is the `[..]` pattern on `[!; N]` with `N > 0` so we must take care to not emit it.
136//!
137//! This is all handled by [`PatCx::ctors_for_ty`] and
138//! [`ConstructorSet::split`]. The invariants of [`SplitConstructorSet`] are also of interest.
139//!
140//!
141//! ## Unions
142//!
143//! Unions allow us to match a value via several overlapping representations at the same time. For
144//! example, the following is exhaustive because when seeing the value as a boolean we handled all
145//! possible cases (other cases such as `n == 3` would trigger UB).
146//!
147//! ```rust
148//! # fn main() {
149//! union U8AsBool {
150//! n: u8,
151//! b: bool,
152//! }
153//! let x = U8AsBool { n: 1 };
154//! unsafe {
155//! match x {
156//! U8AsBool { n: 2 } => {}
157//! U8AsBool { b: true } => {}
158//! U8AsBool { b: false } => {}
159//! }
160//! }
161//! # }
162//! ```
163//!
164//! Pattern-matching has no knowledge that e.g. `false as u8 == 0`, so the values we consider in the
165//! algorithm look like `U8AsBool { b: true, n: 2 }`. In other words, for the most part a union is
166//! treated like a struct with the same fields. The difference lies in how we construct witnesses of
167//! non-exhaustiveness.
168//!
169//!
170//! ## Opaque patterns
171//!
172//! Some patterns, such as constants that are not allowed to be matched structurally, cannot be
173//! inspected, which we handle with `Constructor::Opaque`. Since we know nothing of these patterns,
174//! we assume they never cover each other. In order to respect the invariants of
175//! [`SplitConstructorSet`], we give each `Opaque` constructor a unique id so we can recognize it.
176177use std::cmp::{self, Ordering, max, min};
178use std::fmt;
179use std::iter::once;
180181use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS};
182use rustc_index::IndexVec;
183use rustc_index::bit_set::{DenseBitSet, GrowableBitSet};
184use smallvec::SmallVec;
185186use self::Constructor::*;
187use self::MaybeInfiniteInt::*;
188use self::SliceKind::*;
189use crate::PatCx;
190191/// Whether we have seen a constructor in the column or not.
192#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Presence {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Presence::Unseen => "Unseen",
Presence::Seen => "Seen",
})
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Presence { }
#[automatically_derived]
impl ::core::clone::Clone for Presence {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Presence { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Presence { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Presence {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Presence { }Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Presence {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Presence {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other))
}
}Ord)]
193enum Presence {
194 Unseen,
195 Seen,
196}
197198#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RangeEnd {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RangeEnd::Included => "Included",
RangeEnd::Excluded => "Excluded",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RangeEnd { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RangeEnd { }
#[automatically_derived]
impl ::core::clone::Clone for RangeEnd {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RangeEnd { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RangeEnd {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for RangeEnd { }Eq)]
199pub enum RangeEnd {
200 Included,
201 Excluded,
202}
203204impl fmt::Displayfor RangeEnd {
205fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206f.write_str(match self {
207 RangeEnd::Included => "..=",
208 RangeEnd::Excluded => "..",
209 })
210 }
211}
212213/// A possibly infinite integer. Values are encoded such that the ordering on `u128` matches the
214/// natural order on the original type. For example, `-128i8` is encoded as `0` and `127i8` as
215/// `255`. See `signed_bias` for details.
216#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MaybeInfiniteInt {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::NegInfinity =>
::core::fmt::Formatter::write_str(f, "NegInfinity"),
Self::Finite(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Finite",
&__self_0),
Self::PosInfinity =>
::core::fmt::Formatter::write_str(f, "PosInfinity"),
}
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MaybeInfiniteInt { }
#[automatically_derived]
impl ::core::clone::Clone for MaybeInfiniteInt {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u128>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MaybeInfiniteInt { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MaybeInfiniteInt { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MaybeInfiniteInt {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Finite(__self_0), Self::Finite(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MaybeInfiniteInt {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u128>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MaybeInfiniteInt {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MaybeInfiniteInt {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
match (self, other) {
(Self::Finite(__self_0), Self::Finite(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ =>
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other)),
}
}
}Ord)]
217pub enum MaybeInfiniteInt {
218 NegInfinity,
219/// Encoded value. DO NOT CONSTRUCT BY HAND; use `new_finite_{int,uint}`.
220#[non_exhaustive]
221Finite(u128),
222 PosInfinity,
223}
224225impl MaybeInfiniteInt {
226pub fn new_finite_uint(bits: u128) -> Self {
227Finite(bits)
228 }
229pub fn new_finite_int(bits: u128, size: u64) -> Self {
230// Perform a shift if the underlying types are signed, which makes the interval arithmetic
231 // type-independent.
232let bias = 1u128 << (size - 1);
233Finite(bits ^ bias)
234 }
235236pub fn as_finite_uint(self) -> Option<u128> {
237match self {
238Finite(bits) => Some(bits),
239_ => None,
240 }
241 }
242pub fn as_finite_int(self, size: u64) -> Option<u128> {
243// We decode the shift.
244match self {
245Finite(bits) => {
246let bias = 1u128 << (size - 1);
247Some(bits ^ bias)
248 }
249_ => None,
250 }
251 }
252253/// Note: this will not turn a finite value into an infinite one or vice-versa.
254pub fn minus_one(self) -> Option<Self> {
255match self {
256Finite(n) => n.checked_sub(1).map(Finite),
257 x => Some(x),
258 }
259 }
260/// Note: this will turn `u128::MAX` into `PosInfinity`. This means `plus_one` and `minus_one`
261 /// are not strictly inverses, but that poses no problem in our use of them.
262 /// this will not turn a finite value into an infinite one or vice-versa.
263pub fn plus_one(self) -> Option<Self> {
264match self {
265Finite(n) => match n.checked_add(1) {
266Some(m) => Some(Finite(m)),
267None => Some(PosInfinity),
268 },
269 x => Some(x),
270 }
271 }
272}
273274/// An exclusive interval, used for precise integer exhaustiveness checking. `IntRange`s always
275/// store a contiguous range.
276///
277/// `IntRange` is never used to encode an empty range or a "range" that wraps around the (offset)
278/// space: i.e., `range.lo < range.hi`.
279#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IntRange { }
#[automatically_derived]
impl ::core::clone::Clone for IntRange {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<MaybeInfiniteInt>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IntRange { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for IntRange { }
#[automatically_derived]
impl ::core::cmp::PartialEq for IntRange {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.lo == other.lo && self.hi == other.hi
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IntRange {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<MaybeInfiniteInt>;
}
}Eq)]
280pub struct IntRange {
281pub lo: MaybeInfiniteInt, // Must not be `PosInfinity`.
282pub hi: MaybeInfiniteInt, // Must not be `NegInfinity`.
283}
284285impl IntRange {
286/// Best effort; will not know that e.g. `255u8..` is a singleton.
287pub fn is_singleton(&self) -> bool {
288// Since `lo` and `hi` can't be the same `Infinity` and `plus_one` never changes from finite
289 // to infinite, this correctly only detects ranges that contain exactly one `Finite(x)`.
290self.lo.plus_one() == Some(self.hi)
291 }
292293/// Construct a singleton range.
294 /// `x` must be a `Finite(_)` value.
295#[inline]
296pub fn from_singleton(x: MaybeInfiniteInt) -> IntRange {
297// `unwrap()` is ok on a finite value
298IntRange { lo: x, hi: x.plus_one().unwrap() }
299 }
300301/// Construct a range with these boundaries.
302 /// `lo` must not be `PosInfinity`. `hi` must not be `NegInfinity`.
303#[inline]
304pub fn from_range(lo: MaybeInfiniteInt, mut hi: MaybeInfiniteInt, end: RangeEnd) -> IntRange {
305if end == RangeEnd::Included {
306hi = hi.plus_one().unwrap();
307 }
308if lo >= hi {
309// This should have been caught earlier by E0030.
310{
::core::panicking::panic_fmt(format_args!("malformed range pattern: {0:?}..{1:?}",
lo, hi));
};panic!("malformed range pattern: {lo:?}..{hi:?}");
311 }
312IntRange { lo, hi }
313 }
314315#[inline]
316pub fn is_subrange(&self, other: &Self) -> bool {
317other.lo <= self.lo && self.hi <= other.hi
318 }
319320fn intersection(&self, other: &Self) -> Option<Self> {
321if self.lo < other.hi && other.lo < self.hi {
322Some(IntRange { lo: max(self.lo, other.lo), hi: min(self.hi, other.hi) })
323 } else {
324None325 }
326 }
327328/// Partition a range of integers into disjoint subranges. This does constructor splitting for
329 /// integer ranges as explained at the top of the file.
330 ///
331 /// This returns an output that covers `self`. The output is split so that the only
332 /// intersections between an output range and a column range are inclusions. No output range
333 /// straddles the boundary of one of the inputs.
334 ///
335 /// Additionally, we track for each output range whether it is covered by one of the column ranges or not.
336 ///
337 /// The following input:
338 /// ```text
339 /// (--------------------------) // `self`
340 /// (------) (----------) (-)
341 /// (------) (--------)
342 /// ```
343 /// is first intersected with `self`:
344 /// ```text
345 /// (--------------------------) // `self`
346 /// (----) (----------) (-)
347 /// (------) (--------)
348 /// ```
349 /// and then iterated over as follows:
350 /// ```text
351 /// (-(--)-(-)-(------)-)--(-)-
352 /// ```
353 /// where each sequence of dashes is an output range, and dashes outside parentheses are marked
354 /// as `Presence::Missing`.
355 ///
356 /// ## `isize`/`usize`
357 ///
358 /// Whereas a wildcard of type `i32` stands for the range `i32::MIN..=i32::MAX`, a `usize`
359 /// wildcard stands for `0..PosInfinity` and a `isize` wildcard stands for
360 /// `NegInfinity..PosInfinity`. In other words, as far as `IntRange` is concerned, there are
361 /// values before `isize::MIN` and after `usize::MAX`/`isize::MAX`.
362 /// This is to avoid e.g. `0..(u32::MAX as usize)` from being exhaustive on one architecture and
363 /// not others. This was decided in <https://github.com/rust-lang/rfcs/pull/2591>.
364 ///
365 /// These infinities affect splitting subtly: it is possible to get `NegInfinity..0` and
366 /// `usize::MAX+1..PosInfinity` in the output. Diagnostics must be careful to handle these
367 /// fictitious ranges sensibly.
368fn split(
369&self,
370 column_ranges: impl Iterator<Item = IntRange>,
371 ) -> impl Iterator<Item = (Presence, IntRange)> {
372// The boundaries of ranges in `column_ranges` intersected with `self`.
373 // We do parenthesis matching for input ranges. A boundary counts as +1 if it starts
374 // a range and -1 if it ends it. When the count is > 0 between two boundaries, we
375 // are within an input range.
376let mut boundaries: Vec<(MaybeInfiniteInt, isize)> = column_ranges377 .filter_map(|r| self.intersection(&r))
378 .flat_map(|r| [(r.lo, 1), (r.hi, -1)])
379 .collect();
380// We sort by boundary, and for each boundary we sort the "closing parentheses" first. The
381 // order of +1/-1 for a same boundary value is actually irrelevant, because we only look at
382 // the accumulated count between distinct boundary values.
383boundaries.sort_unstable();
384385// Accumulate parenthesis counts.
386let mut paren_counter = 0isize;
387// Gather pairs of adjacent boundaries.
388let mut prev_bdy = self.lo;
389boundaries390 .into_iter()
391// End with the end of the range. The count is ignored.
392.chain(once((self.hi, 0)))
393// List pairs of adjacent boundaries and the count between them.
394.map(move |(bdy, delta)| {
395// `delta` affects the count as we cross `bdy`, so the relevant count between
396 // `prev_bdy` and `bdy` is untouched by `delta`.
397let ret = (prev_bdy, paren_counter, bdy);
398prev_bdy = bdy;
399paren_counter += delta;
400ret401 })
402// Skip empty ranges.
403.filter(|&(prev_bdy, _, bdy)| prev_bdy != bdy)
404// Convert back to ranges.
405.map(move |(prev_bdy, paren_count, bdy)| {
406use Presence::*;
407let presence = if paren_count > 0 { Seen } else { Unseen };
408let range = IntRange { lo: prev_bdy, hi: bdy };
409 (presence, range)
410 })
411 }
412}
413414/// Note: this will render signed ranges incorrectly. To render properly, convert to a pattern
415/// first.
416impl fmt::Debugfor IntRange {
417fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418if self.is_singleton() {
419// Only finite ranges can be singletons.
420let Finite(lo) = self.lo else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
421f.write_fmt(format_args!("{0}", lo))write!(f, "{lo}")?;
422 } else {
423if let Finite(lo) = self.lo {
424f.write_fmt(format_args!("{0}", lo))write!(f, "{lo}")?;
425 }
426f.write_fmt(format_args!("{0}", RangeEnd::Excluded))write!(f, "{}", RangeEnd::Excluded)?;
427if let Finite(hi) = self.hi {
428f.write_fmt(format_args!("{0}", hi))write!(f, "{hi}")?;
429 }
430 }
431Ok(())
432 }
433}
434435#[derive(#[automatically_derived]
impl ::core::marker::Copy for SliceKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SliceKind { }
#[automatically_derived]
impl ::core::clone::Clone for SliceKind {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SliceKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::FixedLen(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FixedLen", &__self_0),
Self::VarLen(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "VarLen",
__self_0, &__self_1),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SliceKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SliceKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::FixedLen(__self_0), Self::FixedLen(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::VarLen(__self_0, __self_1),
Self::VarLen(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SliceKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq)]
436pub enum SliceKind {
437/// Patterns of length `n` (`[x, y]`).
438FixedLen(usize),
439/// Patterns using the `..` notation (`[x, .., y]`).
440 /// Captures any array constructor of `length >= i + j`.
441 /// In the case where `array_len` is `Some(_)`,
442 /// this indicates that we only care about the first `i` and the last `j` values of the array,
443 /// and everything in between is a wildcard `_`.
444VarLen(usize, usize),
445}
446447impl SliceKind {
448pub fn arity(self) -> usize {
449match self {
450FixedLen(length) => length,
451VarLen(prefix, suffix) => prefix + suffix,
452 }
453 }
454455/// Whether this pattern includes patterns of length `other_len`.
456fn covers_length(self, other_len: usize) -> bool {
457match self {
458FixedLen(len) => len == other_len,
459VarLen(prefix, suffix) => prefix + suffix <= other_len,
460 }
461 }
462}
463464/// A constructor for array and slice patterns.
465#[derive(#[automatically_derived]
impl ::core::marker::Copy for Slice { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Slice { }
#[automatically_derived]
impl ::core::clone::Clone for Slice {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Option<usize>>;
let _: ::core::clone::AssertParamIsClone<SliceKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Slice {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Slice",
"array_len", &self.array_len, "kind", &&self.kind)
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Slice { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Slice {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.array_len == other.array_len && self.kind == other.kind
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Slice {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<usize>>;
let _: ::core::cmp::AssertParamIsEq<SliceKind>;
}
}Eq)]
466pub struct Slice {
467/// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`.
468pub(crate) array_len: Option<usize>,
469/// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`.
470pub(crate) kind: SliceKind,
471}
472473impl Slice {
474pub fn new(array_len: Option<usize>, kind: SliceKind) -> Self {
475let kind = match (array_len, kind) {
476// If the middle `..` has length 0, we effectively have a fixed-length pattern.
477(Some(len), VarLen(prefix, suffix)) if prefix + suffix == len => FixedLen(len),
478 (Some(len), VarLen(prefix, suffix)) if prefix + suffix > len => {
::core::panicking::panic_fmt(format_args!("Slice pattern of length {0} longer than its array length {1}",
prefix + suffix, len));
}panic!(
479"Slice pattern of length {} longer than its array length {len}",
480 prefix + suffix
481 ),
482_ => kind,
483 };
484Slice { array_len, kind }
485 }
486487pub fn arity(self) -> usize {
488self.kind.arity()
489 }
490491/// See `Constructor::is_covered_by`
492fn is_covered_by(self, other: Self) -> bool {
493other.kind.covers_length(self.arity())
494 }
495496// Getters. They are used by rust-analyzer.
497pub fn array_len(self) -> Option<usize> {
498self.array_len
499 }
500501pub fn kind(self) -> SliceKind {
502self.kind
503 }
504505/// This computes constructor splitting for variable-length slices, as explained at the top of
506 /// the file.
507 ///
508 /// A slice pattern `[x, .., y]` behaves like the infinite or-pattern `[x, y] | [x, _, y] | [x,
509 /// _, _, y] | etc`. The corresponding value constructors are fixed-length array constructors of
510 /// corresponding lengths. We obviously can't list this infinitude of constructors.
511 /// Thankfully, it turns out that for each finite set of slice patterns, all sufficiently large
512 /// array lengths are equivalent.
513 ///
514 /// Let's look at an example, where we are trying to split the last pattern:
515 /// ```
516 /// # fn foo(x: &[bool]) {
517 /// match x {
518 /// [true, true, ..] => {}
519 /// [.., false, false] => {}
520 /// [..] => {}
521 /// }
522 /// # }
523 /// ```
524 /// Here are the results of specialization for the first few lengths:
525 /// ```
526 /// # fn foo(x: &[bool]) { match x {
527 /// // length 0
528 /// [] => {}
529 /// // length 1
530 /// [_] => {}
531 /// // length 2
532 /// [true, true] => {}
533 /// [false, false] => {}
534 /// [_, _] => {}
535 /// // length 3
536 /// [true, true, _ ] => {}
537 /// [_, false, false] => {}
538 /// [_, _, _ ] => {}
539 /// // length 4
540 /// [true, true, _, _ ] => {}
541 /// [_, _, false, false] => {}
542 /// [_, _, _, _ ] => {}
543 /// // length 5
544 /// [true, true, _, _, _ ] => {}
545 /// [_, _, _, false, false] => {}
546 /// [_, _, _, _, _ ] => {}
547 /// # _ => {}
548 /// # }}
549 /// ```
550 ///
551 /// We see that above length 4, we are simply inserting columns full of wildcards in the middle.
552 /// This means that specialization and witness computation with slices of length `l >= 4` will
553 /// give equivalent results regardless of `l`. This applies to any set of slice patterns: there
554 /// will be a length `L` above which all lengths behave the same. This is exactly what we need
555 /// for constructor splitting.
556 ///
557 /// A variable-length slice pattern covers all lengths from its arity up to infinity. As we just
558 /// saw, we can split this in two: lengths below `L` are treated individually with a
559 /// fixed-length slice each; lengths above `L` are grouped into a single variable-length slice
560 /// constructor.
561 ///
562 /// For each variable-length slice pattern `p` with a prefix of length `plₚ` and suffix of
563 /// length `slₚ`, only the first `plₚ` and the last `slₚ` elements are examined. Therefore, as
564 /// long as `L` is positive (to avoid concerns about empty types), all elements after the
565 /// maximum prefix length and before the maximum suffix length are not examined by any
566 /// variable-length pattern, and therefore can be ignored. This gives us a way to compute `L`.
567 ///
568 /// Additionally, if fixed-length patterns exist, we must pick an `L` large enough to miss them,
569 /// so we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))`.
570 /// `max_slice` below will be made to have this arity `L`.
571 ///
572 /// If `self` is fixed-length, it is returned as-is.
573 ///
574 /// Additionally, we track for each output slice whether it is covered by one of the column slices or not.
575fn split(
576self,
577 column_slices: impl Iterator<Item = Slice>,
578 ) -> impl Iterator<Item = (Presence, Slice)> {
579// Range of lengths below `L`.
580let smaller_lengths;
581let arity = self.arity();
582let mut max_slice = self.kind;
583// Tracks the smallest variable-length slice we've seen. Any slice arity above it is
584 // therefore `Presence::Seen` in the column.
585let mut min_var_len = usize::MAX;
586// Tracks the fixed-length slices we've seen, to mark them as `Presence::Seen`.
587let mut seen_fixed_lens = GrowableBitSet::new_empty();
588match &mut max_slice {
589VarLen(max_prefix_len, max_suffix_len) => {
590// A length larger than any fixed-length slice encountered.
591 // We start at 1 in case the subtype is empty because in that case the zero-length
592 // slice must be treated separately from the rest.
593let mut fixed_len_upper_bound = 1;
594// We grow `max_slice` to be larger than all slices encountered, as described above.
595 // `L` is `max_slice.arity()`. For diagnostics, we keep the prefix and suffix
596 // lengths separate.
597for slice in column_slices {
598match slice.kind {
599 FixedLen(len) => {
600 fixed_len_upper_bound = cmp::max(fixed_len_upper_bound, len + 1);
601 seen_fixed_lens.insert(len);
602 }
603 VarLen(prefix, suffix) => {
604*max_prefix_len = cmp::max(*max_prefix_len, prefix);
605*max_suffix_len = cmp::max(*max_suffix_len, suffix);
606 min_var_len = cmp::min(min_var_len, prefix + suffix);
607 }
608 }
609 }
610// If `fixed_len_upper_bound >= L`, we set `L` to `fixed_len_upper_bound`.
611if let Some(delta) =
612fixed_len_upper_bound.checked_sub(*max_prefix_len + *max_suffix_len)
613 {
614*max_prefix_len += delta615 }
616617// We cap the arity of `max_slice` at the array size.
618match self.array_len {
619Some(len) if max_slice.arity() >= len => max_slice = FixedLen(len),
620_ => {}
621 }
622623smaller_lengths = match self.array_len {
624// The only admissible fixed-length slice is one of the array size. Whether `max_slice`
625 // is fixed-length or variable-length, it will be the only relevant slice to output
626 // here.
627Some(_) => 0..0, // empty range
628 // We need to cover all arities in the range `(arity..infinity)`. We split that
629 // range into two: lengths smaller than `max_slice.arity()` are treated
630 // independently as fixed-lengths slices, and lengths above are captured by
631 // `max_slice`.
632None => self.arity()..max_slice.arity(),
633 };
634 }
635FixedLen(_) => {
636// No need to split here. We only track presence.
637for slice in column_slices {
638match slice.kind {
639 FixedLen(len) => {
640if len == arity {
641 seen_fixed_lens.insert(len);
642 }
643 }
644 VarLen(prefix, suffix) => {
645 min_var_len = cmp::min(min_var_len, prefix + suffix);
646 }
647 }
648 }
649smaller_lengths = 0..0;
650 }
651 };
652653smaller_lengths.map(FixedLen).chain(once(max_slice)).map(move |kind| {
654let arity = kind.arity();
655let seen = if min_var_len <= arity || seen_fixed_lens.contains(arity) {
656 Presence::Seen657 } else {
658 Presence::Unseen659 };
660 (seen, Slice::new(self.array_len, kind))
661 })
662 }
663}
664665/// A globally unique id to distinguish `Opaque` patterns.
666#[derive(#[automatically_derived]
impl ::core::clone::Clone for OpaqueId {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for OpaqueId {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "OpaqueId",
&&self.0)
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for OpaqueId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for OpaqueId {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for OpaqueId {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq)]
667pub struct OpaqueId(u32);
668669impl OpaqueId {
670pub fn new() -> Self {
671use std::sync::atomic::{AtomicU32, Ordering};
672static OPAQUE_ID: AtomicU32 = AtomicU32::new(0);
673OpaqueId(OPAQUE_ID.fetch_add(1, Ordering::SeqCst))
674 }
675}
676677/// A value can be decomposed into a constructor applied to some fields. This struct represents
678/// the constructor. See also `Fields`.
679///
680/// `pat_constructor` retrieves the constructor corresponding to a pattern.
681/// `specialize_constructor` returns the list of fields corresponding to a pattern, given a
682/// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
683/// `Fields`.
684#[derive(#[automatically_derived]
impl<Cx: ::core::fmt::Debug + PatCx> ::core::fmt::Debug for Constructor<Cx>
where Cx::VariantIdx: ::core::fmt::Debug, Cx::StrLit: ::core::fmt::Debug,
Cx::Ty: ::core::fmt::Debug {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Struct => ::core::fmt::Formatter::write_str(f, "Struct"),
Self::Variant(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Variant", &__self_0),
Self::Ref => ::core::fmt::Formatter::write_str(f, "Ref"),
Self::Slice(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Slice",
&__self_0),
Self::UnionField =>
::core::fmt::Formatter::write_str(f, "UnionField"),
Self::Bool(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Bool",
&__self_0),
Self::IntRange(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IntRange", &__self_0),
Self::F16Range(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"F16Range", __self_0, __self_1, &__self_2),
Self::F32Range(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"F32Range", __self_0, __self_1, &__self_2),
Self::F64Range(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"F64Range", __self_0, __self_1, &__self_2),
Self::F128Range(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"F128Range", __self_0, __self_1, &__self_2),
Self::Str(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Str",
&__self_0),
Self::DerefPattern(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DerefPattern", &__self_0),
Self::Opaque(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Opaque",
&__self_0),
Self::Or => ::core::fmt::Formatter::write_str(f, "Or"),
Self::Wildcard =>
::core::fmt::Formatter::write_str(f, "Wildcard"),
Self::Never => ::core::fmt::Formatter::write_str(f, "Never"),
Self::NonExhaustive =>
::core::fmt::Formatter::write_str(f, "NonExhaustive"),
Self::Hidden => ::core::fmt::Formatter::write_str(f, "Hidden"),
Self::Missing => ::core::fmt::Formatter::write_str(f, "Missing"),
Self::PrivateUninhabited =>
::core::fmt::Formatter::write_str(f, "PrivateUninhabited"),
}
}
}Debug)]
685pub enum Constructor<Cx: PatCx> {
686/// Tuples and structs.
687Struct,
688/// Enum variants.
689Variant(Cx::VariantIdx),
690/// References
691Ref,
692/// Array and slice patterns.
693Slice(Slice),
694/// Union field accesses.
695UnionField,
696/// Booleans
697Bool(bool),
698/// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
699IntRange(IntRange),
700/// Ranges of floating-point literal values (`2.0..=5.2`).
701F16Range(IeeeFloat<HalfS>, IeeeFloat<HalfS>, RangeEnd),
702 F32Range(IeeeFloat<SingleS>, IeeeFloat<SingleS>, RangeEnd),
703 F64Range(IeeeFloat<DoubleS>, IeeeFloat<DoubleS>, RangeEnd),
704 F128Range(IeeeFloat<QuadS>, IeeeFloat<QuadS>, RangeEnd),
705/// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
706Str(Cx::StrLit),
707/// Deref patterns (enabled by the `deref_patterns` feature) provide a way of matching on a
708 /// smart pointer ADT through its pointee. They don't directly correspond to ADT constructors,
709 /// and currently are not supported alongside them. Carries the type of the pointee.
710DerefPattern(Cx::Ty),
711/// Constants that must not be matched structurally. They are treated as black boxes for the
712 /// purposes of exhaustiveness: we must not inspect them, and they don't count towards making a
713 /// match exhaustive.
714 /// Carries an id that must be unique within a match. We need this to ensure the invariants of
715 /// [`SplitConstructorSet`].
716Opaque(OpaqueId),
717/// Or-pattern.
718Or,
719/// Wildcard pattern.
720Wildcard,
721/// Never pattern. Only used in `WitnessPat`. An actual never pattern should be lowered as
722 /// `Wildcard`.
723Never,
724/// Fake extra constructor for enums that aren't allowed to be matched exhaustively. Also used
725 /// for those types for which we cannot list constructors explicitly, like `f64` and `str`. Only
726 /// used in `WitnessPat`.
727NonExhaustive,
728/// Fake extra constructor for variants that should not be mentioned in diagnostics. We use this
729 /// for variants behind an unstable gate as well as `#[doc(hidden)]` ones. Only used in
730 /// `WitnessPat`.
731Hidden,
732/// Fake extra constructor for constructors that are not seen in the matrix, as explained at the
733 /// top of the file. Only used for specialization.
734Missing,
735/// Fake extra constructor that indicates and empty field that is private. When we encounter one
736 /// we skip the column entirely so we don't observe its emptiness. Only used for specialization.
737PrivateUninhabited,
738}
739740impl<Cx: PatCx> Clonefor Constructor<Cx> {
741fn clone(&self) -> Self {
742match self {
743 Constructor::Struct => Constructor::Struct,
744 Constructor::Variant(idx) => Constructor::Variant(*idx),
745 Constructor::Ref => Constructor::Ref,
746 Constructor::Slice(slice) => Constructor::Slice(*slice),
747 Constructor::UnionField => Constructor::UnionField,
748 Constructor::Bool(b) => Constructor::Bool(*b),
749 Constructor::IntRange(range) => Constructor::IntRange(*range),
750 Constructor::F16Range(lo, hi, end) => Constructor::F16Range(*lo, *hi, *end),
751 Constructor::F32Range(lo, hi, end) => Constructor::F32Range(*lo, *hi, *end),
752 Constructor::F64Range(lo, hi, end) => Constructor::F64Range(*lo, *hi, *end),
753 Constructor::F128Range(lo, hi, end) => Constructor::F128Range(*lo, *hi, *end),
754 Constructor::Str(value) => Constructor::Str(value.clone()),
755 Constructor::DerefPattern(ty) => Constructor::DerefPattern(ty.clone()),
756 Constructor::Opaque(inner) => Constructor::Opaque(inner.clone()),
757 Constructor::Or => Constructor::Or,
758 Constructor::Never => Constructor::Never,
759 Constructor::Wildcard => Constructor::Wildcard,
760 Constructor::NonExhaustive => Constructor::NonExhaustive,
761 Constructor::Hidden => Constructor::Hidden,
762 Constructor::Missing => Constructor::Missing,
763 Constructor::PrivateUninhabited => Constructor::PrivateUninhabited,
764 }
765 }
766}
767768impl<Cx: PatCx> Constructor<Cx> {
769pub(crate) fn is_non_exhaustive(&self) -> bool {
770#[allow(non_exhaustive_omitted_patterns)] match self {
NonExhaustive => true,
_ => false,
}matches!(self, NonExhaustive)771 }
772773pub(crate) fn as_variant(&self) -> Option<Cx::VariantIdx> {
774match self {
775Variant(i) => Some(*i),
776_ => None,
777 }
778 }
779fn as_bool(&self) -> Option<bool> {
780match self {
781Bool(b) => Some(*b),
782_ => None,
783 }
784 }
785pub(crate) fn as_int_range(&self) -> Option<&IntRange> {
786match self {
787IntRange(range) => Some(range),
788_ => None,
789 }
790 }
791fn as_slice(&self) -> Option<Slice> {
792match self {
793Slice(slice) => Some(*slice),
794_ => None,
795 }
796 }
797798/// The number of fields for this constructor. This must be kept in sync with
799 /// `Fields::wildcards`.
800pub(crate) fn arity(&self, cx: &Cx, ty: &Cx::Ty) -> usize {
801cx.ctor_arity(self, ty)
802 }
803804/// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`.
805 /// For the simple cases, this is simply checking for equality. For the "grouped" constructors,
806 /// this checks for inclusion.
807// We inline because this has a single call site in `Matrix::specialize_constructor`.
808#[inline]
809pub(crate) fn is_covered_by(&self, cx: &Cx, other: &Self) -> Result<bool, Cx::Error> {
810Ok(match (self, other) {
811 (Wildcard, _) => {
812return Err(cx.bug(format_args!("Constructor splitting should not have returned `Wildcard`")format_args!(
813"Constructor splitting should not have returned `Wildcard`"
814)));
815 }
816// Wildcards cover anything
817(_, Wildcard) => true,
818// `PrivateUninhabited` skips everything.
819(PrivateUninhabited, _) => true,
820// Only a wildcard pattern can match these special constructors.
821(Missing { .. } | NonExhaustive | Hidden, _) => false,
822823 (Struct, Struct) => true,
824 (Ref, Ref) => true,
825 (UnionField, UnionField) => true,
826 (Variant(self_id), Variant(other_id)) => self_id == other_id,
827 (Bool(self_b), Bool(other_b)) => self_b == other_b,
828829 (IntRange(self_range), IntRange(other_range)) => self_range.is_subrange(other_range),
830 (F16Range(self_from, self_to, self_end), F16Range(other_from, other_to, other_end)) => {
831self_from.ge(other_from)
832 && match self_to.partial_cmp(other_to) {
833Some(Ordering::Less) => true,
834Some(Ordering::Equal) => other_end == self_end,
835_ => false,
836 }
837 }
838 (F32Range(self_from, self_to, self_end), F32Range(other_from, other_to, other_end)) => {
839self_from.ge(other_from)
840 && match self_to.partial_cmp(other_to) {
841Some(Ordering::Less) => true,
842Some(Ordering::Equal) => other_end == self_end,
843_ => false,
844 }
845 }
846 (F64Range(self_from, self_to, self_end), F64Range(other_from, other_to, other_end)) => {
847self_from.ge(other_from)
848 && match self_to.partial_cmp(other_to) {
849Some(Ordering::Less) => true,
850Some(Ordering::Equal) => other_end == self_end,
851_ => false,
852 }
853 }
854 (
855F128Range(self_from, self_to, self_end),
856F128Range(other_from, other_to, other_end),
857 ) => {
858self_from.ge(other_from)
859 && match self_to.partial_cmp(other_to) {
860Some(Ordering::Less) => true,
861Some(Ordering::Equal) => other_end == self_end,
862_ => false,
863 }
864 }
865 (Str(self_val), Str(other_val)) => {
866// FIXME Once valtrees are available we can directly use the bytes
867 // in the `Str` variant of the valtree for the comparison here.
868self_val == other_val869 }
870 (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
871872// Deref patterns only interact with other deref patterns. Prior to usefulness analysis,
873 // we ensure they don't appear alongside any other non-wild non-opaque constructors.
874(DerefPattern(_), DerefPattern(_)) => true,
875876// Opaque constructors don't interact with anything unless they come from the
877 // syntactically identical pattern.
878(Opaque(self_id), Opaque(other_id)) => self_id == other_id,
879 (Opaque(..), _) | (_, Opaque(..)) => false,
880881_ => {
882return Err(cx.delayed_bug(format_args!("trying to compare incompatible constructors {0:?} and {1:?}",
self, other)format_args!(
883"trying to compare incompatible constructors {self:?} and {other:?}"
884)));
885 }
886 })
887 }
888889pub(crate) fn fmt_fields(
890&self,
891 f: &mut fmt::Formatter<'_>,
892 ty: &Cx::Ty,
893mut fields: impl Iterator<Item = impl fmt::Debug>,
894 ) -> fmt::Result {
895let mut first = true;
896let mut start_or_continue = |s| {
897if first {
898first = false;
899""
900} else {
901s902 }
903 };
904let mut start_or_comma = || start_or_continue(", ");
905906match self {
907Struct | Variant(_) | UnionField => {
908 Cx::write_variant_name(f, self, ty)?;
909// Without `cx`, we can't know which field corresponds to which, so we can't
910 // get the names of the fields. Instead we just display everything as a tuple
911 // struct, which should be good enough.
912f.write_fmt(format_args!("("))write!(f, "(")?;
913for p in fields {
914f.write_fmt(format_args!("{0}{1:?}", start_or_comma(), p))write!(f, "{}{:?}", start_or_comma(), p)?;
915 }
916f.write_fmt(format_args!(")"))write!(f, ")")?;
917 }
918// Note: given the expansion of `&str` patterns done in `expand_pattern`, we should
919 // be careful to detect strings here. However a string literal pattern will never
920 // be reported as a non-exhaustiveness witness, so we can ignore this issue.
921Ref => {
922f.write_fmt(format_args!("&{0:?}", fields.next().unwrap()))write!(f, "&{:?}", fields.next().unwrap())?;
923 }
924Slice(slice) => {
925f.write_fmt(format_args!("["))write!(f, "[")?;
926match slice.kind {
927 SliceKind::FixedLen(_) => {
928for p in fields {
929f.write_fmt(format_args!("{0}{1:?}", start_or_comma(), p))write!(f, "{}{:?}", start_or_comma(), p)?;
930 }
931 }
932 SliceKind::VarLen(prefix_len, _) => {
933for p in fields.by_ref().take(prefix_len) {
934f.write_fmt(format_args!("{0}{1:?}", start_or_comma(), p))write!(f, "{}{:?}", start_or_comma(), p)?;
935 }
936f.write_fmt(format_args!("{0}..", start_or_comma()))write!(f, "{}..", start_or_comma())?;
937for p in fields {
938f.write_fmt(format_args!("{0}{1:?}", start_or_comma(), p))write!(f, "{}{:?}", start_or_comma(), p)?;
939 }
940 }
941 }
942f.write_fmt(format_args!("]"))write!(f, "]")?;
943 }
944Bool(b) => f.write_fmt(format_args!("{0}", b))write!(f, "{b}")?,
945// Best-effort, will render signed ranges incorrectly
946IntRange(range) => f.write_fmt(format_args!("{0:?}", range))write!(f, "{range:?}")?,
947F16Range(lo, hi, end) => f.write_fmt(format_args!("{0}{1}{2}", lo, end, hi))write!(f, "{lo}{end}{hi}")?,
948F32Range(lo, hi, end) => f.write_fmt(format_args!("{0}{1}{2}", lo, end, hi))write!(f, "{lo}{end}{hi}")?,
949F64Range(lo, hi, end) => f.write_fmt(format_args!("{0}{1}{2}", lo, end, hi))write!(f, "{lo}{end}{hi}")?,
950F128Range(lo, hi, end) => f.write_fmt(format_args!("{0}{1}{2}", lo, end, hi))write!(f, "{lo}{end}{hi}")?,
951Str(value) => f.write_fmt(format_args!("{0:?}", value))write!(f, "{value:?}")?,
952DerefPattern(_) => f.write_fmt(format_args!("deref!({0:?})", fields.next().unwrap()))write!(f, "deref!({:?})", fields.next().unwrap())?,
953Opaque(..) => f.write_fmt(format_args!("<constant pattern>"))write!(f, "<constant pattern>")?,
954Or => {
955for pat in fields {
956f.write_fmt(format_args!("{0}{1:?}", start_or_continue(" | "), pat))write!(f, "{}{:?}", start_or_continue(" | "), pat)?;
957 }
958 }
959Never => f.write_fmt(format_args!("!"))write!(f, "!")?,
960Wildcard | Missing | NonExhaustive | Hidden | PrivateUninhabited => f.write_fmt(format_args!("_"))write!(f, "_")?,
961 }
962Ok(())
963 }
964}
965966#[derive(#[automatically_derived]
impl ::core::fmt::Debug for VariantVisibility {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
VariantVisibility::Visible => "Visible",
VariantVisibility::Hidden => "Hidden",
VariantVisibility::Empty => "Empty",
})
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for VariantVisibility { }
#[automatically_derived]
impl ::core::clone::Clone for VariantVisibility {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for VariantVisibility { }Copy)]
967pub enum VariantVisibility {
968/// Variant that doesn't fit the other cases, i.e. most variants.
969Visible,
970/// Variant behind an unstable gate or with the `#[doc(hidden)]` attribute. It will not be
971 /// mentioned in diagnostics unless the user mentioned it first.
972Hidden,
973/// Variant that matches no value. E.g. `Some::<Option<!>>` if the `exhaustive_patterns` feature
974 /// is enabled. Like `Hidden`, it will not be mentioned in diagnostics unless the user mentioned
975 /// it first.
976Empty,
977}
978979/// Describes the set of all constructors for a type. For details, in particular about the emptiness
980/// of constructors, see the top of the file.
981///
982/// In terms of division of responsibility, [`ConstructorSet::split`] handles all of the
983/// `exhaustive_patterns` feature.
984#[derive(#[automatically_derived]
impl<Cx: ::core::fmt::Debug + PatCx> ::core::fmt::Debug for ConstructorSet<Cx>
where Cx::VariantIdx: ::core::fmt::Debug {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Struct { empty: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Struct", "empty", &__self_0),
Self::Variants { variants: __self_0, non_exhaustive: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Variants", "variants", __self_0, "non_exhaustive",
&__self_1),
Self::Ref => ::core::fmt::Formatter::write_str(f, "Ref"),
Self::Union => ::core::fmt::Formatter::write_str(f, "Union"),
Self::Bool => ::core::fmt::Formatter::write_str(f, "Bool"),
Self::Integers { range_1: __self_0, range_2: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Integers", "range_1", __self_0, "range_2", &__self_1),
Self::Slice { array_len: __self_0, subtype_is_empty: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Slice",
"array_len", __self_0, "subtype_is_empty", &__self_1),
Self::Unlistable =>
::core::fmt::Formatter::write_str(f, "Unlistable"),
Self::NoConstructors =>
::core::fmt::Formatter::write_str(f, "NoConstructors"),
}
}
}Debug)]
985pub enum ConstructorSet<Cx: PatCx> {
986/// The type is a tuple or struct. `empty` tracks whether the type is empty.
987Struct { empty: bool },
988/// This type has the following list of constructors. If `variants` is empty and
989 /// `non_exhaustive` is false, don't use this; use `NoConstructors` instead.
990Variants { variants: IndexVec<Cx::VariantIdx, VariantVisibility>, non_exhaustive: bool },
991/// The type is `&T`.
992Ref,
993/// The type is a union.
994Union,
995/// Booleans.
996Bool,
997/// The type is spanned by integer values. The range or ranges give the set of allowed values.
998 /// The second range is only useful for `char`.
999Integers { range_1: IntRange, range_2: Option<IntRange> },
1000/// The type is matched by slices. `array_len` is the compile-time length of the array, if
1001 /// known. If `subtype_is_empty`, all constructors are empty except possibly the zero-length
1002 /// slice `[]`.
1003Slice { array_len: Option<usize>, subtype_is_empty: bool },
1004/// The constructors cannot be listed, and the type cannot be matched exhaustively. E.g. `str`,
1005 /// floats.
1006Unlistable,
1007/// The type has no constructors (not even empty ones). This is `!` and empty enums.
1008NoConstructors,
1009}
10101011/// Describes the result of analyzing the constructors in a column of a match.
1012///
1013/// `present` is morally the set of constructors present in the column, and `missing` is the set of
1014/// constructors that exist in the type but are not present in the column.
1015///
1016/// More formally, if we discard wildcards from the column, this respects the following constraints:
1017/// 1. the union of `present`, `missing` and `missing_empty` covers all the constructors of the type
1018/// 2. each constructor in `present` is covered by something in the column
1019/// 3. no constructor in `missing` or `missing_empty` is covered by anything in the column
1020/// 4. each constructor in the column is equal to the union of one or more constructors in `present`
1021/// 5. `missing` does not contain empty constructors (see discussion about emptiness at the top of
1022/// the file);
1023/// 6. `missing_empty` contains only empty constructors
1024/// 7. constructors in `present`, `missing` and `missing_empty` are split for the column; in other
1025/// words, they are either fully included in or fully disjoint from each constructor in the
1026/// column. In yet other words, there are no non-trivial intersections like between `0..10` and
1027/// `5..15`.
1028///
1029/// We must be particularly careful with weird constructors like `Opaque`: they're not formally part
1030/// of the `ConstructorSet` for the type, yet if we forgot to include them in `present` we would be
1031/// ignoring any row with `Opaque`s in the algorithm. Hence the importance of point 4.
1032#[derive(#[automatically_derived]
impl<Cx: ::core::fmt::Debug + PatCx> ::core::fmt::Debug for
SplitConstructorSet<Cx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"SplitConstructorSet", "present", &self.present, "missing",
&self.missing, "missing_empty", &&self.missing_empty)
}
}Debug)]
1033pub struct SplitConstructorSet<Cx: PatCx> {
1034pub present: SmallVec<[Constructor<Cx>; 1]>,
1035pub missing: Vec<Constructor<Cx>>,
1036pub missing_empty: Vec<Constructor<Cx>>,
1037}
10381039impl<Cx: PatCx> ConstructorSet<Cx> {
1040/// This analyzes a column of constructors to 1/ determine which constructors of the type (if
1041 /// any) are missing; 2/ split constructors to handle non-trivial intersections e.g. on ranges
1042 /// or slices. This can get subtle; see [`SplitConstructorSet`] for details of this operation
1043 /// and its invariants.
1044pub fn split<'a>(
1045&self,
1046 ctors: impl Iterator<Item = &'a Constructor<Cx>> + Clone,
1047 ) -> SplitConstructorSet<Cx>
1048where
1049Cx: 'a,
1050 {
1051let mut present: SmallVec<[_; 1]> = SmallVec::new();
1052// Empty constructors found missing.
1053let mut missing_empty = Vec::new();
1054// Nonempty constructors found missing.
1055let mut missing = Vec::new();
1056// Constructors in `ctors`, except wildcards and opaques.
1057let mut seen = Vec::new();
1058// If we see a deref pattern, it must be the only non-wildcard non-opaque constructor; we
1059 // ensure this prior to analysis.
1060let mut deref_pat_present = false;
1061for ctor in ctors.cloned() {
1062match ctor {
1063 DerefPattern(..) => {
1064if !deref_pat_present {
1065 deref_pat_present = true;
1066 present.push(ctor);
1067 }
1068 }
1069 Opaque(..) => present.push(ctor),
1070 Wildcard => {} // discard wildcards
1071_ => seen.push(ctor),
1072 }
1073 }
10741075match self {
1076_ if deref_pat_present => {
1077// Deref patterns are the only constructor; nothing is missing.
1078}
1079 ConstructorSet::Struct { empty } => {
1080if !seen.is_empty() {
1081present.push(Struct);
1082 } else if *empty {
1083missing_empty.push(Struct);
1084 } else {
1085missing.push(Struct);
1086 }
1087 }
1088 ConstructorSet::Ref => {
1089if !seen.is_empty() {
1090present.push(Ref);
1091 } else {
1092missing.push(Ref);
1093 }
1094 }
1095 ConstructorSet::Union => {
1096if !seen.is_empty() {
1097present.push(UnionField);
1098 } else {
1099missing.push(UnionField);
1100 }
1101 }
1102 ConstructorSet::Variants { variants, non_exhaustive } => {
1103let mut seen_set = DenseBitSet::new_empty(variants.len());
1104for idx in seen.iter().filter_map(|c| c.as_variant()) {
1105 seen_set.insert(idx);
1106 }
1107let mut skipped_a_hidden_variant = false;
11081109for (idx, visibility) in variants.iter_enumerated() {
1110let ctor = Variant(idx);
1111if seen_set.contains(idx) {
1112 present.push(ctor);
1113 } else {
1114// We only put visible variants directly into `missing`.
1115match visibility {
1116 VariantVisibility::Visible => missing.push(ctor),
1117 VariantVisibility::Hidden => skipped_a_hidden_variant = true,
1118 VariantVisibility::Empty => missing_empty.push(ctor),
1119 }
1120 }
1121 }
11221123if skipped_a_hidden_variant {
1124missing.push(Hidden);
1125 }
1126if *non_exhaustive {
1127missing.push(NonExhaustive);
1128 }
1129 }
1130 ConstructorSet::Bool => {
1131let mut seen_false = false;
1132let mut seen_true = false;
1133for b in seen.iter().filter_map(|ctor| ctor.as_bool()) {
1134if b {
1135 seen_true = true;
1136 } else {
1137 seen_false = true;
1138 }
1139 }
1140if seen_true {
1141present.push(Bool(true));
1142 } else {
1143missing.push(Bool(true));
1144 }
1145if seen_false {
1146present.push(Bool(false));
1147 } else {
1148missing.push(Bool(false));
1149 }
1150 }
1151 ConstructorSet::Integers { range_1, range_2 } => {
1152let seen_ranges: Vec<_> =
1153seen.iter().filter_map(|ctor| ctor.as_int_range()).copied().collect();
1154for (seen, splitted_range) in range_1.split(seen_ranges.iter().cloned()) {
1155match seen {
1156 Presence::Unseen => missing.push(IntRange(splitted_range)),
1157 Presence::Seen => present.push(IntRange(splitted_range)),
1158 }
1159 }
1160if let Some(range_2) = range_2 {
1161for (seen, splitted_range) in range_2.split(seen_ranges.into_iter()) {
1162match seen {
1163 Presence::Unseen => missing.push(IntRange(splitted_range)),
1164 Presence::Seen => present.push(IntRange(splitted_range)),
1165 }
1166 }
1167 }
1168 }
1169 ConstructorSet::Slice { array_len, subtype_is_empty } => {
1170let seen_slices = seen.iter().filter_map(|c| c.as_slice());
1171let base_slice = Slice::new(*array_len, VarLen(0, 0));
1172for (seen, splitted_slice) in base_slice.split(seen_slices) {
1173let ctor = Slice(splitted_slice);
1174match seen {
1175 Presence::Seen => present.push(ctor),
1176 Presence::Unseen => {
1177if *subtype_is_empty && splitted_slice.arity() != 0 {
1178// We have subpatterns of an empty type, so the constructor is
1179 // empty.
1180missing_empty.push(ctor);
1181 } else {
1182 missing.push(ctor);
1183 }
1184 }
1185 }
1186 }
1187 }
1188 ConstructorSet::Unlistable => {
1189// Since we can't list constructors, we take the ones in the column. This might list
1190 // some constructors several times but there's not much we can do.
1191present.extend(seen);
1192missing.push(NonExhaustive);
1193 }
1194 ConstructorSet::NoConstructors => {
1195// In a `MaybeInvalid` place even an empty pattern may be reachable. We therefore
1196 // add a dummy empty constructor here, which will be ignored if the place is
1197 // `ValidOnly`.
1198missing_empty.push(Never);
1199 }
1200 }
12011202SplitConstructorSet { present, missing, missing_empty }
1203 }
12041205/// Whether this set only contains empty constructors.
1206pub(crate) fn all_empty(&self) -> bool {
1207match self {
1208 ConstructorSet::Bool1209 | ConstructorSet::Integers { .. }
1210 | ConstructorSet::Ref1211 | ConstructorSet::Union1212 | ConstructorSet::Unlistable => false,
1213 ConstructorSet::NoConstructors => true,
1214 ConstructorSet::Struct { empty } => *empty,
1215 ConstructorSet::Variants { variants, non_exhaustive } => {
1216 !*non_exhaustive1217 && variants1218 .iter()
1219 .all(|visibility| #[allow(non_exhaustive_omitted_patterns)] match visibility {
VariantVisibility::Empty => true,
_ => false,
}matches!(visibility, VariantVisibility::Empty))
1220 }
1221 ConstructorSet::Slice { array_len, subtype_is_empty } => {
1222*subtype_is_empty && #[allow(non_exhaustive_omitted_patterns)] match array_len {
Some(1..) => true,
_ => false,
}matches!(array_len, Some(1..))1223 }
1224 }
1225 }
1226}