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