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