1use rustc_arena::{DroplessArena, TypedArena};
2use rustc_ast::Mutability;
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::codes::*;
5use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, msg, struct_span_code_err};
6use rustc_hir::def::*;
7use rustc_hir::def_id::{DefId, LocalDefId};
8use rustc_hir::{self as hir, BindingMode, ByRef, HirId, MatchSource};
9use rustc_infer::infer::TyCtxtInferExt;
10use rustc_middle::bug;
11use rustc_middle::thir::visit::Visitor;
12use rustc_middle::thir::*;
13use rustc_middle::ty::print::with_no_trimmed_paths;
14use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
15use rustc_pattern_analysis::diagnostics::Uncovered;
16use rustc_pattern_analysis::rustc::{
17 Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RevealedTy,
18 RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport, WitnessPat,
19};
20use rustc_session::lint::builtin::{
21 BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
22};
23use rustc_span::edit_distance::find_best_match_for_name;
24use rustc_span::hygiene::DesugaringKind;
25use rustc_span::{Ident, Span};
26use rustc_trait_selection::infer::InferCtxtExt;
27use tracing::instrument;
28
29use crate::diagnostics::*;
30
31pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
32 let typeck_results = tcx.typeck(def_id);
33 let (thir, expr) = tcx.thir_body(def_id)?;
34 let thir = thir.borrow();
35 let pattern_arena = TypedArena::default();
36 let dropless_arena = DroplessArena::default();
37 let mut visitor = MatchVisitor {
38 tcx,
39 thir: &*thir,
40 typeck_results,
41 typing_env: ty::TypingEnv::post_typeck_until_borrowck_for_mir_build(tcx, def_id),
42 hir_source: tcx.local_def_id_to_hir_id(def_id),
43 let_source: LetSource::None,
44 pattern_arena: &pattern_arena,
45 dropless_arena: &dropless_arena,
46 error: Ok(()),
47 };
48 visitor.visit_expr(&thir[expr]);
49
50 let origin = match tcx.def_kind(def_id) {
51 DefKind::AssocFn | DefKind::Fn => "function argument",
52 DefKind::Closure => "closure argument",
53 _ if thir.params.is_empty() => "",
56 kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected function parameters in THIR: {0:?} {1:?}",
kind, def_id))bug!("unexpected function parameters in THIR: {kind:?} {def_id:?}"),
57 };
58
59 for param in thir.params.iter() {
60 if let Some(ref pattern) = param.pat {
61 visitor.check_binding_is_irrefutable(pattern, origin, None, None, None);
62 }
63 }
64 visitor.error
65}
66
67#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RefutableFlag {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RefutableFlag::Irrefutable => "Irrefutable",
RefutableFlag::Refutable => "Refutable",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RefutableFlag { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RefutableFlag {
#[inline]
fn clone(&self) -> RefutableFlag { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for RefutableFlag {
#[inline]
fn eq(&self, other: &RefutableFlag) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
68enum RefutableFlag {
69 Irrefutable,
70 Refutable,
71}
72use RefutableFlag::*;
73
74#[derive(#[automatically_derived]
impl ::core::clone::Clone for LetSource {
#[inline]
fn clone(&self) -> LetSource { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LetSource { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LetSource {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
LetSource::None => "None",
LetSource::PlainLet => "PlainLet",
LetSource::IfLet => "IfLet",
LetSource::IfLetGuard => "IfLetGuard",
LetSource::LetElse => "LetElse",
LetSource::WhileLet => "WhileLet",
LetSource::Else => "Else",
LetSource::ElseIfLet => "ElseIfLet",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for LetSource {
#[inline]
fn eq(&self, other: &LetSource) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LetSource {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
75enum LetSource {
76 None,
77 PlainLet,
78 IfLet,
79 IfLetGuard,
80 LetElse,
81 WhileLet,
82 Else,
83 ElseIfLet,
84}
85
86struct MatchVisitor<'p, 'tcx> {
87 tcx: TyCtxt<'tcx>,
88 typing_env: ty::TypingEnv<'tcx>,
89 typeck_results: &'tcx ty::TypeckResults<'tcx>,
90 thir: &'p Thir<'tcx>,
91 hir_source: HirId,
92 let_source: LetSource,
93 pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
94 dropless_arena: &'p DroplessArena,
95 error: Result<(), ErrorGuaranteed>,
99}
100
101impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> {
103 fn thir(&self) -> &'p Thir<'tcx> {
104 self.thir
105 }
106
107 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("visit_arm",
"rustc_mir_build::thir::pattern::check_match",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(107u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("arm")
}> =
::tracing::__macro_support::FieldName::new("arm");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.with_hir_source(arm.hir_id,
|this|
{
if let Some(expr) = arm.guard {
this.with_let_source(LetSource::IfLetGuard,
|this| { this.visit_expr(&this.thir[expr]) });
}
this.visit_pat(&arm.pattern);
this.visit_expr(&self.thir[arm.body]);
});
}
}
}#[instrument(level = "trace", skip(self))]
108 fn visit_arm(&mut self, arm: &'p Arm<'tcx>) {
109 self.with_hir_source(arm.hir_id, |this| {
110 if let Some(expr) = arm.guard {
111 this.with_let_source(LetSource::IfLetGuard, |this| {
112 this.visit_expr(&this.thir[expr])
113 });
114 }
115 this.visit_pat(&arm.pattern);
116 this.visit_expr(&self.thir[arm.body]);
117 });
118 }
119
120 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("visit_expr",
"rustc_mir_build::thir::pattern::check_match",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(120u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ex")
}> =
::tracing::__macro_support::FieldName::new("ex");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ex)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match ex.kind {
ExprKind::Scope { value, hir_id, .. } => {
self.with_hir_source(hir_id,
|this| { this.visit_expr(&this.thir[value]); });
return;
}
ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
let let_source =
match ex.span.desugaring_kind() {
Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
_ =>
match self.let_source {
LetSource::Else => LetSource::ElseIfLet,
_ => LetSource::IfLet,
},
};
self.with_let_source(let_source,
|this| this.visit_expr(&self.thir[cond]));
self.with_let_source(LetSource::None,
|this| { this.visit_expr(&this.thir[then]); });
if let Some(else_) = else_opt {
self.with_let_source(LetSource::Else,
|this| { this.visit_expr(&this.thir[else_]) });
}
return;
}
ExprKind::Match { scrutinee, ref arms, match_source } => {
self.check_match(scrutinee, arms, match_source, ex.span);
}
ExprKind::LoopMatch {
match_data: LoopMatchMatchData {
scrutinee, ref arms, span
}, .. } => {
self.check_match(scrutinee, arms, MatchSource::Normal,
span);
}
ExprKind::Let { ref pat, expr } => {
self.check_let(pat, Some(expr), ex.span, None);
}
ExprKind::LogicalOp { op: LogicalOp::And, .. } if
!#[allow(non_exhaustive_omitted_patterns)] match self.let_source
{
LetSource::None => true,
_ => false,
} => {
let mut chain_refutabilities = Vec::new();
let Ok(()) =
self.visit_land(ex,
&mut chain_refutabilities) else { return };
if let [Some((_, Irrefutable))] = chain_refutabilities[..] {
self.lint_single_let(ex.span, None, None);
}
return;
}
_ => {}
};
self.with_let_source(LetSource::None,
|this| visit::walk_expr(this, ex));
}
}
}#[instrument(level = "trace", skip(self))]
121 fn visit_expr(&mut self, ex: &'p Expr<'tcx>) {
122 match ex.kind {
123 ExprKind::Scope { value, hir_id, .. } => {
124 self.with_hir_source(hir_id, |this| {
125 this.visit_expr(&this.thir[value]);
126 });
127 return;
128 }
129 ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
130 let let_source = match ex.span.desugaring_kind() {
132 Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
133 _ => match self.let_source {
134 LetSource::Else => LetSource::ElseIfLet,
135 _ => LetSource::IfLet,
136 },
137 };
138 self.with_let_source(let_source, |this| this.visit_expr(&self.thir[cond]));
139 self.with_let_source(LetSource::None, |this| {
140 this.visit_expr(&this.thir[then]);
141 });
142 if let Some(else_) = else_opt {
143 self.with_let_source(LetSource::Else, |this| {
144 this.visit_expr(&this.thir[else_])
145 });
146 }
147 return;
148 }
149 ExprKind::Match { scrutinee, ref arms, match_source } => {
150 self.check_match(scrutinee, arms, match_source, ex.span);
151 }
152 ExprKind::LoopMatch {
153 match_data: LoopMatchMatchData { scrutinee, ref arms, span },
154 ..
155 } => {
156 self.check_match(scrutinee, arms, MatchSource::Normal, span);
157 }
158 ExprKind::Let { ref pat, expr } => {
159 self.check_let(pat, Some(expr), ex.span, None);
160 }
161 ExprKind::LogicalOp { op: LogicalOp::And, .. }
162 if !matches!(self.let_source, LetSource::None) =>
163 {
164 let mut chain_refutabilities = Vec::new();
165 let Ok(()) = self.visit_land(ex, &mut chain_refutabilities) else { return };
166 if let [Some((_, Irrefutable))] = chain_refutabilities[..] {
168 self.lint_single_let(ex.span, None, None);
169 }
170 return;
171 }
172 _ => {}
173 };
174 self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex));
175 }
176
177 fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) {
178 match stmt.kind {
179 StmtKind::Let { ref pattern, initializer, else_block, hir_id, span, .. } => {
180 self.with_hir_source(hir_id, |this| {
181 let let_source =
182 if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet };
183 let else_span = else_block.map(|bid| this.thir.blocks[bid].span);
184 this.with_let_source(let_source, |this| {
185 this.check_let(pattern, initializer, span, else_span)
186 });
187 visit::walk_stmt(this, stmt);
188 });
189 }
190 StmtKind::Expr { .. } => {
191 visit::walk_stmt(self, stmt);
192 }
193 }
194 }
195}
196
197impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
198 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("with_let_source",
"rustc_mir_build::thir::pattern::check_match",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(198u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("let_source")
}> =
::tracing::__macro_support::FieldName::new("let_source");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_source)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let old_let_source = self.let_source;
self.let_source = let_source;
f(self);
self.let_source = old_let_source;
}
}
}#[instrument(level = "trace", skip(self, f))]
199 fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
200 let old_let_source = self.let_source;
201 self.let_source = let_source;
202 f(self);
203 self.let_source = old_let_source;
204 }
205
206 fn with_hir_source<T>(&mut self, new_hir_source: HirId, f: impl FnOnce(&mut Self) -> T) -> T {
207 let old_hir_source = self.hir_source;
208 self.hir_source = new_hir_source;
209 let ret = f(self);
210 self.hir_source = old_hir_source;
211 ret
212 }
213
214 fn visit_land(
217 &mut self,
218 ex: &'p Expr<'tcx>,
219 accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
220 ) -> Result<(), ErrorGuaranteed> {
221 match ex.kind {
222 ExprKind::Scope { value, hir_id, .. } => {
223 self.with_hir_source(hir_id, |this| this.visit_land(&this.thir[value], accumulator))
224 }
225 ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
226 let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
228 let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
229 accumulator.push(res_rhs);
230 res_lhs
231 }
232 _ => {
233 let res = self.visit_land_rhs(ex)?;
234 accumulator.push(res);
235 Ok(())
236 }
237 }
238 }
239
240 fn visit_land_rhs(
244 &mut self,
245 ex: &'p Expr<'tcx>,
246 ) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
247 match ex.kind {
248 ExprKind::Scope { value, hir_id, .. } => {
249 self.with_hir_source(hir_id, |this| this.visit_land_rhs(&this.thir[value]))
250 }
251 ExprKind::Let { ref pat, expr } => {
252 let expr = &self.thir()[expr];
253 self.with_let_source(LetSource::None, |this| {
254 this.visit_expr(expr);
255 });
256 Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
257 }
258 _ => {
259 self.with_let_source(LetSource::None, |this| {
260 this.visit_expr(ex);
261 });
262 Ok(None)
263 }
264 }
265 }
266
267 fn lower_pattern(
268 &mut self,
269 cx: &PatCtxt<'p, 'tcx>,
270 pat: &'p Pat<'tcx>,
271 ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
272 if let Err(err) = pat.pat_error_reported() {
273 self.error = Err(err);
274 Err(err)
275 } else {
276 let refutable = if cx.refutable { Refutable } else { Irrefutable };
278 let mut err = Ok(());
279 pat.walk_always(|pat| {
280 check_borrow_conflicts_in_at_patterns(self, pat);
281 check_for_bindings_named_same_as_variants(self, pat, refutable);
282 err = err.and(check_never_pattern(cx, pat));
283 });
284 err?;
285 Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
286 }
287 }
288
289 fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
292 use ExprKind::*;
293 match &scrutinee.kind {
294 Deref { .. } => false,
297 Field { lhs, .. } => {
299 let lhs = &self.thir()[*lhs];
300 match lhs.ty.kind() {
301 ty::Adt(def, _) if def.is_union() => false,
302 _ => self.is_known_valid_scrutinee(lhs),
303 }
304 }
305 Index { lhs, .. } => {
307 let lhs = &self.thir()[*lhs];
308 self.is_known_valid_scrutinee(lhs)
309 }
310
311 Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
313
314 NeverToAny { source }
316 | Cast { source }
317 | Use { source }
318 | PointerCoercion { source, .. }
319 | PlaceTypeAscription { source, .. }
320 | ValueTypeAscription { source, .. }
321 | PlaceUnwrapUnsafeBinder { source }
322 | ValueUnwrapUnsafeBinder { source }
323 | WrapUnsafeBinder { source } => self.is_known_valid_scrutinee(&self.thir()[*source]),
324
325 Become { .. }
327 | Break { .. }
328 | Continue { .. }
329 | ConstContinue { .. }
330 | Return { .. } => true,
331
332 Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
334
335 RawBorrow { .. }
337 | Adt { .. }
338 | Array { .. }
339 | Binary { .. }
340 | Block { .. }
341 | Borrow { .. }
342 | Call { .. }
343 | ByUse { .. }
344 | Closure { .. }
345 | ConstBlock { .. }
346 | ConstParam { .. }
347 | If { .. }
348 | Literal { .. }
349 | LogicalOp { .. }
350 | Loop { .. }
351 | LoopMatch { .. }
352 | Match { .. }
353 | NamedConst { .. }
354 | NonHirLiteral { .. }
355 | Repeat { .. }
356 | StaticRef { .. }
357 | ThreadLocalRef { .. }
358 | Tuple { .. }
359 | Unary { .. }
360 | UpvarRef { .. }
361 | VarRef { .. }
362 | ZstLiteral { .. }
363 | Yield { .. }
364 | Reborrow { .. } => true,
365 }
366 }
367
368 fn new_cx(
369 &self,
370 refutability: RefutableFlag,
371 whole_match_span: Option<Span>,
372 scrutinee: Option<&Expr<'tcx>>,
373 scrut_span: Span,
374 ) -> PatCtxt<'p, 'tcx> {
375 let refutable = match refutability {
376 Irrefutable => false,
377 Refutable => true,
378 };
379 let known_valid_scrutinee =
382 scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
383 PatCtxt {
384 tcx: self.tcx,
385 typeck_results: self.typeck_results,
386 typing_env: self.typing_env,
387 module: self.tcx.parent_module(self.hir_source),
388 dropless_arena: self.dropless_arena,
389 match_lint_level: self.hir_source,
390 whole_match_span,
391 scrut_span,
392 refutable,
393 known_valid_scrutinee,
394 internal_state: Default::default(),
395 }
396 }
397
398 fn analyze_patterns(
399 &mut self,
400 cx: &PatCtxt<'p, 'tcx>,
401 arms: &[MatchArm<'p, 'tcx>],
402 scrut_ty: Ty<'tcx>,
403 ) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
404 let report =
405 rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
406 self.error = Err(err);
407 err
408 })?;
409
410 for (arm, is_useful) in report.arm_usefulness.iter() {
412 if let Usefulness::Useful(redundant_subpats) = is_useful
413 && !redundant_subpats.is_empty()
414 {
415 let mut redundant_subpats = redundant_subpats.clone();
416 redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
418 for (pat, explanation) in redundant_subpats {
419 report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None)
420 }
421 }
422 }
423 Ok(report)
424 }
425
426 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_let",
"rustc_mir_build::thir::pattern::check_match",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(426u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat")
}> =
::tracing::__macro_support::FieldName::new("pat");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("scrutinee")
}> =
::tracing::__macro_support::FieldName::new("scrutinee");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("else_span")
}> =
::tracing::__macro_support::FieldName::new("else_span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scrutinee)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&else_span)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if !(self.let_source != LetSource::None) {
::core::panicking::panic("assertion failed: self.let_source != LetSource::None")
};
let scrut = scrutinee.map(|id| &self.thir[id]);
if let LetSource::PlainLet = self.let_source {
if let hir::Node::LetStmt(&hir::LetStmt {
source: hir::LocalSource::AssignDesugar, .. }) =
self.tcx.hir_node(self.hir_source) {
self.check_binding_is_irrefutable(pat, "assignment",
Some(Inform { descr: "destructuring assignments" }), scrut,
None);
} else {
self.check_binding_is_irrefutable(pat, "local binding",
Some(Inform { descr: "`let` bindings" }), scrut,
Some(span));
}
} else if let Ok(Irrefutable) =
self.is_let_irrefutable(pat, scrut) {
if span.from_expansion() {
self.lint_single_let(span, None, None);
return;
}
let let_else_span =
self.check_irrefutable_option_some(pat, scrut, span);
let sm = self.tcx.sess.source_map();
let next_token_start =
sm.span_extend_while_whitespace(span.clone()).hi();
let line_span =
sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
let else_keyword_span = sm.span_until_whitespace(line_span);
self.lint_single_let(span, Some(else_keyword_span),
let_else_span);
}
}
}
}#[instrument(level = "trace", skip(self))]
427 fn check_let(
428 &mut self,
429 pat: &'p Pat<'tcx>,
430 scrutinee: Option<ExprId>,
431 span: Span,
432 else_span: Option<Span>,
433 ) {
434 assert!(self.let_source != LetSource::None);
435 let scrut = scrutinee.map(|id| &self.thir[id]);
436 if let LetSource::PlainLet = self.let_source {
437 if let hir::Node::LetStmt(&hir::LetStmt {
440 source: hir::LocalSource::AssignDesugar,
441 ..
442 }) = self.tcx.hir_node(self.hir_source)
443 {
444 self.check_binding_is_irrefutable(
445 pat,
446 "assignment",
447 Some(Inform { descr: "destructuring assignments" }),
448 scrut,
449 None,
450 );
451 } else {
452 self.check_binding_is_irrefutable(
453 pat,
454 "local binding",
455 Some(Inform { descr: "`let` bindings" }),
456 scrut,
457 Some(span),
458 );
459 }
460 } else if let Ok(Irrefutable) = self.is_let_irrefutable(pat, scrut) {
461 if span.from_expansion() {
462 self.lint_single_let(span, None, None);
463 return;
464 }
465 let let_else_span = self.check_irrefutable_option_some(pat, scrut, span);
466
467 let sm = self.tcx.sess.source_map();
468 let next_token_start = sm.span_extend_while_whitespace(span.clone()).hi();
469 let line_span = sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
470 let else_keyword_span = sm.span_until_whitespace(line_span);
471 self.lint_single_let(span, Some(else_keyword_span), let_else_span);
472 }
473 }
474
475 fn check_irrefutable_option_some(
477 &self,
478 pat: &'p Pat<'tcx>,
479 initializer: Option<&Expr<'tcx>>,
480 span: Span,
481 ) -> Option<LetElseReplacementSuggestion> {
482 if let sm = self.tcx.sess.source_map()
483 && let Some(initializer) = initializer
484 && let Some(s_ty) = initializer.ty.ty_adt_def()
485 && self.tcx.is_diagnostic_item(rustc_span::sym::Option, s_ty.did())
486 && let ExprKind::Scope { value, .. } = initializer.kind
487 && let initializer_expr = &self.thir[value]
488 && let ExprKind::Adt(AdtExpr { fields, .. }) = &initializer_expr.kind
489 && let Some(field) = fields.first()
490 && let inner = &self.thir[field.expr]
491 && let Some(inner_ty) = inner.ty.ty_adt_def()
492 && self.tcx.is_diagnostic_item(rustc_span::sym::Option, inner_ty.did())
493 && let Ok(rhs) = sm.span_to_snippet(inner.span)
494 && let Ok(lhs) = sm.span_to_snippet(pat.span)
495 {
496 let lhs = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Some({0})", lhs))
})format!("Some({})", lhs);
497 Some(LetElseReplacementSuggestion { span, lhs, rhs })
498 } else {
499 None
500 }
501 }
502
503 fn check_match(
504 &mut self,
505 scrut: ExprId,
506 arms: &[ArmId],
507 source: hir::MatchSource,
508 expr_span: Span,
509 ) {
510 let scrut = &self.thir[scrut];
511 let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
512
513 let mut tarms = Vec::with_capacity(arms.len());
514 for &arm in arms {
515 let arm = &self.thir.arms[arm];
516 let got_error = self.with_hir_source(arm.hir_id, |this| {
517 let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
518 let arm =
519 MatchArm { pat, arm_data: this.hir_source, has_guard: arm.guard.is_some() };
520 tarms.push(arm);
521 false
522 });
523 if got_error {
524 return;
525 }
526 }
527
528 let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
529
530 match source {
531 hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
534 hir::MatchSource::ForLoopDesugar
535 | hir::MatchSource::Postfix
536 | hir::MatchSource::Normal
537 | hir::MatchSource::FormatArgs => {
538 let is_match_arm =
539 #[allow(non_exhaustive_omitted_patterns)] match source {
hir::MatchSource::Postfix | hir::MatchSource::Normal => true,
_ => false,
}matches!(source, hir::MatchSource::Postfix | hir::MatchSource::Normal);
540 report_arm_reachability(&cx, &report, is_match_arm);
541 }
542 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
545 }
546
547 let witnesses = report.non_exhaustiveness_witnesses;
549 if !witnesses.is_empty() {
550 if source == hir::MatchSource::ForLoopDesugar
551 && let [_, snd_arm] = *arms
552 {
553 let pat = &self.thir[snd_arm].pattern;
555 if true {
{
match (&pat.span.desugaring_kind(), &Some(DesugaringKind::ForLoop)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(pat.span.desugaring_kind(), Some(DesugaringKind::ForLoop));
557 let PatKind::Variant { ref subpatterns, .. } = pat.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
558 let [pat_field] = &subpatterns[..] else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
559 self.check_binding_is_irrefutable(
560 &pat_field.pattern,
561 "`for` loop binding",
562 None,
563 None,
564 None,
565 );
566 } else {
567 let braces_span = match source {
570 hir::MatchSource::Normal => scrut
571 .span
572 .find_ancestor_in_same_ctxt(expr_span)
573 .map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
574 hir::MatchSource::Postfix => {
575 scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
578 let sm = self.tcx.sess.source_map();
579 let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
580 if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
581 let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
582 sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
584 } else {
585 None
586 }
587 })
588 }
589 hir::MatchSource::ForLoopDesugar
590 | hir::MatchSource::TryDesugar(_)
591 | hir::MatchSource::AwaitDesugar
592 | hir::MatchSource::FormatArgs => None,
593 };
594
595 let would_be_exhaustive_without_guards = {
598 let any_arm_has_guard = tarms.iter().any(|arm| arm.has_guard);
599 any_arm_has_guard && {
600 let guardless_arms: Vec<_> =
601 tarms.iter().map(|arm| MatchArm { has_guard: false, ..*arm }).collect();
602 rustc_pattern_analysis::rustc::analyze_match(&cx, &guardless_arms, scrut.ty)
603 .is_ok_and(|report| report.non_exhaustiveness_witnesses.is_empty())
604 }
605 };
606 self.error = Err(report_non_exhaustive_match(
607 &cx,
608 self.thir,
609 scrut.ty,
610 scrut.span,
611 witnesses,
612 arms,
613 braces_span,
614 would_be_exhaustive_without_guards,
615 ));
616 }
617 }
618 }
619
620 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lint_single_let",
"rustc_mir_build::thir::pattern::check_match",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(620u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("let_span")
}> =
::tracing::__macro_support::FieldName::new("let_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("else_keyword_span")
}> =
::tracing::__macro_support::FieldName::new("else_keyword_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("let_else_span")
}> =
::tracing::__macro_support::FieldName::new("let_else_span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&else_keyword_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_else_span)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
report_irrefutable_let_patterns(self.tcx, self.hir_source,
self.let_source, 1, let_span, else_keyword_span,
let_else_span);
}
}
}#[instrument(level = "trace", skip(self))]
621 fn lint_single_let(
622 &mut self,
623 let_span: Span,
624 else_keyword_span: Option<Span>,
625 let_else_span: Option<LetElseReplacementSuggestion>,
626 ) {
627 report_irrefutable_let_patterns(
628 self.tcx,
629 self.hir_source,
630 self.let_source,
631 1,
632 let_span,
633 else_keyword_span,
634 let_else_span,
635 );
636 }
637
638 fn analyze_binding(
639 &mut self,
640 pat: &'p Pat<'tcx>,
641 refutability: RefutableFlag,
642 scrut: Option<&Expr<'tcx>>,
643 ) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
644 let cx = self.new_cx(refutability, None, scrut, pat.span);
645 let pat = self.lower_pattern(&cx, pat)?;
646 let arms = [MatchArm { pat, arm_data: self.hir_source, has_guard: false }];
647 let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?;
648 Ok((cx, report))
649 }
650
651 fn is_let_irrefutable(
652 &mut self,
653 pat: &'p Pat<'tcx>,
654 scrut: Option<&Expr<'tcx>>,
655 ) -> Result<RefutableFlag, ErrorGuaranteed> {
656 let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?;
657 report_arm_reachability(&cx, &report, false);
659 Ok(if report.non_exhaustiveness_witnesses.is_empty() { Irrefutable } else { Refutable })
662 }
663
664 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_binding_is_irrefutable",
"rustc_mir_build::thir::pattern::check_match",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(664u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat")
}> =
::tracing::__macro_support::FieldName::new("pat");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("inform")
}> =
::tracing::__macro_support::FieldName::new("inform");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("scrut")
}> =
::tracing::__macro_support::FieldName::new("scrut");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sp")
}> =
::tracing::__macro_support::FieldName::new("sp");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&origin as
&dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inform)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scrut)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let pattern_ty = pat.ty;
let Ok((cx, report)) =
self.analyze_binding(pat, Irrefutable, scrut) else { return };
let witnesses = report.non_exhaustiveness_witnesses;
if witnesses.is_empty() { return; }
let mut let_suggestion = None;
let mut misc_suggestion = None;
let mut interpreted_as_const = None;
let mut interpreted_as_const_sugg = None;
if let Some(def_id) =
is_const_pat_that_looks_like_binding(self.tcx, pat) {
let span = self.tcx.def_span(def_id);
let variable = self.tcx.item_name(def_id).to_string();
interpreted_as_const =
Some(InterpretedAsConst {
span,
variable: variable.clone(),
});
interpreted_as_const_sugg =
Some(InterpretedAsConstSugg { span: pat.span, variable });
} else if let PatKind::Constant { .. } = pat.kind &&
let Ok(snippet) =
self.tcx.sess.source_map().span_to_snippet(pat.span) {
if snippet.chars().all(|c| c.is_digit(10)) {
misc_suggestion =
Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
start_span: pat.span.shrink_to_lo(),
});
}
}
if let Some(span) = sp &&
self.tcx.sess.source_map().is_span_accessible(span) &&
interpreted_as_const.is_none() && scrut.is_some() {
let mut bindings = ::alloc::vec::Vec::new();
pat.each_binding(|name, _, _, _| bindings.push(name));
let semi_span = span.shrink_to_hi();
let start_span = span.shrink_to_lo();
let end_span = semi_span.shrink_to_lo();
let count = witnesses.len();
let_suggestion =
Some(if bindings.is_empty() {
SuggestLet::If { start_span, semi_span, count }
} else { SuggestLet::Else { end_span, count } });
};
let adt_defined_here =
report_adt_defined_here(self.tcx, pattern_ty, &witnesses,
false);
let witness_1_is_privately_uninhabited =
if let Some(witness_1) = witnesses.get(0) &&
let ty::Adt(adt, args) = witness_1.ty().kind() &&
adt.is_enum() &&
let Constructor::Variant(variant_index) = witness_1.ctor() {
let variant_inhabited =
adt.variant(*variant_index).inhabited_predicate(self.tcx,
*adt).instantiate(self.tcx, args);
variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
&&
!variant_inhabited.apply_ignore_module(self.tcx,
cx.typing_env)
} else { false };
let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
self.error =
Err(self.tcx.dcx().emit_err(PatternNotCovered {
span: pat.span,
origin,
uncovered: Uncovered::new(pat.span, &cx, witnesses),
inform,
interpreted_as_const,
interpreted_as_const_sugg,
witness_1_is_privately_uninhabited,
witness_1,
_p: (),
pattern_ty,
let_suggestion,
misc_suggestion,
adt_defined_here,
}));
}
}
}#[instrument(level = "trace", skip(self))]
665 fn check_binding_is_irrefutable(
666 &mut self,
667 pat: &'p Pat<'tcx>,
668 origin: &str,
669 inform: Option<Inform>,
670 scrut: Option<&Expr<'tcx>>,
671 sp: Option<Span>,
672 ) {
673 let pattern_ty = pat.ty;
674
675 let Ok((cx, report)) = self.analyze_binding(pat, Irrefutable, scrut) else { return };
676 let witnesses = report.non_exhaustiveness_witnesses;
677 if witnesses.is_empty() {
678 return;
680 }
681
682 let mut let_suggestion = None;
683 let mut misc_suggestion = None;
684 let mut interpreted_as_const = None;
685 let mut interpreted_as_const_sugg = None;
686
687 if let Some(def_id) = is_const_pat_that_looks_like_binding(self.tcx, pat) {
688 let span = self.tcx.def_span(def_id);
689 let variable = self.tcx.item_name(def_id).to_string();
690 interpreted_as_const = Some(InterpretedAsConst { span, variable: variable.clone() });
692 interpreted_as_const_sugg = Some(InterpretedAsConstSugg { span: pat.span, variable });
693 } else if let PatKind::Constant { .. } = pat.kind
694 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
695 {
696 if snippet.chars().all(|c| c.is_digit(10)) {
698 misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
700 start_span: pat.span.shrink_to_lo(),
701 });
702 }
703 }
704
705 if let Some(span) = sp
706 && self.tcx.sess.source_map().is_span_accessible(span)
707 && interpreted_as_const.is_none()
708 && scrut.is_some()
709 {
710 let mut bindings = vec![];
711 pat.each_binding(|name, _, _, _| bindings.push(name));
712
713 let semi_span = span.shrink_to_hi();
714 let start_span = span.shrink_to_lo();
715 let end_span = semi_span.shrink_to_lo();
716 let count = witnesses.len();
717
718 let_suggestion = Some(if bindings.is_empty() {
719 SuggestLet::If { start_span, semi_span, count }
720 } else {
721 SuggestLet::Else { end_span, count }
722 });
723 };
724
725 let adt_defined_here = report_adt_defined_here(self.tcx, pattern_ty, &witnesses, false);
726
727 let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
730 && let ty::Adt(adt, args) = witness_1.ty().kind()
731 && adt.is_enum()
732 && let Constructor::Variant(variant_index) = witness_1.ctor()
733 {
734 let variant_inhabited = adt
735 .variant(*variant_index)
736 .inhabited_predicate(self.tcx, *adt)
737 .instantiate(self.tcx, args);
738 variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
739 && !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env)
740 } else {
741 false
742 };
743
744 let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
745
746 self.error = Err(self.tcx.dcx().emit_err(PatternNotCovered {
747 span: pat.span,
748 origin,
749 uncovered: Uncovered::new(pat.span, &cx, witnesses),
750 inform,
751 interpreted_as_const,
752 interpreted_as_const_sugg,
753 witness_1_is_privately_uninhabited,
754 witness_1,
755 _p: (),
756 pattern_ty,
757 let_suggestion,
758 misc_suggestion,
759 adt_defined_here,
760 }));
761 }
762}
763
764fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) {
776 let PatKind::Binding { name, mode, ty, subpattern: Some(ref sub), .. } = pat.kind else {
778 return;
779 };
780
781 let is_binding_by_move = |ty: Ty<'tcx>| !cx.tcx.type_is_copy_modulo_regions(cx.typing_env, ty);
782
783 let sess = cx.tcx.sess;
784
785 let mut_outer = match mode.0 {
787 ByRef::No if is_binding_by_move(ty) => {
788 let mut conflicts_ref = Vec::new();
790 sub.each_binding(|_, mode, _, span| {
791 if #[allow(non_exhaustive_omitted_patterns)] match mode {
ByRef::Yes(..) => true,
_ => false,
}matches!(mode, ByRef::Yes(..)) {
792 conflicts_ref.push(span)
793 }
794 });
795 if !conflicts_ref.is_empty() {
796 sess.dcx().emit_err(BorrowOfMovedValue {
797 binding_span: pat.span,
798 conflicts_ref,
799 name: Ident::new(name, pat.span),
800 ty,
801 suggest_borrowing: Some(pat.span.shrink_to_lo()),
802 });
803 }
804 return;
805 }
806 ByRef::No => return,
807 ByRef::Yes(_, m) => m,
808 };
809
810 let mut conflicts_move = Vec::new();
813 let mut conflicts_mut_mut = Vec::new();
814 let mut conflicts_mut_ref = Vec::new();
815 sub.each_binding(|name, mode, ty, span| {
816 match mode {
817 ByRef::Yes(_, mut_inner) => match (mut_outer, mut_inner) {
818 (Mutability::Not, Mutability::Not) => {}
820 (Mutability::Mut, Mutability::Mut) => {
822 conflicts_mut_mut.push(Conflict::Mut { span, name })
823 }
824 (Mutability::Not, Mutability::Mut) => {
825 conflicts_mut_ref.push(Conflict::Mut { span, name })
826 }
827 (Mutability::Mut, Mutability::Not) => {
828 conflicts_mut_ref.push(Conflict::Ref { span, name })
829 }
830 },
831 ByRef::No if is_binding_by_move(ty) => {
832 conflicts_move.push(Conflict::Moved { span, name }) }
834 ByRef::No => {} }
836 });
837
838 let report_mut_mut = !conflicts_mut_mut.is_empty();
839 let report_mut_ref = !conflicts_mut_ref.is_empty();
840 let report_move_conflict = !conflicts_move.is_empty();
841
842 let mut occurrences = match mut_outer {
843 Mutability::Mut => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Conflict::Mut { span: pat.span, name }]))vec![Conflict::Mut { span: pat.span, name }],
844 Mutability::Not => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Conflict::Ref { span: pat.span, name }]))vec![Conflict::Ref { span: pat.span, name }],
845 };
846 occurrences.extend(conflicts_mut_mut);
847 occurrences.extend(conflicts_mut_ref);
848 occurrences.extend(conflicts_move);
849
850 if report_mut_mut {
852 sess.dcx().emit_err(MultipleMutBorrows { span: pat.span, occurrences });
854 } else if report_mut_ref {
855 match mut_outer {
857 Mutability::Mut => {
858 sess.dcx().emit_err(AlreadyMutBorrowed { span: pat.span, occurrences });
859 }
860 Mutability::Not => {
861 sess.dcx().emit_err(AlreadyBorrowed { span: pat.span, occurrences });
862 }
863 };
864 } else if report_move_conflict {
865 sess.dcx().emit_err(MovedWhileBorrowed { span: pat.span, occurrences });
867 }
868}
869
870fn check_for_bindings_named_same_as_variants(
871 cx: &MatchVisitor<'_, '_>,
872 pat: &Pat<'_>,
873 rf: RefutableFlag,
874) {
875 if let PatKind::Binding {
876 name,
877 mode: BindingMode(ByRef::No, Mutability::Not),
878 subpattern: None,
879 ty,
880 ..
881 } = pat.kind
882 && let ty::Adt(edef, _) = ty.peel_refs().kind()
883 && edef.is_enum()
884 && edef
885 .variants()
886 .iter()
887 .any(|variant| variant.name == name && variant.ctor_kind() == Some(CtorKind::Const))
888 {
889 let variant_count = edef.variants().len();
890 let ty_path = { let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(edef.did()) }with_no_trimmed_paths!(cx.tcx.def_path_str(edef.did()));
891 cx.tcx.emit_node_span_lint(
892 BINDINGS_WITH_VARIANT_NAME,
893 cx.hir_source,
894 pat.span,
895 BindingsWithVariantName {
896 suggestion: if rf == Refutable || variant_count == 1 {
900 Some(pat.span)
901 } else {
902 None
903 },
904 ty_path,
905 name: Ident::new(name, pat.span),
906 },
907 )
908 }
909}
910
911fn check_never_pattern<'tcx>(
913 cx: &PatCtxt<'_, 'tcx>,
914 pat: &Pat<'tcx>,
915) -> Result<(), ErrorGuaranteed> {
916 if let PatKind::Never = pat.kind {
917 if !cx.is_uninhabited(pat.ty) {
918 return Err(cx.tcx.dcx().emit_err(NonEmptyNeverPattern { span: pat.span, ty: pat.ty }));
919 }
920 }
921 Ok(())
922}
923
924fn report_irrefutable_let_patterns(
925 tcx: TyCtxt<'_>,
926 id: HirId,
927 source: LetSource,
928 count: usize,
929 span: Span,
930 else_keyword_span: Option<Span>,
931 let_else_span: Option<LetElseReplacementSuggestion>,
932) {
933 macro_rules! emit_diag {
934 ($lint:tt) => {{
935 tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span, $lint { count });
936 }};
937 }
938
939 match source {
940 LetSource::None | LetSource::PlainLet | LetSource::Else => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
941 LetSource::IfLet | LetSource::ElseIfLet => {
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
IrrefutableLetPatternsIfLet { count });
}emit_diag!(IrrefutableLetPatternsIfLet),
942 LetSource::IfLetGuard => {
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
IrrefutableLetPatternsIfLetGuard { count });
}emit_diag!(IrrefutableLetPatternsIfLetGuard),
943 LetSource::LetElse => {
944 let spans = match else_keyword_span {
945 Some(else_keyword_span) => {
946 let mut spans = MultiSpan::from_span(else_keyword_span);
947 spans.push_span_label(
948 span,
949 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("assigning to binding pattern will always succeed"))msg!("assigning to binding pattern will always succeed"),
950 );
951 spans
952 }
953 None => span.into(),
954 };
955
956 tcx.emit_node_span_lint(
957 IRREFUTABLE_LET_PATTERNS,
958 id,
959 spans,
960 IrrefutableLetPatternsLetElse { be_replaced: let_else_span },
961 );
962 }
963 LetSource::WhileLet => {
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
IrrefutableLetPatternsWhileLet { count });
}emit_diag!(IrrefutableLetPatternsWhileLet),
964 }
965}
966
967fn report_unreachable_pattern<'p, 'tcx>(
969 cx: &PatCtxt<'p, 'tcx>,
970 hir_id: HirId,
971 pat: &DeconstructedPat<'p, 'tcx>,
972 explanation: &RedundancyExplanation<'p, 'tcx>,
973 whole_arm_span: Option<Span>,
974) {
975 static CAP_COVERED_BY_MANY: usize = 4;
976 let pat_span = pat.data().span;
977 let mut lint = UnreachablePatternInner {
978 span: Some(pat_span),
979 matches_no_values: None,
980 matches_no_values_ty: **pat.ty(),
981 uninhabited_note: None,
982 covered_by_catchall: None,
983 covered_by_one: None,
984 covered_by_many: None,
985 wanted_constant: None,
986 accessible_constant: None,
987 inaccessible_constant: None,
988 pattern_let_binding: None,
989 suggest_remove: None,
990 };
991 let mut covered_by_many_n_more_count = None;
992 match explanation.covered_by.as_slice() {
993 [] => {
994 lint.span = None; lint.uninhabited_note = Some(()); lint.matches_no_values = Some(pat_span);
998 lint.suggest_remove = whole_arm_span; pat.walk(&mut |subpat| {
1000 let ty = **subpat.ty();
1001 if cx.is_uninhabited(ty) {
1002 lint.matches_no_values_ty = ty;
1003 false } else if #[allow(non_exhaustive_omitted_patterns)] match subpat.ctor() {
Constructor::Ref | Constructor::UnionField => true,
_ => false,
}matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) {
1005 false } else {
1007 true
1008 }
1009 });
1010 }
1011 [covering_pat] if pat_is_catchall(covering_pat) => {
1012 let pat = covering_pat.data();
1014 lint.covered_by_catchall = Some(pat.span);
1015 find_fallback_pattern_typo(cx, hir_id, pat, &mut lint);
1016 }
1017 [covering_pat] => {
1018 lint.covered_by_one = Some(covering_pat.data().span);
1019 }
1020 covering_pats => {
1021 let mut iter = covering_pats.iter();
1022 let mut multispan = MultiSpan::from_span(pat_span);
1023 for p in iter.by_ref().take(CAP_COVERED_BY_MANY) {
1024 multispan.push_span_label(p.data().span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("matches some of the same values"))msg!("matches some of the same values"));
1025 }
1026 let remain = iter.count();
1027 if remain == 0 {
1028 multispan.push_span_label(pat_span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("collectively making this unreachable"))msg!("collectively making this unreachable"));
1029 } else {
1030 covered_by_many_n_more_count = Some(remain);
1031 multispan.push_span_label(
1032 pat_span,
1033 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...and {$covered_by_many_n_more_count} other patterns collectively make this unreachable"))msg!("...and {$covered_by_many_n_more_count} other patterns collectively make this unreachable"),
1034 );
1035 }
1036 lint.covered_by_many = Some(multispan);
1037 }
1038 }
1039 cx.tcx.emit_node_span_lint(
1040 UNREACHABLE_PATTERNS,
1041 hir_id,
1042 pat_span,
1043 UnreachablePattern { inner: lint, covered_by_many_n_more_count },
1044 );
1045}
1046
1047fn find_fallback_pattern_typo<'tcx>(
1049 cx: &PatCtxt<'_, 'tcx>,
1050 hir_id: HirId,
1051 pat: &Pat<'tcx>,
1052 lint: &mut UnreachablePatternInner<'_>,
1053) {
1054 if cx.tcx.lint_level_spec_at_node(UNREACHABLE_PATTERNS, hir_id).is_allow() {
1055 return;
1058 }
1059 if let PatKind::Binding { name, subpattern: None, ty, .. } = pat.kind {
1060 let mut accessible = ::alloc::vec::Vec::new()vec![];
1062 let mut accessible_path = ::alloc::vec::Vec::new()vec![];
1063 let mut inaccessible = ::alloc::vec::Vec::new()vec![];
1064 let mut imported = ::alloc::vec::Vec::new()vec![];
1065 let mut imported_spans = ::alloc::vec::Vec::new()vec![];
1066 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
1067 let parent = cx.tcx.hir_get_parent_item(hir_id);
1068
1069 for item in cx.tcx.hir_crate_items(()).free_items() {
1070 if let DefKind::Use = cx.tcx.def_kind(item.owner_id) {
1071 let item = cx.tcx.hir_expect_item(item.owner_id.def_id);
1073 let hir::ItemKind::Use(path, _) = item.kind else {
1074 continue;
1075 };
1076 if let Some(value_ns) = path.res.value_ns
1077 && let Res::Def(DefKind::Const { .. }, id) = value_ns
1078 && infcx.can_eq(
1079 param_env,
1080 ty,
1081 cx.tcx.type_of(id).instantiate_identity().skip_norm_wip(),
1082 )
1083 {
1084 if cx.tcx.visibility(id).is_accessible_from(parent, cx.tcx) {
1085 let item_name = cx.tcx.item_name(id);
1087 accessible.push(item_name);
1088 accessible_path.push({ let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(id) }with_no_trimmed_paths!(cx.tcx.def_path_str(id)));
1089 } else if cx.tcx.visibility(item.owner_id).is_accessible_from(parent, cx.tcx) {
1090 let ident = item.kind.ident().unwrap();
1093 imported.push(ident.name);
1094 imported_spans.push(ident.span);
1095 }
1096 }
1097 }
1098 if let DefKind::Const { .. } = cx.tcx.def_kind(item.owner_id)
1099 && infcx.can_eq(
1100 param_env,
1101 ty,
1102 cx.tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip(),
1103 )
1104 {
1105 let item_name = cx.tcx.item_name(item.owner_id);
1107 let vis = cx.tcx.visibility(item.owner_id);
1108 if vis.is_accessible_from(parent, cx.tcx) {
1109 accessible.push(item_name);
1110 let path = { let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(item.owner_id) }with_no_trimmed_paths!(cx.tcx.def_path_str(item.owner_id));
1117 accessible_path.push(path);
1118 } else if name == item_name {
1119 inaccessible.push(cx.tcx.def_span(item.owner_id));
1122 }
1123 }
1124 }
1125 if let Some((i, &const_name)) =
1126 accessible.iter().enumerate().find(|&(_, &const_name)| const_name == name)
1127 {
1128 lint.wanted_constant = Some(WantedConstant {
1130 span: pat.span,
1131 is_typo: false,
1132 const_name: const_name.to_string(),
1133 const_path: accessible_path[i].clone(),
1134 });
1135 } else if let Some(name) = find_best_match_for_name(&accessible, name, None) {
1136 lint.wanted_constant = Some(WantedConstant {
1138 span: pat.span,
1139 is_typo: true,
1140 const_name: name.to_string(),
1141 const_path: name.to_string(),
1142 });
1143 } else if let Some(i) =
1144 imported.iter().enumerate().find(|&(_, &const_name)| const_name == name).map(|(i, _)| i)
1145 {
1146 lint.accessible_constant = Some(imported_spans[i]);
1149 } else if let Some(name) = find_best_match_for_name(&imported, name, None) {
1150 lint.wanted_constant = Some(WantedConstant {
1153 span: pat.span,
1154 is_typo: true,
1155 const_path: name.to_string(),
1156 const_name: name.to_string(),
1157 });
1158 } else if !inaccessible.is_empty() {
1159 for span in inaccessible {
1160 lint.inaccessible_constant = Some(span);
1162 }
1163 } else {
1164 for (_, node) in cx.tcx.hir_parent_iter(hir_id) {
1167 match node {
1168 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(let_stmt), .. }) => {
1169 if let hir::PatKind::Binding(_, _, binding_name, _) = let_stmt.pat.kind {
1170 if name == binding_name.name {
1171 lint.pattern_let_binding = Some(binding_name.span);
1172 }
1173 }
1174 }
1175 hir::Node::Block(hir::Block { stmts, .. }) => {
1176 for stmt in *stmts {
1177 if let hir::StmtKind::Let(let_stmt) = stmt.kind
1178 && let hir::PatKind::Binding(_, _, binding_name, _) =
1179 let_stmt.pat.kind
1180 && name == binding_name.name
1181 {
1182 lint.pattern_let_binding = Some(binding_name.span);
1183 }
1184 }
1185 }
1186 hir::Node::Item(_) => break,
1187 _ => {}
1188 }
1189 }
1190 }
1191 }
1192}
1193
1194fn report_arm_reachability<'p, 'tcx>(
1196 cx: &PatCtxt<'p, 'tcx>,
1197 report: &UsefulnessReport<'p, 'tcx>,
1198 is_match_arm: bool,
1199) {
1200 let sm = cx.tcx.sess.source_map();
1201 for (arm, is_useful) in report.arm_usefulness.iter() {
1202 if let Usefulness::Redundant(explanation) = is_useful {
1203 let hir_id = arm.arm_data;
1204 let arm_span = cx.tcx.hir_span(hir_id);
1205 let whole_arm_span = if is_match_arm {
1206 if let Some(comma) = sm.span_followed_by(arm_span, ",") {
1208 Some(arm_span.to(comma))
1209 } else {
1210 Some(arm_span)
1211 }
1212 } else {
1213 None
1214 };
1215 report_unreachable_pattern(cx, hir_id, arm.pat, explanation, whole_arm_span)
1216 }
1217 }
1218}
1219
1220fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
1222 match pat.ctor() {
1223 Constructor::Wildcard => true,
1224 Constructor::Struct | Constructor::Ref => {
1225 pat.iter_fields().all(|ipat| pat_is_catchall(&ipat.pat))
1226 }
1227 _ => false,
1228 }
1229}
1230
1231fn is_const_pat_that_looks_like_binding<'tcx>(tcx: TyCtxt<'tcx>, pat: &Pat<'tcx>) -> Option<DefId> {
1237 if let Some(def_id) = try { pat.extra.as_deref()?.expanded_const? }
1241 && #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
DefKind::Const { .. } => true,
_ => false,
}matches!(tcx.def_kind(def_id), DefKind::Const { .. })
1242 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(pat.span)
1243 && snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
1244 {
1245 Some(def_id)
1246 } else {
1247 None
1248 }
1249}
1250
1251fn report_non_exhaustive_match<'p, 'tcx>(
1253 cx: &PatCtxt<'p, 'tcx>,
1254 thir: &Thir<'tcx>,
1255 scrut_ty: Ty<'tcx>,
1256 sp: Span,
1257 witnesses: Vec<WitnessPat<'p, 'tcx>>,
1258 arms: &[ArmId],
1259 braces_span: Option<Span>,
1260 would_be_exhaustive_without_guards: bool,
1261) -> ErrorGuaranteed {
1262 let is_empty_match = arms.is_empty();
1263 let non_empty_enum = match scrut_ty.kind() {
1264 ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
1265 _ => false,
1266 };
1267 if is_empty_match && !non_empty_enum {
1270 return cx.tcx.dcx().emit_err(NonExhaustivePatternsTypeNotEmpty {
1271 cx,
1272 scrut_span: sp,
1273 braces_span,
1274 ty: scrut_ty,
1275 });
1276 }
1277
1278 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
1280 let mut err = {
cx.tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("non-exhaustive patterns: {0} not covered",
joined_patterns))
})).with_code(E0004)
}struct_span_code_err!(
1281 cx.tcx.dcx(),
1282 sp,
1283 E0004,
1284 "non-exhaustive patterns: {joined_patterns} not covered"
1285 );
1286 err.span_label(
1287 sp,
1288 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pattern{0} {1} not covered",
if witnesses.len() == 1 { "" } else { "s" }, joined_patterns))
})format!(
1289 "pattern{} {} not covered",
1290 rustc_errors::pluralize!(witnesses.len()),
1291 joined_patterns
1292 ),
1293 );
1294
1295 if let Some(AdtDefinedHere { adt_def_span, ty, variants }) =
1297 report_adt_defined_here(cx.tcx, scrut_ty, &witnesses, true)
1298 {
1299 let mut multi_span = MultiSpan::from_span(adt_def_span);
1300 multi_span.push_span_label(adt_def_span, "");
1301 for Variant { span } in variants {
1302 multi_span.push_span_label(span, "not covered");
1303 }
1304 err.span_note(multi_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", ty))
})format!("`{ty}` defined here"));
1305 }
1306 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the matched value is of type `{0}`",
scrut_ty))
})format!("the matched value is of type `{}`", scrut_ty));
1307
1308 if !is_empty_match {
1309 let mut special_tys = FxIndexSet::default();
1310 collect_special_tys(cx, &witnesses[0], &mut special_tys);
1312
1313 for ty in special_tys {
1314 if ty.is_ptr_sized_integral() {
1315 if ty.inner() == cx.tcx.types.usize {
1316 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::MAX` is not treated as exhaustive, so half-open ranges are necessary to match exhaustively",
ty))
})format!(
1317 "`{ty}::MAX` is not treated as exhaustive, \
1318 so half-open ranges are necessary to match exhaustively",
1319 ));
1320 } else if ty.inner() == cx.tcx.types.isize {
1321 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::MIN` and `{0}::MAX` are not treated as exhaustive, so half-open ranges are necessary to match exhaustively",
ty))
})format!(
1322 "`{ty}::MIN` and `{ty}::MAX` are not treated as exhaustive, \
1323 so half-open ranges are necessary to match exhaustively",
1324 ));
1325 }
1326 } else if ty.inner() == cx.tcx.types.str_ {
1327 err.note("`&str` cannot be matched exhaustively, so a wildcard `_` is necessary");
1328 } else if cx.is_foreign_non_exhaustive_enum(ty) {
1329 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively",
ty))
})format!("`{ty}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively"));
1330 } else if cx.is_uninhabited(ty.inner()) {
1331 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited but is not being matched by value, so a wildcard `_` is required",
ty))
})format!("`{ty}` is uninhabited but is not being matched by value, so a wildcard `_` is required"));
1334 }
1335 }
1336 }
1337
1338 if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
1339 if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.typing_env) {
1340 err.note("references are always considered inhabited");
1341 }
1342 }
1343
1344 for &arm in arms {
1345 let arm = &thir.arms[arm];
1346 if let Some(def_id) = is_const_pat_that_looks_like_binding(cx.tcx, &arm.pattern) {
1347 let const_name = cx.tcx.item_name(def_id);
1348 err.span_label(
1349 arm.pattern.span,
1350 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t introduce a new catch-all binding, but rather pattern matches against the value of constant `{0}`",
const_name))
})format!(
1351 "this pattern doesn't introduce a new catch-all binding, but rather pattern \
1352 matches against the value of constant `{const_name}`",
1353 ),
1354 );
1355 err.span_note(cx.tcx.def_span(def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constant `{0}` defined here",
const_name))
})format!("constant `{const_name}` defined here"));
1356 err.span_suggestion_verbose(
1357 arm.pattern.span.shrink_to_hi(),
1358 "if you meant to introduce a binding, use a different name",
1359 "_var".to_string(),
1360 Applicability::MaybeIncorrect,
1361 );
1362 }
1363 }
1364
1365 let suggest_the_witnesses = witnesses.len() < 4;
1367 let suggested_arm = if suggest_the_witnesses {
1368 let pattern = witnesses
1369 .iter()
1370 .map(|witness| cx.print_witness_pat(witness))
1371 .collect::<Vec<String>>()
1372 .join(" | ");
1373 if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns() {
1374 pattern
1376 } else {
1377 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} => todo!()", pattern))
})format!("{pattern} => todo!()")
1379 }
1380 } else {
1381 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_ => todo!()"))
})format!("_ => todo!()")
1383 };
1384 let mut suggestion = None;
1385 let sm = cx.tcx.sess.source_map();
1386 match arms {
1387 [] if let Some(braces_span) = braces_span => {
1388 let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
1390 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", snippet))
})format!("\n{snippet}"), " ")
1391 } else {
1392 (" ".to_string(), "")
1393 };
1394 suggestion = Some((
1395 braces_span,
1396 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{{0}{1}{2},{0}}}", indentation,
more, suggested_arm))
})format!(" {{{indentation}{more}{suggested_arm},{indentation}}}",),
1397 ));
1398 }
1399 [only] => {
1400 let only = &thir[*only];
1401 let (pre_indentation, is_multiline) = if let Some(snippet) =
1402 sm.indentation_before(only.span)
1403 && let Ok(with_trailing) =
1404 sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
1405 && sm.is_multiline(with_trailing)
1406 {
1407 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", snippet))
})format!("\n{snippet}"), true)
1408 } else {
1409 (" ".to_string(), false)
1410 };
1411 let only_body = &thir[only.body];
1412 let comma = if #[allow(non_exhaustive_omitted_patterns)] match only_body.kind {
ExprKind::Block { .. } => true,
_ => false,
}matches!(only_body.kind, ExprKind::Block { .. })
1413 && only.span.eq_ctxt(only_body.span)
1414 && is_multiline
1415 {
1416 ""
1417 } else {
1418 ","
1419 };
1420 suggestion = Some((
1421 only.span.shrink_to_hi(),
1422 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", comma, pre_indentation,
suggested_arm))
})format!("{comma}{pre_indentation}{suggested_arm}"),
1423 ));
1424 }
1425 [.., prev, last] => {
1426 let prev = &thir[*prev];
1427 let last = &thir[*last];
1428 if prev.span.eq_ctxt(last.span) {
1429 let last_body = &thir[last.body];
1430 let comma = if #[allow(non_exhaustive_omitted_patterns)] match last_body.kind {
ExprKind::Block { .. } => true,
_ => false,
}matches!(last_body.kind, ExprKind::Block { .. })
1431 && last.span.eq_ctxt(last_body.span)
1432 {
1433 ""
1434 } else {
1435 ","
1436 };
1437 let spacing = if sm.is_multiline(prev.span.between(last.span)) {
1438 sm.indentation_before(last.span).map(|indent| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}"))
1439 } else {
1440 Some(" ".to_string())
1441 };
1442 if let Some(spacing) = spacing {
1443 suggestion = Some((
1444 last.span.shrink_to_hi(),
1445 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", comma, spacing,
suggested_arm))
})format!("{comma}{spacing}{suggested_arm}"),
1446 ));
1447 }
1448 }
1449 }
1450 _ => {}
1451 }
1452
1453 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ensure that all possible cases are being handled by adding a match arm with a wildcard pattern{0}{1}",
if witnesses.len() > 1 && suggest_the_witnesses &&
suggestion.is_some() {
", a match arm with multiple or-patterns"
} else { "" },
match witnesses.len() {
0 if suggestion.is_some() => " as shown",
0 => "",
1 if suggestion.is_some() =>
" or an explicit pattern as shown",
1 => " or an explicit pattern",
_ if suggestion.is_some() =>
" as shown, or multiple match arms",
_ => " or multiple match arms",
}))
})format!(
1454 "ensure that all possible cases are being handled by adding a match arm with a wildcard \
1455 pattern{}{}",
1456 if witnesses.len() > 1 && suggest_the_witnesses && suggestion.is_some() {
1457 ", a match arm with multiple or-patterns"
1458 } else {
1459 ""
1461 },
1462 match witnesses.len() {
1463 0 if suggestion.is_some() => " as shown",
1465 0 => "",
1466 1 if suggestion.is_some() => " or an explicit pattern as shown",
1467 1 => " or an explicit pattern",
1468 _ if suggestion.is_some() => " as shown, or multiple match arms",
1469 _ => " or multiple match arms",
1470 },
1471 );
1472
1473 if would_be_exhaustive_without_guards {
1474 err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
1475 }
1476 if let Some((span, sugg)) = suggestion {
1477 err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
1478 } else {
1479 err.help(msg);
1480 }
1481 err.emit()
1482}
1483
1484fn joined_uncovered_patterns<'p, 'tcx>(
1485 cx: &PatCtxt<'p, 'tcx>,
1486 witnesses: &[WitnessPat<'p, 'tcx>],
1487) -> String {
1488 const LIMIT: usize = 3;
1489 let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.print_witness_pat(pat);
1490 match witnesses {
1491 [] => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1492 [witness] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
cx.print_witness_pat(witness)))
})format!("`{}`", cx.print_witness_pat(witness)),
1493 [head @ .., tail] if head.len() < LIMIT => {
1494 let head: Vec<_> = head.iter().map(pat_to_str).collect();
1495 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`",
head.join("`, `"), cx.print_witness_pat(tail)))
})format!("`{}` and `{}`", head.join("`, `"), cx.print_witness_pat(tail))
1496 }
1497 _ => {
1498 let (head, tail) = witnesses.split_at(LIMIT);
1499 let head: Vec<_> = head.iter().map(pat_to_str).collect();
1500 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and {1} more",
head.join("`, `"), tail.len()))
})format!("`{}` and {} more", head.join("`, `"), tail.len())
1501 }
1502 }
1503}
1504
1505fn collect_special_tys<'tcx>(
1507 cx: &PatCtxt<'_, 'tcx>,
1508 pat: &WitnessPat<'_, 'tcx>,
1509 special_tys: &mut FxIndexSet<RevealedTy<'tcx>>,
1510) {
1511 if #[allow(non_exhaustive_omitted_patterns)] match pat.ctor() {
Constructor::NonExhaustive | Constructor::Never => true,
_ => false,
}matches!(pat.ctor(), Constructor::NonExhaustive | Constructor::Never) {
1512 special_tys.insert(*pat.ty());
1513 }
1514 if let Constructor::IntRange(range) = pat.ctor() {
1515 if cx.is_range_beyond_boundaries(range, *pat.ty()) {
1516 special_tys.insert(*pat.ty());
1518 }
1519 }
1520 pat.iter_fields().for_each(|field_pat| collect_special_tys(cx, field_pat, special_tys))
1521}
1522
1523fn report_adt_defined_here<'tcx>(
1524 tcx: TyCtxt<'tcx>,
1525 ty: Ty<'tcx>,
1526 witnesses: &[WitnessPat<'_, 'tcx>],
1527 point_at_non_local_ty: bool,
1528) -> Option<AdtDefinedHere<'tcx>> {
1529 let ty = ty.peel_refs();
1530 let ty::Adt(def, _) = ty.kind() else {
1531 return None;
1532 };
1533 let adt_def_span =
1534 tcx.hir_get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
1535 let adt_def_span = if point_at_non_local_ty {
1536 adt_def_span.unwrap_or_else(|| tcx.def_span(def.did()))
1537 } else {
1538 adt_def_span?
1539 };
1540
1541 let mut variants = ::alloc::vec::Vec::new()vec![];
1542 for span in maybe_point_at_variant(tcx, *def, witnesses.iter().take(5)) {
1543 variants.push(Variant { span });
1544 }
1545 Some(AdtDefinedHere { adt_def_span, ty, variants })
1546}
1547
1548fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'p>(
1549 tcx: TyCtxt<'tcx>,
1550 def: AdtDef<'tcx>,
1551 patterns: impl Iterator<Item = &'a WitnessPat<'p, 'tcx>>,
1552) -> Vec<Span> {
1553 let mut covered = ::alloc::vec::Vec::new()vec![];
1554 for pattern in patterns {
1555 if let Constructor::Variant(variant_index) = pattern.ctor() {
1556 if let ty::Adt(this_def, _) = pattern.ty().kind()
1557 && this_def.did() != def.did()
1558 {
1559 continue;
1560 }
1561 let sp = def.variant(*variant_index).ident(tcx).span;
1562 if covered.contains(&sp) {
1563 continue;
1566 }
1567 covered.push(sp);
1568 }
1569 covered.extend(maybe_point_at_variant(tcx, def, pattern.iter_fields()));
1570 }
1571 covered
1572}