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