]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/mod.rs
Rollup merge of #75485 - RalfJung:pin, r=nagisa
[rust.git] / src / librustc_mir / borrow_check / diagnostics / mod.rs
1 //! Borrow checker diagnostics.
2
3 use rustc_errors::DiagnosticBuilder;
4 use rustc_hir as hir;
5 use rustc_hir::def::Namespace;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::lang_items::LangItemGroup;
8 use rustc_hir::GeneratorKind;
9 use rustc_middle::mir::{
10     AggregateKind, Constant, Field, Local, LocalInfo, LocalKind, Location, Operand, Place,
11     PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
12 };
13 use rustc_middle::ty::print::Print;
14 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt};
15 use rustc_span::{
16     hygiene::{DesugaringKind, ForLoopLoc},
17     symbol::sym,
18     Span,
19 };
20 use rustc_target::abi::VariantIdx;
21
22 use super::borrow_set::BorrowData;
23 use super::MirBorrowckCtxt;
24 use crate::dataflow::move_paths::{InitLocation, LookupResult};
25
26 mod find_use;
27 mod outlives_suggestion;
28 mod region_name;
29 mod var_name;
30
31 mod conflict_errors;
32 mod explain_borrow;
33 mod move_errors;
34 mod mutability_errors;
35 mod region_errors;
36
37 crate use mutability_errors::AccessKind;
38 crate use outlives_suggestion::OutlivesSuggestionBuilder;
39 crate use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
40 crate use region_name::{RegionName, RegionNameSource};
41 use rustc_span::symbol::Ident;
42
43 pub(super) struct IncludingDowncast(pub(super) bool);
44
45 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
46     /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
47     /// is moved after being invoked.
48     ///
49     /// ```text
50     /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
51     ///       its environment
52     ///   --> $DIR/issue-42065.rs:16:29
53     ///    |
54     /// LL |         for (key, value) in dict {
55     ///    |                             ^^^^
56     /// ```
57     pub(super) fn add_moved_or_invoked_closure_note(
58         &self,
59         location: Location,
60         place: PlaceRef<'tcx>,
61         diag: &mut DiagnosticBuilder<'_>,
62     ) {
63         debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
64         let mut target = place.local_or_deref_local();
65         for stmt in &self.body[location.block].statements[location.statement_index..] {
66             debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
67             if let StatementKind::Assign(box (into, Rvalue::Use(from))) = &stmt.kind {
68                 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
69                 match from {
70                     Operand::Copy(ref place) | Operand::Move(ref place)
71                         if target == place.local_or_deref_local() =>
72                     {
73                         target = into.local_or_deref_local()
74                     }
75                     _ => {}
76                 }
77             }
78         }
79
80         // Check if we are attempting to call a closure after it has been invoked.
81         let terminator = self.body[location.block].terminator();
82         debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
83         if let TerminatorKind::Call {
84             func:
85                 Operand::Constant(box Constant {
86                     literal: ty::Const { ty: &ty::TyS { kind: ty::FnDef(id, _), .. }, .. },
87                     ..
88                 }),
89             args,
90             ..
91         } = &terminator.kind
92         {
93             debug!("add_moved_or_invoked_closure_note: id={:?}", id);
94             if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
95                 let closure = match args.first() {
96                     Some(Operand::Copy(ref place)) | Some(Operand::Move(ref place))
97                         if target == place.local_or_deref_local() =>
98                     {
99                         place.local_or_deref_local().unwrap()
100                     }
101                     _ => return,
102                 };
103
104                 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
105                 if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind {
106                     let did = did.expect_local();
107                     let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
108
109                     if let Some((span, name)) =
110                         self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
111                     {
112                         diag.span_note(
113                             *span,
114                             &format!(
115                                 "closure cannot be invoked more than once because it moves the \
116                                  variable `{}` out of its environment",
117                                 name,
118                             ),
119                         );
120                         return;
121                     }
122                 }
123             }
124         }
125
126         // Check if we are just moving a closure after it has been invoked.
127         if let Some(target) = target {
128             if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind {
129                 let did = did.expect_local();
130                 let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
131
132                 if let Some((span, name)) =
133                     self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
134                 {
135                     diag.span_note(
136                         *span,
137                         &format!(
138                             "closure cannot be moved more than once as it is not `Copy` due to \
139                              moving the variable `{}` out of its environment",
140                             name
141                         ),
142                     );
143                 }
144             }
145         }
146     }
147
148     /// End-user visible description of `place` if one can be found.
149     /// If the place is a temporary for instance, `"value"` will be returned.
150     pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
151         match self.describe_place(place_ref) {
152             Some(mut descr) => {
153                 // Surround descr with `backticks`.
154                 descr.reserve(2);
155                 descr.insert_str(0, "`");
156                 descr.push_str("`");
157                 descr
158             }
159             None => "value".to_string(),
160         }
161     }
162
163     /// End-user visible description of `place` if one can be found.
164     /// If the place is a temporary for instance, None will be returned.
165     pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
166         self.describe_place_with_options(place_ref, IncludingDowncast(false))
167     }
168
169     /// End-user visible description of `place` if one can be found. If the
170     /// place is a temporary for instance, None will be returned.
171     /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
172     /// `Downcast` and `IncludingDowncast` is true
173     pub(super) fn describe_place_with_options(
174         &self,
175         place: PlaceRef<'tcx>,
176         including_downcast: IncludingDowncast,
177     ) -> Option<String> {
178         let mut buf = String::new();
179         match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
180             Ok(()) => Some(buf),
181             Err(()) => None,
182         }
183     }
184
185     /// Appends end-user visible description of `place` to `buf`.
186     fn append_place_to_string(
187         &self,
188         place: PlaceRef<'tcx>,
189         buf: &mut String,
190         mut autoderef: bool,
191         including_downcast: &IncludingDowncast,
192     ) -> Result<(), ()> {
193         match place {
194             PlaceRef { local, projection: [] } => {
195                 self.append_local_to_string(local, buf)?;
196             }
197             PlaceRef { local, projection: [ProjectionElem::Deref] }
198                 if self.body.local_decls[local].is_ref_for_guard() =>
199             {
200                 self.append_place_to_string(
201                     PlaceRef { local, projection: &[] },
202                     buf,
203                     autoderef,
204                     &including_downcast,
205                 )?;
206             }
207             PlaceRef { local, projection: [ProjectionElem::Deref] }
208                 if self.body.local_decls[local].is_ref_to_static() =>
209             {
210                 let local_info = &self.body.local_decls[local].local_info;
211                 if let Some(box LocalInfo::StaticRef { def_id, .. }) = *local_info {
212                     buf.push_str(&self.infcx.tcx.item_name(def_id).as_str());
213                 } else {
214                     unreachable!();
215                 }
216             }
217             PlaceRef { local, projection: [proj_base @ .., elem] } => {
218                 match elem {
219                     ProjectionElem::Deref => {
220                         let upvar_field_projection = self.is_upvar_field_projection(place);
221                         if let Some(field) = upvar_field_projection {
222                             let var_index = field.index();
223                             let name = self.upvars[var_index].name.to_string();
224                             if self.upvars[var_index].by_ref {
225                                 buf.push_str(&name);
226                             } else {
227                                 buf.push_str(&format!("*{}", &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_str(&"*");
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                         let upvar_field_projection = self.is_upvar_field_projection(place);
264                         if let Some(field) = upvar_field_projection {
265                             let var_index = field.index();
266                             let name = self.upvars[var_index].name.to_string();
267                             buf.push_str(&name);
268                         } else {
269                             let field_name = self
270                                 .describe_field(PlaceRef { local, projection: proj_base }, *field);
271                             self.append_place_to_string(
272                                 PlaceRef { local, projection: proj_base },
273                                 buf,
274                                 autoderef,
275                                 &including_downcast,
276                             )?;
277                             buf.push_str(&format!(".{}", field_name));
278                         }
279                     }
280                     ProjectionElem::Index(index) => {
281                         autoderef = true;
282
283                         self.append_place_to_string(
284                             PlaceRef { local, projection: proj_base },
285                             buf,
286                             autoderef,
287                             &including_downcast,
288                         )?;
289                         buf.push_str("[");
290                         if self.append_local_to_string(*index, buf).is_err() {
291                             buf.push_str("_");
292                         }
293                         buf.push_str("]");
294                     }
295                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
296                         autoderef = true;
297                         // Since it isn't possible to borrow an element on a particular index and
298                         // then use another while the borrow is held, don't output indices details
299                         // to avoid confusing the end-user
300                         self.append_place_to_string(
301                             PlaceRef { local, projection: proj_base },
302                             buf,
303                             autoderef,
304                             &including_downcast,
305                         )?;
306                         buf.push_str(&"[..]");
307                     }
308                 };
309             }
310         }
311
312         Ok(())
313     }
314
315     /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
316     /// a name, or its name was generated by the compiler, then `Err` is returned
317     fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
318         let decl = &self.body.local_decls[local];
319         match self.local_names[local] {
320             Some(name) if !decl.from_compiler_desugaring() => {
321                 buf.push_str(&name.as_str());
322                 Ok(())
323             }
324             _ => Err(()),
325         }
326     }
327
328     /// End-user visible description of the `field`nth field of `base`
329     fn describe_field(&self, place: PlaceRef<'tcx>, field: Field) -> String {
330         // FIXME Place2 Make this work iteratively
331         match place {
332             PlaceRef { local, projection: [] } => {
333                 let local = &self.body.local_decls[local];
334                 self.describe_field_from_ty(&local.ty, field, None)
335             }
336             PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
337                 ProjectionElem::Deref => {
338                     self.describe_field(PlaceRef { local, projection: proj_base }, field)
339                 }
340                 ProjectionElem::Downcast(_, variant_index) => {
341                     let base_ty =
342                         Place::ty_from(place.local, place.projection, self.body, self.infcx.tcx).ty;
343                     self.describe_field_from_ty(&base_ty, field, Some(*variant_index))
344                 }
345                 ProjectionElem::Field(_, field_type) => {
346                     self.describe_field_from_ty(&field_type, field, None)
347                 }
348                 ProjectionElem::Index(..)
349                 | ProjectionElem::ConstantIndex { .. }
350                 | ProjectionElem::Subslice { .. } => {
351                     self.describe_field(PlaceRef { local, projection: proj_base }, field)
352                 }
353             },
354         }
355     }
356
357     /// End-user visible description of the `field_index`nth field of `ty`
358     fn describe_field_from_ty(
359         &self,
360         ty: Ty<'_>,
361         field: Field,
362         variant_index: Option<VariantIdx>,
363     ) -> String {
364         if ty.is_box() {
365             // If the type is a box, the field is described from the boxed type
366             self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
367         } else {
368             match ty.kind {
369                 ty::Adt(def, _) => {
370                     let variant = if let Some(idx) = variant_index {
371                         assert!(def.is_enum());
372                         &def.variants[idx]
373                     } else {
374                         def.non_enum_variant()
375                     };
376                     variant.fields[field.index()].ident.to_string()
377                 }
378                 ty::Tuple(_) => field.index().to_string(),
379                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
380                     self.describe_field_from_ty(&ty, field, variant_index)
381                 }
382                 ty::Array(ty, _) | ty::Slice(ty) => {
383                     self.describe_field_from_ty(&ty, field, variant_index)
384                 }
385                 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
386                     // `tcx.upvars_mentioned(def_id)` returns an `Option`, which is `None` in case
387                     // the closure comes from another crate. But in that case we wouldn't
388                     // be borrowck'ing it, so we can just unwrap:
389                     let (&var_id, _) = self
390                         .infcx
391                         .tcx
392                         .upvars_mentioned(def_id)
393                         .unwrap()
394                         .get_index(field.index())
395                         .unwrap();
396
397                     self.infcx.tcx.hir().name(var_id).to_string()
398                 }
399                 _ => {
400                     // Might need a revision when the fields in trait RFC is implemented
401                     // (https://github.com/rust-lang/rfcs/pull/1546)
402                     bug!("End-user description not implemented for field access on `{:?}`", ty);
403                 }
404             }
405         }
406     }
407
408     /// Add a note that a type does not implement `Copy`
409     pub(super) fn note_type_does_not_implement_copy(
410         &self,
411         err: &mut DiagnosticBuilder<'a>,
412         place_desc: &str,
413         ty: Ty<'tcx>,
414         span: Option<Span>,
415     ) {
416         let message = format!(
417             "move occurs because {} has type `{}`, which does not implement the `Copy` trait",
418             place_desc, ty,
419         );
420         if let Some(span) = span {
421             err.span_label(span, message);
422         } else {
423             err.note(&message);
424         }
425     }
426
427     pub(super) fn borrowed_content_source(
428         &self,
429         deref_base: PlaceRef<'tcx>,
430     ) -> BorrowedContentSource<'tcx> {
431         let tcx = self.infcx.tcx;
432
433         // Look up the provided place and work out the move path index for it,
434         // we'll use this to check whether it was originally from an overloaded
435         // operator.
436         match self.move_data.rev_lookup.find(deref_base) {
437             LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
438                 debug!("borrowed_content_source: mpi={:?}", mpi);
439
440                 for i in &self.move_data.init_path_map[mpi] {
441                     let init = &self.move_data.inits[*i];
442                     debug!("borrowed_content_source: init={:?}", init);
443                     // We're only interested in statements that initialized a value, not the
444                     // initializations from arguments.
445                     let loc = match init.location {
446                         InitLocation::Statement(stmt) => stmt,
447                         _ => continue,
448                     };
449
450                     let bbd = &self.body[loc.block];
451                     let is_terminator = bbd.statements.len() == loc.statement_index;
452                     debug!(
453                         "borrowed_content_source: loc={:?} is_terminator={:?}",
454                         loc, is_terminator,
455                     );
456                     if !is_terminator {
457                         continue;
458                     } else if let Some(Terminator {
459                         kind: TerminatorKind::Call { ref func, from_hir_call: false, .. },
460                         ..
461                     }) = bbd.terminator
462                     {
463                         if let Some(source) =
464                             BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
465                         {
466                             return source;
467                         }
468                     }
469                 }
470             }
471             // Base is a `static` so won't be from an overloaded operator
472             _ => (),
473         };
474
475         // If we didn't find an overloaded deref or index, then assume it's a
476         // built in deref and check the type of the base.
477         let base_ty = Place::ty_from(deref_base.local, deref_base.projection, self.body, tcx).ty;
478         if base_ty.is_unsafe_ptr() {
479             BorrowedContentSource::DerefRawPointer
480         } else if base_ty.is_mutable_ptr() {
481             BorrowedContentSource::DerefMutableRef
482         } else {
483             BorrowedContentSource::DerefSharedRef
484         }
485     }
486 }
487
488 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
489     /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
490     /// name where required.
491     pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
492         let mut s = String::new();
493         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
494
495         // We need to add synthesized lifetimes where appropriate. We do
496         // this by hooking into the pretty printer and telling it to label the
497         // lifetimes without names with the value `'0`.
498         match ty.kind {
499             ty::Ref(
500                 ty::RegionKind::ReLateBound(_, br)
501                 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
502                 _,
503                 _,
504             ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
505             _ => {}
506         }
507
508         let _ = ty.print(printer);
509         s
510     }
511
512     /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
513     /// synthesized lifetime name where required.
514     pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
515         let mut s = String::new();
516         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
517
518         let region = match ty.kind {
519             ty::Ref(region, _, _) => {
520                 match region {
521                     ty::RegionKind::ReLateBound(_, br)
522                     | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
523                         printer.region_highlight_mode.highlighting_bound_region(*br, counter)
524                     }
525                     _ => {}
526                 }
527
528                 region
529             }
530             _ => bug!("ty for annotation of borrow region is not a reference"),
531         };
532
533         let _ = region.print(printer);
534         s
535     }
536 }
537
538 /// The span(s) associated to a use of a place.
539 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
540 pub(super) enum UseSpans {
541     /// The access is caused by capturing a variable for a closure.
542     ClosureUse {
543         /// This is true if the captured variable was from a generator.
544         generator_kind: Option<GeneratorKind>,
545         /// The span of the args of the closure, including the `move` keyword if
546         /// it's present.
547         args_span: Span,
548         /// The span of the first use of the captured variable inside the closure.
549         var_span: Span,
550     },
551     /// The access is caused by using a variable as the receiver of a method
552     /// that takes 'self'
553     FnSelfUse {
554         /// The span of the variable being moved
555         var_span: Span,
556         /// The span of the method call on the variable
557         fn_call_span: Span,
558         /// The definition span of the method being called
559         fn_span: Span,
560         kind: FnSelfUseKind,
561     },
562     /// This access is caused by a `match` or `if let` pattern.
563     PatUse(Span),
564     /// This access has a single span associated to it: common case.
565     OtherUse(Span),
566 }
567
568 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
569 pub(super) enum FnSelfUseKind {
570     /// A normal method call of the form `receiver.foo(a, b, c)`
571     Normal { self_arg: Ident, implicit_into_iter: bool },
572     /// A call to `FnOnce::call_once`, desugared from `my_closure(a, b, c)`
573     FnOnceCall,
574     /// A call to an operator trait, desuraged from operator syntax (e.g. `a << b`)
575     Operator { self_arg: Ident },
576 }
577
578 impl UseSpans {
579     pub(super) fn args_or_use(self) -> Span {
580         match self {
581             UseSpans::ClosureUse { args_span: span, .. }
582             | UseSpans::PatUse(span)
583             | UseSpans::FnSelfUse { var_span: span, .. }
584             | UseSpans::OtherUse(span) => span,
585         }
586     }
587
588     pub(super) fn var_or_use(self) -> Span {
589         match self {
590             UseSpans::ClosureUse { var_span: span, .. }
591             | UseSpans::PatUse(span)
592             | UseSpans::FnSelfUse { var_span: span, .. }
593             | UseSpans::OtherUse(span) => span,
594         }
595     }
596
597     pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
598         match self {
599             UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
600             _ => None,
601         }
602     }
603
604     // Add a span label to the arguments of the closure, if it exists.
605     pub(super) fn args_span_label(
606         self,
607         err: &mut DiagnosticBuilder<'_>,
608         message: impl Into<String>,
609     ) {
610         if let UseSpans::ClosureUse { args_span, .. } = self {
611             err.span_label(args_span, message);
612         }
613     }
614
615     // Add a span label to the use of the captured variable, if it exists.
616     pub(super) fn var_span_label(
617         self,
618         err: &mut DiagnosticBuilder<'_>,
619         message: impl Into<String>,
620     ) {
621         if let UseSpans::ClosureUse { var_span, .. } = self {
622             err.span_label(var_span, message);
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) -> String {
644         match *self {
645             UseSpans::ClosureUse { generator_kind, .. } => {
646                 if generator_kind.is_some() {
647                     " in generator".to_string()
648                 } else {
649                     " in closure".to_string()
650                 }
651             }
652             _ => "".to_string(),
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 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) => match ty.kind {
683                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Rc, def.did) => {
684                     "an `Rc`".to_string()
685                 }
686                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Arc, def.did) => {
687                     "an `Arc`".to_string()
688                 }
689                 _ => format!("dereference of `{}`", ty),
690             },
691             BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
692         }
693     }
694
695     pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
696         match *self {
697             BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
698             BorrowedContentSource::DerefSharedRef => Some("shared reference"),
699             BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
700             // Overloaded deref and index operators should be evaluated into a
701             // temporary. So we don't need a description here.
702             BorrowedContentSource::OverloadedDeref(_)
703             | BorrowedContentSource::OverloadedIndex(_) => None,
704         }
705     }
706
707     pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
708         match *self {
709             BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
710             BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
711             BorrowedContentSource::DerefMutableRef => {
712                 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
713             }
714             BorrowedContentSource::OverloadedDeref(ty) => match ty.kind {
715                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Rc, def.did) => {
716                     "an `Rc`".to_string()
717                 }
718                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Arc, def.did) => {
719                     "an `Arc`".to_string()
720                 }
721                 _ => format!("a dereference of `{}`", ty),
722             },
723             BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
724         }
725     }
726
727     fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
728         match func.kind {
729             ty::FnDef(def_id, substs) => {
730                 let trait_id = tcx.trait_of_item(def_id)?;
731
732                 let lang_items = tcx.lang_items();
733                 if Some(trait_id) == lang_items.deref_trait()
734                     || Some(trait_id) == lang_items.deref_mut_trait()
735                 {
736                     Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
737                 } else if Some(trait_id) == lang_items.index_trait()
738                     || Some(trait_id) == lang_items.index_mut_trait()
739                 {
740                     Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
741                 } else {
742                     None
743                 }
744             }
745             _ => None,
746         }
747     }
748 }
749
750 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
751     /// Finds the spans associated to a move or copy of move_place at location.
752     pub(super) fn move_spans(
753         &self,
754         moved_place: PlaceRef<'tcx>, // Could also be an upvar.
755         location: Location,
756     ) -> UseSpans {
757         use self::UseSpans::*;
758
759         let stmt = match self.body[location.block].statements.get(location.statement_index) {
760             Some(stmt) => stmt,
761             None => return OtherUse(self.body.source_info(location).span),
762         };
763
764         debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
765         if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) = stmt.kind {
766             match kind {
767                 box AggregateKind::Closure(def_id, _)
768                 | box AggregateKind::Generator(def_id, _, _) => {
769                     debug!("move_spans: def_id={:?} places={:?}", def_id, places);
770                     if let Some((args_span, generator_kind, var_span)) =
771                         self.closure_span(*def_id, moved_place, places)
772                     {
773                         return ClosureUse { generator_kind, args_span, var_span };
774                     }
775                 }
776                 _ => {}
777             }
778         }
779
780         let normal_ret =
781             if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {
782                 PatUse(stmt.source_info.span)
783             } else {
784                 OtherUse(stmt.source_info.span)
785             };
786
787         // We are trying to find MIR of the form:
788         // ```
789         // _temp = _moved_val;
790         // ...
791         // FnSelfCall(_temp, ...)
792         // ```
793         //
794         // where `_moved_val` is the place we generated the move error for,
795         // `_temp` is some other local, and `FnSelfCall` is a function
796         // that has a `self` parameter.
797
798         let target_temp = match stmt.kind {
799             StatementKind::Assign(box (temp, _)) if temp.as_local().is_some() => {
800                 temp.as_local().unwrap()
801             }
802             _ => return normal_ret,
803         };
804
805         debug!("move_spans: target_temp = {:?}", target_temp);
806
807         if let Some(Terminator {
808             kind: TerminatorKind::Call { func, args, fn_span, from_hir_call, .. },
809             ..
810         }) = &self.body[location.block].terminator
811         {
812             let mut method_did = None;
813             if let Operand::Constant(box Constant { literal: ty::Const { ty, .. }, .. }) = func {
814                 if let ty::FnDef(def_id, _) = ty.kind {
815                     debug!("move_spans: fn = {:?}", def_id);
816                     if let Some(ty::AssocItem { fn_has_self_parameter, .. }) =
817                         self.infcx.tcx.opt_associated_item(def_id)
818                     {
819                         if *fn_has_self_parameter {
820                             method_did = Some(def_id);
821                         }
822                     }
823                 }
824             }
825
826             let tcx = self.infcx.tcx;
827             let method_did = if let Some(did) = method_did { did } else { return normal_ret };
828
829             if let [Operand::Move(self_place), ..] = **args {
830                 if self_place.as_local() == Some(target_temp) {
831                     let parent = tcx.parent(method_did);
832                     let is_fn_once = parent == tcx.lang_items().fn_once_trait();
833                     let is_operator = !from_hir_call
834                         && parent.map_or(false, |p| {
835                             tcx.lang_items().group(LangItemGroup::Op).contains(&p)
836                         });
837                     let fn_call_span = *fn_span;
838
839                     let self_arg = tcx.fn_arg_names(method_did)[0];
840
841                     let kind = if is_fn_once {
842                         FnSelfUseKind::FnOnceCall
843                     } else if is_operator {
844                         FnSelfUseKind::Operator { self_arg }
845                     } else {
846                         debug!(
847                             "move_spans: method_did={:?}, fn_call_span={:?}",
848                             method_did, fn_call_span
849                         );
850                         let implicit_into_iter = matches!(
851                             fn_call_span.desugaring_kind(),
852                             Some(DesugaringKind::ForLoop(ForLoopLoc::IntoIter))
853                         );
854                         FnSelfUseKind::Normal { self_arg, implicit_into_iter }
855                     };
856
857                     return FnSelfUse {
858                         var_span: stmt.source_info.span,
859                         fn_call_span,
860                         fn_span: self
861                             .infcx
862                             .tcx
863                             .sess
864                             .source_map()
865                             .guess_head_span(self.infcx.tcx.def_span(method_did)),
866                         kind,
867                     };
868                 }
869             }
870         }
871         normal_ret
872     }
873
874     /// Finds the span of arguments of a closure (within `maybe_closure_span`)
875     /// and its usage of the local assigned at `location`.
876     /// This is done by searching in statements succeeding `location`
877     /// and originating from `maybe_closure_span`.
878     pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
879         use self::UseSpans::*;
880         debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
881
882         let target = match self.body[location.block].statements.get(location.statement_index) {
883             Some(&Statement { kind: StatementKind::Assign(box (ref place, _)), .. }) => {
884                 if let Some(local) = place.as_local() {
885                     local
886                 } else {
887                     return OtherUse(use_span);
888                 }
889             }
890             _ => return OtherUse(use_span),
891         };
892
893         if self.body.local_kind(target) != LocalKind::Temp {
894             // operands are always temporaries.
895             return OtherUse(use_span);
896         }
897
898         for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
899             if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) =
900                 stmt.kind
901             {
902                 let (def_id, is_generator) = match kind {
903                     box AggregateKind::Closure(def_id, _) => (def_id, false),
904                     box AggregateKind::Generator(def_id, _, _) => (def_id, true),
905                     _ => continue,
906                 };
907
908                 debug!(
909                     "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
910                     def_id, is_generator, places
911                 );
912                 if let Some((args_span, generator_kind, var_span)) =
913                     self.closure_span(*def_id, Place::from(target).as_ref(), places)
914                 {
915                     return ClosureUse { generator_kind, args_span, var_span };
916                 } else {
917                     return OtherUse(use_span);
918                 }
919             }
920
921             if use_span != stmt.source_info.span {
922                 break;
923             }
924         }
925
926         OtherUse(use_span)
927     }
928
929     /// Finds the span of a captured variable within a closure or generator.
930     fn closure_span(
931         &self,
932         def_id: DefId,
933         target_place: PlaceRef<'tcx>,
934         places: &Vec<Operand<'tcx>>,
935     ) -> Option<(Span, Option<GeneratorKind>, Span)> {
936         debug!(
937             "closure_span: def_id={:?} target_place={:?} places={:?}",
938             def_id, target_place, places
939         );
940         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(def_id.as_local()?);
941         let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
942         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
943         if let hir::ExprKind::Closure(.., body_id, args_span, _) = expr {
944             for (upvar, place) in self.infcx.tcx.upvars_mentioned(def_id)?.values().zip(places) {
945                 match place {
946                     Operand::Copy(place) | Operand::Move(place)
947                         if target_place == place.as_ref() =>
948                     {
949                         debug!("closure_span: found captured local {:?}", place);
950                         let body = self.infcx.tcx.hir().body(*body_id);
951                         let generator_kind = body.generator_kind();
952                         return Some((*args_span, generator_kind, upvar.span));
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 {
964         let span = self.body.source_info(borrow.reserve_location).span;
965         self.borrow_spans(span, borrow.reserve_location)
966     }
967 }