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, 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 self.check_let(&loc.pat, init, loc.span);
85 let (msg, sp) = match loc.source {
86 hir::LocalSource::Normal => ("local binding", Some(loc.span)),
87 hir::LocalSource::AsyncFn => ("async fn binding", None),
88 hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
89 hir::LocalSource::AssignDesugar(_) => ("destructuring assignment binding", None),
92 self.check_irrefutable(&loc.pat, msg, sp);
96 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
97 intravisit::walk_param(self, param);
98 self.check_irrefutable(¶m.pat, "function argument", None);
102 impl PatCtxt<'_, '_> {
103 fn report_inlining_errors(&self) {
104 for error in &self.errors {
106 PatternError::StaticInPattern(span) => {
107 self.span_e0158(span, "statics cannot be referenced in patterns")
109 PatternError::AssocConstInPattern(span) => {
110 self.span_e0158(span, "associated consts cannot be referenced in patterns")
112 PatternError::ConstParamInPattern(span) => {
113 self.span_e0158(span, "const parameters cannot be referenced in patterns")
115 PatternError::NonConstPath(span) => {
116 rustc_middle::mir::interpret::struct_error(
118 "runtime values cannot be referenced in patterns",
126 fn span_e0158(&self, span: Span, text: &str) {
127 struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
131 impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
132 fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) {
133 pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
134 check_for_bindings_named_same_as_variants(self, pat, rf);
139 cx: &mut MatchCheckCtxt<'p, 'tcx>,
140 pat: &'tcx hir::Pat<'tcx>,
141 have_errors: &mut bool,
142 ) -> &'p DeconstructedPat<'p, 'tcx> {
143 let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
144 patcx.include_lint_checks();
145 let pattern = patcx.lower_pattern(pat);
146 let pattern: &_ = cx.pattern_arena.alloc(DeconstructedPat::from_pat(cx, &pattern));
147 if !patcx.errors.is_empty() {
149 patcx.report_inlining_errors();
154 fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'p, 'tcx> {
157 param_env: self.param_env,
158 module: self.tcx.parent_module(hir_id).to_def_id(),
159 pattern_arena: &self.pattern_arena,
163 fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, scrutinee: &hir::Expr<'_>, span: Span) {
164 self.check_patterns(pat, Refutable);
165 let mut cx = self.new_cx(scrutinee.hir_id);
166 let tpat = self.lower_pattern(&mut cx, pat, &mut false);
167 self.check_let_reachability(&mut cx, pat.hir_id, tpat, span);
172 scrut: &hir::Expr<'_>,
173 hir_arms: &'tcx [hir::Arm<'tcx>],
174 source: hir::MatchSource,
177 let mut cx = self.new_cx(scrut.hir_id);
179 for arm in hir_arms {
180 // Check the arm for some things unrelated to exhaustiveness.
181 self.check_patterns(&arm.pat, Refutable);
182 if let Some(hir::Guard::IfLet(ref let_expr)) = arm.guard {
183 self.check_patterns(let_expr.pat, Refutable);
184 let tpat = self.lower_pattern(&mut cx, let_expr.pat, &mut false);
185 self.check_let_reachability(&mut cx, let_expr.pat.hir_id, tpat, tpat.span());
189 let mut have_errors = false;
191 let arms: Vec<_> = hir_arms
193 .map(|hir::Arm { pat, guard, .. }| MatchArm {
194 pat: self.lower_pattern(&mut cx, pat, &mut have_errors),
196 has_guard: guard.is_some(),
200 // Bail out early if lowering failed.
205 let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
206 let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
209 // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
210 // when the iterator is an uninhabited type. unreachable_code will trigger instead.
211 hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
212 hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
213 report_arm_reachability(&cx, &report)
215 // Unreachable patterns in try and await expressions occur when one of
216 // the arms are an uninhabited type. Which is OK.
217 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
220 // Check if the match is exhaustive.
221 let witnesses = report.non_exhaustiveness_witnesses;
222 if !witnesses.is_empty() {
223 if source == hir::MatchSource::ForLoopDesugar && hir_arms.len() == 2 {
224 // the for loop pattern is not irrefutable
225 let pat = hir_arms[1].pat.for_loop_some().unwrap();
226 self.check_irrefutable(pat, "`for` loop binding", None);
228 non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, hir_arms, expr_span);
233 fn check_let_reachability(
235 cx: &mut MatchCheckCtxt<'p, 'tcx>,
237 pat: &'p DeconstructedPat<'p, 'tcx>,
240 if self.check_let_chain(cx, pat_id) {
244 if is_let_irrefutable(cx, pat_id, pat) {
245 irrefutable_let_pattern(cx.tcx, pat_id, span);
249 fn check_let_chain(&mut self, cx: &mut MatchCheckCtxt<'p, 'tcx>, pat_id: HirId) -> bool {
250 let hir = self.tcx.hir();
251 let parent = hir.get_parent_node(pat_id);
253 // First, figure out if the given pattern is part of a let chain,
254 // and if so, obtain the top node of the chain.
255 let mut top = parent;
256 let mut part_of_chain = false;
258 let new_top = hir.get_parent_node(top);
259 if let hir::Node::Expr(
261 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
267 // If this isn't the first iteration, we need to check
268 // if there is a let expr before us in the chain, so
269 // that we avoid doubly checking the let chain.
271 // The way a chain of &&s is encoded is ((let ... && let ...) && let ...) && let ...
272 // as && is left-to-right associative. Thus, we need to check rhs.
273 if part_of_chain && matches!(rhs.kind, hir::ExprKind::Let(..)) {
276 // If there is a let at the lhs, and we provide the rhs, we don't do any checking either.
277 if !part_of_chain && matches!(lhs.kind, hir::ExprKind::Let(..)) && rhs.hir_id == top
282 // We've reached the top.
286 // Since this function is called within a let context, it is reasonable to assume that any parent
287 // `&&` infers a let chain
288 part_of_chain = true;
295 // Second, obtain the refutabilities of all exprs in the chain,
296 // and record chain members that aren't let exprs.
297 let mut chain_refutabilities = Vec::new();
298 let hir::Node::Expr(top_expr) = hir.get(top) else {
299 // We ensure right above that it's an Expr
302 let mut cur_expr = top_expr;
304 let mut add = |expr: &hir::Expr<'tcx>| {
305 let refutability = match expr.kind {
306 hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
307 let mut ncx = self.new_cx(init.hir_id);
308 let tpat = self.lower_pattern(&mut ncx, pat, &mut false);
310 let refutable = !is_let_irrefutable(&mut ncx, pat.hir_id, tpat);
311 Some((*span, refutable))
315 chain_refutabilities.push(refutability);
318 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
329 chain_refutabilities.reverse();
331 // Third, emit the actual warnings.
333 if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, false)))) {
334 // The entire chain is made up of irrefutable `let` statements
335 let let_source = let_source_parent(self.tcx, top, None);
336 irrefutable_let_patterns(
340 chain_refutabilities.len(),
345 let lint_affix = |affix: &[Option<(Span, bool)>], kind, suggestion| {
346 let span_start = affix[0].unwrap().0;
347 let span_end = affix.last().unwrap().unwrap().0;
348 let span = span_start.to(span_end);
349 let cnt = affix.len();
350 cx.tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, top, span, |lint| {
351 let s = pluralize!(cnt);
352 let mut diag = lint.build(&format!("{kind} irrefutable pattern{s} in let chain"));
354 "{these} pattern{s} will always match",
355 these = pluralize!("this", cnt),
358 "consider moving {} {suggestion}",
359 if cnt > 1 { "them" } else { "it" }
364 if let Some(until) = chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, false)))) && until > 0 {
365 // The chain has a non-zero prefix of irrefutable `let` statements.
367 // Check if the let source is while, for there is no alternative place to put a prefix,
368 // and we shouldn't lint.
369 let let_source = let_source_parent(self.tcx, top, None);
370 if !matches!(let_source, LetSource::WhileLet) {
372 let prefix = &chain_refutabilities[..until];
373 lint_affix(prefix, "leading", "outside of the construct");
376 if let Some(from) = chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, false)))) && from != (chain_refutabilities.len() - 1) {
377 // The chain has a non-empty suffix of irrefutable `let` statements
378 let suffix = &chain_refutabilities[from + 1..];
379 lint_affix(suffix, "trailing", "into the body");
384 fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
385 let mut cx = self.new_cx(pat.hir_id);
387 let pattern = self.lower_pattern(&mut cx, pat, &mut false);
388 let pattern_ty = pattern.ty();
389 let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
390 let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
392 // Note: we ignore whether the pattern is unreachable (i.e. whether the type is empty). We
393 // only care about exhaustiveness here.
394 let witnesses = report.non_exhaustiveness_witnesses;
395 if witnesses.is_empty() {
396 // The pattern is irrefutable.
397 self.check_patterns(pat, Irrefutable);
401 let joined_patterns = joined_uncovered_patterns(&cx, &witnesses);
403 let mut bindings = vec![];
405 let mut err = struct_span_err!(
409 "refutable pattern in {}: {} not covered",
413 let suggest_if_let = match &pat.kind {
414 hir::PatKind::Path(hir::QPath::Resolved(None, path))
415 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
417 const_not_var(&mut err, cx.tcx, pat, path);
421 pat.walk(&mut |pat: &hir::Pat<'_>| {
423 hir::PatKind::Binding(_, _, ident, _) => {
424 bindings.push(ident);
431 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
436 if let (Some(span), true) = (sp, suggest_if_let) {
438 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
439 an `enum` with only one variant",
441 if self.tcx.sess.source_map().is_span_accessible(span) {
442 let semi_span = span.shrink_to_hi().with_lo(span.hi() - BytePos(1));
443 let start_span = span.shrink_to_lo();
444 let end_span = semi_span.shrink_to_lo();
445 err.multipart_suggestion(
447 "you might want to use `if let` to ignore the variant{} that {} matched",
448 pluralize!(witnesses.len()),
449 match witnesses.len() {
455 match &bindings[..] {
456 [] => (start_span, "if ".to_string()),
457 [binding] => (start_span, format!("let {} = if ", binding)),
464 .map(|ident| ident.to_string())
470 match &bindings[..] {
471 [] => (semi_span, " { todo!() }".to_string()),
473 (end_span, format!(" {{ {} }} else {{ todo!() }}", binding))
478 " {{ ({}) }} else {{ todo!() }}",
481 .map(|ident| ident.to_string())
488 Applicability::HasPlaceholders,
490 if !bindings.is_empty() && cx.tcx.sess.is_nightly_build() {
491 err.span_suggestion_verbose(
492 semi_span.shrink_to_lo(),
494 "alternatively, you might want to use \
495 let else to handle the variant{} that {} matched",
496 pluralize!(witnesses.len()),
497 match witnesses.len() {
502 " else { todo!() }".to_string(),
503 Applicability::HasPlaceholders,
508 "for more information, visit \
509 https://doc.rust-lang.org/book/ch18-02-refutability.html",
513 adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
514 err.note(&format!("the matched value is of type `{}`", pattern_ty));
519 /// A path pattern was interpreted as a constant, not a new variable.
520 /// This caused an irrefutable match failure in e.g. `let`.
521 fn const_not_var(err: &mut Diagnostic, tcx: TyCtxt<'_>, pat: &Pat<'_>, path: &hir::Path<'_>) {
522 let descr = path.res.descr();
525 format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
530 "introduce a variable instead",
531 format!("{}_var", path.segments[0].ident).to_lowercase(),
532 // Cannot use `MachineApplicable` as it's not really *always* correct
533 // because there may be such an identifier in scope or the user maybe
534 // really wanted to match against the constant. This is quite unlikely however.
535 Applicability::MaybeIncorrect,
538 if let Some(span) = tcx.hir().res_span(path.res) {
539 err.span_label(span, format!("{} defined here", descr));
543 fn check_for_bindings_named_same_as_variants(
544 cx: &MatchVisitor<'_, '_, '_>,
548 pat.walk_always(|p| {
549 if let hir::PatKind::Binding(_, _, ident, None) = p.kind
550 && let Some(ty::BindByValue(hir::Mutability::Not)) =
551 cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
552 && let pat_ty = cx.typeck_results.pat_ty(p).peel_refs()
553 && let ty::Adt(edef, _) = pat_ty.kind()
555 && edef.variants().iter().any(|variant| {
556 variant.ident(cx.tcx) == ident && variant.ctor_kind == CtorKind::Const
559 let variant_count = edef.variants().len();
560 cx.tcx.struct_span_lint_hir(
561 BINDINGS_WITH_VARIANT_NAME,
565 let ty_path = cx.tcx.def_path_str(edef.did());
566 let mut err = lint.build(&format!(
567 "pattern binding `{}` is named the same as one \
568 of the variants of the type `{}`",
571 err.code(error_code!(E0170));
572 // If this is an irrefutable pattern, and there's > 1 variant,
573 // then we can't actually match on this. Applying the below
574 // suggestion would produce code that breaks on `check_irrefutable`.
575 if rf == Refutable || variant_count == 1 {
578 "to match on the variant, qualify the path",
579 format!("{}::{}", ty_path, ident),
580 Applicability::MachineApplicable,
590 /// Checks for common cases of "catchall" patterns that may not be intended as such.
591 fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
595 Single => pat.iter_fields().all(|pat| pat_is_catchall(pat)),
600 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
601 tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
602 let mut err = lint.build("unreachable pattern");
603 if let Some(catchall) = catchall {
604 // We had a catchall pattern, hint at that.
605 err.span_label(span, "unreachable pattern");
606 err.span_label(catchall, "matches any value");
612 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, id: HirId, span: Span) {
613 let source = let_source(tcx, id);
614 irrefutable_let_patterns(tcx, id, source, 1, span);
617 fn irrefutable_let_patterns(
624 macro_rules! emit_diag {
631 let s = pluralize!(count);
632 let these = pluralize!("this", count);
633 let mut diag = $lint.build(&format!("irrefutable {} pattern{s}", $source_name));
634 diag.note(&format!("{these} pattern{s} will always match, so the {}", $note_sufix));
635 diag.help(concat!("consider ", $help_sufix));
640 let span = match source {
641 LetSource::LetElse(span) => span,
644 tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| match source {
645 LetSource::GenericLet => {
646 emit_diag!(lint, "`let`", "`let` is useless", "removing `let`");
648 LetSource::IfLet => {
652 "`if let` is useless",
653 "replacing the `if let` with a `let`"
656 LetSource::IfLetGuard => {
661 "removing the guard and adding a `let` inside the match arm"
664 LetSource::LetElse(..) => {
668 "`else` clause is useless",
669 "removing the `else` clause"
672 LetSource::WhileLet => {
676 "loop will never exit",
677 "instead using a `loop { ... }` with a `let` inside it"
683 fn is_let_irrefutable<'p, 'tcx>(
684 cx: &mut MatchCheckCtxt<'p, 'tcx>,
686 pat: &'p DeconstructedPat<'p, 'tcx>,
688 let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
689 let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty());
691 // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
692 // This also reports unreachable sub-patterns though, so we can't just replace it with an
693 // `is_uninhabited` check.
694 report_arm_reachability(&cx, &report);
696 // If the list of witnesses is empty, the match is exhaustive,
697 // i.e. the `if let` pattern is irrefutable.
698 report.non_exhaustiveness_witnesses.is_empty()
701 /// Report unreachable arms, if any.
702 fn report_arm_reachability<'p, 'tcx>(
703 cx: &MatchCheckCtxt<'p, 'tcx>,
704 report: &UsefulnessReport<'p, 'tcx>,
707 let mut catchall = None;
708 for (arm, is_useful) in report.arm_usefulness.iter() {
710 Unreachable => unreachable_pattern(cx.tcx, arm.pat.span(), arm.hir_id, catchall),
711 Reachable(unreachables) if unreachables.is_empty() => {}
712 // The arm is reachable, but contains unreachable subpatterns (from or-patterns).
713 Reachable(unreachables) => {
714 let mut unreachables = unreachables.clone();
715 // Emit lints in the order in which they occur in the file.
716 unreachables.sort_unstable();
717 for span in unreachables {
718 unreachable_pattern(cx.tcx, span, arm.hir_id, None);
722 if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
723 catchall = Some(arm.pat.span());
728 /// Report that a match is not exhaustive.
729 fn non_exhaustive_match<'p, 'tcx>(
730 cx: &MatchCheckCtxt<'p, 'tcx>,
733 witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
734 arms: &[hir::Arm<'tcx>],
737 let is_empty_match = arms.is_empty();
738 let non_empty_enum = match scrut_ty.kind() {
739 ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
742 // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
746 let mut patterns_len = 0;
747 if is_empty_match && !non_empty_enum {
751 format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
753 pattern = "_".to_string();
755 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
759 format!("non-exhaustive patterns: {} not covered", joined_patterns),
761 err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
762 patterns_len = witnesses.len();
763 pattern = if witnesses.len() < 4 {
766 .map(|witness| witness.to_pat(cx).to_string())
767 .collect::<Vec<String>>()
774 let is_variant_list_non_exhaustive = match scrut_ty.kind() {
775 ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => true,
779 adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
781 "the matched value is of type `{}`{}",
783 if is_variant_list_non_exhaustive { ", which is marked as non-exhaustive" } else { "" }
785 if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
787 && witnesses.len() == 1
788 && matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
791 "`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \
795 if cx.tcx.sess.is_nightly_build() {
797 "add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
798 enable precise `{}` matching",
803 if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
804 if cx.tcx.is_ty_uninhabited_from(cx.module, *sub_ty, cx.param_env) {
805 err.note("references are always considered inhabited");
809 let mut suggestion = None;
810 let sm = cx.tcx.sess.source_map();
812 [] if sp.eq_ctxt(expr_span) => {
813 // Get the span for the empty match body `{}`.
814 let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
815 (format!("\n{}", snippet), " ")
817 (" ".to_string(), "")
820 sp.shrink_to_hi().with_hi(expr_span.hi()),
822 " {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
823 indentation = indentation,
830 let (pre_indentation, is_multiline) = if let Some(snippet) = sm.indentation_before(only.span)
831 && let Ok(with_trailing) = sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
832 && sm.is_multiline(with_trailing)
834 (format!("\n{}", snippet), true)
836 (" ".to_string(), false)
838 let comma = if matches!(only.body.kind, hir::ExprKind::Block(..))
839 && only.span.eq_ctxt(only.body.span)
847 only.span.shrink_to_hi(),
848 format!("{}{}{} => todo!()", comma, pre_indentation, pattern),
851 [.., prev, last] if prev.span.eq_ctxt(last.span) => {
852 let comma = if matches!(last.body.kind, hir::ExprKind::Block(..))
853 && last.span.eq_ctxt(last.body.span)
859 let spacing = if sm.is_multiline(prev.span.between(last.span)) {
860 sm.indentation_before(last.span).map(|indent| format!("\n{indent}"))
862 Some(" ".to_string())
864 if let Some(spacing) = spacing {
866 last.span.shrink_to_hi(),
867 format!("{}{}{} => todo!()", comma, spacing, pattern),
875 "ensure that all possible cases are being handled by adding a match arm with a wildcard \
877 if patterns_len > 1 && patterns_len < 4 && suggestion.is_some() {
878 ", a match arm with multiple or-patterns"
880 // we are either not suggesting anything, or suggesting `_`
884 // non-exhaustive enum case
885 0 if suggestion.is_some() => " as shown",
887 1 if suggestion.is_some() => " or an explicit pattern as shown",
888 1 => " or an explicit pattern",
889 _ if suggestion.is_some() => " as shown, or multiple match arms",
890 _ => " or multiple match arms",
893 if let Some((span, sugg)) = suggestion {
894 err.span_suggestion_verbose(span, &msg, sugg, Applicability::HasPlaceholders);
901 pub(crate) fn joined_uncovered_patterns<'p, 'tcx>(
902 cx: &MatchCheckCtxt<'p, 'tcx>,
903 witnesses: &[DeconstructedPat<'p, 'tcx>],
905 const LIMIT: usize = 3;
906 let pat_to_str = |pat: &DeconstructedPat<'p, 'tcx>| pat.to_pat(cx).to_string();
909 [witness] => format!("`{}`", witness.to_pat(cx)),
910 [head @ .., tail] if head.len() < LIMIT => {
911 let head: Vec<_> = head.iter().map(pat_to_str).collect();
912 format!("`{}` and `{}`", head.join("`, `"), tail.to_pat(cx))
915 let (head, tail) = witnesses.split_at(LIMIT);
916 let head: Vec<_> = head.iter().map(pat_to_str).collect();
917 format!("`{}` and {} more", head.join("`, `"), tail.len())
922 pub(crate) fn pattern_not_covered_label(
923 witnesses: &[DeconstructedPat<'_, '_>],
924 joined_patterns: &str,
926 format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
929 /// Point at the definition of non-covered `enum` variants.
930 fn adt_defined_here<'p, 'tcx>(
931 cx: &MatchCheckCtxt<'p, 'tcx>,
932 err: &mut Diagnostic,
934 witnesses: &[DeconstructedPat<'p, 'tcx>],
936 let ty = ty.peel_refs();
937 if let ty::Adt(def, _) = ty.kind() {
938 let mut spans = vec![];
939 if witnesses.len() < 5 {
940 for sp in maybe_point_at_variant(cx, *def, witnesses.iter()) {
947 .get_if_local(def.did())
948 .and_then(|node| node.ident())
949 .map(|ident| ident.span)
950 .unwrap_or_else(|| cx.tcx.def_span(def.did()));
951 let mut span: MultiSpan =
952 if spans.is_empty() { def_span.into() } else { spans.clone().into() };
954 span.push_span_label(def_span, "");
956 span.push_span_label(pat, "not covered");
958 err.span_note(span, &format!("`{}` defined here", ty));
962 fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>(
963 cx: &MatchCheckCtxt<'p, 'tcx>,
965 patterns: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
968 let mut covered = vec![];
969 for pattern in patterns {
970 if let Variant(variant_index) = pattern.ctor() {
971 if let ty::Adt(this_def, _) = pattern.ty().kind() && this_def.did() != def.did() {
974 let sp = def.variant(*variant_index).ident(cx.tcx).span;
975 if covered.contains(&sp) {
976 // Don't point at variants that have already been covered due to other patterns to avoid
982 covered.extend(maybe_point_at_variant(cx, def, pattern.iter_fields()));
987 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
988 fn is_binding_by_move(cx: &MatchVisitor<'_, '_, '_>, hir_id: HirId, span: Span) -> bool {
989 !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
992 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
994 /// For example, this would reject:
995 /// - `ref x @ Some(ref mut y)`,
996 /// - `ref mut x @ Some(ref y)`,
997 /// - `ref mut x @ Some(ref mut y)`,
998 /// - `ref mut? x @ Some(y)`, and
999 /// - `x @ Some(ref mut? y)`.
1001 /// This analysis is *not* subsumed by NLL.
1002 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
1003 // Extract `sub` in `binding @ sub`.
1004 let (name, sub) = match &pat.kind {
1005 hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
1008 let binding_span = pat.span.with_hi(name.span.hi());
1010 let typeck_results = cx.typeck_results;
1011 let sess = cx.tcx.sess;
1013 // Get the binding move, extract the mutability if by-ref.
1014 let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) {
1015 Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
1016 // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
1017 let mut conflicts_ref = Vec::new();
1018 sub.each_binding(|_, hir_id, span, _| {
1019 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1020 Some(ty::BindByValue(_)) | None => {}
1021 Some(ty::BindByReference(_)) => conflicts_ref.push(span),
1024 if !conflicts_ref.is_empty() {
1025 let occurs_because = format!(
1026 "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
1028 typeck_results.node_type(pat.hir_id),
1030 sess.struct_span_err(pat.span, "borrow of moved value")
1031 .span_label(binding_span, format!("value moved into `{}` here", name))
1032 .span_label(binding_span, occurs_because)
1033 .span_labels(conflicts_ref, "value borrowed here after move")
1038 Some(ty::BindByValue(_)) | None => return,
1039 Some(ty::BindByReference(m)) => m,
1042 // We now have `ref $mut_outer binding @ sub` (semantically).
1043 // Recurse into each binding in `sub` and find mutability or move conflicts.
1044 let mut conflicts_move = Vec::new();
1045 let mut conflicts_mut_mut = Vec::new();
1046 let mut conflicts_mut_ref = Vec::new();
1047 sub.each_binding(|_, hir_id, span, name| {
1048 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1049 Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
1050 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
1051 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
1052 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
1054 Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
1055 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
1057 Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
1061 // Report errors if any.
1062 if !conflicts_mut_mut.is_empty() {
1063 // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
1065 .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
1066 err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
1067 for (span, name) in conflicts_mut_mut {
1068 err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
1070 for (span, name) in conflicts_mut_ref {
1071 err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
1073 for (span, name) in conflicts_move {
1074 err.span_label(span, format!("also moved into `{}` here", name));
1077 } else if !conflicts_mut_ref.is_empty() {
1078 // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
1079 let (primary, also) = match mut_outer {
1080 Mutability::Mut => ("mutable", "immutable"),
1081 Mutability::Not => ("immutable", "mutable"),
1084 format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
1085 let mut err = sess.struct_span_err(pat.span, &msg);
1086 err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
1087 for (span, name) in conflicts_mut_ref {
1088 err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
1090 for (span, name) in conflicts_move {
1091 err.span_label(span, format!("also moved into `{}` here", name));
1094 } else if !conflicts_move.is_empty() {
1095 // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
1097 sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
1098 err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
1099 for (span, name) in conflicts_move {
1100 err.span_label(span, format!("value moved into `{}` here", name));
1106 #[derive(Clone, Copy, Debug)]
1107 pub enum LetSource {
1115 fn let_source(tcx: TyCtxt<'_>, pat_id: HirId) -> LetSource {
1116 let hir = tcx.hir();
1118 let parent = hir.get_parent_node(pat_id);
1119 let_source_parent(tcx, parent, Some(pat_id))
1122 fn let_source_parent(tcx: TyCtxt<'_>, parent: HirId, pat_id: Option<HirId>) -> LetSource {
1123 let hir = tcx.hir();
1125 let parent_node = hir.get(parent);
1128 hir::Node::Arm(hir::Arm {
1129 guard: Some(hir::Guard::IfLet(&hir::Let { pat: hir::Pat { hir_id, .. }, .. })),
1131 }) if Some(*hir_id) == pat_id => {
1132 return LetSource::IfLetGuard;
1137 let parent_parent = hir.get_parent_node(parent);
1138 let parent_parent_node = hir.get(parent_parent);
1139 if let hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(_), span, .. }) =
1142 return LetSource::LetElse(*span);
1145 let parent_parent_parent = hir.get_parent_node(parent_parent);
1146 let parent_parent_parent_parent = hir.get_parent_node(parent_parent_parent);
1147 let parent_parent_parent_parent_node = hir.get(parent_parent_parent_parent);
1149 if let hir::Node::Expr(hir::Expr {
1150 kind: hir::ExprKind::Loop(_, _, hir::LoopSource::While, _),
1152 }) = parent_parent_parent_parent_node
1154 return LetSource::WhileLet;
1157 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::If(..), .. }) = parent_parent_node {
1158 return LetSource::IfLet;
1161 LetSource::GenericLet