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