1 use super::deconstruct_pat::{Constructor, DeconstructedPat};
2 use super::usefulness::{
3 compute_match_usefulness, MatchArm, MatchCheckCtxt, Reachability, UsefulnessReport,
5 use super::{PatCtxt, PatternError};
7 use rustc_arena::TypedArena;
8 use rustc_ast::Mutability;
10 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
11 ErrorGuaranteed, MultiSpan,
14 use rustc_hir::def::*;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::intravisit::{self, Visitor};
17 use rustc_hir::{HirId, Pat};
18 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
19 use rustc_session::lint::builtin::{
20 BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
22 use rustc_session::Session;
23 use rustc_span::source_map::Spanned;
24 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span};
26 crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
27 let body_id = match def_id.as_local() {
29 Some(id) => tcx.hir().body_owned_by(tcx.hir().local_def_id_to_hir_id(id)),
32 let pattern_arena = TypedArena::default();
33 let mut visitor = MatchVisitor {
35 typeck_results: tcx.typeck_body(body_id),
36 param_env: tcx.param_env(def_id),
37 pattern_arena: &pattern_arena,
39 visitor.visit_body(tcx.hir().body(body_id));
45 error_message: String,
46 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
47 struct_span_err!(sess, sp, E0004, "{}", &error_message)
57 struct MatchVisitor<'a, 'p, 'tcx> {
59 typeck_results: &'a ty::TypeckResults<'tcx>,
60 param_env: ty::ParamEnv<'tcx>,
61 pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
64 impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, '_, 'tcx> {
65 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
66 intravisit::walk_expr(self, ex);
68 hir::ExprKind::Match(scrut, arms, source) => {
69 self.check_match(scrut, arms, *source, ex.span)
71 hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
72 self.check_let(pat, init, *span)
78 fn visit_local(&mut self, loc: &'tcx hir::Local<'tcx>) {
79 intravisit::walk_local(self, loc);
81 let (msg, sp) = match loc.source {
82 hir::LocalSource::Normal => ("local binding", Some(loc.span)),
83 hir::LocalSource::AsyncFn => ("async fn binding", None),
84 hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
85 hir::LocalSource::AssignDesugar(_) => ("destructuring assignment binding", None),
87 self.check_irrefutable(&loc.pat, msg, sp);
90 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
91 intravisit::walk_param(self, param);
92 self.check_irrefutable(¶m.pat, "function argument", None);
96 impl PatCtxt<'_, '_> {
97 fn report_inlining_errors(&self) {
98 for error in &self.errors {
100 PatternError::StaticInPattern(span) => {
101 self.span_e0158(span, "statics cannot be referenced in patterns")
103 PatternError::AssocConstInPattern(span) => {
104 self.span_e0158(span, "associated consts cannot be referenced in patterns")
106 PatternError::ConstParamInPattern(span) => {
107 self.span_e0158(span, "const parameters cannot be referenced in patterns")
109 PatternError::NonConstPath(span) => {
110 rustc_middle::mir::interpret::struct_error(
112 "runtime values cannot be referenced in patterns",
120 fn span_e0158(&self, span: Span, text: &str) {
121 struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
125 impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
126 fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) {
127 pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
128 check_for_bindings_named_same_as_variants(self, pat, rf);
133 cx: &mut MatchCheckCtxt<'p, 'tcx>,
134 pat: &'tcx hir::Pat<'tcx>,
135 have_errors: &mut bool,
136 ) -> &'p DeconstructedPat<'p, 'tcx> {
137 let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
138 patcx.include_lint_checks();
139 let pattern = patcx.lower_pattern(pat);
140 let pattern: &_ = cx.pattern_arena.alloc(DeconstructedPat::from_pat(cx, &pattern));
141 if !patcx.errors.is_empty() {
143 patcx.report_inlining_errors();
148 fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'p, 'tcx> {
151 param_env: self.param_env,
152 module: self.tcx.parent_module(hir_id).to_def_id(),
153 pattern_arena: &self.pattern_arena,
157 fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, scrutinee: &hir::Expr<'_>, span: Span) {
158 self.check_patterns(pat, Refutable);
159 let mut cx = self.new_cx(scrutinee.hir_id);
160 let tpat = self.lower_pattern(&mut cx, pat, &mut false);
161 self.check_let_reachability(&mut cx, pat.hir_id, tpat, span);
166 scrut: &hir::Expr<'_>,
167 hir_arms: &'tcx [hir::Arm<'tcx>],
168 source: hir::MatchSource,
171 let mut cx = self.new_cx(scrut.hir_id);
173 for arm in hir_arms {
174 // Check the arm for some things unrelated to exhaustiveness.
175 self.check_patterns(&arm.pat, Refutable);
176 if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
177 self.check_patterns(pat, Refutable);
178 let tpat = self.lower_pattern(&mut cx, pat, &mut false);
179 self.check_let_reachability(&mut cx, pat.hir_id, tpat, tpat.span());
183 let mut have_errors = false;
185 let arms: Vec<_> = hir_arms
187 .map(|hir::Arm { pat, guard, .. }| MatchArm {
188 pat: self.lower_pattern(&mut cx, pat, &mut have_errors),
190 has_guard: guard.is_some(),
194 // Bail out early if lowering failed.
199 let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
200 let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
203 // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
204 // when the iterator is an uninhabited type. unreachable_code will trigger instead.
205 hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
206 hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
207 report_arm_reachability(&cx, &report)
209 // Unreachable patterns in try and await expressions occur when one of
210 // the arms are an uninhabited type. Which is OK.
211 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
214 // Check if the match is exhaustive.
215 let witnesses = report.non_exhaustiveness_witnesses;
216 if !witnesses.is_empty() {
217 if source == hir::MatchSource::ForLoopDesugar && hir_arms.len() == 2 {
218 // the for loop pattern is not irrefutable
219 let pat = hir_arms[1].pat.for_loop_some().unwrap();
220 self.check_irrefutable(pat, "`for` loop binding", None);
222 non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, hir_arms, expr_span);
227 fn check_let_reachability(
229 cx: &mut MatchCheckCtxt<'p, 'tcx>,
231 pat: &'p DeconstructedPat<'p, 'tcx>,
234 if self.check_let_chain(cx, pat_id) {
238 if is_let_irrefutable(cx, pat_id, pat) {
239 irrefutable_let_pattern(cx.tcx, pat_id, span);
243 fn check_let_chain(&mut self, cx: &mut MatchCheckCtxt<'p, 'tcx>, pat_id: HirId) -> bool {
244 let hir = self.tcx.hir();
245 let parent = hir.get_parent_node(pat_id);
247 // First, figure out if the given pattern is part of a let chain,
248 // and if so, obtain the top node of the chain.
249 let mut top = parent;
250 let mut part_of_chain = false;
252 let new_top = hir.get_parent_node(top);
253 if let hir::Node::Expr(
255 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
261 // If this isn't the first iteration, we need to check
262 // if there is a let expr before us in the chain, so
263 // that we avoid doubly checking the let chain.
265 // The way a chain of &&s is encoded is ((let ... && let ...) && let ...) && let ...
266 // as && is left-to-right associative. Thus, we need to check rhs.
267 if part_of_chain && matches!(rhs.kind, hir::ExprKind::Let(..)) {
270 // If there is a let at the lhs, and we provide the rhs, we don't do any checking either.
271 if !part_of_chain && matches!(lhs.kind, hir::ExprKind::Let(..)) && rhs.hir_id == top
276 // We've reached the top.
280 // Since this function is called within a let context, it is reasonable to assume that any parent
281 // `&&` infers a let chain
282 part_of_chain = true;
289 // Second, obtain the refutabilities of all exprs in the chain,
290 // and record chain members that aren't let exprs.
291 let mut chain_refutabilities = Vec::new();
292 let hir::Node::Expr(top_expr) = hir.get(top) else {
293 // We ensure right above that it's an Expr
296 let mut cur_expr = top_expr;
298 let mut add = |expr: &hir::Expr<'tcx>| {
299 let refutability = match expr.kind {
300 hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
301 let mut ncx = self.new_cx(init.hir_id);
302 let tpat = self.lower_pattern(&mut ncx, pat, &mut false);
304 let refutable = !is_let_irrefutable(&mut ncx, pat.hir_id, tpat);
305 Some((*span, refutable))
309 chain_refutabilities.push(refutability);
312 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
323 chain_refutabilities.reverse();
325 // Third, emit the actual warnings.
327 if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, false)))) {
328 // The entire chain is made up of irrefutable `let` statements
329 let let_source = let_source_parent(self.tcx, top, None);
330 irrefutable_let_patterns(
334 chain_refutabilities.len(),
339 let lint_affix = |affix: &[Option<(Span, bool)>], kind, suggestion| {
340 let span_start = affix[0].unwrap().0;
341 let span_end = affix.last().unwrap().unwrap().0;
342 let span = span_start.to(span_end);
343 let cnt = affix.len();
344 cx.tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, top, span, |lint| {
345 let s = pluralize!(cnt);
346 let mut diag = lint.build(&format!("{kind} irrefutable pattern{s} in let chain"));
348 "{these} pattern{s} will always match",
349 these = pluralize!("this", cnt),
352 "consider moving {} {suggestion}",
353 if cnt > 1 { "them" } else { "it" }
358 if let Some(until) = chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, false)))) && until > 0 {
359 // The chain has a non-zero prefix of irrefutable `let` statements.
361 // Check if the let source is while, for there is no alternative place to put a prefix,
362 // and we shouldn't lint.
363 let let_source = let_source_parent(self.tcx, top, None);
364 if !matches!(let_source, LetSource::WhileLet) {
366 let prefix = &chain_refutabilities[..until];
367 lint_affix(prefix, "leading", "outside of the construct");
370 if let Some(from) = chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, false)))) && from != (chain_refutabilities.len() - 1) {
371 // The chain has a non-empty suffix of irrefutable `let` statements
372 let suffix = &chain_refutabilities[from + 1..];
373 lint_affix(suffix, "trailing", "into the body");
378 fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
379 let mut cx = self.new_cx(pat.hir_id);
381 let pattern = self.lower_pattern(&mut cx, pat, &mut false);
382 let pattern_ty = pattern.ty();
383 let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
384 let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
386 // Note: we ignore whether the pattern is unreachable (i.e. whether the type is empty). We
387 // only care about exhaustiveness here.
388 let witnesses = report.non_exhaustiveness_witnesses;
389 if witnesses.is_empty() {
390 // The pattern is irrefutable.
391 self.check_patterns(pat, Irrefutable);
395 let joined_patterns = joined_uncovered_patterns(&cx, &witnesses);
397 let mut bindings = vec![];
399 let mut err = struct_span_err!(
403 "refutable pattern in {}: {} not covered",
407 let suggest_if_let = match &pat.kind {
408 hir::PatKind::Path(hir::QPath::Resolved(None, path))
409 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
411 const_not_var(&mut err, cx.tcx, pat, path);
415 pat.walk(&mut |pat: &hir::Pat<'_>| {
417 hir::PatKind::Binding(_, _, ident, _) => {
418 bindings.push(ident);
425 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
430 if let (Some(span), true) = (sp, suggest_if_let) {
432 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
433 an `enum` with only one variant",
435 if self.tcx.sess.source_map().span_to_snippet(span).is_ok() {
436 let semi_span = span.shrink_to_hi().with_lo(span.hi() - BytePos(1));
437 let start_span = span.shrink_to_lo();
438 let end_span = semi_span.shrink_to_lo();
439 err.multipart_suggestion(
441 "you might want to use `if let` to ignore the variant{} that {} matched",
442 pluralize!(witnesses.len()),
443 match witnesses.len() {
449 match &bindings[..] {
450 [] => (start_span, "if ".to_string()),
451 [binding] => (start_span, format!("let {} = if ", binding)),
458 .map(|ident| ident.to_string())
464 match &bindings[..] {
465 [] => (semi_span, " { todo!() }".to_string()),
467 (end_span, format!(" {{ {} }} else {{ todo!() }}", binding))
472 " {{ ({}) }} else {{ todo!() }}",
475 .map(|ident| ident.to_string())
482 Applicability::HasPlaceholders,
484 if !bindings.is_empty() && cx.tcx.sess.is_nightly_build() {
485 err.span_suggestion_verbose(
486 semi_span.shrink_to_lo(),
488 "alternatively, on nightly, you might want to use \
489 `#![feature(let_else)]` to handle the variant{} that {} matched",
490 pluralize!(witnesses.len()),
491 match witnesses.len() {
496 " else { todo!() }".to_string(),
497 Applicability::HasPlaceholders,
502 "for more information, visit \
503 https://doc.rust-lang.org/book/ch18-02-refutability.html",
507 adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
508 err.note(&format!("the matched value is of type `{}`", pattern_ty));
513 /// A path pattern was interpreted as a constant, not a new variable.
514 /// This caused an irrefutable match failure in e.g. `let`.
515 fn const_not_var(err: &mut Diagnostic, tcx: TyCtxt<'_>, pat: &Pat<'_>, path: &hir::Path<'_>) {
516 let descr = path.res.descr();
519 format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
524 "introduce a variable instead",
525 format!("{}_var", path.segments[0].ident).to_lowercase(),
526 // Cannot use `MachineApplicable` as it's not really *always* correct
527 // because there may be such an identifier in scope or the user maybe
528 // really wanted to match against the constant. This is quite unlikely however.
529 Applicability::MaybeIncorrect,
532 if let Some(span) = tcx.hir().res_span(path.res) {
533 err.span_label(span, format!("{} defined here", descr));
537 fn check_for_bindings_named_same_as_variants(
538 cx: &MatchVisitor<'_, '_, '_>,
542 pat.walk_always(|p| {
543 if let hir::PatKind::Binding(_, _, ident, None) = p.kind
544 && let Some(ty::BindByValue(hir::Mutability::Not)) =
545 cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
546 && let pat_ty = cx.typeck_results.pat_ty(p).peel_refs()
547 && let ty::Adt(edef, _) = pat_ty.kind()
549 && edef.variants().iter().any(|variant| {
550 variant.ident(cx.tcx) == ident && variant.ctor_kind == CtorKind::Const
553 let variant_count = edef.variants().len();
554 cx.tcx.struct_span_lint_hir(
555 BINDINGS_WITH_VARIANT_NAME,
559 let ty_path = cx.tcx.def_path_str(edef.did());
560 let mut err = lint.build(&format!(
561 "pattern binding `{}` is named the same as one \
562 of the variants of the type `{}`",
565 err.code(error_code!(E0170));
566 // If this is an irrefutable pattern, and there's > 1 variant,
567 // then we can't actually match on this. Applying the below
568 // suggestion would produce code that breaks on `check_irrefutable`.
569 if rf == Refutable || variant_count == 1 {
572 "to match on the variant, qualify the path",
573 format!("{}::{}", ty_path, ident),
574 Applicability::MachineApplicable,
584 /// Checks for common cases of "catchall" patterns that may not be intended as such.
585 fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
589 Single => pat.iter_fields().all(|pat| pat_is_catchall(pat)),
594 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
595 tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
596 let mut err = lint.build("unreachable pattern");
597 if let Some(catchall) = catchall {
598 // We had a catchall pattern, hint at that.
599 err.span_label(span, "unreachable pattern");
600 err.span_label(catchall, "matches any value");
606 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, id: HirId, span: Span) {
607 let source = let_source(tcx, id);
608 irrefutable_let_patterns(tcx, id, source, 1, span);
611 fn irrefutable_let_patterns(
618 macro_rules! emit_diag {
625 let s = pluralize!(count);
626 let these = pluralize!("this", count);
627 let mut diag = $lint.build(&format!("irrefutable {} pattern{s}", $source_name));
628 diag.note(&format!("{these} pattern{s} will always match, so the {}", $note_sufix));
629 diag.help(concat!("consider ", $help_sufix));
634 let span = match source {
635 LetSource::LetElse(span) => span,
638 tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| match source {
639 LetSource::GenericLet => {
640 emit_diag!(lint, "`let`", "`let` is useless", "removing `let`");
642 LetSource::IfLet => {
646 "`if let` is useless",
647 "replacing the `if let` with a `let`"
650 LetSource::IfLetGuard => {
655 "removing the guard and adding a `let` inside the match arm"
658 LetSource::LetElse(..) => {
662 "`else` clause is useless",
663 "removing the `else` clause"
666 LetSource::WhileLet => {
670 "loop will never exit",
671 "instead using a `loop { ... }` with a `let` inside it"
677 fn is_let_irrefutable<'p, 'tcx>(
678 cx: &mut MatchCheckCtxt<'p, 'tcx>,
680 pat: &'p DeconstructedPat<'p, 'tcx>,
682 let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
683 let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty());
685 // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
686 // This also reports unreachable sub-patterns though, so we can't just replace it with an
687 // `is_uninhabited` check.
688 report_arm_reachability(&cx, &report);
690 // If the list of witnesses is empty, the match is exhaustive,
691 // i.e. the `if let` pattern is irrefutable.
692 report.non_exhaustiveness_witnesses.is_empty()
695 /// Report unreachable arms, if any.
696 fn report_arm_reachability<'p, 'tcx>(
697 cx: &MatchCheckCtxt<'p, 'tcx>,
698 report: &UsefulnessReport<'p, 'tcx>,
701 let mut catchall = None;
702 for (arm, is_useful) in report.arm_usefulness.iter() {
704 Unreachable => unreachable_pattern(cx.tcx, arm.pat.span(), arm.hir_id, catchall),
705 Reachable(unreachables) if unreachables.is_empty() => {}
706 // The arm is reachable, but contains unreachable subpatterns (from or-patterns).
707 Reachable(unreachables) => {
708 let mut unreachables = unreachables.clone();
709 // Emit lints in the order in which they occur in the file.
710 unreachables.sort_unstable();
711 for span in unreachables {
712 unreachable_pattern(cx.tcx, span, arm.hir_id, None);
716 if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
717 catchall = Some(arm.pat.span());
722 /// Report that a match is not exhaustive.
723 fn non_exhaustive_match<'p, 'tcx>(
724 cx: &MatchCheckCtxt<'p, 'tcx>,
727 witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
728 arms: &[hir::Arm<'tcx>],
731 let is_empty_match = arms.is_empty();
732 let non_empty_enum = match scrut_ty.kind() {
733 ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
736 // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
740 let mut patterns_len = 0;
741 if is_empty_match && !non_empty_enum {
745 format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
747 pattern = "_".to_string();
749 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
753 format!("non-exhaustive patterns: {} not covered", joined_patterns),
755 err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
756 patterns_len = witnesses.len();
757 pattern = if witnesses.len() < 4 {
760 .map(|witness| witness.to_pat(cx).to_string())
761 .collect::<Vec<String>>()
768 let is_variant_list_non_exhaustive = match scrut_ty.kind() {
769 ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => true,
773 adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
775 "the matched value is of type `{}`{}",
777 if is_variant_list_non_exhaustive { ", which is marked as non-exhaustive" } else { "" }
779 if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
781 && witnesses.len() == 1
782 && matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
785 "`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \
789 if cx.tcx.sess.is_nightly_build() {
791 "add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
792 enable precise `{}` matching",
797 if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
798 if cx.tcx.is_ty_uninhabited_from(cx.module, *sub_ty, cx.param_env) {
799 err.note("references are always considered inhabited");
803 let mut suggestion = None;
804 let sm = cx.tcx.sess.source_map();
806 [] if sp.ctxt() == expr_span.ctxt() => {
807 // Get the span for the empty match body `{}`.
808 let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
809 (format!("\n{}", snippet), " ")
811 (" ".to_string(), "")
814 sp.shrink_to_hi().with_hi(expr_span.hi()),
816 " {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
817 indentation = indentation,
824 let pre_indentation = if let (Some(snippet), true) = (
825 sm.indentation_before(only.span),
826 sm.is_multiline(sp.shrink_to_hi().with_hi(only.span.lo())),
828 format!("\n{}", snippet)
832 let comma = if matches!(only.body.kind, hir::ExprKind::Block(..)) { "" } else { "," };
834 only.span.shrink_to_hi(),
835 format!("{}{}{} => todo!()", comma, pre_indentation, pattern),
838 [.., prev, last] if prev.span.ctxt() == last.span.ctxt() => {
839 if let Ok(snippet) = sm.span_to_snippet(prev.span.between(last.span)) {
841 if matches!(last.body.kind, hir::ExprKind::Block(..)) { "" } else { "," };
843 last.span.shrink_to_hi(),
847 snippet.strip_prefix(',').unwrap_or(&snippet),
857 "ensure that all possible cases are being handled by adding a match arm with a wildcard \
859 if patterns_len > 1 && patterns_len < 4 && suggestion.is_some() {
860 ", a match arm with multiple or-patterns"
862 // we are either not suggesting anything, or suggesting `_`
866 // non-exhaustive enum case
867 0 if suggestion.is_some() => " as shown",
869 1 if suggestion.is_some() => " or an explicit pattern as shown",
870 1 => " or an explicit pattern",
871 _ if suggestion.is_some() => " as shown, or multiple match arms",
872 _ => " or multiple match arms",
875 if let Some((span, sugg)) = suggestion {
876 err.span_suggestion_verbose(span, &msg, sugg, Applicability::HasPlaceholders);
883 crate fn joined_uncovered_patterns<'p, 'tcx>(
884 cx: &MatchCheckCtxt<'p, 'tcx>,
885 witnesses: &[DeconstructedPat<'p, 'tcx>],
887 const LIMIT: usize = 3;
888 let pat_to_str = |pat: &DeconstructedPat<'p, 'tcx>| pat.to_pat(cx).to_string();
891 [witness] => format!("`{}`", witness.to_pat(cx)),
892 [head @ .., tail] if head.len() < LIMIT => {
893 let head: Vec<_> = head.iter().map(pat_to_str).collect();
894 format!("`{}` and `{}`", head.join("`, `"), tail.to_pat(cx))
897 let (head, tail) = witnesses.split_at(LIMIT);
898 let head: Vec<_> = head.iter().map(pat_to_str).collect();
899 format!("`{}` and {} more", head.join("`, `"), tail.len())
904 crate fn pattern_not_covered_label(
905 witnesses: &[DeconstructedPat<'_, '_>],
906 joined_patterns: &str,
908 format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
911 /// Point at the definition of non-covered `enum` variants.
912 fn adt_defined_here<'p, 'tcx>(
913 cx: &MatchCheckCtxt<'p, 'tcx>,
914 err: &mut Diagnostic,
916 witnesses: &[DeconstructedPat<'p, 'tcx>],
918 let ty = ty.peel_refs();
919 if let ty::Adt(def, _) = ty.kind() {
920 let mut spans = vec![];
921 if witnesses.len() < 5 {
922 for sp in maybe_point_at_variant(cx, *def, witnesses.iter()) {
929 .get_if_local(def.did())
930 .and_then(|node| node.ident())
931 .map(|ident| ident.span)
932 .unwrap_or_else(|| cx.tcx.def_span(def.did()));
933 let mut span: MultiSpan =
934 if spans.is_empty() { def_span.into() } else { spans.clone().into() };
936 span.push_span_label(def_span, String::new());
938 span.push_span_label(pat, "not covered".to_string());
940 err.span_note(span, &format!("`{}` defined here", ty));
944 fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>(
945 cx: &MatchCheckCtxt<'p, 'tcx>,
947 patterns: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
950 let mut covered = vec![];
951 for pattern in patterns {
952 if let Variant(variant_index) = pattern.ctor() {
953 if let ty::Adt(this_def, _) = pattern.ty().kind() && this_def.did() != def.did() {
956 let sp = def.variant(*variant_index).ident(cx.tcx).span;
957 if covered.contains(&sp) {
958 // Don't point at variants that have already been covered due to other patterns to avoid
964 covered.extend(maybe_point_at_variant(cx, def, pattern.iter_fields()));
969 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
970 fn is_binding_by_move(cx: &MatchVisitor<'_, '_, '_>, hir_id: HirId, span: Span) -> bool {
971 !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
974 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
976 /// For example, this would reject:
977 /// - `ref x @ Some(ref mut y)`,
978 /// - `ref mut x @ Some(ref y)`,
979 /// - `ref mut x @ Some(ref mut y)`,
980 /// - `ref mut? x @ Some(y)`, and
981 /// - `x @ Some(ref mut? y)`.
983 /// This analysis is *not* subsumed by NLL.
984 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
985 // Extract `sub` in `binding @ sub`.
986 let (name, sub) = match &pat.kind {
987 hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
990 let binding_span = pat.span.with_hi(name.span.hi());
992 let typeck_results = cx.typeck_results;
993 let sess = cx.tcx.sess;
995 // Get the binding move, extract the mutability if by-ref.
996 let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) {
997 Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
998 // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
999 let mut conflicts_ref = Vec::new();
1000 sub.each_binding(|_, hir_id, span, _| {
1001 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1002 Some(ty::BindByValue(_)) | None => {}
1003 Some(ty::BindByReference(_)) => conflicts_ref.push(span),
1006 if !conflicts_ref.is_empty() {
1007 let occurs_because = format!(
1008 "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
1010 typeck_results.node_type(pat.hir_id),
1012 sess.struct_span_err(pat.span, "borrow of moved value")
1013 .span_label(binding_span, format!("value moved into `{}` here", name))
1014 .span_label(binding_span, occurs_because)
1015 .span_labels(conflicts_ref, "value borrowed here after move")
1020 Some(ty::BindByValue(_)) | None => return,
1021 Some(ty::BindByReference(m)) => m,
1024 // We now have `ref $mut_outer binding @ sub` (semantically).
1025 // Recurse into each binding in `sub` and find mutability or move conflicts.
1026 let mut conflicts_move = Vec::new();
1027 let mut conflicts_mut_mut = Vec::new();
1028 let mut conflicts_mut_ref = Vec::new();
1029 sub.each_binding(|_, hir_id, span, name| {
1030 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1031 Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
1032 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
1033 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
1034 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
1036 Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
1037 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
1039 Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
1043 // Report errors if any.
1044 if !conflicts_mut_mut.is_empty() {
1045 // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
1047 .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
1048 err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
1049 for (span, name) in conflicts_mut_mut {
1050 err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
1052 for (span, name) in conflicts_mut_ref {
1053 err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
1055 for (span, name) in conflicts_move {
1056 err.span_label(span, format!("also moved into `{}` here", name));
1059 } else if !conflicts_mut_ref.is_empty() {
1060 // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
1061 let (primary, also) = match mut_outer {
1062 Mutability::Mut => ("mutable", "immutable"),
1063 Mutability::Not => ("immutable", "mutable"),
1066 format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
1067 let mut err = sess.struct_span_err(pat.span, &msg);
1068 err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
1069 for (span, name) in conflicts_mut_ref {
1070 err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
1072 for (span, name) in conflicts_move {
1073 err.span_label(span, format!("also moved into `{}` here", name));
1076 } else if !conflicts_move.is_empty() {
1077 // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
1079 sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
1080 err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
1081 for (span, name) in conflicts_move {
1082 err.span_label(span, format!("value moved into `{}` here", name));
1088 #[derive(Clone, Copy, Debug)]
1089 pub enum LetSource {
1097 fn let_source(tcx: TyCtxt<'_>, pat_id: HirId) -> LetSource {
1098 let hir = tcx.hir();
1100 let parent = hir.get_parent_node(pat_id);
1101 let_source_parent(tcx, parent, Some(pat_id))
1104 fn let_source_parent(tcx: TyCtxt<'_>, parent: HirId, pat_id: Option<HirId>) -> LetSource {
1105 let hir = tcx.hir();
1107 let parent_node = hir.get(parent);
1110 hir::Node::Arm(hir::Arm {
1111 guard: Some(hir::Guard::IfLet(&hir::Pat { hir_id, .. }, _)),
1113 }) if Some(hir_id) == pat_id => {
1114 return LetSource::IfLetGuard;
1116 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Let(..), span, .. }) => {
1117 let expn_data = span.ctxt().outer_expn_data();
1118 if let ExpnKind::Desugaring(DesugaringKind::LetElse) = expn_data.kind {
1119 return LetSource::LetElse(expn_data.call_site);
1125 let parent_parent = hir.get_parent_node(parent);
1126 let parent_parent_node = hir.get(parent_parent);
1128 let parent_parent_parent = hir.get_parent_node(parent_parent);
1129 let parent_parent_parent_parent = hir.get_parent_node(parent_parent_parent);
1130 let parent_parent_parent_parent_node = hir.get(parent_parent_parent_parent);
1132 if let hir::Node::Expr(hir::Expr {
1133 kind: hir::ExprKind::Loop(_, _, hir::LoopSource::While, _),
1135 }) = parent_parent_parent_parent_node
1137 return LetSource::WhileLet;
1140 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::If(..), .. }) = parent_parent_node {
1141 return LetSource::IfLet;
1144 LetSource::GenericLet