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::lint::builtin::BINDINGS_WITH_VARIANT_NAME;
16 use rustc_session::lint::builtin::{IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS};
17 use rustc_session::parse::feature_err;
18 use rustc_session::Session;
19 use rustc_span::{sym, Span};
22 crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
23 let body_id = match def_id.as_local() {
25 Some(id) => tcx.hir().body_owned_by(tcx.hir().as_local_hir_id(id)),
28 let mut visitor = MatchVisitor {
30 tables: tcx.body_tables(body_id),
31 param_env: tcx.param_env(def_id),
32 pattern_arena: TypedArena::default(),
34 visitor.visit_body(tcx.hir().body(body_id));
37 fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBuilder<'_> {
38 struct_span_err!(sess, sp, E0004, "{}", &error_message)
41 struct MatchVisitor<'a, 'tcx> {
43 tables: &'a ty::TypeckTables<'tcx>,
44 param_env: ty::ParamEnv<'tcx>,
45 pattern_arena: TypedArena<super::Pat<'tcx>>,
48 impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, 'tcx> {
49 type Map = intravisit::ErasedMap<'tcx>;
51 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
52 NestedVisitorMap::None
55 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
56 intravisit::walk_expr(self, ex);
58 if let hir::ExprKind::Match(ref scrut, ref arms, source) = ex.kind {
59 self.check_match(scrut, arms, source);
63 fn visit_local(&mut self, loc: &'tcx hir::Local<'tcx>) {
64 intravisit::walk_local(self, loc);
66 let (msg, sp) = match loc.source {
67 hir::LocalSource::Normal => ("local binding", Some(loc.span)),
68 hir::LocalSource::ForLoopDesugar => ("`for` loop binding", None),
69 hir::LocalSource::AsyncFn => ("async fn binding", None),
70 hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
72 self.check_irrefutable(&loc.pat, msg, sp);
73 self.check_patterns(false, &loc.pat);
76 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
77 intravisit::walk_param(self, param);
78 self.check_irrefutable(¶m.pat, "function argument", None);
79 self.check_patterns(false, ¶m.pat);
83 impl PatCtxt<'_, '_> {
84 fn report_inlining_errors(&self, pat_span: Span) {
85 for error in &self.errors {
87 PatternError::StaticInPattern(span) => {
88 self.span_e0158(span, "statics cannot be referenced in patterns")
90 PatternError::AssocConstInPattern(span) => {
91 self.span_e0158(span, "associated consts cannot be referenced in patterns")
93 PatternError::ConstParamInPattern(span) => {
94 self.span_e0158(span, "const parameters cannot be referenced in patterns")
96 PatternError::FloatBug => {
97 // FIXME(#31407) this is only necessary because float parsing is buggy
98 ::rustc_middle::mir::interpret::struct_error(
99 self.tcx.at(pat_span),
100 "could not evaluate float literal (see issue #31407)",
104 PatternError::NonConstPath(span) => {
105 ::rustc_middle::mir::interpret::struct_error(
107 "runtime values cannot be referenced in patterns",
115 fn span_e0158(&self, span: Span, text: &str) {
116 struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
120 impl<'tcx> MatchVisitor<'_, 'tcx> {
121 fn check_patterns(&mut self, has_guard: bool, pat: &Pat<'_>) {
122 if !self.tcx.features().move_ref_pattern {
123 check_legality_of_move_bindings(self, has_guard, pat);
125 pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
126 if !self.tcx.features().bindings_after_at {
127 check_legality_of_bindings_in_at_patterns(self, pat);
129 check_for_bindings_named_same_as_variants(self, pat);
132 fn lower_pattern<'p>(
134 cx: &mut MatchCheckCtxt<'p, 'tcx>,
135 pat: &'tcx hir::Pat<'tcx>,
136 have_errors: &mut bool,
137 ) -> (&'p super::Pat<'tcx>, Ty<'tcx>) {
138 let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.tables);
139 patcx.include_lint_checks();
140 let pattern = patcx.lower_pattern(pat);
141 let pattern_ty = pattern.ty;
142 let pattern: &_ = cx.pattern_arena.alloc(expand_pattern(cx, pattern));
143 if !patcx.errors.is_empty() {
145 patcx.report_inlining_errors(pat.span);
147 (pattern, pattern_ty)
150 fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'_, 'tcx> {
153 param_env: self.param_env,
154 module: self.tcx.parent_module(hir_id).to_def_id(),
155 pattern_arena: &self.pattern_arena,
161 scrut: &hir::Expr<'_>,
162 arms: &'tcx [hir::Arm<'tcx>],
163 source: hir::MatchSource,
166 // Check the arm for some things unrelated to exhaustiveness.
167 self.check_patterns(arm.guard.is_some(), &arm.pat);
170 let mut cx = self.new_cx(scrut.hir_id);
172 let mut have_errors = false;
174 let inlined_arms: Vec<_> = arms
176 .map(|hir::Arm { pat, guard, .. }| {
177 (self.lower_pattern(&mut cx, pat, &mut have_errors).0, pat.hir_id, guard.is_some())
181 // Bail out early if inlining failed.
186 // Fourth, check for unreachable arms.
187 let matrix = check_arms(&mut cx, &inlined_arms, source);
189 // Fifth, check if the match is exhaustive.
190 // Note: An empty match isn't the same as an empty matrix for diagnostics purposes,
191 // since an empty matrix can occur when there are arms, if those arms all have guards.
192 let scrut_ty = self.tables.expr_ty_adjusted(scrut);
193 let is_empty_match = inlined_arms.is_empty();
194 check_exhaustive(&mut cx, scrut_ty, scrut.span, &matrix, scrut.hir_id, is_empty_match);
197 fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
198 let mut cx = self.new_cx(pat.hir_id);
200 let (pattern, pattern_ty) = self.lower_pattern(&mut cx, pat, &mut false);
201 let pats: Matrix<'_, '_> = vec![PatStack::from_pattern(pattern)].into_iter().collect();
203 let witnesses = match check_not_useful(&mut cx, pattern_ty, &pats, pat.hir_id) {
208 let joined_patterns = joined_uncovered_patterns(&witnesses);
209 let mut err = struct_span_err!(
213 "refutable pattern in {}: {} not covered",
217 let suggest_if_let = match &pat.kind {
218 hir::PatKind::Path(hir::QPath::Resolved(None, path))
219 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
221 const_not_var(&mut err, cx.tcx, pat, path);
225 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
230 if let (Some(span), true) = (sp, suggest_if_let) {
232 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
233 an `enum` with only one variant",
235 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
238 "you might want to use `if let` to ignore the variant that isn't matched",
239 format!("if {} {{ /* */ }}", &snippet[..snippet.len() - 1]),
240 Applicability::HasPlaceholders,
244 "for more information, visit \
245 https://doc.rust-lang.org/book/ch18-02-refutability.html",
249 adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
250 err.note(&format!("the matched value is of type `{}`", pattern_ty));
255 /// A path pattern was interpreted as a constant, not a new variable.
256 /// This caused an irrefutable match failure in e.g. `let`.
258 err: &mut DiagnosticBuilder<'_>,
261 path: &hir::Path<'_>,
263 let descr = path.res.descr();
266 format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
271 "introduce a variable instead",
272 format!("{}_var", path.segments[0].ident).to_lowercase(),
273 // Cannot use `MachineApplicable` as it's not really *always* correct
274 // because there may be such an identifier in scope or the user maybe
275 // really wanted to match against the constant. This is quite unlikely however.
276 Applicability::MaybeIncorrect,
279 if let Some(span) = tcx.hir().res_span(path.res) {
280 err.span_label(span, format!("{} defined here", descr));
284 fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
285 pat.walk_always(|p| {
286 if let hir::PatKind::Binding(_, _, ident, None) = p.kind {
287 if let Some(ty::BindByValue(hir::Mutability::Not)) =
288 cx.tables.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
290 let pat_ty = cx.tables.pat_ty(p).peel_refs();
291 if let ty::Adt(edef, _) = pat_ty.kind {
293 && edef.variants.iter().any(|variant| {
294 variant.ident == ident && variant.ctor_kind == CtorKind::Const
297 cx.tcx.struct_span_lint_hir(
298 BINDINGS_WITH_VARIANT_NAME,
302 let ty_path = cx.tcx.def_path_str(edef.did);
304 "pattern binding `{}` is named the same as one \
305 of the variants of the type `{}`",
308 .code(error_code!(E0170))
311 "to match on the variant, qualify the path",
312 format!("{}::{}", ty_path, ident),
313 Applicability::MachineApplicable,
325 /// Checks for common cases of "catchall" patterns that may not be intended as such.
326 fn pat_is_catchall(pat: &super::Pat<'_>) -> bool {
327 use super::PatKind::*;
329 Binding { subpattern: None, .. } => true,
330 Binding { subpattern: Some(s), .. } | Deref { subpattern: s } => pat_is_catchall(s),
331 Leaf { subpatterns: s } => s.iter().all(|p| pat_is_catchall(&p.pattern)),
336 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
337 tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
338 let mut err = lint.build("unreachable pattern");
339 if let Some(catchall) = catchall {
340 // We had a catchall pattern, hint at that.
341 err.span_label(span, "unreachable pattern");
342 err.span_label(catchall, "matches any value");
348 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, source: hir::MatchSource) {
349 tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| {
350 let msg = match source {
351 hir::MatchSource::IfLetDesugar { .. } => "irrefutable if-let pattern",
352 hir::MatchSource::WhileLetDesugar => "irrefutable while-let pattern",
355 lint.build(msg).emit()
359 /// Check for unreachable patterns.
360 fn check_arms<'p, 'tcx>(
361 cx: &mut MatchCheckCtxt<'p, 'tcx>,
362 arms: &[(&'p super::Pat<'tcx>, HirId, bool)],
363 source: hir::MatchSource,
364 ) -> Matrix<'p, 'tcx> {
365 let mut seen = Matrix::empty();
366 let mut catchall = None;
367 for (arm_index, (pat, id, has_guard)) in arms.iter().copied().enumerate() {
368 let v = PatStack::from_pattern(pat);
369 match is_useful(cx, &seen, &v, LeaveOutWitness, id, has_guard, true) {
372 hir::MatchSource::IfDesugar { .. } | hir::MatchSource::WhileDesugar => bug!(),
374 hir::MatchSource::IfLetDesugar { .. } | hir::MatchSource::WhileLetDesugar => {
375 // Check which arm we're on.
377 // The arm with the user-specified pattern.
378 0 => unreachable_pattern(cx.tcx, pat.span, id, None),
379 // The arm with the wildcard pattern.
380 1 => irrefutable_let_pattern(cx.tcx, pat.span, id, source),
385 hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
386 unreachable_pattern(cx.tcx, pat.span, id, catchall);
389 // Unreachable patterns in try and await expressions occur when one of
390 // the arms are an uninhabited type. Which is OK.
391 hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
394 Useful(unreachable_subpatterns) => {
395 for pat in unreachable_subpatterns {
396 unreachable_pattern(cx.tcx, pat.span, id, None);
399 UsefulWithWitness(_) => bug!(),
403 if catchall.is_none() && pat_is_catchall(pat) {
404 catchall = Some(pat.span);
411 fn check_not_useful<'p, 'tcx>(
412 cx: &mut MatchCheckCtxt<'p, 'tcx>,
414 matrix: &Matrix<'p, 'tcx>,
416 ) -> Result<(), Vec<super::Pat<'tcx>>> {
417 let wild_pattern = cx.pattern_arena.alloc(super::Pat::wildcard_from_ty(ty));
418 let v = PatStack::from_pattern(wild_pattern);
420 // false is given for `is_under_guard` argument due to the wildcard
421 // pattern not having a guard
422 match is_useful(cx, matrix, &v, ConstructWitness, hir_id, false, true) {
423 NotUseful => Ok(()), // This is good, wildcard pattern isn't reachable.
424 UsefulWithWitness(pats) => Err(if pats.is_empty() {
425 bug!("Exhaustiveness check returned no witnesses")
427 pats.into_iter().map(|w| w.single_pattern()).collect()
433 fn check_exhaustive<'p, 'tcx>(
434 cx: &mut MatchCheckCtxt<'p, 'tcx>,
437 matrix: &Matrix<'p, 'tcx>,
439 is_empty_match: bool,
441 // In the absence of the `exhaustive_patterns` feature, empty matches are not detected by
442 // `is_useful` to exhaustively match uninhabited types, so we manually check here.
443 if is_empty_match && !cx.tcx.features().exhaustive_patterns {
444 let scrutinee_is_visibly_uninhabited = match scrut_ty.kind {
448 && def.variants.is_empty()
449 && !cx.is_foreign_non_exhaustive_enum(scrut_ty)
453 if scrutinee_is_visibly_uninhabited {
454 // If the type *is* uninhabited, an empty match is vacuously exhaustive.
459 let witnesses = match check_not_useful(cx, scrut_ty, matrix, hir_id) {
464 let non_empty_enum = match scrut_ty.kind {
465 ty::Adt(def, _) => def.is_enum() && !def.variants.is_empty(),
468 // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
471 if is_empty_match && !non_empty_enum {
475 format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
478 let joined_patterns = joined_uncovered_patterns(&witnesses);
482 format!("non-exhaustive patterns: {} not covered", joined_patterns),
484 err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
487 adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
489 "ensure that all possible cases are being handled, \
490 possibly by adding wildcards or more match arms",
492 err.note(&format!("the matched value is of type `{}`", scrut_ty));
496 fn joined_uncovered_patterns(witnesses: &[super::Pat<'_>]) -> String {
497 const LIMIT: usize = 3;
500 [witness] => format!("`{}`", witness),
501 [head @ .., tail] if head.len() < LIMIT => {
502 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
503 format!("`{}` and `{}`", head.join("`, `"), tail)
506 let (head, tail) = witnesses.split_at(LIMIT);
507 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
508 format!("`{}` and {} more", head.join("`, `"), tail.len())
513 fn pattern_not_covered_label(witnesses: &[super::Pat<'_>], joined_patterns: &str) -> String {
514 format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
517 /// Point at the definition of non-covered `enum` variants.
519 cx: &MatchCheckCtxt<'_, '_>,
520 err: &mut DiagnosticBuilder<'_>,
522 witnesses: &[super::Pat<'_>],
524 let ty = ty.peel_refs();
525 if let ty::Adt(def, _) = ty.kind {
526 if let Some(sp) = cx.tcx.hir().span_if_local(def.did) {
527 err.span_label(sp, format!("`{}` defined here", ty));
530 if witnesses.len() < 4 {
531 for sp in maybe_point_at_variant(ty, &witnesses) {
532 err.span_label(sp, "not covered");
538 fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec<Span> {
539 let mut covered = vec![];
540 if let ty::Adt(def, _) = ty.kind {
541 // Don't point at variants that have already been covered due to other patterns to avoid
543 for pattern in patterns {
544 use PatKind::{AscribeUserType, Deref, Leaf, Or, Variant};
545 match &*pattern.kind {
546 AscribeUserType { subpattern, .. } | Deref { subpattern } => {
547 covered.extend(maybe_point_at_variant(ty, slice::from_ref(&subpattern)));
549 Variant { adt_def, variant_index, subpatterns, .. } if adt_def.did == def.did => {
550 let sp = def.variants[*variant_index].ident.span;
551 if covered.contains(&sp) {
556 let pats = subpatterns
558 .map(|field_pattern| field_pattern.pattern.clone())
559 .collect::<Box<[_]>>();
560 covered.extend(maybe_point_at_variant(ty, &pats));
562 Leaf { subpatterns } => {
563 let pats = subpatterns
565 .map(|field_pattern| field_pattern.pattern.clone())
566 .collect::<Box<[_]>>();
567 covered.extend(maybe_point_at_variant(ty, &pats));
570 let pats = pats.iter().cloned().collect::<Box<[_]>>();
571 covered.extend(maybe_point_at_variant(ty, &pats));
580 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
581 fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> bool {
582 !cx.tables.node_type(hir_id).is_copy_modulo_regions(cx.tcx, cx.param_env, span)
585 /// Check the legality of legality of by-move bindings.
586 fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: bool, pat: &Pat<'_>) {
587 let sess = cx.tcx.sess;
588 let tables = cx.tables;
590 // Find all by-ref spans.
591 let mut by_ref_spans = Vec::new();
592 pat.each_binding(|_, hir_id, span, _| {
593 if let Some(ty::BindByReference(_)) = tables.extract_binding_mode(sess, hir_id, span) {
594 by_ref_spans.push(span);
598 // Find bad by-move spans:
599 let by_move_spans = &mut Vec::new();
600 let mut check_move = |p: &Pat<'_>, sub: Option<&Pat<'_>>| {
601 // Check legality of moving out of the enum.
603 // `x @ Foo(..)` is legal, but `x @ Foo(y)` isn't.
604 if sub.map_or(false, |p| p.contains_bindings()) {
605 struct_span_err!(sess, p.span, E0007, "cannot bind by-move with sub-bindings")
606 .span_label(p.span, "binds an already bound by-move value by moving it")
608 } else if !has_guard && !by_ref_spans.is_empty() {
609 by_move_spans.push(p.span);
612 pat.walk_always(|p| {
613 if let hir::PatKind::Binding(.., sub) = &p.kind {
614 if let Some(ty::BindByValue(_)) = tables.extract_binding_mode(sess, p.hir_id, p.span) {
615 if is_binding_by_move(cx, p.hir_id, p.span) {
616 check_move(p, sub.as_deref());
622 // Found some bad by-move spans, error!
623 if !by_move_spans.is_empty() {
624 let mut err = feature_err(
626 sym::move_ref_pattern,
627 by_move_spans.clone(),
628 "binding by-move and by-ref in the same pattern is unstable",
630 for span in by_ref_spans.iter() {
631 err.span_label(*span, "by-ref pattern here");
633 for span in by_move_spans.iter() {
634 err.span_label(*span, "by-move pattern here");
640 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
642 /// For example, this would reject:
643 /// - `ref x @ Some(ref mut y)`,
644 /// - `ref mut x @ Some(ref y)`,
645 /// - `ref mut x @ Some(ref mut y)`,
646 /// - `ref mut? x @ Some(y)`, and
647 /// - `x @ Some(ref mut? y)`.
649 /// This analysis is *not* subsumed by NLL.
650 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
651 // Extract `sub` in `binding @ sub`.
652 let (name, sub) = match &pat.kind {
653 hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
656 let binding_span = pat.span.with_hi(name.span.hi());
658 let tables = cx.tables;
659 let sess = cx.tcx.sess;
661 // Get the binding move, extract the mutability if by-ref.
662 let mut_outer = match tables.extract_binding_mode(sess, pat.hir_id, pat.span) {
663 Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
664 // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
665 let mut conflicts_ref = Vec::new();
666 sub.each_binding(|_, hir_id, span, _| {
667 match tables.extract_binding_mode(sess, hir_id, span) {
668 Some(ty::BindByValue(_)) | None => {}
669 Some(ty::BindByReference(_)) => conflicts_ref.push(span),
672 if !conflicts_ref.is_empty() {
673 let occurs_because = format!(
674 "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
676 tables.node_type(pat.hir_id),
678 sess.struct_span_err(pat.span, "borrow of moved value")
679 .span_label(binding_span, format!("value moved into `{}` here", name))
680 .span_label(binding_span, occurs_because)
681 .span_labels(conflicts_ref, "value borrowed here after move")
686 Some(ty::BindByValue(_)) | None => return,
687 Some(ty::BindByReference(m)) => m,
690 // We now have `ref $mut_outer binding @ sub` (semantically).
691 // Recurse into each binding in `sub` and find mutability or move conflicts.
692 let mut conflicts_move = Vec::new();
693 let mut conflicts_mut_mut = Vec::new();
694 let mut conflicts_mut_ref = Vec::new();
695 sub.each_binding(|_, hir_id, span, name| {
696 match tables.extract_binding_mode(sess, hir_id, span) {
697 Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
698 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
699 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
700 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
702 Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
703 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
705 Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
709 // Report errors if any.
710 if !conflicts_mut_mut.is_empty() {
711 // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
713 .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
714 err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
715 for (span, name) in conflicts_mut_mut {
716 err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
718 for (span, name) in conflicts_mut_ref {
719 err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
721 for (span, name) in conflicts_move {
722 err.span_label(span, format!("also moved into `{}` here", name));
725 } else if !conflicts_mut_ref.is_empty() {
726 // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
727 let (primary, also) = match mut_outer {
728 Mutability::Mut => ("mutable", "immutable"),
729 Mutability::Not => ("immutable", "mutable"),
732 format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
733 let mut err = sess.struct_span_err(pat.span, &msg);
734 err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
735 for (span, name) in conflicts_mut_ref {
736 err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
738 for (span, name) in conflicts_move {
739 err.span_label(span, format!("also moved into `{}` here", name));
742 } else if !conflicts_move.is_empty() {
743 // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
745 sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
746 err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
747 for (span, name) in conflicts_move {
748 err.span_label(span, format!("value moved into `{}` here", name));
754 /// Forbids bindings in `@` patterns. This used to be is necessary for memory safety,
755 /// because of the way rvalues were handled in the borrow check. (See issue #14587.)
756 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
757 AtBindingPatternVisitor { cx, bindings_allowed: true }.visit_pat(pat);
759 struct AtBindingPatternVisitor<'a, 'b, 'tcx> {
760 cx: &'a MatchVisitor<'b, 'tcx>,
761 bindings_allowed: bool,
764 impl<'v> Visitor<'v> for AtBindingPatternVisitor<'_, '_, '_> {
765 type Map = intravisit::ErasedMap<'v>;
767 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
768 NestedVisitorMap::None
771 fn visit_pat(&mut self, pat: &Pat<'_>) {
773 hir::PatKind::Binding(.., ref subpat) => {
774 if !self.bindings_allowed {
776 &self.cx.tcx.sess.parse_sess,
777 sym::bindings_after_at,
779 "pattern bindings after an `@` are unstable",
784 if subpat.is_some() {
785 let bindings_were_allowed = self.bindings_allowed;
786 self.bindings_allowed = false;
787 intravisit::walk_pat(self, pat);
788 self.bindings_allowed = bindings_were_allowed;
791 _ => intravisit::walk_pat(self, pat),