1use std::cell::Cell;
2use std::fmt;
3use std::iter::once;
4
5use rustc_abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx};
6use rustc_arena::DroplessArena;
7use rustc_hir::HirId;
8use rustc_hir::def_id::DefId;
9use rustc_index::{Idx, IndexVec};
10use rustc_middle::middle::stability::EvalResult;
11use rustc_middle::thir::{self, Pat, PatKind, PatRange, PatRangeBoundary};
12use rustc_middle::ty::layout::IntegerExt;
13use rustc_middle::ty::{
14 self, FieldDef, OpaqueTypeKey, ScalarInt, Ty, TyCtxt, TypeVisitableExt, VariantDef,
15};
16use rustc_middle::{bug, span_bug};
17use rustc_session::lint;
18use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
19
20use crate::constructor::Constructor::*;
21use crate::constructor::{
22 IntRange, MaybeInfiniteInt, OpaqueId, RangeEnd, Slice, SliceKind, VariantVisibility,
23};
24use crate::lints::lint_nonexhaustive_missing_variants;
25use crate::pat_column::PatternColumn;
26use crate::rustc::print::EnumInfo;
27use crate::usefulness::{PlaceValidity, compute_match_usefulness};
28use crate::{PatCx, PrivateUninhabitedField, errors};
29
30mod print;
31
32pub type Constructor<'p, 'tcx> = crate::constructor::Constructor<RustcPatCtxt<'p, 'tcx>>;
34pub type ConstructorSet<'p, 'tcx> = crate::constructor::ConstructorSet<RustcPatCtxt<'p, 'tcx>>;
35pub type DeconstructedPat<'p, 'tcx> = crate::pat::DeconstructedPat<RustcPatCtxt<'p, 'tcx>>;
36pub type MatchArm<'p, 'tcx> = crate::MatchArm<'p, RustcPatCtxt<'p, 'tcx>>;
37pub type RedundancyExplanation<'p, 'tcx> =
38 crate::usefulness::RedundancyExplanation<'p, RustcPatCtxt<'p, 'tcx>>;
39pub type Usefulness<'p, 'tcx> = crate::usefulness::Usefulness<'p, RustcPatCtxt<'p, 'tcx>>;
40pub type UsefulnessReport<'p, 'tcx> =
41 crate::usefulness::UsefulnessReport<'p, RustcPatCtxt<'p, 'tcx>>;
42pub type WitnessPat<'p, 'tcx> = crate::pat::WitnessPat<RustcPatCtxt<'p, 'tcx>>;
43
44#[repr(transparent)]
50#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for RevealedTy<'tcx> {
#[inline]
fn clone(&self) -> RevealedTy<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for RevealedTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for RevealedTy<'tcx> {
#[inline]
fn eq(&self, other: &RevealedTy<'tcx>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for RevealedTy<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
}
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for RevealedTy<'tcx> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
51pub struct RevealedTy<'tcx>(Ty<'tcx>);
52
53impl<'tcx> fmt::Display for RevealedTy<'tcx> {
54 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
55 self.0.fmt(fmt)
56 }
57}
58
59impl<'tcx> fmt::Debug for RevealedTy<'tcx> {
60 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
61 self.0.fmt(fmt)
62 }
63}
64
65impl<'tcx> std::ops::Deref for RevealedTy<'tcx> {
66 type Target = Ty<'tcx>;
67 fn deref(&self) -> &Self::Target {
68 &self.0
69 }
70}
71
72impl<'tcx> RevealedTy<'tcx> {
73 pub fn inner(self) -> Ty<'tcx> {
74 self.0
75 }
76}
77
78#[derive(#[automatically_derived]
impl<'p, 'tcx: 'p> ::core::clone::Clone for RustcPatCtxt<'p, 'tcx> {
#[inline]
fn clone(&self) -> RustcPatCtxt<'p, 'tcx> {
RustcPatCtxt {
tcx: ::core::clone::Clone::clone(&self.tcx),
typeck_results: ::core::clone::Clone::clone(&self.typeck_results),
module: ::core::clone::Clone::clone(&self.module),
typing_env: ::core::clone::Clone::clone(&self.typing_env),
dropless_arena: ::core::clone::Clone::clone(&self.dropless_arena),
match_lint_level: ::core::clone::Clone::clone(&self.match_lint_level),
whole_match_span: ::core::clone::Clone::clone(&self.whole_match_span),
scrut_span: ::core::clone::Clone::clone(&self.scrut_span),
refutable: ::core::clone::Clone::clone(&self.refutable),
known_valid_scrutinee: ::core::clone::Clone::clone(&self.known_valid_scrutinee),
internal_state: ::core::clone::Clone::clone(&self.internal_state),
}
}
}Clone)]
79pub struct RustcPatCtxt<'p, 'tcx: 'p> {
80 pub tcx: TyCtxt<'tcx>,
81 pub typeck_results: &'tcx ty::TypeckResults<'tcx>,
82 pub module: DefId,
88 pub typing_env: ty::TypingEnv<'tcx>,
89 pub dropless_arena: &'p DroplessArena,
91 pub match_lint_level: HirId,
93 pub whole_match_span: Option<Span>,
95 pub scrut_span: Span,
97 pub refutable: bool,
99 pub known_valid_scrutinee: bool,
102 pub internal_state: RustcPatCtxtState,
103}
104
105#[derive(#[automatically_derived]
impl ::core::clone::Clone for RustcPatCtxtState {
#[inline]
fn clone(&self) -> RustcPatCtxtState {
RustcPatCtxtState {
has_lowered_deref_pat: ::core::clone::Clone::clone(&self.has_lowered_deref_pat),
}
}
}Clone, #[automatically_derived]
impl ::core::default::Default for RustcPatCtxtState {
#[inline]
fn default() -> RustcPatCtxtState {
RustcPatCtxtState {
has_lowered_deref_pat: ::core::default::Default::default(),
}
}
}Default)]
107pub struct RustcPatCtxtState {
108 has_lowered_deref_pat: Cell<bool>,
112}
113
114impl<'p, 'tcx: 'p> fmt::Debug for RustcPatCtxt<'p, 'tcx> {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.debug_struct("RustcPatCtxt").finish()
117 }
118}
119
120impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> {
121 #[inline]
127 pub fn reveal_opaque_ty(&self, ty: Ty<'tcx>) -> RevealedTy<'tcx> {
128 fn reveal_inner<'tcx>(cx: &RustcPatCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> RevealedTy<'tcx> {
129 let ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *ty.kind()
130 else {
131 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
132 };
133 if let Some(local_def_id) = def_id.as_local() {
134 let key = ty::OpaqueTypeKey { def_id: local_def_id, args };
135 if let Some(ty) = cx.reveal_opaque_key(key) {
136 return RevealedTy(ty);
137 }
138 }
139 RevealedTy(ty)
140 }
141 if let ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) = ty.kind() {
142 reveal_inner(self, ty)
143 } else {
144 RevealedTy(ty)
145 }
146 }
147
148 fn reveal_opaque_key(&self, key: OpaqueTypeKey<'tcx>) -> Option<Ty<'tcx>> {
151 self.typeck_results
152 .hidden_types
153 .get(&key.def_id)
154 .map(|x| x.ty.instantiate(self.tcx, key.args))
155 }
156 pub fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
158 !ty.inhabited_predicate(self.tcx).apply_revealing_opaque(
159 self.tcx,
160 self.typing_env,
161 self.module,
162 &|key| self.reveal_opaque_key(key),
163 )
164 }
165
166 pub fn is_foreign_non_exhaustive_enum(&self, ty: RevealedTy<'tcx>) -> bool {
168 match ty.kind() {
169 ty::Adt(def, ..) => def.variant_list_has_applicable_non_exhaustive(),
170 _ => false,
171 }
172 }
173
174 pub fn is_range_beyond_boundaries(&self, range: &IntRange, ty: RevealedTy<'tcx>) -> bool {
177 ty.is_ptr_sized_integral() && {
178 let lo = self.hoist_pat_range_bdy(range.lo, ty);
183 #[allow(non_exhaustive_omitted_patterns)] match lo {
PatRangeBoundary::PosInfinity => true,
_ => false,
}matches!(lo, PatRangeBoundary::PosInfinity)
184 || #[allow(non_exhaustive_omitted_patterns)] match range.hi {
MaybeInfiniteInt::Finite(0) => true,
_ => false,
}matches!(range.hi, MaybeInfiniteInt::Finite(0))
185 }
186 }
187
188 pub(crate) fn variant_sub_tys(
189 &self,
190 ty: RevealedTy<'tcx>,
191 variant: &'tcx VariantDef,
192 ) -> impl Iterator<Item = (&'tcx FieldDef, RevealedTy<'tcx>)> {
193 let ty::Adt(_, args) = ty.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
194 variant.fields.iter().map(move |field| {
195 let ty = field.ty(self.tcx, args);
196 let ty =
198 self.tcx.try_normalize_erasing_regions(self.typing_env, ty).unwrap_or_else(|e| {
199 self.tcx.dcx().span_delayed_bug(
200 self.scrut_span,
201 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Failed to normalize {0:?} in typing_env={1:?} while getting variant sub tys for {2:?}",
e.get_type_for_failure(), self.typing_env, ty))
})format!(
202 "Failed to normalize {:?} in typing_env={:?} while getting variant sub tys for {ty:?}",
203 e.get_type_for_failure(),
204 self.typing_env,
205 ),
206 );
207 ty
208 });
209 let ty = self.reveal_opaque_ty(ty);
210 (field, ty)
211 })
212 }
213
214 pub(crate) fn variant_index_for_adt(
215 ctor: &Constructor<'p, 'tcx>,
216 adt: ty::AdtDef<'tcx>,
217 ) -> VariantIdx {
218 match *ctor {
219 Variant(idx) => idx,
220 Struct | UnionField => {
221 if !!adt.is_enum() {
::core::panicking::panic("assertion failed: !adt.is_enum()")
};assert!(!adt.is_enum());
222 FIRST_VARIANT
223 }
224 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("bad constructor {0:?} for adt {1:?}",
ctor, adt))bug!("bad constructor {:?} for adt {:?}", ctor, adt),
225 }
226 }
227
228 pub(crate) fn ctor_sub_tys(
231 &self,
232 ctor: &Constructor<'p, 'tcx>,
233 ty: RevealedTy<'tcx>,
234 ) -> impl Iterator<Item = (RevealedTy<'tcx>, PrivateUninhabitedField)> + ExactSizeIterator {
235 fn reveal_and_alloc<'a, 'tcx>(
236 cx: &'a RustcPatCtxt<'_, 'tcx>,
237 iter: impl Iterator<Item = Ty<'tcx>>,
238 ) -> &'a [(RevealedTy<'tcx>, PrivateUninhabitedField)] {
239 cx.dropless_arena.alloc_from_iter(
240 iter.map(|ty| cx.reveal_opaque_ty(ty))
241 .map(|ty| (ty, PrivateUninhabitedField(false))),
242 )
243 }
244 let cx = self;
245 let slice = match ctor {
246 Struct | Variant(_) | UnionField => match ty.kind() {
247 ty::Tuple(fs) => reveal_and_alloc(cx, fs.iter()),
248 ty::Adt(adt, _) => {
249 let variant = &adt.variant(RustcPatCtxt::variant_index_for_adt(&ctor, *adt));
250 let tys = cx.variant_sub_tys(ty, variant).map(|(field, ty)| {
251 let is_visible =
252 adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx);
253 let is_uninhabited = cx.is_uninhabited(*ty);
254 let skip = is_uninhabited && !is_visible;
255 (ty, PrivateUninhabitedField(skip))
256 });
257 cx.dropless_arena.alloc_from_iter(tys)
258 }
259 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type for constructor `{0:?}`: {1:?}",
ctor, ty))bug!("Unexpected type for constructor `{ctor:?}`: {ty:?}"),
260 },
261 Ref => match ty.kind() {
262 ty::Ref(_, rty, _) => reveal_and_alloc(cx, once(*rty)),
263 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type for `Ref` constructor: {0:?}",
ty))bug!("Unexpected type for `Ref` constructor: {ty:?}"),
264 },
265 Slice(slice) => match ty.builtin_index() {
266 Some(ty) => {
267 let arity = slice.arity();
268 reveal_and_alloc(cx, (0..arity).map(|_| ty))
269 }
270 None => ::rustc_middle::util::bug::bug_fmt(format_args!("bad slice pattern {0:?} {1:?}",
ctor, ty))bug!("bad slice pattern {:?} {:?}", ctor, ty),
271 },
272 DerefPattern(pointee_ty) => reveal_and_alloc(cx, once(pointee_ty.inner())),
273 Bool(..) | IntRange(..) | F16Range(..) | F32Range(..) | F64Range(..)
274 | F128Range(..) | Str(..) | Opaque(..) | Never | NonExhaustive | Hidden | Missing
275 | PrivateUninhabited | Wildcard => &[],
276 Or => {
277 ::rustc_middle::util::bug::bug_fmt(format_args!("called `Fields::wildcards` on an `Or` ctor"))bug!("called `Fields::wildcards` on an `Or` ctor")
278 }
279 };
280 slice.iter().copied()
281 }
282
283 pub(crate) fn ctor_arity(&self, ctor: &Constructor<'p, 'tcx>, ty: RevealedTy<'tcx>) -> usize {
285 match ctor {
286 Struct | Variant(_) | UnionField => match ty.kind() {
287 ty::Tuple(fs) => fs.len(),
288 ty::Adt(adt, ..) => {
289 let variant_idx = RustcPatCtxt::variant_index_for_adt(&ctor, *adt);
290 adt.variant(variant_idx).fields.len()
291 }
292 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type for constructor `{0:?}`: {1:?}",
ctor, ty))bug!("Unexpected type for constructor `{ctor:?}`: {ty:?}"),
293 },
294 Ref | DerefPattern(_) => 1,
295 Slice(slice) => slice.arity(),
296 Bool(..) | IntRange(..) | F16Range(..) | F32Range(..) | F64Range(..)
297 | F128Range(..) | Str(..) | Opaque(..) | Never | NonExhaustive | Hidden | Missing
298 | PrivateUninhabited | Wildcard => 0,
299 Or => ::rustc_middle::util::bug::bug_fmt(format_args!("The `Or` constructor doesn\'t have a fixed arity"))bug!("The `Or` constructor doesn't have a fixed arity"),
300 }
301 }
302
303 pub fn ctors_for_ty(
307 &self,
308 ty: RevealedTy<'tcx>,
309 ) -> Result<ConstructorSet<'p, 'tcx>, ErrorGuaranteed> {
310 let cx = self;
311 let make_uint_range = |start, end| {
312 IntRange::from_range(
313 MaybeInfiniteInt::new_finite_uint(start),
314 MaybeInfiniteInt::new_finite_uint(end),
315 RangeEnd::Included,
316 )
317 };
318 ty.error_reported()?;
320 Ok(match ty.kind() {
323 ty::Bool => ConstructorSet::Bool,
324 ty::Char => {
325 ConstructorSet::Integers {
327 range_1: make_uint_range('\u{0000}' as u128, '\u{D7FF}' as u128),
328 range_2: Some(make_uint_range('\u{E000}' as u128, '\u{10FFFF}' as u128)),
329 }
330 }
331 &ty::Int(ity) => {
332 let range = if ty.is_ptr_sized_integral() {
333 IntRange {
335 lo: MaybeInfiniteInt::NegInfinity,
336 hi: MaybeInfiniteInt::PosInfinity,
337 }
338 } else {
339 let size = Integer::from_int_ty(&cx.tcx, ity).size().bits();
340 let min = 1u128 << (size - 1);
341 let max = min - 1;
342 let min = MaybeInfiniteInt::new_finite_int(min, size);
343 let max = MaybeInfiniteInt::new_finite_int(max, size);
344 IntRange::from_range(min, max, RangeEnd::Included)
345 };
346 ConstructorSet::Integers { range_1: range, range_2: None }
347 }
348 &ty::Uint(uty) => {
349 let range = if ty.is_ptr_sized_integral() {
350 let lo = MaybeInfiniteInt::new_finite_uint(0);
352 IntRange { lo, hi: MaybeInfiniteInt::PosInfinity }
353 } else {
354 let size = Integer::from_uint_ty(&cx.tcx, uty).size();
355 let max = size.truncate(u128::MAX);
356 make_uint_range(0, max)
357 };
358 ConstructorSet::Integers { range_1: range, range_2: None }
359 }
360 ty::Slice(sub_ty) => ConstructorSet::Slice {
361 array_len: None,
362 subtype_is_empty: cx.is_uninhabited(*sub_ty),
363 },
364 ty::Array(sub_ty, len) => {
365 ConstructorSet::Slice {
367 array_len: len.try_to_target_usize(cx.tcx).map(|l| l as usize),
368 subtype_is_empty: cx.is_uninhabited(*sub_ty),
369 }
370 }
371 ty::Adt(def, args) if def.is_enum() => {
372 let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(ty);
373 if def.variants().is_empty() && !is_declared_nonexhaustive {
374 ConstructorSet::NoConstructors
375 } else {
376 let mut variants =
377 IndexVec::from_elem(VariantVisibility::Visible, def.variants());
378 for (idx, v) in def.variants().iter_enumerated() {
379 let variant_def_id = def.variant(idx).def_id;
380 let is_inhabited = v
382 .inhabited_predicate(cx.tcx, *def)
383 .instantiate(cx.tcx, args)
384 .apply_revealing_opaque(cx.tcx, cx.typing_env, cx.module, &|key| {
385 cx.reveal_opaque_key(key)
386 });
387 let is_unstable = #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.eval_stability(variant_def_id,
None, DUMMY_SP, None) {
EvalResult::Deny { .. } => true,
_ => false,
}matches!(
389 cx.tcx.eval_stability(variant_def_id, None, DUMMY_SP, None),
390 EvalResult::Deny { .. }
391 );
392 let is_doc_hidden =
394 cx.tcx.is_doc_hidden(variant_def_id) && !variant_def_id.is_local();
395 let visibility = if !is_inhabited {
396 VariantVisibility::Empty
398 } else if is_unstable || is_doc_hidden {
399 VariantVisibility::Hidden
400 } else {
401 VariantVisibility::Visible
402 };
403 variants[idx] = visibility;
404 }
405
406 ConstructorSet::Variants { variants, non_exhaustive: is_declared_nonexhaustive }
407 }
408 }
409 ty::Adt(def, _) if def.is_union() => ConstructorSet::Union,
410 ty::Adt(..) | ty::Tuple(..) => {
411 ConstructorSet::Struct { empty: cx.is_uninhabited(ty.inner()) }
412 }
413 ty::Ref(..) => ConstructorSet::Ref,
414 ty::Never => ConstructorSet::NoConstructors,
415 ty::Float(_)
418 | ty::Str
419 | ty::Foreign(_)
420 | ty::RawPtr(_, _)
421 | ty::FnDef(_, _)
422 | ty::FnPtr(..)
423 | ty::Pat(_, _)
424 | ty::Dynamic(_, _)
425 | ty::Closure(..)
426 | ty::CoroutineClosure(..)
427 | ty::Coroutine(_, _)
428 | ty::UnsafeBinder(_)
429 | ty::Alias(_)
430 | ty::Param(_)
431 | ty::Error(_) => ConstructorSet::Unlistable,
432 ty::CoroutineWitness(_, _) | ty::Bound(_, _) | ty::Placeholder(_) | ty::Infer(_) => {
433 ::rustc_middle::util::bug::bug_fmt(format_args!("Encountered unexpected type in `ConstructorSet::for_ty`: {0:?}",
ty))bug!("Encountered unexpected type in `ConstructorSet::for_ty`: {ty:?}")
434 }
435 })
436 }
437
438 pub(crate) fn lower_pat_range_bdy(
439 &self,
440 bdy: PatRangeBoundary<'tcx>,
441 ty: RevealedTy<'tcx>,
442 ) -> MaybeInfiniteInt {
443 match bdy {
444 PatRangeBoundary::NegInfinity => MaybeInfiniteInt::NegInfinity,
445 PatRangeBoundary::Finite(value) => {
446 let bits = value.to_leaf().to_bits_unchecked();
447 match *ty.kind() {
448 ty::Int(ity) => {
449 let size = Integer::from_int_ty(&self.tcx, ity).size().bits();
450 MaybeInfiniteInt::new_finite_int(bits, size)
451 }
452 _ => MaybeInfiniteInt::new_finite_uint(bits),
453 }
454 }
455 PatRangeBoundary::PosInfinity => MaybeInfiniteInt::PosInfinity,
456 }
457 }
458
459 pub fn lower_pat(&self, pat: &'p Pat<'tcx>) -> DeconstructedPat<'p, 'tcx> {
462 let cx = self;
463 let ty = cx.reveal_opaque_ty(pat.ty);
464 let ctor;
465 let arity;
466 let fields: Vec<_>;
467 match &pat.kind {
468 PatKind::Binding { subpattern: Some(subpat), .. }
469 | PatKind::Guard { subpattern: subpat, .. } => return self.lower_pat(subpat),
470 PatKind::Missing | PatKind::Binding { subpattern: None, .. } | PatKind::Wild => {
471 ctor = Wildcard;
472 fields = ::alloc::vec::Vec::new()vec![];
473 arity = 0;
474 }
475 PatKind::Deref { pin, subpattern } => {
476 fields = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.lower_pat(subpattern).at_index(0)]))vec![self.lower_pat(subpattern).at_index(0)];
477 arity = 1;
478 ctor = match (pin, ty.maybe_pinned_ref()) {
479 (ty::Pinnedness::Not, Some((_, ty::Pinnedness::Not, _, _))) => Ref,
480 (ty::Pinnedness::Pinned, Some((inner_ty, ty::Pinnedness::Pinned, _, _))) => {
481 self.internal_state.has_lowered_deref_pat.set(true);
482 DerefPattern(RevealedTy(inner_ty))
483 }
484 _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("pattern has unexpected type: pat: {0:?}, ty: {1:?}",
pat.kind, ty.inner()))span_bug!(
485 pat.span,
486 "pattern has unexpected type: pat: {:?}, ty: {:?}",
487 pat.kind,
488 ty.inner()
489 ),
490 };
491 }
492 PatKind::DerefPattern { subpattern, .. } => {
493 fields = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.lower_pat(subpattern).at_index(0)]))vec![self.lower_pat(subpattern).at_index(0)];
499 arity = 1;
500 ctor = DerefPattern(cx.reveal_opaque_ty(subpattern.ty));
501 self.internal_state.has_lowered_deref_pat.set(true);
502 }
503 PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
504 match ty.kind() {
505 ty::Tuple(fs) => {
506 ctor = Struct;
507 arity = fs.len();
508 fields = subpatterns
509 .iter()
510 .map(|ipat| self.lower_pat(&ipat.pattern).at_index(ipat.field.index()))
511 .collect();
512 }
513 ty::Adt(adt, _) => {
514 ctor = match pat.kind {
515 PatKind::Leaf { .. } if adt.is_union() => UnionField,
516 PatKind::Leaf { .. } => Struct,
517 PatKind::Variant { variant_index, .. } => Variant(variant_index),
518 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
519 };
520 let variant =
521 &adt.variant(RustcPatCtxt::variant_index_for_adt(&ctor, *adt));
522 arity = variant.fields.len();
523 fields = subpatterns
524 .iter()
525 .map(|ipat| self.lower_pat(&ipat.pattern).at_index(ipat.field.index()))
526 .collect();
527 }
528 _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("pattern has unexpected type: pat: {0:?}, ty: {1}", pat.kind,
ty.inner()))span_bug!(
529 pat.span,
530 "pattern has unexpected type: pat: {:?}, ty: {}",
531 pat.kind,
532 ty.inner()
533 ),
534 }
535 }
536 PatKind::Constant { value } => {
537 match ty.kind() {
538 ty::Bool => {
539 ctor = Bool(value.try_to_bool().unwrap());
540 fields = ::alloc::vec::Vec::new()vec![];
541 arity = 0;
542 }
543 ty::Char | ty::Int(_) | ty::Uint(_) => {
544 ctor = {
545 let bits = value.to_leaf().to_bits_unchecked();
546 let x = match *ty.kind() {
547 ty::Int(ity) => {
548 let size = Integer::from_int_ty(&cx.tcx, ity).size().bits();
549 MaybeInfiniteInt::new_finite_int(bits, size)
550 }
551 _ => MaybeInfiniteInt::new_finite_uint(bits),
552 };
553 IntRange(IntRange::from_singleton(x))
554 };
555 fields = ::alloc::vec::Vec::new()vec![];
556 arity = 0;
557 }
558 ty::Float(ty::FloatTy::F16) => {
559 use rustc_apfloat::Float;
560 let bits = value.to_leaf().to_u16();
561 let value = rustc_apfloat::ieee::Half::from_bits(bits.into());
562 ctor = F16Range(value, value, RangeEnd::Included);
563 fields = ::alloc::vec::Vec::new()vec![];
564 arity = 0;
565 }
566 ty::Float(ty::FloatTy::F32) => {
567 use rustc_apfloat::Float;
568 let bits = value.to_leaf().to_u32();
569 let value = rustc_apfloat::ieee::Single::from_bits(bits.into());
570 ctor = F32Range(value, value, RangeEnd::Included);
571 fields = ::alloc::vec::Vec::new()vec![];
572 arity = 0;
573 }
574 ty::Float(ty::FloatTy::F64) => {
575 use rustc_apfloat::Float;
576 let bits = value.to_leaf().to_u64();
577 let value = rustc_apfloat::ieee::Double::from_bits(bits.into());
578 ctor = F64Range(value, value, RangeEnd::Included);
579 fields = ::alloc::vec::Vec::new()vec![];
580 arity = 0;
581 }
582 ty::Float(ty::FloatTy::F128) => {
583 use rustc_apfloat::Float;
584 let bits = value.to_leaf().to_u128();
585 let value = rustc_apfloat::ieee::Quad::from_bits(bits);
586 ctor = F128Range(value, value, RangeEnd::Included);
587 fields = ::alloc::vec::Vec::new()vec![];
588 arity = 0;
589 }
590 ty::Str => {
591 ctor = Str(*value);
595 fields = ::alloc::vec::Vec::new()vec![];
596 arity = 0;
597 }
598 _ => {
602 ctor = Opaque(OpaqueId::new());
603 fields = ::alloc::vec::Vec::new()vec![];
604 arity = 0;
605 }
606 }
607 }
608 PatKind::Range(patrange) => {
609 let PatRange { lo, hi, end, .. } = patrange.as_ref();
610 let end = match end {
611 rustc_hir::RangeEnd::Included => RangeEnd::Included,
612 rustc_hir::RangeEnd::Excluded => RangeEnd::Excluded,
613 };
614 ctor = match ty.kind() {
615 ty::Char | ty::Int(_) | ty::Uint(_) => {
616 let lo = cx.lower_pat_range_bdy(*lo, ty);
617 let hi = cx.lower_pat_range_bdy(*hi, ty);
618 IntRange(IntRange::from_range(lo, hi, end))
619 }
620 ty::Float(fty) => {
621 use rustc_apfloat::Float;
622 let lo = lo.as_finite().map(|c| c.to_leaf().to_bits_unchecked());
623 let hi = hi.as_finite().map(|c| c.to_leaf().to_bits_unchecked());
624 match fty {
625 ty::FloatTy::F16 => {
626 use rustc_apfloat::ieee::Half;
627 let lo = lo.map(Half::from_bits).unwrap_or(-Half::INFINITY);
628 let hi = hi.map(Half::from_bits).unwrap_or(Half::INFINITY);
629 F16Range(lo, hi, end)
630 }
631 ty::FloatTy::F32 => {
632 use rustc_apfloat::ieee::Single;
633 let lo = lo.map(Single::from_bits).unwrap_or(-Single::INFINITY);
634 let hi = hi.map(Single::from_bits).unwrap_or(Single::INFINITY);
635 F32Range(lo, hi, end)
636 }
637 ty::FloatTy::F64 => {
638 use rustc_apfloat::ieee::Double;
639 let lo = lo.map(Double::from_bits).unwrap_or(-Double::INFINITY);
640 let hi = hi.map(Double::from_bits).unwrap_or(Double::INFINITY);
641 F64Range(lo, hi, end)
642 }
643 ty::FloatTy::F128 => {
644 use rustc_apfloat::ieee::Quad;
645 let lo = lo.map(Quad::from_bits).unwrap_or(-Quad::INFINITY);
646 let hi = hi.map(Quad::from_bits).unwrap_or(Quad::INFINITY);
647 F128Range(lo, hi, end)
648 }
649 }
650 }
651 _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("invalid type for range pattern: {0}", ty.inner()))span_bug!(pat.span, "invalid type for range pattern: {}", ty.inner()),
652 };
653 fields = ::alloc::vec::Vec::new()vec![];
654 arity = 0;
655 }
656 PatKind::Array { prefix, slice, suffix } | PatKind::Slice { prefix, slice, suffix } => {
657 let array_len = match ty.kind() {
658 ty::Array(_, length) => Some(
659 length
660 .try_to_target_usize(cx.tcx)
661 .expect("expected len of array pat to be definite")
662 as usize,
663 ),
664 ty::Slice(_) => None,
665 _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("bad ty {0} for slice pattern", ty.inner()))span_bug!(pat.span, "bad ty {} for slice pattern", ty.inner()),
666 };
667 let kind = if slice.is_some() {
668 SliceKind::VarLen(prefix.len(), suffix.len())
669 } else {
670 SliceKind::FixedLen(prefix.len() + suffix.len())
671 };
672 ctor = Slice(Slice::new(array_len, kind));
673 fields = prefix
674 .iter()
675 .chain(suffix.iter())
676 .map(|p| self.lower_pat(&*p))
677 .enumerate()
678 .map(|(i, p)| p.at_index(i))
679 .collect();
680 arity = kind.arity();
681 }
682 PatKind::Or { .. } => {
683 ctor = Or;
684 let pats = expand_or_pat(pat);
685 fields = pats
686 .into_iter()
687 .map(|p| self.lower_pat(p))
688 .enumerate()
689 .map(|(i, p)| p.at_index(i))
690 .collect();
691 arity = fields.len();
692 }
693 PatKind::Never => {
694 ctor = Wildcard;
698 fields = ::alloc::vec::Vec::new()vec![];
699 arity = 0;
700 }
701 PatKind::Error(_) => {
702 ctor = Opaque(OpaqueId::new());
703 fields = ::alloc::vec::Vec::new()vec![];
704 arity = 0;
705 }
706 }
707 DeconstructedPat::new(ctor, fields, arity, ty, pat)
708 }
709
710 fn hoist_pat_range_bdy(
715 &self,
716 miint: MaybeInfiniteInt,
717 ty: RevealedTy<'tcx>,
718 ) -> PatRangeBoundary<'tcx> {
719 use MaybeInfiniteInt::*;
720 let tcx = self.tcx;
721 match miint {
722 NegInfinity => PatRangeBoundary::NegInfinity,
723 Finite(_) => {
724 let size = ty.primitive_size(tcx);
725 let bits = match *ty.kind() {
726 ty::Int(_) => miint.as_finite_int(size.bits()).unwrap(),
727 _ => miint.as_finite_uint().unwrap(),
728 };
729 match ScalarInt::try_from_uint(bits, size) {
730 Some(scalar) => {
731 let valtree = ty::ValTree::from_scalar_int(tcx, scalar);
732 PatRangeBoundary::Finite(valtree)
733 }
734 None => PatRangeBoundary::PosInfinity,
738 }
739 }
740 PosInfinity => PatRangeBoundary::PosInfinity,
741 }
742 }
743
744 fn print_pat_range(&self, range: &IntRange, ty: RevealedTy<'tcx>) -> String {
746 use MaybeInfiniteInt::*;
747 let cx = self;
748 if #[allow(non_exhaustive_omitted_patterns)] match (range.lo, range.hi) {
(NegInfinity, PosInfinity) => true,
_ => false,
}matches!((range.lo, range.hi), (NegInfinity, PosInfinity)) {
749 "_".to_string()
750 } else if range.is_singleton() {
751 let lo = cx.hoist_pat_range_bdy(range.lo, ty);
752 let value = ty::Value { ty: ty.inner(), valtree: lo.as_finite().unwrap() };
753 value.to_string()
754 } else {
755 let mut end = rustc_hir::RangeEnd::Included;
757 let mut lo = cx.hoist_pat_range_bdy(range.lo, ty);
758 if #[allow(non_exhaustive_omitted_patterns)] match lo {
PatRangeBoundary::PosInfinity => true,
_ => false,
}matches!(lo, PatRangeBoundary::PosInfinity) {
759 let max = ty.numeric_max_val(cx.tcx).unwrap();
765 let max = ty::ValTree::from_scalar_int(cx.tcx, max.try_to_scalar_int().unwrap());
766 lo = PatRangeBoundary::Finite(max);
767 }
768 let hi = if let Some(hi) = range.hi.minus_one() {
769 hi
770 } else {
771 end = rustc_hir::RangeEnd::Excluded;
773 range.hi
774 };
775 let hi = cx.hoist_pat_range_bdy(hi, ty);
776 PatRange { lo, hi, end, ty: ty.inner() }.to_string()
777 }
778 }
779
780 pub fn print_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> String {
784 let cx = self;
785 let print = |p| cx.print_witness_pat(p);
786 match pat.ctor() {
787 Bool(b) => b.to_string(),
788 Str(s) => s.to_string(),
789 IntRange(range) => return self.print_pat_range(range, *pat.ty()),
790 Struct | Variant(_) | UnionField => {
791 let enum_info = match *pat.ty().kind() {
792 ty::Adt(adt_def, _) if adt_def.is_enum() => EnumInfo::Enum {
793 adt_def,
794 variant_index: RustcPatCtxt::variant_index_for_adt(pat.ctor(), adt_def),
795 },
796 ty::Adt(..) | ty::Tuple(..) => EnumInfo::NotEnum,
797 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected ctor for type {0:?} {1:?}",
pat.ctor(), *pat.ty()))bug!("unexpected ctor for type {:?} {:?}", pat.ctor(), *pat.ty()),
798 };
799
800 let subpatterns = pat
801 .iter_fields()
802 .enumerate()
803 .map(|(i, pat)| print::FieldPat {
804 field: FieldIdx::new(i),
805 pattern: print(pat),
806 is_wildcard: would_print_as_wildcard(cx.tcx, pat),
807 })
808 .collect::<Vec<_>>();
809
810 let mut s = String::new();
811 print::write_struct_like(
812 &mut s,
813 self.tcx,
814 pat.ty().inner(),
815 &enum_info,
816 &subpatterns,
817 )
818 .unwrap();
819 s
820 }
821 Ref => {
822 let mut s = String::new();
823 print::write_ref_like(&mut s, pat.ty().inner(), &print(&pat.fields[0])).unwrap();
824 s
825 }
826 DerefPattern(_) if pat.ty().is_box() && !self.tcx.features().deref_patterns() => {
827 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("box {0}", print(&pat.fields[0])))
})format!("box {}", print(&pat.fields[0]))
833 }
834 DerefPattern(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("deref!({0})",
print(&pat.fields[0])))
})format!("deref!({})", print(&pat.fields[0])),
835 Slice(slice) => {
836 let (prefix_len, has_dot_dot) = match slice.kind {
837 SliceKind::FixedLen(len) => (len, false),
838 SliceKind::VarLen(prefix_len, _) => (prefix_len, true),
839 };
840
841 let (mut prefix, mut suffix) = pat.fields.split_at(prefix_len);
842
843 if has_dot_dot && slice.array_len.is_some() {
849 while let [rest @ .., last] = prefix
850 && would_print_as_wildcard(cx.tcx, last)
851 {
852 prefix = rest;
853 }
854 while let [first, rest @ ..] = suffix
855 && would_print_as_wildcard(cx.tcx, first)
856 {
857 suffix = rest;
858 }
859 }
860
861 let prefix = prefix.iter().map(print).collect::<Vec<_>>();
862 let suffix = suffix.iter().map(print).collect::<Vec<_>>();
863
864 let mut s = String::new();
865 print::write_slice_like(&mut s, &prefix, has_dot_dot, &suffix).unwrap();
866 s
867 }
868 Never if self.tcx.features().never_patterns() => "!".to_string(),
869 Never | Wildcard | NonExhaustive | Hidden | PrivateUninhabited => "_".to_string(),
870 Missing { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("trying to convert a `Missing` constructor into a `Pat`; this is probably a bug,\n `Missing` should have been processed in `apply_constructors`"))bug!(
871 "trying to convert a `Missing` constructor into a `Pat`; this is probably a bug,
872 `Missing` should have been processed in `apply_constructors`"
873 ),
874 F16Range(..) | F32Range(..) | F64Range(..) | F128Range(..) | Opaque(..) | Or => {
875 ::rustc_middle::util::bug::bug_fmt(format_args!("can\'t convert to pattern: {0:?}",
pat))bug!("can't convert to pattern: {:?}", pat)
876 }
877 }
878 }
879}
880
881fn would_print_as_wildcard(tcx: TyCtxt<'_>, p: &WitnessPat<'_, '_>) -> bool {
883 match p.ctor() {
884 Constructor::IntRange(IntRange {
885 lo: MaybeInfiniteInt::NegInfinity,
886 hi: MaybeInfiniteInt::PosInfinity,
887 })
888 | Constructor::Wildcard
889 | Constructor::NonExhaustive
890 | Constructor::Hidden
891 | Constructor::PrivateUninhabited => true,
892 Constructor::Never if !tcx.features().never_patterns() => true,
893 _ => false,
894 }
895}
896
897impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> {
898 type Ty = RevealedTy<'tcx>;
899 type Error = ErrorGuaranteed;
900 type VariantIdx = VariantIdx;
901 type StrLit = ty::Value<'tcx>;
902 type ArmData = HirId;
903 type PatData = &'p Pat<'tcx>;
904
905 fn is_exhaustive_patterns_feature_on(&self) -> bool {
906 self.tcx.features().exhaustive_patterns()
907 }
908
909 fn ctor_arity(&self, ctor: &crate::constructor::Constructor<Self>, ty: &Self::Ty) -> usize {
910 self.ctor_arity(ctor, *ty)
911 }
912 fn ctor_sub_tys(
913 &self,
914 ctor: &crate::constructor::Constructor<Self>,
915 ty: &Self::Ty,
916 ) -> impl Iterator<Item = (Self::Ty, PrivateUninhabitedField)> + ExactSizeIterator {
917 self.ctor_sub_tys(ctor, *ty)
918 }
919 fn ctors_for_ty(
920 &self,
921 ty: &Self::Ty,
922 ) -> Result<crate::constructor::ConstructorSet<Self>, Self::Error> {
923 self.ctors_for_ty(*ty)
924 }
925
926 fn write_variant_name(
927 f: &mut fmt::Formatter<'_>,
928 ctor: &crate::constructor::Constructor<Self>,
929 ty: &Self::Ty,
930 ) -> fmt::Result {
931 if let ty::Adt(adt, _) = ty.kind() {
932 let variant = adt.variant(Self::variant_index_for_adt(ctor, *adt));
933 f.write_fmt(format_args!("{0}", variant.name))write!(f, "{}", variant.name)?;
934 }
935 Ok(())
936 }
937
938 fn bug(&self, fmt: fmt::Arguments<'_>) -> Self::Error {
939 ::rustc_middle::util::bug::span_bug_fmt(self.scrut_span,
format_args!("{0}", fmt))span_bug!(self.scrut_span, "{}", fmt)
940 }
941
942 fn lint_overlapping_range_endpoints(
943 &self,
944 pat: &crate::pat::DeconstructedPat<Self>,
945 overlaps_on: IntRange,
946 overlaps_with: &[&crate::pat::DeconstructedPat<Self>],
947 ) {
948 let overlap_as_pat = self.print_pat_range(&overlaps_on, *pat.ty());
949 let overlaps: Vec<_> = overlaps_with
950 .iter()
951 .map(|pat| pat.data().span)
952 .map(|span| errors::Overlap { range: overlap_as_pat.to_string(), span })
953 .collect();
954 let pat_span = pat.data().span;
955 self.tcx.emit_node_span_lint(
956 lint::builtin::OVERLAPPING_RANGE_ENDPOINTS,
957 self.match_lint_level,
958 pat_span,
959 errors::OverlappingRangeEndpoints { overlap: overlaps, range: pat_span },
960 );
961 }
962
963 fn complexity_exceeded(&self) -> Result<(), Self::Error> {
964 let span = self.whole_match_span.unwrap_or(self.scrut_span);
965 Err(self.tcx.dcx().span_err(span, "reached pattern complexity limit"))
966 }
967
968 fn lint_non_contiguous_range_endpoints(
969 &self,
970 pat: &crate::pat::DeconstructedPat<Self>,
971 gap: IntRange,
972 gapped_with: &[&crate::pat::DeconstructedPat<Self>],
973 ) {
974 let &thir_pat = pat.data();
975 let thir::PatKind::Range(range) = &thir_pat.kind else { return };
976 if range.end != rustc_hir::RangeEnd::Excluded {
978 return;
979 }
980 let suggested_range: String = {
983 let mut suggested_range = PatRange::clone(range);
985 suggested_range.end = rustc_hir::RangeEnd::Included;
986 suggested_range.to_string()
987 };
988 let gap_as_pat = self.print_pat_range(&gap, *pat.ty());
989 if gapped_with.is_empty() {
990 self.tcx.emit_node_span_lint(
992 lint::builtin::NON_CONTIGUOUS_RANGE_ENDPOINTS,
993 self.match_lint_level,
994 thir_pat.span,
995 errors::ExclusiveRangeMissingMax {
996 first_range: thir_pat.span,
998 max: gap_as_pat,
1000 suggestion: suggested_range,
1002 },
1003 );
1004 } else {
1005 self.tcx.emit_node_span_lint(
1006 lint::builtin::NON_CONTIGUOUS_RANGE_ENDPOINTS,
1007 self.match_lint_level,
1008 thir_pat.span,
1009 errors::ExclusiveRangeMissingGap {
1010 first_range: thir_pat.span,
1012 gap: gap_as_pat.to_string(),
1014 suggestion: suggested_range,
1016 gap_with: gapped_with
1019 .iter()
1020 .map(|pat| errors::GappedRange {
1021 span: pat.data().span,
1022 gap: gap_as_pat.to_string(),
1023 first_range: range.to_string(),
1024 })
1025 .collect(),
1026 },
1027 );
1028 }
1029 }
1030
1031 fn match_may_contain_deref_pats(&self) -> bool {
1032 self.internal_state.has_lowered_deref_pat.get()
1033 }
1034
1035 fn report_mixed_deref_pat_ctors(
1036 &self,
1037 deref_pat: &crate::pat::DeconstructedPat<Self>,
1038 normal_pat: &crate::pat::DeconstructedPat<Self>,
1039 ) -> Self::Error {
1040 let deref_pattern_label = deref_pat.data().span;
1041 let normal_constructor_label = normal_pat.data().span;
1042 self.tcx.dcx().emit_err(errors::MixedDerefPatternConstructors {
1043 spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[deref_pattern_label, normal_constructor_label]))vec![deref_pattern_label, normal_constructor_label],
1044 smart_pointer_ty: deref_pat.ty().inner(),
1045 deref_pattern_label,
1046 normal_constructor_label,
1047 })
1048 }
1049}
1050
1051fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> {
1053 fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) {
1054 if let PatKind::Or { pats } = &pat.kind {
1055 for pat in pats.iter() {
1056 expand(pat, vec);
1057 }
1058 } else {
1059 vec.push(pat)
1060 }
1061 }
1062
1063 let mut pats = Vec::new();
1064 expand(pat, &mut pats);
1065 pats
1066}
1067
1068pub fn analyze_match<'p, 'tcx>(
1071 tycx: &RustcPatCtxt<'p, 'tcx>,
1072 arms: &[MatchArm<'p, 'tcx>],
1073 scrut_ty: Ty<'tcx>,
1074) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
1075 let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
1076
1077 let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee);
1078 let report = compute_match_usefulness(
1079 tycx,
1080 arms,
1081 scrut_ty,
1082 scrut_validity,
1083 tycx.tcx.pattern_complexity_limit().0,
1084 )?;
1085
1086 if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() {
1089 let pat_column = PatternColumn::new(arms);
1090 lint_nonexhaustive_missing_variants(tycx, arms, &pat_column, scrut_ty)?;
1091 }
1092
1093 Ok(report)
1094}