1 use super::_match::Usefulness::*;
2 use super::_match::WitnessPreference::*;
3 use super::_match::{expand_pattern, is_useful, MatchCheckCtxt, Matrix, PatStack};
4 use super::{PatCtxt, PatKind, PatternError};
6 use rustc_arena::TypedArena;
7 use rustc_ast::ast::Mutability;
8 use rustc_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder};
10 use rustc_hir::def::*;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
13 use rustc_hir::{HirId, Pat};
14 use rustc_middle::ty::{self, Ty, TyCtxt};
15 use rustc_session::config::nightly_options;
16 use rustc_session::lint::builtin::BINDINGS_WITH_VARIANT_NAME;
17 use rustc_session::lint::builtin::{IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS};
18 use rustc_session::parse::feature_err;
19 use rustc_session::Session;
20 use rustc_span::{sym, Span};
23 crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
24 let body_id = match def_id.as_local() {
26 Some(id) => tcx.hir().body_owned_by(tcx.hir().local_def_id_to_hir_id(id)),
29 let mut visitor = MatchVisitor {
31 typeck_results: tcx.typeck_body(body_id),
32 param_env: tcx.param_env(def_id),
33 pattern_arena: TypedArena::default(),
35 visitor.visit_body(tcx.hir().body(body_id));
38 fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBuilder<'_> {
39 struct_span_err!(sess, sp, E0004, "{}", &error_message)
42 struct MatchVisitor<'a, 'tcx> {
44 typeck_results: &'a ty::TypeckResults<'tcx>,
45 param_env: ty::ParamEnv<'tcx>,
46 pattern_arena: TypedArena<super::Pat<'tcx>>,
49 impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, 'tcx> {
50 type Map = intravisit::ErasedMap<'tcx>;
52 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
53 NestedVisitorMap::None
56 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
57 intravisit::walk_expr(self, ex);
59 if let hir::ExprKind::Match(ref scrut, ref arms, source) = ex.kind {
60 self.check_match(scrut, arms, source);
64 fn visit_local(&mut self, loc: &'tcx hir::Local<'tcx>) {
65 intravisit::walk_local(self, loc);
67 let (msg, sp) = match loc.source {
68 hir::LocalSource::Normal => ("local binding", Some(loc.span)),
69 hir::LocalSource::ForLoopDesugar => ("`for` loop binding", None),
70 hir::LocalSource::AsyncFn => ("async fn binding", None),
71 hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
73 self.check_irrefutable(&loc.pat, msg, sp);
74 self.check_patterns(false, &loc.pat);
77 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
78 intravisit::walk_param(self, param);
79 self.check_irrefutable(¶m.pat, "function argument", None);
80 self.check_patterns(false, ¶m.pat);
84 impl PatCtxt<'_, '_> {
85 fn report_inlining_errors(&self, pat_span: Span) {
86 for error in &self.errors {
88 PatternError::StaticInPattern(span) => {
89 self.span_e0158(span, "statics cannot be referenced in patterns")
91 PatternError::AssocConstInPattern(span) => {
92 self.span_e0158(span, "associated consts cannot be referenced in patterns")
94 PatternError::ConstParamInPattern(span) => {
95 self.span_e0158(span, "const parameters cannot be referenced in patterns")
97 PatternError::FloatBug => {
98 // FIXME(#31407) this is only necessary because float parsing is buggy
99 ::rustc_middle::mir::interpret::struct_error(
100 self.tcx.at(pat_span),
101 "could not evaluate float literal (see issue #31407)",
105 PatternError::NonConstPath(span) => {
106 ::rustc_middle::mir::interpret::struct_error(
108 "runtime values cannot be referenced in patterns",
116 fn span_e0158(&self, span: Span, text: &str) {
117 struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
121 impl<'tcx> MatchVisitor<'_, 'tcx> {
122 fn check_patterns(&mut self, has_guard: bool, pat: &Pat<'_>) {
123 if !self.tcx.features().move_ref_pattern {
124 check_legality_of_move_bindings(self, has_guard, pat);
126 pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
127 if !self.tcx.features().bindings_after_at {
128 check_legality_of_bindings_in_at_patterns(self, pat);
130 check_for_bindings_named_same_as_variants(self, pat);
133 fn lower_pattern<'p>(
135 cx: &mut MatchCheckCtxt<'p, 'tcx>,
136 pat: &'tcx hir::Pat<'tcx>,
137 have_errors: &mut bool,
138 ) -> (&'p super::Pat<'tcx>, Ty<'tcx>) {
139 let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
140 patcx.include_lint_checks();
141 let pattern = patcx.lower_pattern(pat);
142 let pattern_ty = pattern.ty;
143 let pattern: &_ = cx.pattern_arena.alloc(expand_pattern(cx, pattern));
144 if !patcx.errors.is_empty() {
146 patcx.report_inlining_errors(pat.span);
148 (pattern, pattern_ty)
151 fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'_, 'tcx> {
154 param_env: self.param_env,
155 module: self.tcx.parent_module(hir_id).to_def_id(),
156 pattern_arena: &self.pattern_arena,
162 scrut: &hir::Expr<'_>,
163 arms: &'tcx [hir::Arm<'tcx>],
164 source: hir::MatchSource,
167 // Check the arm for some things unrelated to exhaustiveness.
168 self.check_patterns(arm.guard.is_some(), &arm.pat);
171 let mut cx = self.new_cx(scrut.hir_id);
173 let mut have_errors = false;
175 let inlined_arms: Vec<_> = arms
177 .map(|hir::Arm { pat, guard, .. }| {
178 (self.lower_pattern(&mut cx, pat, &mut have_errors).0, pat.hir_id, guard.is_some())
182 // Bail out early if inlining failed.
187 // Fourth, check for unreachable arms.
188 let matrix = check_arms(&mut cx, &inlined_arms, source);
190 // Fifth, check if the match is exhaustive.
191 // Note: An empty match isn't the same as an empty matrix for diagnostics purposes,
192 // since an empty matrix can occur when there are arms, if those arms all have guards.
193 let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
194 let is_empty_match = inlined_arms.is_empty();
195 check_exhaustive(&mut cx, scrut_ty, scrut.span, &matrix, scrut.hir_id, is_empty_match);
198 fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
199 let mut cx = self.new_cx(pat.hir_id);
201 let (pattern, pattern_ty) = self.lower_pattern(&mut cx, pat, &mut false);
202 let pats: Matrix<'_, '_> = vec![PatStack::from_pattern(pattern)].into_iter().collect();
204 let witnesses = match check_not_useful(&mut cx, pattern_ty, &pats, pat.hir_id) {
209 let joined_patterns = joined_uncovered_patterns(&witnesses);
210 let mut err = struct_span_err!(
214 "refutable pattern in {}: {} not covered",
218 let suggest_if_let = match &pat.kind {
219 hir::PatKind::Path(hir::QPath::Resolved(None, path))
220 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
222 const_not_var(&mut err, cx.tcx, pat, path);
226 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
231 if let (Some(span), true) = (sp, suggest_if_let) {
233 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
234 an `enum` with only one variant",
236 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
239 "you might want to use `if let` to ignore the variant that isn't matched",
240 format!("if {} {{ /* */ }}", &snippet[..snippet.len() - 1]),
241 Applicability::HasPlaceholders,
245 "for more information, visit \
246 https://doc.rust-lang.org/book/ch18-02-refutability.html",
250 adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
251 err.note(&format!("the matched value is of type `{}`", pattern_ty));
256 /// A path pattern was interpreted as a constant, not a new variable.
257 /// This caused an irrefutable match failure in e.g. `let`.
259 err: &mut DiagnosticBuilder<'_>,
262 path: &hir::Path<'_>,
264 let descr = path.res.descr();
267 format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
272 "introduce a variable instead",
273 format!("{}_var", path.segments[0].ident).to_lowercase(),
274 // Cannot use `MachineApplicable` as it's not really *always* correct
275 // because there may be such an identifier in scope or the user maybe
276 // really wanted to match against the constant. This is quite unlikely however.
277 Applicability::MaybeIncorrect,
280 if let Some(span) = tcx.hir().res_span(path.res) {
281 err.span_label(span, format!("{} defined here", descr));
285 fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
286 pat.walk_always(|p| {
287 if let hir::PatKind::Binding(_, _, ident, None) = p.kind {
288 if let Some(ty::BindByValue(hir::Mutability::Not)) =
289 cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
291 let pat_ty = cx.typeck_results.pat_ty(p).peel_refs();
292 if let ty::Adt(edef, _) = pat_ty.kind {
294 && edef.variants.iter().any(|variant| {
295 variant.ident == ident && variant.ctor_kind == CtorKind::Const
298 cx.tcx.struct_span_lint_hir(
299 BINDINGS_WITH_VARIANT_NAME,
303 let ty_path = cx.tcx.def_path_str(edef.did);
305 "pattern binding `{}` is named the same as one \
306 of the variants of the type `{}`",
309 .code(error_code!(E0170))
312 "to match on the variant, qualify the path",
313 format!("{}::{}", ty_path, ident),
314 Applicability::MachineApplicable,
326 /// Checks for common cases of "catchall" patterns that may not be intended as such.
327 fn pat_is_catchall(pat: &super::Pat<'_>) -> bool {
328 use super::PatKind::*;
330 Binding { subpattern: None, .. } => true,
331 Binding { subpattern: Some(s), .. } | Deref { subpattern: s } => pat_is_catchall(s),
332 Leaf { subpatterns: s } => s.iter().all(|p| pat_is_catchall(&p.pattern)),
337 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
338 tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
339 let mut err = lint.build("unreachable pattern");
340 if let Some(catchall) = catchall {
341 // We had a catchall pattern, hint at that.
342 err.span_label(span, "unreachable pattern");
343 err.span_label(catchall, "matches any value");
349 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, source: hir::MatchSource) {
350 tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| {
351 let msg = match source {
352 hir::MatchSource::IfLetDesugar { .. } => "irrefutable if-let pattern",
353 hir::MatchSource::WhileLetDesugar => "irrefutable while-let pattern",
356 lint.build(msg).emit()
360 /// Check for unreachable patterns.
361 fn check_arms<'p, 'tcx>(
362 cx: &mut MatchCheckCtxt<'p, 'tcx>,
363 arms: &[(&'p super::Pat<'tcx>, HirId, bool)],
364 source: hir::MatchSource,
365 ) -> Matrix<'p, 'tcx> {
366 let mut seen = Matrix::empty();
367 let mut catchall = None;
368 for (arm_index, (pat, id, has_guard)) in arms.iter().copied().enumerate() {
369 let v = PatStack::from_pattern(pat);
370 match is_useful(cx, &seen, &v, LeaveOutWitness, id, has_guard, true) {
373 hir::MatchSource::IfDesugar { .. } | hir::MatchSource::WhileDesugar => bug!(),
375 hir::MatchSource::IfLetDesugar { .. } | hir::MatchSource::WhileLetDesugar => {
376 // Check which arm we're on.
378 // The arm with the user-specified pattern.
379 0 => unreachable_pattern(cx.tcx, pat.span, id, None),
380 // The arm with the wildcard pattern.
381 1 => irrefutable_let_pattern(cx.tcx, pat.span, id, source),
386 hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
387 unreachable_pattern(cx.tcx, pat.span, id, catchall);
390 // Unreachable patterns in try and await expressions occur when one of
391 // the arms are an uninhabited type. Which is OK.
392 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
395 Useful(unreachable_subpatterns) => {
396 for span in unreachable_subpatterns {
397 unreachable_pattern(cx.tcx, span, id, None);
400 UsefulWithWitness(_) => bug!(),
404 if catchall.is_none() && pat_is_catchall(pat) {
405 catchall = Some(pat.span);
412 fn check_not_useful<'p, 'tcx>(
413 cx: &mut MatchCheckCtxt<'p, 'tcx>,
415 matrix: &Matrix<'p, 'tcx>,
417 ) -> Result<(), Vec<super::Pat<'tcx>>> {
418 let wild_pattern = cx.pattern_arena.alloc(super::Pat::wildcard_from_ty(ty));
419 let v = PatStack::from_pattern(wild_pattern);
421 // false is given for `is_under_guard` argument due to the wildcard
422 // pattern not having a guard
423 match is_useful(cx, matrix, &v, ConstructWitness, hir_id, false, true) {
424 NotUseful => Ok(()), // This is good, wildcard pattern isn't reachable.
425 UsefulWithWitness(pats) => Err(if pats.is_empty() {
426 bug!("Exhaustiveness check returned no witnesses")
428 pats.into_iter().map(|w| w.single_pattern()).collect()
434 fn check_exhaustive<'p, 'tcx>(
435 cx: &mut MatchCheckCtxt<'p, 'tcx>,
438 matrix: &Matrix<'p, 'tcx>,
440 is_empty_match: bool,
442 // In the absence of the `exhaustive_patterns` feature, empty matches are not detected by
443 // `is_useful` to exhaustively match uninhabited types, so we manually check here.
444 if is_empty_match && !cx.tcx.features().exhaustive_patterns {
445 let scrutinee_is_visibly_uninhabited = match scrut_ty.kind {
449 && def.variants.is_empty()
450 && !cx.is_foreign_non_exhaustive_enum(scrut_ty)
454 if scrutinee_is_visibly_uninhabited {
455 // If the type *is* uninhabited, an empty match is vacuously exhaustive.
460 let witnesses = match check_not_useful(cx, scrut_ty, matrix, hir_id) {
465 let non_empty_enum = match scrut_ty.kind {
466 ty::Adt(def, _) => def.is_enum() && !def.variants.is_empty(),
469 // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
472 if is_empty_match && !non_empty_enum {
476 format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
479 let joined_patterns = joined_uncovered_patterns(&witnesses);
483 format!("non-exhaustive patterns: {} not covered", joined_patterns),
485 err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
488 adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
490 "ensure that all possible cases are being handled, \
491 possibly by adding wildcards or more match arms",
493 err.note(&format!("the matched value is of type `{}`", scrut_ty));
494 if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
496 && witnesses.len() == 1
497 && witnesses[0].is_wildcard()
500 "`{}` does not have a fixed maximum value, \
501 so a wildcard `_` is necessary to match exhaustively",
504 if nightly_options::is_nightly_build() {
506 "add `#![feature(precise_pointer_size_matching)]` \
507 to the crate attributes to enable precise `{}` matching",
515 fn joined_uncovered_patterns(witnesses: &[super::Pat<'_>]) -> String {
516 const LIMIT: usize = 3;
519 [witness] => format!("`{}`", witness),
520 [head @ .., tail] if head.len() < LIMIT => {
521 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
522 format!("`{}` and `{}`", head.join("`, `"), tail)
525 let (head, tail) = witnesses.split_at(LIMIT);
526 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
527 format!("`{}` and {} more", head.join("`, `"), tail.len())
532 fn pattern_not_covered_label(witnesses: &[super::Pat<'_>], joined_patterns: &str) -> String {
533 format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
536 /// Point at the definition of non-covered `enum` variants.
538 cx: &MatchCheckCtxt<'_, '_>,
539 err: &mut DiagnosticBuilder<'_>,
541 witnesses: &[super::Pat<'_>],
543 let ty = ty.peel_refs();
544 if let ty::Adt(def, _) = ty.kind {
545 if let Some(sp) = cx.tcx.hir().span_if_local(def.did) {
546 err.span_label(sp, format!("`{}` defined here", ty));
549 if witnesses.len() < 4 {
550 for sp in maybe_point_at_variant(ty, &witnesses) {
551 err.span_label(sp, "not covered");
557 fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec<Span> {
558 let mut covered = vec![];
559 if let ty::Adt(def, _) = ty.kind {
560 // Don't point at variants that have already been covered due to other patterns to avoid
562 for pattern in patterns {
563 use PatKind::{AscribeUserType, Deref, Leaf, Or, Variant};
564 match &*pattern.kind {
565 AscribeUserType { subpattern, .. } | Deref { subpattern } => {
566 covered.extend(maybe_point_at_variant(ty, slice::from_ref(&subpattern)));
568 Variant { adt_def, variant_index, subpatterns, .. } if adt_def.did == def.did => {
569 let sp = def.variants[*variant_index].ident.span;
570 if covered.contains(&sp) {
575 let pats = subpatterns
577 .map(|field_pattern| field_pattern.pattern.clone())
578 .collect::<Box<[_]>>();
579 covered.extend(maybe_point_at_variant(ty, &pats));
581 Leaf { subpatterns } => {
582 let pats = subpatterns
584 .map(|field_pattern| field_pattern.pattern.clone())
585 .collect::<Box<[_]>>();
586 covered.extend(maybe_point_at_variant(ty, &pats));
589 let pats = pats.iter().cloned().collect::<Box<[_]>>();
590 covered.extend(maybe_point_at_variant(ty, &pats));
599 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
600 fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> bool {
601 !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
604 /// Check the legality of legality of by-move bindings.
605 fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: bool, pat: &Pat<'_>) {
606 let sess = cx.tcx.sess;
607 let typeck_results = cx.typeck_results;
609 // Find all by-ref spans.
610 let mut by_ref_spans = Vec::new();
611 pat.each_binding(|_, hir_id, span, _| {
612 if let Some(ty::BindByReference(_)) =
613 typeck_results.extract_binding_mode(sess, hir_id, span)
615 by_ref_spans.push(span);
619 // Find bad by-move spans:
620 let by_move_spans = &mut Vec::new();
621 let mut check_move = |p: &Pat<'_>, sub: Option<&Pat<'_>>| {
622 // Check legality of moving out of the enum.
624 // `x @ Foo(..)` is legal, but `x @ Foo(y)` isn't.
625 if sub.map_or(false, |p| p.contains_bindings()) {
626 struct_span_err!(sess, p.span, E0007, "cannot bind by-move with sub-bindings")
627 .span_label(p.span, "binds an already bound by-move value by moving it")
629 } else if !has_guard && !by_ref_spans.is_empty() {
630 by_move_spans.push(p.span);
633 pat.walk_always(|p| {
634 if let hir::PatKind::Binding(.., sub) = &p.kind {
635 if let Some(ty::BindByValue(_)) =
636 typeck_results.extract_binding_mode(sess, p.hir_id, p.span)
638 if is_binding_by_move(cx, p.hir_id, p.span) {
639 check_move(p, sub.as_deref());
645 // Found some bad by-move spans, error!
646 if !by_move_spans.is_empty() {
647 let mut err = feature_err(
649 sym::move_ref_pattern,
650 by_move_spans.clone(),
651 "binding by-move and by-ref in the same pattern is unstable",
653 for span in by_ref_spans.iter() {
654 err.span_label(*span, "by-ref pattern here");
656 for span in by_move_spans.iter() {
657 err.span_label(*span, "by-move pattern here");
663 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
665 /// For example, this would reject:
666 /// - `ref x @ Some(ref mut y)`,
667 /// - `ref mut x @ Some(ref y)`,
668 /// - `ref mut x @ Some(ref mut y)`,
669 /// - `ref mut? x @ Some(y)`, and
670 /// - `x @ Some(ref mut? y)`.
672 /// This analysis is *not* subsumed by NLL.
673 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
674 // Extract `sub` in `binding @ sub`.
675 let (name, sub) = match &pat.kind {
676 hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
679 let binding_span = pat.span.with_hi(name.span.hi());
681 let typeck_results = cx.typeck_results;
682 let sess = cx.tcx.sess;
684 // Get the binding move, extract the mutability if by-ref.
685 let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) {
686 Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
687 // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
688 let mut conflicts_ref = Vec::new();
689 sub.each_binding(|_, hir_id, span, _| {
690 match typeck_results.extract_binding_mode(sess, hir_id, span) {
691 Some(ty::BindByValue(_)) | None => {}
692 Some(ty::BindByReference(_)) => conflicts_ref.push(span),
695 if !conflicts_ref.is_empty() {
696 let occurs_because = format!(
697 "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
699 typeck_results.node_type(pat.hir_id),
701 sess.struct_span_err(pat.span, "borrow of moved value")
702 .span_label(binding_span, format!("value moved into `{}` here", name))
703 .span_label(binding_span, occurs_because)
704 .span_labels(conflicts_ref, "value borrowed here after move")
709 Some(ty::BindByValue(_)) | None => return,
710 Some(ty::BindByReference(m)) => m,
713 // We now have `ref $mut_outer binding @ sub` (semantically).
714 // Recurse into each binding in `sub` and find mutability or move conflicts.
715 let mut conflicts_move = Vec::new();
716 let mut conflicts_mut_mut = Vec::new();
717 let mut conflicts_mut_ref = Vec::new();
718 sub.each_binding(|_, hir_id, span, name| {
719 match typeck_results.extract_binding_mode(sess, hir_id, span) {
720 Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
721 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
722 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
723 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
725 Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
726 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
728 Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
732 // Report errors if any.
733 if !conflicts_mut_mut.is_empty() {
734 // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
736 .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
737 err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
738 for (span, name) in conflicts_mut_mut {
739 err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
741 for (span, name) in conflicts_mut_ref {
742 err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
744 for (span, name) in conflicts_move {
745 err.span_label(span, format!("also moved into `{}` here", name));
748 } else if !conflicts_mut_ref.is_empty() {
749 // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
750 let (primary, also) = match mut_outer {
751 Mutability::Mut => ("mutable", "immutable"),
752 Mutability::Not => ("immutable", "mutable"),
755 format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
756 let mut err = sess.struct_span_err(pat.span, &msg);
757 err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
758 for (span, name) in conflicts_mut_ref {
759 err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
761 for (span, name) in conflicts_move {
762 err.span_label(span, format!("also moved into `{}` here", name));
765 } else if !conflicts_move.is_empty() {
766 // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
768 sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
769 err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
770 for (span, name) in conflicts_move {
771 err.span_label(span, format!("value moved into `{}` here", name));
777 /// Forbids bindings in `@` patterns. This used to be is necessary for memory safety,
778 /// because of the way rvalues were handled in the borrow check. (See issue #14587.)
779 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
780 AtBindingPatternVisitor { cx, bindings_allowed: true }.visit_pat(pat);
782 struct AtBindingPatternVisitor<'a, 'b, 'tcx> {
783 cx: &'a MatchVisitor<'b, 'tcx>,
784 bindings_allowed: bool,
787 impl<'v> Visitor<'v> for AtBindingPatternVisitor<'_, '_, '_> {
788 type Map = intravisit::ErasedMap<'v>;
790 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
791 NestedVisitorMap::None
794 fn visit_pat(&mut self, pat: &Pat<'_>) {
796 hir::PatKind::Binding(.., ref subpat) => {
797 if !self.bindings_allowed {
799 &self.cx.tcx.sess.parse_sess,
800 sym::bindings_after_at,
802 "pattern bindings after an `@` are unstable",
807 if subpat.is_some() {
808 let bindings_were_allowed = self.bindings_allowed;
809 self.bindings_allowed = false;
810 intravisit::walk_pat(self, pat);
811 self.bindings_allowed = bindings_were_allowed;
814 _ => intravisit::walk_pat(self, pat),