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