]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_mir_build / src / thir / pattern / deconstruct_pat.rs
1 //! [`super::usefulness`] explains most of what is happening in this file. As explained there,
2 //! values and patterns are made from constructors applied to fields. This file defines a
3 //! `Constructor` enum, a `Fields` struct, and various operations to manipulate them and convert
4 //! them from/to patterns.
5 //!
6 //! There's one idea that is not detailed in [`super::usefulness`] because the details are not
7 //! needed there: _constructor splitting_.
8 //!
9 //! # Constructor splitting
10 //!
11 //! The idea is as follows: given a constructor `c` and a matrix, we want to specialize in turn
12 //! with all the value constructors that are covered by `c`, and compute usefulness for each.
13 //! Instead of listing all those constructors (which is intractable), we group those value
14 //! constructors together as much as possible. Example:
15 //!
16 //! ```compile_fail,E0004
17 //! match (0, false) {
18 //! (0 ..=100, true) => {} // `p_1`
19 //! (50..=150, false) => {} // `p_2`
20 //! (0 ..=200, _) => {} // `q`
21 //! }
22 //! ```
23 //!
24 //! The naive approach would try all numbers in the range `0..=200`. But we can be a lot more
25 //! clever: `0` and `1` for example will match the exact same rows, and return equivalent
26 //! witnesses. In fact all of `0..50` would. We can thus restrict our exploration to 4
27 //! constructors: `0..50`, `50..=100`, `101..=150` and `151..=200`. That is enough and infinitely
28 //! more tractable.
29 //!
30 //! We capture this idea in a function `split(p_1 ... p_n, c)` which returns a list of constructors
31 //! `c'` covered by `c`. Given such a `c'`, we require that all value ctors `c''` covered by `c'`
32 //! return an equivalent set of witnesses after specializing and computing usefulness.
33 //! In the example above, witnesses for specializing by `c''` covered by `0..50` will only differ
34 //! in their first element.
35 //!
36 //! We usually also ask that the `c'` together cover all of the original `c`. However we allow
37 //! skipping some constructors as long as it doesn't change whether the resulting list of witnesses
38 //! is empty of not. We use this in the wildcard `_` case.
39 //!
40 //! Splitting is implemented in the [`Constructor::split`] function. We don't do splitting for
41 //! or-patterns; instead we just try the alternatives one-by-one. For details on splitting
42 //! wildcards, see [`SplitWildcard`]; for integer ranges, see [`SplitIntRange`]; for slices, see
43 //! [`SplitVarLenSlice`].
44
45 use self::Constructor::*;
46 use self::SliceKind::*;
47
48 use super::compare_const_vals;
49 use super::usefulness::{MatchCheckCtxt, PatCtxt};
50
51 use rustc_data_structures::captures::Captures;
52 use rustc_index::vec::Idx;
53
54 use rustc_hir::{HirId, RangeEnd};
55 use rustc_middle::mir::{self, Field};
56 use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange};
57 use rustc_middle::ty::layout::IntegerExt;
58 use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
59 use rustc_middle::{middle::stability::EvalResult, mir::interpret::ConstValue};
60 use rustc_session::lint;
61 use rustc_span::{Span, DUMMY_SP};
62 use rustc_target::abi::{Integer, Size, VariantIdx};
63
64 use smallvec::{smallvec, SmallVec};
65 use std::cell::Cell;
66 use std::cmp::{self, max, min, Ordering};
67 use std::fmt;
68 use std::iter::{once, IntoIterator};
69 use std::ops::RangeInclusive;
70
71 /// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.
72 fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> {
73 fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) {
74 if let PatKind::Or { pats } = pat.kind.as_ref() {
75 for pat in pats {
76 expand(pat, vec);
77 }
78 } else {
79 vec.push(pat)
80 }
81 }
82
83 let mut pats = Vec::new();
84 expand(pat, &mut pats);
85 pats
86 }
87
88 /// An inclusive interval, used for precise integer exhaustiveness checking.
89 /// `IntRange`s always store a contiguous range. This means that values are
90 /// encoded such that `0` encodes the minimum value for the integer,
91 /// regardless of the signedness.
92 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
93 /// This makes comparisons and arithmetic on interval endpoints much more
94 /// straightforward. See `signed_bias` for details.
95 ///
96 /// `IntRange` is never used to encode an empty range or a "range" that wraps
97 /// around the (offset) space: i.e., `range.lo <= range.hi`.
98 #[derive(Clone, PartialEq, Eq)]
99 pub(super) struct IntRange {
100 range: RangeInclusive<u128>,
101 /// Keeps the bias used for encoding the range. It depends on the type of the range and
102 /// possibly the pointer size of the current architecture. The algorithm ensures we never
103 /// compare `IntRange`s with different types/architectures.
104 bias: u128,
105 }
106
107 impl IntRange {
108 #[inline]
109 fn is_integral(ty: Ty<'_>) -> bool {
110 matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool)
111 }
112
113 fn is_singleton(&self) -> bool {
114 self.range.start() == self.range.end()
115 }
116
117 fn boundaries(&self) -> (u128, u128) {
118 (*self.range.start(), *self.range.end())
119 }
120
121 #[inline]
122 fn integral_size_and_signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Size, u128)> {
123 match *ty.kind() {
124 ty::Bool => Some((Size::from_bytes(1), 0)),
125 ty::Char => Some((Size::from_bytes(4), 0)),
126 ty::Int(ity) => {
127 let size = Integer::from_int_ty(&tcx, ity).size();
128 Some((size, 1u128 << (size.bits() as u128 - 1)))
129 }
130 ty::Uint(uty) => Some((Integer::from_uint_ty(&tcx, uty).size(), 0)),
131 _ => None,
132 }
133 }
134
135 #[inline]
136 fn from_constant<'tcx>(
137 tcx: TyCtxt<'tcx>,
138 param_env: ty::ParamEnv<'tcx>,
139 value: mir::ConstantKind<'tcx>,
140 ) -> Option<IntRange> {
141 let ty = value.ty();
142 if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, ty) {
143 let val = (|| {
144 match value {
145 mir::ConstantKind::Val(ConstValue::Scalar(scalar), _) => {
146 // For this specific pattern we can skip a lot of effort and go
147 // straight to the result, after doing a bit of checking. (We
148 // could remove this branch and just fall through, which
149 // is more general but much slower.)
150 if let Ok(Ok(bits)) = scalar.to_bits_or_ptr_internal(target_size) {
151 return Some(bits);
152 } else {
153 return None;
154 }
155 }
156 mir::ConstantKind::Ty(c) => match c.kind() {
157 ty::ConstKind::Value(_) => bug!(
158 "encountered ConstValue in mir::ConstantKind::Ty, whereas this is expected to be in ConstantKind::Val"
159 ),
160 _ => {}
161 },
162 _ => {}
163 }
164
165 // This is a more general form of the previous case.
166 value.try_eval_bits(tcx, param_env, ty)
167 })()?;
168 let val = val ^ bias;
169 Some(IntRange { range: val..=val, bias })
170 } else {
171 None
172 }
173 }
174
175 #[inline]
176 fn from_range<'tcx>(
177 tcx: TyCtxt<'tcx>,
178 lo: u128,
179 hi: u128,
180 ty: Ty<'tcx>,
181 end: &RangeEnd,
182 ) -> Option<IntRange> {
183 if Self::is_integral(ty) {
184 // Perform a shift if the underlying types are signed,
185 // which makes the interval arithmetic simpler.
186 let bias = IntRange::signed_bias(tcx, ty);
187 let (lo, hi) = (lo ^ bias, hi ^ bias);
188 let offset = (*end == RangeEnd::Excluded) as u128;
189 if lo > hi || (lo == hi && *end == RangeEnd::Excluded) {
190 // This should have been caught earlier by E0030.
191 bug!("malformed range pattern: {}..={}", lo, (hi - offset));
192 }
193 Some(IntRange { range: lo..=(hi - offset), bias })
194 } else {
195 None
196 }
197 }
198
199 // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
200 fn signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> u128 {
201 match *ty.kind() {
202 ty::Int(ity) => {
203 let bits = Integer::from_int_ty(&tcx, ity).size().bits() as u128;
204 1u128 << (bits - 1)
205 }
206 _ => 0,
207 }
208 }
209
210 fn is_subrange(&self, other: &Self) -> bool {
211 other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
212 }
213
214 fn intersection(&self, other: &Self) -> Option<Self> {
215 let (lo, hi) = self.boundaries();
216 let (other_lo, other_hi) = other.boundaries();
217 if lo <= other_hi && other_lo <= hi {
218 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), bias: self.bias })
219 } else {
220 None
221 }
222 }
223
224 fn suspicious_intersection(&self, other: &Self) -> bool {
225 // `false` in the following cases:
226 // 1 ---- // 1 ---------- // 1 ---- // 1 ----
227 // 2 ---------- // 2 ---- // 2 ---- // 2 ----
228 //
229 // The following are currently `false`, but could be `true` in the future (#64007):
230 // 1 --------- // 1 ---------
231 // 2 ---------- // 2 ----------
232 //
233 // `true` in the following cases:
234 // 1 ------- // 1 -------
235 // 2 -------- // 2 -------
236 let (lo, hi) = self.boundaries();
237 let (other_lo, other_hi) = other.boundaries();
238 (lo == other_hi || hi == other_lo) && !self.is_singleton() && !other.is_singleton()
239 }
240
241 /// Only used for displaying the range properly.
242 fn to_pat<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Pat<'tcx> {
243 let (lo, hi) = self.boundaries();
244
245 let bias = self.bias;
246 let (lo, hi) = (lo ^ bias, hi ^ bias);
247
248 let env = ty::ParamEnv::empty().and(ty);
249 let lo_const = mir::ConstantKind::from_bits(tcx, lo, env);
250 let hi_const = mir::ConstantKind::from_bits(tcx, hi, env);
251
252 let kind = if lo == hi {
253 PatKind::Constant { value: lo_const }
254 } else {
255 PatKind::Range(PatRange { lo: lo_const, hi: hi_const, end: RangeEnd::Included })
256 };
257
258 Pat { ty, span: DUMMY_SP, kind: Box::new(kind) }
259 }
260
261 /// Lint on likely incorrect range patterns (#63987)
262 pub(super) fn lint_overlapping_range_endpoints<'a, 'p: 'a, 'tcx: 'a>(
263 &self,
264 pcx: PatCtxt<'_, 'p, 'tcx>,
265 pats: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
266 column_count: usize,
267 hir_id: HirId,
268 ) {
269 if self.is_singleton() {
270 return;
271 }
272
273 if column_count != 1 {
274 // FIXME: for now, only check for overlapping ranges on simple range
275 // patterns. Otherwise with the current logic the following is detected
276 // as overlapping:
277 // ```
278 // match (0u8, true) {
279 // (0 ..= 125, false) => {}
280 // (125 ..= 255, true) => {}
281 // _ => {}
282 // }
283 // ```
284 return;
285 }
286
287 let overlaps: Vec<_> = pats
288 .filter_map(|pat| Some((pat.ctor().as_int_range()?, pat.span())))
289 .filter(|(range, _)| self.suspicious_intersection(range))
290 .map(|(range, span)| (self.intersection(&range).unwrap(), span))
291 .collect();
292
293 if !overlaps.is_empty() {
294 pcx.cx.tcx.struct_span_lint_hir(
295 lint::builtin::OVERLAPPING_RANGE_ENDPOINTS,
296 hir_id,
297 pcx.span,
298 |lint| {
299 let mut err = lint.build("multiple patterns overlap on their endpoints");
300 for (int_range, span) in overlaps {
301 err.span_label(
302 span,
303 &format!(
304 "this range overlaps on `{}`...",
305 int_range.to_pat(pcx.cx.tcx, pcx.ty)
306 ),
307 );
308 }
309 err.span_label(pcx.span, "... with this range");
310 err.note("you likely meant to write mutually exclusive ranges");
311 err.emit();
312 },
313 );
314 }
315 }
316
317 /// See `Constructor::is_covered_by`
318 fn is_covered_by(&self, other: &Self) -> bool {
319 if self.intersection(other).is_some() {
320 // Constructor splitting should ensure that all intersections we encounter are actually
321 // inclusions.
322 assert!(self.is_subrange(other));
323 true
324 } else {
325 false
326 }
327 }
328 }
329
330 /// Note: this is often not what we want: e.g. `false` is converted into the range `0..=0` and
331 /// would be displayed as such. To render properly, convert to a pattern first.
332 impl fmt::Debug for IntRange {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 let (lo, hi) = self.boundaries();
335 let bias = self.bias;
336 let (lo, hi) = (lo ^ bias, hi ^ bias);
337 write!(f, "{}", lo)?;
338 write!(f, "{}", RangeEnd::Included)?;
339 write!(f, "{}", hi)
340 }
341 }
342
343 /// Represents a border between 2 integers. Because the intervals spanning borders must be able to
344 /// cover every integer, we need to be able to represent 2^128 + 1 such borders.
345 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
346 enum IntBorder {
347 JustBefore(u128),
348 AfterMax,
349 }
350
351 /// A range of integers that is partitioned into disjoint subranges. This does constructor
352 /// splitting for integer ranges as explained at the top of the file.
353 ///
354 /// This is fed multiple ranges, and returns an output that covers the input, but is split so that
355 /// the only intersections between an output range and a seen range are inclusions. No output range
356 /// straddles the boundary of one of the inputs.
357 ///
358 /// The following input:
359 /// ```text
360 /// |-------------------------| // `self`
361 /// |------| |----------| |----|
362 /// |-------| |-------|
363 /// ```
364 /// would be iterated over as follows:
365 /// ```text
366 /// ||---|--||-|---|---|---|--|
367 /// ```
368 #[derive(Debug, Clone)]
369 struct SplitIntRange {
370 /// The range we are splitting
371 range: IntRange,
372 /// The borders of ranges we have seen. They are all contained within `range`. This is kept
373 /// sorted.
374 borders: Vec<IntBorder>,
375 }
376
377 impl SplitIntRange {
378 fn new(range: IntRange) -> Self {
379 SplitIntRange { range, borders: Vec::new() }
380 }
381
382 /// Internal use
383 fn to_borders(r: IntRange) -> [IntBorder; 2] {
384 use IntBorder::*;
385 let (lo, hi) = r.boundaries();
386 let lo = JustBefore(lo);
387 let hi = match hi.checked_add(1) {
388 Some(m) => JustBefore(m),
389 None => AfterMax,
390 };
391 [lo, hi]
392 }
393
394 /// Add ranges relative to which we split.
395 fn split(&mut self, ranges: impl Iterator<Item = IntRange>) {
396 let this_range = &self.range;
397 let included_ranges = ranges.filter_map(|r| this_range.intersection(&r));
398 let included_borders = included_ranges.flat_map(|r| {
399 let borders = Self::to_borders(r);
400 once(borders[0]).chain(once(borders[1]))
401 });
402 self.borders.extend(included_borders);
403 self.borders.sort_unstable();
404 }
405
406 /// Iterate over the contained ranges.
407 fn iter<'a>(&'a self) -> impl Iterator<Item = IntRange> + Captures<'a> {
408 use IntBorder::*;
409
410 let self_range = Self::to_borders(self.range.clone());
411 // Start with the start of the range.
412 let mut prev_border = self_range[0];
413 self.borders
414 .iter()
415 .copied()
416 // End with the end of the range.
417 .chain(once(self_range[1]))
418 // List pairs of adjacent borders.
419 .map(move |border| {
420 let ret = (prev_border, border);
421 prev_border = border;
422 ret
423 })
424 // Skip duplicates.
425 .filter(|(prev_border, border)| prev_border != border)
426 // Finally, convert to ranges.
427 .map(move |(prev_border, border)| {
428 let range = match (prev_border, border) {
429 (JustBefore(n), JustBefore(m)) if n < m => n..=(m - 1),
430 (JustBefore(n), AfterMax) => n..=u128::MAX,
431 _ => unreachable!(), // Ruled out by the sorting and filtering we did
432 };
433 IntRange { range, bias: self.range.bias }
434 })
435 }
436 }
437
438 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
439 enum SliceKind {
440 /// Patterns of length `n` (`[x, y]`).
441 FixedLen(usize),
442 /// Patterns using the `..` notation (`[x, .., y]`).
443 /// Captures any array constructor of `length >= i + j`.
444 /// In the case where `array_len` is `Some(_)`,
445 /// this indicates that we only care about the first `i` and the last `j` values of the array,
446 /// and everything in between is a wildcard `_`.
447 VarLen(usize, usize),
448 }
449
450 impl SliceKind {
451 fn arity(self) -> usize {
452 match self {
453 FixedLen(length) => length,
454 VarLen(prefix, suffix) => prefix + suffix,
455 }
456 }
457
458 /// Whether this pattern includes patterns of length `other_len`.
459 fn covers_length(self, other_len: usize) -> bool {
460 match self {
461 FixedLen(len) => len == other_len,
462 VarLen(prefix, suffix) => prefix + suffix <= other_len,
463 }
464 }
465 }
466
467 /// A constructor for array and slice patterns.
468 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
469 pub(super) struct Slice {
470 /// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`.
471 array_len: Option<usize>,
472 /// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`.
473 kind: SliceKind,
474 }
475
476 impl Slice {
477 fn new(array_len: Option<usize>, kind: SliceKind) -> Self {
478 let kind = match (array_len, kind) {
479 // If the middle `..` is empty, we effectively have a fixed-length pattern.
480 (Some(len), VarLen(prefix, suffix)) if prefix + suffix >= len => FixedLen(len),
481 _ => kind,
482 };
483 Slice { array_len, kind }
484 }
485
486 fn arity(self) -> usize {
487 self.kind.arity()
488 }
489
490 /// See `Constructor::is_covered_by`
491 fn is_covered_by(self, other: Self) -> bool {
492 other.kind.covers_length(self.arity())
493 }
494 }
495
496 /// This computes constructor splitting for variable-length slices, as explained at the top of the
497 /// file.
498 ///
499 /// A slice pattern `[x, .., y]` behaves like the infinite or-pattern `[x, y] | [x, _, y] | [x, _,
500 /// _, y] | ...`. The corresponding value constructors are fixed-length array constructors above a
501 /// given minimum length. We obviously can't list this infinitude of constructors. Thankfully,
502 /// it turns out that for each finite set of slice patterns, all sufficiently large array lengths
503 /// are equivalent.
504 ///
505 /// Let's look at an example, where we are trying to split the last pattern:
506 /// ```
507 /// # fn foo(x: &[bool]) {
508 /// match x {
509 /// [true, true, ..] => {}
510 /// [.., false, false] => {}
511 /// [..] => {}
512 /// }
513 /// # }
514 /// ```
515 /// Here are the results of specialization for the first few lengths:
516 /// ```
517 /// # fn foo(x: &[bool]) { match x {
518 /// // length 0
519 /// [] => {}
520 /// // length 1
521 /// [_] => {}
522 /// // length 2
523 /// [true, true] => {}
524 /// [false, false] => {}
525 /// [_, _] => {}
526 /// // length 3
527 /// [true, true, _ ] => {}
528 /// [_, false, false] => {}
529 /// [_, _, _ ] => {}
530 /// // length 4
531 /// [true, true, _, _ ] => {}
532 /// [_, _, false, false] => {}
533 /// [_, _, _, _ ] => {}
534 /// // length 5
535 /// [true, true, _, _, _ ] => {}
536 /// [_, _, _, false, false] => {}
537 /// [_, _, _, _, _ ] => {}
538 /// # _ => {}
539 /// # }}
540 /// ```
541 ///
542 /// If we went above length 5, we would simply be inserting more columns full of wildcards in the
543 /// middle. This means that the set of witnesses for length `l >= 5` if equivalent to the set for
544 /// any other `l' >= 5`: simply add or remove wildcards in the middle to convert between them.
545 ///
546 /// This applies to any set of slice patterns: there will be a length `L` above which all lengths
547 /// behave the same. This is exactly what we need for constructor splitting. Therefore a
548 /// variable-length slice can be split into a variable-length slice of minimal length `L`, and many
549 /// fixed-length slices of lengths `< L`.
550 ///
551 /// For each variable-length pattern `p` with a prefix of length `plâ‚š` and suffix of length `slâ‚š`,
552 /// only the first `plâ‚š` and the last `slâ‚š` elements are examined. Therefore, as long as `L` is
553 /// positive (to avoid concerns about empty types), all elements after the maximum prefix length
554 /// and before the maximum suffix length are not examined by any variable-length pattern, and
555 /// therefore can be added/removed without affecting them - creating equivalent patterns from any
556 /// sufficiently-large length.
557 ///
558 /// Of course, if fixed-length patterns exist, we must be sure that our length is large enough to
559 /// miss them all, so we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))`
560 ///
561 /// `max_slice` below will be made to have arity `L`.
562 #[derive(Debug)]
563 struct SplitVarLenSlice {
564 /// If the type is an array, this is its size.
565 array_len: Option<usize>,
566 /// The arity of the input slice.
567 arity: usize,
568 /// The smallest slice bigger than any slice seen. `max_slice.arity()` is the length `L`
569 /// described above.
570 max_slice: SliceKind,
571 }
572
573 impl SplitVarLenSlice {
574 fn new(prefix: usize, suffix: usize, array_len: Option<usize>) -> Self {
575 SplitVarLenSlice { array_len, arity: prefix + suffix, max_slice: VarLen(prefix, suffix) }
576 }
577
578 /// Pass a set of slices relative to which to split this one.
579 fn split(&mut self, slices: impl Iterator<Item = SliceKind>) {
580 let VarLen(max_prefix_len, max_suffix_len) = &mut self.max_slice else {
581 // No need to split
582 return;
583 };
584 // We grow `self.max_slice` to be larger than all slices encountered, as described above.
585 // For diagnostics, we keep the prefix and suffix lengths separate, but grow them so that
586 // `L = max_prefix_len + max_suffix_len`.
587 let mut max_fixed_len = 0;
588 for slice in slices {
589 match slice {
590 FixedLen(len) => {
591 max_fixed_len = cmp::max(max_fixed_len, len);
592 }
593 VarLen(prefix, suffix) => {
594 *max_prefix_len = cmp::max(*max_prefix_len, prefix);
595 *max_suffix_len = cmp::max(*max_suffix_len, suffix);
596 }
597 }
598 }
599 // We want `L = max(L, max_fixed_len + 1)`, modulo the fact that we keep prefix and
600 // suffix separate.
601 if max_fixed_len + 1 >= *max_prefix_len + *max_suffix_len {
602 // The subtraction can't overflow thanks to the above check.
603 // The new `max_prefix_len` is larger than its previous value.
604 *max_prefix_len = max_fixed_len + 1 - *max_suffix_len;
605 }
606
607 // We cap the arity of `max_slice` at the array size.
608 match self.array_len {
609 Some(len) if self.max_slice.arity() >= len => self.max_slice = FixedLen(len),
610 _ => {}
611 }
612 }
613
614 /// Iterate over the partition of this slice.
615 fn iter<'a>(&'a self) -> impl Iterator<Item = Slice> + Captures<'a> {
616 let smaller_lengths = match self.array_len {
617 // The only admissible fixed-length slice is one of the array size. Whether `max_slice`
618 // is fixed-length or variable-length, it will be the only relevant slice to output
619 // here.
620 Some(_) => (0..0), // empty range
621 // We cover all arities in the range `(self.arity..infinity)`. We split that range into
622 // two: lengths smaller than `max_slice.arity()` are treated independently as
623 // fixed-lengths slices, and lengths above are captured by `max_slice`.
624 None => self.arity..self.max_slice.arity(),
625 };
626 smaller_lengths
627 .map(FixedLen)
628 .chain(once(self.max_slice))
629 .map(move |kind| Slice::new(self.array_len, kind))
630 }
631 }
632
633 /// A value can be decomposed into a constructor applied to some fields. This struct represents
634 /// the constructor. See also `Fields`.
635 ///
636 /// `pat_constructor` retrieves the constructor corresponding to a pattern.
637 /// `specialize_constructor` returns the list of fields corresponding to a pattern, given a
638 /// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
639 /// `Fields`.
640 #[derive(Clone, Debug, PartialEq)]
641 pub(super) enum Constructor<'tcx> {
642 /// The constructor for patterns that have a single constructor, like tuples, struct patterns
643 /// and fixed-length arrays.
644 Single,
645 /// Enum variants.
646 Variant(VariantIdx),
647 /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
648 IntRange(IntRange),
649 /// Ranges of floating-point literal values (`2.0..=5.2`).
650 FloatRange(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>, RangeEnd),
651 /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
652 Str(mir::ConstantKind<'tcx>),
653 /// Array and slice patterns.
654 Slice(Slice),
655 /// Constants that must not be matched structurally. They are treated as black
656 /// boxes for the purposes of exhaustiveness: we must not inspect them, and they
657 /// don't count towards making a match exhaustive.
658 Opaque,
659 /// Fake extra constructor for enums that aren't allowed to be matched exhaustively. Also used
660 /// for those types for which we cannot list constructors explicitly, like `f64` and `str`.
661 NonExhaustive,
662 /// Stands for constructors that are not seen in the matrix, as explained in the documentation
663 /// for [`SplitWildcard`]. The carried `bool` is used for the `non_exhaustive_omitted_patterns`
664 /// lint.
665 Missing { nonexhaustive_enum_missing_real_variants: bool },
666 /// Wildcard pattern.
667 Wildcard,
668 /// Or-pattern.
669 Or,
670 }
671
672 impl<'tcx> Constructor<'tcx> {
673 pub(super) fn is_wildcard(&self) -> bool {
674 matches!(self, Wildcard)
675 }
676
677 pub(super) fn is_non_exhaustive(&self) -> bool {
678 matches!(self, NonExhaustive)
679 }
680
681 fn as_int_range(&self) -> Option<&IntRange> {
682 match self {
683 IntRange(range) => Some(range),
684 _ => None,
685 }
686 }
687
688 fn as_slice(&self) -> Option<Slice> {
689 match self {
690 Slice(slice) => Some(*slice),
691 _ => None,
692 }
693 }
694
695 /// Checks if the `Constructor` is a variant and `TyCtxt::eval_stability` returns
696 /// `EvalResult::Deny { .. }`.
697 ///
698 /// This means that the variant has a stdlib unstable feature marking it.
699 pub(super) fn is_unstable_variant(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> bool {
700 if let Constructor::Variant(idx) = self && let ty::Adt(adt, _) = pcx.ty.kind() {
701 let variant_def_id = adt.variant(*idx).def_id;
702 // Filter variants that depend on a disabled unstable feature.
703 return matches!(
704 pcx.cx.tcx.eval_stability(variant_def_id, None, DUMMY_SP, None),
705 EvalResult::Deny { .. }
706 );
707 }
708 false
709 }
710
711 /// Checks if the `Constructor` is a `Constructor::Variant` with a `#[doc(hidden)]`
712 /// attribute from a type not local to the current crate.
713 pub(super) fn is_doc_hidden_variant(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> bool {
714 if let Constructor::Variant(idx) = self && let ty::Adt(adt, _) = pcx.ty.kind() {
715 let variant_def_id = adt.variants()[*idx].def_id;
716 return pcx.cx.tcx.is_doc_hidden(variant_def_id) && !variant_def_id.is_local();
717 }
718 false
719 }
720
721 fn variant_index_for_adt(&self, adt: ty::AdtDef<'tcx>) -> VariantIdx {
722 match *self {
723 Variant(idx) => idx,
724 Single => {
725 assert!(!adt.is_enum());
726 VariantIdx::new(0)
727 }
728 _ => bug!("bad constructor {:?} for adt {:?}", self, adt),
729 }
730 }
731
732 /// The number of fields for this constructor. This must be kept in sync with
733 /// `Fields::wildcards`.
734 pub(super) fn arity(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> usize {
735 match self {
736 Single | Variant(_) => match pcx.ty.kind() {
737 ty::Tuple(fs) => fs.len(),
738 ty::Ref(..) => 1,
739 ty::Adt(adt, ..) => {
740 if adt.is_box() {
741 // The only legal patterns of type `Box` (outside `std`) are `_` and box
742 // patterns. If we're here we can assume this is a box pattern.
743 1
744 } else {
745 let variant = &adt.variant(self.variant_index_for_adt(*adt));
746 Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant).count()
747 }
748 }
749 _ => bug!("Unexpected type for `Single` constructor: {:?}", pcx.ty),
750 },
751 Slice(slice) => slice.arity(),
752 Str(..)
753 | FloatRange(..)
754 | IntRange(..)
755 | NonExhaustive
756 | Opaque
757 | Missing { .. }
758 | Wildcard => 0,
759 Or => bug!("The `Or` constructor doesn't have a fixed arity"),
760 }
761 }
762
763 /// Some constructors (namely `Wildcard`, `IntRange` and `Slice`) actually stand for a set of actual
764 /// constructors (like variants, integers or fixed-sized slices). When specializing for these
765 /// constructors, we want to be specialising for the actual underlying constructors.
766 /// Naively, we would simply return the list of constructors they correspond to. We instead are
767 /// more clever: if there are constructors that we know will behave the same wrt the current
768 /// matrix, we keep them grouped. For example, all slices of a sufficiently large length
769 /// will either be all useful or all non-useful with a given matrix.
770 ///
771 /// See the branches for details on how the splitting is done.
772 ///
773 /// This function may discard some irrelevant constructors if this preserves behavior and
774 /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the
775 /// matrix, unless all of them are.
776 pub(super) fn split<'a>(
777 &self,
778 pcx: PatCtxt<'_, '_, 'tcx>,
779 ctors: impl Iterator<Item = &'a Constructor<'tcx>> + Clone,
780 ) -> SmallVec<[Self; 1]>
781 where
782 'tcx: 'a,
783 {
784 match self {
785 Wildcard => {
786 let mut split_wildcard = SplitWildcard::new(pcx);
787 split_wildcard.split(pcx, ctors);
788 split_wildcard.into_ctors(pcx)
789 }
790 // Fast-track if the range is trivial. In particular, we don't do the overlapping
791 // ranges check.
792 IntRange(ctor_range) if !ctor_range.is_singleton() => {
793 let mut split_range = SplitIntRange::new(ctor_range.clone());
794 let int_ranges = ctors.filter_map(|ctor| ctor.as_int_range());
795 split_range.split(int_ranges.cloned());
796 split_range.iter().map(IntRange).collect()
797 }
798 &Slice(Slice { kind: VarLen(self_prefix, self_suffix), array_len }) => {
799 let mut split_self = SplitVarLenSlice::new(self_prefix, self_suffix, array_len);
800 let slices = ctors.filter_map(|c| c.as_slice()).map(|s| s.kind);
801 split_self.split(slices);
802 split_self.iter().map(Slice).collect()
803 }
804 // Any other constructor can be used unchanged.
805 _ => smallvec![self.clone()],
806 }
807 }
808
809 /// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`.
810 /// For the simple cases, this is simply checking for equality. For the "grouped" constructors,
811 /// this checks for inclusion.
812 // We inline because this has a single call site in `Matrix::specialize_constructor`.
813 #[inline]
814 pub(super) fn is_covered_by<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>, other: &Self) -> bool {
815 // This must be kept in sync with `is_covered_by_any`.
816 match (self, other) {
817 // Wildcards cover anything
818 (_, Wildcard) => true,
819 // The missing ctors are not covered by anything in the matrix except wildcards.
820 (Missing { .. } | Wildcard, _) => false,
821
822 (Single, Single) => true,
823 (Variant(self_id), Variant(other_id)) => self_id == other_id,
824
825 (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range),
826 (
827 FloatRange(self_from, self_to, self_end),
828 FloatRange(other_from, other_to, other_end),
829 ) => {
830 match (
831 compare_const_vals(pcx.cx.tcx, *self_to, *other_to, pcx.cx.param_env),
832 compare_const_vals(pcx.cx.tcx, *self_from, *other_from, pcx.cx.param_env),
833 ) {
834 (Some(to), Some(from)) => {
835 (from == Ordering::Greater || from == Ordering::Equal)
836 && (to == Ordering::Less
837 || (other_end == self_end && to == Ordering::Equal))
838 }
839 _ => false,
840 }
841 }
842 (Str(self_val), Str(other_val)) => {
843 // FIXME Once valtrees are available we can directly use the bytes
844 // in the `Str` variant of the valtree for the comparison here.
845 self_val == other_val
846 }
847 (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
848
849 // We are trying to inspect an opaque constant. Thus we skip the row.
850 (Opaque, _) | (_, Opaque) => false,
851 // Only a wildcard pattern can match the special extra constructor.
852 (NonExhaustive, _) => false,
853
854 _ => span_bug!(
855 pcx.span,
856 "trying to compare incompatible constructors {:?} and {:?}",
857 self,
858 other
859 ),
860 }
861 }
862
863 /// Faster version of `is_covered_by` when applied to many constructors. `used_ctors` is
864 /// assumed to be built from `matrix.head_ctors()` with wildcards filtered out, and `self` is
865 /// assumed to have been split from a wildcard.
866 fn is_covered_by_any<'p>(
867 &self,
868 pcx: PatCtxt<'_, 'p, 'tcx>,
869 used_ctors: &[Constructor<'tcx>],
870 ) -> bool {
871 if used_ctors.is_empty() {
872 return false;
873 }
874
875 // This must be kept in sync with `is_covered_by`.
876 match self {
877 // If `self` is `Single`, `used_ctors` cannot contain anything else than `Single`s.
878 Single => !used_ctors.is_empty(),
879 Variant(vid) => used_ctors.iter().any(|c| matches!(c, Variant(i) if i == vid)),
880 IntRange(range) => used_ctors
881 .iter()
882 .filter_map(|c| c.as_int_range())
883 .any(|other| range.is_covered_by(other)),
884 Slice(slice) => used_ctors
885 .iter()
886 .filter_map(|c| c.as_slice())
887 .any(|other| slice.is_covered_by(other)),
888 // This constructor is never covered by anything else
889 NonExhaustive => false,
890 Str(..) | FloatRange(..) | Opaque | Missing { .. } | Wildcard | Or => {
891 span_bug!(pcx.span, "found unexpected ctor in all_ctors: {:?}", self)
892 }
893 }
894 }
895 }
896
897 /// A wildcard constructor that we split relative to the constructors in the matrix, as explained
898 /// at the top of the file.
899 ///
900 /// A constructor that is not present in the matrix rows will only be covered by the rows that have
901 /// wildcards. Thus we can group all of those constructors together; we call them "missing
902 /// constructors". Splitting a wildcard would therefore list all present constructors individually
903 /// (or grouped if they are integers or slices), and then all missing constructors together as a
904 /// group.
905 ///
906 /// However we can go further: since any constructor will match the wildcard rows, and having more
907 /// rows can only reduce the amount of usefulness witnesses, we can skip the present constructors
908 /// and only try the missing ones.
909 /// This will not preserve the whole list of witnesses, but will preserve whether the list is empty
910 /// or not. In fact this is quite natural from the point of view of diagnostics too. This is done
911 /// in `to_ctors`: in some cases we only return `Missing`.
912 #[derive(Debug)]
913 pub(super) struct SplitWildcard<'tcx> {
914 /// Constructors seen in the matrix.
915 matrix_ctors: Vec<Constructor<'tcx>>,
916 /// All the constructors for this type
917 all_ctors: SmallVec<[Constructor<'tcx>; 1]>,
918 }
919
920 impl<'tcx> SplitWildcard<'tcx> {
921 pub(super) fn new<'p>(pcx: PatCtxt<'_, 'p, 'tcx>) -> Self {
922 debug!("SplitWildcard::new({:?})", pcx.ty);
923 let cx = pcx.cx;
924 let make_range = |start, end| {
925 IntRange(
926 // `unwrap()` is ok because we know the type is an integer.
927 IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included).unwrap(),
928 )
929 };
930 // This determines the set of all possible constructors for the type `pcx.ty`. For numbers,
931 // arrays and slices we use ranges and variable-length slices when appropriate.
932 //
933 // If the `exhaustive_patterns` feature is enabled, we make sure to omit constructors that
934 // are statically impossible. E.g., for `Option<!>`, we do not include `Some(_)` in the
935 // returned list of constructors.
936 // Invariant: this is empty if and only if the type is uninhabited (as determined by
937 // `cx.is_uninhabited()`).
938 let all_ctors = match pcx.ty.kind() {
939 ty::Bool => smallvec![make_range(0, 1)],
940 ty::Array(sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => {
941 let len = len.eval_usize(cx.tcx, cx.param_env) as usize;
942 if len != 0 && cx.is_uninhabited(*sub_ty) {
943 smallvec![]
944 } else {
945 smallvec![Slice(Slice::new(Some(len), VarLen(0, 0)))]
946 }
947 }
948 // Treat arrays of a constant but unknown length like slices.
949 ty::Array(sub_ty, _) | ty::Slice(sub_ty) => {
950 let kind = if cx.is_uninhabited(*sub_ty) { FixedLen(0) } else { VarLen(0, 0) };
951 smallvec![Slice(Slice::new(None, kind))]
952 }
953 ty::Adt(def, substs) if def.is_enum() => {
954 // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
955 // additional "unknown" constructor.
956 // There is no point in enumerating all possible variants, because the user can't
957 // actually match against them all themselves. So we always return only the fictitious
958 // constructor.
959 // E.g., in an example like:
960 //
961 // ```
962 // let err: io::ErrorKind = ...;
963 // match err {
964 // io::ErrorKind::NotFound => {},
965 // }
966 // ```
967 //
968 // we don't want to show every possible IO error, but instead have only `_` as the
969 // witness.
970 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
971
972 let is_exhaustive_pat_feature = cx.tcx.features().exhaustive_patterns;
973
974 // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
975 // as though it had an "unknown" constructor to avoid exposing its emptiness. The
976 // exception is if the pattern is at the top level, because we want empty matches to be
977 // considered exhaustive.
978 let is_secretly_empty =
979 def.variants().is_empty() && !is_exhaustive_pat_feature && !pcx.is_top_level;
980
981 let mut ctors: SmallVec<[_; 1]> = def
982 .variants()
983 .iter_enumerated()
984 .filter(|(_, v)| {
985 // If `exhaustive_patterns` is enabled, we exclude variants known to be
986 // uninhabited.
987 let is_uninhabited = is_exhaustive_pat_feature
988 && v.uninhabited_from(cx.tcx, substs, def.adt_kind(), cx.param_env)
989 .contains(cx.tcx, cx.module);
990 !is_uninhabited
991 })
992 .map(|(idx, _)| Variant(idx))
993 .collect();
994
995 if is_secretly_empty || is_declared_nonexhaustive {
996 ctors.push(NonExhaustive);
997 }
998 ctors
999 }
1000 ty::Char => {
1001 smallvec![
1002 // The valid Unicode Scalar Value ranges.
1003 make_range('\u{0000}' as u128, '\u{D7FF}' as u128),
1004 make_range('\u{E000}' as u128, '\u{10FFFF}' as u128),
1005 ]
1006 }
1007 ty::Int(_) | ty::Uint(_)
1008 if pcx.ty.is_ptr_sized_integral()
1009 && !cx.tcx.features().precise_pointer_size_matching =>
1010 {
1011 // `usize`/`isize` are not allowed to be matched exhaustively unless the
1012 // `precise_pointer_size_matching` feature is enabled. So we treat those types like
1013 // `#[non_exhaustive]` enums by returning a special unmatchable constructor.
1014 smallvec![NonExhaustive]
1015 }
1016 &ty::Int(ity) => {
1017 let bits = Integer::from_int_ty(&cx.tcx, ity).size().bits() as u128;
1018 let min = 1u128 << (bits - 1);
1019 let max = min - 1;
1020 smallvec![make_range(min, max)]
1021 }
1022 &ty::Uint(uty) => {
1023 let size = Integer::from_uint_ty(&cx.tcx, uty).size();
1024 let max = size.truncate(u128::MAX);
1025 smallvec![make_range(0, max)]
1026 }
1027 // If `exhaustive_patterns` is disabled and our scrutinee is the never type, we cannot
1028 // expose its emptiness. The exception is if the pattern is at the top level, because we
1029 // want empty matches to be considered exhaustive.
1030 ty::Never if !cx.tcx.features().exhaustive_patterns && !pcx.is_top_level => {
1031 smallvec![NonExhaustive]
1032 }
1033 ty::Never => smallvec![],
1034 _ if cx.is_uninhabited(pcx.ty) => smallvec![],
1035 ty::Adt(..) | ty::Tuple(..) | ty::Ref(..) => smallvec![Single],
1036 // This type is one for which we cannot list constructors, like `str` or `f64`.
1037 _ => smallvec![NonExhaustive],
1038 };
1039
1040 SplitWildcard { matrix_ctors: Vec::new(), all_ctors }
1041 }
1042
1043 /// Pass a set of constructors relative to which to split this one. Don't call twice, it won't
1044 /// do what you want.
1045 pub(super) fn split<'a>(
1046 &mut self,
1047 pcx: PatCtxt<'_, '_, 'tcx>,
1048 ctors: impl Iterator<Item = &'a Constructor<'tcx>> + Clone,
1049 ) where
1050 'tcx: 'a,
1051 {
1052 // Since `all_ctors` never contains wildcards, this won't recurse further.
1053 self.all_ctors =
1054 self.all_ctors.iter().flat_map(|ctor| ctor.split(pcx, ctors.clone())).collect();
1055 self.matrix_ctors = ctors.filter(|c| !c.is_wildcard()).cloned().collect();
1056 }
1057
1058 /// Whether there are any value constructors for this type that are not present in the matrix.
1059 fn any_missing(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> bool {
1060 self.iter_missing(pcx).next().is_some()
1061 }
1062
1063 /// Iterate over the constructors for this type that are not present in the matrix.
1064 pub(super) fn iter_missing<'a, 'p>(
1065 &'a self,
1066 pcx: PatCtxt<'a, 'p, 'tcx>,
1067 ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'p> {
1068 self.all_ctors.iter().filter(move |ctor| !ctor.is_covered_by_any(pcx, &self.matrix_ctors))
1069 }
1070
1071 /// Return the set of constructors resulting from splitting the wildcard. As explained at the
1072 /// top of the file, if any constructors are missing we can ignore the present ones.
1073 fn into_ctors(self, pcx: PatCtxt<'_, '_, 'tcx>) -> SmallVec<[Constructor<'tcx>; 1]> {
1074 if self.any_missing(pcx) {
1075 // Some constructors are missing, thus we can specialize with the special `Missing`
1076 // constructor, which stands for those constructors that are not seen in the matrix,
1077 // and matches the same rows as any of them (namely the wildcard rows). See the top of
1078 // the file for details.
1079 // However, when all constructors are missing we can also specialize with the full
1080 // `Wildcard` constructor. The difference will depend on what we want in diagnostics.
1081
1082 // If some constructors are missing, we typically want to report those constructors,
1083 // e.g.:
1084 // ```
1085 // enum Direction { N, S, E, W }
1086 // let Direction::N = ...;
1087 // ```
1088 // we can report 3 witnesses: `S`, `E`, and `W`.
1089 //
1090 // However, if the user didn't actually specify a constructor
1091 // in this arm, e.g., in
1092 // ```
1093 // let x: (Direction, Direction, bool) = ...;
1094 // let (_, _, false) = x;
1095 // ```
1096 // we don't want to show all 16 possible witnesses `(<direction-1>, <direction-2>,
1097 // true)` - we are satisfied with `(_, _, true)`. So if all constructors are missing we
1098 // prefer to report just a wildcard `_`.
1099 //
1100 // The exception is: if we are at the top-level, for example in an empty match, we
1101 // sometimes prefer reporting the list of constructors instead of just `_`.
1102 let report_when_all_missing = pcx.is_top_level && !IntRange::is_integral(pcx.ty);
1103 let ctor = if !self.matrix_ctors.is_empty() || report_when_all_missing {
1104 if pcx.is_non_exhaustive {
1105 Missing {
1106 nonexhaustive_enum_missing_real_variants: self
1107 .iter_missing(pcx)
1108 .any(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx))),
1109 }
1110 } else {
1111 Missing { nonexhaustive_enum_missing_real_variants: false }
1112 }
1113 } else {
1114 Wildcard
1115 };
1116 return smallvec![ctor];
1117 }
1118
1119 // All the constructors are present in the matrix, so we just go through them all.
1120 self.all_ctors
1121 }
1122 }
1123
1124 /// A value can be decomposed into a constructor applied to some fields. This struct represents
1125 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
1126 ///
1127 /// This is constructed for a constructor using [`Fields::wildcards()`]. The idea is that
1128 /// [`Fields::wildcards()`] constructs a list of fields where all entries are wildcards, and then
1129 /// given a pattern we fill some of the fields with its subpatterns.
1130 /// In the following example `Fields::wildcards` returns `[_, _, _, _]`. Then in
1131 /// `extract_pattern_arguments` we fill some of the entries, and the result is
1132 /// `[Some(0), _, _, _]`.
1133 /// ```compile_fail,E0004
1134 /// # fn foo() -> [Option<u8>; 4] { [None; 4] }
1135 /// let x: [Option<u8>; 4] = foo();
1136 /// match x {
1137 /// [Some(0), ..] => {}
1138 /// }
1139 /// ```
1140 ///
1141 /// Note that the number of fields of a constructor may not match the fields declared in the
1142 /// original struct/variant. This happens if a private or `non_exhaustive` field is uninhabited,
1143 /// because the code mustn't observe that it is uninhabited. In that case that field is not
1144 /// included in `fields`. For that reason, when you have a `mir::Field` you must use
1145 /// `index_with_declared_idx`.
1146 #[derive(Debug, Clone, Copy)]
1147 pub(super) struct Fields<'p, 'tcx> {
1148 fields: &'p [DeconstructedPat<'p, 'tcx>],
1149 }
1150
1151 impl<'p, 'tcx> Fields<'p, 'tcx> {
1152 fn empty() -> Self {
1153 Fields { fields: &[] }
1154 }
1155
1156 fn singleton(cx: &MatchCheckCtxt<'p, 'tcx>, field: DeconstructedPat<'p, 'tcx>) -> Self {
1157 let field: &_ = cx.pattern_arena.alloc(field);
1158 Fields { fields: std::slice::from_ref(field) }
1159 }
1160
1161 pub(super) fn from_iter(
1162 cx: &MatchCheckCtxt<'p, 'tcx>,
1163 fields: impl IntoIterator<Item = DeconstructedPat<'p, 'tcx>>,
1164 ) -> Self {
1165 let fields: &[_] = cx.pattern_arena.alloc_from_iter(fields);
1166 Fields { fields }
1167 }
1168
1169 fn wildcards_from_tys(
1170 cx: &MatchCheckCtxt<'p, 'tcx>,
1171 tys: impl IntoIterator<Item = Ty<'tcx>>,
1172 ) -> Self {
1173 Fields::from_iter(cx, tys.into_iter().map(DeconstructedPat::wildcard))
1174 }
1175
1176 // In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide
1177 // uninhabited fields in order not to reveal the uninhabitedness of the whole variant.
1178 // This lists the fields we keep along with their types.
1179 fn list_variant_nonhidden_fields<'a>(
1180 cx: &'a MatchCheckCtxt<'p, 'tcx>,
1181 ty: Ty<'tcx>,
1182 variant: &'a VariantDef,
1183 ) -> impl Iterator<Item = (Field, Ty<'tcx>)> + Captures<'a> + Captures<'p> {
1184 let ty::Adt(adt, substs) = ty.kind() else { bug!() };
1185 // Whether we must not match the fields of this variant exhaustively.
1186 let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did().is_local();
1187
1188 variant.fields.iter().enumerate().filter_map(move |(i, field)| {
1189 let ty = field.ty(cx.tcx, substs);
1190 // `field.ty()` doesn't normalize after substituting.
1191 let ty = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
1192 let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx);
1193 let is_uninhabited = cx.is_uninhabited(ty);
1194
1195 if is_uninhabited && (!is_visible || is_non_exhaustive) {
1196 None
1197 } else {
1198 Some((Field::new(i), ty))
1199 }
1200 })
1201 }
1202
1203 /// Creates a new list of wildcard fields for a given constructor. The result must have a
1204 /// length of `constructor.arity()`.
1205 pub(super) fn wildcards(
1206 cx: &MatchCheckCtxt<'p, 'tcx>,
1207 ty: Ty<'tcx>,
1208 constructor: &Constructor<'tcx>,
1209 ) -> Self {
1210 let ret = match constructor {
1211 Single | Variant(_) => match ty.kind() {
1212 ty::Tuple(fs) => Fields::wildcards_from_tys(cx, fs.iter()),
1213 ty::Ref(_, rty, _) => Fields::wildcards_from_tys(cx, once(*rty)),
1214 ty::Adt(adt, substs) => {
1215 if adt.is_box() {
1216 // The only legal patterns of type `Box` (outside `std`) are `_` and box
1217 // patterns. If we're here we can assume this is a box pattern.
1218 Fields::wildcards_from_tys(cx, once(substs.type_at(0)))
1219 } else {
1220 let variant = &adt.variant(constructor.variant_index_for_adt(*adt));
1221 let tys = Fields::list_variant_nonhidden_fields(cx, ty, variant)
1222 .map(|(_, ty)| ty);
1223 Fields::wildcards_from_tys(cx, tys)
1224 }
1225 }
1226 _ => bug!("Unexpected type for `Single` constructor: {:?}", ty),
1227 },
1228 Slice(slice) => match *ty.kind() {
1229 ty::Slice(ty) | ty::Array(ty, _) => {
1230 let arity = slice.arity();
1231 Fields::wildcards_from_tys(cx, (0..arity).map(|_| ty))
1232 }
1233 _ => bug!("bad slice pattern {:?} {:?}", constructor, ty),
1234 },
1235 Str(..)
1236 | FloatRange(..)
1237 | IntRange(..)
1238 | NonExhaustive
1239 | Opaque
1240 | Missing { .. }
1241 | Wildcard => Fields::empty(),
1242 Or => {
1243 bug!("called `Fields::wildcards` on an `Or` ctor")
1244 }
1245 };
1246 debug!("Fields::wildcards({:?}, {:?}) = {:#?}", constructor, ty, ret);
1247 ret
1248 }
1249
1250 /// Returns the list of patterns.
1251 pub(super) fn iter_patterns<'a>(
1252 &'a self,
1253 ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a> {
1254 self.fields.iter()
1255 }
1256 }
1257
1258 /// Values and patterns can be represented as a constructor applied to some fields. This represents
1259 /// a pattern in this form.
1260 /// This also keeps track of whether the pattern has been found reachable during analysis. For this
1261 /// reason we should be careful not to clone patterns for which we care about that. Use
1262 /// `clone_and_forget_reachability` if you're sure.
1263 pub(crate) struct DeconstructedPat<'p, 'tcx> {
1264 ctor: Constructor<'tcx>,
1265 fields: Fields<'p, 'tcx>,
1266 ty: Ty<'tcx>,
1267 span: Span,
1268 reachable: Cell<bool>,
1269 }
1270
1271 impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> {
1272 pub(super) fn wildcard(ty: Ty<'tcx>) -> Self {
1273 Self::new(Wildcard, Fields::empty(), ty, DUMMY_SP)
1274 }
1275
1276 pub(super) fn new(
1277 ctor: Constructor<'tcx>,
1278 fields: Fields<'p, 'tcx>,
1279 ty: Ty<'tcx>,
1280 span: Span,
1281 ) -> Self {
1282 DeconstructedPat { ctor, fields, ty, span, reachable: Cell::new(false) }
1283 }
1284
1285 /// Construct a pattern that matches everything that starts with this constructor.
1286 /// For example, if `ctor` is a `Constructor::Variant` for `Option::Some`, we get the pattern
1287 /// `Some(_)`.
1288 pub(super) fn wild_from_ctor(pcx: PatCtxt<'_, 'p, 'tcx>, ctor: Constructor<'tcx>) -> Self {
1289 let fields = Fields::wildcards(pcx.cx, pcx.ty, &ctor);
1290 DeconstructedPat::new(ctor, fields, pcx.ty, DUMMY_SP)
1291 }
1292
1293 /// Clone this value. This method emphasizes that cloning loses reachability information and
1294 /// should be done carefully.
1295 pub(super) fn clone_and_forget_reachability(&self) -> Self {
1296 DeconstructedPat::new(self.ctor.clone(), self.fields, self.ty, self.span)
1297 }
1298
1299 pub(crate) fn from_pat(cx: &MatchCheckCtxt<'p, 'tcx>, pat: &Pat<'tcx>) -> Self {
1300 let mkpat = |pat| DeconstructedPat::from_pat(cx, pat);
1301 let ctor;
1302 let fields;
1303 match pat.kind.as_ref() {
1304 PatKind::AscribeUserType { subpattern, .. } => return mkpat(subpattern),
1305 PatKind::Binding { subpattern: Some(subpat), .. } => return mkpat(subpat),
1306 PatKind::Binding { subpattern: None, .. } | PatKind::Wild => {
1307 ctor = Wildcard;
1308 fields = Fields::empty();
1309 }
1310 PatKind::Deref { subpattern } => {
1311 ctor = Single;
1312 fields = Fields::singleton(cx, mkpat(subpattern));
1313 }
1314 PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
1315 match pat.ty.kind() {
1316 ty::Tuple(fs) => {
1317 ctor = Single;
1318 let mut wilds: SmallVec<[_; 2]> =
1319 fs.iter().map(DeconstructedPat::wildcard).collect();
1320 for pat in subpatterns {
1321 wilds[pat.field.index()] = mkpat(&pat.pattern);
1322 }
1323 fields = Fields::from_iter(cx, wilds);
1324 }
1325 ty::Adt(adt, substs) if adt.is_box() => {
1326 // The only legal patterns of type `Box` (outside `std`) are `_` and box
1327 // patterns. If we're here we can assume this is a box pattern.
1328 // FIXME(Nadrieril): A `Box` can in theory be matched either with `Box(_,
1329 // _)` or a box pattern. As a hack to avoid an ICE with the former, we
1330 // ignore other fields than the first one. This will trigger an error later
1331 // anyway.
1332 // See https://github.com/rust-lang/rust/issues/82772 ,
1333 // explanation: https://github.com/rust-lang/rust/pull/82789#issuecomment-796921977
1334 // The problem is that we can't know from the type whether we'll match
1335 // normally or through box-patterns. We'll have to figure out a proper
1336 // solution when we introduce generalized deref patterns. Also need to
1337 // prevent mixing of those two options.
1338 let pat = subpatterns.into_iter().find(|pat| pat.field.index() == 0);
1339 let pat = if let Some(pat) = pat {
1340 mkpat(&pat.pattern)
1341 } else {
1342 DeconstructedPat::wildcard(substs.type_at(0))
1343 };
1344 ctor = Single;
1345 fields = Fields::singleton(cx, pat);
1346 }
1347 ty::Adt(adt, _) => {
1348 ctor = match pat.kind.as_ref() {
1349 PatKind::Leaf { .. } => Single,
1350 PatKind::Variant { variant_index, .. } => Variant(*variant_index),
1351 _ => bug!(),
1352 };
1353 let variant = &adt.variant(ctor.variant_index_for_adt(*adt));
1354 // For each field in the variant, we store the relevant index into `self.fields` if any.
1355 let mut field_id_to_id: Vec<Option<usize>> =
1356 (0..variant.fields.len()).map(|_| None).collect();
1357 let tys = Fields::list_variant_nonhidden_fields(cx, pat.ty, variant)
1358 .enumerate()
1359 .map(|(i, (field, ty))| {
1360 field_id_to_id[field.index()] = Some(i);
1361 ty
1362 });
1363 let mut wilds: SmallVec<[_; 2]> =
1364 tys.map(DeconstructedPat::wildcard).collect();
1365 for pat in subpatterns {
1366 if let Some(i) = field_id_to_id[pat.field.index()] {
1367 wilds[i] = mkpat(&pat.pattern);
1368 }
1369 }
1370 fields = Fields::from_iter(cx, wilds);
1371 }
1372 _ => bug!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, pat.ty),
1373 }
1374 }
1375 PatKind::Constant { value } => {
1376 if let Some(int_range) = IntRange::from_constant(cx.tcx, cx.param_env, *value) {
1377 ctor = IntRange(int_range);
1378 fields = Fields::empty();
1379 } else {
1380 match pat.ty.kind() {
1381 ty::Float(_) => {
1382 ctor = FloatRange(*value, *value, RangeEnd::Included);
1383 fields = Fields::empty();
1384 }
1385 ty::Ref(_, t, _) if t.is_str() => {
1386 // We want a `&str` constant to behave like a `Deref` pattern, to be compatible
1387 // with other `Deref` patterns. This could have been done in `const_to_pat`,
1388 // but that causes issues with the rest of the matching code.
1389 // So here, the constructor for a `"foo"` pattern is `&` (represented by
1390 // `Single`), and has one field. That field has constructor `Str(value)` and no
1391 // fields.
1392 // Note: `t` is `str`, not `&str`.
1393 let subpattern =
1394 DeconstructedPat::new(Str(*value), Fields::empty(), *t, pat.span);
1395 ctor = Single;
1396 fields = Fields::singleton(cx, subpattern)
1397 }
1398 // All constants that can be structurally matched have already been expanded
1399 // into the corresponding `Pat`s by `const_to_pat`. Constants that remain are
1400 // opaque.
1401 _ => {
1402 ctor = Opaque;
1403 fields = Fields::empty();
1404 }
1405 }
1406 }
1407 }
1408 &PatKind::Range(PatRange { lo, hi, end }) => {
1409 let ty = lo.ty();
1410 ctor = if let Some(int_range) = IntRange::from_range(
1411 cx.tcx,
1412 lo.eval_bits(cx.tcx, cx.param_env, lo.ty()),
1413 hi.eval_bits(cx.tcx, cx.param_env, hi.ty()),
1414 ty,
1415 &end,
1416 ) {
1417 IntRange(int_range)
1418 } else {
1419 FloatRange(lo, hi, end)
1420 };
1421 fields = Fields::empty();
1422 }
1423 PatKind::Array { prefix, slice, suffix } | PatKind::Slice { prefix, slice, suffix } => {
1424 let array_len = match pat.ty.kind() {
1425 ty::Array(_, length) => Some(length.eval_usize(cx.tcx, cx.param_env) as usize),
1426 ty::Slice(_) => None,
1427 _ => span_bug!(pat.span, "bad ty {:?} for slice pattern", pat.ty),
1428 };
1429 let kind = if slice.is_some() {
1430 VarLen(prefix.len(), suffix.len())
1431 } else {
1432 FixedLen(prefix.len() + suffix.len())
1433 };
1434 ctor = Slice(Slice::new(array_len, kind));
1435 fields = Fields::from_iter(cx, prefix.iter().chain(suffix).map(mkpat));
1436 }
1437 PatKind::Or { .. } => {
1438 ctor = Or;
1439 let pats = expand_or_pat(pat);
1440 fields = Fields::from_iter(cx, pats.into_iter().map(mkpat));
1441 }
1442 }
1443 DeconstructedPat::new(ctor, fields, pat.ty, pat.span)
1444 }
1445
1446 pub(crate) fn to_pat(&self, cx: &MatchCheckCtxt<'p, 'tcx>) -> Pat<'tcx> {
1447 let is_wildcard = |pat: &Pat<'_>| {
1448 matches!(*pat.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild)
1449 };
1450 let mut subpatterns = self.iter_fields().map(|p| p.to_pat(cx));
1451 let pat = match &self.ctor {
1452 Single | Variant(_) => match self.ty.kind() {
1453 ty::Tuple(..) => PatKind::Leaf {
1454 subpatterns: subpatterns
1455 .enumerate()
1456 .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
1457 .collect(),
1458 },
1459 ty::Adt(adt_def, _) if adt_def.is_box() => {
1460 // Without `box_patterns`, the only legal pattern of type `Box` is `_` (outside
1461 // of `std`). So this branch is only reachable when the feature is enabled and
1462 // the pattern is a box pattern.
1463 PatKind::Deref { subpattern: subpatterns.next().unwrap() }
1464 }
1465 ty::Adt(adt_def, substs) => {
1466 let variant_index = self.ctor.variant_index_for_adt(*adt_def);
1467 let variant = &adt_def.variant(variant_index);
1468 let subpatterns = Fields::list_variant_nonhidden_fields(cx, self.ty, variant)
1469 .zip(subpatterns)
1470 .map(|((field, _ty), pattern)| FieldPat { field, pattern })
1471 .collect();
1472
1473 if adt_def.is_enum() {
1474 PatKind::Variant { adt_def: *adt_def, substs, variant_index, subpatterns }
1475 } else {
1476 PatKind::Leaf { subpatterns }
1477 }
1478 }
1479 // Note: given the expansion of `&str` patterns done in `expand_pattern`, we should
1480 // be careful to reconstruct the correct constant pattern here. However a string
1481 // literal pattern will never be reported as a non-exhaustiveness witness, so we
1482 // ignore this issue.
1483 ty::Ref(..) => PatKind::Deref { subpattern: subpatterns.next().unwrap() },
1484 _ => bug!("unexpected ctor for type {:?} {:?}", self.ctor, self.ty),
1485 },
1486 Slice(slice) => {
1487 match slice.kind {
1488 FixedLen(_) => PatKind::Slice {
1489 prefix: subpatterns.collect(),
1490 slice: None,
1491 suffix: vec![],
1492 },
1493 VarLen(prefix, _) => {
1494 let mut subpatterns = subpatterns.peekable();
1495 let mut prefix: Vec<_> = subpatterns.by_ref().take(prefix).collect();
1496 if slice.array_len.is_some() {
1497 // Improves diagnostics a bit: if the type is a known-size array, instead
1498 // of reporting `[x, _, .., _, y]`, we prefer to report `[x, .., y]`.
1499 // This is incorrect if the size is not known, since `[_, ..]` captures
1500 // arrays of lengths `>= 1` whereas `[..]` captures any length.
1501 while !prefix.is_empty() && is_wildcard(prefix.last().unwrap()) {
1502 prefix.pop();
1503 }
1504 while subpatterns.peek().is_some()
1505 && is_wildcard(subpatterns.peek().unwrap())
1506 {
1507 subpatterns.next();
1508 }
1509 }
1510 let suffix: Vec<_> = subpatterns.collect();
1511 let wild = Pat::wildcard_from_ty(self.ty);
1512 PatKind::Slice { prefix, slice: Some(wild), suffix }
1513 }
1514 }
1515 }
1516 &Str(value) => PatKind::Constant { value },
1517 &FloatRange(lo, hi, end) => PatKind::Range(PatRange { lo, hi, end }),
1518 IntRange(range) => return range.to_pat(cx.tcx, self.ty),
1519 Wildcard | NonExhaustive => PatKind::Wild,
1520 Missing { .. } => bug!(
1521 "trying to convert a `Missing` constructor into a `Pat`; this is probably a bug,
1522 `Missing` should have been processed in `apply_constructors`"
1523 ),
1524 Opaque | Or => {
1525 bug!("can't convert to pattern: {:?}", self)
1526 }
1527 };
1528
1529 Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(pat) }
1530 }
1531
1532 pub(super) fn is_or_pat(&self) -> bool {
1533 matches!(self.ctor, Or)
1534 }
1535
1536 pub(super) fn ctor(&self) -> &Constructor<'tcx> {
1537 &self.ctor
1538 }
1539 pub(super) fn ty(&self) -> Ty<'tcx> {
1540 self.ty
1541 }
1542 pub(super) fn span(&self) -> Span {
1543 self.span
1544 }
1545
1546 pub(super) fn iter_fields<'a>(
1547 &'a self,
1548 ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a> {
1549 self.fields.iter_patterns()
1550 }
1551
1552 /// Specialize this pattern with a constructor.
1553 /// `other_ctor` can be different from `self.ctor`, but must be covered by it.
1554 pub(super) fn specialize<'a>(
1555 &'a self,
1556 cx: &MatchCheckCtxt<'p, 'tcx>,
1557 other_ctor: &Constructor<'tcx>,
1558 ) -> SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]> {
1559 match (&self.ctor, other_ctor) {
1560 (Wildcard, _) => {
1561 // We return a wildcard for each field of `other_ctor`.
1562 Fields::wildcards(cx, self.ty, other_ctor).iter_patterns().collect()
1563 }
1564 (Slice(self_slice), Slice(other_slice))
1565 if self_slice.arity() != other_slice.arity() =>
1566 {
1567 // The only tricky case: two slices of different arity. Since `self_slice` covers
1568 // `other_slice`, `self_slice` must be `VarLen`, i.e. of the form
1569 // `[prefix, .., suffix]`. Moreover `other_slice` is guaranteed to have a larger
1570 // arity. So we fill the middle part with enough wildcards to reach the length of
1571 // the new, larger slice.
1572 match self_slice.kind {
1573 FixedLen(_) => bug!("{:?} doesn't cover {:?}", self_slice, other_slice),
1574 VarLen(prefix, suffix) => {
1575 let (ty::Slice(inner_ty) | ty::Array(inner_ty, _)) = *self.ty.kind() else {
1576 bug!("bad slice pattern {:?} {:?}", self.ctor, self.ty);
1577 };
1578 let prefix = &self.fields.fields[..prefix];
1579 let suffix = &self.fields.fields[self_slice.arity() - suffix..];
1580 let wildcard: &_ =
1581 cx.pattern_arena.alloc(DeconstructedPat::wildcard(inner_ty));
1582 let extra_wildcards = other_slice.arity() - self_slice.arity();
1583 let extra_wildcards = (0..extra_wildcards).map(|_| wildcard);
1584 prefix.iter().chain(extra_wildcards).chain(suffix).collect()
1585 }
1586 }
1587 }
1588 _ => self.fields.iter_patterns().collect(),
1589 }
1590 }
1591
1592 /// We keep track for each pattern if it was ever reachable during the analysis. This is used
1593 /// with `unreachable_spans` to report unreachable subpatterns arising from or patterns.
1594 pub(super) fn set_reachable(&self) {
1595 self.reachable.set(true)
1596 }
1597 pub(super) fn is_reachable(&self) -> bool {
1598 self.reachable.get()
1599 }
1600
1601 /// Report the spans of subpatterns that were not reachable, if any.
1602 pub(super) fn unreachable_spans(&self) -> Vec<Span> {
1603 let mut spans = Vec::new();
1604 self.collect_unreachable_spans(&mut spans);
1605 spans
1606 }
1607
1608 fn collect_unreachable_spans(&self, spans: &mut Vec<Span>) {
1609 // We don't look at subpatterns if we already reported the whole pattern as unreachable.
1610 if !self.is_reachable() {
1611 spans.push(self.span);
1612 } else {
1613 for p in self.iter_fields() {
1614 p.collect_unreachable_spans(spans);
1615 }
1616 }
1617 }
1618 }
1619
1620 /// This is mostly copied from the `Pat` impl. This is best effort and not good enough for a
1621 /// `Display` impl.
1622 impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
1623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1624 // Printing lists is a chore.
1625 let mut first = true;
1626 let mut start_or_continue = |s| {
1627 if first {
1628 first = false;
1629 ""
1630 } else {
1631 s
1632 }
1633 };
1634 let mut start_or_comma = || start_or_continue(", ");
1635
1636 match &self.ctor {
1637 Single | Variant(_) => match self.ty.kind() {
1638 ty::Adt(def, _) if def.is_box() => {
1639 // Without `box_patterns`, the only legal pattern of type `Box` is `_` (outside
1640 // of `std`). So this branch is only reachable when the feature is enabled and
1641 // the pattern is a box pattern.
1642 let subpattern = self.iter_fields().next().unwrap();
1643 write!(f, "box {:?}", subpattern)
1644 }
1645 ty::Adt(..) | ty::Tuple(..) => {
1646 let variant = match self.ty.kind() {
1647 ty::Adt(adt, _) => Some(adt.variant(self.ctor.variant_index_for_adt(*adt))),
1648 ty::Tuple(_) => None,
1649 _ => unreachable!(),
1650 };
1651
1652 if let Some(variant) = variant {
1653 write!(f, "{}", variant.name)?;
1654 }
1655
1656 // Without `cx`, we can't know which field corresponds to which, so we can't
1657 // get the names of the fields. Instead we just display everything as a tuple
1658 // struct, which should be good enough.
1659 write!(f, "(")?;
1660 for p in self.iter_fields() {
1661 write!(f, "{}", start_or_comma())?;
1662 write!(f, "{:?}", p)?;
1663 }
1664 write!(f, ")")
1665 }
1666 // Note: given the expansion of `&str` patterns done in `expand_pattern`, we should
1667 // be careful to detect strings here. However a string literal pattern will never
1668 // be reported as a non-exhaustiveness witness, so we can ignore this issue.
1669 ty::Ref(_, _, mutbl) => {
1670 let subpattern = self.iter_fields().next().unwrap();
1671 write!(f, "&{}{:?}", mutbl.prefix_str(), subpattern)
1672 }
1673 _ => write!(f, "_"),
1674 },
1675 Slice(slice) => {
1676 let mut subpatterns = self.fields.iter_patterns();
1677 write!(f, "[")?;
1678 match slice.kind {
1679 FixedLen(_) => {
1680 for p in subpatterns {
1681 write!(f, "{}{:?}", start_or_comma(), p)?;
1682 }
1683 }
1684 VarLen(prefix_len, _) => {
1685 for p in subpatterns.by_ref().take(prefix_len) {
1686 write!(f, "{}{:?}", start_or_comma(), p)?;
1687 }
1688 write!(f, "{}", start_or_comma())?;
1689 write!(f, "..")?;
1690 for p in subpatterns {
1691 write!(f, "{}{:?}", start_or_comma(), p)?;
1692 }
1693 }
1694 }
1695 write!(f, "]")
1696 }
1697 &FloatRange(lo, hi, end) => {
1698 write!(f, "{}", lo)?;
1699 write!(f, "{}", end)?;
1700 write!(f, "{}", hi)
1701 }
1702 IntRange(range) => write!(f, "{:?}", range), // Best-effort, will render e.g. `false` as `0..=0`
1703 Wildcard | Missing { .. } | NonExhaustive => write!(f, "_ : {:?}", self.ty),
1704 Or => {
1705 for pat in self.iter_fields() {
1706 write!(f, "{}{:?}", start_or_continue(" | "), pat)?;
1707 }
1708 Ok(())
1709 }
1710 Str(value) => write!(f, "{}", value),
1711 Opaque => write!(f, "<constant pattern>"),
1712 }
1713 }
1714 }