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