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