]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/conflict_errors.rs
Use structured suggestion when requiring `Copy` constraint in type param
[rust.git] / src / librustc_mir / borrow_check / conflict_errors.rs
1 use rustc::hir;
2 use rustc::hir::def_id::DefId;
3 use rustc::hir::{AsyncGeneratorKind, GeneratorKind};
4 use rustc::mir::{
5     self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
6     FakeReadCause, Local, LocalDecl, LocalInfo, LocalKind, Location, Operand, Place, PlaceBase,
7     PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
8 };
9 use rustc::ty::{self, Ty};
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_index::vec::Idx;
12 use rustc_errors::{Applicability, DiagnosticBuilder};
13 use syntax_pos::Span;
14 use syntax::source_map::DesugaringKind;
15
16 use super::nll::explain_borrow::BorrowExplanation;
17 use super::nll::region_infer::{RegionName, RegionNameSource};
18 use super::prefixes::IsPrefixOf;
19 use super::WriteKind;
20 use super::borrow_set::BorrowData;
21 use super::MirBorrowckCtxt;
22 use super::{InitializationRequiringAction, PrefixSet};
23 use super::error_reporting::{IncludingDowncast, UseSpans};
24 use crate::dataflow::drop_flag_effects;
25 use crate::dataflow::indexes::{MovePathIndex, MoveOutIndex};
26 use crate::util::borrowck_errors;
27
28 #[derive(Debug)]
29 struct MoveSite {
30     /// Index of the "move out" that we found. The `MoveData` can
31     /// then tell us where the move occurred.
32     moi: MoveOutIndex,
33
34     /// `true` if we traversed a back edge while walking from the point
35     /// of error to the move site.
36     traversed_back_edge: bool
37 }
38
39 /// Which case a StorageDeadOrDrop is for.
40 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
41 enum StorageDeadOrDrop<'tcx> {
42     LocalStorageDead,
43     BoxedStorageDead,
44     Destructor(Ty<'tcx>),
45 }
46
47 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
48     pub(super) fn report_use_of_moved_or_uninitialized(
49         &mut self,
50         location: Location,
51         desired_action: InitializationRequiringAction,
52         (moved_place, used_place, span): (PlaceRef<'cx, 'tcx>, PlaceRef<'cx, 'tcx>, Span),
53         mpi: MovePathIndex,
54     ) {
55         debug!(
56             "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
57              moved_place={:?} used_place={:?} span={:?} mpi={:?}",
58             location, desired_action, moved_place, used_place, span, mpi
59         );
60
61         let use_spans = self.move_spans(moved_place, location)
62             .or_else(|| self.borrow_spans(span, location));
63         let span = use_spans.args_or_use();
64
65         let move_site_vec = self.get_moved_indexes(location, mpi);
66         debug!(
67             "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
68             move_site_vec
69         );
70         let move_out_indices: Vec<_> = move_site_vec
71             .iter()
72             .map(|move_site| move_site.moi)
73             .collect();
74
75         if move_out_indices.is_empty() {
76             let root_place = self
77                 .prefixes(used_place, PrefixSet::All)
78                 .last()
79                 .unwrap();
80
81             if !self.uninitialized_error_reported.insert(root_place) {
82                 debug!(
83                     "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
84                     root_place
85                 );
86                 return;
87             }
88
89             let item_msg = match self.describe_place_with_options(used_place,
90                                                                   IncludingDowncast(true)) {
91                 Some(name) => format!("`{}`", name),
92                 None => "value".to_owned(),
93             };
94             let mut err = self.cannot_act_on_uninitialized_variable(
95                 span,
96                 desired_action.as_noun(),
97                 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
98                     .unwrap_or_else(|| "_".to_owned()),
99             );
100             err.span_label(span, format!("use of possibly-uninitialized {}", item_msg));
101
102             use_spans.var_span_label(
103                 &mut err,
104                 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
105             );
106
107             err.buffer(&mut self.errors_buffer);
108         } else {
109             if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
110                 if self.prefixes(*reported_place, PrefixSet::All)
111                     .any(|p| p == used_place)
112                 {
113                     debug!(
114                         "report_use_of_moved_or_uninitialized place: error suppressed \
115                          mois={:?}",
116                         move_out_indices
117                     );
118                     return;
119                 }
120             }
121
122             let msg = ""; //FIXME: add "partially " or "collaterally "
123
124             let mut err = self.cannot_act_on_moved_value(
125                 span,
126                 desired_action.as_noun(),
127                 msg,
128                 self.describe_place_with_options(moved_place, IncludingDowncast(true)),
129             );
130
131             self.add_moved_or_invoked_closure_note(
132                 location,
133                 used_place,
134                 &mut err,
135             );
136
137             let mut is_loop_move = false;
138             let is_partial_move = move_site_vec.iter().any(|move_site| {
139                 let move_out = self.move_data.moves[(*move_site).moi];
140                 let moved_place = &self.move_data.move_paths[move_out.path].place;
141                 used_place != moved_place.as_ref()
142                     && used_place.is_prefix_of(moved_place.as_ref())
143             });
144             for move_site in &move_site_vec {
145                 let move_out = self.move_data.moves[(*move_site).moi];
146                 let moved_place = &self.move_data.move_paths[move_out.path].place;
147
148                 let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
149                 let move_span = move_spans.args_or_use();
150
151                 let move_msg = if move_spans.for_closure() {
152                     " into closure"
153                 } else {
154                     ""
155                 };
156
157                 if span == move_span {
158                     err.span_label(
159                         span,
160                         format!("value moved{} here, in previous iteration of loop", move_msg),
161                     );
162                     is_loop_move = true;
163                 } else if move_site.traversed_back_edge {
164                     err.span_label(
165                         move_span,
166                         format!(
167                             "value moved{} here, in previous iteration of loop",
168                             move_msg
169                         ),
170                     );
171                 } else {
172                     err.span_label(move_span, format!("value moved{} here", move_msg));
173                     move_spans.var_span_label(
174                         &mut err,
175                         format!("variable moved due to use{}", move_spans.describe()),
176                     );
177                 }
178                 if Some(DesugaringKind::ForLoop) == move_span.desugaring_kind() {
179                     let sess = self.infcx.tcx.sess;
180                     if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
181                         err.span_suggestion(
182                             move_span,
183                             "consider borrowing to avoid moving into the for loop",
184                             format!("&{}", snippet),
185                             Applicability::MaybeIncorrect,
186                         );
187                     }
188                 }
189             }
190
191             use_spans.var_span_label(
192                 &mut err,
193                 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
194             );
195
196             if !is_loop_move {
197                 err.span_label(
198                     span,
199                     format!(
200                         "value {} here {}",
201                         desired_action.as_verb_in_past_tense(),
202                         if is_partial_move { "after partial move" } else { "after move" },
203                     ),
204                 );
205             }
206
207             let ty =
208                 Place::ty_from(used_place.base, used_place.projection, self.body, self.infcx.tcx)
209                     .ty;
210             let needs_note = match ty.kind {
211                 ty::Closure(id, _) => {
212                     let tables = self.infcx.tcx.typeck_tables_of(id);
213                     let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
214
215                     tables.closure_kind_origins().get(hir_id).is_none()
216                 }
217                 _ => true,
218             };
219
220             if needs_note {
221                 let mpi = self.move_data.moves[move_out_indices[0]].path;
222                 let place = &self.move_data.move_paths[mpi].place;
223
224                 let ty = place.ty(self.body, self.infcx.tcx).ty;
225                 let opt_name =
226                     self.describe_place_with_options(place.as_ref(), IncludingDowncast(true));
227                 let note_msg = match opt_name {
228                     Some(ref name) => format!("`{}`", name),
229                     None => "value".to_owned(),
230                 };
231                 if let ty::Param(param_ty) = ty.kind {
232                     let tcx = self.infcx.tcx;
233                     let generics = tcx.generics_of(self.mir_def_id);
234                     let param = generics.type_param(&param_ty, tcx);
235                     let generics = tcx.hir().get_generics(self.mir_def_id).unwrap();
236                     let msg = "consider adding a `Copy` constraint to this type argument";
237                     for param in generics.params.iter().filter(|p| {
238                         p.name.ident().as_str() == param.name.as_str()
239                     }) {
240                         let param_name = param.name.ident().as_str();
241                         if param_name.starts_with("impl ") {
242                             // `impl Trait` in argument:
243                             // `fn foo(x: impl Trait) {}` â†’ `fn foo(t: impl Trait + Trait2) {}`
244                             err.span_suggestion(
245                                 param.span,
246                                 msg,
247                                 // `impl CurrentTrait + MissingTrait`
248                                 format!("{} + Copy", param_name),
249                                 Applicability::MachineApplicable,
250                             );
251                         } else if generics.where_clause.predicates.is_empty() &&
252                             param.bounds.is_empty()
253                         {
254                             // If there are no bounds whatsoever, suggest adding a constraint
255                             // to the type parameter:
256                             // `fn foo<T>(t: T) {}` â†’ `fn foo<T: Trait>(t: T) {}`
257                             err.span_suggestion(
258                                 param.span,
259                                 msg,
260                                 format!("{}: Copy", param_name),
261                                 Applicability::MachineApplicable,
262                             );
263                         } else if !generics.where_clause.predicates.is_empty() {
264                             // There is a `where` clause, so suggest expanding it:
265                             // `fn foo<T>(t: T) where T: Debug {}` â†’
266                             // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
267                             err.span_suggestion(
268                                 generics.where_clause.span().unwrap().shrink_to_hi(),
269                                 msg,
270                                 format!(", {}: Copy", param_name),
271                                 Applicability::MachineApplicable,
272                             );
273                         } else {
274                             // If there is no `where` clause lean towards constraining to the
275                             // type parameter:
276                             // `fn foo<X: Bar, T>(t: T, x: X) {}` â†’ `fn foo<T: Trait>(t: T) {}`
277                             // `fn foo<T: Bar>(t: T) {}` â†’ `fn foo<T: Bar + Trait>(t: T) {}`
278                             let sp = param.span.with_hi(span.hi());
279                             let span = tcx.sess.source_map()
280                                 .span_through_char(sp, ':');
281                             if sp != param.span && sp != span {
282                                 // Only suggest if we have high certainty that the span
283                                 // covers the colon in `foo<T: Trait>`.
284                                 err.span_suggestion(span, msg, format!(
285                                     "{}: Copy +",
286                                     param_name,
287                                 ), Applicability::MachineApplicable);
288                             } else {
289                                 err.span_label(param.span, msg);
290                             }
291                         }
292                     }
293                 }
294                 let span = if let Some(local) = place.as_local() {
295                     let decl = &self.body.local_decls[local];
296                     Some(decl.source_info.span)
297                 } else {
298                     None
299                 };
300                 self.note_type_does_not_implement_copy(
301                     &mut err,
302                     &note_msg,
303                     ty,
304                     span,
305                 );
306             }
307
308             if let Some((_, mut old_err)) = self.move_error_reported
309                 .insert(move_out_indices, (used_place, err))
310             {
311                 // Cancel the old error so it doesn't ICE.
312                 old_err.cancel();
313             }
314         }
315     }
316
317     pub(super) fn report_move_out_while_borrowed(
318         &mut self,
319         location: Location,
320         (place, span): (&Place<'tcx>, Span),
321         borrow: &BorrowData<'tcx>,
322     ) {
323         debug!(
324             "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
325             location, place, span, borrow
326         );
327         let value_msg = match self.describe_place(place.as_ref()) {
328             Some(name) => format!("`{}`", name),
329             None => "value".to_owned(),
330         };
331         let borrow_msg = match self.describe_place(borrow.borrowed_place.as_ref()) {
332             Some(name) => format!("`{}`", name),
333             None => "value".to_owned(),
334         };
335
336         let borrow_spans = self.retrieve_borrow_spans(borrow);
337         let borrow_span = borrow_spans.args_or_use();
338
339         let move_spans = self.move_spans(place.as_ref(), location);
340         let span = move_spans.args_or_use();
341
342         let mut err = self.cannot_move_when_borrowed(
343             span,
344             &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
345         );
346         err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
347         err.span_label(span, format!("move out of {} occurs here", value_msg));
348
349         borrow_spans.var_span_label(
350             &mut err,
351             format!("borrow occurs due to use{}", borrow_spans.describe())
352         );
353
354         move_spans.var_span_label(
355             &mut err,
356             format!("move occurs due to use{}", move_spans.describe())
357         );
358
359         self.explain_why_borrow_contains_point(
360             location,
361             borrow,
362             None,
363         ).add_explanation_to_diagnostic(
364             self.infcx.tcx,
365             self.body,
366             &self.local_names,
367             &mut err,
368             "",
369             Some(borrow_span),
370         );
371         err.buffer(&mut self.errors_buffer);
372     }
373
374     pub(super) fn report_use_while_mutably_borrowed(
375         &mut self,
376         location: Location,
377         (place, _span): (&Place<'tcx>, Span),
378         borrow: &BorrowData<'tcx>,
379     ) -> DiagnosticBuilder<'cx> {
380         let borrow_spans = self.retrieve_borrow_spans(borrow);
381         let borrow_span = borrow_spans.args_or_use();
382
383         // Conflicting borrows are reported separately, so only check for move
384         // captures.
385         let use_spans = self.move_spans(place.as_ref(), location);
386         let span = use_spans.var_or_use();
387
388         let mut err = self.cannot_use_when_mutably_borrowed(
389             span,
390             &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
391             borrow_span,
392             &self.describe_place(borrow.borrowed_place.as_ref())
393                 .unwrap_or_else(|| "_".to_owned()),
394         );
395
396         borrow_spans.var_span_label(&mut err, {
397             let place = &borrow.borrowed_place;
398             let desc_place =
399                 self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned());
400
401             format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
402         });
403
404         self.explain_why_borrow_contains_point(location, borrow, None)
405             .add_explanation_to_diagnostic(
406                 self.infcx.tcx,
407                 self.body,
408                 &self.local_names,
409                 &mut err,
410                 "",
411                 None,
412             );
413         err
414     }
415
416     pub(super) fn report_conflicting_borrow(
417         &mut self,
418         location: Location,
419         (place, span): (&Place<'tcx>, Span),
420         gen_borrow_kind: BorrowKind,
421         issued_borrow: &BorrowData<'tcx>,
422     ) -> DiagnosticBuilder<'cx> {
423         let issued_spans = self.retrieve_borrow_spans(issued_borrow);
424         let issued_span = issued_spans.args_or_use();
425
426         let borrow_spans = self.borrow_spans(span, location);
427         let span = borrow_spans.args_or_use();
428
429         let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
430             "generator"
431         } else {
432             "closure"
433         };
434
435         let (desc_place, msg_place, msg_borrow, union_type_name) =
436             self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
437
438         let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
439         let second_borrow_desc = if explanation.is_explained() {
440             "second "
441         } else {
442             ""
443         };
444
445         // FIXME: supply non-"" `opt_via` when appropriate
446         let first_borrow_desc;
447         let mut err = match (
448             gen_borrow_kind,
449             issued_borrow.kind,
450         ) {
451             (BorrowKind::Shared, BorrowKind::Mut { .. }) => {
452                 first_borrow_desc = "mutable ";
453                 self.cannot_reborrow_already_borrowed(
454                     span,
455                     &desc_place,
456                     &msg_place,
457                     "immutable",
458                     issued_span,
459                     "it",
460                     "mutable",
461                     &msg_borrow,
462                     None,
463                 )
464             }
465             (BorrowKind::Mut { .. }, BorrowKind::Shared) => {
466                 first_borrow_desc = "immutable ";
467                 self.cannot_reborrow_already_borrowed(
468                     span,
469                     &desc_place,
470                     &msg_place,
471                     "mutable",
472                     issued_span,
473                     "it",
474                     "immutable",
475                     &msg_borrow,
476                     None,
477                 )
478             }
479
480             (BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
481                 first_borrow_desc = "first ";
482                 self.cannot_mutably_borrow_multiply(
483                     span,
484                     &desc_place,
485                     &msg_place,
486                     issued_span,
487                     &msg_borrow,
488                     None,
489                 )
490             }
491
492             (BorrowKind::Unique, BorrowKind::Unique) => {
493                 first_borrow_desc = "first ";
494                 self.cannot_uniquely_borrow_by_two_closures(
495                     span,
496                     &desc_place,
497                     issued_span,
498                     None,
499                 )
500             }
501
502             (BorrowKind::Mut { .. }, BorrowKind::Shallow)
503             | (BorrowKind::Unique, BorrowKind::Shallow) => {
504                 if let Some(immutable_section_description) = self.classify_immutable_section(
505                     &issued_borrow.assigned_place,
506                 ) {
507                     let mut err = self.cannot_mutate_in_immutable_section(
508                         span,
509                         issued_span,
510                         &desc_place,
511                         immutable_section_description,
512                         "mutably borrow",
513                     );
514                     borrow_spans.var_span_label(
515                         &mut err,
516                         format!(
517                             "borrow occurs due to use of `{}`{}",
518                             desc_place,
519                             borrow_spans.describe(),
520                         ),
521                     );
522
523                     return err;
524                 } else {
525                     first_borrow_desc = "immutable ";
526                     self.cannot_reborrow_already_borrowed(
527                         span,
528                         &desc_place,
529                         &msg_place,
530                         "mutable",
531                         issued_span,
532                         "it",
533                         "immutable",
534                         &msg_borrow,
535                         None,
536                     )
537                 }
538             }
539
540             (BorrowKind::Unique, _) => {
541                 first_borrow_desc = "first ";
542                 self.cannot_uniquely_borrow_by_one_closure(
543                     span,
544                     container_name,
545                     &desc_place,
546                     "",
547                     issued_span,
548                     "it",
549                     "",
550                     None,
551                 )
552             },
553
554             (BorrowKind::Shared, BorrowKind::Unique) => {
555                 first_borrow_desc = "first ";
556                 self.cannot_reborrow_already_uniquely_borrowed(
557                     span,
558                     container_name,
559                     &desc_place,
560                     "",
561                     "immutable",
562                     issued_span,
563                     "",
564                     None,
565                     second_borrow_desc,
566                 )
567             }
568
569             (BorrowKind::Mut { .. }, BorrowKind::Unique) => {
570                 first_borrow_desc = "first ";
571                 self.cannot_reborrow_already_uniquely_borrowed(
572                     span,
573                     container_name,
574                     &desc_place,
575                     "",
576                     "mutable",
577                     issued_span,
578                     "",
579                     None,
580                     second_borrow_desc,
581                 )
582             }
583
584             (BorrowKind::Shared, BorrowKind::Shared)
585             | (BorrowKind::Shared, BorrowKind::Shallow)
586             | (BorrowKind::Shallow, BorrowKind::Mut { .. })
587             | (BorrowKind::Shallow, BorrowKind::Unique)
588             | (BorrowKind::Shallow, BorrowKind::Shared)
589             | (BorrowKind::Shallow, BorrowKind::Shallow) => unreachable!(),
590         };
591
592         if issued_spans == borrow_spans {
593             borrow_spans.var_span_label(
594                 &mut err,
595                 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
596             );
597         } else {
598             let borrow_place = &issued_borrow.borrowed_place;
599             let borrow_place_desc = self.describe_place(borrow_place.as_ref())
600                                         .unwrap_or_else(|| "_".to_owned());
601             issued_spans.var_span_label(
602                 &mut err,
603                 format!(
604                     "first borrow occurs due to use of `{}`{}",
605                     borrow_place_desc,
606                     issued_spans.describe(),
607                 ),
608             );
609
610             borrow_spans.var_span_label(
611                 &mut err,
612                 format!(
613                     "second borrow occurs due to use of `{}`{}",
614                     desc_place,
615                     borrow_spans.describe(),
616                 ),
617             );
618         }
619
620         if union_type_name != "" {
621             err.note(&format!(
622                 "`{}` is a field of the union `{}`, so it overlaps the field `{}`",
623                 msg_place, union_type_name, msg_borrow,
624             ));
625         }
626
627         explanation.add_explanation_to_diagnostic(
628             self.infcx.tcx,
629             self.body,
630             &self.local_names,
631             &mut err,
632             first_borrow_desc,
633             None,
634         );
635
636         err
637     }
638
639     /// Returns the description of the root place for a conflicting borrow and the full
640     /// descriptions of the places that caused the conflict.
641     ///
642     /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
643     /// attempted while a shared borrow is live, then this function will return:
644     ///
645     ///     ("x", "", "")
646     ///
647     /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
648     /// a shared borrow of another field `x.y`, then this function will return:
649     ///
650     ///     ("x", "x.z", "x.y")
651     ///
652     /// In the more complex union case, where the union is a field of a struct, then if a mutable
653     /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
654     /// another field `x.u.y`, then this function will return:
655     ///
656     ///     ("x.u", "x.u.z", "x.u.y")
657     ///
658     /// This is used when creating error messages like below:
659     ///
660     /// >  cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
661     /// >  mutable (via `a.u.s.b`) [E0502]
662     pub(super) fn describe_place_for_conflicting_borrow(
663         &self,
664         first_borrowed_place: &Place<'tcx>,
665         second_borrowed_place: &Place<'tcx>,
666     ) -> (String, String, String, String) {
667         // Define a small closure that we can use to check if the type of a place
668         // is a union.
669         let union_ty = |place_base, place_projection| {
670             let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
671             ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
672         };
673         let describe_place = |place| self.describe_place(place).unwrap_or_else(|| "_".to_owned());
674
675         // Start with an empty tuple, so we can use the functions on `Option` to reduce some
676         // code duplication (particularly around returning an empty description in the failure
677         // case).
678         Some(())
679             .filter(|_| {
680                 // If we have a conflicting borrow of the same place, then we don't want to add
681                 // an extraneous "via x.y" to our diagnostics, so filter out this case.
682                 first_borrowed_place != second_borrowed_place
683             })
684             .and_then(|_| {
685                 // We're going to want to traverse the first borrowed place to see if we can find
686                 // field access to a union. If we find that, then we will keep the place of the
687                 // union being accessed and the field that was being accessed so we can check the
688                 // second borrowed place for the same union and a access to a different field.
689                 let Place {
690                     base,
691                     projection,
692                 } = first_borrowed_place;
693
694                 let mut cursor = projection.as_ref();
695                 while let [proj_base @ .., elem] = cursor {
696                     cursor = proj_base;
697
698                     match elem {
699                         ProjectionElem::Field(field, _) if union_ty(base, proj_base).is_some() => {
700                             return Some((PlaceRef {
701                                 base: base,
702                                 projection: proj_base,
703                             }, field));
704                         },
705                         _ => {},
706                     }
707                 }
708                 None
709             })
710             .and_then(|(target_base, target_field)| {
711                 // With the place of a union and a field access into it, we traverse the second
712                 // borrowed place and look for a access to a different field of the same union.
713                 let Place {
714                     base,
715                     projection,
716                 } = second_borrowed_place;
717
718                 let mut cursor = projection.as_ref();
719                 while let [proj_base @ .., elem] = cursor {
720                     cursor = proj_base;
721
722                     if let ProjectionElem::Field(field, _) = elem {
723                         if let Some(union_ty) = union_ty(base, proj_base) {
724                             if field != target_field
725                                 && base == target_base.base
726                                 && proj_base == target_base.projection {
727                                 // FIXME when we avoid clone reuse describe_place closure
728                                 let describe_base_place =  self.describe_place(PlaceRef {
729                                     base: base,
730                                     projection: proj_base,
731                                 }).unwrap_or_else(|| "_".to_owned());
732
733                                 return Some((
734                                     describe_base_place,
735                                     describe_place(first_borrowed_place.as_ref()),
736                                     describe_place(second_borrowed_place.as_ref()),
737                                     union_ty.to_string(),
738                                 ));
739                             }
740                         }
741                     }
742                 }
743                 None
744             })
745             .unwrap_or_else(|| {
746                 // If we didn't find a field access into a union, or both places match, then
747                 // only return the description of the first place.
748                 (
749                     describe_place(first_borrowed_place.as_ref()),
750                     "".to_string(),
751                     "".to_string(),
752                     "".to_string(),
753                 )
754             })
755     }
756
757     /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
758     ///
759     /// This means that some data referenced by `borrow` needs to live
760     /// past the point where the StorageDeadOrDrop of `place` occurs.
761     /// This is usually interpreted as meaning that `place` has too
762     /// short a lifetime. (But sometimes it is more useful to report
763     /// it as a more direct conflict between the execution of a
764     /// `Drop::drop` with an aliasing borrow.)
765     pub(super) fn report_borrowed_value_does_not_live_long_enough(
766         &mut self,
767         location: Location,
768         borrow: &BorrowData<'tcx>,
769         place_span: (&Place<'tcx>, Span),
770         kind: Option<WriteKind>,
771     ) {
772         debug!(
773             "report_borrowed_value_does_not_live_long_enough(\
774              {:?}, {:?}, {:?}, {:?}\
775              )",
776             location, borrow, place_span, kind
777         );
778
779         let drop_span = place_span.1;
780         let root_place = self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All)
781             .last()
782             .unwrap();
783
784         let borrow_spans = self.retrieve_borrow_spans(borrow);
785         let borrow_span = borrow_spans.var_or_use();
786
787         assert!(root_place.projection.is_empty());
788         let proper_span = match root_place.base {
789             PlaceBase::Local(local) => self.body.local_decls[*local].source_info.span,
790             _ => drop_span,
791         };
792
793         let root_place_projection = self.infcx.tcx.intern_place_elems(root_place.projection);
794
795         if self.access_place_error_reported
796             .contains(&(Place {
797                 base: root_place.base.clone(),
798                 projection: root_place_projection,
799             }, borrow_span))
800         {
801             debug!(
802                 "suppressing access_place error when borrow doesn't live long enough for {:?}",
803                 borrow_span
804             );
805             return;
806         }
807
808         self.access_place_error_reported
809             .insert((Place {
810                 base: root_place.base.clone(),
811                 projection: root_place_projection,
812             }, borrow_span));
813
814         if let PlaceBase::Local(local) = borrow.borrowed_place.base {
815             if self.body.local_decls[local].is_ref_to_thread_local() {
816                 let err = self.report_thread_local_value_does_not_live_long_enough(
817                     drop_span,
818                     borrow_span,
819                 );
820                 err.buffer(&mut self.errors_buffer);
821                 return;
822             }
823         };
824
825         if let StorageDeadOrDrop::Destructor(dropped_ty) =
826             self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
827         {
828             // If a borrow of path `B` conflicts with drop of `D` (and
829             // we're not in the uninteresting case where `B` is a
830             // prefix of `D`), then report this as a more interesting
831             // destructor conflict.
832             if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
833                 self.report_borrow_conflicts_with_destructor(
834                     location, borrow, place_span, kind, dropped_ty,
835                 );
836                 return;
837             }
838         }
839
840         let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
841
842         let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
843         let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
844
845         debug!(
846             "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
847             place_desc,
848             explanation
849         );
850         let err = match (place_desc, explanation) {
851             // If the outlives constraint comes from inside the closure,
852             // for example:
853             //
854             // let x = 0;
855             // let y = &x;
856             // Box::new(|| y) as Box<Fn() -> &'static i32>
857             //
858             // then just use the normal error. The closure isn't escaping
859             // and `move` will not help here.
860             (
861                 Some(ref name),
862                 BorrowExplanation::MustBeValidFor {
863                     category: category @ ConstraintCategory::Return,
864                     from_closure: false,
865                     ref region_name,
866                     span,
867                     ..
868                 },
869             )
870             | (
871                 Some(ref name),
872                 BorrowExplanation::MustBeValidFor {
873                     category: category @ ConstraintCategory::CallArgument,
874                     from_closure: false,
875                     ref region_name,
876                     span,
877                     ..
878                 },
879             ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
880                 borrow_spans,
881                 borrow_span,
882                 region_name,
883                 category,
884                 span,
885                 &format!("`{}`", name),
886             ),
887             (
888                 Some(ref name),
889                 BorrowExplanation::MustBeValidFor {
890                     category: category @ ConstraintCategory::OpaqueType,
891                     from_closure: false,
892                     ref region_name,
893                     span,
894                     ..
895                 },
896
897             ) if borrow_spans.for_generator() => self.report_escaping_closure_capture(
898                 borrow_spans,
899                 borrow_span,
900                 region_name,
901                 category,
902                 span,
903                 &format!("`{}`", name),
904             ),
905             (
906                 ref name,
907                 BorrowExplanation::MustBeValidFor {
908                     category: ConstraintCategory::Assignment,
909                     from_closure: false,
910                     region_name: RegionName {
911                         source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
912                         ..
913                     },
914                     span,
915                     ..
916                 },
917             ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
918             (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
919                 location,
920                 &name,
921                 &borrow,
922                 drop_span,
923                 borrow_spans,
924                 explanation,
925             ),
926             (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
927                 location,
928                 &borrow,
929                 drop_span,
930                 borrow_spans,
931                 proper_span,
932                 explanation,
933             ),
934         };
935
936         err.buffer(&mut self.errors_buffer);
937     }
938
939     fn report_local_value_does_not_live_long_enough(
940         &mut self,
941         location: Location,
942         name: &str,
943         borrow: &BorrowData<'tcx>,
944         drop_span: Span,
945         borrow_spans: UseSpans,
946         explanation: BorrowExplanation,
947     ) -> DiagnosticBuilder<'cx> {
948         debug!(
949             "report_local_value_does_not_live_long_enough(\
950              {:?}, {:?}, {:?}, {:?}, {:?}\
951              )",
952             location, name, borrow, drop_span, borrow_spans
953         );
954
955         let borrow_span = borrow_spans.var_or_use();
956         if let BorrowExplanation::MustBeValidFor {
957             category,
958             span,
959             ref opt_place_desc,
960             from_closure: false,
961             ..
962         } = explanation {
963             if let Some(diag) = self.try_report_cannot_return_reference_to_local(
964                 borrow,
965                 borrow_span,
966                 span,
967                 category,
968                 opt_place_desc.as_ref(),
969             ) {
970                 return diag;
971             }
972         }
973
974         let mut err = self.path_does_not_live_long_enough(
975             borrow_span,
976             &format!("`{}`", name),
977         );
978
979         if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
980             let region_name = annotation.emit(self, &mut err);
981
982             err.span_label(
983                 borrow_span,
984                 format!("`{}` would have to be valid for `{}`...", name, region_name),
985             );
986
987             if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
988                 err.span_label(
989                     drop_span,
990                     format!(
991                         "...but `{}` will be dropped here, when the function `{}` returns",
992                         name,
993                         self.infcx.tcx.hir().name(fn_hir_id),
994                     ),
995                 );
996
997                 err.note(
998                     "functions cannot return a borrow to data owned within the function's scope, \
999                      functions can only return borrows to data passed as arguments",
1000                 );
1001                 err.note(
1002                     "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
1003                      references-and-borrowing.html#dangling-references>",
1004                 );
1005             } else {
1006                 err.span_label(
1007                     drop_span,
1008                     format!("...but `{}` dropped here while still borrowed", name),
1009                 );
1010             }
1011
1012             if let BorrowExplanation::MustBeValidFor { .. } = explanation {
1013             } else {
1014                 explanation.add_explanation_to_diagnostic(
1015                     self.infcx.tcx,
1016                     self.body,
1017                     &self.local_names,
1018                     &mut err,
1019                     "",
1020                     None,
1021                 );
1022             }
1023         } else {
1024             err.span_label(borrow_span, "borrowed value does not live long enough");
1025             err.span_label(
1026                 drop_span,
1027                 format!("`{}` dropped here while still borrowed", name),
1028             );
1029
1030             let within = if borrow_spans.for_generator() {
1031                 " by generator"
1032             } else {
1033                 ""
1034             };
1035
1036             borrow_spans.args_span_label(
1037                 &mut err,
1038                 format!("value captured here{}", within),
1039             );
1040
1041             explanation.add_explanation_to_diagnostic(
1042                 self.infcx.tcx, self.body, &self.local_names, &mut err, "", None);
1043         }
1044
1045         err
1046     }
1047
1048     fn report_borrow_conflicts_with_destructor(
1049         &mut self,
1050         location: Location,
1051         borrow: &BorrowData<'tcx>,
1052         (place, drop_span): (&Place<'tcx>, Span),
1053         kind: Option<WriteKind>,
1054         dropped_ty: Ty<'tcx>,
1055     ) {
1056         debug!(
1057             "report_borrow_conflicts_with_destructor(\
1058              {:?}, {:?}, ({:?}, {:?}), {:?}\
1059              )",
1060             location, borrow, place, drop_span, kind,
1061         );
1062
1063         let borrow_spans = self.retrieve_borrow_spans(borrow);
1064         let borrow_span = borrow_spans.var_or_use();
1065
1066         let mut err = self.cannot_borrow_across_destructor(borrow_span);
1067
1068         let what_was_dropped = match self.describe_place(place.as_ref()) {
1069             Some(name) => format!("`{}`", name),
1070             None => String::from("temporary value"),
1071         };
1072
1073         let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
1074             Some(borrowed) => format!(
1075                 "here, drop of {D} needs exclusive access to `{B}`, \
1076                  because the type `{T}` implements the `Drop` trait",
1077                 D = what_was_dropped,
1078                 T = dropped_ty,
1079                 B = borrowed
1080             ),
1081             None => format!(
1082                 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
1083                 D = what_was_dropped,
1084                 T = dropped_ty
1085             ),
1086         };
1087         err.span_label(drop_span, label);
1088
1089         // Only give this note and suggestion if they could be relevant.
1090         let explanation =
1091             self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
1092         match explanation {
1093             BorrowExplanation::UsedLater { .. }
1094             | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1095                 err.note("consider using a `let` binding to create a longer lived value");
1096             }
1097             _ => {}
1098         }
1099
1100         explanation.add_explanation_to_diagnostic(
1101             self.infcx.tcx,
1102             self.body,
1103             &self.local_names,
1104             &mut err,
1105             "",
1106             None,
1107         );
1108
1109         err.buffer(&mut self.errors_buffer);
1110     }
1111
1112     fn report_thread_local_value_does_not_live_long_enough(
1113         &mut self,
1114         drop_span: Span,
1115         borrow_span: Span,
1116     ) -> DiagnosticBuilder<'cx> {
1117         debug!(
1118             "report_thread_local_value_does_not_live_long_enough(\
1119              {:?}, {:?}\
1120              )",
1121             drop_span, borrow_span
1122         );
1123
1124         let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1125
1126         err.span_label(
1127             borrow_span,
1128             "thread-local variables cannot be borrowed beyond the end of the function",
1129         );
1130         err.span_label(drop_span, "end of enclosing function is here");
1131
1132         err
1133     }
1134
1135     fn report_temporary_value_does_not_live_long_enough(
1136         &mut self,
1137         location: Location,
1138         borrow: &BorrowData<'tcx>,
1139         drop_span: Span,
1140         borrow_spans: UseSpans,
1141         proper_span: Span,
1142         explanation: BorrowExplanation,
1143     ) -> DiagnosticBuilder<'cx> {
1144         debug!(
1145             "report_temporary_value_does_not_live_long_enough(\
1146              {:?}, {:?}, {:?}, {:?}\
1147              )",
1148             location, borrow, drop_span, proper_span
1149         );
1150
1151         if let BorrowExplanation::MustBeValidFor {
1152             category,
1153             span,
1154             from_closure: false,
1155             ..
1156         } = explanation {
1157             if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1158                 borrow,
1159                 proper_span,
1160                 span,
1161                 category,
1162                 None,
1163             ) {
1164                 return diag;
1165             }
1166         }
1167
1168         let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1169         err.span_label(
1170             proper_span,
1171             "creates a temporary which is freed while still in use",
1172         );
1173         err.span_label(
1174             drop_span,
1175             "temporary value is freed at the end of this statement",
1176         );
1177
1178         match explanation {
1179             BorrowExplanation::UsedLater(..)
1180             | BorrowExplanation::UsedLaterInLoop(..)
1181             | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1182                 // Only give this note and suggestion if it could be relevant.
1183                 err.note("consider using a `let` binding to create a longer lived value");
1184             }
1185             _ => {}
1186         }
1187         explanation.add_explanation_to_diagnostic(
1188             self.infcx.tcx,
1189             self.body,
1190             &self.local_names,
1191             &mut err,
1192             "",
1193             None,
1194         );
1195
1196         let within = if borrow_spans.for_generator() {
1197             " by generator"
1198         } else {
1199             ""
1200         };
1201
1202         borrow_spans.args_span_label(
1203             &mut err,
1204             format!("value captured here{}", within),
1205         );
1206
1207         err
1208     }
1209
1210     fn try_report_cannot_return_reference_to_local(
1211         &self,
1212         borrow: &BorrowData<'tcx>,
1213         borrow_span: Span,
1214         return_span: Span,
1215         category: ConstraintCategory,
1216         opt_place_desc: Option<&String>,
1217     ) -> Option<DiagnosticBuilder<'cx>> {
1218         let return_kind = match category {
1219             ConstraintCategory::Return => "return",
1220             ConstraintCategory::Yield => "yield",
1221             _ => return None,
1222         };
1223
1224         // FIXME use a better heuristic than Spans
1225         let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1226             "reference to"
1227         } else {
1228             "value referencing"
1229         };
1230
1231         let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1232             let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1233                 match self.body.local_kind(local) {
1234                     LocalKind::ReturnPointer
1235                     | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1236                     LocalKind::Var => "local variable ",
1237                     LocalKind::Arg
1238                     if !self.upvars.is_empty()
1239                         && local == Local::new(1) => {
1240                         "variable captured by `move` "
1241                     }
1242                     LocalKind::Arg => {
1243                         "function parameter "
1244                     }
1245                 }
1246             } else {
1247                 "local data "
1248             };
1249             (
1250                 format!("{}`{}`", local_kind, place_desc),
1251                 format!("`{}` is borrowed here", place_desc),
1252             )
1253         } else {
1254             let root_place = self.prefixes(borrow.borrowed_place.as_ref(),
1255                                            PrefixSet::All)
1256                 .last()
1257                 .unwrap();
1258             let local = if let PlaceRef {
1259                 base: PlaceBase::Local(local),
1260                 projection: [],
1261             } = root_place {
1262                 local
1263             } else {
1264                 bug!("try_report_cannot_return_reference_to_local: not a local")
1265             };
1266             match self.body.local_kind(*local) {
1267                 LocalKind::ReturnPointer | LocalKind::Temp => (
1268                     "temporary value".to_string(),
1269                     "temporary value created here".to_string(),
1270                 ),
1271                 LocalKind::Arg => (
1272                     "function parameter".to_string(),
1273                     "function parameter borrowed here".to_string(),
1274                 ),
1275                 LocalKind::Var => (
1276                     "local binding".to_string(),
1277                     "local binding introduced here".to_string(),
1278                 ),
1279             }
1280         };
1281
1282         let mut err = self.cannot_return_reference_to_local(
1283             return_span,
1284             return_kind,
1285             reference_desc,
1286             &place_desc,
1287         );
1288
1289         if return_span != borrow_span {
1290             err.span_label(borrow_span, note);
1291         }
1292
1293         Some(err)
1294     }
1295
1296     fn report_escaping_closure_capture(
1297         &mut self,
1298         use_span: UseSpans,
1299         var_span: Span,
1300         fr_name: &RegionName,
1301         category: ConstraintCategory,
1302         constraint_span: Span,
1303         captured_var: &str,
1304     ) -> DiagnosticBuilder<'cx> {
1305         let tcx = self.infcx.tcx;
1306         let args_span = use_span.args_or_use();
1307         let mut err = self.cannot_capture_in_long_lived_closure(
1308             args_span,
1309             captured_var,
1310             var_span,
1311         );
1312
1313         let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1314             Ok(mut string) => {
1315                 if string.starts_with("async ") {
1316                     string.insert_str(6, "move ");
1317                 } else if string.starts_with("async|") {
1318                     string.insert_str(5, " move");
1319                 } else {
1320                     string.insert_str(0, "move ");
1321                 };
1322                 string
1323             },
1324             Err(_) => "move |<args>| <body>".to_string()
1325         };
1326         let kind = match use_span.generator_kind() {
1327             Some(generator_kind) => match generator_kind {
1328                 GeneratorKind::Async(async_kind) => match async_kind {
1329                     AsyncGeneratorKind::Block => "async block",
1330                     AsyncGeneratorKind::Closure => "async closure",
1331                     _ => bug!("async block/closure expected, but async funtion found."),
1332                 },
1333                 GeneratorKind::Gen => "generator",
1334             }
1335             None => "closure",
1336         };
1337         err.span_suggestion(
1338             args_span,
1339             &format!(
1340                 "to force the {} to take ownership of {} (and any \
1341                  other referenced variables), use the `move` keyword",
1342                  kind,
1343                  captured_var
1344             ),
1345             suggestion,
1346             Applicability::MachineApplicable,
1347         );
1348
1349         let msg = match category {
1350             ConstraintCategory::Return => "closure is returned here".to_string(),
1351             ConstraintCategory::OpaqueType => "generator is returned here".to_string(),
1352             ConstraintCategory::CallArgument => {
1353                 fr_name.highlight_region_name(&mut err);
1354                 format!("function requires argument type to outlive `{}`", fr_name)
1355             }
1356             _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1357                        category: `{:?}`", category),
1358         };
1359         err.span_note(constraint_span, &msg);
1360         err
1361     }
1362
1363     fn report_escaping_data(
1364         &mut self,
1365         borrow_span: Span,
1366         name: &Option<String>,
1367         upvar_span: Span,
1368         upvar_name: &str,
1369         escape_span: Span,
1370     ) -> DiagnosticBuilder<'cx> {
1371         let tcx = self.infcx.tcx;
1372
1373         let escapes_from = if tcx.is_closure(self.mir_def_id) {
1374             let tables = tcx.typeck_tables_of(self.mir_def_id);
1375             let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1376             match tables.node_type(mir_hir_id).kind {
1377                 ty::Closure(..) => "closure",
1378                 ty::Generator(..) => "generator",
1379                 _ => bug!("Closure body doesn't have a closure or generator type"),
1380             }
1381         } else {
1382             "function"
1383         };
1384
1385         let mut err = borrowck_errors::borrowed_data_escapes_closure(
1386             tcx,
1387             escape_span,
1388             escapes_from,
1389         );
1390
1391         err.span_label(
1392             upvar_span,
1393             format!(
1394                 "`{}` is declared here, outside of the {} body",
1395                 upvar_name, escapes_from
1396             ),
1397         );
1398
1399         err.span_label(
1400             borrow_span,
1401             format!(
1402                 "borrow is only valid in the {} body",
1403                 escapes_from
1404             ),
1405         );
1406
1407         if let Some(name) = name {
1408             err.span_label(
1409                 escape_span,
1410                 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1411             );
1412         } else {
1413             err.span_label(
1414                 escape_span,
1415                 format!("reference escapes the {} body here", escapes_from),
1416             );
1417         }
1418
1419         err
1420     }
1421
1422     fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1423         let body = self.body;
1424
1425         let mut stack = Vec::new();
1426         stack.extend(body.predecessor_locations(location).map(|predecessor| {
1427             let is_back_edge = location.dominates(predecessor, &self.dominators);
1428             (predecessor, is_back_edge)
1429         }));
1430
1431         let mut visited = FxHashSet::default();
1432         let mut result = vec![];
1433
1434         'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1435             debug!(
1436                 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1437                 location, is_back_edge
1438             );
1439
1440             if !visited.insert(location) {
1441                 continue;
1442             }
1443
1444             // check for moves
1445             let stmt_kind = body[location.block]
1446                 .statements
1447                 .get(location.statement_index)
1448                 .map(|s| &s.kind);
1449             if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1450                 // this analysis only tries to find moves explicitly
1451                 // written by the user, so we ignore the move-outs
1452                 // created by `StorageDead` and at the beginning
1453                 // of a function.
1454             } else {
1455                 // If we are found a use of a.b.c which was in error, then we want to look for
1456                 // moves not only of a.b.c but also a.b and a.
1457                 //
1458                 // Note that the moves data already includes "parent" paths, so we don't have to
1459                 // worry about the other case: that is, if there is a move of a.b.c, it is already
1460                 // marked as a move of a.b and a as well, so we will generate the correct errors
1461                 // there.
1462                 let mut mpis = vec![mpi];
1463                 let move_paths = &self.move_data.move_paths;
1464                 mpis.extend(move_paths[mpi].parents(move_paths));
1465
1466                 for moi in &self.move_data.loc_map[location] {
1467                     debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1468                     if mpis.contains(&self.move_data.moves[*moi].path) {
1469                         debug!("report_use_of_moved_or_uninitialized: found");
1470                         result.push(MoveSite {
1471                             moi: *moi,
1472                             traversed_back_edge: is_back_edge,
1473                         });
1474
1475                         // Strictly speaking, we could continue our DFS here. There may be
1476                         // other moves that can reach the point of error. But it is kind of
1477                         // confusing to highlight them.
1478                         //
1479                         // Example:
1480                         //
1481                         // ```
1482                         // let a = vec![];
1483                         // let b = a;
1484                         // let c = a;
1485                         // drop(a); // <-- current point of error
1486                         // ```
1487                         //
1488                         // Because we stop the DFS here, we only highlight `let c = a`,
1489                         // and not `let b = a`. We will of course also report an error at
1490                         // `let c = a` which highlights `let b = a` as the move.
1491                         continue 'dfs;
1492                     }
1493                 }
1494             }
1495
1496             // check for inits
1497             let mut any_match = false;
1498             drop_flag_effects::for_location_inits(
1499                 self.infcx.tcx,
1500                 self.body,
1501                 self.move_data,
1502                 location,
1503                 |m| {
1504                     if m == mpi {
1505                         any_match = true;
1506                     }
1507                 },
1508             );
1509             if any_match {
1510                 continue 'dfs;
1511             }
1512
1513             stack.extend(body.predecessor_locations(location).map(|predecessor| {
1514                 let back_edge = location.dominates(predecessor, &self.dominators);
1515                 (predecessor, is_back_edge || back_edge)
1516             }));
1517         }
1518
1519         result
1520     }
1521
1522     pub(super) fn report_illegal_mutation_of_borrowed(
1523         &mut self,
1524         location: Location,
1525         (place, span): (&Place<'tcx>, Span),
1526         loan: &BorrowData<'tcx>,
1527     ) {
1528         let loan_spans = self.retrieve_borrow_spans(loan);
1529         let loan_span = loan_spans.args_or_use();
1530
1531         if loan.kind == BorrowKind::Shallow {
1532             if let Some(section) = self.classify_immutable_section(&loan.assigned_place) {
1533                 let mut err = self.cannot_mutate_in_immutable_section(
1534                     span,
1535                     loan_span,
1536                     &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1537                     section,
1538                     "assign",
1539                 );
1540                 loan_spans.var_span_label(
1541                     &mut err,
1542                     format!("borrow occurs due to use{}", loan_spans.describe()),
1543                 );
1544
1545                 err.buffer(&mut self.errors_buffer);
1546
1547                 return;
1548             }
1549         }
1550
1551         let mut err = self.cannot_assign_to_borrowed(
1552             span,
1553             loan_span,
1554             &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1555         );
1556
1557         loan_spans.var_span_label(
1558             &mut err,
1559             format!("borrow occurs due to use{}", loan_spans.describe()),
1560         );
1561
1562         self.explain_why_borrow_contains_point(location, loan, None)
1563             .add_explanation_to_diagnostic(
1564                 self.infcx.tcx,
1565                 self.body,
1566                 &self.local_names,
1567                 &mut err,
1568                 "",
1569                 None,
1570             );
1571
1572         err.buffer(&mut self.errors_buffer);
1573     }
1574
1575     /// Reports an illegal reassignment; for example, an assignment to
1576     /// (part of) a non-`mut` local that occurs potentially after that
1577     /// local has already been initialized. `place` is the path being
1578     /// assigned; `err_place` is a place providing a reason why
1579     /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1580     /// assignment to `x.f`).
1581     pub(super) fn report_illegal_reassignment(
1582         &mut self,
1583         _location: Location,
1584         (place, span): (&Place<'tcx>, Span),
1585         assigned_span: Span,
1586         err_place: &Place<'tcx>,
1587     ) {
1588         let (from_arg, local_decl, local_name) = match err_place.as_local() {
1589             Some(local) => (
1590                 self.body.local_kind(local) == LocalKind::Arg,
1591                 Some(&self.body.local_decls[local]),
1592                 self.local_names[local],
1593             ),
1594             None => (false, None, None),
1595         };
1596
1597         // If root local is initialized immediately (everything apart from let
1598         // PATTERN;) then make the error refer to that local, rather than the
1599         // place being assigned later.
1600         let (place_description, assigned_span) = match local_decl {
1601             Some(LocalDecl {
1602                 local_info: LocalInfo::User(ClearCrossCrate::Clear),
1603                 ..
1604             })
1605             | Some(LocalDecl {
1606                 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1607                     opt_match_place: None,
1608                     ..
1609                 }))),
1610                 ..
1611             })
1612             | Some(LocalDecl {
1613                 local_info: LocalInfo::StaticRef { .. },
1614                 ..
1615             })
1616             | Some(LocalDecl {
1617                 local_info: LocalInfo::Other,
1618                 ..
1619             })
1620             | None => (self.describe_place(place.as_ref()), assigned_span),
1621             Some(decl) => (self.describe_place(err_place.as_ref()), decl.source_info.span),
1622         };
1623
1624         let mut err = self.cannot_reassign_immutable(
1625             span,
1626             place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1627             from_arg,
1628         );
1629         let msg = if from_arg {
1630             "cannot assign to immutable argument"
1631         } else {
1632             "cannot assign twice to immutable variable"
1633         };
1634         if span != assigned_span {
1635             if !from_arg {
1636                 let value_msg = match place_description {
1637                     Some(name) => format!("`{}`", name),
1638                     None => "value".to_owned(),
1639                 };
1640                 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1641             }
1642         }
1643         if let Some(decl) = local_decl {
1644             if let Some(name) = local_name {
1645                 if decl.can_be_made_mutable() {
1646                     err.span_suggestion(
1647                         decl.source_info.span,
1648                         "make this binding mutable",
1649                         format!("mut {}", name),
1650                         Applicability::MachineApplicable,
1651                     );
1652                 }
1653             }
1654         }
1655         err.span_label(span, msg);
1656         err.buffer(&mut self.errors_buffer);
1657     }
1658
1659     fn classify_drop_access_kind(&self, place: PlaceRef<'cx, 'tcx>) -> StorageDeadOrDrop<'tcx> {
1660         let tcx = self.infcx.tcx;
1661         match place.projection {
1662             [] => {
1663                 StorageDeadOrDrop::LocalStorageDead
1664             }
1665             [proj_base @ .., elem] => {
1666                 // FIXME(spastorino) make this iterate
1667                 let base_access = self.classify_drop_access_kind(PlaceRef {
1668                     base: place.base,
1669                     projection: proj_base,
1670                 });
1671                 match elem {
1672                     ProjectionElem::Deref => match base_access {
1673                         StorageDeadOrDrop::LocalStorageDead
1674                         | StorageDeadOrDrop::BoxedStorageDead => {
1675                             assert!(
1676                                 Place::ty_from(&place.base, proj_base, self.body, tcx).ty.is_box(),
1677                                 "Drop of value behind a reference or raw pointer"
1678                             );
1679                             StorageDeadOrDrop::BoxedStorageDead
1680                         }
1681                         StorageDeadOrDrop::Destructor(_) => base_access,
1682                     },
1683                     ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1684                         let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1685                         match base_ty.kind {
1686                             ty::Adt(def, _) if def.has_dtor(tcx) => {
1687                                 // Report the outermost adt with a destructor
1688                                 match base_access {
1689                                     StorageDeadOrDrop::Destructor(_) => base_access,
1690                                     StorageDeadOrDrop::LocalStorageDead
1691                                     | StorageDeadOrDrop::BoxedStorageDead => {
1692                                         StorageDeadOrDrop::Destructor(base_ty)
1693                                     }
1694                                 }
1695                             }
1696                             _ => base_access,
1697                         }
1698                     }
1699
1700                     ProjectionElem::ConstantIndex { .. }
1701                     | ProjectionElem::Subslice { .. }
1702                     | ProjectionElem::Index(_) => base_access,
1703                 }
1704             }
1705         }
1706     }
1707
1708     /// Describe the reason for the fake borrow that was assigned to `place`.
1709     fn classify_immutable_section(&self, place: &Place<'tcx>) -> Option<&'static str> {
1710         use rustc::mir::visit::Visitor;
1711         struct FakeReadCauseFinder<'a, 'tcx> {
1712             place: &'a Place<'tcx>,
1713             cause: Option<FakeReadCause>,
1714         }
1715         impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'_, 'tcx> {
1716             fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1717                 match statement {
1718                     Statement {
1719                         kind: StatementKind::FakeRead(cause, box ref place),
1720                         ..
1721                     } if *place == *self.place => {
1722                         self.cause = Some(*cause);
1723                     }
1724                     _ => (),
1725                 }
1726             }
1727         }
1728         let mut visitor = FakeReadCauseFinder { place, cause: None };
1729         visitor.visit_body(&self.body);
1730         match visitor.cause {
1731             Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1732             Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1733             _ => None,
1734         }
1735     }
1736
1737     /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1738     /// borrow of local value that does not live long enough.
1739     fn annotate_argument_and_return_for_borrow(
1740         &self,
1741         borrow: &BorrowData<'tcx>,
1742     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1743         // Define a fallback for when we can't match a closure.
1744         let fallback = || {
1745             let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1746             if is_closure {
1747                 None
1748             } else {
1749                 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1750                 match ty.kind {
1751                     ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1752                         self.mir_def_id,
1753                         self.infcx.tcx.fn_sig(self.mir_def_id),
1754                     ),
1755                     _ => None,
1756                 }
1757             }
1758         };
1759
1760         // In order to determine whether we need to annotate, we need to check whether the reserve
1761         // place was an assignment into a temporary.
1762         //
1763         // If it was, we check whether or not that temporary is eventually assigned into the return
1764         // place. If it was, we can add annotations about the function's return type and arguments
1765         // and it'll make sense.
1766         let location = borrow.reserve_location;
1767         debug!(
1768             "annotate_argument_and_return_for_borrow: location={:?}",
1769             location
1770         );
1771         if let Some(&Statement { kind: StatementKind::Assign(box(ref reservation, _)), ..})
1772              = &self.body[location.block].statements.get(location.statement_index)
1773         {
1774             debug!(
1775                 "annotate_argument_and_return_for_borrow: reservation={:?}",
1776                 reservation
1777             );
1778             // Check that the initial assignment of the reserve location is into a temporary.
1779             let mut target = match reservation.as_local() {
1780                 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
1781                 _ => return None,
1782             };
1783
1784             // Next, look through the rest of the block, checking if we are assigning the
1785             // `target` (that is, the place that contains our borrow) to anything.
1786             let mut annotated_closure = None;
1787             for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1788                 debug!(
1789                     "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1790                     target, stmt
1791                 );
1792                 if let StatementKind::Assign(box(place, rvalue)) = &stmt.kind {
1793                     if let Some(assigned_to) = place.as_local() {
1794                         debug!(
1795                             "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1796                              rvalue={:?}",
1797                             assigned_to, rvalue
1798                         );
1799                         // Check if our `target` was captured by a closure.
1800                         if let Rvalue::Aggregate(
1801                             box AggregateKind::Closure(def_id, substs),
1802                             operands,
1803                         ) = rvalue
1804                         {
1805                             for operand in operands {
1806                                 let assigned_from = match operand {
1807                                     Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1808                                         assigned_from
1809                                     }
1810                                     _ => continue,
1811                                 };
1812                                 debug!(
1813                                     "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1814                                     assigned_from
1815                                 );
1816
1817                                 // Find the local from the operand.
1818                                 let assigned_from_local = match assigned_from.local_or_deref_local()
1819                                 {
1820                                     Some(local) => local,
1821                                     None => continue,
1822                                 };
1823
1824                                 if assigned_from_local != target {
1825                                     continue;
1826                                 }
1827
1828                                 // If a closure captured our `target` and then assigned
1829                                 // into a place then we should annotate the closure in
1830                                 // case it ends up being assigned into the return place.
1831                                 annotated_closure = self.annotate_fn_sig(
1832                                     *def_id,
1833                                     self.infcx.closure_sig(*def_id, *substs),
1834                                 );
1835                                 debug!(
1836                                     "annotate_argument_and_return_for_borrow: \
1837                                      annotated_closure={:?} assigned_from_local={:?} \
1838                                      assigned_to={:?}",
1839                                     annotated_closure, assigned_from_local, assigned_to
1840                                 );
1841
1842                                 if assigned_to == mir::RETURN_PLACE {
1843                                     // If it was assigned directly into the return place, then
1844                                     // return now.
1845                                     return annotated_closure;
1846                                 } else {
1847                                     // Otherwise, update the target.
1848                                     target = assigned_to;
1849                                 }
1850                             }
1851
1852                             // If none of our closure's operands matched, then skip to the next
1853                             // statement.
1854                             continue;
1855                         }
1856
1857                         // Otherwise, look at other types of assignment.
1858                         let assigned_from = match rvalue {
1859                             Rvalue::Ref(_, _, assigned_from) => assigned_from,
1860                             Rvalue::Use(operand) => match operand {
1861                                 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1862                                     assigned_from
1863                                 }
1864                                 _ => continue,
1865                             },
1866                             _ => continue,
1867                         };
1868                         debug!(
1869                             "annotate_argument_and_return_for_borrow: \
1870                              assigned_from={:?}",
1871                             assigned_from,
1872                         );
1873
1874                         // Find the local from the rvalue.
1875                         let assigned_from_local = match assigned_from.local_or_deref_local() {
1876                             Some(local) => local,
1877                             None => continue,
1878                         };
1879                         debug!(
1880                             "annotate_argument_and_return_for_borrow: \
1881                              assigned_from_local={:?}",
1882                             assigned_from_local,
1883                         );
1884
1885                         // Check if our local matches the target - if so, we've assigned our
1886                         // borrow to a new place.
1887                         if assigned_from_local != target {
1888                             continue;
1889                         }
1890
1891                         // If we assigned our `target` into a new place, then we should
1892                         // check if it was the return place.
1893                         debug!(
1894                             "annotate_argument_and_return_for_borrow: \
1895                              assigned_from_local={:?} assigned_to={:?}",
1896                             assigned_from_local, assigned_to
1897                         );
1898                         if assigned_to == mir::RETURN_PLACE {
1899                             // If it was then return the annotated closure if there was one,
1900                             // else, annotate this function.
1901                             return annotated_closure.or_else(fallback);
1902                         }
1903
1904                         // If we didn't assign into the return place, then we just update
1905                         // the target.
1906                         target = assigned_to;
1907                     }
1908                 }
1909             }
1910
1911             // Check the terminator if we didn't find anything in the statements.
1912             let terminator = &self.body[location.block].terminator();
1913             debug!(
1914                 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1915                 target, terminator
1916             );
1917             if let TerminatorKind::Call {
1918                 destination: Some((place, _)),
1919                 args,
1920                 ..
1921             } = &terminator.kind
1922             {
1923                 if let Some(assigned_to) = place.as_local() {
1924                     debug!(
1925                         "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1926                         assigned_to, args
1927                     );
1928                     for operand in args {
1929                         let assigned_from = match operand {
1930                             Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1931                                 assigned_from
1932                             }
1933                             _ => continue,
1934                         };
1935                         debug!(
1936                             "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1937                             assigned_from,
1938                         );
1939
1940                         if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1941                             debug!(
1942                                 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1943                                 assigned_from_local,
1944                             );
1945
1946                             if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1947                                 return annotated_closure.or_else(fallback);
1948                             }
1949                         }
1950                     }
1951                 }
1952             }
1953         }
1954
1955         // If we haven't found an assignment into the return place, then we need not add
1956         // any annotations.
1957         debug!("annotate_argument_and_return_for_borrow: none found");
1958         None
1959     }
1960
1961     /// Annotate the first argument and return type of a function signature if they are
1962     /// references.
1963     fn annotate_fn_sig(
1964         &self,
1965         did: DefId,
1966         sig: ty::PolyFnSig<'tcx>,
1967     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1968         debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1969         let is_closure = self.infcx.tcx.is_closure(did);
1970         let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
1971         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1972
1973         // We need to work out which arguments to highlight. We do this by looking
1974         // at the return type, where there are three cases:
1975         //
1976         // 1. If there are named arguments, then we should highlight the return type and
1977         //    highlight any of the arguments that are also references with that lifetime.
1978         //    If there are no arguments that have the same lifetime as the return type,
1979         //    then don't highlight anything.
1980         // 2. The return type is a reference with an anonymous lifetime. If this is
1981         //    the case, then we can take advantage of (and teach) the lifetime elision
1982         //    rules.
1983         //
1984         //    We know that an error is being reported. So the arguments and return type
1985         //    must satisfy the elision rules. Therefore, if there is a single argument
1986         //    then that means the return type and first (and only) argument have the same
1987         //    lifetime and the borrow isn't meeting that, we can highlight the argument
1988         //    and return type.
1989         //
1990         //    If there are multiple arguments then the first argument must be self (else
1991         //    it would not satisfy the elision rules), so we can highlight self and the
1992         //    return type.
1993         // 3. The return type is not a reference. In this case, we don't highlight
1994         //    anything.
1995         let return_ty = sig.output();
1996         match return_ty.skip_binder().kind {
1997             ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1998                 // This is case 1 from above, return type is a named reference so we need to
1999                 // search for relevant arguments.
2000                 let mut arguments = Vec::new();
2001                 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
2002                     if let ty::Ref(argument_region, _, _) = argument.kind {
2003                         if argument_region == return_region {
2004                             // Need to use the `rustc::ty` types to compare against the
2005                             // `return_region`. Then use the `rustc::hir` type to get only
2006                             // the lifetime span.
2007                             if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
2008                                 // With access to the lifetime, we can get
2009                                 // the span of it.
2010                                 arguments.push((*argument, lifetime.span));
2011                             } else {
2012                                 bug!("ty type is a ref but hir type is not");
2013                             }
2014                         }
2015                     }
2016                 }
2017
2018                 // We need to have arguments. This shouldn't happen, but it's worth checking.
2019                 if arguments.is_empty() {
2020                     return None;
2021                 }
2022
2023                 // We use a mix of the HIR and the Ty types to get information
2024                 // as the HIR doesn't have full types for closure arguments.
2025                 let return_ty = *sig.output().skip_binder();
2026                 let mut return_span = fn_decl.output.span();
2027                 if let hir::FunctionRetTy::Return(ty) = &fn_decl.output {
2028                     if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
2029                         return_span = lifetime.span;
2030                     }
2031                 }
2032
2033                 Some(AnnotatedBorrowFnSignature::NamedFunction {
2034                     arguments,
2035                     return_ty,
2036                     return_span,
2037                 })
2038             }
2039             ty::Ref(_, _, _) if is_closure => {
2040                 // This is case 2 from above but only for closures, return type is anonymous
2041                 // reference so we select
2042                 // the first argument.
2043                 let argument_span = fn_decl.inputs.first()?.span;
2044                 let argument_ty = sig.inputs().skip_binder().first()?;
2045
2046                 // Closure arguments are wrapped in a tuple, so we need to get the first
2047                 // from that.
2048                 if let ty::Tuple(elems) = argument_ty.kind {
2049                     let argument_ty = elems.first()?.expect_ty();
2050                     if let ty::Ref(_, _, _) = argument_ty.kind {
2051                         return Some(AnnotatedBorrowFnSignature::Closure {
2052                             argument_ty,
2053                             argument_span,
2054                         });
2055                     }
2056                 }
2057
2058                 None
2059             }
2060             ty::Ref(_, _, _) => {
2061                 // This is also case 2 from above but for functions, return type is still an
2062                 // anonymous reference so we select the first argument.
2063                 let argument_span = fn_decl.inputs.first()?.span;
2064                 let argument_ty = sig.inputs().skip_binder().first()?;
2065
2066                 let return_span = fn_decl.output.span();
2067                 let return_ty = *sig.output().skip_binder();
2068
2069                 // We expect the first argument to be a reference.
2070                 match argument_ty.kind {
2071                     ty::Ref(_, _, _) => {}
2072                     _ => return None,
2073                 }
2074
2075                 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2076                     argument_ty,
2077                     argument_span,
2078                     return_ty,
2079                     return_span,
2080                 })
2081             }
2082             _ => {
2083                 // This is case 3 from above, return type is not a reference so don't highlight
2084                 // anything.
2085                 None
2086             }
2087         }
2088     }
2089 }
2090
2091 #[derive(Debug)]
2092 enum AnnotatedBorrowFnSignature<'tcx> {
2093     NamedFunction {
2094         arguments: Vec<(Ty<'tcx>, Span)>,
2095         return_ty: Ty<'tcx>,
2096         return_span: Span,
2097     },
2098     AnonymousFunction {
2099         argument_ty: Ty<'tcx>,
2100         argument_span: Span,
2101         return_ty: Ty<'tcx>,
2102         return_span: Span,
2103     },
2104     Closure {
2105         argument_ty: Ty<'tcx>,
2106         argument_span: Span,
2107     },
2108 }
2109
2110 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2111     /// Annotate the provided diagnostic with information about borrow from the fn signature that
2112     /// helps explain.
2113     pub(super) fn emit(
2114         &self,
2115         cx: &mut MirBorrowckCtxt<'_, 'tcx>,
2116         diag: &mut DiagnosticBuilder<'_>,
2117     ) -> String {
2118         match self {
2119             AnnotatedBorrowFnSignature::Closure {
2120                 argument_ty,
2121                 argument_span,
2122             } => {
2123                 diag.span_label(
2124                     *argument_span,
2125                     format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2126                 );
2127
2128                 cx.get_region_name_for_ty(argument_ty, 0)
2129             }
2130             AnnotatedBorrowFnSignature::AnonymousFunction {
2131                 argument_ty,
2132                 argument_span,
2133                 return_ty,
2134                 return_span,
2135             } => {
2136                 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2137                 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2138
2139                 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2140                 let types_equal = return_ty_name == argument_ty_name;
2141                 diag.span_label(
2142                     *return_span,
2143                     format!(
2144                         "{}has type `{}`",
2145                         if types_equal { "also " } else { "" },
2146                         return_ty_name,
2147                     ),
2148                 );
2149
2150                 diag.note(
2151                     "argument and return type have the same lifetime due to lifetime elision rules",
2152                 );
2153                 diag.note(
2154                     "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2155                      lifetime-syntax.html#lifetime-elision>",
2156                 );
2157
2158                 cx.get_region_name_for_ty(return_ty, 0)
2159             }
2160             AnnotatedBorrowFnSignature::NamedFunction {
2161                 arguments,
2162                 return_ty,
2163                 return_span,
2164             } => {
2165                 // Region of return type and arguments checked to be the same earlier.
2166                 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2167                 for (_, argument_span) in arguments {
2168                     diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2169                 }
2170
2171                 diag.span_label(
2172                     *return_span,
2173                     format!("also has lifetime `{}`", region_name,),
2174                 );
2175
2176                 diag.help(&format!(
2177                     "use data from the highlighted arguments which match the `{}` lifetime of \
2178                      the return type",
2179                     region_name,
2180                 ));
2181
2182                 region_name
2183             }
2184         }
2185     }
2186 }