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, DelayDm, 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, Span};
26 pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
27 let body_id = match def_id.as_local() {
29 Some(def_id) => tcx.hir().body_owned_by(def_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 if let Some(init) = loc.init && els.is_some() {
82 // Build a span without the else { ... } as we don't want to underline
83 // the entire else block in the IDE setting.
84 let span = loc.span.with_hi(init.span.hi());
85 self.check_let(&loc.pat, init, span);
88 let (msg, sp) = match loc.source {
89 hir::LocalSource::Normal => ("local binding", Some(loc.span)),
90 hir::LocalSource::AsyncFn => ("async fn binding", None),
91 hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
92 hir::LocalSource::AssignDesugar(_) => ("destructuring assignment binding", None),
95 self.check_irrefutable(&loc.pat, msg, sp);
99 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
100 intravisit::walk_param(self, param);
101 self.check_irrefutable(¶m.pat, "function argument", None);
105 impl PatCtxt<'_, '_> {
106 fn report_inlining_errors(&self) {
107 for error in &self.errors {
109 PatternError::StaticInPattern(span) => {
110 self.span_e0158(span, "statics cannot be referenced in patterns")
112 PatternError::AssocConstInPattern(span) => {
113 self.span_e0158(span, "associated consts cannot be referenced in patterns")
115 PatternError::ConstParamInPattern(span) => {
116 self.span_e0158(span, "const parameters cannot be referenced in patterns")
118 PatternError::NonConstPath(span) => {
119 rustc_middle::mir::interpret::struct_error(
121 "runtime values cannot be referenced in patterns",
129 fn span_e0158(&self, span: Span, text: &str) {
130 struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
134 impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
135 fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) {
136 pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
137 check_for_bindings_named_same_as_variants(self, pat, rf);
142 cx: &mut MatchCheckCtxt<'p, 'tcx>,
143 pat: &'tcx hir::Pat<'tcx>,
144 have_errors: &mut bool,
145 ) -> &'p DeconstructedPat<'p, 'tcx> {
146 let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
147 patcx.include_lint_checks();
148 let pattern = patcx.lower_pattern(pat);
149 let pattern: &_ = cx.pattern_arena.alloc(DeconstructedPat::from_pat(cx, &pattern));
150 if !patcx.errors.is_empty() {
152 patcx.report_inlining_errors();
157 fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'p, 'tcx> {
160 param_env: self.param_env,
161 module: self.tcx.parent_module(hir_id).to_def_id(),
162 pattern_arena: &self.pattern_arena,
166 fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, scrutinee: &hir::Expr<'_>, span: Span) {
167 self.check_patterns(pat, Refutable);
168 let mut cx = self.new_cx(scrutinee.hir_id);
169 let tpat = self.lower_pattern(&mut cx, pat, &mut false);
170 self.check_let_reachability(&mut cx, pat.hir_id, tpat, span);
175 scrut: &hir::Expr<'_>,
176 hir_arms: &'tcx [hir::Arm<'tcx>],
177 source: hir::MatchSource,
180 let mut cx = self.new_cx(scrut.hir_id);
182 for arm in hir_arms {
183 // Check the arm for some things unrelated to exhaustiveness.
184 self.check_patterns(&arm.pat, Refutable);
185 if let Some(hir::Guard::IfLet(ref let_expr)) = arm.guard {
186 self.check_patterns(let_expr.pat, Refutable);
187 let tpat = self.lower_pattern(&mut cx, let_expr.pat, &mut false);
188 self.check_let_reachability(&mut cx, let_expr.pat.hir_id, tpat, tpat.span());
192 let mut have_errors = false;
194 let arms: Vec<_> = hir_arms
196 .map(|hir::Arm { pat, guard, .. }| MatchArm {
197 pat: self.lower_pattern(&mut cx, pat, &mut have_errors),
199 has_guard: guard.is_some(),
203 // Bail out early if lowering failed.
208 let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
209 let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
212 // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
213 // when the iterator is an uninhabited type. unreachable_code will trigger instead.
214 hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
215 hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
216 report_arm_reachability(&cx, &report)
218 // Unreachable patterns in try and await expressions occur when one of
219 // the arms are an uninhabited type. Which is OK.
220 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
223 // Check if the match is exhaustive.
224 let witnesses = report.non_exhaustiveness_witnesses;
225 if !witnesses.is_empty() {
226 if source == hir::MatchSource::ForLoopDesugar && hir_arms.len() == 2 {
227 // the for loop pattern is not irrefutable
228 let pat = hir_arms[1].pat.for_loop_some().unwrap();
229 self.check_irrefutable(pat, "`for` loop binding", None);
231 non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, hir_arms, expr_span);
236 fn check_let_reachability(
238 cx: &mut MatchCheckCtxt<'p, 'tcx>,
240 pat: &'p DeconstructedPat<'p, 'tcx>,
243 if self.check_let_chain(cx, pat_id) {
247 if is_let_irrefutable(cx, pat_id, pat) {
248 irrefutable_let_pattern(cx.tcx, pat_id, span);
252 fn check_let_chain(&mut self, cx: &mut MatchCheckCtxt<'p, 'tcx>, pat_id: HirId) -> bool {
253 let hir = self.tcx.hir();
254 let parent = hir.get_parent_node(pat_id);
256 // First, figure out if the given pattern is part of a let chain,
257 // and if so, obtain the top node of the chain.
258 let mut top = parent;
259 let mut part_of_chain = false;
261 let new_top = hir.get_parent_node(top);
262 if let hir::Node::Expr(
264 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
270 // If this isn't the first iteration, we need to check
271 // if there is a let expr before us in the chain, so
272 // that we avoid doubly checking the let chain.
274 // The way a chain of &&s is encoded is ((let ... && let ...) && let ...) && let ...
275 // as && is left-to-right associative. Thus, we need to check rhs.
276 if part_of_chain && matches!(rhs.kind, hir::ExprKind::Let(..)) {
279 // If there is a let at the lhs, and we provide the rhs, we don't do any checking either.
280 if !part_of_chain && matches!(lhs.kind, hir::ExprKind::Let(..)) && rhs.hir_id == top
285 // We've reached the top.
289 // Since this function is called within a let context, it is reasonable to assume that any parent
290 // `&&` infers a let chain
291 part_of_chain = true;
298 // Second, obtain the refutabilities of all exprs in the chain,
299 // and record chain members that aren't let exprs.
300 let mut chain_refutabilities = Vec::new();
301 let hir::Node::Expr(top_expr) = hir.get(top) else {
302 // We ensure right above that it's an Expr
305 let mut cur_expr = top_expr;
307 let mut add = |expr: &hir::Expr<'tcx>| {
308 let refutability = match expr.kind {
309 hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
310 let mut ncx = self.new_cx(init.hir_id);
311 let tpat = self.lower_pattern(&mut ncx, pat, &mut false);
313 let refutable = !is_let_irrefutable(&mut ncx, pat.hir_id, tpat);
314 Some((*span, refutable))
318 chain_refutabilities.push(refutability);
321 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
332 chain_refutabilities.reverse();
334 // Third, emit the actual warnings.
336 if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, false)))) {
337 // The entire chain is made up of irrefutable `let` statements
338 let let_source = let_source_parent(self.tcx, top, None);
339 irrefutable_let_patterns(
343 chain_refutabilities.len(),
348 let lint_affix = |affix: &[Option<(Span, bool)>], kind, suggestion| {
349 let span_start = affix[0].unwrap().0;
350 let span_end = affix.last().unwrap().unwrap().0;
351 let span = span_start.to(span_end);
352 let cnt = affix.len();
353 let s = pluralize!(cnt);
354 cx.tcx.struct_span_lint_hir(
355 IRREFUTABLE_LET_PATTERNS,
358 format!("{kind} irrefutable pattern{s} in let chain"),
361 "{these} pattern{s} will always match",
362 these = pluralize!("this", cnt),
365 "consider moving {} {suggestion}",
366 if cnt > 1 { "them" } else { "it" }
371 if let Some(until) = chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, false)))) && until > 0 {
372 // The chain has a non-zero prefix of irrefutable `let` statements.
374 // Check if the let source is while, for there is no alternative place to put a prefix,
375 // and we shouldn't lint.
376 // For let guards inside a match, prefixes might use bindings of the match pattern,
377 // so can't always be moved out.
378 // FIXME: Add checking whether the bindings are actually used in the prefix,
379 // and lint if they are not.
380 let let_source = let_source_parent(self.tcx, top, None);
381 if !matches!(let_source, LetSource::WhileLet | LetSource::IfLetGuard) {
383 let prefix = &chain_refutabilities[..until];
384 lint_affix(prefix, "leading", "outside of the construct");
387 if let Some(from) = chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, false)))) && from != (chain_refutabilities.len() - 1) {
388 // The chain has a non-empty suffix of irrefutable `let` statements
389 let suffix = &chain_refutabilities[from + 1..];
390 lint_affix(suffix, "trailing", "into the body");
395 fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
396 let mut cx = self.new_cx(pat.hir_id);
398 let pattern = self.lower_pattern(&mut cx, pat, &mut false);
399 let pattern_ty = pattern.ty();
400 let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
401 let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
403 // Note: we ignore whether the pattern is unreachable (i.e. whether the type is empty). We
404 // only care about exhaustiveness here.
405 let witnesses = report.non_exhaustiveness_witnesses;
406 if witnesses.is_empty() {
407 // The pattern is irrefutable.
408 self.check_patterns(pat, Irrefutable);
412 let joined_patterns = joined_uncovered_patterns(&cx, &witnesses);
414 let mut bindings = vec![];
416 let mut err = struct_span_err!(
420 "refutable pattern in {}: {} not covered",
424 let suggest_if_let = match &pat.kind {
425 hir::PatKind::Path(hir::QPath::Resolved(None, path))
426 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
428 const_not_var(&mut err, cx.tcx, pat, path);
432 pat.walk(&mut |pat: &hir::Pat<'_>| {
434 hir::PatKind::Binding(_, _, ident, _) => {
435 bindings.push(ident);
442 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
447 if let (Some(span), true) = (sp, suggest_if_let) {
449 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
450 an `enum` with only one variant",
452 if self.tcx.sess.source_map().is_span_accessible(span) {
453 let semi_span = span.shrink_to_hi().with_lo(span.hi() - BytePos(1));
454 let start_span = span.shrink_to_lo();
455 let end_span = semi_span.shrink_to_lo();
456 err.multipart_suggestion(
458 "you might want to use `if let` to ignore the variant{} that {} matched",
459 pluralize!(witnesses.len()),
460 match witnesses.len() {
466 match &bindings[..] {
467 [] => (start_span, "if ".to_string()),
468 [binding] => (start_span, format!("let {} = if ", binding)),
475 .map(|ident| ident.to_string())
481 match &bindings[..] {
482 [] => (semi_span, " { todo!() }".to_string()),
484 (end_span, format!(" {{ {} }} else {{ todo!() }}", binding))
489 " {{ ({}) }} else {{ todo!() }}",
492 .map(|ident| ident.to_string())
499 Applicability::HasPlaceholders,
501 if !bindings.is_empty() {
502 err.span_suggestion_verbose(
503 semi_span.shrink_to_lo(),
505 "alternatively, you might want to use \
506 let else to handle the variant{} that {} matched",
507 pluralize!(witnesses.len()),
508 match witnesses.len() {
514 Applicability::HasPlaceholders,
519 "for more information, visit \
520 https://doc.rust-lang.org/book/ch18-02-refutability.html",
524 adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
525 err.note(&format!("the matched value is of type `{}`", pattern_ty));
530 /// A path pattern was interpreted as a constant, not a new variable.
531 /// This caused an irrefutable match failure in e.g. `let`.
532 fn const_not_var(err: &mut Diagnostic, tcx: TyCtxt<'_>, pat: &Pat<'_>, path: &hir::Path<'_>) {
533 let descr = path.res.descr();
536 format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
541 "introduce a variable instead",
542 format!("{}_var", path.segments[0].ident).to_lowercase(),
543 // Cannot use `MachineApplicable` as it's not really *always* correct
544 // because there may be such an identifier in scope or the user maybe
545 // really wanted to match against the constant. This is quite unlikely however.
546 Applicability::MaybeIncorrect,
549 if let Some(span) = tcx.hir().res_span(path.res) {
550 err.span_label(span, format!("{} defined here", descr));
554 fn check_for_bindings_named_same_as_variants(
555 cx: &MatchVisitor<'_, '_, '_>,
559 pat.walk_always(|p| {
560 if let hir::PatKind::Binding(_, _, ident, None) = p.kind
561 && let Some(ty::BindByValue(hir::Mutability::Not)) =
562 cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
563 && let pat_ty = cx.typeck_results.pat_ty(p).peel_refs()
564 && let ty::Adt(edef, _) = pat_ty.kind()
566 && edef.variants().iter().any(|variant| {
567 variant.ident(cx.tcx) == ident && variant.ctor_kind == CtorKind::Const
570 let variant_count = edef.variants().len();
571 cx.tcx.struct_span_lint_hir(
572 BINDINGS_WITH_VARIANT_NAME,
576 "pattern binding `{}` is named the same as one \
577 of the variants of the type `{}`",
578 ident, cx.tcx.def_path_str(edef.did())
581 let ty_path = cx.tcx.def_path_str(edef.did());
582 lint.code(error_code!(E0170));
584 // If this is an irrefutable pattern, and there's > 1 variant,
585 // then we can't actually match on this. Applying the below
586 // suggestion would produce code that breaks on `check_irrefutable`.
587 if rf == Refutable || variant_count == 1 {
588 lint.span_suggestion(
590 "to match on the variant, qualify the path",
591 format!("{}::{}", ty_path, ident),
592 Applicability::MachineApplicable,
603 /// Checks for common cases of "catchall" patterns that may not be intended as such.
604 fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
608 Single => pat.iter_fields().all(|pat| pat_is_catchall(pat)),
613 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
614 tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, "unreachable pattern", |lint| {
615 if let Some(catchall) = catchall {
616 // We had a catchall pattern, hint at that.
617 lint.span_label(span, "unreachable pattern");
618 lint.span_label(catchall, "matches any value");
624 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, id: HirId, span: Span) {
625 let source = let_source(tcx, id);
626 irrefutable_let_patterns(tcx, id, source, 1, span);
629 fn irrefutable_let_patterns(
636 macro_rules! emit_diag {
643 let s = pluralize!(count);
644 let these = pluralize!("this", count);
645 tcx.struct_span_lint_hir(
646 IRREFUTABLE_LET_PATTERNS,
649 format!("irrefutable {} pattern{s}", $source_name),
652 "{these} pattern{s} will always match, so the {}",
655 .help(concat!("consider ", $help_sufix))
662 LetSource::GenericLet => {
663 emit_diag!(lint, "`let`", "`let` is useless", "removing `let`");
665 LetSource::IfLet => {
669 "`if let` is useless",
670 "replacing the `if let` with a `let`"
673 LetSource::IfLetGuard => {
678 "removing the guard and adding a `let` inside the match arm"
681 LetSource::LetElse => {
685 "`else` clause is useless",
686 "removing the `else` clause"
689 LetSource::WhileLet => {
693 "loop will never exit",
694 "instead using a `loop { ... }` with a `let` inside it"
700 fn is_let_irrefutable<'p, 'tcx>(
701 cx: &mut MatchCheckCtxt<'p, 'tcx>,
703 pat: &'p DeconstructedPat<'p, 'tcx>,
705 let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
706 let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty());
708 // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
709 // This also reports unreachable sub-patterns though, so we can't just replace it with an
710 // `is_uninhabited` check.
711 report_arm_reachability(&cx, &report);
713 // If the list of witnesses is empty, the match is exhaustive,
714 // i.e. the `if let` pattern is irrefutable.
715 report.non_exhaustiveness_witnesses.is_empty()
718 /// Report unreachable arms, if any.
719 fn report_arm_reachability<'p, 'tcx>(
720 cx: &MatchCheckCtxt<'p, 'tcx>,
721 report: &UsefulnessReport<'p, 'tcx>,
724 let mut catchall = None;
725 for (arm, is_useful) in report.arm_usefulness.iter() {
727 Unreachable => unreachable_pattern(cx.tcx, arm.pat.span(), arm.hir_id, catchall),
728 Reachable(unreachables) if unreachables.is_empty() => {}
729 // The arm is reachable, but contains unreachable subpatterns (from or-patterns).
730 Reachable(unreachables) => {
731 let mut unreachables = unreachables.clone();
732 // Emit lints in the order in which they occur in the file.
733 unreachables.sort_unstable();
734 for span in unreachables {
735 unreachable_pattern(cx.tcx, span, arm.hir_id, None);
739 if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
740 catchall = Some(arm.pat.span());
745 /// Report that a match is not exhaustive.
746 fn non_exhaustive_match<'p, 'tcx>(
747 cx: &MatchCheckCtxt<'p, 'tcx>,
750 witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
751 arms: &[hir::Arm<'tcx>],
754 let is_empty_match = arms.is_empty();
755 let non_empty_enum = match scrut_ty.kind() {
756 ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
759 // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
763 let mut patterns_len = 0;
764 if is_empty_match && !non_empty_enum {
768 format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
770 pattern = "_".to_string();
772 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
776 format!("non-exhaustive patterns: {} not covered", joined_patterns),
778 err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
779 patterns_len = witnesses.len();
780 pattern = if witnesses.len() < 4 {
783 .map(|witness| witness.to_pat(cx).to_string())
784 .collect::<Vec<String>>()
791 let is_variant_list_non_exhaustive = match scrut_ty.kind() {
792 ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => true,
796 adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
798 "the matched value is of type `{}`{}",
800 if is_variant_list_non_exhaustive { ", which is marked as non-exhaustive" } else { "" }
802 if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
804 && witnesses.len() == 1
805 && matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
808 "`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \
812 if cx.tcx.sess.is_nightly_build() {
814 "add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
815 enable precise `{}` matching",
820 if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
821 if cx.tcx.is_ty_uninhabited_from(cx.module, *sub_ty, cx.param_env) {
822 err.note("references are always considered inhabited");
826 let mut suggestion = None;
827 let sm = cx.tcx.sess.source_map();
829 [] if sp.eq_ctxt(expr_span) => {
830 // Get the span for the empty match body `{}`.
831 let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
832 (format!("\n{}", snippet), " ")
834 (" ".to_string(), "")
837 sp.shrink_to_hi().with_hi(expr_span.hi()),
839 " {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
840 indentation = indentation,
847 let (pre_indentation, is_multiline) = if let Some(snippet) = sm.indentation_before(only.span)
848 && let Ok(with_trailing) = sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
849 && sm.is_multiline(with_trailing)
851 (format!("\n{}", snippet), true)
853 (" ".to_string(), false)
855 let comma = if matches!(only.body.kind, hir::ExprKind::Block(..))
856 && only.span.eq_ctxt(only.body.span)
864 only.span.shrink_to_hi(),
865 format!("{}{}{} => todo!()", comma, pre_indentation, pattern),
868 [.., prev, last] if prev.span.eq_ctxt(last.span) => {
869 let comma = if matches!(last.body.kind, hir::ExprKind::Block(..))
870 && last.span.eq_ctxt(last.body.span)
876 let spacing = if sm.is_multiline(prev.span.between(last.span)) {
877 sm.indentation_before(last.span).map(|indent| format!("\n{indent}"))
879 Some(" ".to_string())
881 if let Some(spacing) = spacing {
883 last.span.shrink_to_hi(),
884 format!("{}{}{} => todo!()", comma, spacing, pattern),
892 "ensure that all possible cases are being handled by adding a match arm with a wildcard \
894 if patterns_len > 1 && patterns_len < 4 && suggestion.is_some() {
895 ", a match arm with multiple or-patterns"
897 // we are either not suggesting anything, or suggesting `_`
901 // non-exhaustive enum case
902 0 if suggestion.is_some() => " as shown",
904 1 if suggestion.is_some() => " or an explicit pattern as shown",
905 1 => " or an explicit pattern",
906 _ if suggestion.is_some() => " as shown, or multiple match arms",
907 _ => " or multiple match arms",
910 if let Some((span, sugg)) = suggestion {
911 err.span_suggestion_verbose(span, &msg, sugg, Applicability::HasPlaceholders);
918 pub(crate) fn joined_uncovered_patterns<'p, 'tcx>(
919 cx: &MatchCheckCtxt<'p, 'tcx>,
920 witnesses: &[DeconstructedPat<'p, 'tcx>],
922 const LIMIT: usize = 3;
923 let pat_to_str = |pat: &DeconstructedPat<'p, 'tcx>| pat.to_pat(cx).to_string();
926 [witness] => format!("`{}`", witness.to_pat(cx)),
927 [head @ .., tail] if head.len() < LIMIT => {
928 let head: Vec<_> = head.iter().map(pat_to_str).collect();
929 format!("`{}` and `{}`", head.join("`, `"), tail.to_pat(cx))
932 let (head, tail) = witnesses.split_at(LIMIT);
933 let head: Vec<_> = head.iter().map(pat_to_str).collect();
934 format!("`{}` and {} more", head.join("`, `"), tail.len())
939 pub(crate) fn pattern_not_covered_label(
940 witnesses: &[DeconstructedPat<'_, '_>],
941 joined_patterns: &str,
943 format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
946 /// Point at the definition of non-covered `enum` variants.
947 fn adt_defined_here<'p, 'tcx>(
948 cx: &MatchCheckCtxt<'p, 'tcx>,
949 err: &mut Diagnostic,
951 witnesses: &[DeconstructedPat<'p, 'tcx>],
953 let ty = ty.peel_refs();
954 if let ty::Adt(def, _) = ty.kind() {
955 let mut spans = vec![];
956 if witnesses.len() < 5 {
957 for sp in maybe_point_at_variant(cx, *def, witnesses.iter()) {
964 .get_if_local(def.did())
965 .and_then(|node| node.ident())
966 .map(|ident| ident.span)
967 .unwrap_or_else(|| cx.tcx.def_span(def.did()));
968 let mut span: MultiSpan =
969 if spans.is_empty() { def_span.into() } else { spans.clone().into() };
971 span.push_span_label(def_span, "");
973 span.push_span_label(pat, "not covered");
975 err.span_note(span, &format!("`{}` defined here", ty));
979 fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>(
980 cx: &MatchCheckCtxt<'p, 'tcx>,
982 patterns: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
985 let mut covered = vec![];
986 for pattern in patterns {
987 if let Variant(variant_index) = pattern.ctor() {
988 if let ty::Adt(this_def, _) = pattern.ty().kind() && this_def.did() != def.did() {
991 let sp = def.variant(*variant_index).ident(cx.tcx).span;
992 if covered.contains(&sp) {
993 // Don't point at variants that have already been covered due to other patterns to avoid
999 covered.extend(maybe_point_at_variant(cx, def, pattern.iter_fields()));
1004 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
1005 fn is_binding_by_move(cx: &MatchVisitor<'_, '_, '_>, hir_id: HirId) -> bool {
1006 !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx, cx.param_env)
1009 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
1011 /// For example, this would reject:
1012 /// - `ref x @ Some(ref mut y)`,
1013 /// - `ref mut x @ Some(ref y)`,
1014 /// - `ref mut x @ Some(ref mut y)`,
1015 /// - `ref mut? x @ Some(y)`, and
1016 /// - `x @ Some(ref mut? y)`.
1018 /// This analysis is *not* subsumed by NLL.
1019 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
1020 // Extract `sub` in `binding @ sub`.
1021 let (name, sub) = match &pat.kind {
1022 hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
1025 let binding_span = pat.span.with_hi(name.span.hi());
1027 let typeck_results = cx.typeck_results;
1028 let sess = cx.tcx.sess;
1030 // Get the binding move, extract the mutability if by-ref.
1031 let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) {
1032 Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id) => {
1033 // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
1034 let mut conflicts_ref = Vec::new();
1035 sub.each_binding(|_, hir_id, span, _| {
1036 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1037 Some(ty::BindByValue(_)) | None => {}
1038 Some(ty::BindByReference(_)) => conflicts_ref.push(span),
1041 if !conflicts_ref.is_empty() {
1042 let occurs_because = format!(
1043 "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
1045 typeck_results.node_type(pat.hir_id),
1047 sess.struct_span_err(pat.span, "borrow of moved value")
1048 .span_label(binding_span, format!("value moved into `{}` here", name))
1049 .span_label(binding_span, occurs_because)
1050 .span_labels(conflicts_ref, "value borrowed here after move")
1055 Some(ty::BindByValue(_)) | None => return,
1056 Some(ty::BindByReference(m)) => m,
1059 // We now have `ref $mut_outer binding @ sub` (semantically).
1060 // Recurse into each binding in `sub` and find mutability or move conflicts.
1061 let mut conflicts_move = Vec::new();
1062 let mut conflicts_mut_mut = Vec::new();
1063 let mut conflicts_mut_ref = Vec::new();
1064 sub.each_binding(|_, hir_id, span, name| {
1065 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1066 Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
1067 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
1068 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
1069 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
1071 Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id) => {
1072 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
1074 Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
1078 // Report errors if any.
1079 if !conflicts_mut_mut.is_empty() {
1080 // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
1082 .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
1083 err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
1084 for (span, name) in conflicts_mut_mut {
1085 err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
1087 for (span, name) in conflicts_mut_ref {
1088 err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
1090 for (span, name) in conflicts_move {
1091 err.span_label(span, format!("also moved into `{}` here", name));
1094 } else if !conflicts_mut_ref.is_empty() {
1095 // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
1096 let (primary, also) = match mut_outer {
1097 Mutability::Mut => ("mutable", "immutable"),
1098 Mutability::Not => ("immutable", "mutable"),
1101 format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
1102 let mut err = sess.struct_span_err(pat.span, &msg);
1103 err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
1104 for (span, name) in conflicts_mut_ref {
1105 err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
1107 for (span, name) in conflicts_move {
1108 err.span_label(span, format!("also moved into `{}` here", name));
1111 } else if !conflicts_move.is_empty() {
1112 // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
1114 sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
1115 err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
1116 for (span, name) in conflicts_move {
1117 err.span_label(span, format!("value moved into `{}` here", name));
1123 #[derive(Clone, Copy, Debug)]
1124 pub enum LetSource {
1132 fn let_source(tcx: TyCtxt<'_>, pat_id: HirId) -> LetSource {
1133 let hir = tcx.hir();
1135 let parent = hir.get_parent_node(pat_id);
1136 let_source_parent(tcx, parent, Some(pat_id))
1139 fn let_source_parent(tcx: TyCtxt<'_>, parent: HirId, pat_id: Option<HirId>) -> LetSource {
1140 let hir = tcx.hir();
1142 let parent_node = hir.get(parent);
1145 hir::Node::Arm(hir::Arm {
1146 guard: Some(hir::Guard::IfLet(&hir::Let { pat: hir::Pat { hir_id, .. }, .. })),
1148 }) if Some(*hir_id) == pat_id => {
1149 return LetSource::IfLetGuard;
1154 let parent_parent = hir.get_parent_node(parent);
1155 let parent_parent_node = hir.get(parent_parent);
1156 match parent_parent_node {
1157 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(_), .. }) => {
1158 return LetSource::LetElse;
1160 hir::Node::Arm(hir::Arm { guard: Some(hir::Guard::If(_)), .. }) => {
1161 return LetSource::IfLetGuard;
1166 let parent_parent_parent = hir.get_parent_node(parent_parent);
1167 let parent_parent_parent_parent = hir.get_parent_node(parent_parent_parent);
1168 let parent_parent_parent_parent_node = hir.get(parent_parent_parent_parent);
1170 if let hir::Node::Expr(hir::Expr {
1171 kind: hir::ExprKind::Loop(_, _, hir::LoopSource::While, _),
1173 }) = parent_parent_parent_parent_node
1175 return LetSource::WhileLet;
1178 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::If(..), .. }) = parent_parent_node {
1179 return LetSource::IfLet;
1182 LetSource::GenericLet