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, struct_span_code_err};
7use rustc_hir::def::*;
8use rustc_hir::def_id::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::*;
32use crate::fluent_generated as fluent;
33
34pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
35 let typeck_results = tcx.typeck(def_id);
36 let (thir, expr) = tcx.thir_body(def_id)?;
37 let thir = thir.borrow();
38 let pattern_arena = TypedArena::default();
39 let dropless_arena = DroplessArena::default();
40 let mut visitor = MatchVisitor {
41 tcx,
42 thir: &*thir,
43 typeck_results,
44 typing_env: ty::TypingEnv::non_body_analysis(tcx, def_id),
46 lint_level: tcx.local_def_id_to_hir_id(def_id),
47 let_source: LetSource::None,
48 pattern_arena: &pattern_arena,
49 dropless_arena: &dropless_arena,
50 error: Ok(()),
51 };
52 visitor.visit_expr(&thir[expr]);
53
54 let origin = match tcx.def_kind(def_id) {
55 DefKind::AssocFn | DefKind::Fn => "function argument",
56 DefKind::Closure => "closure argument",
57 _ if thir.params.is_empty() => "",
60 kind => bug!("unexpected function parameters in THIR: {kind:?} {def_id:?}"),
61 };
62
63 for param in thir.params.iter() {
64 if let Some(box ref pattern) = param.pat {
65 visitor.check_binding_is_irrefutable(pattern, origin, None, None);
66 }
67 }
68 visitor.error
69}
70
71#[derive(Debug, Copy, Clone, PartialEq)]
72enum RefutableFlag {
73 Irrefutable,
74 Refutable,
75}
76use RefutableFlag::*;
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79enum LetSource {
80 None,
81 PlainLet,
82 IfLet,
83 IfLetGuard,
84 LetElse,
85 WhileLet,
86 Else,
87 ElseIfLet,
88}
89
90struct MatchVisitor<'p, 'tcx> {
91 tcx: TyCtxt<'tcx>,
92 typing_env: ty::TypingEnv<'tcx>,
93 typeck_results: &'tcx ty::TypeckResults<'tcx>,
94 thir: &'p Thir<'tcx>,
95 lint_level: HirId,
96 let_source: LetSource,
97 pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
98 dropless_arena: &'p DroplessArena,
99 error: Result<(), ErrorGuaranteed>,
103}
104
105impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> {
108 fn thir(&self) -> &'p Thir<'tcx> {
109 self.thir
110 }
111
112 #[instrument(level = "trace", skip(self))]
113 fn visit_arm(&mut self, arm: &'p Arm<'tcx>) {
114 self.with_lint_level(arm.lint_level, |this| {
115 if let Some(expr) = arm.guard {
116 this.with_let_source(LetSource::IfLetGuard, |this| {
117 this.visit_expr(&this.thir[expr])
118 });
119 }
120 this.visit_pat(&arm.pattern);
121 this.visit_expr(&self.thir[arm.body]);
122 });
123 }
124
125 #[instrument(level = "trace", skip(self))]
126 fn visit_expr(&mut self, ex: &'p Expr<'tcx>) {
127 match ex.kind {
128 ExprKind::Scope { value, lint_level, .. } => {
129 self.with_lint_level(lint_level, |this| {
130 this.visit_expr(&this.thir[value]);
131 });
132 return;
133 }
134 ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
135 let let_source = match ex.span.desugaring_kind() {
137 Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
138 _ => match self.let_source {
139 LetSource::Else => LetSource::ElseIfLet,
140 _ => LetSource::IfLet,
141 },
142 };
143 self.with_let_source(let_source, |this| this.visit_expr(&self.thir[cond]));
144 self.with_let_source(LetSource::None, |this| {
145 this.visit_expr(&this.thir[then]);
146 });
147 if let Some(else_) = else_opt {
148 self.with_let_source(LetSource::Else, |this| {
149 this.visit_expr(&this.thir[else_])
150 });
151 }
152 return;
153 }
154 ExprKind::Match { scrutinee, box ref arms, match_source } => {
155 self.check_match(scrutinee, arms, match_source, ex.span);
156 }
157 ExprKind::LoopMatch {
158 match_data: box LoopMatchMatchData { scrutinee, box ref arms, span },
159 ..
160 } => {
161 self.check_match(scrutinee, arms, MatchSource::Normal, span);
162 }
163 ExprKind::Let { box ref pat, expr } => {
164 self.check_let(pat, Some(expr), ex.span);
165 }
166 ExprKind::LogicalOp { op: LogicalOp::And, .. }
167 if !matches!(self.let_source, LetSource::None) =>
168 {
169 let mut chain_refutabilities = Vec::new();
170 let Ok(()) = self.visit_land(ex, &mut chain_refutabilities) else { return };
171 if chain_refutabilities.iter().any(|x| x.is_some()) {
173 self.check_let_chain(chain_refutabilities, ex.span);
174 }
175 return;
176 }
177 _ => {}
178 };
179 self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex));
180 }
181
182 fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) {
183 match stmt.kind {
184 StmtKind::Let {
185 box ref pattern, initializer, else_block, lint_level, span, ..
186 } => {
187 self.with_lint_level(lint_level, |this| {
188 let let_source =
189 if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet };
190 this.with_let_source(let_source, |this| {
191 this.check_let(pattern, initializer, span)
192 });
193 visit::walk_stmt(this, stmt);
194 });
195 }
196 StmtKind::Expr { .. } => {
197 visit::walk_stmt(self, stmt);
198 }
199 }
200 }
201}
202
203impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
204 #[instrument(level = "trace", skip(self, f))]
205 fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
206 let old_let_source = self.let_source;
207 self.let_source = let_source;
208 ensure_sufficient_stack(|| f(self));
209 self.let_source = old_let_source;
210 }
211
212 fn with_lint_level<T>(
213 &mut self,
214 new_lint_level: LintLevel,
215 f: impl FnOnce(&mut Self) -> T,
216 ) -> T {
217 if let LintLevel::Explicit(hir_id) = new_lint_level {
218 let old_lint_level = self.lint_level;
219 self.lint_level = hir_id;
220 let ret = f(self);
221 self.lint_level = old_lint_level;
222 ret
223 } else {
224 f(self)
225 }
226 }
227
228 fn visit_land(
231 &mut self,
232 ex: &'p Expr<'tcx>,
233 accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
234 ) -> Result<(), ErrorGuaranteed> {
235 match ex.kind {
236 ExprKind::Scope { value, lint_level, .. } => self.with_lint_level(lint_level, |this| {
237 this.visit_land(&this.thir[value], accumulator)
238 }),
239 ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
240 let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
242 let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
243 accumulator.push(res_rhs);
244 res_lhs
245 }
246 _ => {
247 let res = self.visit_land_rhs(ex)?;
248 accumulator.push(res);
249 Ok(())
250 }
251 }
252 }
253
254 fn visit_land_rhs(
258 &mut self,
259 ex: &'p Expr<'tcx>,
260 ) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
261 match ex.kind {
262 ExprKind::Scope { value, lint_level, .. } => {
263 self.with_lint_level(lint_level, |this| this.visit_land_rhs(&this.thir[value]))
264 }
265 ExprKind::Let { box ref pat, expr } => {
266 let expr = &self.thir()[expr];
267 self.with_let_source(LetSource::None, |this| {
268 this.visit_expr(expr);
269 });
270 Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
271 }
272 _ => {
273 self.with_let_source(LetSource::None, |this| {
274 this.visit_expr(ex);
275 });
276 Ok(None)
277 }
278 }
279 }
280
281 fn lower_pattern(
282 &mut self,
283 cx: &PatCtxt<'p, 'tcx>,
284 pat: &'p Pat<'tcx>,
285 ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
286 if let Err(err) = pat.pat_error_reported() {
287 self.error = Err(err);
288 Err(err)
289 } else {
290 let refutable = if cx.refutable { Refutable } else { Irrefutable };
292 let mut err = Ok(());
293 pat.walk_always(|pat| {
294 check_borrow_conflicts_in_at_patterns(self, pat);
295 check_for_bindings_named_same_as_variants(self, pat, refutable);
296 err = err.and(check_never_pattern(cx, pat));
297 });
298 err?;
299 Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
300 }
301 }
302
303 fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
306 use ExprKind::*;
307 match &scrutinee.kind {
308 Deref { .. } => false,
311 Field { lhs, .. } => {
313 let lhs = &self.thir()[*lhs];
314 match lhs.ty.kind() {
315 ty::Adt(def, _) if def.is_union() => false,
316 _ => self.is_known_valid_scrutinee(lhs),
317 }
318 }
319 Index { lhs, .. } => {
321 let lhs = &self.thir()[*lhs];
322 self.is_known_valid_scrutinee(lhs)
323 }
324
325 Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
327
328 NeverToAny { source }
330 | Cast { source }
331 | Use { source }
332 | PointerCoercion { source, .. }
333 | PlaceTypeAscription { source, .. }
334 | ValueTypeAscription { source, .. }
335 | PlaceUnwrapUnsafeBinder { source }
336 | ValueUnwrapUnsafeBinder { source }
337 | WrapUnsafeBinder { source } => self.is_known_valid_scrutinee(&self.thir()[*source]),
338
339 Become { .. }
341 | Break { .. }
342 | Continue { .. }
343 | ConstContinue { .. }
344 | Return { .. } => true,
345
346 Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
348
349 RawBorrow { .. }
351 | Adt { .. }
352 | Array { .. }
353 | Binary { .. }
354 | Block { .. }
355 | Borrow { .. }
356 | Box { .. }
357 | Call { .. }
358 | ByUse { .. }
359 | Closure { .. }
360 | ConstBlock { .. }
361 | ConstParam { .. }
362 | If { .. }
363 | Literal { .. }
364 | LogicalOp { .. }
365 | Loop { .. }
366 | LoopMatch { .. }
367 | Match { .. }
368 | NamedConst { .. }
369 | NonHirLiteral { .. }
370 | OffsetOf { .. }
371 | Repeat { .. }
372 | StaticRef { .. }
373 | ThreadLocalRef { .. }
374 | Tuple { .. }
375 | Unary { .. }
376 | UpvarRef { .. }
377 | VarRef { .. }
378 | ZstLiteral { .. }
379 | Yield { .. } => true,
380 }
381 }
382
383 fn new_cx(
384 &self,
385 refutability: RefutableFlag,
386 whole_match_span: Option<Span>,
387 scrutinee: Option<&Expr<'tcx>>,
388 scrut_span: Span,
389 ) -> PatCtxt<'p, 'tcx> {
390 let refutable = match refutability {
391 Irrefutable => false,
392 Refutable => true,
393 };
394 let known_valid_scrutinee =
397 scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
398 PatCtxt {
399 tcx: self.tcx,
400 typeck_results: self.typeck_results,
401 typing_env: self.typing_env,
402 module: self.tcx.parent_module(self.lint_level).to_def_id(),
403 dropless_arena: self.dropless_arena,
404 match_lint_level: self.lint_level,
405 whole_match_span,
406 scrut_span,
407 refutable,
408 known_valid_scrutinee,
409 internal_state: Default::default(),
410 }
411 }
412
413 fn analyze_patterns(
414 &mut self,
415 cx: &PatCtxt<'p, 'tcx>,
416 arms: &[MatchArm<'p, 'tcx>],
417 scrut_ty: Ty<'tcx>,
418 ) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
419 let report =
420 rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
421 self.error = Err(err);
422 err
423 })?;
424
425 for (arm, is_useful) in report.arm_usefulness.iter() {
427 if let Usefulness::Useful(redundant_subpats) = is_useful
428 && !redundant_subpats.is_empty()
429 {
430 let mut redundant_subpats = redundant_subpats.clone();
431 redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
433 for (pat, explanation) in redundant_subpats {
434 report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None)
435 }
436 }
437 }
438 Ok(report)
439 }
440
441 #[instrument(level = "trace", skip(self))]
442 fn check_let(&mut self, pat: &'p Pat<'tcx>, scrutinee: Option<ExprId>, span: Span) {
443 assert!(self.let_source != LetSource::None);
444 let scrut = scrutinee.map(|id| &self.thir[id]);
445 if let LetSource::PlainLet = self.let_source {
446 self.check_binding_is_irrefutable(pat, "local binding", scrut, Some(span))
447 } else {
448 let Ok(refutability) = self.is_let_irrefutable(pat, scrut) else { return };
449 if matches!(refutability, Irrefutable) {
450 report_irrefutable_let_patterns(
451 self.tcx,
452 self.lint_level,
453 self.let_source,
454 1,
455 span,
456 );
457 }
458 }
459 }
460
461 fn check_match(
462 &mut self,
463 scrut: ExprId,
464 arms: &[ArmId],
465 source: hir::MatchSource,
466 expr_span: Span,
467 ) {
468 let scrut = &self.thir[scrut];
469 let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
470
471 let mut tarms = Vec::with_capacity(arms.len());
472 for &arm in arms {
473 let arm = &self.thir.arms[arm];
474 let got_error = self.with_lint_level(arm.lint_level, |this| {
475 let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
476 let arm =
477 MatchArm { pat, arm_data: this.lint_level, has_guard: arm.guard.is_some() };
478 tarms.push(arm);
479 false
480 });
481 if got_error {
482 return;
483 }
484 }
485
486 let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
487
488 match source {
489 hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
492 hir::MatchSource::ForLoopDesugar
493 | hir::MatchSource::Postfix
494 | hir::MatchSource::Normal
495 | hir::MatchSource::FormatArgs => {
496 let is_match_arm =
497 matches!(source, hir::MatchSource::Postfix | hir::MatchSource::Normal);
498 report_arm_reachability(&cx, &report, is_match_arm);
499 }
500 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
503 }
504
505 let witnesses = report.non_exhaustiveness_witnesses;
507 if !witnesses.is_empty() {
508 if source == hir::MatchSource::ForLoopDesugar
509 && let [_, snd_arm] = *arms
510 {
511 let pat = &self.thir[snd_arm].pattern;
513 debug_assert_eq!(pat.span.desugaring_kind(), Some(DesugaringKind::ForLoop));
515 let PatKind::Variant { ref subpatterns, .. } = pat.kind else { bug!() };
516 let [pat_field] = &subpatterns[..] else { bug!() };
517 self.check_binding_is_irrefutable(
518 &pat_field.pattern,
519 "`for` loop binding",
520 None,
521 None,
522 );
523 } else {
524 let braces_span = match source {
527 hir::MatchSource::Normal => scrut
528 .span
529 .find_ancestor_in_same_ctxt(expr_span)
530 .map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
531 hir::MatchSource::Postfix => {
532 scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
535 let sm = self.tcx.sess.source_map();
536 let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
537 if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
538 let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
539 sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
541 } else {
542 None
543 }
544 })
545 }
546 hir::MatchSource::ForLoopDesugar
547 | hir::MatchSource::TryDesugar(_)
548 | hir::MatchSource::AwaitDesugar
549 | hir::MatchSource::FormatArgs => None,
550 };
551 self.error = Err(report_non_exhaustive_match(
552 &cx,
553 self.thir,
554 scrut.ty,
555 scrut.span,
556 witnesses,
557 arms,
558 braces_span,
559 ));
560 }
561 }
562 }
563
564 #[instrument(level = "trace", skip(self))]
565 fn check_let_chain(
566 &mut self,
567 chain_refutabilities: Vec<Option<(Span, RefutableFlag)>>,
568 whole_chain_span: Span,
569 ) {
570 assert!(self.let_source != LetSource::None);
571
572 if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, Irrefutable)))) {
573 report_irrefutable_let_patterns(
575 self.tcx,
576 self.lint_level,
577 self.let_source,
578 chain_refutabilities.len(),
579 whole_chain_span,
580 );
581 return;
582 }
583
584 if let Some(until) =
585 chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, Irrefutable))))
586 && until > 0
587 {
588 if !matches!(
598 self.let_source,
599 LetSource::WhileLet | LetSource::IfLetGuard | LetSource::ElseIfLet
600 ) {
601 let prefix = &chain_refutabilities[..until];
603 let span_start = prefix[0].unwrap().0;
604 let span_end = prefix.last().unwrap().unwrap().0;
605 let span = span_start.to(span_end);
606 let count = prefix.len();
607 self.tcx.emit_node_span_lint(
608 IRREFUTABLE_LET_PATTERNS,
609 self.lint_level,
610 span,
611 LeadingIrrefutableLetPatterns { count },
612 );
613 }
614 }
615
616 if let Some(from) =
617 chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, Irrefutable))))
618 && from != (chain_refutabilities.len() - 1)
619 {
620 let suffix = &chain_refutabilities[from + 1..];
622 let span_start = suffix[0].unwrap().0;
623 let span_end = suffix.last().unwrap().unwrap().0;
624 let span = span_start.to(span_end);
625 let count = suffix.len();
626 self.tcx.emit_node_span_lint(
627 IRREFUTABLE_LET_PATTERNS,
628 self.lint_level,
629 span,
630 TrailingIrrefutableLetPatterns { count },
631 );
632 }
633 }
634
635 fn analyze_binding(
636 &mut self,
637 pat: &'p Pat<'tcx>,
638 refutability: RefutableFlag,
639 scrut: Option<&Expr<'tcx>>,
640 ) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
641 let cx = self.new_cx(refutability, None, scrut, pat.span);
642 let pat = self.lower_pattern(&cx, pat)?;
643 let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
644 let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?;
645 Ok((cx, report))
646 }
647
648 fn is_let_irrefutable(
649 &mut self,
650 pat: &'p Pat<'tcx>,
651 scrut: Option<&Expr<'tcx>>,
652 ) -> Result<RefutableFlag, ErrorGuaranteed> {
653 let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?;
654 report_arm_reachability(&cx, &report, false);
656 Ok(if report.non_exhaustiveness_witnesses.is_empty() { Irrefutable } else { Refutable })
659 }
660
661 #[instrument(level = "trace", skip(self))]
662 fn check_binding_is_irrefutable(
663 &mut self,
664 pat: &'p Pat<'tcx>,
665 origin: &str,
666 scrut: Option<&Expr<'tcx>>,
667 sp: Option<Span>,
668 ) {
669 let pattern_ty = pat.ty;
670
671 let Ok((cx, report)) = self.analyze_binding(pat, Irrefutable, scrut) else { return };
672 let witnesses = report.non_exhaustiveness_witnesses;
673 if witnesses.is_empty() {
674 return;
676 }
677
678 let inform = sp.is_some().then_some(Inform);
679 let mut let_suggestion = None;
680 let mut misc_suggestion = None;
681 let mut interpreted_as_const = None;
682 let mut interpreted_as_const_sugg = None;
683
684 let mut unpeeled_pat = pat;
687 while let PatKind::AscribeUserType { ref subpattern, .. } = unpeeled_pat.kind {
688 unpeeled_pat = subpattern;
689 }
690
691 if let PatKind::ExpandedConstant { def_id, .. } = unpeeled_pat.kind
692 && let DefKind::Const = self.tcx.def_kind(def_id)
693 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
694 && snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
696 {
697 let span = self.tcx.def_span(def_id);
698 let variable = self.tcx.item_name(def_id).to_string();
699 interpreted_as_const = Some(InterpretedAsConst { span, variable: variable.clone() });
701 interpreted_as_const_sugg = Some(InterpretedAsConstSugg { span: pat.span, variable });
702 } else if let PatKind::Constant { .. } = unpeeled_pat.kind
703 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
704 {
705 if snippet.chars().all(|c| c.is_digit(10)) {
707 misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
709 start_span: pat.span.shrink_to_lo(),
710 });
711 }
712 }
713
714 if let Some(span) = sp
715 && self.tcx.sess.source_map().is_span_accessible(span)
716 && interpreted_as_const.is_none()
717 && scrut.is_some()
718 {
719 let mut bindings = vec![];
720 pat.each_binding(|name, _, _, _| bindings.push(name));
721
722 let semi_span = span.shrink_to_hi();
723 let start_span = span.shrink_to_lo();
724 let end_span = semi_span.shrink_to_lo();
725 let count = witnesses.len();
726
727 let_suggestion = Some(if bindings.is_empty() {
728 SuggestLet::If { start_span, semi_span, count }
729 } else {
730 SuggestLet::Else { end_span, count }
731 });
732 };
733
734 let adt_defined_here = report_adt_defined_here(self.tcx, pattern_ty, &witnesses, false);
735
736 let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
739 && let ty::Adt(adt, args) = witness_1.ty().kind()
740 && adt.is_enum()
741 && let Constructor::Variant(variant_index) = witness_1.ctor()
742 {
743 let variant_inhabited = adt
744 .variant(*variant_index)
745 .inhabited_predicate(self.tcx, *adt)
746 .instantiate(self.tcx, args);
747 variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
748 && !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env)
749 } else {
750 false
751 };
752
753 let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
754
755 self.error = Err(self.tcx.dcx().emit_err(PatternNotCovered {
756 span: pat.span,
757 origin,
758 uncovered: Uncovered::new(pat.span, &cx, witnesses),
759 inform,
760 interpreted_as_const,
761 interpreted_as_const_sugg,
762 witness_1_is_privately_uninhabited,
763 witness_1,
764 _p: (),
765 pattern_ty,
766 let_suggestion,
767 misc_suggestion,
768 adt_defined_here,
769 }));
770 }
771}
772
773fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) {
785 let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else {
787 return;
788 };
789
790 let is_binding_by_move = |ty: Ty<'tcx>| !cx.tcx.type_is_copy_modulo_regions(cx.typing_env, ty);
791
792 let sess = cx.tcx.sess;
793
794 let mut_outer = match mode.0 {
796 ByRef::No if is_binding_by_move(ty) => {
797 let mut conflicts_ref = Vec::new();
799 sub.each_binding(|_, mode, _, span| {
800 if matches!(mode, ByRef::Yes(_)) {
801 conflicts_ref.push(span)
802 }
803 });
804 if !conflicts_ref.is_empty() {
805 sess.dcx().emit_err(BorrowOfMovedValue {
806 binding_span: pat.span,
807 conflicts_ref,
808 name: Ident::new(name, pat.span),
809 ty,
810 suggest_borrowing: Some(pat.span.shrink_to_lo()),
811 });
812 }
813 return;
814 }
815 ByRef::No => return,
816 ByRef::Yes(m) => m,
817 };
818
819 let mut conflicts_move = Vec::new();
822 let mut conflicts_mut_mut = Vec::new();
823 let mut conflicts_mut_ref = Vec::new();
824 sub.each_binding(|name, mode, ty, span| {
825 match mode {
826 ByRef::Yes(mut_inner) => match (mut_outer, mut_inner) {
827 (Mutability::Not, Mutability::Not) => {}
829 (Mutability::Mut, Mutability::Mut) => {
831 conflicts_mut_mut.push(Conflict::Mut { span, name })
832 }
833 (Mutability::Not, Mutability::Mut) => {
834 conflicts_mut_ref.push(Conflict::Mut { span, name })
835 }
836 (Mutability::Mut, Mutability::Not) => {
837 conflicts_mut_ref.push(Conflict::Ref { span, name })
838 }
839 },
840 ByRef::No if is_binding_by_move(ty) => {
841 conflicts_move.push(Conflict::Moved { span, name }) }
843 ByRef::No => {} }
845 });
846
847 let report_mut_mut = !conflicts_mut_mut.is_empty();
848 let report_mut_ref = !conflicts_mut_ref.is_empty();
849 let report_move_conflict = !conflicts_move.is_empty();
850
851 let mut occurrences = match mut_outer {
852 Mutability::Mut => vec![Conflict::Mut { span: pat.span, name }],
853 Mutability::Not => vec![Conflict::Ref { span: pat.span, name }],
854 };
855 occurrences.extend(conflicts_mut_mut);
856 occurrences.extend(conflicts_mut_ref);
857 occurrences.extend(conflicts_move);
858
859 if report_mut_mut {
861 sess.dcx().emit_err(MultipleMutBorrows { span: pat.span, occurrences });
863 } else if report_mut_ref {
864 match mut_outer {
866 Mutability::Mut => {
867 sess.dcx().emit_err(AlreadyMutBorrowed { span: pat.span, occurrences });
868 }
869 Mutability::Not => {
870 sess.dcx().emit_err(AlreadyBorrowed { span: pat.span, occurrences });
871 }
872 };
873 } else if report_move_conflict {
874 sess.dcx().emit_err(MovedWhileBorrowed { span: pat.span, occurrences });
876 }
877}
878
879fn check_for_bindings_named_same_as_variants(
880 cx: &MatchVisitor<'_, '_>,
881 pat: &Pat<'_>,
882 rf: RefutableFlag,
883) {
884 if let PatKind::Binding {
885 name,
886 mode: BindingMode(ByRef::No, Mutability::Not),
887 subpattern: None,
888 ty,
889 ..
890 } = pat.kind
891 && let ty::Adt(edef, _) = ty.peel_refs().kind()
892 && edef.is_enum()
893 && edef
894 .variants()
895 .iter()
896 .any(|variant| variant.name == name && variant.ctor_kind() == Some(CtorKind::Const))
897 {
898 let variant_count = edef.variants().len();
899 let ty_path = with_no_trimmed_paths!(cx.tcx.def_path_str(edef.did()));
900 cx.tcx.emit_node_span_lint(
901 BINDINGS_WITH_VARIANT_NAME,
902 cx.lint_level,
903 pat.span,
904 BindingsWithVariantName {
905 suggestion: if rf == Refutable || variant_count == 1 {
909 Some(pat.span)
910 } else {
911 None
912 },
913 ty_path,
914 name: Ident::new(name, pat.span),
915 },
916 )
917 }
918}
919
920fn check_never_pattern<'tcx>(
922 cx: &PatCtxt<'_, 'tcx>,
923 pat: &Pat<'tcx>,
924) -> Result<(), ErrorGuaranteed> {
925 if let PatKind::Never = pat.kind {
926 if !cx.is_uninhabited(pat.ty) {
927 return Err(cx.tcx.dcx().emit_err(NonEmptyNeverPattern { span: pat.span, ty: pat.ty }));
928 }
929 }
930 Ok(())
931}
932
933fn report_irrefutable_let_patterns(
934 tcx: TyCtxt<'_>,
935 id: HirId,
936 source: LetSource,
937 count: usize,
938 span: Span,
939) {
940 macro_rules! emit_diag {
941 ($lint:tt) => {{
942 tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span, $lint { count });
943 }};
944 }
945
946 match source {
947 LetSource::None | LetSource::PlainLet | LetSource::Else => bug!(),
948 LetSource::IfLet | LetSource::ElseIfLet => emit_diag!(IrrefutableLetPatternsIfLet),
949 LetSource::IfLetGuard => emit_diag!(IrrefutableLetPatternsIfLetGuard),
950 LetSource::LetElse => emit_diag!(IrrefutableLetPatternsLetElse),
951 LetSource::WhileLet => emit_diag!(IrrefutableLetPatternsWhileLet),
952 }
953}
954
955fn report_unreachable_pattern<'p, 'tcx>(
957 cx: &PatCtxt<'p, 'tcx>,
958 hir_id: HirId,
959 pat: &DeconstructedPat<'p, 'tcx>,
960 explanation: &RedundancyExplanation<'p, 'tcx>,
961 whole_arm_span: Option<Span>,
962) {
963 static CAP_COVERED_BY_MANY: usize = 4;
964 let pat_span = pat.data().span;
965 let mut lint = UnreachablePattern {
966 span: Some(pat_span),
967 matches_no_values: None,
968 matches_no_values_ty: **pat.ty(),
969 uninhabited_note: None,
970 covered_by_catchall: None,
971 covered_by_one: None,
972 covered_by_many: None,
973 covered_by_many_n_more_count: 0,
974 wanted_constant: None,
975 accessible_constant: None,
976 inaccessible_constant: None,
977 pattern_let_binding: None,
978 suggest_remove: None,
979 };
980 match explanation.covered_by.as_slice() {
981 [] => {
982 lint.span = None; lint.uninhabited_note = Some(()); lint.matches_no_values = Some(pat_span);
986 lint.suggest_remove = whole_arm_span; pat.walk(&mut |subpat| {
988 let ty = **subpat.ty();
989 if cx.is_uninhabited(ty) {
990 lint.matches_no_values_ty = ty;
991 false } else if matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) {
993 false } else {
995 true
996 }
997 });
998 }
999 [covering_pat] if pat_is_catchall(covering_pat) => {
1000 let pat = covering_pat.data();
1002 lint.covered_by_catchall = Some(pat.span);
1003 find_fallback_pattern_typo(cx, hir_id, pat, &mut lint);
1004 }
1005 [covering_pat] => {
1006 lint.covered_by_one = Some(covering_pat.data().span);
1007 }
1008 covering_pats => {
1009 let mut iter = covering_pats.iter();
1010 let mut multispan = MultiSpan::from_span(pat_span);
1011 for p in iter.by_ref().take(CAP_COVERED_BY_MANY) {
1012 multispan.push_span_label(
1013 p.data().span,
1014 fluent::mir_build_unreachable_matches_same_values,
1015 );
1016 }
1017 let remain = iter.count();
1018 if remain == 0 {
1019 multispan.push_span_label(
1020 pat_span,
1021 fluent::mir_build_unreachable_making_this_unreachable,
1022 );
1023 } else {
1024 lint.covered_by_many_n_more_count = remain;
1025 multispan.push_span_label(
1026 pat_span,
1027 fluent::mir_build_unreachable_making_this_unreachable_n_more,
1028 );
1029 }
1030 lint.covered_by_many = Some(multispan);
1031 }
1032 }
1033 cx.tcx.emit_node_span_lint(UNREACHABLE_PATTERNS, hir_id, pat_span, lint);
1034}
1035
1036fn find_fallback_pattern_typo<'tcx>(
1038 cx: &PatCtxt<'_, 'tcx>,
1039 hir_id: HirId,
1040 pat: &Pat<'tcx>,
1041 lint: &mut UnreachablePattern<'_>,
1042) {
1043 if let Level::Allow = cx.tcx.lint_level_at_node(UNREACHABLE_PATTERNS, hir_id).level {
1044 return;
1047 }
1048 if let PatKind::Binding { name, subpattern: None, ty, .. } = pat.kind {
1049 let mut accessible = vec![];
1051 let mut accessible_path = vec![];
1052 let mut inaccessible = vec![];
1053 let mut imported = vec![];
1054 let mut imported_spans = vec![];
1055 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
1056 let parent = cx.tcx.hir_get_parent_item(hir_id);
1057
1058 for item in cx.tcx.hir_crate_items(()).free_items() {
1059 if let DefKind::Use = cx.tcx.def_kind(item.owner_id) {
1060 let item = cx.tcx.hir_expect_item(item.owner_id.def_id);
1062 let hir::ItemKind::Use(path, _) = item.kind else {
1063 continue;
1064 };
1065 if let Some(value_ns) = path.res.value_ns
1066 && let Res::Def(DefKind::Const, id) = value_ns
1067 && infcx.can_eq(param_env, ty, cx.tcx.type_of(id).instantiate_identity())
1068 {
1069 if cx.tcx.visibility(id).is_accessible_from(parent, cx.tcx) {
1070 let item_name = cx.tcx.item_name(id);
1072 accessible.push(item_name);
1073 accessible_path.push(with_no_trimmed_paths!(cx.tcx.def_path_str(id)));
1074 } else if cx.tcx.visibility(item.owner_id).is_accessible_from(parent, cx.tcx) {
1075 let ident = item.kind.ident().unwrap();
1078 imported.push(ident.name);
1079 imported_spans.push(ident.span);
1080 }
1081 }
1082 }
1083 if let DefKind::Const = cx.tcx.def_kind(item.owner_id)
1084 && infcx.can_eq(param_env, ty, cx.tcx.type_of(item.owner_id).instantiate_identity())
1085 {
1086 let item_name = cx.tcx.item_name(item.owner_id);
1088 let vis = cx.tcx.visibility(item.owner_id);
1089 if vis.is_accessible_from(parent, cx.tcx) {
1090 accessible.push(item_name);
1091 let path = with_no_trimmed_paths!(cx.tcx.def_path_str(item.owner_id));
1098 accessible_path.push(path);
1099 } else if name == item_name {
1100 inaccessible.push(cx.tcx.def_span(item.owner_id));
1103 }
1104 }
1105 }
1106 if let Some((i, &const_name)) =
1107 accessible.iter().enumerate().find(|&(_, &const_name)| const_name == name)
1108 {
1109 lint.wanted_constant = Some(WantedConstant {
1111 span: pat.span,
1112 is_typo: false,
1113 const_name: const_name.to_string(),
1114 const_path: accessible_path[i].clone(),
1115 });
1116 } else if let Some(name) = find_best_match_for_name(&accessible, name, None) {
1117 lint.wanted_constant = Some(WantedConstant {
1119 span: pat.span,
1120 is_typo: true,
1121 const_name: name.to_string(),
1122 const_path: name.to_string(),
1123 });
1124 } else if let Some(i) =
1125 imported.iter().enumerate().find(|&(_, &const_name)| const_name == name).map(|(i, _)| i)
1126 {
1127 lint.accessible_constant = Some(imported_spans[i]);
1130 } else if let Some(name) = find_best_match_for_name(&imported, name, None) {
1131 lint.wanted_constant = Some(WantedConstant {
1134 span: pat.span,
1135 is_typo: true,
1136 const_path: name.to_string(),
1137 const_name: name.to_string(),
1138 });
1139 } else if !inaccessible.is_empty() {
1140 for span in inaccessible {
1141 lint.inaccessible_constant = Some(span);
1143 }
1144 } else {
1145 for (_, node) in cx.tcx.hir_parent_iter(hir_id) {
1148 match node {
1149 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(let_stmt), .. }) => {
1150 if let hir::PatKind::Binding(_, _, binding_name, _) = let_stmt.pat.kind {
1151 if name == binding_name.name {
1152 lint.pattern_let_binding = Some(binding_name.span);
1153 }
1154 }
1155 }
1156 hir::Node::Block(hir::Block { stmts, .. }) => {
1157 for stmt in *stmts {
1158 if let hir::StmtKind::Let(let_stmt) = stmt.kind {
1159 if let hir::PatKind::Binding(_, _, binding_name, _) =
1160 let_stmt.pat.kind
1161 {
1162 if name == binding_name.name {
1163 lint.pattern_let_binding = Some(binding_name.span);
1164 }
1165 }
1166 }
1167 }
1168 }
1169 hir::Node::Item(_) => break,
1170 _ => {}
1171 }
1172 }
1173 }
1174 }
1175}
1176
1177fn report_arm_reachability<'p, 'tcx>(
1179 cx: &PatCtxt<'p, 'tcx>,
1180 report: &UsefulnessReport<'p, 'tcx>,
1181 is_match_arm: bool,
1182) {
1183 let sm = cx.tcx.sess.source_map();
1184 for (arm, is_useful) in report.arm_usefulness.iter() {
1185 if let Usefulness::Redundant(explanation) = is_useful {
1186 let hir_id = arm.arm_data;
1187 let arm_span = cx.tcx.hir_span(hir_id);
1188 let whole_arm_span = if is_match_arm {
1189 let with_whitespace = sm.span_extend_while_whitespace(arm_span);
1191 if let Some(comma) = sm.span_look_ahead(with_whitespace, ",", Some(1)) {
1192 Some(arm_span.to(comma))
1193 } else {
1194 Some(arm_span)
1195 }
1196 } else {
1197 None
1198 };
1199 report_unreachable_pattern(cx, hir_id, arm.pat, explanation, whole_arm_span)
1200 }
1201 }
1202}
1203
1204fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
1206 match pat.ctor() {
1207 Constructor::Wildcard => true,
1208 Constructor::Struct | Constructor::Ref => {
1209 pat.iter_fields().all(|ipat| pat_is_catchall(&ipat.pat))
1210 }
1211 _ => false,
1212 }
1213}
1214
1215fn report_non_exhaustive_match<'p, 'tcx>(
1217 cx: &PatCtxt<'p, 'tcx>,
1218 thir: &Thir<'tcx>,
1219 scrut_ty: Ty<'tcx>,
1220 sp: Span,
1221 witnesses: Vec<WitnessPat<'p, 'tcx>>,
1222 arms: &[ArmId],
1223 braces_span: Option<Span>,
1224) -> ErrorGuaranteed {
1225 let is_empty_match = arms.is_empty();
1226 let non_empty_enum = match scrut_ty.kind() {
1227 ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
1228 _ => false,
1229 };
1230 if is_empty_match && !non_empty_enum {
1233 return cx.tcx.dcx().emit_err(NonExhaustivePatternsTypeNotEmpty {
1234 cx,
1235 scrut_span: sp,
1236 braces_span,
1237 ty: scrut_ty,
1238 });
1239 }
1240
1241 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
1243 let mut err = struct_span_code_err!(
1244 cx.tcx.dcx(),
1245 sp,
1246 E0004,
1247 "non-exhaustive patterns: {joined_patterns} not covered"
1248 );
1249 err.span_label(
1250 sp,
1251 format!(
1252 "pattern{} {} not covered",
1253 rustc_errors::pluralize!(witnesses.len()),
1254 joined_patterns
1255 ),
1256 );
1257
1258 if let Some(AdtDefinedHere { adt_def_span, ty, variants }) =
1260 report_adt_defined_here(cx.tcx, scrut_ty, &witnesses, true)
1261 {
1262 let mut multi_span = MultiSpan::from_span(adt_def_span);
1263 multi_span.push_span_label(adt_def_span, "");
1264 for Variant { span } in variants {
1265 multi_span.push_span_label(span, "not covered");
1266 }
1267 err.span_note(multi_span, format!("`{ty}` defined here"));
1268 }
1269 err.note(format!("the matched value is of type `{}`", scrut_ty));
1270
1271 if !is_empty_match {
1272 let mut special_tys = FxIndexSet::default();
1273 collect_special_tys(cx, &witnesses[0], &mut special_tys);
1275
1276 for ty in special_tys {
1277 if ty.is_ptr_sized_integral() {
1278 if ty.inner() == cx.tcx.types.usize {
1279 err.note(format!(
1280 "`{ty}` does not have a fixed maximum value, so half-open ranges are \
1281 necessary to match exhaustively",
1282 ));
1283 } else if ty.inner() == cx.tcx.types.isize {
1284 err.note(format!(
1285 "`{ty}` does not have fixed minimum and maximum values, so half-open \
1286 ranges are necessary to match exhaustively",
1287 ));
1288 }
1289 } else if ty.inner() == cx.tcx.types.str_ {
1290 err.note("`&str` cannot be matched exhaustively, so a wildcard `_` is necessary");
1291 } else if cx.is_foreign_non_exhaustive_enum(ty) {
1292 err.note(format!("`{ty}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively"));
1293 } else if cx.is_uninhabited(ty.inner()) {
1294 err.note(format!("`{ty}` is uninhabited but is not being matched by value, so a wildcard `_` is required"));
1297 }
1298 }
1299 }
1300
1301 if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
1302 if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.typing_env) {
1303 err.note("references are always considered inhabited");
1304 }
1305 }
1306
1307 for &arm in arms {
1308 let arm = &thir.arms[arm];
1309 if let PatKind::ExpandedConstant { def_id, .. } = arm.pattern.kind
1310 && !matches!(cx.tcx.def_kind(def_id), DefKind::InlineConst)
1311 && let Ok(snippet) = cx.tcx.sess.source_map().span_to_snippet(arm.pattern.span)
1312 && snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
1314 {
1315 let const_name = cx.tcx.item_name(def_id);
1316 err.span_label(
1317 arm.pattern.span,
1318 format!(
1319 "this pattern doesn't introduce a new catch-all binding, but rather pattern \
1320 matches against the value of constant `{const_name}`",
1321 ),
1322 );
1323 err.span_note(cx.tcx.def_span(def_id), format!("constant `{const_name}` defined here"));
1324 err.span_suggestion_verbose(
1325 arm.pattern.span.shrink_to_hi(),
1326 "if you meant to introduce a binding, use a different name",
1327 "_var".to_string(),
1328 Applicability::MaybeIncorrect,
1329 );
1330 }
1331 }
1332
1333 let suggest_the_witnesses = witnesses.len() < 4;
1335 let suggested_arm = if suggest_the_witnesses {
1336 let pattern = witnesses
1337 .iter()
1338 .map(|witness| cx.print_witness_pat(witness))
1339 .collect::<Vec<String>>()
1340 .join(" | ");
1341 if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns() {
1342 pattern
1344 } else {
1345 format!("{pattern} => todo!()")
1346 }
1347 } else {
1348 format!("_ => todo!()")
1349 };
1350 let mut suggestion = None;
1351 let sm = cx.tcx.sess.source_map();
1352 match arms {
1353 [] if let Some(braces_span) = braces_span => {
1354 let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
1356 (format!("\n{snippet}"), " ")
1357 } else {
1358 (" ".to_string(), "")
1359 };
1360 suggestion = Some((
1361 braces_span,
1362 format!(" {{{indentation}{more}{suggested_arm},{indentation}}}",),
1363 ));
1364 }
1365 [only] => {
1366 let only = &thir[*only];
1367 let (pre_indentation, is_multiline) = if let Some(snippet) =
1368 sm.indentation_before(only.span)
1369 && let Ok(with_trailing) =
1370 sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
1371 && sm.is_multiline(with_trailing)
1372 {
1373 (format!("\n{snippet}"), true)
1374 } else {
1375 (" ".to_string(), false)
1376 };
1377 let only_body = &thir[only.body];
1378 let comma = if matches!(only_body.kind, ExprKind::Block { .. })
1379 && only.span.eq_ctxt(only_body.span)
1380 && is_multiline
1381 {
1382 ""
1383 } else {
1384 ","
1385 };
1386 suggestion = Some((
1387 only.span.shrink_to_hi(),
1388 format!("{comma}{pre_indentation}{suggested_arm}"),
1389 ));
1390 }
1391 [.., prev, last] => {
1392 let prev = &thir[*prev];
1393 let last = &thir[*last];
1394 if prev.span.eq_ctxt(last.span) {
1395 let last_body = &thir[last.body];
1396 let comma = if matches!(last_body.kind, ExprKind::Block { .. })
1397 && last.span.eq_ctxt(last_body.span)
1398 {
1399 ""
1400 } else {
1401 ","
1402 };
1403 let spacing = if sm.is_multiline(prev.span.between(last.span)) {
1404 sm.indentation_before(last.span).map(|indent| format!("\n{indent}"))
1405 } else {
1406 Some(" ".to_string())
1407 };
1408 if let Some(spacing) = spacing {
1409 suggestion = Some((
1410 last.span.shrink_to_hi(),
1411 format!("{comma}{spacing}{suggested_arm}"),
1412 ));
1413 }
1414 }
1415 }
1416 _ => {}
1417 }
1418
1419 let msg = format!(
1420 "ensure that all possible cases are being handled by adding a match arm with a wildcard \
1421 pattern{}{}",
1422 if witnesses.len() > 1 && suggest_the_witnesses && suggestion.is_some() {
1423 ", a match arm with multiple or-patterns"
1424 } else {
1425 ""
1427 },
1428 match witnesses.len() {
1429 0 if suggestion.is_some() => " as shown",
1431 0 => "",
1432 1 if suggestion.is_some() => " or an explicit pattern as shown",
1433 1 => " or an explicit pattern",
1434 _ if suggestion.is_some() => " as shown, or multiple match arms",
1435 _ => " or multiple match arms",
1436 },
1437 );
1438
1439 let all_arms_have_guards = arms.iter().all(|arm_id| thir[*arm_id].guard.is_some());
1440 if !is_empty_match && all_arms_have_guards {
1441 err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
1442 }
1443 if let Some((span, sugg)) = suggestion {
1444 err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
1445 } else {
1446 err.help(msg);
1447 }
1448 err.emit()
1449}
1450
1451fn joined_uncovered_patterns<'p, 'tcx>(
1452 cx: &PatCtxt<'p, 'tcx>,
1453 witnesses: &[WitnessPat<'p, 'tcx>],
1454) -> String {
1455 const LIMIT: usize = 3;
1456 let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.print_witness_pat(pat);
1457 match witnesses {
1458 [] => bug!(),
1459 [witness] => format!("`{}`", cx.print_witness_pat(witness)),
1460 [head @ .., tail] if head.len() < LIMIT => {
1461 let head: Vec<_> = head.iter().map(pat_to_str).collect();
1462 format!("`{}` and `{}`", head.join("`, `"), cx.print_witness_pat(tail))
1463 }
1464 _ => {
1465 let (head, tail) = witnesses.split_at(LIMIT);
1466 let head: Vec<_> = head.iter().map(pat_to_str).collect();
1467 format!("`{}` and {} more", head.join("`, `"), tail.len())
1468 }
1469 }
1470}
1471
1472fn collect_special_tys<'tcx>(
1474 cx: &PatCtxt<'_, 'tcx>,
1475 pat: &WitnessPat<'_, 'tcx>,
1476 special_tys: &mut FxIndexSet<RevealedTy<'tcx>>,
1477) {
1478 if matches!(pat.ctor(), Constructor::NonExhaustive | Constructor::Never) {
1479 special_tys.insert(*pat.ty());
1480 }
1481 if let Constructor::IntRange(range) = pat.ctor() {
1482 if cx.is_range_beyond_boundaries(range, *pat.ty()) {
1483 special_tys.insert(*pat.ty());
1485 }
1486 }
1487 pat.iter_fields().for_each(|field_pat| collect_special_tys(cx, field_pat, special_tys))
1488}
1489
1490fn report_adt_defined_here<'tcx>(
1491 tcx: TyCtxt<'tcx>,
1492 ty: Ty<'tcx>,
1493 witnesses: &[WitnessPat<'_, 'tcx>],
1494 point_at_non_local_ty: bool,
1495) -> Option<AdtDefinedHere<'tcx>> {
1496 let ty = ty.peel_refs();
1497 let ty::Adt(def, _) = ty.kind() else {
1498 return None;
1499 };
1500 let adt_def_span =
1501 tcx.hir_get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
1502 let adt_def_span = if point_at_non_local_ty {
1503 adt_def_span.unwrap_or_else(|| tcx.def_span(def.did()))
1504 } else {
1505 adt_def_span?
1506 };
1507
1508 let mut variants = vec![];
1509 for span in maybe_point_at_variant(tcx, *def, witnesses.iter().take(5)) {
1510 variants.push(Variant { span });
1511 }
1512 Some(AdtDefinedHere { adt_def_span, ty, variants })
1513}
1514
1515fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'p>(
1516 tcx: TyCtxt<'tcx>,
1517 def: AdtDef<'tcx>,
1518 patterns: impl Iterator<Item = &'a WitnessPat<'p, 'tcx>>,
1519) -> Vec<Span> {
1520 let mut covered = vec![];
1521 for pattern in patterns {
1522 if let Constructor::Variant(variant_index) = pattern.ctor() {
1523 if let ty::Adt(this_def, _) = pattern.ty().kind()
1524 && this_def.did() != def.did()
1525 {
1526 continue;
1527 }
1528 let sp = def.variant(*variant_index).ident(tcx).span;
1529 if covered.contains(&sp) {
1530 continue;
1533 }
1534 covered.push(sp);
1535 }
1536 covered.extend(maybe_point_at_variant(tcx, def, pattern.iter_fields()));
1537 }
1538 covered
1539}