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