1 //! Borrow checker diagnostics.
3 use rustc_errors::DiagnosticBuilder;
5 use rustc_hir::def::Namespace;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::GeneratorKind;
8 use rustc_middle::mir::{
9 AggregateKind, Constant, Field, Local, LocalInfo, LocalKind, Location, Operand, Place,
10 PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
12 use rustc_middle::ty::print::Print;
13 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt};
14 use rustc_span::{symbol::sym, Span};
15 use rustc_target::abi::VariantIdx;
17 use super::borrow_set::BorrowData;
18 use super::MirBorrowckCtxt;
19 use crate::dataflow::move_paths::{InitLocation, LookupResult};
22 mod outlives_suggestion;
29 mod mutability_errors;
32 crate use mutability_errors::AccessKind;
33 crate use outlives_suggestion::OutlivesSuggestionBuilder;
34 crate use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
35 crate use region_name::{RegionName, RegionNameSource};
37 pub(super) struct IncludingDowncast(pub(super) bool);
39 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
40 /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
41 /// is moved after being invoked.
44 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
46 /// --> $DIR/issue-42065.rs:16:29
48 /// LL | for (key, value) in dict {
51 pub(super) fn add_moved_or_invoked_closure_note(
54 place: PlaceRef<'tcx>,
55 diag: &mut DiagnosticBuilder<'_>,
57 debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
58 let mut target = place.local_or_deref_local();
59 for stmt in &self.body[location.block].statements[location.statement_index..] {
60 debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
61 if let StatementKind::Assign(box (into, Rvalue::Use(from))) = &stmt.kind {
62 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
64 Operand::Copy(ref place) | Operand::Move(ref place)
65 if target == place.local_or_deref_local() =>
67 target = into.local_or_deref_local()
74 // Check if we are attempting to call a closure after it has been invoked.
75 let terminator = self.body[location.block].terminator();
76 debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
77 if let TerminatorKind::Call {
79 Operand::Constant(box Constant {
80 literal: ty::Const { ty: &ty::TyS { kind: ty::FnDef(id, _), .. }, .. },
87 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
88 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
89 let closure = match args.first() {
90 Some(Operand::Copy(ref place)) | Some(Operand::Move(ref place))
91 if target == place.local_or_deref_local() =>
93 place.local_or_deref_local().unwrap()
98 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
99 if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind {
100 let did = did.expect_local();
101 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did);
103 if let Some((span, name)) =
104 self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id)
109 "closure cannot be invoked more than once because it moves the \
110 variable `{}` out of its environment",
120 // Check if we are just moving a closure after it has been invoked.
121 if let Some(target) = target {
122 if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind {
123 let did = did.expect_local();
124 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did);
126 if let Some((span, name)) =
127 self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id)
132 "closure cannot be moved more than once as it is not `Copy` due to \
133 moving the variable `{}` out of its environment",
142 /// End-user visible description of `place` if one can be found.
143 /// If the place is a temporary for instance, `"value"` will be returned.
144 pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
145 match self.describe_place(place_ref) {
147 // Surround descr with `backticks`.
149 descr.insert_str(0, "`");
153 None => "value".to_string(),
157 /// End-user visible description of `place` if one can be found.
158 /// If the place is a temporary for instance, None will be returned.
159 pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
160 self.describe_place_with_options(place_ref, IncludingDowncast(false))
163 /// End-user visible description of `place` if one can be found. If the
164 /// place is a temporary for instance, None will be returned.
165 /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
166 /// `Downcast` and `IncludingDowncast` is true
167 pub(super) fn describe_place_with_options(
169 place: PlaceRef<'tcx>,
170 including_downcast: IncludingDowncast,
171 ) -> Option<String> {
172 let mut buf = String::new();
173 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
179 /// Appends end-user visible description of `place` to `buf`.
180 fn append_place_to_string(
182 place: PlaceRef<'tcx>,
185 including_downcast: &IncludingDowncast,
186 ) -> Result<(), ()> {
188 PlaceRef { local, projection: [] } => {
189 self.append_local_to_string(local, buf)?;
191 PlaceRef { local, projection: [ProjectionElem::Deref] }
192 if self.body.local_decls[local].is_ref_for_guard() =>
194 self.append_place_to_string(
195 PlaceRef { local, projection: &[] },
201 PlaceRef { local, projection: [ProjectionElem::Deref] }
202 if self.body.local_decls[local].is_ref_to_static() =>
204 let local_info = &self.body.local_decls[local].local_info;
205 if let Some(box LocalInfo::StaticRef { def_id, .. }) = *local_info {
206 buf.push_str(&self.infcx.tcx.item_name(def_id).as_str());
211 PlaceRef { local, projection: [proj_base @ .., elem] } => {
213 ProjectionElem::Deref => {
214 let upvar_field_projection = self.is_upvar_field_projection(place);
215 if let Some(field) = upvar_field_projection {
216 let var_index = field.index();
217 let name = self.upvars[var_index].name.to_string();
218 if self.upvars[var_index].by_ref {
221 buf.push_str(&format!("*{}", &name));
225 // FIXME turn this recursion into iteration
226 self.append_place_to_string(
227 PlaceRef { local, projection: proj_base },
234 self.append_place_to_string(
235 PlaceRef { local, projection: proj_base },
243 ProjectionElem::Downcast(..) => {
244 self.append_place_to_string(
245 PlaceRef { local, projection: proj_base },
250 if including_downcast.0 {
254 ProjectionElem::Field(field, _ty) => {
257 let upvar_field_projection = self.is_upvar_field_projection(place);
258 if let Some(field) = upvar_field_projection {
259 let var_index = field.index();
260 let name = self.upvars[var_index].name.to_string();
263 let field_name = self
264 .describe_field(PlaceRef { local, projection: proj_base }, *field);
265 self.append_place_to_string(
266 PlaceRef { local, projection: proj_base },
271 buf.push_str(&format!(".{}", field_name));
274 ProjectionElem::Index(index) => {
277 self.append_place_to_string(
278 PlaceRef { local, projection: proj_base },
284 if self.append_local_to_string(*index, buf).is_err() {
289 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
291 // Since it isn't possible to borrow an element on a particular index and
292 // then use another while the borrow is held, don't output indices details
293 // to avoid confusing the end-user
294 self.append_place_to_string(
295 PlaceRef { local, projection: proj_base },
300 buf.push_str(&"[..]");
309 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
310 /// a name, or its name was generated by the compiler, then `Err` is returned
311 fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
312 let decl = &self.body.local_decls[local];
313 match self.local_names[local] {
314 Some(name) if !decl.from_compiler_desugaring() => {
315 buf.push_str(&name.as_str());
322 /// End-user visible description of the `field`nth field of `base`
323 fn describe_field(&self, place: PlaceRef<'tcx>, field: Field) -> String {
324 // FIXME Place2 Make this work iteratively
326 PlaceRef { local, projection: [] } => {
327 let local = &self.body.local_decls[local];
328 self.describe_field_from_ty(&local.ty, field, None)
330 PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
331 ProjectionElem::Deref => {
332 self.describe_field(PlaceRef { local, projection: proj_base }, field)
334 ProjectionElem::Downcast(_, variant_index) => {
336 Place::ty_from(place.local, place.projection, self.body, self.infcx.tcx).ty;
337 self.describe_field_from_ty(&base_ty, field, Some(*variant_index))
339 ProjectionElem::Field(_, field_type) => {
340 self.describe_field_from_ty(&field_type, field, None)
342 ProjectionElem::Index(..)
343 | ProjectionElem::ConstantIndex { .. }
344 | ProjectionElem::Subslice { .. } => {
345 self.describe_field(PlaceRef { local, projection: proj_base }, field)
351 /// End-user visible description of the `field_index`nth field of `ty`
352 fn describe_field_from_ty(
356 variant_index: Option<VariantIdx>,
359 // If the type is a box, the field is described from the boxed type
360 self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
364 let variant = if let Some(idx) = variant_index {
365 assert!(def.is_enum());
368 def.non_enum_variant()
370 variant.fields[field.index()].ident.to_string()
372 ty::Tuple(_) => field.index().to_string(),
373 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
374 self.describe_field_from_ty(&ty, field, variant_index)
376 ty::Array(ty, _) | ty::Slice(ty) => {
377 self.describe_field_from_ty(&ty, field, variant_index)
379 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
380 // `tcx.upvars(def_id)` returns an `Option`, which is `None` in case
381 // the closure comes from another crate. But in that case we wouldn't
382 // be borrowck'ing it, so we can just unwrap:
384 self.infcx.tcx.upvars(def_id).unwrap().get_index(field.index()).unwrap();
386 self.infcx.tcx.hir().name(var_id).to_string()
389 // Might need a revision when the fields in trait RFC is implemented
390 // (https://github.com/rust-lang/rfcs/pull/1546)
391 bug!("End-user description not implemented for field access on `{:?}`", ty);
397 /// Add a note that a type does not implement `Copy`
398 pub(super) fn note_type_does_not_implement_copy(
400 err: &mut DiagnosticBuilder<'a>,
405 let message = format!(
406 "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
409 if let Some(span) = span {
410 err.span_label(span, message);
416 pub(super) fn borrowed_content_source(
418 deref_base: PlaceRef<'tcx>,
419 ) -> BorrowedContentSource<'tcx> {
420 let tcx = self.infcx.tcx;
422 // Look up the provided place and work out the move path index for it,
423 // we'll use this to check whether it was originally from an overloaded
425 match self.move_data.rev_lookup.find(deref_base) {
426 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
427 debug!("borrowed_content_source: mpi={:?}", mpi);
429 for i in &self.move_data.init_path_map[mpi] {
430 let init = &self.move_data.inits[*i];
431 debug!("borrowed_content_source: init={:?}", init);
432 // We're only interested in statements that initialized a value, not the
433 // initializations from arguments.
434 let loc = match init.location {
435 InitLocation::Statement(stmt) => stmt,
439 let bbd = &self.body[loc.block];
440 let is_terminator = bbd.statements.len() == loc.statement_index;
442 "borrowed_content_source: loc={:?} is_terminator={:?}",
447 } else if let Some(Terminator {
448 kind: TerminatorKind::Call { ref func, from_hir_call: false, .. },
452 if let Some(source) =
453 BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
460 // Base is a `static` so won't be from an overloaded operator
464 // If we didn't find an overloaded deref or index, then assume it's a
465 // built in deref and check the type of the base.
466 let base_ty = Place::ty_from(deref_base.local, deref_base.projection, self.body, tcx).ty;
467 if base_ty.is_unsafe_ptr() {
468 BorrowedContentSource::DerefRawPointer
469 } else if base_ty.is_mutable_ptr() {
470 BorrowedContentSource::DerefMutableRef
472 BorrowedContentSource::DerefSharedRef
477 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
478 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
479 /// name where required.
480 pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
481 let mut s = String::new();
482 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
484 // We need to add synthesized lifetimes where appropriate. We do
485 // this by hooking into the pretty printer and telling it to label the
486 // lifetimes without names with the value `'0`.
489 ty::RegionKind::ReLateBound(_, br)
490 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
493 ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
497 let _ = ty.print(printer);
501 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
502 /// synthesized lifetime name where required.
503 pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
504 let mut s = String::new();
505 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
507 let region = match ty.kind {
508 ty::Ref(region, _, _) => {
510 ty::RegionKind::ReLateBound(_, br)
511 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
512 printer.region_highlight_mode.highlighting_bound_region(*br, counter)
519 _ => bug!("ty for annotation of borrow region is not a reference"),
522 let _ = region.print(printer);
527 // The span(s) associated to a use of a place.
528 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
529 pub(super) enum UseSpans {
530 // The access is caused by capturing a variable for a closure.
532 // This is true if the captured variable was from a generator.
533 generator_kind: Option<GeneratorKind>,
534 // The span of the args of the closure, including the `move` keyword if
537 // The span of the first use of the captured variable inside the closure.
540 // This access has a single span associated to it: common case.
545 pub(super) fn args_or_use(self) -> Span {
547 UseSpans::ClosureUse { args_span: span, .. } | UseSpans::OtherUse(span) => span,
551 pub(super) fn var_or_use(self) -> Span {
553 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
557 pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
559 UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
564 // Add a span label to the arguments of the closure, if it exists.
565 pub(super) fn args_span_label(
567 err: &mut DiagnosticBuilder<'_>,
568 message: impl Into<String>,
570 if let UseSpans::ClosureUse { args_span, .. } = self {
571 err.span_label(args_span, message);
575 // Add a span label to the use of the captured variable, if it exists.
576 pub(super) fn var_span_label(
578 err: &mut DiagnosticBuilder<'_>,
579 message: impl Into<String>,
581 if let UseSpans::ClosureUse { var_span, .. } = self {
582 err.span_label(var_span, message);
586 /// Returns `false` if this place is not used in a closure.
587 pub(super) fn for_closure(&self) -> bool {
589 UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(),
594 /// Returns `false` if this place is not used in a generator.
595 pub(super) fn for_generator(&self) -> bool {
597 UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(),
602 /// Describe the span associated with a use of a place.
603 pub(super) fn describe(&self) -> String {
605 UseSpans::ClosureUse { generator_kind, .. } => {
606 if generator_kind.is_some() {
607 " in generator".to_string()
609 " in closure".to_string()
616 pub(super) fn or_else<F>(self, if_other: F) -> Self
621 closure @ UseSpans::ClosureUse { .. } => closure,
622 UseSpans::OtherUse(_) => if_other(),
627 pub(super) enum BorrowedContentSource<'tcx> {
631 OverloadedDeref(Ty<'tcx>),
632 OverloadedIndex(Ty<'tcx>),
635 impl BorrowedContentSource<'tcx> {
636 pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
638 BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
639 BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
640 BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
641 BorrowedContentSource::OverloadedDeref(ty) => match ty.kind {
642 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Rc, def.did) => {
643 "an `Rc`".to_string()
645 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Arc, def.did) => {
646 "an `Arc`".to_string()
648 _ => format!("dereference of `{}`", ty),
650 BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
654 pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
656 BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
657 BorrowedContentSource::DerefSharedRef => Some("shared reference"),
658 BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
659 // Overloaded deref and index operators should be evaluated into a
660 // temporary. So we don't need a description here.
661 BorrowedContentSource::OverloadedDeref(_)
662 | BorrowedContentSource::OverloadedIndex(_) => None,
666 pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
668 BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
669 BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
670 BorrowedContentSource::DerefMutableRef => {
671 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
673 BorrowedContentSource::OverloadedDeref(ty) => match ty.kind {
674 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Rc, def.did) => {
675 "an `Rc`".to_string()
677 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Arc, def.did) => {
678 "an `Arc`".to_string()
680 _ => format!("a dereference of `{}`", ty),
682 BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
686 fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
688 ty::FnDef(def_id, substs) => {
689 let trait_id = tcx.trait_of_item(def_id)?;
691 let lang_items = tcx.lang_items();
692 if Some(trait_id) == lang_items.deref_trait()
693 || Some(trait_id) == lang_items.deref_mut_trait()
695 Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
696 } else if Some(trait_id) == lang_items.index_trait()
697 || Some(trait_id) == lang_items.index_mut_trait()
699 Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
709 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
710 /// Finds the spans associated to a move or copy of move_place at location.
711 pub(super) fn move_spans(
713 moved_place: PlaceRef<'tcx>, // Could also be an upvar.
716 use self::UseSpans::*;
718 let stmt = match self.body[location.block].statements.get(location.statement_index) {
720 None => return OtherUse(self.body.source_info(location).span),
723 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
724 if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) = stmt.kind {
725 let def_id = match kind {
726 box AggregateKind::Closure(def_id, _)
727 | box AggregateKind::Generator(def_id, _, _) => def_id,
728 _ => return OtherUse(stmt.source_info.span),
731 debug!("move_spans: def_id={:?} places={:?}", def_id, places);
732 if let Some((args_span, generator_kind, var_span)) =
733 self.closure_span(*def_id, moved_place, places)
735 return ClosureUse { generator_kind, args_span, var_span };
739 OtherUse(stmt.source_info.span)
742 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
743 /// and its usage of the local assigned at `location`.
744 /// This is done by searching in statements succeeding `location`
745 /// and originating from `maybe_closure_span`.
746 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
747 use self::UseSpans::*;
748 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
750 let target = match self.body[location.block].statements.get(location.statement_index) {
751 Some(&Statement { kind: StatementKind::Assign(box (ref place, _)), .. }) => {
752 if let Some(local) = place.as_local() {
755 return OtherUse(use_span);
758 _ => return OtherUse(use_span),
761 if self.body.local_kind(target) != LocalKind::Temp {
762 // operands are always temporaries.
763 return OtherUse(use_span);
766 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
767 if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) =
770 let (def_id, is_generator) = match kind {
771 box AggregateKind::Closure(def_id, _) => (def_id, false),
772 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
777 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
778 def_id, is_generator, places
780 if let Some((args_span, generator_kind, var_span)) =
781 self.closure_span(*def_id, Place::from(target).as_ref(), places)
783 return ClosureUse { generator_kind, args_span, var_span };
785 return OtherUse(use_span);
789 if use_span != stmt.source_info.span {
797 /// Finds the span of a captured variable within a closure or generator.
801 target_place: PlaceRef<'tcx>,
802 places: &Vec<Operand<'tcx>>,
803 ) -> Option<(Span, Option<GeneratorKind>, Span)> {
805 "closure_span: def_id={:?} target_place={:?} places={:?}",
806 def_id, target_place, places
808 let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id.as_local()?);
809 let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
810 debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
811 if let hir::ExprKind::Closure(.., body_id, args_span, _) = expr {
812 for (upvar, place) in self.infcx.tcx.upvars(def_id)?.values().zip(places) {
814 Operand::Copy(place) | Operand::Move(place)
815 if target_place == place.as_ref() =>
817 debug!("closure_span: found captured local {:?}", place);
818 let body = self.infcx.tcx.hir().body(*body_id);
819 let generator_kind = body.generator_kind();
820 return Some((*args_span, generator_kind, upvar.span));
829 /// Helper to retrieve span(s) of given borrow from the current MIR
831 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans {
832 let span = self.body.source_info(borrow.reserve_location).span;
833 self.borrow_spans(span, borrow.reserve_location)