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