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