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