]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/mod.rs
Rollup merge of #105515 - estebank:issue-104141, r=oli-obk
[rust.git] / compiler / rustc_borrowck / src / diagnostics / mod.rs
1 //! Borrow checker diagnostics.
2
3 use itertools::Itertools;
4 use rustc_const_eval::util::{call_kind, CallDesugaringKind};
5 use rustc_errors::{Applicability, Diagnostic};
6 use rustc_hir as hir;
7 use rustc_hir::def::{CtorKind, Namespace};
8 use rustc_hir::GeneratorKind;
9 use rustc_infer::infer::TyCtxtInferExt;
10 use rustc_middle::mir::tcx::PlaceTy;
11 use rustc_middle::mir::{
12     AggregateKind, Constant, FakeReadCause, Field, Local, LocalInfo, LocalKind, Location, Operand,
13     Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
14 };
15 use rustc_middle::ty::print::Print;
16 use rustc_middle::ty::{self, DefIdTree, Instance, Ty, TyCtxt};
17 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult};
18 use rustc_span::def_id::LocalDefId;
19 use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP};
20 use rustc_target::abi::VariantIdx;
21 use rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions;
22
23 use super::borrow_set::BorrowData;
24 use super::MirBorrowckCtxt;
25
26 mod find_all_local_uses;
27 mod find_use;
28 mod outlives_suggestion;
29 mod region_name;
30 mod var_name;
31
32 mod bound_region_errors;
33 mod conflict_errors;
34 mod explain_borrow;
35 mod move_errors;
36 mod mutability_errors;
37 mod region_errors;
38
39 pub(crate) use bound_region_errors::{ToUniverseInfo, UniverseInfo};
40 pub(crate) use mutability_errors::AccessKind;
41 pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder;
42 pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
43 pub(crate) use region_name::{RegionName, RegionNameSource};
44 pub(crate) use rustc_const_eval::util::CallKind;
45
46 pub(super) struct DescribePlaceOpt {
47     pub including_downcast: bool,
48
49     /// Enable/Disable tuple fields.
50     /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x`
51     pub including_tuple_field: bool,
52 }
53
54 pub(super) struct IncludingTupleField(pub(super) bool);
55
56 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
57     /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
58     /// is moved after being invoked.
59     ///
60     /// ```text
61     /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
62     ///       its environment
63     ///   --> $DIR/issue-42065.rs:16:29
64     ///    |
65     /// LL |         for (key, value) in dict {
66     ///    |                             ^^^^
67     /// ```
68     pub(super) fn add_moved_or_invoked_closure_note(
69         &self,
70         location: Location,
71         place: PlaceRef<'tcx>,
72         diag: &mut Diagnostic,
73     ) -> bool {
74         debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
75         let mut target = place.local_or_deref_local();
76         for stmt in &self.body[location.block].statements[location.statement_index..] {
77             debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
78             if let StatementKind::Assign(box (into, Rvalue::Use(from))) = &stmt.kind {
79                 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
80                 match from {
81                     Operand::Copy(place) | Operand::Move(place)
82                         if target == place.local_or_deref_local() =>
83                     {
84                         target = into.local_or_deref_local()
85                     }
86                     _ => {}
87                 }
88             }
89         }
90
91         // Check if we are attempting to call a closure after it has been invoked.
92         let terminator = self.body[location.block].terminator();
93         debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
94         if let TerminatorKind::Call {
95             func: Operand::Constant(box Constant { literal, .. }),
96             args,
97             ..
98         } = &terminator.kind
99         {
100             if let ty::FnDef(id, _) = *literal.ty().kind() {
101                 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
102                 if Some(self.infcx.tcx.parent(id)) == self.infcx.tcx.lang_items().fn_once_trait() {
103                     let closure = match args.first() {
104                         Some(Operand::Copy(place) | Operand::Move(place))
105                             if target == place.local_or_deref_local() =>
106                         {
107                             place.local_or_deref_local().unwrap()
108                         }
109                         _ => return false,
110                     };
111
112                     debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
113                     if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
114                         let did = did.expect_local();
115                         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
116
117                         if let Some((span, hir_place)) =
118                             self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
119                         {
120                             diag.span_note(
121                                 *span,
122                                 &format!(
123                                     "closure cannot be invoked more than once because it moves the \
124                                     variable `{}` out of its environment",
125                                     ty::place_to_string_for_capture(self.infcx.tcx, hir_place)
126                                 ),
127                             );
128                             return true;
129                         }
130                     }
131                 }
132             }
133         }
134
135         // Check if we are just moving a closure after it has been invoked.
136         if let Some(target) = target {
137             if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() {
138                 let did = did.expect_local();
139                 let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
140
141                 if let Some((span, hir_place)) =
142                     self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
143                 {
144                     diag.span_note(
145                         *span,
146                         &format!(
147                             "closure cannot be moved more than once as it is not `Copy` due to \
148                              moving the variable `{}` out of its environment",
149                             ty::place_to_string_for_capture(self.infcx.tcx, hir_place)
150                         ),
151                     );
152                     return true;
153                 }
154             }
155         }
156         false
157     }
158
159     /// End-user visible description of `place` if one can be found.
160     /// If the place is a temporary for instance, `"value"` will be returned.
161     pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
162         match self.describe_place(place_ref) {
163             Some(mut descr) => {
164                 // Surround descr with `backticks`.
165                 descr.reserve(2);
166                 descr.insert(0, '`');
167                 descr.push('`');
168                 descr
169             }
170             None => "value".to_string(),
171         }
172     }
173
174     /// End-user visible description of `place` if one can be found.
175     /// If the place is a temporary for instance, `None` will be returned.
176     pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
177         self.describe_place_with_options(
178             place_ref,
179             DescribePlaceOpt { including_downcast: false, including_tuple_field: true },
180         )
181     }
182
183     /// End-user visible description of `place` if one can be found. If the place is a temporary
184     /// for instance, `None` will be returned.
185     /// `IncludingDowncast` parameter makes the function return `None` if `ProjectionElem` is
186     /// `Downcast` and `IncludingDowncast` is true
187     pub(super) fn describe_place_with_options(
188         &self,
189         place: PlaceRef<'tcx>,
190         opt: DescribePlaceOpt,
191     ) -> Option<String> {
192         let local = place.local;
193         let mut autoderef_index = None;
194         let mut buf = String::new();
195         let mut ok = self.append_local_to_string(local, &mut buf);
196
197         for (index, elem) in place.projection.into_iter().enumerate() {
198             match elem {
199                 ProjectionElem::Deref => {
200                     if index == 0 {
201                         if self.body.local_decls[local].is_ref_for_guard() {
202                             continue;
203                         }
204                         if let Some(box LocalInfo::StaticRef { def_id, .. }) =
205                             &self.body.local_decls[local].local_info
206                         {
207                             buf.push_str(self.infcx.tcx.item_name(*def_id).as_str());
208                             ok = Ok(());
209                             continue;
210                         }
211                     }
212                     if let Some(field) = self.is_upvar_field_projection(PlaceRef {
213                         local,
214                         projection: place.projection.split_at(index + 1).0,
215                     }) {
216                         let var_index = field.index();
217                         buf = self.upvars[var_index].place.to_string(self.infcx.tcx);
218                         ok = Ok(());
219                         if !self.upvars[var_index].by_ref {
220                             buf.insert(0, '*');
221                         }
222                     } else {
223                         if autoderef_index.is_none() {
224                             autoderef_index =
225                                 match place.projection.into_iter().rev().find_position(|elem| {
226                                     !matches!(
227                                         elem,
228                                         ProjectionElem::Deref | ProjectionElem::Downcast(..)
229                                     )
230                                 }) {
231                                     Some((index, _)) => Some(place.projection.len() - index),
232                                     None => Some(0),
233                                 };
234                         }
235                         if index >= autoderef_index.unwrap() {
236                             buf.insert(0, '*');
237                         }
238                     }
239                 }
240                 ProjectionElem::Downcast(..) if opt.including_downcast => return None,
241                 ProjectionElem::Downcast(..) => (),
242                 ProjectionElem::OpaqueCast(..) => (),
243                 ProjectionElem::Field(field, _ty) => {
244                     // FIXME(project-rfc_2229#36): print capture precisely here.
245                     if let Some(field) = self.is_upvar_field_projection(PlaceRef {
246                         local,
247                         projection: place.projection.split_at(index + 1).0,
248                     }) {
249                         buf = self.upvars[field.index()].place.to_string(self.infcx.tcx);
250                         ok = Ok(());
251                     } else {
252                         let field_name = self.describe_field(
253                             PlaceRef { local, projection: place.projection.split_at(index).0 },
254                             *field,
255                             IncludingTupleField(opt.including_tuple_field),
256                         );
257                         if let Some(field_name_str) = field_name {
258                             buf.push('.');
259                             buf.push_str(&field_name_str);
260                         }
261                     }
262                 }
263                 ProjectionElem::Index(index) => {
264                     buf.push('[');
265                     if self.append_local_to_string(*index, &mut buf).is_err() {
266                         buf.push('_');
267                     }
268                     buf.push(']');
269                 }
270                 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
271                     // Since it isn't possible to borrow an element on a particular index and
272                     // then use another while the borrow is held, don't output indices details
273                     // to avoid confusing the end-user
274                     buf.push_str("[..]");
275                 }
276             }
277         }
278         ok.ok().map(|_| buf)
279     }
280
281     fn describe_name(&self, place: PlaceRef<'tcx>) -> Option<Symbol> {
282         for elem in place.projection.into_iter() {
283             match elem {
284                 ProjectionElem::Downcast(Some(name), _) => {
285                     return Some(*name);
286                 }
287                 _ => {}
288             }
289         }
290         None
291     }
292
293     /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
294     /// a name, or its name was generated by the compiler, then `Err` is returned
295     fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
296         let decl = &self.body.local_decls[local];
297         match self.local_names[local] {
298             Some(name) if !decl.from_compiler_desugaring() => {
299                 buf.push_str(name.as_str());
300                 Ok(())
301             }
302             _ => Err(()),
303         }
304     }
305
306     /// End-user visible description of the `field`nth field of `base`
307     fn describe_field(
308         &self,
309         place: PlaceRef<'tcx>,
310         field: Field,
311         including_tuple_field: IncludingTupleField,
312     ) -> Option<String> {
313         let place_ty = match place {
314             PlaceRef { local, projection: [] } => PlaceTy::from_ty(self.body.local_decls[local].ty),
315             PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
316                 ProjectionElem::Deref
317                 | ProjectionElem::Index(..)
318                 | ProjectionElem::ConstantIndex { .. }
319                 | ProjectionElem::Subslice { .. } => {
320                     PlaceRef { local, projection: proj_base }.ty(self.body, self.infcx.tcx)
321                 }
322                 ProjectionElem::Downcast(..) => place.ty(self.body, self.infcx.tcx),
323                 ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(*ty),
324                 ProjectionElem::Field(_, field_type) => PlaceTy::from_ty(*field_type),
325             },
326         };
327         self.describe_field_from_ty(
328             place_ty.ty,
329             field,
330             place_ty.variant_index,
331             including_tuple_field,
332         )
333     }
334
335     /// End-user visible description of the `field_index`nth field of `ty`
336     fn describe_field_from_ty(
337         &self,
338         ty: Ty<'_>,
339         field: Field,
340         variant_index: Option<VariantIdx>,
341         including_tuple_field: IncludingTupleField,
342     ) -> Option<String> {
343         if ty.is_box() {
344             // If the type is a box, the field is described from the boxed type
345             self.describe_field_from_ty(ty.boxed_ty(), field, variant_index, including_tuple_field)
346         } else {
347             match *ty.kind() {
348                 ty::Adt(def, _) => {
349                     let variant = if let Some(idx) = variant_index {
350                         assert!(def.is_enum());
351                         &def.variant(idx)
352                     } else {
353                         def.non_enum_variant()
354                     };
355                     if !including_tuple_field.0 && variant.ctor_kind() == Some(CtorKind::Fn) {
356                         return None;
357                     }
358                     Some(variant.fields[field.index()].name.to_string())
359                 }
360                 ty::Tuple(_) => Some(field.index().to_string()),
361                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
362                     self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
363                 }
364                 ty::Array(ty, _) | ty::Slice(ty) => {
365                     self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
366                 }
367                 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
368                     // We won't be borrowck'ing here if the closure came from another crate,
369                     // so it's safe to call `expect_local`.
370                     //
371                     // We know the field exists so it's safe to call operator[] and `unwrap` here.
372                     let def_id = def_id.expect_local();
373                     let var_id = self
374                         .infcx
375                         .tcx
376                         .typeck(def_id)
377                         .closure_min_captures_flattened(def_id)
378                         .nth(field.index())
379                         .unwrap()
380                         .get_root_variable();
381
382                     Some(self.infcx.tcx.hir().name(var_id).to_string())
383                 }
384                 _ => {
385                     // Might need a revision when the fields in trait RFC is implemented
386                     // (https://github.com/rust-lang/rfcs/pull/1546)
387                     bug!("End-user description not implemented for field access on `{:?}`", ty);
388                 }
389             }
390         }
391     }
392
393     /// Add a note that a type does not implement `Copy`
394     pub(super) fn note_type_does_not_implement_copy(
395         &self,
396         err: &mut Diagnostic,
397         place_desc: &str,
398         ty: Ty<'tcx>,
399         span: Option<Span>,
400         move_prefix: &str,
401     ) {
402         let message = format!(
403             "{}move occurs because {} has type `{}`, which does not implement the `Copy` trait",
404             move_prefix, place_desc, ty,
405         );
406         if let Some(span) = span {
407             err.span_label(span, message);
408         } else {
409             err.note(&message);
410         }
411     }
412
413     pub(super) fn borrowed_content_source(
414         &self,
415         deref_base: PlaceRef<'tcx>,
416     ) -> BorrowedContentSource<'tcx> {
417         let tcx = self.infcx.tcx;
418
419         // Look up the provided place and work out the move path index for it,
420         // we'll use this to check whether it was originally from an overloaded
421         // operator.
422         match self.move_data.rev_lookup.find(deref_base) {
423             LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
424                 debug!("borrowed_content_source: mpi={:?}", mpi);
425
426                 for i in &self.move_data.init_path_map[mpi] {
427                     let init = &self.move_data.inits[*i];
428                     debug!("borrowed_content_source: init={:?}", init);
429                     // We're only interested in statements that initialized a value, not the
430                     // initializations from arguments.
431                     let InitLocation::Statement(loc) = init.location else { continue };
432
433                     let bbd = &self.body[loc.block];
434                     let is_terminator = bbd.statements.len() == loc.statement_index;
435                     debug!(
436                         "borrowed_content_source: loc={:?} is_terminator={:?}",
437                         loc, is_terminator,
438                     );
439                     if !is_terminator {
440                         continue;
441                     } else if let Some(Terminator {
442                         kind: TerminatorKind::Call { func, from_hir_call: false, .. },
443                         ..
444                     }) = &bbd.terminator
445                     {
446                         if let Some(source) =
447                             BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
448                         {
449                             return source;
450                         }
451                     }
452                 }
453             }
454             // Base is a `static` so won't be from an overloaded operator
455             _ => (),
456         };
457
458         // If we didn't find an overloaded deref or index, then assume it's a
459         // built in deref and check the type of the base.
460         let base_ty = deref_base.ty(self.body, tcx).ty;
461         if base_ty.is_unsafe_ptr() {
462             BorrowedContentSource::DerefRawPointer
463         } else if base_ty.is_mutable_ptr() {
464             BorrowedContentSource::DerefMutableRef
465         } else {
466             BorrowedContentSource::DerefSharedRef
467         }
468     }
469
470     /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
471     /// name where required.
472     pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
473         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
474
475         // We need to add synthesized lifetimes where appropriate. We do
476         // this by hooking into the pretty printer and telling it to label the
477         // lifetimes without names with the value `'0`.
478         if let ty::Ref(region, ..) = ty.kind() {
479             match **region {
480                 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
481                 | ty::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
482                     printer.region_highlight_mode.highlighting_bound_region(br, counter)
483                 }
484                 _ => {}
485             }
486         }
487
488         ty.print(printer).unwrap().into_buffer()
489     }
490
491     /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
492     /// synthesized lifetime name where required.
493     pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
494         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
495
496         let region = if let ty::Ref(region, ..) = ty.kind() {
497             match **region {
498                 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
499                 | ty::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
500                     printer.region_highlight_mode.highlighting_bound_region(br, counter)
501                 }
502                 _ => {}
503             }
504             region
505         } else {
506             bug!("ty for annotation of borrow region is not a reference");
507         };
508
509         region.print(printer).unwrap().into_buffer()
510     }
511 }
512
513 /// The span(s) associated to a use of a place.
514 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
515 pub(super) enum UseSpans<'tcx> {
516     /// The access is caused by capturing a variable for a closure.
517     ClosureUse {
518         /// This is true if the captured variable was from a generator.
519         generator_kind: Option<GeneratorKind>,
520         /// The span of the args of the closure, including the `move` keyword if
521         /// it's present.
522         args_span: Span,
523         /// The span of the use resulting in capture kind
524         /// Check `ty::CaptureInfo` for more details
525         capture_kind_span: Span,
526         /// The span of the use resulting in the captured path
527         /// Check `ty::CaptureInfo` for more details
528         path_span: Span,
529     },
530     /// The access is caused by using a variable as the receiver of a method
531     /// that takes 'self'
532     FnSelfUse {
533         /// The span of the variable being moved
534         var_span: Span,
535         /// The span of the method call on the variable
536         fn_call_span: Span,
537         /// The definition span of the method being called
538         fn_span: Span,
539         kind: CallKind<'tcx>,
540     },
541     /// This access is caused by a `match` or `if let` pattern.
542     PatUse(Span),
543     /// This access has a single span associated to it: common case.
544     OtherUse(Span),
545 }
546
547 impl UseSpans<'_> {
548     pub(super) fn args_or_use(self) -> Span {
549         match self {
550             UseSpans::ClosureUse { args_span: span, .. }
551             | UseSpans::PatUse(span)
552             | UseSpans::OtherUse(span) => span,
553             UseSpans::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }, .. } => {
554                 fn_call_span
555             }
556             UseSpans::FnSelfUse { var_span, .. } => var_span,
557         }
558     }
559
560     /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
561     pub(super) fn var_or_use_path_span(self) -> Span {
562         match self {
563             UseSpans::ClosureUse { path_span: span, .. }
564             | UseSpans::PatUse(span)
565             | UseSpans::OtherUse(span) => span,
566             UseSpans::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }, .. } => {
567                 fn_call_span
568             }
569             UseSpans::FnSelfUse { var_span, .. } => var_span,
570         }
571     }
572
573     /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
574     pub(super) fn var_or_use(self) -> Span {
575         match self {
576             UseSpans::ClosureUse { capture_kind_span: span, .. }
577             | UseSpans::PatUse(span)
578             | UseSpans::OtherUse(span) => span,
579             UseSpans::FnSelfUse { fn_call_span, kind: CallKind::DerefCoercion { .. }, .. } => {
580                 fn_call_span
581             }
582             UseSpans::FnSelfUse { var_span, .. } => var_span,
583         }
584     }
585
586     pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
587         match self {
588             UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
589             _ => None,
590         }
591     }
592
593     /// Add a span label to the arguments of the closure, if it exists.
594     pub(super) fn args_span_label(self, err: &mut Diagnostic, message: impl Into<String>) {
595         if let UseSpans::ClosureUse { args_span, .. } = self {
596             err.span_label(args_span, message);
597         }
598     }
599
600     /// Add a span label to the use of the captured variable, if it exists.
601     /// only adds label to the `path_span`
602     pub(super) fn var_path_only_subdiag(
603         self,
604         err: &mut Diagnostic,
605         action: crate::InitializationRequiringAction,
606     ) {
607         use crate::session_diagnostics::CaptureVarPathUseCause::*;
608         use crate::InitializationRequiringAction::*;
609         if let UseSpans::ClosureUse { generator_kind, path_span, .. } = self {
610             match generator_kind {
611                 Some(_) => {
612                     err.subdiagnostic(match action {
613                         Borrow => BorrowInGenerator { path_span },
614                         MatchOn | Use => UseInGenerator { path_span },
615                         Assignment => AssignInGenerator { path_span },
616                         PartialAssignment => AssignPartInGenerator { path_span },
617                     });
618                 }
619                 None => {
620                     err.subdiagnostic(match action {
621                         Borrow => BorrowInClosure { path_span },
622                         MatchOn | Use => UseInClosure { path_span },
623                         Assignment => AssignInClosure { path_span },
624                         PartialAssignment => AssignPartInClosure { path_span },
625                     });
626                 }
627             }
628         }
629     }
630
631     /// Add a span label to the use of the captured variable, if it exists.
632     pub(super) fn var_span_label(
633         self,
634         err: &mut Diagnostic,
635         message: impl Into<String>,
636         kind_desc: impl Into<String>,
637     ) {
638         if let UseSpans::ClosureUse { capture_kind_span, path_span, .. } = self {
639             if capture_kind_span == path_span {
640                 err.span_label(capture_kind_span, message);
641             } else {
642                 let capture_kind_label =
643                     format!("capture is {} because of use here", kind_desc.into());
644                 let path_label = message;
645                 err.span_label(capture_kind_span, capture_kind_label);
646                 err.span_label(path_span, path_label);
647             }
648         }
649     }
650
651     /// Add a subdiagnostic to the use of the captured variable, if it exists.
652     pub(super) fn var_subdiag(
653         self,
654         err: &mut Diagnostic,
655         kind: Option<rustc_middle::mir::BorrowKind>,
656         f: impl Fn(Option<GeneratorKind>, Span) -> crate::session_diagnostics::CaptureVarCause,
657     ) {
658         use crate::session_diagnostics::CaptureVarKind::*;
659         if let UseSpans::ClosureUse { generator_kind, capture_kind_span, path_span, .. } = self {
660             if capture_kind_span != path_span {
661                 err.subdiagnostic(match kind {
662                     Some(kd) => match kd {
663                         rustc_middle::mir::BorrowKind::Shared
664                         | rustc_middle::mir::BorrowKind::Shallow
665                         | rustc_middle::mir::BorrowKind::Unique => {
666                             Immute { kind_span: capture_kind_span }
667                         }
668
669                         rustc_middle::mir::BorrowKind::Mut { .. } => {
670                             Mut { kind_span: capture_kind_span }
671                         }
672                     },
673                     None => Move { kind_span: capture_kind_span },
674                 });
675             };
676             err.subdiagnostic(f(generator_kind, path_span));
677         }
678     }
679
680     /// Returns `false` if this place is not used in a closure.
681     pub(super) fn for_closure(&self) -> bool {
682         match *self {
683             UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(),
684             _ => false,
685         }
686     }
687
688     /// Returns `false` if this place is not used in a generator.
689     pub(super) fn for_generator(&self) -> bool {
690         match *self {
691             UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(),
692             _ => false,
693         }
694     }
695
696     /// Describe the span associated with a use of a place.
697     pub(super) fn describe(&self) -> &str {
698         match *self {
699             UseSpans::ClosureUse { generator_kind, .. } => {
700                 if generator_kind.is_some() {
701                     " in generator"
702                 } else {
703                     " in closure"
704                 }
705             }
706             _ => "",
707         }
708     }
709
710     pub(super) fn or_else<F>(self, if_other: F) -> Self
711     where
712         F: FnOnce() -> Self,
713     {
714         match self {
715             closure @ UseSpans::ClosureUse { .. } => closure,
716             UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
717             fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
718         }
719     }
720 }
721
722 pub(super) enum BorrowedContentSource<'tcx> {
723     DerefRawPointer,
724     DerefMutableRef,
725     DerefSharedRef,
726     OverloadedDeref(Ty<'tcx>),
727     OverloadedIndex(Ty<'tcx>),
728 }
729
730 impl<'tcx> BorrowedContentSource<'tcx> {
731     pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
732         match *self {
733             BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
734             BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
735             BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
736             BorrowedContentSource::OverloadedDeref(ty) => ty
737                 .ty_adt_def()
738                 .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
739                     name @ (sym::Rc | sym::Arc) => Some(format!("an `{}`", name)),
740                     _ => None,
741                 })
742                 .unwrap_or_else(|| format!("dereference of `{}`", ty)),
743             BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
744         }
745     }
746
747     pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
748         match *self {
749             BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
750             BorrowedContentSource::DerefSharedRef => Some("shared reference"),
751             BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
752             // Overloaded deref and index operators should be evaluated into a
753             // temporary. So we don't need a description here.
754             BorrowedContentSource::OverloadedDeref(_)
755             | BorrowedContentSource::OverloadedIndex(_) => None,
756         }
757     }
758
759     pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
760         match *self {
761             BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
762             BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
763             BorrowedContentSource::DerefMutableRef => {
764                 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
765             }
766             BorrowedContentSource::OverloadedDeref(ty) => ty
767                 .ty_adt_def()
768                 .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
769                     name @ (sym::Rc | sym::Arc) => Some(format!("an `{}`", name)),
770                     _ => None,
771                 })
772                 .unwrap_or_else(|| format!("dereference of `{}`", ty)),
773             BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
774         }
775     }
776
777     fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
778         match *func.kind() {
779             ty::FnDef(def_id, substs) => {
780                 let trait_id = tcx.trait_of_item(def_id)?;
781
782                 let lang_items = tcx.lang_items();
783                 if Some(trait_id) == lang_items.deref_trait()
784                     || Some(trait_id) == lang_items.deref_mut_trait()
785                 {
786                     Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
787                 } else if Some(trait_id) == lang_items.index_trait()
788                     || Some(trait_id) == lang_items.index_mut_trait()
789                 {
790                     Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
791                 } else {
792                     None
793                 }
794             }
795             _ => None,
796         }
797     }
798 }
799
800 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
801     /// Finds the spans associated to a move or copy of move_place at location.
802     pub(super) fn move_spans(
803         &self,
804         moved_place: PlaceRef<'tcx>, // Could also be an upvar.
805         location: Location,
806     ) -> UseSpans<'tcx> {
807         use self::UseSpans::*;
808
809         let Some(stmt) = self.body[location.block].statements.get(location.statement_index) else {
810             return OtherUse(self.body.source_info(location).span);
811         };
812
813         debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
814         if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind
815             && let AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) = **kind
816         {
817             debug!("move_spans: def_id={:?} places={:?}", def_id, places);
818             if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
819                 self.closure_span(def_id, moved_place, places)
820             {
821                 return ClosureUse {
822                     generator_kind,
823                     args_span,
824                     capture_kind_span,
825                     path_span,
826                 };
827             }
828         }
829
830         // StatementKind::FakeRead only contains a def_id if they are introduced as a result
831         // of pattern matching within a closure.
832         if let StatementKind::FakeRead(box (cause, place)) = stmt.kind {
833             match cause {
834                 FakeReadCause::ForMatchedPlace(Some(closure_def_id))
835                 | FakeReadCause::ForLet(Some(closure_def_id)) => {
836                     debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);
837                     let places = &[Operand::Move(place)];
838                     if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
839                         self.closure_span(closure_def_id, moved_place, places)
840                     {
841                         return ClosureUse {
842                             generator_kind,
843                             args_span,
844                             capture_kind_span,
845                             path_span,
846                         };
847                     }
848                 }
849                 _ => {}
850             }
851         }
852
853         let normal_ret =
854             if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {
855                 PatUse(stmt.source_info.span)
856             } else {
857                 OtherUse(stmt.source_info.span)
858             };
859
860         // We are trying to find MIR of the form:
861         // ```
862         // _temp = _moved_val;
863         // ...
864         // FnSelfCall(_temp, ...)
865         // ```
866         //
867         // where `_moved_val` is the place we generated the move error for,
868         // `_temp` is some other local, and `FnSelfCall` is a function
869         // that has a `self` parameter.
870
871         let target_temp = match stmt.kind {
872             StatementKind::Assign(box (temp, _)) if temp.as_local().is_some() => {
873                 temp.as_local().unwrap()
874             }
875             _ => return normal_ret,
876         };
877
878         debug!("move_spans: target_temp = {:?}", target_temp);
879
880         if let Some(Terminator {
881             kind: TerminatorKind::Call { fn_span, from_hir_call, .. }, ..
882         }) = &self.body[location.block].terminator
883         {
884             let Some((method_did, method_substs)) =
885                 rustc_const_eval::util::find_self_call(
886                     self.infcx.tcx,
887                     &self.body,
888                     target_temp,
889                     location.block,
890                 )
891             else {
892                 return normal_ret;
893             };
894
895             let kind = call_kind(
896                 self.infcx.tcx,
897                 self.param_env,
898                 method_did,
899                 method_substs,
900                 *fn_span,
901                 *from_hir_call,
902                 Some(self.infcx.tcx.fn_arg_names(method_did)[0]),
903             );
904
905             return FnSelfUse {
906                 var_span: stmt.source_info.span,
907                 fn_call_span: *fn_span,
908                 fn_span: self.infcx.tcx.def_span(method_did),
909                 kind,
910             };
911         }
912         normal_ret
913     }
914
915     /// Finds the span of arguments of a closure (within `maybe_closure_span`)
916     /// and its usage of the local assigned at `location`.
917     /// This is done by searching in statements succeeding `location`
918     /// and originating from `maybe_closure_span`.
919     pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
920         use self::UseSpans::*;
921         debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
922
923         let target = match self.body[location.block].statements.get(location.statement_index) {
924             Some(Statement { kind: StatementKind::Assign(box (place, _)), .. }) => {
925                 if let Some(local) = place.as_local() {
926                     local
927                 } else {
928                     return OtherUse(use_span);
929                 }
930             }
931             _ => return OtherUse(use_span),
932         };
933
934         if self.body.local_kind(target) != LocalKind::Temp {
935             // operands are always temporaries.
936             return OtherUse(use_span);
937         }
938
939         for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
940             if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind {
941                 let (&def_id, is_generator) = match kind {
942                     box AggregateKind::Closure(def_id, _) => (def_id, false),
943                     box AggregateKind::Generator(def_id, _, _) => (def_id, true),
944                     _ => continue,
945                 };
946
947                 debug!(
948                     "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
949                     def_id, is_generator, places
950                 );
951                 if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
952                     self.closure_span(def_id, Place::from(target).as_ref(), places)
953                 {
954                     return ClosureUse { generator_kind, args_span, capture_kind_span, path_span };
955                 } else {
956                     return OtherUse(use_span);
957                 }
958             }
959
960             if use_span != stmt.source_info.span {
961                 break;
962             }
963         }
964
965         OtherUse(use_span)
966     }
967
968     /// Finds the spans of a captured place within a closure or generator.
969     /// The first span is the location of the use resulting in the capture kind of the capture
970     /// The second span is the location the use resulting in the captured path of the capture
971     fn closure_span(
972         &self,
973         def_id: LocalDefId,
974         target_place: PlaceRef<'tcx>,
975         places: &[Operand<'tcx>],
976     ) -> Option<(Span, Option<GeneratorKind>, Span, Span)> {
977         debug!(
978             "closure_span: def_id={:?} target_place={:?} places={:?}",
979             def_id, target_place, places
980         );
981         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(def_id);
982         let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
983         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
984         if let hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) = expr {
985             for (captured_place, place) in
986                 self.infcx.tcx.typeck(def_id).closure_min_captures_flattened(def_id).zip(places)
987             {
988                 match place {
989                     Operand::Copy(place) | Operand::Move(place)
990                         if target_place == place.as_ref() =>
991                     {
992                         debug!("closure_span: found captured local {:?}", place);
993                         let body = self.infcx.tcx.hir().body(body);
994                         let generator_kind = body.generator_kind();
995
996                         return Some((
997                             fn_decl_span,
998                             generator_kind,
999                             captured_place.get_capture_kind_span(self.infcx.tcx),
1000                             captured_place.get_path_span(self.infcx.tcx),
1001                         ));
1002                     }
1003                     _ => {}
1004                 }
1005             }
1006         }
1007         None
1008     }
1009
1010     /// Helper to retrieve span(s) of given borrow from the current MIR
1011     /// representation
1012     pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
1013         let span = self.body.source_info(borrow.reserve_location).span;
1014         self.borrow_spans(span, borrow.reserve_location)
1015     }
1016
1017     fn explain_captures(
1018         &mut self,
1019         err: &mut Diagnostic,
1020         span: Span,
1021         move_span: Span,
1022         move_spans: UseSpans<'tcx>,
1023         moved_place: Place<'tcx>,
1024         partially_str: &str,
1025         loop_message: &str,
1026         move_msg: &str,
1027         is_loop_move: bool,
1028         maybe_reinitialized_locations_is_empty: bool,
1029     ) {
1030         if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {
1031             let place_name = self
1032                 .describe_place(moved_place.as_ref())
1033                 .map(|n| format!("`{}`", n))
1034                 .unwrap_or_else(|| "value".to_owned());
1035             match kind {
1036                 CallKind::FnCall { fn_trait_id, .. }
1037                     if Some(fn_trait_id) == self.infcx.tcx.lang_items().fn_once_trait() =>
1038                 {
1039                     err.span_label(
1040                         fn_call_span,
1041                         &format!(
1042                             "{} {}moved due to this call{}",
1043                             place_name, partially_str, loop_message
1044                         ),
1045                     );
1046                     err.span_note(
1047                         var_span,
1048                         "this value implements `FnOnce`, which causes it to be moved when called",
1049                     );
1050                 }
1051                 CallKind::Operator { self_arg, .. } => {
1052                     let self_arg = self_arg.unwrap();
1053                     err.span_label(
1054                         fn_call_span,
1055                         &format!(
1056                             "{} {}moved due to usage in operator{}",
1057                             place_name, partially_str, loop_message
1058                         ),
1059                     );
1060                     if self.fn_self_span_reported.insert(fn_span) {
1061                         err.span_note(
1062                             self_arg.span,
1063                             "calling this operator moves the left-hand side",
1064                         );
1065                     }
1066                 }
1067                 CallKind::Normal { self_arg, desugaring, method_did } => {
1068                     let self_arg = self_arg.unwrap();
1069                     if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
1070                         let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
1071                         let suggest = match self.infcx.tcx.get_diagnostic_item(sym::IntoIterator) {
1072                             Some(def_id) => {
1073                                 let infcx = self.infcx.tcx.infer_ctxt().build();
1074                                 type_known_to_meet_bound_modulo_regions(
1075                                     &infcx,
1076                                     self.param_env,
1077                                     infcx.tcx.mk_imm_ref(
1078                                         infcx.tcx.lifetimes.re_erased,
1079                                         infcx.tcx.erase_regions(ty),
1080                                     ),
1081                                     def_id,
1082                                     DUMMY_SP,
1083                                 )
1084                             }
1085                             _ => false,
1086                         };
1087                         if suggest {
1088                             err.span_suggestion_verbose(
1089                                 move_span.shrink_to_lo(),
1090                                 &format!(
1091                                     "consider iterating over a slice of the `{}`'s content to \
1092                                      avoid moving into the `for` loop",
1093                                     ty,
1094                                 ),
1095                                 "&",
1096                                 Applicability::MaybeIncorrect,
1097                             );
1098                         }
1099
1100                         err.span_label(
1101                             fn_call_span,
1102                             &format!(
1103                                 "{} {}moved due to this implicit call to `.into_iter()`{}",
1104                                 place_name, partially_str, loop_message
1105                             ),
1106                         );
1107                         // If the moved place was a `&mut` ref, then we can
1108                         // suggest to reborrow it where it was moved, so it
1109                         // will still be valid by the time we get to the usage.
1110                         if let ty::Ref(_, _, hir::Mutability::Mut) =
1111                             moved_place.ty(self.body, self.infcx.tcx).ty.kind()
1112                         {
1113                             // If we are in a loop this will be suggested later.
1114                             if !is_loop_move {
1115                                 err.span_suggestion_verbose(
1116                                     move_span.shrink_to_lo(),
1117                                     &format!(
1118                                         "consider creating a fresh reborrow of {} here",
1119                                         self.describe_place(moved_place.as_ref())
1120                                             .map(|n| format!("`{}`", n))
1121                                             .unwrap_or_else(|| "the mutable reference".to_string()),
1122                                     ),
1123                                     "&mut *",
1124                                     Applicability::MachineApplicable,
1125                                 );
1126                             }
1127                         }
1128                     } else {
1129                         err.span_label(
1130                             fn_call_span,
1131                             &format!(
1132                                 "{} {}moved due to this method call{}",
1133                                 place_name, partially_str, loop_message
1134                             ),
1135                         );
1136                     }
1137                     let tcx = self.infcx.tcx;
1138                     // Avoid pointing to the same function in multiple different
1139                     // error messages.
1140                     if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1141                         let func = tcx.def_path_str(method_did);
1142                         err.span_note(
1143                             self_arg.span,
1144                             &format!("`{func}` takes ownership of the receiver `self`, which moves {place_name}")
1145                         );
1146                     }
1147                     let parent_did = tcx.parent(method_did);
1148                     let parent_self_ty = (tcx.def_kind(parent_did)
1149                         == rustc_hir::def::DefKind::Impl)
1150                         .then_some(parent_did)
1151                         .and_then(|did| match tcx.type_of(did).kind() {
1152                             ty::Adt(def, ..) => Some(def.did()),
1153                             _ => None,
1154                         });
1155                     let is_option_or_result = parent_self_ty.map_or(false, |def_id| {
1156                         matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
1157                     });
1158                     if is_option_or_result && maybe_reinitialized_locations_is_empty {
1159                         err.span_label(
1160                             var_span,
1161                             "help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents",
1162                         );
1163                     }
1164                 }
1165                 // Other desugarings takes &self, which cannot cause a move
1166                 _ => {}
1167             }
1168         } else {
1169             if move_span != span || !loop_message.is_empty() {
1170                 err.span_label(
1171                     move_span,
1172                     format!("value {}moved{} here{}", partially_str, move_msg, loop_message),
1173                 );
1174             }
1175             // If the move error occurs due to a loop, don't show
1176             // another message for the same span
1177             if loop_message.is_empty() {
1178                 move_spans.var_span_label(
1179                     err,
1180                     format!("variable {}moved due to use{}", partially_str, move_spans.describe()),
1181                     "moved",
1182                 );
1183             }
1184         }
1185     }
1186 }