]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/conflict_errors.rs
Rollup merge of #66090 - pietroalbini:ci-improvements, r=alexcrichton
[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, LocalKind, Location, Operand, Place, PlaceBase, PlaceRef,
7     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 StorageDeadOrDrop::Destructor(dropped_ty) =
748             self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
749         {
750             // If a borrow of path `B` conflicts with drop of `D` (and
751             // we're not in the uninteresting case where `B` is a
752             // prefix of `D`), then report this as a more interesting
753             // destructor conflict.
754             if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
755                 self.report_borrow_conflicts_with_destructor(
756                     location, borrow, place_span, kind, dropped_ty,
757                 );
758                 return;
759             }
760         }
761
762         let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
763
764         let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
765         let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
766
767         debug!(
768             "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
769             place_desc,
770             explanation
771         );
772         let err = match (place_desc, explanation) {
773             (Some(_), _) if self.is_place_thread_local(root_place) => {
774                 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
775             }
776             // If the outlives constraint comes from inside the closure,
777             // for example:
778             //
779             // let x = 0;
780             // let y = &x;
781             // Box::new(|| y) as Box<Fn() -> &'static i32>
782             //
783             // then just use the normal error. The closure isn't escaping
784             // and `move` will not help here.
785             (
786                 Some(ref name),
787                 BorrowExplanation::MustBeValidFor {
788                     category: category @ ConstraintCategory::Return,
789                     from_closure: false,
790                     ref region_name,
791                     span,
792                     ..
793                 },
794             )
795             | (
796                 Some(ref name),
797                 BorrowExplanation::MustBeValidFor {
798                     category: category @ ConstraintCategory::CallArgument,
799                     from_closure: false,
800                     ref region_name,
801                     span,
802                     ..
803                 },
804             ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
805                 borrow_spans,
806                 borrow_span,
807                 region_name,
808                 category,
809                 span,
810                 &format!("`{}`", name),
811             ),
812             (
813                 Some(ref name),
814                 BorrowExplanation::MustBeValidFor {
815                     category: category @ ConstraintCategory::OpaqueType,
816                     from_closure: false,
817                     ref region_name,
818                     span,
819                     ..
820                 },
821
822             ) if borrow_spans.for_generator() => self.report_escaping_closure_capture(
823                 borrow_spans,
824                 borrow_span,
825                 region_name,
826                 category,
827                 span,
828                 &format!("`{}`", name),
829             ),
830             (
831                 ref name,
832                 BorrowExplanation::MustBeValidFor {
833                     category: ConstraintCategory::Assignment,
834                     from_closure: false,
835                     region_name: RegionName {
836                         source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
837                         ..
838                     },
839                     span,
840                     ..
841                 },
842             ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
843             (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
844                 location,
845                 &name,
846                 &borrow,
847                 drop_span,
848                 borrow_spans,
849                 explanation,
850             ),
851             (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
852                 location,
853                 &borrow,
854                 drop_span,
855                 borrow_spans,
856                 proper_span,
857                 explanation,
858             ),
859         };
860
861         err.buffer(&mut self.errors_buffer);
862     }
863
864     fn report_local_value_does_not_live_long_enough(
865         &mut self,
866         location: Location,
867         name: &str,
868         borrow: &BorrowData<'tcx>,
869         drop_span: Span,
870         borrow_spans: UseSpans,
871         explanation: BorrowExplanation,
872     ) -> DiagnosticBuilder<'cx> {
873         debug!(
874             "report_local_value_does_not_live_long_enough(\
875              {:?}, {:?}, {:?}, {:?}, {:?}\
876              )",
877             location, name, borrow, drop_span, borrow_spans
878         );
879
880         let borrow_span = borrow_spans.var_or_use();
881         if let BorrowExplanation::MustBeValidFor {
882             category,
883             span,
884             ref opt_place_desc,
885             from_closure: false,
886             ..
887         } = explanation {
888             if let Some(diag) = self.try_report_cannot_return_reference_to_local(
889                 borrow,
890                 borrow_span,
891                 span,
892                 category,
893                 opt_place_desc.as_ref(),
894             ) {
895                 return diag;
896             }
897         }
898
899         let mut err = self.path_does_not_live_long_enough(
900             borrow_span,
901             &format!("`{}`", name),
902         );
903
904         if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
905             let region_name = annotation.emit(self, &mut err);
906
907             err.span_label(
908                 borrow_span,
909                 format!("`{}` would have to be valid for `{}`...", name, region_name),
910             );
911
912             if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
913                 err.span_label(
914                     drop_span,
915                     format!(
916                         "...but `{}` will be dropped here, when the function `{}` returns",
917                         name,
918                         self.infcx.tcx.hir().name(fn_hir_id),
919                     ),
920                 );
921
922                 err.note(
923                     "functions cannot return a borrow to data owned within the function's scope, \
924                      functions can only return borrows to data passed as arguments",
925                 );
926                 err.note(
927                     "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
928                      references-and-borrowing.html#dangling-references>",
929                 );
930             } else {
931                 err.span_label(
932                     drop_span,
933                     format!("...but `{}` dropped here while still borrowed", name),
934                 );
935             }
936
937             if let BorrowExplanation::MustBeValidFor { .. } = explanation {
938             } else {
939                 explanation.add_explanation_to_diagnostic(
940                     self.infcx.tcx,
941                     self.body,
942                     &mut err,
943                     "",
944                     None,
945                 );
946             }
947         } else {
948             err.span_label(borrow_span, "borrowed value does not live long enough");
949             err.span_label(
950                 drop_span,
951                 format!("`{}` dropped here while still borrowed", name),
952             );
953
954             let within = if borrow_spans.for_generator() {
955                 " by generator"
956             } else {
957                 ""
958             };
959
960             borrow_spans.args_span_label(
961                 &mut err,
962                 format!("value captured here{}", within),
963             );
964
965             explanation.add_explanation_to_diagnostic(
966                 self.infcx.tcx, self.body, &mut err, "", None);
967         }
968
969         err
970     }
971
972     fn report_borrow_conflicts_with_destructor(
973         &mut self,
974         location: Location,
975         borrow: &BorrowData<'tcx>,
976         (place, drop_span): (&Place<'tcx>, Span),
977         kind: Option<WriteKind>,
978         dropped_ty: Ty<'tcx>,
979     ) {
980         debug!(
981             "report_borrow_conflicts_with_destructor(\
982              {:?}, {:?}, ({:?}, {:?}), {:?}\
983              )",
984             location, borrow, place, drop_span, kind,
985         );
986
987         let borrow_spans = self.retrieve_borrow_spans(borrow);
988         let borrow_span = borrow_spans.var_or_use();
989
990         let mut err = self.cannot_borrow_across_destructor(borrow_span);
991
992         let what_was_dropped = match self.describe_place(place.as_ref()) {
993             Some(name) => format!("`{}`", name),
994             None => String::from("temporary value"),
995         };
996
997         let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
998             Some(borrowed) => format!(
999                 "here, drop of {D} needs exclusive access to `{B}`, \
1000                  because the type `{T}` implements the `Drop` trait",
1001                 D = what_was_dropped,
1002                 T = dropped_ty,
1003                 B = borrowed
1004             ),
1005             None => format!(
1006                 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
1007                 D = what_was_dropped,
1008                 T = dropped_ty
1009             ),
1010         };
1011         err.span_label(drop_span, label);
1012
1013         // Only give this note and suggestion if they could be relevant.
1014         let explanation =
1015             self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
1016         match explanation {
1017             BorrowExplanation::UsedLater { .. }
1018             | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1019                 err.note("consider using a `let` binding to create a longer lived value");
1020             }
1021             _ => {}
1022         }
1023
1024         explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1025
1026         err.buffer(&mut self.errors_buffer);
1027     }
1028
1029     fn report_thread_local_value_does_not_live_long_enough(
1030         &mut self,
1031         drop_span: Span,
1032         borrow_span: Span,
1033     ) -> DiagnosticBuilder<'cx> {
1034         debug!(
1035             "report_thread_local_value_does_not_live_long_enough(\
1036              {:?}, {:?}\
1037              )",
1038             drop_span, borrow_span
1039         );
1040
1041         let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1042
1043         err.span_label(
1044             borrow_span,
1045             "thread-local variables cannot be borrowed beyond the end of the function",
1046         );
1047         err.span_label(drop_span, "end of enclosing function is here");
1048
1049         err
1050     }
1051
1052     fn report_temporary_value_does_not_live_long_enough(
1053         &mut self,
1054         location: Location,
1055         borrow: &BorrowData<'tcx>,
1056         drop_span: Span,
1057         borrow_spans: UseSpans,
1058         proper_span: Span,
1059         explanation: BorrowExplanation,
1060     ) -> DiagnosticBuilder<'cx> {
1061         debug!(
1062             "report_temporary_value_does_not_live_long_enough(\
1063              {:?}, {:?}, {:?}, {:?}\
1064              )",
1065             location, borrow, drop_span, proper_span
1066         );
1067
1068         if let BorrowExplanation::MustBeValidFor {
1069             category,
1070             span,
1071             from_closure: false,
1072             ..
1073         } = explanation {
1074             if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1075                 borrow,
1076                 proper_span,
1077                 span,
1078                 category,
1079                 None,
1080             ) {
1081                 return diag;
1082             }
1083         }
1084
1085         let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1086         err.span_label(
1087             proper_span,
1088             "creates a temporary which is freed while still in use",
1089         );
1090         err.span_label(
1091             drop_span,
1092             "temporary value is freed at the end of this statement",
1093         );
1094
1095         match explanation {
1096             BorrowExplanation::UsedLater(..)
1097             | BorrowExplanation::UsedLaterInLoop(..)
1098             | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1099                 // Only give this note and suggestion if it could be relevant.
1100                 err.note("consider using a `let` binding to create a longer lived value");
1101             }
1102             _ => {}
1103         }
1104         explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1105
1106         let within = if borrow_spans.for_generator() {
1107             " by generator"
1108         } else {
1109             ""
1110         };
1111
1112         borrow_spans.args_span_label(
1113             &mut err,
1114             format!("value captured here{}", within),
1115         );
1116
1117         err
1118     }
1119
1120     fn try_report_cannot_return_reference_to_local(
1121         &self,
1122         borrow: &BorrowData<'tcx>,
1123         borrow_span: Span,
1124         return_span: Span,
1125         category: ConstraintCategory,
1126         opt_place_desc: Option<&String>,
1127     ) -> Option<DiagnosticBuilder<'cx>> {
1128         let return_kind = match category {
1129             ConstraintCategory::Return => "return",
1130             ConstraintCategory::Yield => "yield",
1131             _ => return None,
1132         };
1133
1134         // FIXME use a better heuristic than Spans
1135         let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1136             "reference to"
1137         } else {
1138             "value referencing"
1139         };
1140
1141         let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1142             let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1143                 match self.body.local_kind(local) {
1144                     LocalKind::ReturnPointer
1145                     | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1146                     LocalKind::Var => "local variable ",
1147                     LocalKind::Arg
1148                     if !self.upvars.is_empty()
1149                         && local == Local::new(1) => {
1150                         "variable captured by `move` "
1151                     }
1152                     LocalKind::Arg => {
1153                         "function parameter "
1154                     }
1155                 }
1156             } else {
1157                 "local data "
1158             };
1159             (
1160                 format!("{}`{}`", local_kind, place_desc),
1161                 format!("`{}` is borrowed here", place_desc),
1162             )
1163         } else {
1164             let root_place = self.prefixes(borrow.borrowed_place.as_ref(),
1165                                            PrefixSet::All)
1166                 .last()
1167                 .unwrap();
1168             let local = if let PlaceRef {
1169                 base: PlaceBase::Local(local),
1170                 projection: [],
1171             } = root_place {
1172                 local
1173             } else {
1174                 bug!("try_report_cannot_return_reference_to_local: not a local")
1175             };
1176             match self.body.local_kind(*local) {
1177                 LocalKind::ReturnPointer | LocalKind::Temp => (
1178                     "temporary value".to_string(),
1179                     "temporary value created here".to_string(),
1180                 ),
1181                 LocalKind::Arg => (
1182                     "function parameter".to_string(),
1183                     "function parameter borrowed here".to_string(),
1184                 ),
1185                 LocalKind::Var => (
1186                     "local binding".to_string(),
1187                     "local binding introduced here".to_string(),
1188                 ),
1189             }
1190         };
1191
1192         let mut err = self.cannot_return_reference_to_local(
1193             return_span,
1194             return_kind,
1195             reference_desc,
1196             &place_desc,
1197         );
1198
1199         if return_span != borrow_span {
1200             err.span_label(borrow_span, note);
1201         }
1202
1203         Some(err)
1204     }
1205
1206     fn report_escaping_closure_capture(
1207         &mut self,
1208         use_span: UseSpans,
1209         var_span: Span,
1210         fr_name: &RegionName,
1211         category: ConstraintCategory,
1212         constraint_span: Span,
1213         captured_var: &str,
1214     ) -> DiagnosticBuilder<'cx> {
1215         let tcx = self.infcx.tcx;
1216         let args_span = use_span.args_or_use();
1217         let mut err = self.cannot_capture_in_long_lived_closure(
1218             args_span,
1219             captured_var,
1220             var_span,
1221         );
1222
1223         let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1224             Ok(mut string) => {
1225                 if string.starts_with("async ") {
1226                     string.insert_str(6, "move ");
1227                 } else if string.starts_with("async|") {
1228                     string.insert_str(5, " move");
1229                 } else {
1230                     string.insert_str(0, "move ");
1231                 };
1232                 string
1233             },
1234             Err(_) => "move |<args>| <body>".to_string()
1235         };
1236         let kind = match use_span.generator_kind() {
1237             Some(generator_kind) => match generator_kind {
1238                 GeneratorKind::Async(async_kind) => match async_kind {
1239                     AsyncGeneratorKind::Block => "async block",
1240                     AsyncGeneratorKind::Closure => "async closure",
1241                     _ => bug!("async block/closure expected, but async funtion found."),
1242                 },
1243                 GeneratorKind::Gen => "generator",
1244             }
1245             None => "closure",
1246         };
1247         err.span_suggestion(
1248             args_span,
1249             &format!(
1250                 "to force the {} to take ownership of {} (and any \
1251                  other referenced variables), use the `move` keyword",
1252                  kind,
1253                  captured_var
1254             ),
1255             suggestion,
1256             Applicability::MachineApplicable,
1257         );
1258
1259         match category {
1260             ConstraintCategory::Return => {
1261                 err.span_note(constraint_span, "closure is returned here");
1262             }
1263             ConstraintCategory::OpaqueType => {
1264                 err.span_note(constraint_span, "generator is returned here");
1265             }
1266             ConstraintCategory::CallArgument => {
1267                 fr_name.highlight_region_name(&mut err);
1268                 err.span_note(
1269                     constraint_span,
1270                     &format!("function requires argument type to outlive `{}`", fr_name),
1271                 );
1272             }
1273             _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1274                        category: `{:?}`", category),
1275         }
1276         err
1277     }
1278
1279     fn report_escaping_data(
1280         &mut self,
1281         borrow_span: Span,
1282         name: &Option<String>,
1283         upvar_span: Span,
1284         upvar_name: &str,
1285         escape_span: Span,
1286     ) -> DiagnosticBuilder<'cx> {
1287         let tcx = self.infcx.tcx;
1288
1289         let escapes_from = if tcx.is_closure(self.mir_def_id) {
1290             let tables = tcx.typeck_tables_of(self.mir_def_id);
1291             let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1292             match tables.node_type(mir_hir_id).kind {
1293                 ty::Closure(..) => "closure",
1294                 ty::Generator(..) => "generator",
1295                 _ => bug!("Closure body doesn't have a closure or generator type"),
1296             }
1297         } else {
1298             "function"
1299         };
1300
1301         let mut err = borrowck_errors::borrowed_data_escapes_closure(
1302             tcx,
1303             escape_span,
1304             escapes_from,
1305         );
1306
1307         err.span_label(
1308             upvar_span,
1309             format!(
1310                 "`{}` is declared here, outside of the {} body",
1311                 upvar_name, escapes_from
1312             ),
1313         );
1314
1315         err.span_label(
1316             borrow_span,
1317             format!(
1318                 "borrow is only valid in the {} body",
1319                 escapes_from
1320             ),
1321         );
1322
1323         if let Some(name) = name {
1324             err.span_label(
1325                 escape_span,
1326                 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1327             );
1328         } else {
1329             err.span_label(
1330                 escape_span,
1331                 format!("reference escapes the {} body here", escapes_from),
1332             );
1333         }
1334
1335         err
1336     }
1337
1338     fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1339         let body = self.body;
1340
1341         let mut stack = Vec::new();
1342         stack.extend(body.predecessor_locations(location).map(|predecessor| {
1343             let is_back_edge = location.dominates(predecessor, &self.dominators);
1344             (predecessor, is_back_edge)
1345         }));
1346
1347         let mut visited = FxHashSet::default();
1348         let mut result = vec![];
1349
1350         'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1351             debug!(
1352                 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1353                 location, is_back_edge
1354             );
1355
1356             if !visited.insert(location) {
1357                 continue;
1358             }
1359
1360             // check for moves
1361             let stmt_kind = body[location.block]
1362                 .statements
1363                 .get(location.statement_index)
1364                 .map(|s| &s.kind);
1365             if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1366                 // this analysis only tries to find moves explicitly
1367                 // written by the user, so we ignore the move-outs
1368                 // created by `StorageDead` and at the beginning
1369                 // of a function.
1370             } else {
1371                 // If we are found a use of a.b.c which was in error, then we want to look for
1372                 // moves not only of a.b.c but also a.b and a.
1373                 //
1374                 // Note that the moves data already includes "parent" paths, so we don't have to
1375                 // worry about the other case: that is, if there is a move of a.b.c, it is already
1376                 // marked as a move of a.b and a as well, so we will generate the correct errors
1377                 // there.
1378                 let mut mpis = vec![mpi];
1379                 let move_paths = &self.move_data.move_paths;
1380                 mpis.extend(move_paths[mpi].parents(move_paths));
1381
1382                 for moi in &self.move_data.loc_map[location] {
1383                     debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1384                     if mpis.contains(&self.move_data.moves[*moi].path) {
1385                         debug!("report_use_of_moved_or_uninitialized: found");
1386                         result.push(MoveSite {
1387                             moi: *moi,
1388                             traversed_back_edge: is_back_edge,
1389                         });
1390
1391                         // Strictly speaking, we could continue our DFS here. There may be
1392                         // other moves that can reach the point of error. But it is kind of
1393                         // confusing to highlight them.
1394                         //
1395                         // Example:
1396                         //
1397                         // ```
1398                         // let a = vec![];
1399                         // let b = a;
1400                         // let c = a;
1401                         // drop(a); // <-- current point of error
1402                         // ```
1403                         //
1404                         // Because we stop the DFS here, we only highlight `let c = a`,
1405                         // and not `let b = a`. We will of course also report an error at
1406                         // `let c = a` which highlights `let b = a` as the move.
1407                         continue 'dfs;
1408                     }
1409                 }
1410             }
1411
1412             // check for inits
1413             let mut any_match = false;
1414             drop_flag_effects::for_location_inits(
1415                 self.infcx.tcx,
1416                 self.body,
1417                 self.move_data,
1418                 location,
1419                 |m| {
1420                     if m == mpi {
1421                         any_match = true;
1422                     }
1423                 },
1424             );
1425             if any_match {
1426                 continue 'dfs;
1427             }
1428
1429             stack.extend(body.predecessor_locations(location).map(|predecessor| {
1430                 let back_edge = location.dominates(predecessor, &self.dominators);
1431                 (predecessor, is_back_edge || back_edge)
1432             }));
1433         }
1434
1435         result
1436     }
1437
1438     pub(super) fn report_illegal_mutation_of_borrowed(
1439         &mut self,
1440         location: Location,
1441         (place, span): (&Place<'tcx>, Span),
1442         loan: &BorrowData<'tcx>,
1443     ) {
1444         let loan_spans = self.retrieve_borrow_spans(loan);
1445         let loan_span = loan_spans.args_or_use();
1446
1447         if loan.kind == BorrowKind::Shallow {
1448             if let Some(section) = self.classify_immutable_section(&loan.assigned_place) {
1449                 let mut err = self.cannot_mutate_in_immutable_section(
1450                     span,
1451                     loan_span,
1452                     &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1453                     section,
1454                     "assign",
1455                 );
1456                 loan_spans.var_span_label(
1457                     &mut err,
1458                     format!("borrow occurs due to use{}", loan_spans.describe()),
1459                 );
1460
1461                 err.buffer(&mut self.errors_buffer);
1462
1463                 return;
1464             }
1465         }
1466
1467         let mut err = self.cannot_assign_to_borrowed(
1468             span,
1469             loan_span,
1470             &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1471         );
1472
1473         loan_spans.var_span_label(
1474             &mut err,
1475             format!("borrow occurs due to use{}", loan_spans.describe()),
1476         );
1477
1478         self.explain_why_borrow_contains_point(location, loan, None)
1479             .add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1480
1481         err.buffer(&mut self.errors_buffer);
1482     }
1483
1484     /// Reports an illegal reassignment; for example, an assignment to
1485     /// (part of) a non-`mut` local that occurs potentially after that
1486     /// local has already been initialized. `place` is the path being
1487     /// assigned; `err_place` is a place providing a reason why
1488     /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1489     /// assignment to `x.f`).
1490     pub(super) fn report_illegal_reassignment(
1491         &mut self,
1492         _location: Location,
1493         (place, span): (&Place<'tcx>, Span),
1494         assigned_span: Span,
1495         err_place: &Place<'tcx>,
1496     ) {
1497         let (from_arg, local_decl) = if let Some(local) = err_place.as_local() {
1498             if let LocalKind::Arg = self.body.local_kind(local) {
1499                 (true, Some(&self.body.local_decls[local]))
1500             } else {
1501                 (false, Some(&self.body.local_decls[local]))
1502             }
1503         } else {
1504             (false, None)
1505         };
1506
1507         // If root local is initialized immediately (everything apart from let
1508         // PATTERN;) then make the error refer to that local, rather than the
1509         // place being assigned later.
1510         let (place_description, assigned_span) = match local_decl {
1511             Some(LocalDecl {
1512                 is_user_variable: Some(ClearCrossCrate::Clear),
1513                 ..
1514             })
1515             | Some(LocalDecl {
1516                 is_user_variable:
1517                     Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1518                         opt_match_place: None,
1519                         ..
1520                     }))),
1521                 ..
1522             })
1523             | Some(LocalDecl {
1524                 is_user_variable: None,
1525                 ..
1526             })
1527             | None => (self.describe_place(place.as_ref()), assigned_span),
1528             Some(decl) => (self.describe_place(err_place.as_ref()), decl.source_info.span),
1529         };
1530
1531         let mut err = self.cannot_reassign_immutable(
1532             span,
1533             place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1534             from_arg,
1535         );
1536         let msg = if from_arg {
1537             "cannot assign to immutable argument"
1538         } else {
1539             "cannot assign twice to immutable variable"
1540         };
1541         if span != assigned_span {
1542             if !from_arg {
1543                 let value_msg = match place_description {
1544                     Some(name) => format!("`{}`", name),
1545                     None => "value".to_owned(),
1546                 };
1547                 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1548             }
1549         }
1550         if let Some(decl) = local_decl {
1551             if let Some(name) = decl.name {
1552                 if decl.can_be_made_mutable() {
1553                     err.span_suggestion(
1554                         decl.source_info.span,
1555                         "make this binding mutable",
1556                         format!("mut {}", name),
1557                         Applicability::MachineApplicable,
1558                     );
1559                 }
1560             }
1561         }
1562         err.span_label(span, msg);
1563         err.buffer(&mut self.errors_buffer);
1564     }
1565
1566     fn classify_drop_access_kind(&self, place: PlaceRef<'cx, 'tcx>) -> StorageDeadOrDrop<'tcx> {
1567         let tcx = self.infcx.tcx;
1568         match place.projection {
1569             [] => {
1570                 StorageDeadOrDrop::LocalStorageDead
1571             }
1572             [proj_base @ .., elem] => {
1573                 // FIXME(spastorino) make this iterate
1574                 let base_access = self.classify_drop_access_kind(PlaceRef {
1575                     base: place.base,
1576                     projection: proj_base,
1577                 });
1578                 match elem {
1579                     ProjectionElem::Deref => match base_access {
1580                         StorageDeadOrDrop::LocalStorageDead
1581                         | StorageDeadOrDrop::BoxedStorageDead => {
1582                             assert!(
1583                                 Place::ty_from(&place.base, proj_base, self.body, tcx).ty.is_box(),
1584                                 "Drop of value behind a reference or raw pointer"
1585                             );
1586                             StorageDeadOrDrop::BoxedStorageDead
1587                         }
1588                         StorageDeadOrDrop::Destructor(_) => base_access,
1589                     },
1590                     ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1591                         let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1592                         match base_ty.kind {
1593                             ty::Adt(def, _) if def.has_dtor(tcx) => {
1594                                 // Report the outermost adt with a destructor
1595                                 match base_access {
1596                                     StorageDeadOrDrop::Destructor(_) => base_access,
1597                                     StorageDeadOrDrop::LocalStorageDead
1598                                     | StorageDeadOrDrop::BoxedStorageDead => {
1599                                         StorageDeadOrDrop::Destructor(base_ty)
1600                                     }
1601                                 }
1602                             }
1603                             _ => base_access,
1604                         }
1605                     }
1606
1607                     ProjectionElem::ConstantIndex { .. }
1608                     | ProjectionElem::Subslice { .. }
1609                     | ProjectionElem::Index(_) => base_access,
1610                 }
1611             }
1612         }
1613     }
1614
1615     /// Describe the reason for the fake borrow that was assigned to `place`.
1616     fn classify_immutable_section(&self, place: &Place<'tcx>) -> Option<&'static str> {
1617         use rustc::mir::visit::Visitor;
1618         struct FakeReadCauseFinder<'a, 'tcx> {
1619             place: &'a Place<'tcx>,
1620             cause: Option<FakeReadCause>,
1621         }
1622         impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'_, 'tcx> {
1623             fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1624                 match statement {
1625                     Statement {
1626                         kind: StatementKind::FakeRead(cause, box ref place),
1627                         ..
1628                     } if *place == *self.place => {
1629                         self.cause = Some(*cause);
1630                     }
1631                     _ => (),
1632                 }
1633             }
1634         }
1635         let mut visitor = FakeReadCauseFinder { place, cause: None };
1636         visitor.visit_body(&self.body);
1637         match visitor.cause {
1638             Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1639             Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1640             _ => None,
1641         }
1642     }
1643
1644     /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1645     /// borrow of local value that does not live long enough.
1646     fn annotate_argument_and_return_for_borrow(
1647         &self,
1648         borrow: &BorrowData<'tcx>,
1649     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1650         // Define a fallback for when we can't match a closure.
1651         let fallback = || {
1652             let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1653             if is_closure {
1654                 None
1655             } else {
1656                 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1657                 match ty.kind {
1658                     ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1659                         self.mir_def_id,
1660                         self.infcx.tcx.fn_sig(self.mir_def_id),
1661                     ),
1662                     _ => None,
1663                 }
1664             }
1665         };
1666
1667         // In order to determine whether we need to annotate, we need to check whether the reserve
1668         // place was an assignment into a temporary.
1669         //
1670         // If it was, we check whether or not that temporary is eventually assigned into the return
1671         // place. If it was, we can add annotations about the function's return type and arguments
1672         // and it'll make sense.
1673         let location = borrow.reserve_location;
1674         debug!(
1675             "annotate_argument_and_return_for_borrow: location={:?}",
1676             location
1677         );
1678         if let Some(&Statement { kind: StatementKind::Assign(box(ref reservation, _)), ..})
1679              = &self.body[location.block].statements.get(location.statement_index)
1680         {
1681             debug!(
1682                 "annotate_argument_and_return_for_borrow: reservation={:?}",
1683                 reservation
1684             );
1685             // Check that the initial assignment of the reserve location is into a temporary.
1686             let mut target = match reservation.as_local() {
1687                 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
1688                 _ => return None,
1689             };
1690
1691             // Next, look through the rest of the block, checking if we are assigning the
1692             // `target` (that is, the place that contains our borrow) to anything.
1693             let mut annotated_closure = None;
1694             for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1695                 debug!(
1696                     "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1697                     target, stmt
1698                 );
1699                 if let StatementKind::Assign(box(place, rvalue)) = &stmt.kind {
1700                     if let Some(assigned_to) = place.as_local() {
1701                         debug!(
1702                             "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1703                              rvalue={:?}",
1704                             assigned_to, rvalue
1705                         );
1706                         // Check if our `target` was captured by a closure.
1707                         if let Rvalue::Aggregate(
1708                             box AggregateKind::Closure(def_id, substs),
1709                             operands,
1710                         ) = rvalue
1711                         {
1712                             for operand in operands {
1713                                 let assigned_from = match operand {
1714                                     Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1715                                         assigned_from
1716                                     }
1717                                     _ => continue,
1718                                 };
1719                                 debug!(
1720                                     "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1721                                     assigned_from
1722                                 );
1723
1724                                 // Find the local from the operand.
1725                                 let assigned_from_local = match assigned_from.local_or_deref_local()
1726                                 {
1727                                     Some(local) => local,
1728                                     None => continue,
1729                                 };
1730
1731                                 if assigned_from_local != target {
1732                                     continue;
1733                                 }
1734
1735                                 // If a closure captured our `target` and then assigned
1736                                 // into a place then we should annotate the closure in
1737                                 // case it ends up being assigned into the return place.
1738                                 annotated_closure = self.annotate_fn_sig(
1739                                     *def_id,
1740                                     self.infcx.closure_sig(*def_id, *substs),
1741                                 );
1742                                 debug!(
1743                                     "annotate_argument_and_return_for_borrow: \
1744                                      annotated_closure={:?} assigned_from_local={:?} \
1745                                      assigned_to={:?}",
1746                                     annotated_closure, assigned_from_local, assigned_to
1747                                 );
1748
1749                                 if assigned_to == mir::RETURN_PLACE {
1750                                     // If it was assigned directly into the return place, then
1751                                     // return now.
1752                                     return annotated_closure;
1753                                 } else {
1754                                     // Otherwise, update the target.
1755                                     target = assigned_to;
1756                                 }
1757                             }
1758
1759                             // If none of our closure's operands matched, then skip to the next
1760                             // statement.
1761                             continue;
1762                         }
1763
1764                         // Otherwise, look at other types of assignment.
1765                         let assigned_from = match rvalue {
1766                             Rvalue::Ref(_, _, assigned_from) => assigned_from,
1767                             Rvalue::Use(operand) => match operand {
1768                                 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1769                                     assigned_from
1770                                 }
1771                                 _ => continue,
1772                             },
1773                             _ => continue,
1774                         };
1775                         debug!(
1776                             "annotate_argument_and_return_for_borrow: \
1777                              assigned_from={:?}",
1778                             assigned_from,
1779                         );
1780
1781                         // Find the local from the rvalue.
1782                         let assigned_from_local = match assigned_from.local_or_deref_local() {
1783                             Some(local) => local,
1784                             None => continue,
1785                         };
1786                         debug!(
1787                             "annotate_argument_and_return_for_borrow: \
1788                              assigned_from_local={:?}",
1789                             assigned_from_local,
1790                         );
1791
1792                         // Check if our local matches the target - if so, we've assigned our
1793                         // borrow to a new place.
1794                         if assigned_from_local != target {
1795                             continue;
1796                         }
1797
1798                         // If we assigned our `target` into a new place, then we should
1799                         // check if it was the return place.
1800                         debug!(
1801                             "annotate_argument_and_return_for_borrow: \
1802                              assigned_from_local={:?} assigned_to={:?}",
1803                             assigned_from_local, assigned_to
1804                         );
1805                         if assigned_to == mir::RETURN_PLACE {
1806                             // If it was then return the annotated closure if there was one,
1807                             // else, annotate this function.
1808                             return annotated_closure.or_else(fallback);
1809                         }
1810
1811                         // If we didn't assign into the return place, then we just update
1812                         // the target.
1813                         target = assigned_to;
1814                     }
1815                 }
1816             }
1817
1818             // Check the terminator if we didn't find anything in the statements.
1819             let terminator = &self.body[location.block].terminator();
1820             debug!(
1821                 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1822                 target, terminator
1823             );
1824             if let TerminatorKind::Call {
1825                 destination: Some((place, _)),
1826                 args,
1827                 ..
1828             } = &terminator.kind
1829             {
1830                 if let Some(assigned_to) = place.as_local() {
1831                     debug!(
1832                         "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1833                         assigned_to, args
1834                     );
1835                     for operand in args {
1836                         let assigned_from = match operand {
1837                             Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1838                                 assigned_from
1839                             }
1840                             _ => continue,
1841                         };
1842                         debug!(
1843                             "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1844                             assigned_from,
1845                         );
1846
1847                         if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1848                             debug!(
1849                                 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1850                                 assigned_from_local,
1851                             );
1852
1853                             if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1854                                 return annotated_closure.or_else(fallback);
1855                             }
1856                         }
1857                     }
1858                 }
1859             }
1860         }
1861
1862         // If we haven't found an assignment into the return place, then we need not add
1863         // any annotations.
1864         debug!("annotate_argument_and_return_for_borrow: none found");
1865         None
1866     }
1867
1868     /// Annotate the first argument and return type of a function signature if they are
1869     /// references.
1870     fn annotate_fn_sig(
1871         &self,
1872         did: DefId,
1873         sig: ty::PolyFnSig<'tcx>,
1874     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1875         debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1876         let is_closure = self.infcx.tcx.is_closure(did);
1877         let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
1878         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1879
1880         // We need to work out which arguments to highlight. We do this by looking
1881         // at the return type, where there are three cases:
1882         //
1883         // 1. If there are named arguments, then we should highlight the return type and
1884         //    highlight any of the arguments that are also references with that lifetime.
1885         //    If there are no arguments that have the same lifetime as the return type,
1886         //    then don't highlight anything.
1887         // 2. The return type is a reference with an anonymous lifetime. If this is
1888         //    the case, then we can take advantage of (and teach) the lifetime elision
1889         //    rules.
1890         //
1891         //    We know that an error is being reported. So the arguments and return type
1892         //    must satisfy the elision rules. Therefore, if there is a single argument
1893         //    then that means the return type and first (and only) argument have the same
1894         //    lifetime and the borrow isn't meeting that, we can highlight the argument
1895         //    and return type.
1896         //
1897         //    If there are multiple arguments then the first argument must be self (else
1898         //    it would not satisfy the elision rules), so we can highlight self and the
1899         //    return type.
1900         // 3. The return type is not a reference. In this case, we don't highlight
1901         //    anything.
1902         let return_ty = sig.output();
1903         match return_ty.skip_binder().kind {
1904             ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1905                 // This is case 1 from above, return type is a named reference so we need to
1906                 // search for relevant arguments.
1907                 let mut arguments = Vec::new();
1908                 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1909                     if let ty::Ref(argument_region, _, _) = argument.kind {
1910                         if argument_region == return_region {
1911                             // Need to use the `rustc::ty` types to compare against the
1912                             // `return_region`. Then use the `rustc::hir` type to get only
1913                             // the lifetime span.
1914                             if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
1915                                 // With access to the lifetime, we can get
1916                                 // the span of it.
1917                                 arguments.push((*argument, lifetime.span));
1918                             } else {
1919                                 bug!("ty type is a ref but hir type is not");
1920                             }
1921                         }
1922                     }
1923                 }
1924
1925                 // We need to have arguments. This shouldn't happen, but it's worth checking.
1926                 if arguments.is_empty() {
1927                     return None;
1928                 }
1929
1930                 // We use a mix of the HIR and the Ty types to get information
1931                 // as the HIR doesn't have full types for closure arguments.
1932                 let return_ty = *sig.output().skip_binder();
1933                 let mut return_span = fn_decl.output.span();
1934                 if let hir::FunctionRetTy::Return(ty) = &fn_decl.output {
1935                     if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
1936                         return_span = lifetime.span;
1937                     }
1938                 }
1939
1940                 Some(AnnotatedBorrowFnSignature::NamedFunction {
1941                     arguments,
1942                     return_ty,
1943                     return_span,
1944                 })
1945             }
1946             ty::Ref(_, _, _) if is_closure => {
1947                 // This is case 2 from above but only for closures, return type is anonymous
1948                 // reference so we select
1949                 // the first argument.
1950                 let argument_span = fn_decl.inputs.first()?.span;
1951                 let argument_ty = sig.inputs().skip_binder().first()?;
1952
1953                 // Closure arguments are wrapped in a tuple, so we need to get the first
1954                 // from that.
1955                 if let ty::Tuple(elems) = argument_ty.kind {
1956                     let argument_ty = elems.first()?.expect_ty();
1957                     if let ty::Ref(_, _, _) = argument_ty.kind {
1958                         return Some(AnnotatedBorrowFnSignature::Closure {
1959                             argument_ty,
1960                             argument_span,
1961                         });
1962                     }
1963                 }
1964
1965                 None
1966             }
1967             ty::Ref(_, _, _) => {
1968                 // This is also case 2 from above but for functions, return type is still an
1969                 // anonymous reference so we select the first argument.
1970                 let argument_span = fn_decl.inputs.first()?.span;
1971                 let argument_ty = sig.inputs().skip_binder().first()?;
1972
1973                 let return_span = fn_decl.output.span();
1974                 let return_ty = *sig.output().skip_binder();
1975
1976                 // We expect the first argument to be a reference.
1977                 match argument_ty.kind {
1978                     ty::Ref(_, _, _) => {}
1979                     _ => return None,
1980                 }
1981
1982                 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1983                     argument_ty,
1984                     argument_span,
1985                     return_ty,
1986                     return_span,
1987                 })
1988             }
1989             _ => {
1990                 // This is case 3 from above, return type is not a reference so don't highlight
1991                 // anything.
1992                 None
1993             }
1994         }
1995     }
1996 }
1997
1998 #[derive(Debug)]
1999 enum AnnotatedBorrowFnSignature<'tcx> {
2000     NamedFunction {
2001         arguments: Vec<(Ty<'tcx>, Span)>,
2002         return_ty: Ty<'tcx>,
2003         return_span: Span,
2004     },
2005     AnonymousFunction {
2006         argument_ty: Ty<'tcx>,
2007         argument_span: Span,
2008         return_ty: Ty<'tcx>,
2009         return_span: Span,
2010     },
2011     Closure {
2012         argument_ty: Ty<'tcx>,
2013         argument_span: Span,
2014     },
2015 }
2016
2017 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2018     /// Annotate the provided diagnostic with information about borrow from the fn signature that
2019     /// helps explain.
2020     pub(super) fn emit(
2021         &self,
2022         cx: &mut MirBorrowckCtxt<'_, 'tcx>,
2023         diag: &mut DiagnosticBuilder<'_>,
2024     ) -> String {
2025         match self {
2026             AnnotatedBorrowFnSignature::Closure {
2027                 argument_ty,
2028                 argument_span,
2029             } => {
2030                 diag.span_label(
2031                     *argument_span,
2032                     format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2033                 );
2034
2035                 cx.get_region_name_for_ty(argument_ty, 0)
2036             }
2037             AnnotatedBorrowFnSignature::AnonymousFunction {
2038                 argument_ty,
2039                 argument_span,
2040                 return_ty,
2041                 return_span,
2042             } => {
2043                 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2044                 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2045
2046                 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2047                 let types_equal = return_ty_name == argument_ty_name;
2048                 diag.span_label(
2049                     *return_span,
2050                     format!(
2051                         "{}has type `{}`",
2052                         if types_equal { "also " } else { "" },
2053                         return_ty_name,
2054                     ),
2055                 );
2056
2057                 diag.note(
2058                     "argument and return type have the same lifetime due to lifetime elision rules",
2059                 );
2060                 diag.note(
2061                     "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2062                      lifetime-syntax.html#lifetime-elision>",
2063                 );
2064
2065                 cx.get_region_name_for_ty(return_ty, 0)
2066             }
2067             AnnotatedBorrowFnSignature::NamedFunction {
2068                 arguments,
2069                 return_ty,
2070                 return_span,
2071             } => {
2072                 // Region of return type and arguments checked to be the same earlier.
2073                 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2074                 for (_, argument_span) in arguments {
2075                     diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2076                 }
2077
2078                 diag.span_label(
2079                     *return_span,
2080                     format!("also has lifetime `{}`", region_name,),
2081                 );
2082
2083                 diag.help(&format!(
2084                     "use data from the highlighted arguments which match the `{}` lifetime of \
2085                      the return type",
2086                     region_name,
2087                 ));
2088
2089                 region_name
2090             }
2091         }
2092     }
2093 }