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