]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/mod.rs
Rollup merge of #91797 - the8472:fix-invalid-deref, r=Mark-Simulacrum
[rust.git] / compiler / rustc_borrowck / src / 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, FakeReadCause, Field, Local, LocalInfo, LocalKind, Location, Operand,
11     Place, 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_mir_dataflow::move_paths::{InitLocation, LookupResult};
16 use rustc_span::{hygiene::DesugaringKind, symbol::sym, Span};
17 use rustc_target::abi::VariantIdx;
18
19 use super::borrow_set::BorrowData;
20 use super::MirBorrowckCtxt;
21
22 mod find_all_local_uses;
23 mod find_use;
24 mod outlives_suggestion;
25 mod region_name;
26 mod var_name;
27
28 mod bound_region_errors;
29 mod conflict_errors;
30 mod explain_borrow;
31 mod move_errors;
32 mod mutability_errors;
33 mod region_errors;
34
35 crate use bound_region_errors::{ToUniverseInfo, UniverseInfo};
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: Operand::Constant(box Constant { literal, .. }),
84             args,
85             ..
86         } = &terminator.kind
87         {
88             if let ty::FnDef(id, _) = *literal.ty().kind() {
89                 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
90                 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
91                     let closure = match args.first() {
92                         Some(Operand::Copy(ref place)) | Some(Operand::Move(ref place))
93                             if target == place.local_or_deref_local() =>
94                         {
95                             place.local_or_deref_local().unwrap()
96                         }
97                         _ => return,
98                     };
99
100                     debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
101                     if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
102                         let did = did.expect_local();
103                         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
104
105                         if let Some((span, hir_place)) =
106                             self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
107                         {
108                             diag.span_note(
109                                 *span,
110                                 &format!(
111                                     "closure cannot be invoked more than once because it moves the \
112                                     variable `{}` out of its environment",
113                                     ty::place_to_string_for_capture(self.infcx.tcx, hir_place)
114                                 ),
115                             );
116                             return;
117                         }
118                     }
119                 }
120             }
121         }
122
123         // Check if we are just moving a closure after it has been invoked.
124         if let Some(target) = target {
125             if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() {
126                 let did = did.expect_local();
127                 let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did);
128
129                 if let Some((span, hir_place)) =
130                     self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id)
131                 {
132                     diag.span_note(
133                         *span,
134                         &format!(
135                             "closure cannot be moved more than once as it is not `Copy` due to \
136                              moving the variable `{}` out of its environment",
137                             ty::place_to_string_for_capture(self.infcx.tcx, hir_place)
138                         ),
139                     );
140                 }
141             }
142         }
143     }
144
145     /// End-user visible description of `place` if one can be found.
146     /// If the place is a temporary for instance, `"value"` will be returned.
147     pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
148         match self.describe_place(place_ref) {
149             Some(mut descr) => {
150                 // Surround descr with `backticks`.
151                 descr.reserve(2);
152                 descr.insert(0, '`');
153                 descr.push('`');
154                 descr
155             }
156             None => "value".to_string(),
157         }
158     }
159
160     /// End-user visible description of `place` if one can be found.
161     /// If the place is a temporary for instance, None will be returned.
162     pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
163         self.describe_place_with_options(place_ref, IncludingDowncast(false))
164     }
165
166     /// End-user visible description of `place` if one can be found. If the
167     /// place is a temporary for instance, None will be returned.
168     /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
169     /// `Downcast` and `IncludingDowncast` is true
170     pub(super) fn describe_place_with_options(
171         &self,
172         place: PlaceRef<'tcx>,
173         including_downcast: IncludingDowncast,
174     ) -> Option<String> {
175         let mut buf = String::new();
176         match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
177             Ok(()) => Some(buf),
178             Err(()) => None,
179         }
180     }
181
182     /// Appends end-user visible description of `place` to `buf`.
183     fn append_place_to_string(
184         &self,
185         place: PlaceRef<'tcx>,
186         buf: &mut String,
187         mut autoderef: bool,
188         including_downcast: &IncludingDowncast,
189     ) -> Result<(), ()> {
190         match place {
191             PlaceRef { local, projection: [] } => {
192                 self.append_local_to_string(local, buf)?;
193             }
194             PlaceRef { local, projection: [ProjectionElem::Deref] }
195                 if self.body.local_decls[local].is_ref_for_guard() =>
196             {
197                 self.append_place_to_string(
198                     PlaceRef { local, projection: &[] },
199                     buf,
200                     autoderef,
201                     &including_downcast,
202                 )?;
203             }
204             PlaceRef { local, projection: [ProjectionElem::Deref] }
205                 if self.body.local_decls[local].is_ref_to_static() =>
206             {
207                 let local_info = &self.body.local_decls[local].local_info;
208                 if let Some(box LocalInfo::StaticRef { def_id, .. }) = *local_info {
209                     buf.push_str(&self.infcx.tcx.item_name(def_id).as_str());
210                 } else {
211                     unreachable!();
212                 }
213             }
214             PlaceRef { local, projection: [proj_base @ .., elem] } => {
215                 match elem {
216                     ProjectionElem::Deref => {
217                         let upvar_field_projection = self.is_upvar_field_projection(place);
218                         if let Some(field) = upvar_field_projection {
219                             let var_index = field.index();
220                             let name = self.upvars[var_index].place.to_string(self.infcx.tcx);
221                             if self.upvars[var_index].by_ref {
222                                 buf.push_str(&name);
223                             } else {
224                                 buf.push('*');
225                                 buf.push_str(&name);
226                             }
227                         } else {
228                             if autoderef {
229                                 // FIXME turn this recursion into iteration
230                                 self.append_place_to_string(
231                                     PlaceRef { local, projection: proj_base },
232                                     buf,
233                                     autoderef,
234                                     &including_downcast,
235                                 )?;
236                             } else {
237                                 buf.push('*');
238                                 self.append_place_to_string(
239                                     PlaceRef { local, projection: proj_base },
240                                     buf,
241                                     autoderef,
242                                     &including_downcast,
243                                 )?;
244                             }
245                         }
246                     }
247                     ProjectionElem::Downcast(..) => {
248                         self.append_place_to_string(
249                             PlaceRef { local, projection: proj_base },
250                             buf,
251                             autoderef,
252                             &including_downcast,
253                         )?;
254                         if including_downcast.0 {
255                             return Err(());
256                         }
257                     }
258                     ProjectionElem::Field(field, _ty) => {
259                         autoderef = true;
260
261                         // FIXME(project-rfc_2229#36): print capture precisely here.
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].place.to_string(self.infcx.tcx);
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 = place.ty(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                     // We won't be borrowck'ing here if the closure came from another crate,
386                     // so it's safe to call `expect_local`.
387                     //
388                     // We know the field exists so it's safe to call operator[] and `unwrap` here.
389                     let var_id = self
390                         .infcx
391                         .tcx
392                         .typeck(def_id.expect_local())
393                         .closure_min_captures_flattened(def_id)
394                         .nth(field.index())
395                         .unwrap()
396                         .get_root_variable();
397
398                     self.infcx.tcx.hir().name(var_id).to_string()
399                 }
400                 _ => {
401                     // Might need a revision when the fields in trait RFC is implemented
402                     // (https://github.com/rust-lang/rfcs/pull/1546)
403                     bug!("End-user description not implemented for field access on `{:?}`", ty);
404                 }
405             }
406         }
407     }
408
409     /// Add a note that a type does not implement `Copy`
410     pub(super) fn note_type_does_not_implement_copy(
411         &self,
412         err: &mut DiagnosticBuilder<'a>,
413         place_desc: &str,
414         ty: Ty<'tcx>,
415         span: Option<Span>,
416         move_prefix: &str,
417     ) {
418         let message = format!(
419             "{}move occurs because {} has type `{}`, which does not implement the `Copy` trait",
420             move_prefix, place_desc, ty,
421         );
422         if let Some(span) = span {
423             err.span_label(span, message);
424         } else {
425             err.note(&message);
426         }
427     }
428
429     pub(super) fn borrowed_content_source(
430         &self,
431         deref_base: PlaceRef<'tcx>,
432     ) -> BorrowedContentSource<'tcx> {
433         let tcx = self.infcx.tcx;
434
435         // Look up the provided place and work out the move path index for it,
436         // we'll use this to check whether it was originally from an overloaded
437         // operator.
438         match self.move_data.rev_lookup.find(deref_base) {
439             LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
440                 debug!("borrowed_content_source: mpi={:?}", mpi);
441
442                 for i in &self.move_data.init_path_map[mpi] {
443                     let init = &self.move_data.inits[*i];
444                     debug!("borrowed_content_source: init={:?}", init);
445                     // We're only interested in statements that initialized a value, not the
446                     // initializations from arguments.
447                     let loc = match init.location {
448                         InitLocation::Statement(stmt) => stmt,
449                         _ => continue,
450                     };
451
452                     let bbd = &self.body[loc.block];
453                     let is_terminator = bbd.statements.len() == loc.statement_index;
454                     debug!(
455                         "borrowed_content_source: loc={:?} is_terminator={:?}",
456                         loc, is_terminator,
457                     );
458                     if !is_terminator {
459                         continue;
460                     } else if let Some(Terminator {
461                         kind: TerminatorKind::Call { ref func, from_hir_call: false, .. },
462                         ..
463                     }) = bbd.terminator
464                     {
465                         if let Some(source) =
466                             BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
467                         {
468                             return source;
469                         }
470                     }
471                 }
472             }
473             // Base is a `static` so won't be from an overloaded operator
474             _ => (),
475         };
476
477         // If we didn't find an overloaded deref or index, then assume it's a
478         // built in deref and check the type of the base.
479         let base_ty = deref_base.ty(self.body, tcx).ty;
480         if base_ty.is_unsafe_ptr() {
481             BorrowedContentSource::DerefRawPointer
482         } else if base_ty.is_mutable_ptr() {
483             BorrowedContentSource::DerefMutableRef
484         } else {
485             BorrowedContentSource::DerefSharedRef
486         }
487     }
488 }
489
490 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
491     /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
492     /// name where required.
493     pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
494         let mut s = String::new();
495         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
496
497         // We need to add synthesized lifetimes where appropriate. We do
498         // this by hooking into the pretty printer and telling it to label the
499         // lifetimes without names with the value `'0`.
500         match ty.kind() {
501             ty::Ref(
502                 ty::RegionKind::ReLateBound(_, ty::BoundRegion { kind: br, .. })
503                 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
504                 _,
505                 _,
506             ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
507             _ => {}
508         }
509
510         let _ = ty.print(printer);
511         s
512     }
513
514     /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
515     /// synthesized lifetime name where required.
516     pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
517         let mut s = String::new();
518         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
519
520         let region = match ty.kind() {
521             ty::Ref(region, _, _) => {
522                 match region {
523                     ty::RegionKind::ReLateBound(_, ty::BoundRegion { kind: br, .. })
524                     | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
525                         printer.region_highlight_mode.highlighting_bound_region(*br, counter)
526                     }
527                     _ => {}
528                 }
529
530                 region
531             }
532             _ => bug!("ty for annotation of borrow region is not a reference"),
533         };
534
535         let _ = region.print(printer);
536         s
537     }
538 }
539
540 /// The span(s) associated to a use of a place.
541 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
542 pub(super) enum UseSpans<'tcx> {
543     /// The access is caused by capturing a variable for a closure.
544     ClosureUse {
545         /// This is true if the captured variable was from a generator.
546         generator_kind: Option<GeneratorKind>,
547         /// The span of the args of the closure, including the `move` keyword if
548         /// it's present.
549         args_span: Span,
550         /// The span of the use resulting in capture kind
551         /// Check `ty::CaptureInfo` for more details
552         capture_kind_span: Span,
553         /// The span of the use resulting in the captured path
554         /// Check `ty::CaptureInfo` for more details
555         path_span: Span,
556     },
557     /// The access is caused by using a variable as the receiver of a method
558     /// that takes 'self'
559     FnSelfUse {
560         /// The span of the variable being moved
561         var_span: Span,
562         /// The span of the method call on the variable
563         fn_call_span: Span,
564         /// The definition span of the method being called
565         fn_span: Span,
566         kind: FnSelfUseKind<'tcx>,
567     },
568     /// This access is caused by a `match` or `if let` pattern.
569     PatUse(Span),
570     /// This access has a single span associated to it: common case.
571     OtherUse(Span),
572 }
573
574 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
575 pub(super) enum FnSelfUseKind<'tcx> {
576     /// A normal method call of the form `receiver.foo(a, b, c)`
577     Normal {
578         self_arg: Ident,
579         implicit_into_iter: bool,
580         /// Whether the self type of the method call has an `.as_ref()` method.
581         /// Used for better diagnostics.
582         is_option_or_result: bool,
583     },
584     /// A call to `FnOnce::call_once`, desugared from `my_closure(a, b, c)`
585     FnOnceCall,
586     /// A call to an operator trait, desuraged from operator syntax (e.g. `a << b`)
587     Operator { self_arg: Ident },
588     DerefCoercion {
589         /// The `Span` of the `Target` associated type
590         /// in the `Deref` impl we are using.
591         deref_target: Span,
592         /// The type `T::Deref` we are dereferencing to
593         deref_target_ty: Ty<'tcx>,
594     },
595 }
596
597 impl UseSpans<'_> {
598     pub(super) fn args_or_use(self) -> Span {
599         match self {
600             UseSpans::ClosureUse { args_span: span, .. }
601             | UseSpans::PatUse(span)
602             | UseSpans::OtherUse(span) => span,
603             UseSpans::FnSelfUse {
604                 fn_call_span, kind: FnSelfUseKind::DerefCoercion { .. }, ..
605             } => fn_call_span,
606             UseSpans::FnSelfUse { var_span, .. } => var_span,
607         }
608     }
609
610     /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
611     pub(super) fn var_or_use_path_span(self) -> Span {
612         match self {
613             UseSpans::ClosureUse { path_span: span, .. }
614             | UseSpans::PatUse(span)
615             | UseSpans::OtherUse(span) => span,
616             UseSpans::FnSelfUse {
617                 fn_call_span, kind: FnSelfUseKind::DerefCoercion { .. }, ..
618             } => fn_call_span,
619             UseSpans::FnSelfUse { var_span, .. } => var_span,
620         }
621     }
622
623     /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
624     pub(super) fn var_or_use(self) -> Span {
625         match self {
626             UseSpans::ClosureUse { capture_kind_span: span, .. }
627             | UseSpans::PatUse(span)
628             | UseSpans::OtherUse(span) => span,
629             UseSpans::FnSelfUse {
630                 fn_call_span, kind: FnSelfUseKind::DerefCoercion { .. }, ..
631             } => fn_call_span,
632             UseSpans::FnSelfUse { var_span, .. } => var_span,
633         }
634     }
635
636     pub(super) fn generator_kind(self) -> Option<GeneratorKind> {
637         match self {
638             UseSpans::ClosureUse { generator_kind, .. } => generator_kind,
639             _ => None,
640         }
641     }
642
643     // Add a span label to the arguments of the closure, if it exists.
644     pub(super) fn args_span_label(
645         self,
646         err: &mut DiagnosticBuilder<'_>,
647         message: impl Into<String>,
648     ) {
649         if let UseSpans::ClosureUse { args_span, .. } = self {
650             err.span_label(args_span, message);
651         }
652     }
653
654     // Add a span label to the use of the captured variable, if it exists.
655     // only adds label to the `path_span`
656     pub(super) fn var_span_label_path_only(
657         self,
658         err: &mut DiagnosticBuilder<'_>,
659         message: impl Into<String>,
660     ) {
661         if let UseSpans::ClosureUse { path_span, .. } = self {
662             err.span_label(path_span, message);
663         }
664     }
665
666     // Add a span label to the use of the captured variable, if it exists.
667     pub(super) fn var_span_label(
668         self,
669         err: &mut DiagnosticBuilder<'_>,
670         message: impl Into<String>,
671         kind_desc: impl Into<String>,
672     ) {
673         if let UseSpans::ClosureUse { capture_kind_span, path_span, .. } = self {
674             if capture_kind_span == path_span {
675                 err.span_label(capture_kind_span, message);
676             } else {
677                 let capture_kind_label =
678                     format!("capture is {} because of use here", kind_desc.into());
679                 let path_label = message;
680                 err.span_label(capture_kind_span, capture_kind_label);
681                 err.span_label(path_span, path_label);
682             }
683         }
684     }
685
686     /// Returns `false` if this place is not used in a closure.
687     pub(super) fn for_closure(&self) -> bool {
688         match *self {
689             UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(),
690             _ => false,
691         }
692     }
693
694     /// Returns `false` if this place is not used in a generator.
695     pub(super) fn for_generator(&self) -> bool {
696         match *self {
697             UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(),
698             _ => false,
699         }
700     }
701
702     /// Describe the span associated with a use of a place.
703     pub(super) fn describe(&self) -> String {
704         match *self {
705             UseSpans::ClosureUse { generator_kind, .. } => {
706                 if generator_kind.is_some() {
707                     " in generator".to_string()
708                 } else {
709                     " in closure".to_string()
710                 }
711             }
712             _ => String::new(),
713         }
714     }
715
716     pub(super) fn or_else<F>(self, if_other: F) -> Self
717     where
718         F: FnOnce() -> Self,
719     {
720         match self {
721             closure @ UseSpans::ClosureUse { .. } => closure,
722             UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
723             fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
724         }
725     }
726 }
727
728 pub(super) enum BorrowedContentSource<'tcx> {
729     DerefRawPointer,
730     DerefMutableRef,
731     DerefSharedRef,
732     OverloadedDeref(Ty<'tcx>),
733     OverloadedIndex(Ty<'tcx>),
734 }
735
736 impl BorrowedContentSource<'tcx> {
737     pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
738         match *self {
739             BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
740             BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
741             BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
742             BorrowedContentSource::OverloadedDeref(ty) => ty
743                 .ty_adt_def()
744                 .and_then(|adt| match tcx.get_diagnostic_name(adt.did)? {
745                     name @ (sym::Rc | sym::Arc) => Some(format!("an `{}`", name)),
746                     _ => None,
747                 })
748                 .unwrap_or_else(|| format!("dereference of `{}`", ty)),
749             BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{}`", ty),
750         }
751     }
752
753     pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
754         match *self {
755             BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
756             BorrowedContentSource::DerefSharedRef => Some("shared reference"),
757             BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
758             // Overloaded deref and index operators should be evaluated into a
759             // temporary. So we don't need a description here.
760             BorrowedContentSource::OverloadedDeref(_)
761             | BorrowedContentSource::OverloadedIndex(_) => None,
762         }
763     }
764
765     pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
766         match *self {
767             BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
768             BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
769             BorrowedContentSource::DerefMutableRef => {
770                 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
771             }
772             BorrowedContentSource::OverloadedDeref(ty) => ty
773                 .ty_adt_def()
774                 .and_then(|adt| match tcx.get_diagnostic_name(adt.did)? {
775                     name @ (sym::Rc | sym::Arc) => Some(format!("an `{}`", name)),
776                     _ => None,
777                 })
778                 .unwrap_or_else(|| format!("dereference of `{}`", ty)),
779             BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{}`", ty),
780         }
781     }
782
783     fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
784         match *func.kind() {
785             ty::FnDef(def_id, substs) => {
786                 let trait_id = tcx.trait_of_item(def_id)?;
787
788                 let lang_items = tcx.lang_items();
789                 if Some(trait_id) == lang_items.deref_trait()
790                     || Some(trait_id) == lang_items.deref_mut_trait()
791                 {
792                     Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0)))
793                 } else if Some(trait_id) == lang_items.index_trait()
794                     || Some(trait_id) == lang_items.index_mut_trait()
795                 {
796                     Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0)))
797                 } else {
798                     None
799                 }
800             }
801             _ => None,
802         }
803     }
804 }
805
806 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
807     /// Finds the spans associated to a move or copy of move_place at location.
808     pub(super) fn move_spans(
809         &self,
810         moved_place: PlaceRef<'tcx>, // Could also be an upvar.
811         location: Location,
812     ) -> UseSpans<'tcx> {
813         use self::UseSpans::*;
814
815         let stmt = match self.body[location.block].statements.get(location.statement_index) {
816             Some(stmt) => stmt,
817             None => return OtherUse(self.body.source_info(location).span),
818         };
819
820         debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
821         if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) = stmt.kind {
822             match kind {
823                 box AggregateKind::Closure(def_id, _)
824                 | box AggregateKind::Generator(def_id, _, _) => {
825                     debug!("move_spans: def_id={:?} places={:?}", def_id, places);
826                     if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
827                         self.closure_span(*def_id, moved_place, places)
828                     {
829                         return ClosureUse {
830                             generator_kind,
831                             args_span,
832                             capture_kind_span,
833                             path_span,
834                         };
835                     }
836                 }
837                 _ => {}
838             }
839         }
840
841         // StatementKind::FakeRead only contains a def_id if they are introduced as a result
842         // of pattern matching within a closure.
843         if let StatementKind::FakeRead(box (cause, ref place)) = stmt.kind {
844             match cause {
845                 FakeReadCause::ForMatchedPlace(Some(closure_def_id))
846                 | FakeReadCause::ForLet(Some(closure_def_id)) => {
847                     debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);
848                     let places = &[Operand::Move(*place)];
849                     if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
850                         self.closure_span(closure_def_id, moved_place, places)
851                     {
852                         return ClosureUse {
853                             generator_kind,
854                             args_span,
855                             capture_kind_span,
856                             path_span,
857                         };
858                     }
859                 }
860                 _ => {}
861             }
862         }
863
864         let normal_ret =
865             if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {
866                 PatUse(stmt.source_info.span)
867             } else {
868                 OtherUse(stmt.source_info.span)
869             };
870
871         // We are trying to find MIR of the form:
872         // ```
873         // _temp = _moved_val;
874         // ...
875         // FnSelfCall(_temp, ...)
876         // ```
877         //
878         // where `_moved_val` is the place we generated the move error for,
879         // `_temp` is some other local, and `FnSelfCall` is a function
880         // that has a `self` parameter.
881
882         let target_temp = match stmt.kind {
883             StatementKind::Assign(box (temp, _)) if temp.as_local().is_some() => {
884                 temp.as_local().unwrap()
885             }
886             _ => return normal_ret,
887         };
888
889         debug!("move_spans: target_temp = {:?}", target_temp);
890
891         if let Some(Terminator {
892             kind: TerminatorKind::Call { fn_span, from_hir_call, .. }, ..
893         }) = &self.body[location.block].terminator
894         {
895             let (method_did, method_substs) = if let Some(info) =
896                 rustc_const_eval::util::find_self_call(
897                     self.infcx.tcx,
898                     &self.body,
899                     target_temp,
900                     location.block,
901                 ) {
902                 info
903             } else {
904                 return normal_ret;
905             };
906
907             let tcx = self.infcx.tcx;
908             let parent = tcx.parent(method_did);
909             let is_fn_once = parent == tcx.lang_items().fn_once_trait();
910             let is_operator = !from_hir_call
911                 && parent.map_or(false, |p| tcx.lang_items().group(LangItemGroup::Op).contains(&p));
912             let is_deref = !from_hir_call && tcx.is_diagnostic_item(sym::deref_method, method_did);
913             let fn_call_span = *fn_span;
914
915             let self_arg = tcx.fn_arg_names(method_did)[0];
916
917             debug!(
918                 "terminator = {:?} from_hir_call={:?}",
919                 self.body[location.block].terminator, from_hir_call
920             );
921
922             // Check for a 'special' use of 'self' -
923             // an FnOnce call, an operator (e.g. `<<`), or a
924             // deref coercion.
925             let kind = if is_fn_once {
926                 Some(FnSelfUseKind::FnOnceCall)
927             } else if is_operator {
928                 Some(FnSelfUseKind::Operator { self_arg })
929             } else if is_deref {
930                 let deref_target =
931                     tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| {
932                         Instance::resolve(tcx, self.param_env, deref_target, method_substs)
933                             .transpose()
934                     });
935                 if let Some(Ok(instance)) = deref_target {
936                     let deref_target_ty = instance.ty(tcx, self.param_env);
937                     Some(FnSelfUseKind::DerefCoercion {
938                         deref_target: tcx.def_span(instance.def_id()),
939                         deref_target_ty,
940                     })
941                 } else {
942                     None
943                 }
944             } else {
945                 None
946             };
947
948             let kind = kind.unwrap_or_else(|| {
949                 // This isn't a 'special' use of `self`
950                 debug!("move_spans: method_did={:?}, fn_call_span={:?}", method_did, fn_call_span);
951                 let implicit_into_iter = Some(method_did) == tcx.lang_items().into_iter_fn()
952                     && fn_call_span.desugaring_kind() == Some(DesugaringKind::ForLoop);
953                 let parent_self_ty = parent
954                     .filter(|did| tcx.def_kind(*did) == rustc_hir::def::DefKind::Impl)
955                     .and_then(|did| match tcx.type_of(did).kind() {
956                         ty::Adt(def, ..) => Some(def.did),
957                         _ => None,
958                     });
959                 let is_option_or_result = parent_self_ty.map_or(false, |def_id| {
960                     matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
961                 });
962                 FnSelfUseKind::Normal { self_arg, implicit_into_iter, is_option_or_result }
963             });
964
965             return FnSelfUse {
966                 var_span: stmt.source_info.span,
967                 fn_call_span,
968                 fn_span: self
969                     .infcx
970                     .tcx
971                     .sess
972                     .source_map()
973                     .guess_head_span(self.infcx.tcx.def_span(method_did)),
974                 kind,
975             };
976         }
977         normal_ret
978     }
979
980     /// Finds the span of arguments of a closure (within `maybe_closure_span`)
981     /// and its usage of the local assigned at `location`.
982     /// This is done by searching in statements succeeding `location`
983     /// and originating from `maybe_closure_span`.
984     pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
985         use self::UseSpans::*;
986         debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
987
988         let target = match self.body[location.block].statements.get(location.statement_index) {
989             Some(&Statement { kind: StatementKind::Assign(box (ref place, _)), .. }) => {
990                 if let Some(local) = place.as_local() {
991                     local
992                 } else {
993                     return OtherUse(use_span);
994                 }
995             }
996             _ => return OtherUse(use_span),
997         };
998
999         if self.body.local_kind(target) != LocalKind::Temp {
1000             // operands are always temporaries.
1001             return OtherUse(use_span);
1002         }
1003
1004         for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1005             if let StatementKind::Assign(box (_, Rvalue::Aggregate(ref kind, ref places))) =
1006                 stmt.kind
1007             {
1008                 let (def_id, is_generator) = match kind {
1009                     box AggregateKind::Closure(def_id, _) => (def_id, false),
1010                     box AggregateKind::Generator(def_id, _, _) => (def_id, true),
1011                     _ => continue,
1012                 };
1013
1014                 debug!(
1015                     "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
1016                     def_id, is_generator, places
1017                 );
1018                 if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
1019                     self.closure_span(*def_id, Place::from(target).as_ref(), places)
1020                 {
1021                     return ClosureUse { generator_kind, args_span, capture_kind_span, path_span };
1022                 } else {
1023                     return OtherUse(use_span);
1024                 }
1025             }
1026
1027             if use_span != stmt.source_info.span {
1028                 break;
1029             }
1030         }
1031
1032         OtherUse(use_span)
1033     }
1034
1035     /// Finds the spans of a captured place within a closure or generator.
1036     /// The first span is the location of the use resulting in the capture kind of the capture
1037     /// The second span is the location the use resulting in the captured path of the capture
1038     fn closure_span(
1039         &self,
1040         def_id: DefId,
1041         target_place: PlaceRef<'tcx>,
1042         places: &[Operand<'tcx>],
1043     ) -> Option<(Span, Option<GeneratorKind>, Span, Span)> {
1044         debug!(
1045             "closure_span: def_id={:?} target_place={:?} places={:?}",
1046             def_id, target_place, places
1047         );
1048         let local_did = def_id.as_local()?;
1049         let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(local_did);
1050         let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
1051         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
1052         if let hir::ExprKind::Closure(.., body_id, args_span, _) = expr {
1053             for (captured_place, place) in self
1054                 .infcx
1055                 .tcx
1056                 .typeck(def_id.expect_local())
1057                 .closure_min_captures_flattened(def_id)
1058                 .zip(places)
1059             {
1060                 match place {
1061                     Operand::Copy(place) | Operand::Move(place)
1062                         if target_place == place.as_ref() =>
1063                     {
1064                         debug!("closure_span: found captured local {:?}", place);
1065                         let body = self.infcx.tcx.hir().body(*body_id);
1066                         let generator_kind = body.generator_kind();
1067
1068                         return Some((
1069                             *args_span,
1070                             generator_kind,
1071                             captured_place.get_capture_kind_span(self.infcx.tcx),
1072                             captured_place.get_path_span(self.infcx.tcx),
1073                         ));
1074                     }
1075                     _ => {}
1076                 }
1077             }
1078         }
1079         None
1080     }
1081
1082     /// Helper to retrieve span(s) of given borrow from the current MIR
1083     /// representation
1084     pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
1085         let span = self.body.source_info(borrow.reserve_location).span;
1086         self.borrow_spans(span, borrow.reserve_location)
1087     }
1088 }