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