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