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