1 //! Borrow checker diagnostics.
3 use crate::session_diagnostics
::{
4 CaptureArgLabel
, CaptureReasonLabel
, CaptureReasonNote
, CaptureReasonSuggest
, CaptureVarCause
,
5 CaptureVarKind
, CaptureVarPathUseCause
, OnClosureNote
,
7 use itertools
::Itertools
;
8 use rustc_errors
::{Applicability, Diagnostic}
;
10 use rustc_hir
::def
::{CtorKind, Namespace}
;
11 use rustc_hir
::GeneratorKind
;
12 use rustc_index
::IndexSlice
;
13 use rustc_infer
::infer
::LateBoundRegionConversionTime
;
14 use rustc_middle
::mir
::tcx
::PlaceTy
;
15 use rustc_middle
::mir
::{
16 AggregateKind
, CallSource
, ConstOperand
, FakeReadCause
, Local
, LocalInfo
, LocalKind
, Location
,
17 Operand
, Place
, PlaceRef
, ProjectionElem
, Rvalue
, Statement
, StatementKind
, Terminator
,
20 use rustc_middle
::ty
::print
::Print
;
21 use rustc_middle
::ty
::{self, Instance, Ty, TyCtxt}
;
22 use rustc_middle
::util
::{call_kind, CallDesugaringKind}
;
23 use rustc_mir_dataflow
::move_paths
::{InitLocation, LookupResult}
;
24 use rustc_span
::def_id
::LocalDefId
;
25 use rustc_span
::{symbol::sym, Span, Symbol, DUMMY_SP}
;
26 use rustc_target
::abi
::{FieldIdx, VariantIdx}
;
27 use rustc_trait_selection
::traits
::query
::evaluate_obligation
::InferCtxtExt
;
28 use rustc_trait_selection
::traits
::{
29 type_known_to_meet_bound_modulo_regions
, Obligation
, ObligationCause
,
32 use super::borrow_set
::BorrowData
;
33 use super::MirBorrowckCtxt
;
35 mod find_all_local_uses
;
37 mod outlives_suggestion
;
41 mod bound_region_errors
;
45 mod mutability_errors
;
48 pub(crate) use bound_region_errors
::{ToUniverseInfo, UniverseInfo}
;
49 pub(crate) use mutability_errors
::AccessKind
;
50 pub(crate) use outlives_suggestion
::OutlivesSuggestionBuilder
;
51 pub(crate) use region_errors
::{ErrorConstraintInfo, RegionErrorKind, RegionErrors}
;
52 pub(crate) use region_name
::{RegionName, RegionNameSource}
;
53 pub(crate) use rustc_middle
::util
::CallKind
;
55 pub(super) struct DescribePlaceOpt
{
56 pub including_downcast
: bool
,
58 /// Enable/Disable tuple fields.
59 /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x`
60 pub including_tuple_field
: bool
,
63 pub(super) struct IncludingTupleField(pub(super) bool
);
65 impl<'cx
, 'tcx
> MirBorrowckCtxt
<'cx
, 'tcx
> {
66 /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
67 /// is moved after being invoked.
70 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
72 /// --> $DIR/issue-42065.rs:16:29
74 /// LL | for (key, value) in dict {
77 pub(super) fn add_moved_or_invoked_closure_note(
80 place
: PlaceRef
<'tcx
>,
81 diag
: &mut Diagnostic
,
83 debug
!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location
, place
);
84 let mut target
= place
.local_or_deref_local();
85 for stmt
in &self.body
[location
.block
].statements
[location
.statement_index
..] {
86 debug
!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt
, target
);
87 if let StatementKind
::Assign(box (into
, Rvalue
::Use(from
))) = &stmt
.kind
{
88 debug
!("add_fnonce_closure_note: into={:?} from={:?}", into
, from
);
90 Operand
::Copy(place
) | Operand
::Move(place
)
91 if target
== place
.local_or_deref_local() =>
93 target
= into
.local_or_deref_local()
100 // Check if we are attempting to call a closure after it has been invoked.
101 let terminator
= self.body
[location
.block
].terminator();
102 debug
!("add_moved_or_invoked_closure_note: terminator={:?}", terminator
);
103 if let TerminatorKind
::Call
{
104 func
: Operand
::Constant(box ConstOperand { const_, .. }
),
109 if let ty
::FnDef(id
, _
) = *const_
.ty().kind() {
110 debug
!("add_moved_or_invoked_closure_note: id={:?}", id
);
111 if Some(self.infcx
.tcx
.parent(id
)) == self.infcx
.tcx
.lang_items().fn_once_trait() {
112 let closure
= match args
.first() {
113 Some(Operand
::Copy(place
) | Operand
::Move(place
))
114 if target
== place
.local_or_deref_local() =>
116 place
.local_or_deref_local().unwrap()
121 debug
!("add_moved_or_invoked_closure_note: closure={:?}", closure
);
122 if let ty
::Closure(did
, _
) = self.body
.local_decls
[closure
].ty
.kind() {
123 let did
= did
.expect_local();
124 if let Some((span
, hir_place
)) = self.infcx
.tcx
.closure_kind_origin(did
) {
125 diag
.eager_subdiagnostic(
126 &self.infcx
.tcx
.sess
.parse_sess
.span_diagnostic
,
127 OnClosureNote
::InvokedTwice
{
128 place_name
: &ty
::place_to_string_for_capture(
142 // Check if we are just moving a closure after it has been invoked.
143 if let Some(target
) = target
{
144 if let ty
::Closure(did
, _
) = self.body
.local_decls
[target
].ty
.kind() {
145 let did
= did
.expect_local();
146 if let Some((span
, hir_place
)) = self.infcx
.tcx
.closure_kind_origin(did
) {
147 diag
.eager_subdiagnostic(
148 &self.infcx
.tcx
.sess
.parse_sess
.span_diagnostic
,
149 OnClosureNote
::MovedTwice
{
150 place_name
: &ty
::place_to_string_for_capture(self.infcx
.tcx
, hir_place
),
161 /// End-user visible description of `place` if one can be found.
162 /// If the place is a temporary for instance, `"value"` will be returned.
163 pub(super) fn describe_any_place(&self, place_ref
: PlaceRef
<'tcx
>) -> String
{
164 match self.describe_place(place_ref
) {
166 // Surround descr with `backticks`.
168 descr
.insert(0, '`'
);
172 None
=> "value".to_string(),
176 /// End-user visible description of `place` if one can be found.
177 /// If the place is a temporary for instance, `None` will be returned.
178 pub(super) fn describe_place(&self, place_ref
: PlaceRef
<'tcx
>) -> Option
<String
> {
179 self.describe_place_with_options(
181 DescribePlaceOpt { including_downcast: false, including_tuple_field: true }
,
185 /// End-user visible description of `place` if one can be found. If the place is a temporary
186 /// for instance, `None` will be returned.
187 /// `IncludingDowncast` parameter makes the function return `None` if `ProjectionElem` is
188 /// `Downcast` and `IncludingDowncast` is true
189 pub(super) fn describe_place_with_options(
191 place
: PlaceRef
<'tcx
>,
192 opt
: DescribePlaceOpt
,
193 ) -> Option
<String
> {
194 let local
= place
.local
;
195 let mut autoderef_index
= None
;
196 let mut buf
= String
::new();
197 let mut ok
= self.append_local_to_string(local
, &mut buf
);
199 for (index
, elem
) in place
.projection
.into_iter().enumerate() {
201 ProjectionElem
::Deref
=> {
203 if self.body
.local_decls
[local
].is_ref_for_guard() {
206 if let LocalInfo
::StaticRef { def_id, .. }
=
207 *self.body
.local_decls
[local
].local_info()
209 buf
.push_str(self.infcx
.tcx
.item_name(def_id
).as_str());
214 if let Some(field
) = self.is_upvar_field_projection(PlaceRef
{
216 projection
: place
.projection
.split_at(index
+ 1).0,
218 let var_index
= field
.index();
219 buf
= self.upvars
[var_index
].place
.to_string(self.infcx
.tcx
);
221 if !self.upvars
[var_index
].by_ref
{
225 if autoderef_index
.is_none() {
227 match place
.projection
.into_iter().rev().find_position(|elem
| {
230 ProjectionElem
::Deref
| ProjectionElem
::Downcast(..)
233 Some((index
, _
)) => Some(place
.projection
.len() - index
),
237 if index
>= autoderef_index
.unwrap() {
242 ProjectionElem
::Downcast(..) if opt
.including_downcast
=> return None
,
243 ProjectionElem
::Downcast(..) => (),
244 ProjectionElem
::OpaqueCast(..) => (),
245 ProjectionElem
::Subtype(..) => (),
246 ProjectionElem
::Field(field
, _ty
) => {
247 // FIXME(project-rfc_2229#36): print capture precisely here.
248 if let Some(field
) = self.is_upvar_field_projection(PlaceRef
{
250 projection
: place
.projection
.split_at(index
+ 1).0,
252 buf
= self.upvars
[field
.index()].place
.to_string(self.infcx
.tcx
);
255 let field_name
= self.describe_field(
256 PlaceRef { local, projection: place.projection.split_at(index).0 }
,
258 IncludingTupleField(opt
.including_tuple_field
),
260 if let Some(field_name_str
) = field_name
{
262 buf
.push_str(&field_name_str
);
266 ProjectionElem
::Index(index
) => {
268 if self.append_local_to_string(*index
, &mut buf
).is_err() {
273 ProjectionElem
::ConstantIndex { .. }
| ProjectionElem
::Subslice { .. }
=> {
274 // Since it isn't possible to borrow an element on a particular index and
275 // then use another while the borrow is held, don't output indices details
276 // to avoid confusing the end-user
277 buf
.push_str("[..]");
284 fn describe_name(&self, place
: PlaceRef
<'tcx
>) -> Option
<Symbol
> {
285 for elem
in place
.projection
.into_iter() {
287 ProjectionElem
::Downcast(Some(name
), _
) => {
296 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
297 /// a name, or its name was generated by the compiler, then `Err` is returned
298 fn append_local_to_string(&self, local
: Local
, buf
: &mut String
) -> Result
<(), ()> {
299 let decl
= &self.body
.local_decls
[local
];
300 match self.local_names
[local
] {
301 Some(name
) if !decl
.from_compiler_desugaring() => {
302 buf
.push_str(name
.as_str());
309 /// End-user visible description of the `field`nth field of `base`
312 place
: PlaceRef
<'tcx
>,
314 including_tuple_field
: IncludingTupleField
,
315 ) -> Option
<String
> {
316 let place_ty
= match place
{
317 PlaceRef { local, projection: [] }
=> PlaceTy
::from_ty(self.body
.local_decls
[local
].ty
),
318 PlaceRef { local, projection: [proj_base @ .., elem] }
=> match elem
{
319 ProjectionElem
::Deref
320 | ProjectionElem
::Index(..)
321 | ProjectionElem
::ConstantIndex { .. }
322 | ProjectionElem
::Subslice { .. }
=> {
323 PlaceRef { local, projection: proj_base }
.ty(self.body
, self.infcx
.tcx
)
325 ProjectionElem
::Downcast(..) => place
.ty(self.body
, self.infcx
.tcx
),
326 ProjectionElem
::Subtype(ty
) | ProjectionElem
::OpaqueCast(ty
) => {
327 PlaceTy
::from_ty(*ty
)
329 ProjectionElem
::Field(_
, field_type
) => PlaceTy
::from_ty(*field_type
),
332 self.describe_field_from_ty(
335 place_ty
.variant_index
,
336 including_tuple_field
,
340 /// End-user visible description of the `field_index`nth field of `ty`
341 fn describe_field_from_ty(
345 variant_index
: Option
<VariantIdx
>,
346 including_tuple_field
: IncludingTupleField
,
347 ) -> Option
<String
> {
349 // If the type is a box, the field is described from the boxed type
350 self.describe_field_from_ty(ty
.boxed_ty(), field
, variant_index
, including_tuple_field
)
354 let variant
= if let Some(idx
) = variant_index
{
355 assert
!(def
.is_enum());
358 def
.non_enum_variant()
360 if !including_tuple_field
.0 && variant
.ctor_kind() == Some(CtorKind
::Fn
) {
363 Some(variant
.fields
[field
].name
.to_string())
365 ty
::Tuple(_
) => Some(field
.index().to_string()),
366 ty
::Ref(_
, ty
, _
) | ty
::RawPtr(ty
::TypeAndMut { ty, .. }
) => {
367 self.describe_field_from_ty(ty
, field
, variant_index
, including_tuple_field
)
369 ty
::Array(ty
, _
) | ty
::Slice(ty
) => {
370 self.describe_field_from_ty(ty
, field
, variant_index
, including_tuple_field
)
372 ty
::Closure(def_id
, _
) | ty
::Generator(def_id
, _
, _
) => {
373 // We won't be borrowck'ing here if the closure came from another crate,
374 // so it's safe to call `expect_local`.
376 // We know the field exists so it's safe to call operator[] and `unwrap` here.
377 let def_id
= def_id
.expect_local();
379 self.infcx
.tcx
.closure_captures(def_id
)[field
.index()].get_root_variable();
381 Some(self.infcx
.tcx
.hir().name(var_id
).to_string())
384 // Might need a revision when the fields in trait RFC is implemented
385 // (https://github.com/rust-lang/rfcs/pull/1546)
386 bug
!("End-user description not implemented for field access on `{:?}`", ty
);
392 pub(super) fn borrowed_content_source(
394 deref_base
: PlaceRef
<'tcx
>,
395 ) -> BorrowedContentSource
<'tcx
> {
396 let tcx
= self.infcx
.tcx
;
398 // Look up the provided place and work out the move path index for it,
399 // we'll use this to check whether it was originally from an overloaded
401 match self.move_data
.rev_lookup
.find(deref_base
) {
402 LookupResult
::Exact(mpi
) | LookupResult
::Parent(Some(mpi
)) => {
403 debug
!("borrowed_content_source: mpi={:?}", mpi
);
405 for i
in &self.move_data
.init_path_map
[mpi
] {
406 let init
= &self.move_data
.inits
[*i
];
407 debug
!("borrowed_content_source: init={:?}", init
);
408 // We're only interested in statements that initialized a value, not the
409 // initializations from arguments.
410 let InitLocation
::Statement(loc
) = init
.location
else { continue }
;
412 let bbd
= &self.body
[loc
.block
];
413 let is_terminator
= bbd
.statements
.len() == loc
.statement_index
;
415 "borrowed_content_source: loc={:?} is_terminator={:?}",
420 } else if let Some(Terminator
{
422 TerminatorKind
::Call
{
424 call_source
: CallSource
::OverloadedOperator
,
430 if let Some(source
) =
431 BorrowedContentSource
::from_call(func
.ty(self.body
, tcx
), tcx
)
438 // Base is a `static` so won't be from an overloaded operator
442 // If we didn't find an overloaded deref or index, then assume it's a
443 // built in deref and check the type of the base.
444 let base_ty
= deref_base
.ty(self.body
, tcx
).ty
;
445 if base_ty
.is_unsafe_ptr() {
446 BorrowedContentSource
::DerefRawPointer
447 } else if base_ty
.is_mutable_ptr() {
448 BorrowedContentSource
::DerefMutableRef
450 BorrowedContentSource
::DerefSharedRef
454 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
455 /// name where required.
456 pub(super) fn get_name_for_ty(&self, ty
: Ty
<'tcx
>, counter
: usize) -> String
{
457 let mut printer
= ty
::print
::FmtPrinter
::new(self.infcx
.tcx
, Namespace
::TypeNS
);
459 // We need to add synthesized lifetimes where appropriate. We do
460 // this by hooking into the pretty printer and telling it to label the
461 // lifetimes without names with the value `'0`.
462 if let ty
::Ref(region
, ..) = ty
.kind() {
464 ty
::ReLateBound(_
, ty
::BoundRegion { kind: br, .. }
)
465 | ty
::RePlaceholder(ty
::PlaceholderRegion
{
466 bound
: ty
::BoundRegion { kind: br, .. }
,
468 }) => printer
.region_highlight_mode
.highlighting_bound_region(br
, counter
),
473 ty
.print(printer
).unwrap().into_buffer()
476 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
477 /// synthesized lifetime name where required.
478 pub(super) fn get_region_name_for_ty(&self, ty
: Ty
<'tcx
>, counter
: usize) -> String
{
479 let mut printer
= ty
::print
::FmtPrinter
::new(self.infcx
.tcx
, Namespace
::TypeNS
);
481 let region
= if let ty
::Ref(region
, ..) = ty
.kind() {
483 ty
::ReLateBound(_
, ty
::BoundRegion { kind: br, .. }
)
484 | ty
::RePlaceholder(ty
::PlaceholderRegion
{
485 bound
: ty
::BoundRegion { kind: br, .. }
,
487 }) => printer
.region_highlight_mode
.highlighting_bound_region(br
, counter
),
492 bug
!("ty for annotation of borrow region is not a reference");
495 region
.print(printer
).unwrap().into_buffer()
499 /// The span(s) associated to a use of a place.
500 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
501 pub(super) enum UseSpans
<'tcx
> {
502 /// The access is caused by capturing a variable for a closure.
504 /// This is true if the captured variable was from a generator.
505 generator_kind
: Option
<GeneratorKind
>,
506 /// The span of the args of the closure, including the `move` keyword if
509 /// The span of the use resulting in capture kind
510 /// Check `ty::CaptureInfo` for more details
511 capture_kind_span
: Span
,
512 /// The span of the use resulting in the captured path
513 /// Check `ty::CaptureInfo` for more details
516 /// The access is caused by using a variable as the receiver of a method
517 /// that takes 'self'
519 /// The span of the variable being moved
521 /// The span of the method call on the variable
523 /// The definition span of the method being called
525 kind
: CallKind
<'tcx
>,
527 /// This access is caused by a `match` or `if let` pattern.
529 /// This access has a single span associated to it: common case.
534 pub(super) fn args_or_use(self) -> Span
{
536 UseSpans
::ClosureUse { args_span: span, .. }
537 | UseSpans
::PatUse(span
)
538 | UseSpans
::OtherUse(span
) => span
,
539 UseSpans
::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }
, .. } => {
542 UseSpans
::FnSelfUse { var_span, .. }
=> var_span
,
546 /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
547 pub(super) fn var_or_use_path_span(self) -> Span
{
549 UseSpans
::ClosureUse { path_span: span, .. }
550 | UseSpans
::PatUse(span
)
551 | UseSpans
::OtherUse(span
) => span
,
552 UseSpans
::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }
, .. } => {
555 UseSpans
::FnSelfUse { var_span, .. }
=> var_span
,
559 /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
560 pub(super) fn var_or_use(self) -> Span
{
562 UseSpans
::ClosureUse { capture_kind_span: span, .. }
563 | UseSpans
::PatUse(span
)
564 | UseSpans
::OtherUse(span
) => span
,
565 UseSpans
::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }
, .. } => {
568 UseSpans
::FnSelfUse { var_span, .. }
=> var_span
,
572 pub(super) fn generator_kind(self) -> Option
<GeneratorKind
> {
574 UseSpans
::ClosureUse { generator_kind, .. }
=> generator_kind
,
579 /// Add a span label to the arguments of the closure, if it exists.
580 pub(super) fn args_subdiag(
582 err
: &mut Diagnostic
,
583 f
: impl FnOnce(Span
) -> CaptureArgLabel
,
585 if let UseSpans
::ClosureUse { args_span, .. }
= self {
586 err
.subdiagnostic(f(args_span
));
590 /// Add a span label to the use of the captured variable, if it exists.
591 /// only adds label to the `path_span`
592 pub(super) fn var_path_only_subdiag(
594 err
: &mut Diagnostic
,
595 action
: crate::InitializationRequiringAction
,
597 use crate::InitializationRequiringAction
::*;
598 use CaptureVarPathUseCause
::*;
599 if let UseSpans
::ClosureUse { generator_kind, path_span, .. }
= self {
600 match generator_kind
{
602 err
.subdiagnostic(match action
{
603 Borrow
=> BorrowInGenerator { path_span }
,
604 MatchOn
| Use
=> UseInGenerator { path_span }
,
605 Assignment
=> AssignInGenerator { path_span }
,
606 PartialAssignment
=> AssignPartInGenerator { path_span }
,
610 err
.subdiagnostic(match action
{
611 Borrow
=> BorrowInClosure { path_span }
,
612 MatchOn
| Use
=> UseInClosure { path_span }
,
613 Assignment
=> AssignInClosure { path_span }
,
614 PartialAssignment
=> AssignPartInClosure { path_span }
,
621 /// Add a subdiagnostic to the use of the captured variable, if it exists.
622 pub(super) fn var_subdiag(
624 handler
: Option
<&rustc_errors
::Handler
>,
625 err
: &mut Diagnostic
,
626 kind
: Option
<rustc_middle
::mir
::BorrowKind
>,
627 f
: impl FnOnce(Option
<GeneratorKind
>, Span
) -> CaptureVarCause
,
629 if let UseSpans
::ClosureUse { generator_kind, capture_kind_span, path_span, .. }
= self {
630 if capture_kind_span
!= path_span
{
631 err
.subdiagnostic(match kind
{
632 Some(kd
) => match kd
{
633 rustc_middle
::mir
::BorrowKind
::Shared
634 | rustc_middle
::mir
::BorrowKind
::Fake
=> {
635 CaptureVarKind
::Immut { kind_span: capture_kind_span }
638 rustc_middle
::mir
::BorrowKind
::Mut { .. }
=> {
639 CaptureVarKind
::Mut { kind_span: capture_kind_span }
642 None
=> CaptureVarKind
::Move { kind_span: capture_kind_span }
,
645 let diag
= f(generator_kind
, path_span
);
647 Some(hd
) => err
.eager_subdiagnostic(hd
, diag
),
648 None
=> err
.subdiagnostic(diag
),
653 /// Returns `false` if this place is not used in a closure.
654 pub(super) fn for_closure(&self) -> bool
{
656 UseSpans
::ClosureUse { generator_kind, .. }
=> generator_kind
.is_none(),
661 /// Returns `false` if this place is not used in a generator.
662 pub(super) fn for_generator(&self) -> bool
{
664 UseSpans
::ClosureUse { generator_kind, .. }
=> generator_kind
.is_some(),
669 pub(super) fn or_else
<F
>(self, if_other
: F
) -> Self
674 closure @ UseSpans
::ClosureUse { .. }
=> closure
,
675 UseSpans
::PatUse(_
) | UseSpans
::OtherUse(_
) => if_other(),
676 fn_self @ UseSpans
::FnSelfUse { .. }
=> fn_self
,
681 pub(super) enum BorrowedContentSource
<'tcx
> {
685 OverloadedDeref(Ty
<'tcx
>),
686 OverloadedIndex(Ty
<'tcx
>),
689 impl<'tcx
> BorrowedContentSource
<'tcx
> {
690 pub(super) fn describe_for_unnamed_place(&self, tcx
: TyCtxt
<'_
>) -> String
{
692 BorrowedContentSource
::DerefRawPointer
=> "a raw pointer".to_string(),
693 BorrowedContentSource
::DerefSharedRef
=> "a shared reference".to_string(),
694 BorrowedContentSource
::DerefMutableRef
=> "a mutable reference".to_string(),
695 BorrowedContentSource
::OverloadedDeref(ty
) => ty
697 .and_then(|adt
| match tcx
.get_diagnostic_name(adt
.did())?
{
698 name @
(sym
::Rc
| sym
::Arc
) => Some(format
!("an `{name}`")),
701 .unwrap_or_else(|| format
!("dereference of `{ty}`")),
702 BorrowedContentSource
::OverloadedIndex(ty
) => format
!("index of `{ty}`"),
706 pub(super) fn describe_for_named_place(&self) -> Option
<&'
static str> {
708 BorrowedContentSource
::DerefRawPointer
=> Some("raw pointer"),
709 BorrowedContentSource
::DerefSharedRef
=> Some("shared reference"),
710 BorrowedContentSource
::DerefMutableRef
=> Some("mutable reference"),
711 // Overloaded deref and index operators should be evaluated into a
712 // temporary. So we don't need a description here.
713 BorrowedContentSource
::OverloadedDeref(_
)
714 | BorrowedContentSource
::OverloadedIndex(_
) => None
,
718 pub(super) fn describe_for_immutable_place(&self, tcx
: TyCtxt
<'_
>) -> String
{
720 BorrowedContentSource
::DerefRawPointer
=> "a `*const` pointer".to_string(),
721 BorrowedContentSource
::DerefSharedRef
=> "a `&` reference".to_string(),
722 BorrowedContentSource
::DerefMutableRef
=> {
723 bug
!("describe_for_immutable_place: DerefMutableRef isn't immutable")
725 BorrowedContentSource
::OverloadedDeref(ty
) => ty
727 .and_then(|adt
| match tcx
.get_diagnostic_name(adt
.did())?
{
728 name @
(sym
::Rc
| sym
::Arc
) => Some(format
!("an `{name}`")),
731 .unwrap_or_else(|| format
!("dereference of `{ty}`")),
732 BorrowedContentSource
::OverloadedIndex(ty
) => format
!("an index of `{ty}`"),
736 fn from_call(func
: Ty
<'tcx
>, tcx
: TyCtxt
<'tcx
>) -> Option
<Self> {
738 ty
::FnDef(def_id
, args
) => {
739 let trait_id
= tcx
.trait_of_item(def_id
)?
;
741 let lang_items
= tcx
.lang_items();
742 if Some(trait_id
) == lang_items
.deref_trait()
743 || Some(trait_id
) == lang_items
.deref_mut_trait()
745 Some(BorrowedContentSource
::OverloadedDeref(args
.type_at(0)))
746 } else if Some(trait_id
) == lang_items
.index_trait()
747 || Some(trait_id
) == lang_items
.index_mut_trait()
749 Some(BorrowedContentSource
::OverloadedIndex(args
.type_at(0)))
759 ///helper struct for explain_captures()
760 struct CapturedMessageOpt
{
761 is_partial_move
: bool
,
762 is_loop_message
: bool
,
765 maybe_reinitialized_locations_is_empty
: bool
,
768 impl<'cx
, 'tcx
> MirBorrowckCtxt
<'cx
, 'tcx
> {
769 /// Finds the spans associated to a move or copy of move_place at location.
770 pub(super) fn move_spans(
772 moved_place
: PlaceRef
<'tcx
>, // Could also be an upvar.
774 ) -> UseSpans
<'tcx
> {
775 use self::UseSpans
::*;
777 let Some(stmt
) = self.body
[location
.block
].statements
.get(location
.statement_index
) else {
778 return OtherUse(self.body
.source_info(location
).span
);
781 debug
!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place
, location
, stmt
);
782 if let StatementKind
::Assign(box (_
, Rvalue
::Aggregate(kind
, places
))) = &stmt
.kind
783 && let AggregateKind
::Closure(def_id
, _
) | AggregateKind
::Generator(def_id
, _
, _
) = **kind
785 debug
!("move_spans: def_id={:?} places={:?}", def_id
, places
);
786 let def_id
= def_id
.expect_local();
787 if let Some((args_span
, generator_kind
, capture_kind_span
, path_span
)) =
788 self.closure_span(def_id
, moved_place
, places
)
799 // StatementKind::FakeRead only contains a def_id if they are introduced as a result
800 // of pattern matching within a closure.
801 if let StatementKind
::FakeRead(box (cause
, place
)) = stmt
.kind
{
803 FakeReadCause
::ForMatchedPlace(Some(closure_def_id
))
804 | FakeReadCause
::ForLet(Some(closure_def_id
)) => {
805 debug
!("move_spans: def_id={:?} place={:?}", closure_def_id
, place
);
806 let places
= &[Operand
::Move(place
)];
807 if let Some((args_span
, generator_kind
, capture_kind_span
, path_span
)) =
808 self.closure_span(closure_def_id
, moved_place
, IndexSlice
::from_raw(places
))
823 if moved_place
.projection
.iter().any(|p
| matches
!(p
, ProjectionElem
::Downcast(..))) {
824 PatUse(stmt
.source_info
.span
)
826 OtherUse(stmt
.source_info
.span
)
829 // We are trying to find MIR of the form:
831 // _temp = _moved_val;
833 // FnSelfCall(_temp, ...)
836 // where `_moved_val` is the place we generated the move error for,
837 // `_temp` is some other local, and `FnSelfCall` is a function
838 // that has a `self` parameter.
840 let target_temp
= match stmt
.kind
{
841 StatementKind
::Assign(box (temp
, _
)) if temp
.as_local().is_some() => {
842 temp
.as_local().unwrap()
844 _
=> return normal_ret
,
847 debug
!("move_spans: target_temp = {:?}", target_temp
);
849 if let Some(Terminator
{
850 kind
: TerminatorKind
::Call { fn_span, call_source, .. }
, ..
851 }) = &self.body
[location
.block
].terminator
853 let Some((method_did
, method_args
)) = rustc_middle
::util
::find_self_call(
862 let kind
= call_kind(
868 call_source
.from_hir_call(),
869 Some(self.infcx
.tcx
.fn_arg_names(method_did
)[0]),
873 var_span
: stmt
.source_info
.span
,
874 fn_call_span
: *fn_span
,
875 fn_span
: self.infcx
.tcx
.def_span(method_did
),
882 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
883 /// and its usage of the local assigned at `location`.
884 /// This is done by searching in statements succeeding `location`
885 /// and originating from `maybe_closure_span`.
886 pub(super) fn borrow_spans(&self, use_span
: Span
, location
: Location
) -> UseSpans
<'tcx
> {
887 use self::UseSpans
::*;
888 debug
!("borrow_spans: use_span={:?} location={:?}", use_span
, location
);
890 let target
= match self.body
[location
.block
].statements
.get(location
.statement_index
) {
891 Some(Statement { kind: StatementKind::Assign(box (place, _)), .. }
) => {
892 if let Some(local
) = place
.as_local() {
895 return OtherUse(use_span
);
898 _
=> return OtherUse(use_span
),
901 if self.body
.local_kind(target
) != LocalKind
::Temp
{
902 // operands are always temporaries.
903 return OtherUse(use_span
);
906 // drop and replace might have moved the assignment to the next block
907 let maybe_additional_statement
=
908 if let TerminatorKind
::Drop { target: drop_target, .. }
=
909 self.body
[location
.block
].terminator().kind
911 self.body
[drop_target
].statements
.first()
917 self.body
[location
.block
].statements
[location
.statement_index
+ 1..].iter();
919 for stmt
in statements
.chain(maybe_additional_statement
) {
920 if let StatementKind
::Assign(box (_
, Rvalue
::Aggregate(kind
, places
))) = &stmt
.kind
{
921 let (&def_id
, is_generator
) = match kind
{
922 box AggregateKind
::Closure(def_id
, _
) => (def_id
, false),
923 box AggregateKind
::Generator(def_id
, _
, _
) => (def_id
, true),
926 let def_id
= def_id
.expect_local();
929 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
930 def_id
, is_generator
, places
932 if let Some((args_span
, generator_kind
, capture_kind_span
, path_span
)) =
933 self.closure_span(def_id
, Place
::from(target
).as_ref(), places
)
935 return ClosureUse { generator_kind, args_span, capture_kind_span, path_span }
;
937 return OtherUse(use_span
);
941 if use_span
!= stmt
.source_info
.span
{
949 /// Finds the spans of a captured place within a closure or generator.
950 /// The first span is the location of the use resulting in the capture kind of the capture
951 /// The second span is the location the use resulting in the captured path of the capture
955 target_place
: PlaceRef
<'tcx
>,
956 places
: &IndexSlice
<FieldIdx
, Operand
<'tcx
>>,
957 ) -> Option
<(Span
, Option
<GeneratorKind
>, Span
, Span
)> {
959 "closure_span: def_id={:?} target_place={:?} places={:?}",
960 def_id
, target_place
, places
962 let hir_id
= self.infcx
.tcx
.hir().local_def_id_to_hir_id(def_id
);
963 let expr
= &self.infcx
.tcx
.hir().expect_expr(hir_id
).kind
;
964 debug
!("closure_span: hir_id={:?} expr={:?}", hir_id
, expr
);
965 if let hir
::ExprKind
::Closure(&hir
::Closure { body, fn_decl_span, .. }
) = expr
{
966 for (captured_place
, place
) in
967 self.infcx
.tcx
.closure_captures(def_id
).iter().zip(places
)
970 Operand
::Copy(place
) | Operand
::Move(place
)
971 if target_place
== place
.as_ref() =>
973 debug
!("closure_span: found captured local {:?}", place
);
974 let body
= self.infcx
.tcx
.hir().body(body
);
975 let generator_kind
= body
.generator_kind();
980 captured_place
.get_capture_kind_span(self.infcx
.tcx
),
981 captured_place
.get_path_span(self.infcx
.tcx
),
991 /// Helper to retrieve span(s) of given borrow from the current MIR
993 pub(super) fn retrieve_borrow_spans(&self, borrow
: &BorrowData
<'_
>) -> UseSpans
<'tcx
> {
994 let span
= self.body
.source_info(borrow
.reserve_location
).span
;
995 self.borrow_spans(span
, borrow
.reserve_location
)
1000 err
: &mut Diagnostic
,
1003 move_spans
: UseSpans
<'tcx
>,
1004 moved_place
: Place
<'tcx
>,
1005 msg_opt
: CapturedMessageOpt
,
1007 let CapturedMessageOpt
{
1008 is_partial_move
: is_partial
,
1012 maybe_reinitialized_locations_is_empty
,
1014 if let UseSpans
::FnSelfUse { var_span, fn_call_span, fn_span, kind }
= move_spans
{
1015 let place_name
= self
1016 .describe_place(moved_place
.as_ref())
1017 .map(|n
| format
!("`{n}`"))
1018 .unwrap_or_else(|| "value".to_owned());
1020 CallKind
::FnCall { fn_trait_id, .. }
1021 if Some(fn_trait_id
) == self.infcx
.tcx
.lang_items().fn_once_trait() =>
1023 err
.subdiagnostic(CaptureReasonLabel
::Call
{
1025 place_name
: &place_name
,
1029 err
.subdiagnostic(CaptureReasonNote
::FnOnceMoveInCall { var_span }
);
1031 CallKind
::Operator { self_arg, .. }
=> {
1032 let self_arg
= self_arg
.unwrap();
1033 err
.subdiagnostic(CaptureReasonLabel
::OperatorUse
{
1035 place_name
: &place_name
,
1039 if self.fn_self_span_reported
.insert(fn_span
) {
1040 err
.subdiagnostic(CaptureReasonNote
::LhsMoveByOperator
{
1041 span
: self_arg
.span
,
1045 CallKind
::Normal { self_arg, desugaring, method_did, method_args }
=> {
1046 let self_arg
= self_arg
.unwrap();
1047 let tcx
= self.infcx
.tcx
;
1048 if let Some((CallDesugaringKind
::ForLoopIntoIter
, _
)) = desugaring
{
1049 let ty
= moved_place
.ty(self.body
, tcx
).ty
;
1050 let suggest
= match tcx
.get_diagnostic_item(sym
::IntoIterator
) {
1051 Some(def_id
) => type_known_to_meet_bound_modulo_regions(
1054 Ty
::new_imm_ref(tcx
, tcx
.lifetimes
.re_erased
, ty
),
1060 err
.subdiagnostic(CaptureReasonSuggest
::IterateSlice
{
1062 span
: move_span
.shrink_to_lo(),
1066 err
.subdiagnostic(CaptureReasonLabel
::ImplicitCall
{
1068 place_name
: &place_name
,
1072 // If the moved place was a `&mut` ref, then we can
1073 // suggest to reborrow it where it was moved, so it
1074 // will still be valid by the time we get to the usage.
1075 if let ty
::Ref(_
, _
, hir
::Mutability
::Mut
) =
1076 moved_place
.ty(self.body
, self.infcx
.tcx
).ty
.kind()
1078 // If we are in a loop this will be suggested later.
1080 err
.span_suggestion_verbose(
1081 move_span
.shrink_to_lo(),
1083 "consider creating a fresh reborrow of {} here",
1084 self.describe_place(moved_place
.as_ref())
1085 .map(|n
| format
!("`{n}`"))
1086 .unwrap_or_else(|| "the mutable reference".to_string()),
1089 Applicability
::MachineApplicable
,
1094 if let Some((CallDesugaringKind
::Await
, _
)) = desugaring
{
1095 err
.subdiagnostic(CaptureReasonLabel
::Await
{
1097 place_name
: &place_name
,
1102 err
.subdiagnostic(CaptureReasonLabel
::MethodCall
{
1104 place_name
: &place_name
,
1109 // Erase and shadow everything that could be passed to the new infcx.
1110 let ty
= moved_place
.ty(self.body
, tcx
).ty
;
1112 if let ty
::Adt(def
, args
) = ty
.kind()
1113 && Some(def
.did()) == tcx
.lang_items().pin_type()
1114 && let ty
::Ref(_
, _
, hir
::Mutability
::Mut
) = args
.type_at(0).kind()
1115 && let self_ty
= self.infcx
.instantiate_binder_with_fresh_vars(
1117 LateBoundRegionConversionTime
::FnCall
,
1118 tcx
.fn_sig(method_did
).instantiate(tcx
, method_args
).input(0),
1120 && self.infcx
.can_eq(self.param_env
, ty
, self_ty
)
1122 err
.eager_subdiagnostic(
1123 &self.infcx
.tcx
.sess
.parse_sess
.span_diagnostic
,
1124 CaptureReasonSuggest
::FreshReborrow
{
1125 span
: move_span
.shrink_to_hi(),
1128 if let Some(clone_trait
) = tcx
.lang_items().clone_trait()
1129 && let trait_ref
= ty
::TraitRef
::new(tcx
, clone_trait
, [ty
])
1130 && let o
= Obligation
::new(
1132 ObligationCause
::dummy(),
1134 ty
::Binder
::dummy(trait_ref
),
1136 && self.infcx
.predicate_must_hold_modulo_regions(&o
)
1138 err
.span_suggestion_verbose(
1139 move_span
.shrink_to_hi(),
1140 "you can `clone` the value and consume it, but this might not be \
1141 your desired behavior",
1142 ".clone()".to_string(),
1143 Applicability
::MaybeIncorrect
,
1147 // Avoid pointing to the same function in multiple different
1149 if span
!= DUMMY_SP
&& self.fn_self_span_reported
.insert(self_arg
.span
) {
1150 self.explain_iterator_advancement_in_for_loop_if_applicable(
1156 let func
= tcx
.def_path_str(method_did
);
1157 err
.subdiagnostic(CaptureReasonNote
::FuncTakeSelf
{
1160 span
: self_arg
.span
,
1163 let parent_did
= tcx
.parent(method_did
);
1164 let parent_self_ty
=
1165 matches
!(tcx
.def_kind(parent_did
), rustc_hir
::def
::DefKind
::Impl { .. }
)
1166 .then_some(parent_did
)
1167 .and_then(|did
| match tcx
.type_of(did
).instantiate_identity().kind() {
1168 ty
::Adt(def
, ..) => Some(def
.did()),
1171 let is_option_or_result
= parent_self_ty
.is_some_and(|def_id
| {
1172 matches
!(tcx
.get_diagnostic_name(def_id
), Some(sym
::Option
| sym
::Result
))
1174 if is_option_or_result
&& maybe_reinitialized_locations_is_empty
{
1175 err
.subdiagnostic(CaptureReasonLabel
::BorrowContent { var_span }
);
1178 // Other desugarings takes &self, which cannot cause a move
1182 if move_span
!= span
|| is_loop_message
{
1183 err
.subdiagnostic(CaptureReasonLabel
::MovedHere
{
1190 // If the move error occurs due to a loop, don't show
1191 // another message for the same span
1192 if !is_loop_message
{
1193 move_spans
.var_subdiag(None
, err
, None
, |kind
, var_span
| match kind
{
1194 Some(_
) => CaptureVarCause
::PartialMoveUseInGenerator { var_span, is_partial }
,
1195 None
=> CaptureVarCause
::PartialMoveUseInClosure { var_span, is_partial }
,