]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/borrow_check/diagnostics/mod.rs
use hir::Place instead of Symbol in closure_kind_origin
[rust.git] / compiler / rustc_mir / src / 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::lang_items::LangItemGroup;
8 use rustc_hir::GeneratorKind;
9 use rustc_middle::mir::{
10     AggregateKind, Constant, Field, Local, LocalInfo, LocalKind, Location, Operand, Place,
11     PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
12 };
13 use rustc_middle::ty::print::Print;
14 use rustc_middle::ty::{self, DefIdTree, Instance, Ty, TyCtxt};
15 use rustc_span::{
16     hygiene::{DesugaringKind, ForLoopLoc},
17     symbol::sym,
18     Span,
19 };
20 use rustc_target::abi::VariantIdx;
21
22 use super::borrow_set::BorrowData;
23 use super::MirBorrowckCtxt;
24 use crate::dataflow::move_paths::{InitLocation, LookupResult};
25
26 mod find_use;
27 mod outlives_suggestion;
28 mod region_name;
29 mod var_name;
30
31 mod conflict_errors;
32 mod explain_borrow;
33 mod move_errors;
34 mod mutability_errors;
35 mod region_errors;
36
37 crate use mutability_errors::AccessKind;
38 crate use outlives_suggestion::OutlivesSuggestionBuilder;
39 crate use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
40 crate use region_name::{RegionName, RegionNameSource};
41 use rustc_span::symbol::Ident;
42
43 pub(super) struct IncludingDowncast(pub(super) bool);
44
45 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
46     /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
47     /// is moved after being invoked.
48     ///
49     /// ```text
50     /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
51     ///       its environment
52     ///   --> $DIR/issue-42065.rs:16:29
53     ///    |
54     /// LL |         for (key, value) in dict {
55     ///    |                             ^^^^
56     /// ```
57     pub(super) fn add_moved_or_invoked_closure_note(
58         &self,
59         location: Location,
60         place: PlaceRef<'tcx>,
61         diag: &mut DiagnosticBuilder<'_>,
62     ) {
63         debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
64         let mut target = place.local_or_deref_local();
65         for stmt in &self.body[location.block].statements[location.statement_index..] {
66             debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
67             if let StatementKind::Assign(box (into, Rvalue::Use(from))) = &stmt.kind {
68                 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
69                 match from {
70                     Operand::Copy(ref place) | Operand::Move(ref place)
71                         if target == place.local_or_deref_local() =>
72                     {
73                         target = into.local_or_deref_local()
74                     }
75                     _ => {}
76                 }
77             }
78         }
79
80         // Check if we are attempting to call a closure after it has been invoked.
81         let terminator = self.body[location.block].terminator();
82         debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
83         if let TerminatorKind::Call {
84             func: Operand::Constant(box Constant { literal: ty::Const { ty: const_ty, .. }, .. }),
85             args,
86             ..
87         } = &terminator.kind
88         {
89             if let ty::FnDef(id, _) = *const_ty.kind() {
90                 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
91                 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
92                     let closure = match args.first() {
93                         Some(Operand::Copy(ref place)) | Some(Operand::Move(ref place))
94                             if target == place.local_or_deref_local() =>
95                         {
96                             place.local_or_deref_local().unwrap()
97                         }
98                         _ => return,
99                     };
100
101                     debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
102                     if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
103                         let did = did.expect_local();
104                         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
105
106                         if let Some((span, hir_place)) =
107                             self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
108                         {
109                             diag.span_note(
110                                 *span,
111                                 &format!(
112                                     "closure cannot be invoked more than once because it moves the \
113                                     variable `{}` out of its environment",
114                                     ty::place_to_string_for_capture(self.infcx.tcx, hir_place)
115                                 ),
116                             );
117                             return;
118                         }
119                     }
120                 }
121             }
122         }
123
124         // Check if we are just moving a closure after it has been invoked.
125         if let Some(target) = target {
126             if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() {
127                 let did = did.expect_local();
128                 let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
129
130                 if let Some((span, hir_place)) =
131                     self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
132                 {
133                     diag.span_note(
134                         *span,
135                         &format!(
136                             "closure cannot be moved more than once as it is not `Copy` due to \
137                              moving the variable `{}` out of its environment",
138                             ty::place_to_string_for_capture(self.infcx.tcx, hir_place)
139                         ),
140                     );
141                 }
142             }
143         }
144     }
145
146     /// End-user visible description of `place` if one can be found.
147     /// If the place is a temporary for instance, `"value"` will be returned.
148     pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
149         match self.describe_place(place_ref) {
150             Some(mut descr) => {
151                 // Surround descr with `backticks`.
152                 descr.reserve(2);
153                 descr.insert(0, '`');
154                 descr.push('`');
155                 descr
156             }
157             None => "value".to_string(),
158         }
159     }
160
161     /// End-user visible description of `place` if one can be found.
162     /// If the place is a temporary for instance, None will be returned.
163     pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
164         self.describe_place_with_options(place_ref, IncludingDowncast(false))
165     }
166
167     /// End-user visible description of `place` if one can be found. If the
168     /// place is a temporary for instance, None will be returned.
169     /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
170     /// `Downcast` and `IncludingDowncast` is true
171     pub(super) fn describe_place_with_options(
172         &self,
173         place: PlaceRef<'tcx>,
174         including_downcast: IncludingDowncast,
175     ) -> Option<String> {
176         let mut buf = String::new();
177         match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
178             Ok(()) => Some(buf),
179             Err(()) => None,
180         }
181     }
182
183     /// Appends end-user visible description of `place` to `buf`.
184     fn append_place_to_string(
185         &self,
186         place: PlaceRef<'tcx>,
187         buf: &mut String,
188         mut autoderef: bool,
189         including_downcast: &IncludingDowncast,
190     ) -> Result<(), ()> {
191         match place {
192             PlaceRef { local, projection: [] } => {
193                 self.append_local_to_string(local, buf)?;
194             }
195             PlaceRef { local, projection: [ProjectionElem::Deref] }
196                 if self.body.local_decls[local].is_ref_for_guard() =>
197             {
198                 self.append_place_to_string(
199                     PlaceRef { local, projection: &[] },
200                     buf,
201                     autoderef,
202                     &including_downcast,
203                 )?;
204             }
205             PlaceRef { local, projection: [ProjectionElem::Deref] }
206                 if self.body.local_decls[local].is_ref_to_static() =>
207             {
208                 let local_info = &self.body.local_decls[local].local_info;
209                 if let Some(box LocalInfo::StaticRef { def_id, .. }) = *local_info {
210                     buf.push_str(&self.infcx.tcx.item_name(def_id).as_str());
211                 } else {
212                     unreachable!();
213                 }
214             }
215             PlaceRef { local, projection: [proj_base @ .., elem] } => {
216                 match elem {
217                     ProjectionElem::Deref => {
218                         let upvar_field_projection = self.is_upvar_field_projection(place);
219                         if let Some(field) = upvar_field_projection {
220                             let var_index = field.index();
221                             let name = self.upvars[var_index].name.to_string();
222                             if self.upvars[var_index].by_ref {
223                                 buf.push_str(&name);
224                             } else {
225                                 buf.push('*');
226                                 buf.push_str(&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('*');
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('.');
277                             buf.push_str(&field_name);
278                         }
279                     }
280                     ProjectionElem::Index(index) => {
281                         autoderef = true;
282
283                         self.append_place_to_string(
284                             PlaceRef { local, projection: proj_base },
285                             buf,
286                             autoderef,
287                             &including_downcast,
288                         )?;
289                         buf.push('[');
290                         if self.append_local_to_string(*index, buf).is_err() {
291                             buf.push('_');
292                         }
293                         buf.push(']');
294                     }
295                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
296                         autoderef = true;
297                         // Since it isn't possible to borrow an element on a particular index and
298                         // then use another while the borrow is held, don't output indices details
299                         // to avoid confusing the end-user
300                         self.append_place_to_string(
301                             PlaceRef { local, projection: proj_base },
302                             buf,
303                             autoderef,
304                             &including_downcast,
305                         )?;
306                         buf.push_str("[..]");
307                     }
308                 };
309             }
310         }
311
312         Ok(())
313     }
314
315     /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
316     /// a name, or its name was generated by the compiler, then `Err` is returned
317     fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
318         let decl = &self.body.local_decls[local];
319         match self.local_names[local] {
320             Some(name) if !decl.from_compiler_desugaring() => {
321                 buf.push_str(&name.as_str());
322                 Ok(())
323             }
324             _ => Err(()),
325         }
326     }
327
328     /// End-user visible description of the `field`nth field of `base`
329     fn describe_field(&self, place: PlaceRef<'tcx>, field: Field) -> String {
330         // FIXME Place2 Make this work iteratively
331         match place {
332             PlaceRef { local, projection: [] } => {
333                 let local = &self.body.local_decls[local];
334                 self.describe_field_from_ty(&local.ty, field, None)
335             }
336             PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
337                 ProjectionElem::Deref => {
338                     self.describe_field(PlaceRef { local, projection: proj_base }, field)
339                 }
340                 ProjectionElem::Downcast(_, variant_index) => {
341                     let base_ty =
342                         Place::ty_from(place.local, place.projection, self.body, self.infcx.tcx).ty;
343                     self.describe_field_from_ty(&base_ty, field, Some(*variant_index))
344                 }
345                 ProjectionElem::Field(_, field_type) => {
346                     self.describe_field_from_ty(&field_type, field, None)
347                 }
348                 ProjectionElem::Index(..)
349                 | ProjectionElem::ConstantIndex { .. }
350                 | ProjectionElem::Subslice { .. } => {
351                     self.describe_field(PlaceRef { local, projection: proj_base }, field)
352                 }
353             },
354         }
355     }
356
357     /// End-user visible description of the `field_index`nth field of `ty`
358     fn describe_field_from_ty(
359         &self,
360         ty: Ty<'_>,
361         field: Field,
362         variant_index: Option<VariantIdx>,
363     ) -> String {
364         if ty.is_box() {
365             // If the type is a box, the field is described from the boxed type
366             self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
367         } else {
368             match *ty.kind() {
369                 ty::Adt(def, _) => {
370                     let variant = if let Some(idx) = variant_index {
371                         assert!(def.is_enum());
372                         &def.variants[idx]
373                     } else {
374                         def.non_enum_variant()
375                     };
376                     variant.fields[field.index()].ident.to_string()
377                 }
378                 ty::Tuple(_) => field.index().to_string(),
379                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
380                     self.describe_field_from_ty(&ty, field, variant_index)
381                 }
382                 ty::Array(ty, _) | ty::Slice(ty) => {
383                     self.describe_field_from_ty(&ty, field, variant_index)
384                 }
385                 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
386                     // We won't be borrowck'ing here if the closure came from another crate,
387                     // so it's safe to call `expect_local`.
388                     //
389                     // We know the field exists so it's safe to call operator[] and `unwrap` here.
390                     let (&var_id, _) =
391                         self.infcx.tcx.typeck(def_id.expect_local()).closure_captures[&def_id]
392                             .get_index(field.index())
393                             .unwrap();
394
395                     self.infcx.tcx.hir().name(var_id).to_string()
396                 }
397                 _ => {
398                     // Might need a revision when the fields in trait RFC is implemented
399                     // (https://github.com/rust-lang/rfcs/pull/1546)
400                     bug!("End-user description not implemented for field access on `{:?}`", ty);
401                 }
402             }
403         }
404     }
405
406     /// Add a note that a type does not implement `Copy`
407     pub(super) fn note_type_does_not_implement_copy(
408         &self,
409         err: &mut DiagnosticBuilder<'a>,
410         place_desc: &str,
411         ty: Ty<'tcx>,
412         span: Option<Span>,
413         move_prefix: &str,
414     ) {
415         let message = format!(
416             "{}move occurs because {} has type `{}`, which does not implement the `Copy` trait",
417             move_prefix, 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(_, ty::BoundRegion { kind: 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(_, ty::BoundRegion { kind: 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<'tcx> {
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<'tcx>,
560     },
561     /// This access is caused by a `match` or `if let` pattern.
562     PatUse(Span),
563     /// This access has a single span associated to it: common case.
564     OtherUse(Span),
565 }
566
567 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
568 pub(super) enum FnSelfUseKind<'tcx> {
569     /// A normal method call of the form `receiver.foo(a, b, c)`
570     Normal { self_arg: Ident, implicit_into_iter: bool },
571     /// A call to `FnOnce::call_once`, desugared from `my_closure(a, b, c)`
572     FnOnceCall,
573     /// A call to an operator trait, desuraged from operator syntax (e.g. `a << b`)
574     Operator { self_arg: Ident },
575     DerefCoercion {
576         /// The `Span` of the `Target` associated type
577         /// in the `Deref` impl we are using.
578         deref_target: Span,
579         /// The type `T::Deref` we are dereferencing to
580         deref_target_ty: Ty<'tcx>,
581     },
582 }
583
584 impl UseSpans<'_> {
585     pub(super) fn args_or_use(self) -> Span {
586         match self {
587             UseSpans::ClosureUse { args_span: span, .. }
588             | UseSpans::PatUse(span)
589             | UseSpans::OtherUse(span) => span,
590             UseSpans::FnSelfUse {
591                 fn_call_span, kind: FnSelfUseKind::DerefCoercion { .. }, ..
592             } => fn_call_span,
593             UseSpans::FnSelfUse { var_span, .. } => var_span,
594         }
595     }
596
597     pub(super) fn var_or_use(self) -> Span {
598         match self {
599             UseSpans::ClosureUse { var_span: span, .. }
600             | UseSpans::PatUse(span)
601             | UseSpans::OtherUse(span) => span,
602             UseSpans::FnSelfUse {
603                 fn_call_span, kind: FnSelfUseKind::DerefCoercion { .. }, ..
604             } => fn_call_span,
605             UseSpans::FnSelfUse { var_span, .. } => var_span,
606         }
607     }
608
609     pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
610         match self {
611             UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
612             _ => None,
613         }
614     }
615
616     // Add a span label to the arguments of the closure, if it exists.
617     pub(super) fn args_span_label(
618         self,
619         err: &mut DiagnosticBuilder<'_>,
620         message: impl Into<String>,
621     ) {
622         if let UseSpans::ClosureUse { args_span, .. } = self {
623             err.span_label(args_span, message);
624         }
625     }
626
627     // Add a span label to the use of the captured variable, if it exists.
628     pub(super) fn var_span_label(
629         self,
630         err: &mut DiagnosticBuilder<'_>,
631         message: impl Into<String>,
632     ) {
633         if let UseSpans::ClosureUse { var_span, .. } = self {
634             err.span_label(var_span, message);
635         }
636     }
637
638     /// Returns `false` if this place is not used in a closure.
639     pub(super) fn for_closure(&self) -> bool {
640         match *self {
641             UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(),
642             _ => false,
643         }
644     }
645
646     /// Returns `false` if this place is not used in a generator.
647     pub(super) fn for_generator(&self) -> bool {
648         match *self {
649             UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(),
650             _ => false,
651         }
652     }
653
654     /// Describe the span associated with a use of a place.
655     pub(super) fn describe(&self) -> String {
656         match *self {
657             UseSpans::ClosureUse { generator_kind, .. } => {
658                 if generator_kind.is_some() {
659                     " in generator".to_string()
660                 } else {
661                     " in closure".to_string()
662                 }
663             }
664             _ => String::new(),
665         }
666     }
667
668     pub(super) fn or_else<F>(self, if_other: F) -> Self
669     where
670         F: FnOnce() -> Self,
671     {
672         match self {
673             closure @ UseSpans::ClosureUse { .. } => closure,
674             UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
675             fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
676         }
677     }
678 }
679
680 pub(super) enum BorrowedContentSource<'tcx> {
681     DerefRawPointer,
682     DerefMutableRef,
683     DerefSharedRef,
684     OverloadedDeref(Ty<'tcx>),
685     OverloadedIndex(Ty<'tcx>),
686 }
687
688 impl BorrowedContentSource<'tcx> {
689     pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
690         match *self {
691             BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
692             BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
693             BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
694             BorrowedContentSource::OverloadedDeref(ty) => match ty.kind() {
695                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Rc, def.did) => {
696                     "an `Rc`".to_string()
697                 }
698                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Arc, def.did) => {
699                     "an `Arc`".to_string()
700                 }
701                 _ => format!("dereference of `{}`", ty),
702             },
703             BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
704         }
705     }
706
707     pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
708         match *self {
709             BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
710             BorrowedContentSource::DerefSharedRef => Some("shared reference"),
711             BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
712             // Overloaded deref and index operators should be evaluated into a
713             // temporary. So we don't need a description here.
714             BorrowedContentSource::OverloadedDeref(_)
715             | BorrowedContentSource::OverloadedIndex(_) => None,
716         }
717     }
718
719     pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
720         match *self {
721             BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
722             BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
723             BorrowedContentSource::DerefMutableRef => {
724                 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
725             }
726             BorrowedContentSource::OverloadedDeref(ty) => match ty.kind() {
727                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Rc, def.did) => {
728                     "an `Rc`".to_string()
729                 }
730                 ty::Adt(def, _) if tcx.is_diagnostic_item(sym::Arc, def.did) => {
731                     "an `Arc`".to_string()
732                 }
733                 _ => format!("a dereference of `{}`", ty),
734             },
735             BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
736         }
737     }
738
739     fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
740         match *func.kind() {
741             ty::FnDef(def_id, substs) => {
742                 let trait_id = tcx.trait_of_item(def_id)?;
743
744                 let lang_items = tcx.lang_items();
745                 if Some(trait_id) == lang_items.deref_trait()
746                     || Some(trait_id) == lang_items.deref_mut_trait()
747                 {
748                     Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
749                 } else if Some(trait_id) == lang_items.index_trait()
750                     || Some(trait_id) == lang_items.index_mut_trait()
751                 {
752                     Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
753                 } else {
754                     None
755                 }
756             }
757             _ => None,
758         }
759     }
760 }
761
762 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
763     /// Finds the spans associated to a move or copy of move_place at location.
764     pub(super) fn move_spans(
765         &self,
766         moved_place: PlaceRef<'tcx>, // Could also be an upvar.
767         location: Location,
768     ) -> UseSpans<'tcx> {
769         use self::UseSpans::*;
770
771         let stmt = match self.body[location.block].statements.get(location.statement_index) {
772             Some(stmt) => stmt,
773             None => return OtherUse(self.body.source_info(location).span),
774         };
775
776         debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
777         if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) = stmt.kind {
778             match kind {
779                 box AggregateKind::Closure(def_id, _)
780                 | box AggregateKind::Generator(def_id, _, _) => {
781                     debug!("move_spans: def_id={:?} places={:?}", def_id, places);
782                     if let Some((args_span, generator_kind, var_span)) =
783                         self.closure_span(*def_id, moved_place, places)
784                     {
785                         return ClosureUse { generator_kind, args_span, var_span };
786                     }
787                 }
788                 _ => {}
789             }
790         }
791
792         let normal_ret =
793             if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {
794                 PatUse(stmt.source_info.span)
795             } else {
796                 OtherUse(stmt.source_info.span)
797             };
798
799         // We are trying to find MIR of the form:
800         // ```
801         // _temp = _moved_val;
802         // ...
803         // FnSelfCall(_temp, ...)
804         // ```
805         //
806         // where `_moved_val` is the place we generated the move error for,
807         // `_temp` is some other local, and `FnSelfCall` is a function
808         // that has a `self` parameter.
809
810         let target_temp = match stmt.kind {
811             StatementKind::Assign(box (temp, _)) if temp.as_local().is_some() => {
812                 temp.as_local().unwrap()
813             }
814             _ => return normal_ret,
815         };
816
817         debug!("move_spans: target_temp = {:?}", target_temp);
818
819         if let Some(Terminator {
820             kind: TerminatorKind::Call { fn_span, from_hir_call, .. }, ..
821         }) = &self.body[location.block].terminator
822         {
823             let (method_did, method_substs) = if let Some(info) =
824                 crate::util::find_self_call(self.infcx.tcx, &self.body, target_temp, location.block)
825             {
826                 info
827             } else {
828                 return normal_ret;
829             };
830
831             let tcx = self.infcx.tcx;
832             let parent = tcx.parent(method_did);
833             let is_fn_once = parent == tcx.lang_items().fn_once_trait();
834             let is_operator = !from_hir_call
835                 && parent.map_or(false, |p| tcx.lang_items().group(LangItemGroup::Op).contains(&p));
836             let is_deref = !from_hir_call && tcx.is_diagnostic_item(sym::deref_method, method_did);
837             let fn_call_span = *fn_span;
838
839             let self_arg = tcx.fn_arg_names(method_did)[0];
840
841             debug!(
842                 "terminator = {:?} from_hir_call={:?}",
843                 self.body[location.block].terminator, from_hir_call
844             );
845
846             // Check for a 'special' use of 'self' -
847             // an FnOnce call, an operator (e.g. `<<`), or a
848             // deref coercion.
849             let kind = if is_fn_once {
850                 Some(FnSelfUseKind::FnOnceCall)
851             } else if is_operator {
852                 Some(FnSelfUseKind::Operator { self_arg })
853             } else if is_deref {
854                 let deref_target =
855                     tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| {
856                         Instance::resolve(tcx, self.param_env, deref_target, method_substs)
857                             .transpose()
858                     });
859                 if let Some(Ok(instance)) = deref_target {
860                     let deref_target_ty = instance.ty(tcx, self.param_env);
861                     Some(FnSelfUseKind::DerefCoercion {
862                         deref_target: tcx.def_span(instance.def_id()),
863                         deref_target_ty,
864                     })
865                 } else {
866                     None
867                 }
868             } else {
869                 None
870             };
871
872             let kind = kind.unwrap_or_else(|| {
873                 // This isn't a 'special' use of `self`
874                 debug!("move_spans: method_did={:?}, fn_call_span={:?}", method_did, fn_call_span);
875                 let implicit_into_iter = matches!(
876                     fn_call_span.desugaring_kind(),
877                     Some(DesugaringKind::ForLoop(ForLoopLoc::IntoIter))
878                 );
879                 FnSelfUseKind::Normal { self_arg, implicit_into_iter }
880             });
881
882             return FnSelfUse {
883                 var_span: stmt.source_info.span,
884                 fn_call_span,
885                 fn_span: self
886                     .infcx
887                     .tcx
888                     .sess
889                     .source_map()
890                     .guess_head_span(self.infcx.tcx.def_span(method_did)),
891                 kind,
892             };
893         }
894         normal_ret
895     }
896
897     /// Finds the span of arguments of a closure (within `maybe_closure_span`)
898     /// and its usage of the local assigned at `location`.
899     /// This is done by searching in statements succeeding `location`
900     /// and originating from `maybe_closure_span`.
901     pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
902         use self::UseSpans::*;
903         debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
904
905         let target = match self.body[location.block].statements.get(location.statement_index) {
906             Some(&Statement { kind: StatementKind::Assign(box (ref place, _)), .. }) => {
907                 if let Some(local) = place.as_local() {
908                     local
909                 } else {
910                     return OtherUse(use_span);
911                 }
912             }
913             _ => return OtherUse(use_span),
914         };
915
916         if self.body.local_kind(target) != LocalKind::Temp {
917             // operands are always temporaries.
918             return OtherUse(use_span);
919         }
920
921         for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
922             if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) =
923                 stmt.kind
924             {
925                 let (def_id, is_generator) = match kind {
926                     box AggregateKind::Closure(def_id, _) => (def_id, false),
927                     box AggregateKind::Generator(def_id, _, _) => (def_id, true),
928                     _ => continue,
929                 };
930
931                 debug!(
932                     "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
933                     def_id, is_generator, places
934                 );
935                 if let Some((args_span, generator_kind, var_span)) =
936                     self.closure_span(*def_id, Place::from(target).as_ref(), places)
937                 {
938                     return ClosureUse { generator_kind, args_span, var_span };
939                 } else {
940                     return OtherUse(use_span);
941                 }
942             }
943
944             if use_span != stmt.source_info.span {
945                 break;
946             }
947         }
948
949         OtherUse(use_span)
950     }
951
952     /// Finds the span of a captured variable within a closure or generator.
953     fn closure_span(
954         &self,
955         def_id: DefId,
956         target_place: PlaceRef<'tcx>,
957         places: &Vec<Operand<'tcx>>,
958     ) -> Option<(Span, Option<GeneratorKind>, Span)> {
959         debug!(
960             "closure_span: def_id={:?} target_place={:?} places={:?}",
961             def_id, target_place, places
962         );
963         let local_did = def_id.as_local()?;
964         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(local_did);
965         let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
966         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
967         if let hir::ExprKind::Closure(.., body_id, args_span, _) = expr {
968             for (upvar_hir_id, place) in
969                 self.infcx.tcx.typeck(def_id.expect_local()).closure_captures[&def_id]
970                     .keys()
971                     .zip(places)
972             {
973                 let span = self.infcx.tcx.upvars_mentioned(local_did)?[upvar_hir_id].span;
974                 match place {
975                     Operand::Copy(place) | Operand::Move(place)
976                         if target_place == place.as_ref() =>
977                     {
978                         debug!("closure_span: found captured local {:?}", place);
979                         let body = self.infcx.tcx.hir().body(*body_id);
980                         let generator_kind = body.generator_kind();
981                         let upvar_id = ty::UpvarId {
982                             var_path: ty::UpvarPath { hir_id: *upvar_hir_id },
983                             closure_expr_id: local_did,
984                         };
985
986                         // If we have a more specific span available, point to that.
987                         // We do this even though this span might be part of a borrow error
988                         // message rather than a move error message. Our goal is to point
989                         // to a span that shows why the upvar is used in the closure,
990                         // so a move-related span is as good as any (and potentially better,
991                         // if the overall error is due to a move of the upvar).
992                         let usage_span =
993                             match self.infcx.tcx.typeck(local_did).upvar_capture(upvar_id) {
994                                 ty::UpvarCapture::ByValue(Some(span)) => span,
995                                 _ => span,
996                             };
997                         return Some((*args_span, generator_kind, usage_span));
998                     }
999                     _ => {}
1000                 }
1001             }
1002         }
1003         None
1004     }
1005
1006     /// Helper to retrieve span(s) of given borrow from the current MIR
1007     /// representation
1008     pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
1009         let span = self.body.source_info(borrow.reserve_location).span;
1010         self.borrow_spans(span, borrow.reserve_location)
1011     }
1012 }