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