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