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