1use rustc_arena::{DroplessArena, TypedArena};
2use rustc_ast::Mutability;
3use rustc_attr_ir::find_attr;
4use rustc_data_structures::fx::FxIndexSet;
5use rustc_errors::codes::*;
6use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, msg, struct_span_code_err};
7use rustc_hir::def::*;
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::{self as hir, BindingMode, ByRef, HirId, MatchSource};
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_lint_defs::builtin::{
12 BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
13};
14use rustc_middle::thir::visit::Visitor;
15use rustc_middle::thir::*;
16use rustc_middle::ty::print::with_no_trimmed_paths;
17use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
18use rustc_pattern_analysis::diagnostics::Uncovered;
19use rustc_pattern_analysis::rustc::{
20 Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RevealedTy,
21 RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport, WitnessPat,
22};
23use rustc_span::edit_distance::find_best_match_for_name;
24use rustc_span::hygiene::DesugaringKind;
25use rustc_span::{Ident, Span, bug};
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_through_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_span::macros::bug_impl(None,
format_args!("unexpected function parameters in THIR: {0:?} {1:?}", kind,
def_id), Location::caller())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]
#[rustc_trivial_field_reads]
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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for RefutableFlag {
}
#[automatically_derived]impl ::core::clone::Clone for RefutableFlag {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
RefutableFlag {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RefutableFlag {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
68enum RefutableFlag {
69 Irrefutable,
70 Refutable,
71}
72use RefutableFlag::*;
73
74#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for LetSource {
}
#[automatically_derived]impl ::core::clone::Clone for LetSource {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for LetSource { }Copy, #[automatically_derived]impl ::core::fmt::Debug for LetSource {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"None PlainLet IfLet IfLetGuard LetElse WhileLet Else ElseIfLet",
match self {
LetSource::None => 0usize,
LetSource::PlainLet => 5usize,
LetSource::IfLet => 14usize,
LetSource::IfLetGuard => 20usize,
LetSource::LetElse => 31usize,
LetSource::WhileLet => 39usize,
LetSource::Else => 48usize,
LetSource::ElseIfLet => 53usize,
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for LetSource
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for LetSource {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for LetSource { }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("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/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("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/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);
}
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);
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 this.with_let_source(let_source, |this| {
184 this.check_let(pattern, initializer, span)
185 });
186 visit::walk_stmt(this, stmt);
187 });
188 }
189 StmtKind::Expr { .. } => {
190 visit::walk_stmt(self, stmt);
191 }
192 }
193 }
194}
195
196impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
197 {}
#[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("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(197u32),
::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))]
198 fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
199 let old_let_source = self.let_source;
200 self.let_source = let_source;
201 f(self);
202 self.let_source = old_let_source;
203 }
204
205 fn with_hir_source<T>(&mut self, new_hir_source: HirId, f: impl FnOnce(&mut Self) -> T) -> T {
206 let old_hir_source = self.hir_source;
207 self.hir_source = new_hir_source;
208 let ret = f(self);
209 self.hir_source = old_hir_source;
210 ret
211 }
212
213 fn visit_land(
216 &mut self,
217 ex: &'p Expr<'tcx>,
218 accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
219 ) -> Result<(), ErrorGuaranteed> {
220 match ex.kind {
221 ExprKind::Scope { value, hir_id, .. } => {
222 self.with_hir_source(hir_id, |this| this.visit_land(&this.thir[value], accumulator))
223 }
224 ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
225 let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
227 let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
228 accumulator.push(res_rhs);
229 res_lhs
230 }
231 _ => {
232 let res = self.visit_land_rhs(ex)?;
233 accumulator.push(res);
234 Ok(())
235 }
236 }
237 }
238
239 fn visit_land_rhs(
243 &mut self,
244 ex: &'p Expr<'tcx>,
245 ) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
246 match ex.kind {
247 ExprKind::Scope { value, hir_id, .. } => {
248 self.with_hir_source(hir_id, |this| this.visit_land_rhs(&this.thir[value]))
249 }
250 ExprKind::Let { ref pat, expr } => {
251 let expr = &self.thir()[expr];
252 self.with_let_source(LetSource::None, |this| {
253 this.visit_expr(expr);
254 });
255 Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
256 }
257 _ => {
258 self.with_let_source(LetSource::None, |this| {
259 this.visit_expr(ex);
260 });
261 Ok(None)
262 }
263 }
264 }
265
266 fn lower_pattern(
267 &mut self,
268 cx: &PatCtxt<'p, 'tcx>,
269 pat: &'p Pat<'tcx>,
270 ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
271 if let Err(err) = pat.pat_error_reported() {
272 self.error = Err(err);
273 Err(err)
274 } else {
275 let refutable = if cx.refutable { Refutable } else { Irrefutable };
277 let mut err = Ok(());
278 pat.walk_always(|pat| {
279 check_borrow_conflicts_in_at_patterns(self, pat);
280 check_for_bindings_named_same_as_variants(self, pat, refutable);
281 err = err.and(check_never_pattern(cx, pat));
282 });
283 err?;
284 Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
285 }
286 }
287
288 fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
291 use ExprKind::*;
292 match &scrutinee.kind {
293 Deref { .. } => false,
296 Field { lhs, .. } => {
298 let lhs = &self.thir()[*lhs];
299 match lhs.ty.kind() {
300 ty::Adt(def, _) if def.is_union() => false,
301 _ => self.is_known_valid_scrutinee(lhs),
302 }
303 }
304 Index { lhs, .. } => {
306 let lhs = &self.thir()[*lhs];
307 self.is_known_valid_scrutinee(lhs)
308 }
309
310 Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
312
313 NeverToAny { source }
315 | Cast { source }
316 | ValueExpr { source }
317 | PointerCoercion { source, .. }
318 | PlaceTypeAscription { source, .. }
319 | ValueTypeAscription { source, .. }
320 | PlaceUnwrapUnsafeBinder { source }
321 | ValueUnwrapUnsafeBinder { source }
322 | WrapUnsafeBinder { source } => self.is_known_valid_scrutinee(&self.thir()[*source]),
323
324 Become { .. }
326 | Break { .. }
327 | Continue { .. }
328 | ConstContinue { .. }
329 | Return { .. } => true,
330
331 Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
333
334 RawBorrow { .. }
336 | Adt { .. }
337 | Array { .. }
338 | Binary { .. }
339 | Block { .. }
340 | Borrow { .. }
341 | Call { .. }
342 | ByUse { .. }
343 | Closure { .. }
344 | ConstBlock { .. }
345 | ConstParam { .. }
346 | If { .. }
347 | Literal { .. }
348 | LogicalOp { .. }
349 | Loop { .. }
350 | LoopMatch { .. }
351 | Match { .. }
352 | NamedConst { .. }
353 | NonHirLiteral { .. }
354 | Repeat { .. }
355 | StaticRef { .. }
356 | ThreadLocalRef { .. }
357 | Tuple { .. }
358 | Unary { .. }
359 | UpvarRef { .. }
360 | VarRef { .. }
361 | ZstLiteral { .. }
362 | Yield { .. }
363 | Reborrow { .. } => true,
364 }
365 }
366
367 fn new_cx(
368 &self,
369 refutability: RefutableFlag,
370 whole_match_span: Option<Span>,
371 scrutinee: Option<&Expr<'tcx>>,
372 scrut_span: Span,
373 ) -> PatCtxt<'p, 'tcx> {
374 let refutable = match refutability {
375 Irrefutable => false,
376 Refutable => true,
377 };
378 let known_valid_scrutinee =
381 scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
382 PatCtxt {
383 tcx: self.tcx,
384 typeck_results: self.typeck_results,
385 typing_env: self.typing_env,
386 module: self.tcx.parent_module(self.hir_source),
387 dropless_arena: self.dropless_arena,
388 match_lint_level: self.hir_source,
389 whole_match_span,
390 scrut_span,
391 refutable,
392 known_valid_scrutinee,
393 internal_state: Default::default(),
394 }
395 }
396
397 fn analyze_patterns(
398 &mut self,
399 cx: &PatCtxt<'p, 'tcx>,
400 arms: &[MatchArm<'p, 'tcx>],
401 scrut_ty: Ty<'tcx>,
402 ) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
403 let report =
404 rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
405 self.error = Err(err);
406 err
407 })?;
408
409 for (arm, is_useful) in report.arm_usefulness.iter() {
411 if let Usefulness::Useful(redundant_subpats) = is_useful
412 && !redundant_subpats.is_empty()
413 {
414 let mut redundant_subpats = redundant_subpats.clone();
415 redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span.lo_hi());
417 for (pat, explanation) in redundant_subpats {
418 report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None)
419 }
420 }
421 }
422 Ok(report)
423 }
424
425 {}
#[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("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(425u32),
::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()
}], ::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))])
})
} 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))]
426 fn check_let(&mut self, pat: &'p Pat<'tcx>, scrutinee: Option<ExprId>, span: Span) {
427 assert!(self.let_source != LetSource::None);
428 let scrut = scrutinee.map(|id| &self.thir[id]);
429 if let LetSource::PlainLet = self.let_source {
430 if let hir::Node::LetStmt(&hir::LetStmt {
433 source: hir::LocalSource::AssignDesugar,
434 ..
435 }) = self.tcx.hir_node(self.hir_source)
436 {
437 self.check_binding_is_irrefutable(
438 pat,
439 "assignment",
440 Some(Inform { descr: "destructuring assignments" }),
441 scrut,
442 None,
443 );
444 } else {
445 self.check_binding_is_irrefutable(
446 pat,
447 "local binding",
448 Some(Inform { descr: "`let` bindings" }),
449 scrut,
450 Some(span),
451 );
452 }
453 } else if let Ok(Irrefutable) = self.is_let_irrefutable(pat, scrut) {
454 if span.from_expansion() {
455 self.lint_single_let(span, None, None);
456 return;
457 }
458 let let_else_span = self.check_irrefutable_option_some(pat, scrut, span);
459
460 let sm = self.tcx.sess.source_map();
461 let next_token_start = sm.span_extend_while_whitespace(span.clone()).hi();
462 let line_span = sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
463 let else_keyword_span = sm.span_until_whitespace(line_span);
464 self.lint_single_let(span, Some(else_keyword_span), let_else_span);
465 }
466 }
467
468 fn check_irrefutable_option_some(
470 &self,
471 pat: &'p Pat<'tcx>,
472 initializer: Option<&Expr<'tcx>>,
473 span: Span,
474 ) -> Option<LetElseReplacementSuggestion> {
475 if let sm = self.tcx.sess.source_map()
476 && let Some(initializer) = initializer
477 && let Some(s_ty) = initializer.ty.ty_adt_def()
478 && self.tcx.is_diagnostic_item(rustc_span::sym::Option, s_ty.did())
479 && let ExprKind::Scope { value, .. } = initializer.kind
480 && let initializer_expr = &self.thir[value]
481 && let ExprKind::Adt(AdtExpr { fields, .. }) = &initializer_expr.kind
482 && let Some(field) = fields.first()
483 && let inner = &self.thir[field.expr]
484 && let Some(inner_ty) = inner.ty.ty_adt_def()
485 && self.tcx.is_diagnostic_item(rustc_span::sym::Option, inner_ty.did())
486 && let Ok(rhs) = sm.span_to_snippet(inner.span)
487 && let Ok(lhs) = sm.span_to_snippet(pat.span)
488 {
489 let lhs = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Some({0})", lhs))
})format!("Some({})", lhs);
490 Some(LetElseReplacementSuggestion { span, lhs, rhs })
491 } else {
492 None
493 }
494 }
495
496 fn check_match(
497 &mut self,
498 scrut: ExprId,
499 arms: &[ArmId],
500 source: hir::MatchSource,
501 expr_span: Span,
502 ) {
503 let scrut = &self.thir[scrut];
504 let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
505
506 let mut tarms = Vec::with_capacity(arms.len());
507 for &arm in arms {
508 let arm = &self.thir.arms[arm];
509 let got_error = self.with_hir_source(arm.hir_id, |this| {
510 let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
511 let arm =
512 MatchArm { pat, arm_data: this.hir_source, has_guard: arm.guard.is_some() };
513 tarms.push(arm);
514 false
515 });
516 if got_error {
517 return;
518 }
519 }
520
521 let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
522
523 match source {
524 hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
527 hir::MatchSource::ForLoopDesugar
528 | hir::MatchSource::Postfix
529 | hir::MatchSource::Normal
530 | hir::MatchSource::FormatArgs => {
531 let is_match_arm =
532 #[allow(non_exhaustive_omitted_patterns)] match source {
hir::MatchSource::Postfix | hir::MatchSource::Normal => true,
_ => false,
}matches!(source, hir::MatchSource::Postfix | hir::MatchSource::Normal);
533 report_arm_reachability(&cx, &report, is_match_arm);
534 }
535 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
538 }
539
540 let witnesses = report.non_exhaustiveness_witnesses;
542 if !witnesses.is_empty() {
543 if source == hir::MatchSource::ForLoopDesugar
544 && let [_, snd_arm] = *arms
545 {
546 let pat = &self.thir[snd_arm].pattern;
548 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));
550 let PatKind::Variant { ref subpatterns, .. } = pat.kind else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!() };
551 let [pat_field] = &subpatterns[..] else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!() };
552 self.check_binding_is_irrefutable(
553 &pat_field.pattern,
554 "`for` loop binding",
555 None,
556 None,
557 None,
558 );
559 } else {
560 let braces_span = match source {
563 hir::MatchSource::Normal => scrut
564 .span
565 .find_ancestor_in_same_ctxt(expr_span)
566 .map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
567 hir::MatchSource::Postfix => {
568 scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
571 let sm = self.tcx.sess.source_map();
572 let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
573 if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
574 let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
575 sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
577 } else {
578 None
579 }
580 })
581 }
582 hir::MatchSource::ForLoopDesugar
583 | hir::MatchSource::TryDesugar(_)
584 | hir::MatchSource::AwaitDesugar
585 | hir::MatchSource::FormatArgs => None,
586 };
587
588 let would_be_exhaustive_without_guards = {
591 let any_arm_has_guard = tarms.iter().any(|arm| arm.has_guard);
592 any_arm_has_guard && {
593 let guardless_arms: Vec<_> =
594 tarms.iter().map(|arm| MatchArm { has_guard: false, ..*arm }).collect();
595 rustc_pattern_analysis::rustc::analyze_match(&cx, &guardless_arms, scrut.ty)
596 .is_ok_and(|report| report.non_exhaustiveness_witnesses.is_empty())
597 }
598 };
599 self.error = Err(report_non_exhaustive_match(
600 &cx,
601 self.thir,
602 scrut.ty,
603 scrut.span,
604 witnesses,
605 arms,
606 braces_span,
607 would_be_exhaustive_without_guards,
608 ));
609 }
610 }
611 }
612
613 {}
#[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("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(613u32),
::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))]
614 fn lint_single_let(
615 &mut self,
616 let_span: Span,
617 else_keyword_span: Option<Span>,
618 let_else_span: Option<LetElseReplacementSuggestion>,
619 ) {
620 report_irrefutable_let_patterns(
621 self.tcx,
622 self.hir_source,
623 self.let_source,
624 1,
625 let_span,
626 else_keyword_span,
627 let_else_span,
628 );
629 }
630
631 fn analyze_binding(
632 &mut self,
633 pat: &'p Pat<'tcx>,
634 refutability: RefutableFlag,
635 scrut: Option<&Expr<'tcx>>,
636 ) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
637 let cx = self.new_cx(refutability, None, scrut, pat.span);
638 let pat = self.lower_pattern(&cx, pat)?;
639 let arms = [MatchArm { pat, arm_data: self.hir_source, has_guard: false }];
640 let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?;
641 Ok((cx, report))
642 }
643
644 fn is_let_irrefutable(
645 &mut self,
646 pat: &'p Pat<'tcx>,
647 scrut: Option<&Expr<'tcx>>,
648 ) -> Result<RefutableFlag, ErrorGuaranteed> {
649 let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?;
650 report_arm_reachability(&cx, &report, false);
652 Ok(if report.non_exhaustiveness_witnesses.is_empty() { Irrefutable } else { Refutable })
655 }
656
657 {}
#[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("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
::tracing_core::__macro_support::Option::Some(657u32),
::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 name = self.tcx.item_name(def_id);
interpreted_as_const =
Some(InterpretedAsConst {
span,
variable: name.to_ident_string(),
});
interpreted_as_const_sugg =
Some(InterpretedAsConstSugg {
span: pat.span,
variable: name.to_string(),
});
} 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).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))]
658 fn check_binding_is_irrefutable(
659 &mut self,
660 pat: &'p Pat<'tcx>,
661 origin: &str,
662 inform: Option<Inform>,
663 scrut: Option<&Expr<'tcx>>,
664 sp: Option<Span>,
665 ) {
666 let pattern_ty = pat.ty;
667
668 let Ok((cx, report)) = self.analyze_binding(pat, Irrefutable, scrut) else { return };
669 let witnesses = report.non_exhaustiveness_witnesses;
670 if witnesses.is_empty() {
671 return;
673 }
674
675 let mut let_suggestion = None;
676 let mut misc_suggestion = None;
677 let mut interpreted_as_const = None;
678 let mut interpreted_as_const_sugg = None;
679
680 if let Some(def_id) = is_const_pat_that_looks_like_binding(self.tcx, pat) {
681 let span = self.tcx.def_span(def_id);
682 let name = self.tcx.item_name(def_id);
683 interpreted_as_const =
685 Some(InterpretedAsConst { span, variable: name.to_ident_string() });
686 interpreted_as_const_sugg =
688 Some(InterpretedAsConstSugg { span: pat.span, variable: name.to_string() });
689 } else if let PatKind::Constant { .. } = pat.kind
690 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
691 {
692 if snippet.chars().all(|c| c.is_digit(10)) {
694 misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
696 start_span: pat.span.shrink_to_lo(),
697 });
698 }
699 }
700
701 if let Some(span) = sp
702 && self.tcx.sess.source_map().is_span_accessible(span)
703 && interpreted_as_const.is_none()
704 && scrut.is_some()
705 {
706 let mut bindings = vec![];
707 pat.each_binding(|name, _, _, _| bindings.push(name));
708
709 let semi_span = span.shrink_to_hi();
710 let start_span = span.shrink_to_lo();
711 let end_span = semi_span.shrink_to_lo();
712 let count = witnesses.len();
713
714 let_suggestion = Some(if bindings.is_empty() {
715 SuggestLet::If { start_span, semi_span, count }
716 } else {
717 SuggestLet::Else { end_span, count }
718 });
719 };
720
721 let adt_defined_here = report_adt_defined_here(self.tcx, pattern_ty, &witnesses, false);
722
723 let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
726 && let ty::Adt(adt, args) = witness_1.ty().kind()
727 && adt.is_enum()
728 && let Constructor::Variant(variant_index) = witness_1.ctor()
729 {
730 let variant_inhabited = adt
731 .variant(*variant_index)
732 .inhabited_predicate(self.tcx)
733 .instantiate(self.tcx, *args);
734 variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
735 && !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env)
736 } else {
737 false
738 };
739
740 let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
741
742 self.error = Err(self.tcx.dcx().emit_err(PatternNotCovered {
743 span: pat.span,
744 origin,
745 uncovered: Uncovered::new(pat.span, &cx, witnesses),
746 inform,
747 interpreted_as_const,
748 interpreted_as_const_sugg,
749 witness_1_is_privately_uninhabited,
750 witness_1,
751 _p: (),
752 pattern_ty,
753 let_suggestion,
754 misc_suggestion,
755 adt_defined_here,
756 }));
757 }
758}
759
760fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) {
772 let PatKind::Binding { name, mode, ty, subpattern: Some(ref sub), .. } = pat.kind else {
774 return;
775 };
776
777 let is_binding_by_move = |ty: Ty<'tcx>| !cx.tcx.type_is_copy_modulo_regions(cx.typing_env, ty);
778
779 let sess = cx.tcx.sess;
780
781 let mut_outer = match mode.0 {
783 ByRef::No if is_binding_by_move(ty) => {
784 let mut conflicts_ref = Vec::new();
786 sub.each_binding(|_, mode, _, span| {
787 if #[allow(non_exhaustive_omitted_patterns)] match mode {
ByRef::Yes(..) => true,
_ => false,
}matches!(mode, ByRef::Yes(..)) {
788 conflicts_ref.push(span)
789 }
790 });
791 if !conflicts_ref.is_empty() {
792 sess.dcx().emit_err(BorrowOfMovedValue {
793 binding_span: pat.span,
794 conflicts_ref,
795 name: Ident::new(name, pat.span),
796 ty,
797 suggest_borrowing: Some(pat.span.shrink_to_lo()),
798 });
799 }
800 return;
801 }
802 ByRef::No => return,
803 ByRef::Yes(_, m) => m,
804 };
805
806 let mut conflicts_move = Vec::new();
809 let mut conflicts_mut_mut = Vec::new();
810 let mut conflicts_mut_ref = Vec::new();
811 sub.each_binding(|name, mode, ty, span| {
812 match mode {
813 ByRef::Yes(_, mut_inner) => match (mut_outer, mut_inner) {
814 (Mutability::Not, Mutability::Not) => {}
816 (Mutability::Mut, Mutability::Mut) => {
818 conflicts_mut_mut.push(Conflict::Mut { span, name })
819 }
820 (Mutability::Not, Mutability::Mut) => {
821 conflicts_mut_ref.push(Conflict::Mut { span, name })
822 }
823 (Mutability::Mut, Mutability::Not) => {
824 conflicts_mut_ref.push(Conflict::Ref { span, name })
825 }
826 },
827 ByRef::No if is_binding_by_move(ty) => {
828 conflicts_move.push(Conflict::Moved { span, name }) }
830 ByRef::No => {} }
832 });
833
834 let report_mut_mut = !conflicts_mut_mut.is_empty();
835 let report_mut_ref = !conflicts_mut_ref.is_empty();
836 let report_move_conflict = !conflicts_move.is_empty();
837
838 let mut occurrences = match mut_outer {
839 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 }],
840 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 }],
841 };
842 occurrences.extend(conflicts_mut_mut);
843 occurrences.extend(conflicts_mut_ref);
844 occurrences.extend(conflicts_move);
845
846 if report_mut_mut {
848 sess.dcx().emit_err(MultipleMutBorrows { span: pat.span, occurrences });
850 } else if report_mut_ref {
851 match mut_outer {
853 Mutability::Mut => {
854 sess.dcx().emit_err(AlreadyMutBorrowed { span: pat.span, occurrences });
855 }
856 Mutability::Not => {
857 sess.dcx().emit_err(AlreadyBorrowed { span: pat.span, occurrences });
858 }
859 };
860 } else if report_move_conflict {
861 sess.dcx().emit_err(MovedWhileBorrowed { span: pat.span, occurrences });
863 }
864}
865
866fn check_for_bindings_named_same_as_variants(
867 cx: &MatchVisitor<'_, '_>,
868 pat: &Pat<'_>,
869 rf: RefutableFlag,
870) {
871 if let PatKind::Binding {
872 name,
873 mode: BindingMode(ByRef::No, Mutability::Not),
874 subpattern: None,
875 ty,
876 ..
877 } = pat.kind
878 && let ty::Adt(edef, _) = ty.peel_refs().kind()
879 && edef.is_enum()
880 && edef
881 .variants()
882 .iter()
883 .any(|variant| variant.name == name && variant.ctor_kind() == Some(CtorKind::Const))
884 {
885 let variant_count = edef.variants().len();
886 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()));
887 cx.tcx.emit_node_span_lint(
888 BINDINGS_WITH_VARIANT_NAME,
889 cx.hir_source,
890 pat.span,
891 BindingsWithVariantName {
892 suggestion: if rf == Refutable || variant_count == 1 {
896 Some(pat.span)
897 } else {
898 None
899 },
900 ty_path,
901 name: Ident::new(name, pat.span),
902 },
903 )
904 }
905}
906
907fn check_never_pattern<'tcx>(
909 cx: &PatCtxt<'_, 'tcx>,
910 pat: &Pat<'tcx>,
911) -> Result<(), ErrorGuaranteed> {
912 if let PatKind::Never = pat.kind {
913 if !cx.is_uninhabited(pat.ty) {
914 return Err(cx.tcx.dcx().emit_err(NonEmptyNeverPattern { span: pat.span, ty: pat.ty }));
915 }
916 }
917 Ok(())
918}
919
920fn report_irrefutable_let_patterns(
921 tcx: TyCtxt<'_>,
922 id: HirId,
923 source: LetSource,
924 count: usize,
925 span: Span,
926 else_keyword_span: Option<Span>,
927 let_else_span: Option<LetElseReplacementSuggestion>,
928) {
929 macro_rules! emit_diag {
930 ($lint:tt) => {{
931 tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span, $lint { count });
932 }};
933 }
934
935 match source {
936 LetSource::None | LetSource::PlainLet | LetSource::Else => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
937 LetSource::IfLet | LetSource::ElseIfLet => {
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
IrrefutableLetPatternsIfLet { count });
}emit_diag!(IrrefutableLetPatternsIfLet),
938 LetSource::IfLetGuard => {
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
IrrefutableLetPatternsIfLetGuard { count });
}emit_diag!(IrrefutableLetPatternsIfLetGuard),
939 LetSource::LetElse => {
940 let spans = match else_keyword_span {
941 Some(else_keyword_span) => {
942 let mut spans = MultiSpan::from_span(else_keyword_span);
943 spans.push_span_label(
944 span,
945 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("assigning to binding pattern will always succeed"))msg!("assigning to binding pattern will always succeed"),
946 );
947 spans
948 }
949 None => span.into(),
950 };
951
952 tcx.emit_node_span_lint(
953 IRREFUTABLE_LET_PATTERNS,
954 id,
955 spans,
956 IrrefutableLetPatternsLetElse { be_replaced: let_else_span },
957 );
958 }
959 LetSource::WhileLet => {
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
IrrefutableLetPatternsWhileLet { count });
}emit_diag!(IrrefutableLetPatternsWhileLet),
960 }
961}
962
963fn report_unreachable_pattern<'p, 'tcx>(
965 cx: &PatCtxt<'p, 'tcx>,
966 hir_id: HirId,
967 pat: &DeconstructedPat<'p, 'tcx>,
968 explanation: &RedundancyExplanation<'p, 'tcx>,
969 whole_arm_span: Option<Span>,
970) {
971 static CAP_COVERED_BY_MANY: usize = 4;
972 let pat_span = pat.data().span;
973 let mut lint = UnreachablePatternInner {
974 span: Some(pat_span),
975 matches_no_values: None,
976 matches_no_values_ty: **pat.ty(),
977 uninhabited_note: None,
978 covered_by_catchall: None,
979 covered_by_one: None,
980 covered_by_many: None,
981 wanted_constant: None,
982 accessible_constant: None,
983 inaccessible_constant: None,
984 pattern_let_binding: None,
985 suggest_remove: None,
986 non_exhaustive_attr: None,
987 };
988 let mut covered_by_many_n_more_count = None;
989 match explanation.covered_by.as_slice() {
990 [] => {
991 lint.span = None; lint.uninhabited_note = Some(()); lint.matches_no_values = Some(pat_span);
995 lint.suggest_remove = whole_arm_span; pat.walk(&mut |subpat| {
997 let ty = **subpat.ty();
998 if cx.is_uninhabited(ty) {
999 lint.matches_no_values_ty = ty;
1000 false } else if #[allow(non_exhaustive_omitted_patterns)] match subpat.ctor() {
Constructor::Ref | Constructor::UnionField => true,
_ => false,
}matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) {
1002 false } else {
1004 true
1005 }
1006 });
1007 }
1008 [covering_pat] if pat_is_catchall(covering_pat) => {
1009 let pat = covering_pat.data();
1011 lint.covered_by_catchall = Some(pat.span);
1012 find_fallback_pattern_typo(cx, hir_id, pat, &mut lint);
1013 }
1014 [covering_pat] => {
1015 lint.covered_by_one = Some(covering_pat.data().span);
1016 }
1017 covering_pats => {
1018 let mut iter = covering_pats.iter();
1019 let mut multispan = MultiSpan::from_span(pat_span);
1020 for p in iter.by_ref().take(CAP_COVERED_BY_MANY) {
1021 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"));
1022 }
1023 let remain = iter.count();
1024 if remain == 0 {
1025 multispan.push_span_label(pat_span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("collectively making this unreachable"))msg!("collectively making this unreachable"));
1026 } else {
1027 covered_by_many_n_more_count = Some(remain);
1028 multispan.push_span_label(
1029 pat_span,
1030 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"),
1031 );
1032 }
1033 lint.covered_by_many = Some(multispan);
1034 }
1035 }
1036
1037 if let Constructor::Wildcard = pat.ctor()
1038 && let ty::Adt(adt, _) = pat.ty().peel_refs().kind()
1039 && adt.is_enum()
1040 && let Some(did) = adt.did().as_local()
1041 && let Some(span) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &cx.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NonExhaustive(span)) => {
break 'done Some(span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(cx.tcx, did, NonExhaustive(span) => span)
1042 {
1043 lint.non_exhaustive_attr = Some(*span);
1044 }
1045
1046 cx.tcx.emit_node_span_lint(
1047 UNREACHABLE_PATTERNS,
1048 hir_id,
1049 pat_span,
1050 UnreachablePattern { inner: lint, covered_by_many_n_more_count },
1051 );
1052}
1053
1054fn find_fallback_pattern_typo<'tcx>(
1056 cx: &PatCtxt<'_, 'tcx>,
1057 hir_id: HirId,
1058 pat: &Pat<'tcx>,
1059 lint: &mut UnreachablePatternInner<'_>,
1060) {
1061 if cx.tcx.lint_level_spec_at_node(UNREACHABLE_PATTERNS, hir_id).is_allow() {
1062 return;
1065 }
1066 if let PatKind::Binding { name, subpattern: None, ty, .. } = pat.kind {
1067 let mut accessible = ::alloc::vec::Vec::new()vec![];
1069 let mut accessible_path = ::alloc::vec::Vec::new()vec![];
1070 let mut inaccessible = ::alloc::vec::Vec::new()vec![];
1071 let mut imported = ::alloc::vec::Vec::new()vec![];
1072 let mut imported_spans = ::alloc::vec::Vec::new()vec![];
1073 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
1074 let parent = cx.tcx.hir_get_parent_item(hir_id);
1075
1076 for item in cx.tcx.hir_crate_items(()).free_items() {
1077 if let DefKind::Use = cx.tcx.def_kind(item.owner_id) {
1078 let item = cx.tcx.hir_expect_item(item.owner_id.def_id);
1080 let hir::ItemKind::Use(hir::UseTree { prefix: path, .. }) = item.kind else {
1081 continue;
1082 };
1083 if let Some(value_ns) = path.res.value_ns
1084 && let Res::Def(DefKind::Const, id) = value_ns
1085 && infcx.can_eq(
1086 param_env,
1087 ty,
1088 cx.tcx.type_of(id).instantiate_identity().skip_norm_wip(),
1089 )
1090 {
1091 if cx.tcx.visibility(id).is_accessible_from(parent, cx.tcx) {
1092 let item_name = cx.tcx.item_name(id);
1094 accessible.push(item_name);
1095 accessible_path.push({ let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(id) }with_no_trimmed_paths!(cx.tcx.def_path_str(id)));
1096 } else if cx.tcx.visibility(item.owner_id).is_accessible_from(parent, cx.tcx) {
1097 let ident = item.kind.ident().unwrap();
1100 imported.push(ident.name);
1101 imported_spans.push(ident.span);
1102 }
1103 }
1104 }
1105 if let DefKind::Const = cx.tcx.def_kind(item.owner_id)
1106 && infcx.can_eq(
1107 param_env,
1108 ty,
1109 cx.tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip(),
1110 )
1111 {
1112 let item_name = cx.tcx.item_name(item.owner_id);
1114 let vis = cx.tcx.visibility(item.owner_id);
1115 if vis.is_accessible_from(parent, cx.tcx) {
1116 accessible.push(item_name);
1117 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));
1124 accessible_path.push(path);
1125 } else if name == item_name {
1126 inaccessible.push(cx.tcx.def_span(item.owner_id));
1129 }
1130 }
1131 }
1132 if let Some((i, &const_name)) =
1133 accessible.iter().enumerate().find(|&(_, &const_name)| const_name == name)
1134 {
1135 lint.wanted_constant = Some(WantedConstant {
1137 span: pat.span,
1138 is_typo: false,
1139 const_name: const_name.to_string(),
1140 const_path: accessible_path[i].clone(),
1141 });
1142 } else if let Some(name) = find_best_match_for_name(&accessible, name, None) {
1143 lint.wanted_constant = Some(WantedConstant {
1145 span: pat.span,
1146 is_typo: true,
1147 const_name: name.to_string(),
1148 const_path: name.to_string(),
1149 });
1150 } else if let Some(i) =
1151 imported.iter().enumerate().find(|&(_, &const_name)| const_name == name).map(|(i, _)| i)
1152 {
1153 lint.accessible_constant = Some(imported_spans[i]);
1156 } else if let Some(name) = find_best_match_for_name(&imported, name, None) {
1157 lint.wanted_constant = Some(WantedConstant {
1160 span: pat.span,
1161 is_typo: true,
1162 const_path: name.to_string(),
1163 const_name: name.to_string(),
1164 });
1165 } else if !inaccessible.is_empty() {
1166 for span in inaccessible {
1167 lint.inaccessible_constant = Some(span);
1169 }
1170 } else {
1171 for (_, node) in cx.tcx.hir_parent_iter(hir_id) {
1174 match node {
1175 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(let_stmt), .. }) => {
1176 if let hir::PatKind::Binding(_, _, binding_name, _) = let_stmt.pat.kind {
1177 if name == binding_name.name {
1178 lint.pattern_let_binding = Some(binding_name.span);
1179 }
1180 }
1181 }
1182 hir::Node::Block(hir::Block { stmts, .. }) => {
1183 for stmt in *stmts {
1184 if let hir::StmtKind::Let(let_stmt) = stmt.kind
1185 && let hir::PatKind::Binding(_, _, binding_name, _) =
1186 let_stmt.pat.kind
1187 && name == binding_name.name
1188 {
1189 lint.pattern_let_binding = Some(binding_name.span);
1190 }
1191 }
1192 }
1193 hir::Node::Item(_) => break,
1194 _ => {}
1195 }
1196 }
1197 }
1198 }
1199}
1200
1201fn report_arm_reachability<'p, 'tcx>(
1203 cx: &PatCtxt<'p, 'tcx>,
1204 report: &UsefulnessReport<'p, 'tcx>,
1205 is_match_arm: bool,
1206) {
1207 let sm = cx.tcx.sess.source_map();
1208 for (arm, is_useful) in report.arm_usefulness.iter() {
1209 if let Usefulness::Redundant(explanation) = is_useful {
1210 let hir_id = arm.arm_data;
1211 let arm_span = cx.tcx.hir_span(hir_id);
1212 let whole_arm_span = if is_match_arm {
1213 if let Some(comma) = sm.span_followed_by(arm_span, ",") {
1215 Some(arm_span.to(comma))
1216 } else {
1217 Some(arm_span)
1218 }
1219 } else {
1220 None
1221 };
1222 report_unreachable_pattern(cx, hir_id, arm.pat, explanation, whole_arm_span)
1223 }
1224 }
1225}
1226
1227fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
1229 match pat.ctor() {
1230 Constructor::Wildcard => true,
1231 Constructor::Struct | Constructor::Ref => {
1232 pat.iter_fields().all(|ipat| pat_is_catchall(&ipat.pat))
1233 }
1234 _ => false,
1235 }
1236}
1237
1238fn is_const_pat_that_looks_like_binding<'tcx>(tcx: TyCtxt<'tcx>, pat: &Pat<'tcx>) -> Option<DefId> {
1244 if let ty::AliasConstKind::Free { def_id } = pat.extra.as_deref()?.expanded_const?
1248 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(pat.span)
1249 && snippet
1250 .strip_prefix("r#")
1251 .unwrap_or(&snippet)
1252 .chars()
1253 .all(|c| c.is_alphanumeric() || c == '_')
1254 {
1255 Some(def_id)
1256 } else {
1257 None
1258 }
1259}
1260
1261fn report_non_exhaustive_match<'p, 'tcx>(
1263 cx: &PatCtxt<'p, 'tcx>,
1264 thir: &Thir<'tcx>,
1265 scrut_ty: Ty<'tcx>,
1266 sp: Span,
1267 witnesses: Vec<WitnessPat<'p, 'tcx>>,
1268 arms: &[ArmId],
1269 braces_span: Option<Span>,
1270 would_be_exhaustive_without_guards: bool,
1271) -> ErrorGuaranteed {
1272 let is_empty_match = arms.is_empty();
1273 let non_empty_enum = match scrut_ty.kind() {
1274 ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
1275 _ => false,
1276 };
1277 if is_empty_match && !non_empty_enum {
1280 return cx.tcx.dcx().emit_err(NonExhaustivePatternsTypeNotEmpty {
1281 cx,
1282 scrut_span: sp,
1283 braces_span,
1284 ty: scrut_ty,
1285 });
1286 }
1287
1288 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
1290 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!(
1291 cx.tcx.dcx(),
1292 sp,
1293 E0004,
1294 "non-exhaustive patterns: {joined_patterns} not covered"
1295 );
1296 err.span_label(
1297 sp,
1298 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pattern{0} {1} not covered",
if witnesses.len() == 1 { "" } else { "s" }, joined_patterns))
})format!(
1299 "pattern{} {} not covered",
1300 rustc_errors::pluralize!(witnesses.len()),
1301 joined_patterns
1302 ),
1303 );
1304
1305 if let Some(AdtDefinedHere { adt_def_span, ty, variants }) =
1307 report_adt_defined_here(cx.tcx, scrut_ty, &witnesses, true)
1308 {
1309 let mut multi_span = MultiSpan::from_span(adt_def_span);
1310 multi_span.push_span_context(adt_def_span);
1311 for Variant { span } in variants {
1312 multi_span.push_span_label(span, "not covered");
1313 }
1314 err.span_note(multi_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", ty))
})format!("`{ty}` defined here"));
1315 }
1316 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));
1317
1318 if !is_empty_match {
1319 let mut special_tys = FxIndexSet::default();
1320 collect_special_tys(cx, &witnesses[0], &mut special_tys);
1322
1323 for ty in special_tys {
1324 if ty.is_ptr_sized_integral() {
1325 if ty.inner() == cx.tcx.types.usize {
1326 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!(
1327 "`{ty}::MAX` is not treated as exhaustive, \
1328 so half-open ranges are necessary to match exhaustively",
1329 ));
1330 } else if ty.inner() == cx.tcx.types.isize {
1331 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!(
1332 "`{ty}::MIN` and `{ty}::MAX` are not treated as exhaustive, \
1333 so half-open ranges are necessary to match exhaustively",
1334 ));
1335 }
1336 } else if ty.inner() == cx.tcx.types.str_ {
1337 err.note("`&str` cannot be matched exhaustively, so a wildcard `_` is necessary");
1338 } else if cx.is_foreign_non_exhaustive_enum(ty) {
1339 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"));
1340 } else if cx.is_uninhabited(ty.inner()) {
1341 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"));
1344 }
1345 }
1346 }
1347
1348 if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
1349 if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.typing_env) {
1350 err.note("references are always considered inhabited");
1351 }
1352 }
1353
1354 for &arm in arms {
1355 let arm = &thir.arms[arm];
1356 if let Some(def_id) = is_const_pat_that_looks_like_binding(cx.tcx, &arm.pattern) {
1357 let const_name = cx.tcx.item_name(def_id);
1358 err.span_label(
1359 arm.pattern.span,
1360 ::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!(
1361 "this pattern doesn't introduce a new catch-all binding, but rather pattern \
1362 matches against the value of constant `{const_name}`",
1363 ),
1364 );
1365 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"));
1366 err.span_suggestion_verbose(
1367 arm.pattern.span.shrink_to_hi(),
1368 "if you meant to introduce a binding, use a different name",
1369 "_var".to_string(),
1370 Applicability::MaybeIncorrect,
1371 );
1372 }
1373 }
1374
1375 let suggest_the_witnesses = witnesses.len() < 4;
1377 let suggested_arm = if suggest_the_witnesses {
1378 let pattern = witnesses
1379 .iter()
1380 .map(|witness| cx.print_witness_pat(witness))
1381 .collect::<Vec<String>>()
1382 .join(" | ");
1383 if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns() {
1384 pattern
1386 } else {
1387 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} => todo!()", pattern))
})format!("{pattern} => todo!()")
1389 }
1390 } else {
1391 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_ => todo!()"))
})format!("_ => todo!()")
1393 };
1394 let mut suggestion = None;
1395 let sm = cx.tcx.sess.source_map();
1396 match arms {
1397 [] if let Some(braces_span) = braces_span => {
1398 let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
1400 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", snippet))
})format!("\n{snippet}"), " ")
1401 } else {
1402 (" ".to_string(), "")
1403 };
1404 suggestion = Some((
1405 braces_span,
1406 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{{0}{1}{2},{0}}}", indentation,
more, suggested_arm))
})format!(" {{{indentation}{more}{suggested_arm},{indentation}}}",),
1407 ));
1408 }
1409 [only] => {
1410 let only = &thir[*only];
1411 let (pre_indentation, is_multiline) = if let Some(snippet) =
1412 sm.indentation_before(only.span)
1413 && let Ok(with_trailing) =
1414 sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
1415 && sm.is_multiline(with_trailing)
1416 {
1417 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", snippet))
})format!("\n{snippet}"), true)
1418 } else {
1419 (" ".to_string(), false)
1420 };
1421 let only_body = &thir[only.body];
1422 let comma = if #[allow(non_exhaustive_omitted_patterns)] match only_body.kind {
ExprKind::Block { .. } => true,
_ => false,
}matches!(only_body.kind, ExprKind::Block { .. })
1423 && only.span.ctxt() == only_body.span.ctxt()
1424 && is_multiline
1425 {
1426 ""
1427 } else {
1428 ","
1429 };
1430 suggestion = Some((
1431 only.span.shrink_to_hi(),
1432 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", comma, pre_indentation,
suggested_arm))
})format!("{comma}{pre_indentation}{suggested_arm}"),
1433 ));
1434 }
1435 [.., prev, last] => {
1436 let prev = &thir[*prev];
1437 let last = &thir[*last];
1438 if prev.span.ctxt() == last.span.ctxt() {
1439 let last_body = &thir[last.body];
1440 let comma = if #[allow(non_exhaustive_omitted_patterns)] match last_body.kind {
ExprKind::Block { .. } => true,
_ => false,
}matches!(last_body.kind, ExprKind::Block { .. })
1441 && last.span.ctxt() == last_body.span.ctxt()
1442 {
1443 ""
1444 } else {
1445 ","
1446 };
1447 let spacing = if sm.is_multiline(prev.span.between(last.span)) {
1448 sm.indentation_before(last.span).map(|indent| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}", indent))
})format!("\n{indent}"))
1449 } else {
1450 Some(" ".to_string())
1451 };
1452 if let Some(spacing) = spacing {
1453 suggestion = Some((
1454 last.span.shrink_to_hi(),
1455 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", comma, spacing,
suggested_arm))
})format!("{comma}{spacing}{suggested_arm}"),
1456 ));
1457 }
1458 }
1459 }
1460 _ => {}
1461 }
1462
1463 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!(
1464 "ensure that all possible cases are being handled by adding a match arm with a wildcard \
1465 pattern{}{}",
1466 if witnesses.len() > 1 && suggest_the_witnesses && suggestion.is_some() {
1467 ", a match arm with multiple or-patterns"
1468 } else {
1469 ""
1471 },
1472 match witnesses.len() {
1473 0 if suggestion.is_some() => " as shown",
1475 0 => "",
1476 1 if suggestion.is_some() => " or an explicit pattern as shown",
1477 1 => " or an explicit pattern",
1478 _ if suggestion.is_some() => " as shown, or multiple match arms",
1479 _ => " or multiple match arms",
1480 },
1481 );
1482
1483 if would_be_exhaustive_without_guards {
1484 err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
1485 }
1486 if let Some((span, sugg)) = suggestion {
1487 err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
1488 } else {
1489 err.help(msg);
1490 }
1491 err.emit_err()
1492}
1493
1494fn joined_uncovered_patterns<'p, 'tcx>(
1495 cx: &PatCtxt<'p, 'tcx>,
1496 witnesses: &[WitnessPat<'p, 'tcx>],
1497) -> String {
1498 const LIMIT: usize = 3;
1499 let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.print_witness_pat(pat);
1500 match witnesses {
1501 [] => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
1502 [witness] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
cx.print_witness_pat(witness)))
})format!("`{}`", cx.print_witness_pat(witness)),
1503 [head @ .., tail] if head.len() < LIMIT => {
1504 let head: Vec<_> = head.iter().map(pat_to_str).collect();
1505 ::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))
1506 }
1507 _ => {
1508 let (head, tail) = witnesses.split_at(LIMIT);
1509 let head: Vec<_> = head.iter().map(pat_to_str).collect();
1510 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and {1} more",
head.join("`, `"), tail.len()))
})format!("`{}` and {} more", head.join("`, `"), tail.len())
1511 }
1512 }
1513}
1514
1515fn collect_special_tys<'tcx>(
1517 cx: &PatCtxt<'_, 'tcx>,
1518 pat: &WitnessPat<'_, 'tcx>,
1519 special_tys: &mut FxIndexSet<RevealedTy<'tcx>>,
1520) {
1521 if #[allow(non_exhaustive_omitted_patterns)] match pat.ctor() {
Constructor::NonExhaustive | Constructor::Never => true,
_ => false,
}matches!(pat.ctor(), Constructor::NonExhaustive | Constructor::Never) {
1522 special_tys.insert(*pat.ty());
1523 }
1524 if let Constructor::IntRange(range) = pat.ctor() {
1525 if cx.is_range_beyond_boundaries(range, *pat.ty()) {
1526 special_tys.insert(*pat.ty());
1528 }
1529 }
1530 pat.iter_fields().for_each(|field_pat| collect_special_tys(cx, field_pat, special_tys))
1531}
1532
1533fn report_adt_defined_here<'tcx>(
1534 tcx: TyCtxt<'tcx>,
1535 ty: Ty<'tcx>,
1536 witnesses: &[WitnessPat<'_, 'tcx>],
1537 point_at_non_local_ty: bool,
1538) -> Option<AdtDefinedHere<'tcx>> {
1539 let ty = ty.peel_refs();
1540 let ty::Adt(def, _) = ty.kind() else {
1541 return None;
1542 };
1543 let adt_def_span =
1544 tcx.hir_get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
1545 let adt_def_span = if point_at_non_local_ty {
1546 adt_def_span.unwrap_or_else(|| tcx.def_span(def.did()))
1547 } else {
1548 adt_def_span?
1549 };
1550
1551 let mut variants = ::alloc::vec::Vec::new()vec![];
1552 for span in maybe_point_at_variant(tcx, *def, witnesses.iter().take(5)) {
1553 variants.push(Variant { span });
1554 }
1555 Some(AdtDefinedHere { adt_def_span, ty, variants })
1556}
1557
1558fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'p>(
1559 tcx: TyCtxt<'tcx>,
1560 def: AdtDef<'tcx>,
1561 patterns: impl Iterator<Item = &'a WitnessPat<'p, 'tcx>>,
1562) -> Vec<Span> {
1563 let mut covered = ::alloc::vec::Vec::new()vec![];
1564 for pattern in patterns {
1565 if let Constructor::Variant(variant_index) = pattern.ctor() {
1566 if let ty::Adt(this_def, _) = pattern.ty().kind()
1567 && this_def.did() != def.did()
1568 {
1569 continue;
1570 }
1571 let sp = def.variant(*variant_index).ident(tcx).span;
1572 if covered.contains(&sp) {
1573 continue;
1576 }
1577 covered.push(sp);
1578 }
1579 covered.extend(maybe_point_at_variant(tcx, def, pattern.iter_fields()));
1580 }
1581 covered
1582}