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