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