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