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