]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/conflict_errors.rs
Simplify SaveHandler trait
[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                     (
1145                         "temporary value".to_string(),
1146                         "temporary value created here".to_string(),
1147                     )
1148                 }
1149                 LocalKind::Arg => {
1150                     (
1151                         "function parameter".to_string(),
1152                         "function parameter borrowed here".to_string(),
1153                     )
1154                 },
1155                 LocalKind::Var => bug!("local variable without a name"),
1156             }
1157         };
1158
1159         let mut err = self.cannot_return_reference_to_local(
1160             return_span,
1161             return_kind,
1162             reference_desc,
1163             &place_desc,
1164         );
1165
1166         if return_span != borrow_span {
1167             err.span_label(borrow_span, note);
1168         }
1169
1170         Some(err)
1171     }
1172
1173     fn report_escaping_closure_capture(
1174         &mut self,
1175         args_span: Span,
1176         var_span: Span,
1177         fr_name: &RegionName,
1178         category: ConstraintCategory,
1179         constraint_span: Span,
1180         captured_var: &str,
1181     ) -> DiagnosticBuilder<'cx> {
1182         let tcx = self.infcx.tcx;
1183
1184         let mut err = self.cannot_capture_in_long_lived_closure(
1185             args_span,
1186             captured_var,
1187             var_span,
1188         );
1189
1190         let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1191             Ok(string) => format!("move {}", string),
1192             Err(_) => "move |<args>| <body>".to_string()
1193         };
1194
1195         err.span_suggestion(
1196             args_span,
1197             &format!("to force the closure to take ownership of {} (and any \
1198                       other referenced variables), use the `move` keyword",
1199                       captured_var),
1200             suggestion,
1201             Applicability::MachineApplicable,
1202         );
1203
1204         match category {
1205             ConstraintCategory::Return => {
1206                 err.span_note(constraint_span, "closure is returned here");
1207             }
1208             ConstraintCategory::CallArgument => {
1209                 fr_name.highlight_region_name(&mut err);
1210                 err.span_note(
1211                     constraint_span,
1212                     &format!("function requires argument type to outlive `{}`", fr_name),
1213                 );
1214             }
1215             _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1216                        category: `{:?}`", category),
1217         }
1218         err
1219     }
1220
1221     fn report_escaping_data(
1222         &mut self,
1223         borrow_span: Span,
1224         name: &Option<String>,
1225         upvar_span: Span,
1226         upvar_name: &str,
1227         escape_span: Span,
1228     ) -> DiagnosticBuilder<'cx> {
1229         let tcx = self.infcx.tcx;
1230
1231         let escapes_from = if tcx.is_closure(self.mir_def_id) {
1232             let tables = tcx.typeck_tables_of(self.mir_def_id);
1233             let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1234             match tables.node_type(mir_hir_id).sty {
1235                 ty::Closure(..) => "closure",
1236                 ty::Generator(..) => "generator",
1237                 _ => bug!("Closure body doesn't have a closure or generator type"),
1238             }
1239         } else {
1240             "function"
1241         };
1242
1243         let mut err = borrowck_errors::borrowed_data_escapes_closure(
1244             tcx,
1245             escape_span,
1246             escapes_from,
1247         );
1248
1249         err.span_label(
1250             upvar_span,
1251             format!(
1252                 "`{}` is declared here, outside of the {} body",
1253                 upvar_name, escapes_from
1254             ),
1255         );
1256
1257         err.span_label(
1258             borrow_span,
1259             format!(
1260                 "borrow is only valid in the {} body",
1261                 escapes_from
1262             ),
1263         );
1264
1265         if let Some(name) = name {
1266             err.span_label(
1267                 escape_span,
1268                 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1269             );
1270         } else {
1271             err.span_label(
1272                 escape_span,
1273                 format!("reference escapes the {} body here", escapes_from),
1274             );
1275         }
1276
1277         err
1278     }
1279
1280     fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1281         let body = self.body;
1282
1283         let mut stack = Vec::new();
1284         stack.extend(body.predecessor_locations(location).map(|predecessor| {
1285             let is_back_edge = location.dominates(predecessor, &self.dominators);
1286             (predecessor, is_back_edge)
1287         }));
1288
1289         let mut visited = FxHashSet::default();
1290         let mut result = vec![];
1291
1292         'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1293             debug!(
1294                 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1295                 location, is_back_edge
1296             );
1297
1298             if !visited.insert(location) {
1299                 continue;
1300             }
1301
1302             // check for moves
1303             let stmt_kind = body[location.block]
1304                 .statements
1305                 .get(location.statement_index)
1306                 .map(|s| &s.kind);
1307             if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1308                 // this analysis only tries to find moves explicitly
1309                 // written by the user, so we ignore the move-outs
1310                 // created by `StorageDead` and at the beginning
1311                 // of a function.
1312             } else {
1313                 // If we are found a use of a.b.c which was in error, then we want to look for
1314                 // moves not only of a.b.c but also a.b and a.
1315                 //
1316                 // Note that the moves data already includes "parent" paths, so we don't have to
1317                 // worry about the other case: that is, if there is a move of a.b.c, it is already
1318                 // marked as a move of a.b and a as well, so we will generate the correct errors
1319                 // there.
1320                 let mut mpis = vec![mpi];
1321                 let move_paths = &self.move_data.move_paths;
1322                 mpis.extend(move_paths[mpi].parents(move_paths));
1323
1324                 for moi in &self.move_data.loc_map[location] {
1325                     debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1326                     if mpis.contains(&self.move_data.moves[*moi].path) {
1327                         debug!("report_use_of_moved_or_uninitialized: found");
1328                         result.push(MoveSite {
1329                             moi: *moi,
1330                             traversed_back_edge: is_back_edge,
1331                         });
1332
1333                         // Strictly speaking, we could continue our DFS here. There may be
1334                         // other moves that can reach the point of error. But it is kind of
1335                         // confusing to highlight them.
1336                         //
1337                         // Example:
1338                         //
1339                         // ```
1340                         // let a = vec![];
1341                         // let b = a;
1342                         // let c = a;
1343                         // drop(a); // <-- current point of error
1344                         // ```
1345                         //
1346                         // Because we stop the DFS here, we only highlight `let c = a`,
1347                         // and not `let b = a`. We will of course also report an error at
1348                         // `let c = a` which highlights `let b = a` as the move.
1349                         continue 'dfs;
1350                     }
1351                 }
1352             }
1353
1354             // check for inits
1355             let mut any_match = false;
1356             drop_flag_effects::for_location_inits(
1357                 self.infcx.tcx,
1358                 self.body,
1359                 self.move_data,
1360                 location,
1361                 |m| {
1362                     if m == mpi {
1363                         any_match = true;
1364                     }
1365                 },
1366             );
1367             if any_match {
1368                 continue 'dfs;
1369             }
1370
1371             stack.extend(body.predecessor_locations(location).map(|predecessor| {
1372                 let back_edge = location.dominates(predecessor, &self.dominators);
1373                 (predecessor, is_back_edge || back_edge)
1374             }));
1375         }
1376
1377         result
1378     }
1379
1380     pub(super) fn report_illegal_mutation_of_borrowed(
1381         &mut self,
1382         location: Location,
1383         (place, span): (&Place<'tcx>, Span),
1384         loan: &BorrowData<'tcx>,
1385     ) {
1386         let loan_spans = self.retrieve_borrow_spans(loan);
1387         let loan_span = loan_spans.args_or_use();
1388
1389         if loan.kind == BorrowKind::Shallow {
1390             let mut err = self.cannot_mutate_in_match_guard(
1391                 span,
1392                 loan_span,
1393                 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1394                 "assign",
1395             );
1396             loan_spans.var_span_label(
1397                 &mut err,
1398                 format!("borrow occurs due to use{}", loan_spans.describe()),
1399             );
1400
1401             err.buffer(&mut self.errors_buffer);
1402
1403             return;
1404         }
1405
1406         let mut err = self.cannot_assign_to_borrowed(
1407             span,
1408             loan_span,
1409             &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1410         );
1411
1412         loan_spans.var_span_label(
1413             &mut err,
1414             format!("borrow occurs due to use{}", loan_spans.describe()),
1415         );
1416
1417         self.explain_why_borrow_contains_point(location, loan, None)
1418             .add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1419
1420         err.buffer(&mut self.errors_buffer);
1421     }
1422
1423     /// Reports an illegal reassignment; for example, an assignment to
1424     /// (part of) a non-`mut` local that occurs potentially after that
1425     /// local has already been initialized. `place` is the path being
1426     /// assigned; `err_place` is a place providing a reason why
1427     /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1428     /// assignment to `x.f`).
1429     pub(super) fn report_illegal_reassignment(
1430         &mut self,
1431         _location: Location,
1432         (place, span): (&Place<'tcx>, Span),
1433         assigned_span: Span,
1434         err_place: &Place<'tcx>,
1435     ) {
1436         let (from_arg, local_decl) = if let Place {
1437             base: PlaceBase::Local(local),
1438             projection: None,
1439         } = *err_place {
1440             if let LocalKind::Arg = self.body.local_kind(local) {
1441                 (true, Some(&self.body.local_decls[local]))
1442             } else {
1443                 (false, Some(&self.body.local_decls[local]))
1444             }
1445         } else {
1446             (false, None)
1447         };
1448
1449         // If root local is initialized immediately (everything apart from let
1450         // PATTERN;) then make the error refer to that local, rather than the
1451         // place being assigned later.
1452         let (place_description, assigned_span) = match local_decl {
1453             Some(LocalDecl {
1454                 is_user_variable: Some(ClearCrossCrate::Clear),
1455                 ..
1456             })
1457             | Some(LocalDecl {
1458                 is_user_variable:
1459                     Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1460                         opt_match_place: None,
1461                         ..
1462                     }))),
1463                 ..
1464             })
1465             | Some(LocalDecl {
1466                 is_user_variable: None,
1467                 ..
1468             })
1469             | None => (self.describe_place(place.as_ref()), assigned_span),
1470             Some(decl) => (self.describe_place(err_place.as_ref()), decl.source_info.span),
1471         };
1472
1473         let mut err = self.cannot_reassign_immutable(
1474             span,
1475             place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1476             from_arg,
1477         );
1478         let msg = if from_arg {
1479             "cannot assign to immutable argument"
1480         } else {
1481             "cannot assign twice to immutable variable"
1482         };
1483         if span != assigned_span {
1484             if !from_arg {
1485                 let value_msg = match place_description {
1486                     Some(name) => format!("`{}`", name),
1487                     None => "value".to_owned(),
1488                 };
1489                 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1490             }
1491         }
1492         if let Some(decl) = local_decl {
1493             if let Some(name) = decl.name {
1494                 if decl.can_be_made_mutable() {
1495                     err.span_suggestion(
1496                         decl.source_info.span,
1497                         "make this binding mutable",
1498                         format!("mut {}", name),
1499                         Applicability::MachineApplicable,
1500                     );
1501                 }
1502             }
1503         }
1504         err.span_label(span, msg);
1505         err.buffer(&mut self.errors_buffer);
1506     }
1507
1508     fn classify_drop_access_kind(&self, place: PlaceRef<'cx, 'tcx>) -> StorageDeadOrDrop<'tcx> {
1509         let tcx = self.infcx.tcx;
1510         match place.projection {
1511             None => {
1512                 StorageDeadOrDrop::LocalStorageDead
1513             }
1514             Some(box Projection { ref base, ref elem }) => {
1515                 let base_access = self.classify_drop_access_kind(PlaceRef {
1516                     base: place.base,
1517                     projection: base,
1518                 });
1519                 match elem {
1520                     ProjectionElem::Deref => match base_access {
1521                         StorageDeadOrDrop::LocalStorageDead
1522                         | StorageDeadOrDrop::BoxedStorageDead => {
1523                             assert!(
1524                                 Place::ty_from(&place.base, base, self.body, tcx).ty.is_box(),
1525                                 "Drop of value behind a reference or raw pointer"
1526                             );
1527                             StorageDeadOrDrop::BoxedStorageDead
1528                         }
1529                         StorageDeadOrDrop::Destructor(_) => base_access,
1530                     },
1531                     ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1532                         let base_ty = Place::ty_from(&place.base, base, self.body, tcx).ty;
1533                         match base_ty.sty {
1534                             ty::Adt(def, _) if def.has_dtor(tcx) => {
1535                                 // Report the outermost adt with a destructor
1536                                 match base_access {
1537                                     StorageDeadOrDrop::Destructor(_) => base_access,
1538                                     StorageDeadOrDrop::LocalStorageDead
1539                                     | StorageDeadOrDrop::BoxedStorageDead => {
1540                                         StorageDeadOrDrop::Destructor(base_ty)
1541                                     }
1542                                 }
1543                             }
1544                             _ => base_access,
1545                         }
1546                     }
1547
1548                     ProjectionElem::ConstantIndex { .. }
1549                     | ProjectionElem::Subslice { .. }
1550                     | ProjectionElem::Index(_) => base_access,
1551                 }
1552             }
1553         }
1554     }
1555
1556     /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1557     /// borrow of local value that does not live long enough.
1558     fn annotate_argument_and_return_for_borrow(
1559         &self,
1560         borrow: &BorrowData<'tcx>,
1561     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1562         // Define a fallback for when we can't match a closure.
1563         let fallback = || {
1564             let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1565             if is_closure {
1566                 None
1567             } else {
1568                 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1569                 match ty.sty {
1570                     ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1571                         self.mir_def_id,
1572                         self.infcx.tcx.fn_sig(self.mir_def_id),
1573                     ),
1574                     _ => None,
1575                 }
1576             }
1577         };
1578
1579         // In order to determine whether we need to annotate, we need to check whether the reserve
1580         // place was an assignment into a temporary.
1581         //
1582         // If it was, we check whether or not that temporary is eventually assigned into the return
1583         // place. If it was, we can add annotations about the function's return type and arguments
1584         // and it'll make sense.
1585         let location = borrow.reserve_location;
1586         debug!(
1587             "annotate_argument_and_return_for_borrow: location={:?}",
1588             location
1589         );
1590         if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1591              = &self.body[location.block].statements.get(location.statement_index)
1592         {
1593             debug!(
1594                 "annotate_argument_and_return_for_borrow: reservation={:?}",
1595                 reservation
1596             );
1597             // Check that the initial assignment of the reserve location is into a temporary.
1598             let mut target = *match reservation {
1599                 Place {
1600                     base: PlaceBase::Local(local),
1601                     projection: None,
1602                 } if self.body.local_kind(*local) == LocalKind::Temp => local,
1603                 _ => return None,
1604             };
1605
1606             // Next, look through the rest of the block, checking if we are assigning the
1607             // `target` (that is, the place that contains our borrow) to anything.
1608             let mut annotated_closure = None;
1609             for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1610                 debug!(
1611                     "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1612                     target, stmt
1613                 );
1614                 if let StatementKind::Assign(
1615                     Place {
1616                         base: PlaceBase::Local(assigned_to),
1617                         projection: None,
1618                     },
1619                     box rvalue
1620                 ) = &stmt.kind {
1621                     debug!(
1622                         "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1623                          rvalue={:?}",
1624                         assigned_to, rvalue
1625                     );
1626                     // Check if our `target` was captured by a closure.
1627                     if let Rvalue::Aggregate(
1628                         box AggregateKind::Closure(def_id, substs),
1629                         operands,
1630                     ) = rvalue
1631                     {
1632                         for operand in operands {
1633                             let assigned_from = match operand {
1634                                 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1635                                     assigned_from
1636                                 }
1637                                 _ => continue,
1638                             };
1639                             debug!(
1640                                 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1641                                 assigned_from
1642                             );
1643
1644                             // Find the local from the operand.
1645                             let assigned_from_local = match assigned_from.local_or_deref_local() {
1646                                 Some(local) => local,
1647                                 None => continue,
1648                             };
1649
1650                             if assigned_from_local != target {
1651                                 continue;
1652                             }
1653
1654                             // If a closure captured our `target` and then assigned
1655                             // into a place then we should annotate the closure in
1656                             // case it ends up being assigned into the return place.
1657                             annotated_closure = self.annotate_fn_sig(
1658                                 *def_id,
1659                                 self.infcx.closure_sig(*def_id, *substs),
1660                             );
1661                             debug!(
1662                                 "annotate_argument_and_return_for_borrow: \
1663                                  annotated_closure={:?} assigned_from_local={:?} \
1664                                  assigned_to={:?}",
1665                                 annotated_closure, assigned_from_local, assigned_to
1666                             );
1667
1668                             if *assigned_to == mir::RETURN_PLACE {
1669                                 // If it was assigned directly into the return place, then
1670                                 // return now.
1671                                 return annotated_closure;
1672                             } else {
1673                                 // Otherwise, update the target.
1674                                 target = *assigned_to;
1675                             }
1676                         }
1677
1678                         // If none of our closure's operands matched, then skip to the next
1679                         // statement.
1680                         continue;
1681                     }
1682
1683                     // Otherwise, look at other types of assignment.
1684                     let assigned_from = match rvalue {
1685                         Rvalue::Ref(_, _, assigned_from) => assigned_from,
1686                         Rvalue::Use(operand) => match operand {
1687                             Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1688                                 assigned_from
1689                             }
1690                             _ => continue,
1691                         },
1692                         _ => continue,
1693                     };
1694                     debug!(
1695                         "annotate_argument_and_return_for_borrow: \
1696                          assigned_from={:?}",
1697                         assigned_from,
1698                     );
1699
1700                     // Find the local from the rvalue.
1701                     let assigned_from_local = match assigned_from.local_or_deref_local() {
1702                         Some(local) => local,
1703                         None => continue,
1704                     };
1705                     debug!(
1706                         "annotate_argument_and_return_for_borrow: \
1707                          assigned_from_local={:?}",
1708                         assigned_from_local,
1709                     );
1710
1711                     // Check if our local matches the target - if so, we've assigned our
1712                     // borrow to a new place.
1713                     if assigned_from_local != target {
1714                         continue;
1715                     }
1716
1717                     // If we assigned our `target` into a new place, then we should
1718                     // check if it was the return place.
1719                     debug!(
1720                         "annotate_argument_and_return_for_borrow: \
1721                          assigned_from_local={:?} assigned_to={:?}",
1722                         assigned_from_local, assigned_to
1723                     );
1724                     if *assigned_to == mir::RETURN_PLACE {
1725                         // If it was then return the annotated closure if there was one,
1726                         // else, annotate this function.
1727                         return annotated_closure.or_else(fallback);
1728                     }
1729
1730                     // If we didn't assign into the return place, then we just update
1731                     // the target.
1732                     target = *assigned_to;
1733                 }
1734             }
1735
1736             // Check the terminator if we didn't find anything in the statements.
1737             let terminator = &self.body[location.block].terminator();
1738             debug!(
1739                 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1740                 target, terminator
1741             );
1742             if let TerminatorKind::Call {
1743                 destination: Some((Place {
1744                     base: PlaceBase::Local(assigned_to),
1745                     projection: None,
1746                 }, _)),
1747                 args,
1748                 ..
1749             } = &terminator.kind
1750             {
1751                 debug!(
1752                     "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1753                     assigned_to, args
1754                 );
1755                 for operand in args {
1756                     let assigned_from = match operand {
1757                         Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1758                             assigned_from
1759                         }
1760                         _ => continue,
1761                     };
1762                     debug!(
1763                         "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1764                         assigned_from,
1765                     );
1766
1767                     if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1768                         debug!(
1769                             "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1770                             assigned_from_local,
1771                         );
1772
1773                         if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1774                             return annotated_closure.or_else(fallback);
1775                         }
1776                     }
1777                 }
1778             }
1779         }
1780
1781         // If we haven't found an assignment into the return place, then we need not add
1782         // any annotations.
1783         debug!("annotate_argument_and_return_for_borrow: none found");
1784         None
1785     }
1786
1787     /// Annotate the first argument and return type of a function signature if they are
1788     /// references.
1789     fn annotate_fn_sig(
1790         &self,
1791         did: DefId,
1792         sig: ty::PolyFnSig<'tcx>,
1793     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1794         debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1795         let is_closure = self.infcx.tcx.is_closure(did);
1796         let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
1797         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1798
1799         // We need to work out which arguments to highlight. We do this by looking
1800         // at the return type, where there are three cases:
1801         //
1802         // 1. If there are named arguments, then we should highlight the return type and
1803         //    highlight any of the arguments that are also references with that lifetime.
1804         //    If there are no arguments that have the same lifetime as the return type,
1805         //    then don't highlight anything.
1806         // 2. The return type is a reference with an anonymous lifetime. If this is
1807         //    the case, then we can take advantage of (and teach) the lifetime elision
1808         //    rules.
1809         //
1810         //    We know that an error is being reported. So the arguments and return type
1811         //    must satisfy the elision rules. Therefore, if there is a single argument
1812         //    then that means the return type and first (and only) argument have the same
1813         //    lifetime and the borrow isn't meeting that, we can highlight the argument
1814         //    and return type.
1815         //
1816         //    If there are multiple arguments then the first argument must be self (else
1817         //    it would not satisfy the elision rules), so we can highlight self and the
1818         //    return type.
1819         // 3. The return type is not a reference. In this case, we don't highlight
1820         //    anything.
1821         let return_ty = sig.output();
1822         match return_ty.skip_binder().sty {
1823             ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1824                 // This is case 1 from above, return type is a named reference so we need to
1825                 // search for relevant arguments.
1826                 let mut arguments = Vec::new();
1827                 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1828                     if let ty::Ref(argument_region, _, _) = argument.sty {
1829                         if argument_region == return_region {
1830                             // Need to use the `rustc::ty` types to compare against the
1831                             // `return_region`. Then use the `rustc::hir` type to get only
1832                             // the lifetime span.
1833                             if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
1834                                 // With access to the lifetime, we can get
1835                                 // the span of it.
1836                                 arguments.push((*argument, lifetime.span));
1837                             } else {
1838                                 bug!("ty type is a ref but hir type is not");
1839                             }
1840                         }
1841                     }
1842                 }
1843
1844                 // We need to have arguments. This shouldn't happen, but it's worth checking.
1845                 if arguments.is_empty() {
1846                     return None;
1847                 }
1848
1849                 // We use a mix of the HIR and the Ty types to get information
1850                 // as the HIR doesn't have full types for closure arguments.
1851                 let return_ty = *sig.output().skip_binder();
1852                 let mut return_span = fn_decl.output.span();
1853                 if let hir::FunctionRetTy::Return(ty) = &fn_decl.output {
1854                     if let hir::TyKind::Rptr(lifetime, _) = ty.node {
1855                         return_span = lifetime.span;
1856                     }
1857                 }
1858
1859                 Some(AnnotatedBorrowFnSignature::NamedFunction {
1860                     arguments,
1861                     return_ty,
1862                     return_span,
1863                 })
1864             }
1865             ty::Ref(_, _, _) if is_closure => {
1866                 // This is case 2 from above but only for closures, return type is anonymous
1867                 // reference so we select
1868                 // the first argument.
1869                 let argument_span = fn_decl.inputs.first()?.span;
1870                 let argument_ty = sig.inputs().skip_binder().first()?;
1871
1872                 // Closure arguments are wrapped in a tuple, so we need to get the first
1873                 // from that.
1874                 if let ty::Tuple(elems) = argument_ty.sty {
1875                     let argument_ty = elems.first()?.expect_ty();
1876                     if let ty::Ref(_, _, _) = argument_ty.sty {
1877                         return Some(AnnotatedBorrowFnSignature::Closure {
1878                             argument_ty,
1879                             argument_span,
1880                         });
1881                     }
1882                 }
1883
1884                 None
1885             }
1886             ty::Ref(_, _, _) => {
1887                 // This is also case 2 from above but for functions, return type is still an
1888                 // anonymous reference so we select the first argument.
1889                 let argument_span = fn_decl.inputs.first()?.span;
1890                 let argument_ty = sig.inputs().skip_binder().first()?;
1891
1892                 let return_span = fn_decl.output.span();
1893                 let return_ty = *sig.output().skip_binder();
1894
1895                 // We expect the first argument to be a reference.
1896                 match argument_ty.sty {
1897                     ty::Ref(_, _, _) => {}
1898                     _ => return None,
1899                 }
1900
1901                 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1902                     argument_ty,
1903                     argument_span,
1904                     return_ty,
1905                     return_span,
1906                 })
1907             }
1908             _ => {
1909                 // This is case 3 from above, return type is not a reference so don't highlight
1910                 // anything.
1911                 None
1912             }
1913         }
1914     }
1915 }
1916
1917 #[derive(Debug)]
1918 enum AnnotatedBorrowFnSignature<'tcx> {
1919     NamedFunction {
1920         arguments: Vec<(Ty<'tcx>, Span)>,
1921         return_ty: Ty<'tcx>,
1922         return_span: Span,
1923     },
1924     AnonymousFunction {
1925         argument_ty: Ty<'tcx>,
1926         argument_span: Span,
1927         return_ty: Ty<'tcx>,
1928         return_span: Span,
1929     },
1930     Closure {
1931         argument_ty: Ty<'tcx>,
1932         argument_span: Span,
1933     },
1934 }
1935
1936 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
1937     /// Annotate the provided diagnostic with information about borrow from the fn signature that
1938     /// helps explain.
1939     pub(super) fn emit(
1940         &self,
1941         cx: &mut MirBorrowckCtxt<'_, 'tcx>,
1942         diag: &mut DiagnosticBuilder<'_>,
1943     ) -> String {
1944         match self {
1945             AnnotatedBorrowFnSignature::Closure {
1946                 argument_ty,
1947                 argument_span,
1948             } => {
1949                 diag.span_label(
1950                     *argument_span,
1951                     format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
1952                 );
1953
1954                 cx.get_region_name_for_ty(argument_ty, 0)
1955             }
1956             AnnotatedBorrowFnSignature::AnonymousFunction {
1957                 argument_ty,
1958                 argument_span,
1959                 return_ty,
1960                 return_span,
1961             } => {
1962                 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
1963                 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
1964
1965                 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
1966                 let types_equal = return_ty_name == argument_ty_name;
1967                 diag.span_label(
1968                     *return_span,
1969                     format!(
1970                         "{}has type `{}`",
1971                         if types_equal { "also " } else { "" },
1972                         return_ty_name,
1973                     ),
1974                 );
1975
1976                 diag.note(
1977                     "argument and return type have the same lifetime due to lifetime elision rules",
1978                 );
1979                 diag.note(
1980                     "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
1981                      lifetime-syntax.html#lifetime-elision>",
1982                 );
1983
1984                 cx.get_region_name_for_ty(return_ty, 0)
1985             }
1986             AnnotatedBorrowFnSignature::NamedFunction {
1987                 arguments,
1988                 return_ty,
1989                 return_span,
1990             } => {
1991                 // Region of return type and arguments checked to be the same earlier.
1992                 let region_name = cx.get_region_name_for_ty(return_ty, 0);
1993                 for (_, argument_span) in arguments {
1994                     diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
1995                 }
1996
1997                 diag.span_label(
1998                     *return_span,
1999                     format!("also has lifetime `{}`", region_name,),
2000                 );
2001
2002                 diag.help(&format!(
2003                     "use data from the highlighted arguments which match the `{}` lifetime of \
2004                      the return type",
2005                     region_name,
2006                 ));
2007
2008                 region_name
2009             }
2010         }
2011     }
2012 }