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