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