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