Skip to main content

rustc_pattern_analysis/
constructor.rs

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