]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/error_reporting.rs
Auto merge of #60272 - Jakst:patch-1, r=Manishearth
[rust.git] / src / librustc_mir / borrow_check / error_reporting.rs
1 use crate::borrow_check::nll::explain_borrow::BorrowExplanation;
2 use crate::borrow_check::nll::region_infer::{RegionName, RegionNameSource};
3 use crate::borrow_check::prefixes::IsPrefixOf;
4 use crate::borrow_check::WriteKind;
5 use rustc::hir;
6 use rustc::hir::def::Namespace;
7 use rustc::hir::def_id::DefId;
8 use rustc::middle::region::ScopeTree;
9 use rustc::mir::{
10     self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, Constant,
11     ConstraintCategory, Field, Local, LocalDecl, LocalKind, Location, Operand,
12     Place, PlaceBase, PlaceProjection, ProjectionElem, Rvalue, Statement, StatementKind,
13     Static, StaticKind, TerminatorKind, VarBindingForm,
14 };
15 use rustc::ty::{self, DefIdTree, Ty};
16 use rustc::ty::layout::VariantIdx;
17 use rustc::ty::print::Print;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_data_structures::indexed_vec::Idx;
20 use rustc_errors::{Applicability, DiagnosticBuilder};
21 use syntax_pos::Span;
22 use syntax::source_map::CompilerDesugaringKind;
23 use syntax::symbol::sym;
24
25 use super::borrow_set::BorrowData;
26 use super::{MirBorrowckCtxt};
27 use super::{InitializationRequiringAction, PrefixSet};
28 use crate::dataflow::drop_flag_effects;
29 use crate::dataflow::indexes::{MovePathIndex, MoveOutIndex};
30 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
31
32 #[derive(Debug)]
33 struct MoveSite {
34     /// Index of the "move out" that we found. The `MoveData` can
35     /// then tell us where the move occurred.
36     moi: MoveOutIndex,
37
38     /// `true` if we traversed a back edge while walking from the point
39     /// of error to the move site.
40     traversed_back_edge: bool
41 }
42
43 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
44     pub(super) fn report_use_of_moved_or_uninitialized(
45         &mut self,
46         location: Location,
47         desired_action: InitializationRequiringAction,
48         (moved_place, used_place, span): (&Place<'tcx>, &Place<'tcx>, Span),
49         mpi: MovePathIndex,
50     ) {
51         debug!(
52             "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
53              moved_place={:?} used_place={:?} span={:?} mpi={:?}",
54             location, desired_action, moved_place, used_place, span, mpi
55         );
56
57         let use_spans = self.move_spans(moved_place, location)
58             .or_else(|| self.borrow_spans(span, location));
59         let span = use_spans.args_or_use();
60
61         let move_site_vec = self.get_moved_indexes(location, mpi);
62         debug!(
63             "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
64             move_site_vec
65         );
66         let move_out_indices: Vec<_> = move_site_vec
67             .iter()
68             .map(|move_site| move_site.moi)
69             .collect();
70
71         if move_out_indices.is_empty() {
72             let root_place = self.prefixes(&used_place, PrefixSet::All).last().unwrap();
73
74             if self.uninitialized_error_reported.contains(root_place) {
75                 debug!(
76                     "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
77                     root_place
78                 );
79                 return;
80             }
81
82             self.uninitialized_error_reported.insert(root_place.clone());
83
84             let item_msg = match self.describe_place_with_options(used_place,
85                                                                   IncludingDowncast(true)) {
86                 Some(name) => format!("`{}`", name),
87                 None => "value".to_owned(),
88             };
89             let mut err = self.infcx.tcx.cannot_act_on_uninitialized_variable(
90                 span,
91                 desired_action.as_noun(),
92                 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
93                     .unwrap_or_else(|| "_".to_owned()),
94                 Origin::Mir,
95             );
96             err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
97
98             use_spans.var_span_label(
99                 &mut err,
100                 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
101             );
102
103             err.buffer(&mut self.errors_buffer);
104         } else {
105             if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
106                 if self.prefixes(&reported_place, PrefixSet::All)
107                     .any(|p| p == used_place)
108                 {
109                     debug!(
110                         "report_use_of_moved_or_uninitialized place: error suppressed \
111                          mois={:?}",
112                         move_out_indices
113                     );
114                     return;
115                 }
116             }
117
118             let msg = ""; //FIXME: add "partially " or "collaterally "
119
120             let mut err = self.infcx.tcx.cannot_act_on_moved_value(
121                 span,
122                 desired_action.as_noun(),
123                 msg,
124                 self.describe_place_with_options(&moved_place, IncludingDowncast(true)),
125                 Origin::Mir,
126             );
127
128             self.add_moved_or_invoked_closure_note(
129                 location,
130                 used_place,
131                 &mut err,
132             );
133
134             let mut is_loop_move = false;
135             let is_partial_move = move_site_vec.iter().any(|move_site| {
136                 let move_out = self.move_data.moves[(*move_site).moi];
137                 let moved_place = &self.move_data.move_paths[move_out.path].place;
138                 used_place != moved_place && used_place.is_prefix_of(moved_place)
139             });
140             for move_site in &move_site_vec {
141                 let move_out = self.move_data.moves[(*move_site).moi];
142                 let moved_place = &self.move_data.move_paths[move_out.path].place;
143
144                 let move_spans = self.move_spans(moved_place, move_out.source);
145                 let move_span = move_spans.args_or_use();
146
147                 let move_msg = if move_spans.for_closure() {
148                     " into closure"
149                 } else {
150                     ""
151                 };
152
153                 if span == move_span {
154                     err.span_label(
155                         span,
156                         format!("value moved{} here, in previous iteration of loop", move_msg),
157                     );
158                     if Some(CompilerDesugaringKind::ForLoop) == span.compiler_desugaring_kind() {
159                         if let Ok(snippet) = self.infcx.tcx.sess.source_map()
160                             .span_to_snippet(span)
161                         {
162                             err.span_suggestion(
163                                 move_span,
164                                 "consider borrowing this to avoid moving it into the for loop",
165                                 format!("&{}", snippet),
166                                 Applicability::MaybeIncorrect,
167                             );
168                         }
169                     }
170                     is_loop_move = true;
171                 } else if move_site.traversed_back_edge {
172                     err.span_label(
173                         move_span,
174                         format!(
175                             "value moved{} here, in previous iteration of loop",
176                             move_msg
177                         ),
178                     );
179                 } else {
180                     err.span_label(move_span, format!("value moved{} here", move_msg));
181                     move_spans.var_span_label(
182                         &mut err,
183                         format!("variable moved due to use{}", move_spans.describe()),
184                     );
185                 };
186             }
187
188             use_spans.var_span_label(
189                 &mut err,
190                 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
191             );
192
193             if !is_loop_move {
194                 err.span_label(
195                     span,
196                     format!(
197                         "value {} here {}",
198                         desired_action.as_verb_in_past_tense(),
199                         if is_partial_move { "after partial move" } else { "after move" },
200                     ),
201                 );
202             }
203
204             let ty = used_place.ty(self.mir, self.infcx.tcx).ty;
205             let needs_note = match ty.sty {
206                 ty::Closure(id, _) => {
207                     let tables = self.infcx.tcx.typeck_tables_of(id);
208                     let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
209
210                     tables.closure_kind_origins().get(hir_id).is_none()
211                 }
212                 _ => true,
213             };
214
215             if needs_note {
216                 let mpi = self.move_data.moves[move_out_indices[0]].path;
217                 let place = &self.move_data.move_paths[mpi].place;
218
219                 let ty = place.ty(self.mir, self.infcx.tcx).ty;
220                 let opt_name = self.describe_place_with_options(place, IncludingDowncast(true));
221                 let note_msg = match opt_name {
222                     Some(ref name) => format!("`{}`", name),
223                     None => "value".to_owned(),
224                 };
225                 if let ty::Param(param_ty) = ty.sty {
226                     let tcx = self.infcx.tcx;
227                     let generics = tcx.generics_of(self.mir_def_id);
228                     let def_id = generics.type_param(&param_ty, tcx).def_id;
229                     if let Some(sp) = tcx.hir().span_if_local(def_id) {
230                         err.span_label(
231                             sp,
232                             "consider adding a `Copy` constraint to this type argument",
233                         );
234                     }
235                 }
236                 if let Place::Base(PlaceBase::Local(local)) = place {
237                     let decl = &self.mir.local_decls[*local];
238                     err.span_label(
239                         decl.source_info.span,
240                         format!(
241                             "move occurs because {} has type `{}`, \
242                                 which does not implement the `Copy` trait",
243                             note_msg, ty,
244                     ));
245                 } else {
246                     err.note(&format!(
247                         "move occurs because {} has type `{}`, \
248                          which does not implement the `Copy` trait",
249                         note_msg, ty
250                     ));
251                 }
252             }
253
254             if let Some((_, mut old_err)) = self.move_error_reported
255                 .insert(move_out_indices, (used_place.clone(), err))
256             {
257                 // Cancel the old error so it doesn't ICE.
258                 old_err.cancel();
259             }
260         }
261     }
262
263     pub(super) fn report_move_out_while_borrowed(
264         &mut self,
265         location: Location,
266         (place, span): (&Place<'tcx>, Span),
267         borrow: &BorrowData<'tcx>,
268     ) {
269         debug!(
270             "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
271             location, place, span, borrow
272         );
273         let tcx = self.infcx.tcx;
274         let value_msg = match self.describe_place(place) {
275             Some(name) => format!("`{}`", name),
276             None => "value".to_owned(),
277         };
278         let borrow_msg = match self.describe_place(&borrow.borrowed_place) {
279             Some(name) => format!("`{}`", name),
280             None => "value".to_owned(),
281         };
282
283         let borrow_spans = self.retrieve_borrow_spans(borrow);
284         let borrow_span = borrow_spans.args_or_use();
285
286         let move_spans = self.move_spans(place, location);
287         let span = move_spans.args_or_use();
288
289         let mut err = tcx.cannot_move_when_borrowed(
290             span,
291             &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
292             Origin::Mir,
293         );
294         err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
295         err.span_label(span, format!("move out of {} occurs here", value_msg));
296
297         borrow_spans.var_span_label(
298             &mut err,
299             format!("borrow occurs due to use{}", borrow_spans.describe())
300         );
301
302         move_spans.var_span_label(
303             &mut err,
304             format!("move occurs due to use{}", move_spans.describe())
305         );
306
307         self.explain_why_borrow_contains_point(
308             location,
309             borrow,
310             None,
311         ).add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", Some(borrow_span));
312         err.buffer(&mut self.errors_buffer);
313     }
314
315     pub(super) fn report_use_while_mutably_borrowed(
316         &mut self,
317         location: Location,
318         (place, _span): (&Place<'tcx>, Span),
319         borrow: &BorrowData<'tcx>,
320     ) -> DiagnosticBuilder<'cx> {
321         let tcx = self.infcx.tcx;
322
323         let borrow_spans = self.retrieve_borrow_spans(borrow);
324         let borrow_span = borrow_spans.args_or_use();
325
326         // Conflicting borrows are reported separately, so only check for move
327         // captures.
328         let use_spans = self.move_spans(place, location);
329         let span = use_spans.var_or_use();
330
331         let mut err = tcx.cannot_use_when_mutably_borrowed(
332             span,
333             &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
334             borrow_span,
335             &self.describe_place(&borrow.borrowed_place)
336                 .unwrap_or_else(|| "_".to_owned()),
337             Origin::Mir,
338         );
339
340         borrow_spans.var_span_label(&mut err, {
341             let place = &borrow.borrowed_place;
342             let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
343
344             format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
345         });
346
347         self.explain_why_borrow_contains_point(location, borrow, None)
348             .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
349         err
350     }
351
352     pub(super) fn report_conflicting_borrow(
353         &mut self,
354         location: Location,
355         (place, span): (&Place<'tcx>, Span),
356         gen_borrow_kind: BorrowKind,
357         issued_borrow: &BorrowData<'tcx>,
358     ) -> DiagnosticBuilder<'cx> {
359         let issued_spans = self.retrieve_borrow_spans(issued_borrow);
360         let issued_span = issued_spans.args_or_use();
361
362         let borrow_spans = self.borrow_spans(span, location);
363         let span = borrow_spans.args_or_use();
364
365         let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
366             "generator"
367         } else {
368             "closure"
369         };
370
371         let (desc_place, msg_place, msg_borrow, union_type_name) =
372             self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
373
374         let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
375         let second_borrow_desc = if explanation.is_explained() {
376             "second "
377         } else {
378             ""
379         };
380
381         // FIXME: supply non-"" `opt_via` when appropriate
382         let tcx = self.infcx.tcx;
383         let first_borrow_desc;
384         let mut err = match (
385             gen_borrow_kind,
386             "immutable",
387             "mutable",
388             issued_borrow.kind,
389             "immutable",
390             "mutable",
391         ) {
392             (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
393                 first_borrow_desc = "mutable ";
394                 tcx.cannot_reborrow_already_borrowed(
395                     span,
396                     &desc_place,
397                     &msg_place,
398                     lft,
399                     issued_span,
400                     "it",
401                     rgt,
402                     &msg_borrow,
403                     None,
404                     Origin::Mir,
405                 )
406             }
407             (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
408                 first_borrow_desc = "immutable ";
409                 tcx.cannot_reborrow_already_borrowed(
410                     span,
411                     &desc_place,
412                     &msg_place,
413                     lft,
414                     issued_span,
415                     "it",
416                     rgt,
417                     &msg_borrow,
418                     None,
419                     Origin::Mir,
420                 )
421             }
422
423             (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
424                 first_borrow_desc = "first ";
425                 tcx.cannot_mutably_borrow_multiply(
426                     span,
427                     &desc_place,
428                     &msg_place,
429                     issued_span,
430                     &msg_borrow,
431                     None,
432                     Origin::Mir,
433                 )
434             }
435
436             (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
437                 first_borrow_desc = "first ";
438                 tcx.cannot_uniquely_borrow_by_two_closures(
439                     span,
440                     &desc_place,
441                     issued_span,
442                     None,
443                     Origin::Mir,
444                 )
445             }
446
447             (BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
448             | (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
449                 let mut err = tcx.cannot_mutate_in_match_guard(
450                     span,
451                     issued_span,
452                     &desc_place,
453                     "mutably borrow",
454                     Origin::Mir,
455                 );
456                 borrow_spans.var_span_label(
457                     &mut err,
458                     format!(
459                         "borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe()
460                     ),
461                 );
462
463                 return err;
464             }
465
466             (BorrowKind::Unique, _, _, _, _, _) => {
467                 first_borrow_desc = "first ";
468                 tcx.cannot_uniquely_borrow_by_one_closure(
469                     span,
470                     container_name,
471                     &desc_place,
472                     "",
473                     issued_span,
474                     "it",
475                     "",
476                     None,
477                     Origin::Mir,
478                 )
479             },
480
481             (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
482                 first_borrow_desc = "first ";
483                 tcx.cannot_reborrow_already_uniquely_borrowed(
484                     span,
485                     container_name,
486                     &desc_place,
487                     "",
488                     lft,
489                     issued_span,
490                     "",
491                     None,
492                     second_borrow_desc,
493                     Origin::Mir,
494                 )
495             }
496
497             (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
498                 first_borrow_desc = "first ";
499                 tcx.cannot_reborrow_already_uniquely_borrowed(
500                     span,
501                     container_name,
502                     &desc_place,
503                     "",
504                     lft,
505                     issued_span,
506                     "",
507                     None,
508                     second_borrow_desc,
509                     Origin::Mir,
510                 )
511             }
512
513             (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
514             | (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
515             | (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _)
516             | (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
517             | (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
518             | (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
519         };
520
521         if issued_spans == borrow_spans {
522             borrow_spans.var_span_label(
523                 &mut err,
524                 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
525             );
526         } else {
527             let borrow_place = &issued_borrow.borrowed_place;
528             let borrow_place_desc = self.describe_place(borrow_place)
529                                         .unwrap_or_else(|| "_".to_owned());
530             issued_spans.var_span_label(
531                 &mut err,
532                 format!(
533                     "first borrow occurs due to use of `{}`{}",
534                     borrow_place_desc,
535                     issued_spans.describe(),
536                 ),
537             );
538
539             borrow_spans.var_span_label(
540                 &mut err,
541                 format!(
542                     "second borrow occurs due to use of `{}`{}",
543                     desc_place,
544                     borrow_spans.describe(),
545                 ),
546             );
547         }
548
549         if union_type_name != "" {
550             err.note(&format!(
551                 "`{}` is a field of the union `{}`, so it overlaps the field `{}`",
552                 msg_place, union_type_name, msg_borrow,
553             ));
554         }
555
556         explanation.add_explanation_to_diagnostic(
557             self.infcx.tcx,
558             self.mir,
559             &mut err,
560             first_borrow_desc,
561             None,
562         );
563
564         err
565     }
566
567     /// Returns the description of the root place for a conflicting borrow and the full
568     /// descriptions of the places that caused the conflict.
569     ///
570     /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
571     /// attempted while a shared borrow is live, then this function will return:
572     ///
573     ///     ("x", "", "")
574     ///
575     /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
576     /// a shared borrow of another field `x.y`, then this function will return:
577     ///
578     ///     ("x", "x.z", "x.y")
579     ///
580     /// In the more complex union case, where the union is a field of a struct, then if a mutable
581     /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
582     /// another field `x.u.y`, then this function will return:
583     ///
584     ///     ("x.u", "x.u.z", "x.u.y")
585     ///
586     /// This is used when creating error messages like below:
587     ///
588     /// >  cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
589     /// >  mutable (via `a.u.s.b`) [E0502]
590     pub(super) fn describe_place_for_conflicting_borrow(
591         &self,
592         first_borrowed_place: &Place<'tcx>,
593         second_borrowed_place: &Place<'tcx>,
594     ) -> (String, String, String, String) {
595         // Define a small closure that we can use to check if the type of a place
596         // is a union.
597         let is_union = |place: &Place<'tcx>| -> bool {
598             place.ty(self.mir, self.infcx.tcx).ty
599                 .ty_adt_def()
600                 .map(|adt| adt.is_union())
601                 .unwrap_or(false)
602         };
603
604         // Start with an empty tuple, so we can use the functions on `Option` to reduce some
605         // code duplication (particularly around returning an empty description in the failure
606         // case).
607         Some(())
608             .filter(|_| {
609                 // If we have a conflicting borrow of the same place, then we don't want to add
610                 // an extraneous "via x.y" to our diagnostics, so filter out this case.
611                 first_borrowed_place != second_borrowed_place
612             })
613             .and_then(|_| {
614                 // We're going to want to traverse the first borrowed place to see if we can find
615                 // field access to a union. If we find that, then we will keep the place of the
616                 // union being accessed and the field that was being accessed so we can check the
617                 // second borrowed place for the same union and a access to a different field.
618                 let mut current = first_borrowed_place;
619                 while let Place::Projection(box PlaceProjection { base, elem }) = current {
620                     match elem {
621                         ProjectionElem::Field(field, _) if is_union(base) => {
622                             return Some((base, field));
623                         },
624                         _ => current = base,
625                     }
626                 }
627                 None
628             })
629             .and_then(|(target_base, target_field)| {
630                 // With the place of a union and a field access into it, we traverse the second
631                 // borrowed place and look for a access to a different field of the same union.
632                 let mut current = second_borrowed_place;
633                 while let Place::Projection(box PlaceProjection { base, elem }) = current {
634                     match elem {
635                         ProjectionElem::Field(field, _) if {
636                             is_union(base) && field != target_field && base == target_base
637                         } => {
638                             let desc_base = self.describe_place(base)
639                                 .unwrap_or_else(|| "_".to_owned());
640                             let desc_first = self.describe_place(first_borrowed_place)
641                                 .unwrap_or_else(|| "_".to_owned());
642                             let desc_second = self.describe_place(second_borrowed_place)
643                                 .unwrap_or_else(|| "_".to_owned());
644
645                             // Also compute the name of the union type, eg. `Foo` so we
646                             // can add a helpful note with it.
647                             let ty = base.ty(self.mir, self.infcx.tcx).ty;
648
649                             return Some((desc_base, desc_first, desc_second, ty.to_string()));
650                         },
651                         _ => current = base,
652                     }
653                 }
654                 None
655             })
656             .unwrap_or_else(|| {
657                 // If we didn't find a field access into a union, or both places match, then
658                 // only return the description of the first place.
659                 let desc_place = self.describe_place(first_borrowed_place)
660                     .unwrap_or_else(|| "_".to_owned());
661                 (desc_place, "".to_string(), "".to_string(), "".to_string())
662             })
663     }
664
665     /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
666     ///
667     /// This means that some data referenced by `borrow` needs to live
668     /// past the point where the StorageDeadOrDrop of `place` occurs.
669     /// This is usually interpreted as meaning that `place` has too
670     /// short a lifetime. (But sometimes it is more useful to report
671     /// it as a more direct conflict between the execution of a
672     /// `Drop::drop` with an aliasing borrow.)
673     pub(super) fn report_borrowed_value_does_not_live_long_enough(
674         &mut self,
675         location: Location,
676         borrow: &BorrowData<'tcx>,
677         place_span: (&Place<'tcx>, Span),
678         kind: Option<WriteKind>,
679     ) {
680         debug!(
681             "report_borrowed_value_does_not_live_long_enough(\
682              {:?}, {:?}, {:?}, {:?}\
683              )",
684             location, borrow, place_span, kind
685         );
686
687         let drop_span = place_span.1;
688         let scope_tree = self.infcx.tcx.region_scope_tree(self.mir_def_id);
689         let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
690             .last()
691             .unwrap();
692
693         let borrow_spans = self.retrieve_borrow_spans(borrow);
694         let borrow_span = borrow_spans.var_or_use();
695
696         let proper_span = match *root_place {
697             Place::Base(PlaceBase::Local(local)) => self.mir.local_decls[local].source_info.span,
698             _ => drop_span,
699         };
700
701         if self.access_place_error_reported
702             .contains(&(root_place.clone(), borrow_span))
703         {
704             debug!(
705                 "suppressing access_place error when borrow doesn't live long enough for {:?}",
706                 borrow_span
707             );
708             return;
709         }
710
711         self.access_place_error_reported
712             .insert((root_place.clone(), borrow_span));
713
714         if let StorageDeadOrDrop::Destructor(dropped_ty) =
715             self.classify_drop_access_kind(&borrow.borrowed_place)
716         {
717             // If a borrow of path `B` conflicts with drop of `D` (and
718             // we're not in the uninteresting case where `B` is a
719             // prefix of `D`), then report this as a more interesting
720             // destructor conflict.
721             if !borrow.borrowed_place.is_prefix_of(place_span.0) {
722                 self.report_borrow_conflicts_with_destructor(
723                     location, borrow, place_span, kind, dropped_ty,
724                 );
725                 return;
726             }
727         }
728
729         let place_desc = self.describe_place(&borrow.borrowed_place);
730
731         let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
732         let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
733
734         let err = match (place_desc, explanation) {
735             (Some(_), _) if self.is_place_thread_local(root_place) => {
736                 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
737             }
738             // If the outlives constraint comes from inside the closure,
739             // for example:
740             //
741             // let x = 0;
742             // let y = &x;
743             // Box::new(|| y) as Box<Fn() -> &'static i32>
744             //
745             // then just use the normal error. The closure isn't escaping
746             // and `move` will not help here.
747             (
748                 Some(ref name),
749                 BorrowExplanation::MustBeValidFor {
750                     category: category @ ConstraintCategory::Return,
751                     from_closure: false,
752                     ref region_name,
753                     span,
754                     ..
755                 },
756             )
757             | (
758                 Some(ref name),
759                 BorrowExplanation::MustBeValidFor {
760                     category: category @ ConstraintCategory::CallArgument,
761                     from_closure: false,
762                     ref region_name,
763                     span,
764                     ..
765                 },
766             ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
767                 borrow_spans.args_or_use(),
768                 borrow_span,
769                 region_name,
770                 category,
771                 span,
772                 &format!("`{}`", name),
773             ),
774             (
775                 ref name,
776                 BorrowExplanation::MustBeValidFor {
777                     category: ConstraintCategory::Assignment,
778                     from_closure: false,
779                     region_name: RegionName {
780                         source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
781                         ..
782                     },
783                     span,
784                     ..
785                 },
786             ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
787             (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
788                 location,
789                 &name,
790                 &scope_tree,
791                 &borrow,
792                 drop_span,
793                 borrow_spans,
794                 explanation,
795             ),
796             (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
797                 location,
798                 &scope_tree,
799                 &borrow,
800                 drop_span,
801                 borrow_spans,
802                 proper_span,
803                 explanation,
804             ),
805         };
806
807         err.buffer(&mut self.errors_buffer);
808     }
809
810     fn report_local_value_does_not_live_long_enough(
811         &mut self,
812         location: Location,
813         name: &str,
814         scope_tree: &'tcx ScopeTree,
815         borrow: &BorrowData<'tcx>,
816         drop_span: Span,
817         borrow_spans: UseSpans,
818         explanation: BorrowExplanation,
819     ) -> DiagnosticBuilder<'cx> {
820         debug!(
821             "report_local_value_does_not_live_long_enough(\
822              {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
823              )",
824             location, name, scope_tree, borrow, drop_span, borrow_spans
825         );
826
827         let borrow_span = borrow_spans.var_or_use();
828         if let BorrowExplanation::MustBeValidFor {
829             category,
830             span,
831             ref opt_place_desc,
832             from_closure: false,
833             ..
834         } = explanation {
835             if let Some(diag) = self.try_report_cannot_return_reference_to_local(
836                 borrow,
837                 borrow_span,
838                 span,
839                 category,
840                 opt_place_desc.as_ref(),
841             ) {
842                 return diag;
843             }
844         }
845
846         let mut err = self.infcx.tcx.path_does_not_live_long_enough(
847             borrow_span,
848             &format!("`{}`", name),
849             Origin::Mir,
850         );
851
852         if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
853             let region_name = annotation.emit(self, &mut err);
854
855             err.span_label(
856                 borrow_span,
857                 format!("`{}` would have to be valid for `{}`...", name, region_name),
858             );
859
860             if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
861                 err.span_label(
862                     drop_span,
863                     format!(
864                         "...but `{}` will be dropped here, when the function `{}` returns",
865                         name,
866                         self.infcx.tcx.hir().name_by_hir_id(fn_hir_id),
867                     ),
868                 );
869
870                 err.note(
871                     "functions cannot return a borrow to data owned within the function's scope, \
872                      functions can only return borrows to data passed as arguments",
873                 );
874                 err.note(
875                     "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
876                      references-and-borrowing.html#dangling-references>",
877                 );
878             } else {
879                 err.span_label(
880                     drop_span,
881                     format!("...but `{}` dropped here while still borrowed", name),
882                 );
883             }
884
885             if let BorrowExplanation::MustBeValidFor { .. } = explanation {
886             } else {
887                 explanation.add_explanation_to_diagnostic(
888                     self.infcx.tcx,
889                     self.mir,
890                     &mut err,
891                     "",
892                     None,
893                 );
894             }
895         } else {
896             err.span_label(borrow_span, "borrowed value does not live long enough");
897             err.span_label(
898                 drop_span,
899                 format!("`{}` dropped here while still borrowed", name),
900             );
901
902             let within = if borrow_spans.for_generator() {
903                 " by generator"
904             } else {
905                 ""
906             };
907
908             borrow_spans.args_span_label(
909                 &mut err,
910                 format!("value captured here{}", within),
911             );
912
913             explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
914         }
915
916         err
917     }
918
919     fn report_borrow_conflicts_with_destructor(
920         &mut self,
921         location: Location,
922         borrow: &BorrowData<'tcx>,
923         (place, drop_span): (&Place<'tcx>, Span),
924         kind: Option<WriteKind>,
925         dropped_ty: Ty<'tcx>,
926     ) {
927         debug!(
928             "report_borrow_conflicts_with_destructor(\
929              {:?}, {:?}, ({:?}, {:?}), {:?}\
930              )",
931             location, borrow, place, drop_span, kind,
932         );
933
934         let borrow_spans = self.retrieve_borrow_spans(borrow);
935         let borrow_span = borrow_spans.var_or_use();
936
937         let mut err = self.infcx
938             .tcx
939             .cannot_borrow_across_destructor(borrow_span, Origin::Mir);
940
941         let what_was_dropped = match self.describe_place(place) {
942             Some(name) => format!("`{}`", name.as_str()),
943             None => String::from("temporary value"),
944         };
945
946         let label = match self.describe_place(&borrow.borrowed_place) {
947             Some(borrowed) => format!(
948                 "here, drop of {D} needs exclusive access to `{B}`, \
949                  because the type `{T}` implements the `Drop` trait",
950                 D = what_was_dropped,
951                 T = dropped_ty,
952                 B = borrowed
953             ),
954             None => format!(
955                 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
956                 D = what_was_dropped,
957                 T = dropped_ty
958             ),
959         };
960         err.span_label(drop_span, label);
961
962         // Only give this note and suggestion if they could be relevant.
963         let explanation =
964             self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
965         match explanation {
966             BorrowExplanation::UsedLater { .. }
967             | BorrowExplanation::UsedLaterWhenDropped { .. } => {
968                 err.note("consider using a `let` binding to create a longer lived value");
969             }
970             _ => {}
971         }
972
973         explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
974
975         err.buffer(&mut self.errors_buffer);
976     }
977
978     fn report_thread_local_value_does_not_live_long_enough(
979         &mut self,
980         drop_span: Span,
981         borrow_span: Span,
982     ) -> DiagnosticBuilder<'cx> {
983         debug!(
984             "report_thread_local_value_does_not_live_long_enough(\
985              {:?}, {:?}\
986              )",
987             drop_span, borrow_span
988         );
989
990         let mut err = self.infcx
991             .tcx
992             .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
993
994         err.span_label(
995             borrow_span,
996             "thread-local variables cannot be borrowed beyond the end of the function",
997         );
998         err.span_label(drop_span, "end of enclosing function is here");
999
1000         err
1001     }
1002
1003     fn report_temporary_value_does_not_live_long_enough(
1004         &mut self,
1005         location: Location,
1006         scope_tree: &'tcx ScopeTree,
1007         borrow: &BorrowData<'tcx>,
1008         drop_span: Span,
1009         borrow_spans: UseSpans,
1010         proper_span: Span,
1011         explanation: BorrowExplanation,
1012     ) -> DiagnosticBuilder<'cx> {
1013         debug!(
1014             "report_temporary_value_does_not_live_long_enough(\
1015              {:?}, {:?}, {:?}, {:?}, {:?}\
1016              )",
1017             location, scope_tree, borrow, drop_span, proper_span
1018         );
1019
1020         if let BorrowExplanation::MustBeValidFor {
1021             category,
1022             span,
1023             from_closure: false,
1024             ..
1025         } = explanation {
1026             if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1027                 borrow,
1028                 proper_span,
1029                 span,
1030                 category,
1031                 None,
1032             ) {
1033                 return diag;
1034             }
1035         }
1036
1037         let tcx = self.infcx.tcx;
1038         let mut err = tcx.temporary_value_borrowed_for_too_long(proper_span, Origin::Mir);
1039         err.span_label(
1040             proper_span,
1041             "creates a temporary which is freed while still in use",
1042         );
1043         err.span_label(
1044             drop_span,
1045             "temporary value is freed at the end of this statement",
1046         );
1047
1048         match explanation {
1049             BorrowExplanation::UsedLater(..)
1050             | BorrowExplanation::UsedLaterInLoop(..)
1051             | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1052                 // Only give this note and suggestion if it could be relevant.
1053                 err.note("consider using a `let` binding to create a longer lived value");
1054             }
1055             _ => {}
1056         }
1057         explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
1058
1059         let within = if borrow_spans.for_generator() {
1060             " by generator"
1061         } else {
1062             ""
1063         };
1064
1065         borrow_spans.args_span_label(
1066             &mut err,
1067             format!("value captured here{}", within),
1068         );
1069
1070         err
1071     }
1072
1073     fn try_report_cannot_return_reference_to_local(
1074         &self,
1075         borrow: &BorrowData<'tcx>,
1076         borrow_span: Span,
1077         return_span: Span,
1078         category: ConstraintCategory,
1079         opt_place_desc: Option<&String>,
1080     ) -> Option<DiagnosticBuilder<'cx>> {
1081         let tcx = self.infcx.tcx;
1082
1083         let return_kind = match category {
1084             ConstraintCategory::Return => "return",
1085             ConstraintCategory::Yield => "yield",
1086             _ => return None,
1087         };
1088
1089         // FIXME use a better heuristic than Spans
1090         let reference_desc = if return_span == self.mir.source_info(borrow.reserve_location).span {
1091             "reference to"
1092         } else {
1093             "value referencing"
1094         };
1095
1096         let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1097             let local_kind = match borrow.borrowed_place {
1098                 Place::Base(PlaceBase::Local(local)) => {
1099                     match self.mir.local_kind(local) {
1100                         LocalKind::ReturnPointer
1101                         | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1102                         LocalKind::Var => "local variable ",
1103                         LocalKind::Arg
1104                         if !self.upvars.is_empty()
1105                             && local == Local::new(1) => {
1106                             "variable captured by `move` "
1107                         }
1108                         LocalKind::Arg => {
1109                             "function parameter "
1110                         }
1111                     }
1112                 }
1113                 _ => "local data ",
1114             };
1115             (
1116                 format!("{}`{}`", local_kind, place_desc),
1117                 format!("`{}` is borrowed here", place_desc),
1118             )
1119         } else {
1120             let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
1121                 .last()
1122                 .unwrap();
1123             let local = if let Place::Base(PlaceBase::Local(local)) = *root_place {
1124                 local
1125             } else {
1126                 bug!("try_report_cannot_return_reference_to_local: not a local")
1127             };
1128             match self.mir.local_kind(local) {
1129                 LocalKind::ReturnPointer | LocalKind::Temp => {
1130                     (
1131                         "temporary value".to_string(),
1132                         "temporary value created here".to_string(),
1133                     )
1134                 }
1135                 LocalKind::Arg => {
1136                     (
1137                         "function parameter".to_string(),
1138                         "function parameter borrowed here".to_string(),
1139                     )
1140                 },
1141                 LocalKind::Var => bug!("local variable without a name"),
1142             }
1143         };
1144
1145         let mut err = tcx.cannot_return_reference_to_local(
1146             return_span,
1147             return_kind,
1148             reference_desc,
1149             &place_desc,
1150             Origin::Mir,
1151         );
1152
1153         if return_span != borrow_span {
1154             err.span_label(borrow_span, note);
1155         }
1156
1157         Some(err)
1158     }
1159
1160     fn report_escaping_closure_capture(
1161         &mut self,
1162         args_span: Span,
1163         var_span: Span,
1164         fr_name: &RegionName,
1165         category: ConstraintCategory,
1166         constraint_span: Span,
1167         captured_var: &str,
1168     ) -> DiagnosticBuilder<'cx> {
1169         let tcx = self.infcx.tcx;
1170
1171         let mut err = tcx.cannot_capture_in_long_lived_closure(
1172             args_span,
1173             captured_var,
1174             var_span,
1175           Origin::Mir,
1176         );
1177
1178         let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1179             Ok(string) => format!("move {}", string),
1180             Err(_) => "move |<args>| <body>".to_string()
1181         };
1182
1183         err.span_suggestion(
1184             args_span,
1185             &format!("to force the closure to take ownership of {} (and any \
1186                       other referenced variables), use the `move` keyword",
1187                       captured_var),
1188             suggestion,
1189             Applicability::MachineApplicable,
1190         );
1191
1192         match category {
1193             ConstraintCategory::Return => {
1194                 err.span_note(constraint_span, "closure is returned here");
1195             }
1196             ConstraintCategory::CallArgument => {
1197                 fr_name.highlight_region_name(&mut err);
1198                 err.span_note(
1199                     constraint_span,
1200                     &format!("function requires argument type to outlive `{}`", fr_name),
1201                 );
1202             }
1203             _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1204                        category: `{:?}`", category),
1205         }
1206         err
1207     }
1208
1209     fn report_escaping_data(
1210         &mut self,
1211         borrow_span: Span,
1212         name: &Option<String>,
1213         upvar_span: Span,
1214         upvar_name: &str,
1215         escape_span: Span,
1216     ) -> DiagnosticBuilder<'cx> {
1217         let tcx = self.infcx.tcx;
1218
1219         let escapes_from = if tcx.is_closure(self.mir_def_id) {
1220             let tables = tcx.typeck_tables_of(self.mir_def_id);
1221             let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1222             match tables.node_type(mir_hir_id).sty {
1223                 ty::Closure(..) => "closure",
1224                 ty::Generator(..) => "generator",
1225                 _ => bug!("Closure body doesn't have a closure or generator type"),
1226             }
1227         } else {
1228             "function"
1229         };
1230
1231         let mut err = tcx.borrowed_data_escapes_closure(escape_span, escapes_from, Origin::Mir);
1232
1233         err.span_label(
1234             upvar_span,
1235             format!(
1236                 "`{}` is declared here, outside of the {} body",
1237                 upvar_name, escapes_from
1238             ),
1239         );
1240
1241         err.span_label(
1242             borrow_span,
1243             format!(
1244                 "borrow is only valid in the {} body",
1245                 escapes_from
1246             ),
1247         );
1248
1249         if let Some(name) = name {
1250             err.span_label(
1251                 escape_span,
1252                 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1253             );
1254         } else {
1255             err.span_label(
1256                 escape_span,
1257                 format!("reference escapes the {} body here", escapes_from),
1258             );
1259         }
1260
1261         err
1262     }
1263
1264     fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1265         let mir = self.mir;
1266
1267         let mut stack = Vec::new();
1268         stack.extend(mir.predecessor_locations(location).map(|predecessor| {
1269             let is_back_edge = location.dominates(predecessor, &self.dominators);
1270             (predecessor, is_back_edge)
1271         }));
1272
1273         let mut visited = FxHashSet::default();
1274         let mut result = vec![];
1275
1276         'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1277             debug!(
1278                 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1279                 location, is_back_edge
1280             );
1281
1282             if !visited.insert(location) {
1283                 continue;
1284             }
1285
1286             // check for moves
1287             let stmt_kind = mir[location.block]
1288                 .statements
1289                 .get(location.statement_index)
1290                 .map(|s| &s.kind);
1291             if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1292                 // this analysis only tries to find moves explicitly
1293                 // written by the user, so we ignore the move-outs
1294                 // created by `StorageDead` and at the beginning
1295                 // of a function.
1296             } else {
1297                 // If we are found a use of a.b.c which was in error, then we want to look for
1298                 // moves not only of a.b.c but also a.b and a.
1299                 //
1300                 // Note that the moves data already includes "parent" paths, so we don't have to
1301                 // worry about the other case: that is, if there is a move of a.b.c, it is already
1302                 // marked as a move of a.b and a as well, so we will generate the correct errors
1303                 // there.
1304                 let mut mpis = vec![mpi];
1305                 let move_paths = &self.move_data.move_paths;
1306                 mpis.extend(move_paths[mpi].parents(move_paths));
1307
1308                 for moi in &self.move_data.loc_map[location] {
1309                     debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1310                     if mpis.contains(&self.move_data.moves[*moi].path) {
1311                         debug!("report_use_of_moved_or_uninitialized: found");
1312                         result.push(MoveSite {
1313                             moi: *moi,
1314                             traversed_back_edge: is_back_edge,
1315                         });
1316
1317                         // Strictly speaking, we could continue our DFS here. There may be
1318                         // other moves that can reach the point of error. But it is kind of
1319                         // confusing to highlight them.
1320                         //
1321                         // Example:
1322                         //
1323                         // ```
1324                         // let a = vec![];
1325                         // let b = a;
1326                         // let c = a;
1327                         // drop(a); // <-- current point of error
1328                         // ```
1329                         //
1330                         // Because we stop the DFS here, we only highlight `let c = a`,
1331                         // and not `let b = a`. We will of course also report an error at
1332                         // `let c = a` which highlights `let b = a` as the move.
1333                         continue 'dfs;
1334                     }
1335                 }
1336             }
1337
1338             // check for inits
1339             let mut any_match = false;
1340             drop_flag_effects::for_location_inits(
1341                 self.infcx.tcx,
1342                 self.mir,
1343                 self.move_data,
1344                 location,
1345                 |m| {
1346                     if m == mpi {
1347                         any_match = true;
1348                     }
1349                 },
1350             );
1351             if any_match {
1352                 continue 'dfs;
1353             }
1354
1355             stack.extend(mir.predecessor_locations(location).map(|predecessor| {
1356                 let back_edge = location.dominates(predecessor, &self.dominators);
1357                 (predecessor, is_back_edge || back_edge)
1358             }));
1359         }
1360
1361         result
1362     }
1363
1364     pub(super) fn report_illegal_mutation_of_borrowed(
1365         &mut self,
1366         location: Location,
1367         (place, span): (&Place<'tcx>, Span),
1368         loan: &BorrowData<'tcx>,
1369     ) {
1370         let loan_spans = self.retrieve_borrow_spans(loan);
1371         let loan_span = loan_spans.args_or_use();
1372
1373         let tcx = self.infcx.tcx;
1374         if loan.kind == BorrowKind::Shallow {
1375             let mut err = tcx.cannot_mutate_in_match_guard(
1376                 span,
1377                 loan_span,
1378                 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
1379                 "assign",
1380                 Origin::Mir,
1381             );
1382             loan_spans.var_span_label(
1383                 &mut err,
1384                 format!("borrow occurs due to use{}", loan_spans.describe()),
1385             );
1386
1387             err.buffer(&mut self.errors_buffer);
1388
1389             return;
1390         }
1391
1392         let mut err = tcx.cannot_assign_to_borrowed(
1393             span,
1394             loan_span,
1395             &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
1396             Origin::Mir,
1397         );
1398
1399         loan_spans.var_span_label(
1400             &mut err,
1401             format!("borrow occurs due to use{}", loan_spans.describe()),
1402         );
1403
1404         self.explain_why_borrow_contains_point(location, loan, None)
1405             .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
1406
1407         err.buffer(&mut self.errors_buffer);
1408     }
1409
1410     /// Reports an illegal reassignment; for example, an assignment to
1411     /// (part of) a non-`mut` local that occurs potentially after that
1412     /// local has already been initialized. `place` is the path being
1413     /// assigned; `err_place` is a place providing a reason why
1414     /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1415     /// assignment to `x.f`).
1416     pub(super) fn report_illegal_reassignment(
1417         &mut self,
1418         _location: Location,
1419         (place, span): (&Place<'tcx>, Span),
1420         assigned_span: Span,
1421         err_place: &Place<'tcx>,
1422     ) {
1423         let (from_arg, local_decl) = if let Place::Base(PlaceBase::Local(local)) = *err_place {
1424             if let LocalKind::Arg = self.mir.local_kind(local) {
1425                 (true, Some(&self.mir.local_decls[local]))
1426             } else {
1427                 (false, Some(&self.mir.local_decls[local]))
1428             }
1429         } else {
1430             (false, None)
1431         };
1432
1433         // If root local is initialized immediately (everything apart from let
1434         // PATTERN;) then make the error refer to that local, rather than the
1435         // place being assigned later.
1436         let (place_description, assigned_span) = match local_decl {
1437             Some(LocalDecl {
1438                 is_user_variable: Some(ClearCrossCrate::Clear),
1439                 ..
1440             })
1441             | Some(LocalDecl {
1442                 is_user_variable:
1443                     Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1444                         opt_match_place: None,
1445                         ..
1446                     }))),
1447                 ..
1448             })
1449             | Some(LocalDecl {
1450                 is_user_variable: None,
1451                 ..
1452             })
1453             | None => (self.describe_place(place), assigned_span),
1454             Some(decl) => (self.describe_place(err_place), decl.source_info.span),
1455         };
1456
1457         let mut err = self.infcx.tcx.cannot_reassign_immutable(
1458             span,
1459             place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1460             from_arg,
1461             Origin::Mir,
1462         );
1463         let msg = if from_arg {
1464             "cannot assign to immutable argument"
1465         } else {
1466             "cannot assign twice to immutable variable"
1467         };
1468         if span != assigned_span {
1469             if !from_arg {
1470                 let value_msg = match place_description {
1471                     Some(name) => format!("`{}`", name),
1472                     None => "value".to_owned(),
1473                 };
1474                 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1475             }
1476         }
1477         if let Some(decl) = local_decl {
1478             if let Some(name) = decl.name {
1479                 if decl.can_be_made_mutable() {
1480                     err.span_suggestion(
1481                         decl.source_info.span,
1482                         "make this binding mutable",
1483                         format!("mut {}", name),
1484                         Applicability::MachineApplicable,
1485                     );
1486                 }
1487             }
1488         }
1489         err.span_label(span, msg);
1490         err.buffer(&mut self.errors_buffer);
1491     }
1492 }
1493
1494 pub(super) struct IncludingDowncast(bool);
1495
1496 /// Which case a StorageDeadOrDrop is for.
1497 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1498 enum StorageDeadOrDrop<'tcx> {
1499     LocalStorageDead,
1500     BoxedStorageDead,
1501     Destructor(Ty<'tcx>),
1502 }
1503
1504 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1505
1506     /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
1507     /// is moved after being invoked.
1508     ///
1509     /// ```text
1510     /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
1511     ///       its environment
1512     ///   --> $DIR/issue-42065.rs:16:29
1513     ///    |
1514     /// LL |         for (key, value) in dict {
1515     ///    |                             ^^^^
1516     /// ```
1517     pub(super) fn add_moved_or_invoked_closure_note(
1518         &self,
1519         location: Location,
1520         place: &Place<'tcx>,
1521         diag: &mut DiagnosticBuilder<'_>,
1522     ) {
1523         debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
1524         let mut target = place.local();
1525         for stmt in &self.mir[location.block].statements[location.statement_index..] {
1526             debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
1527             if let StatementKind::Assign(into, box Rvalue::Use(from)) = &stmt.kind {
1528                 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
1529                 match from {
1530                     Operand::Copy(ref place) |
1531                     Operand::Move(ref place) if target == place.local() =>
1532                         target = into.local(),
1533                     _ => {},
1534                 }
1535             }
1536         }
1537
1538         // Check if we are attempting to call a closure after it has been invoked.
1539         let terminator = self.mir[location.block].terminator();
1540         debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
1541         if let TerminatorKind::Call {
1542             func: Operand::Constant(box Constant {
1543                 literal: ty::Const {
1544                     ty: &ty::TyS { sty: ty::FnDef(id, _), ..  },
1545                     ..
1546                 },
1547                 ..
1548             }),
1549             args,
1550             ..
1551         } = &terminator.kind {
1552             debug!("add_moved_or_invoked_closure_note: id={:?}", id);
1553             if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
1554                 let closure = match args.first() {
1555                     Some(Operand::Copy(ref place)) |
1556                     Some(Operand::Move(ref place)) if target == place.local() =>
1557                         place.local().unwrap(),
1558                     _ => return,
1559                 };
1560
1561                 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
1562                 if let ty::Closure(did, _) = self.mir.local_decls[closure].ty.sty {
1563                     let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
1564
1565                     if let Some((span, name)) = self.infcx.tcx.typeck_tables_of(did)
1566                         .closure_kind_origins()
1567                         .get(hir_id)
1568                     {
1569                         diag.span_note(
1570                             *span,
1571                             &format!(
1572                                 "closure cannot be invoked more than once because it moves the \
1573                                  variable `{}` out of its environment",
1574                                 name,
1575                             ),
1576                         );
1577                         return;
1578                     }
1579                 }
1580             }
1581         }
1582
1583         // Check if we are just moving a closure after it has been invoked.
1584         if let Some(target) = target {
1585             if let ty::Closure(did, _) = self.mir.local_decls[target].ty.sty {
1586                 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
1587
1588                 if let Some((span, name)) = self.infcx.tcx.typeck_tables_of(did)
1589                     .closure_kind_origins()
1590                     .get(hir_id)
1591                 {
1592                     diag.span_note(
1593                         *span,
1594                         &format!(
1595                             "closure cannot be moved more than once as it is not `Copy` due to \
1596                              moving the variable `{}` out of its environment",
1597                              name
1598                         ),
1599                     );
1600                 }
1601             }
1602         }
1603     }
1604
1605     /// End-user visible description of `place` if one can be found. If the
1606     /// place is a temporary for instance, None will be returned.
1607     pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
1608         self.describe_place_with_options(place, IncludingDowncast(false))
1609     }
1610
1611     /// End-user visible description of `place` if one can be found. If the
1612     /// place is a temporary for instance, None will be returned.
1613     /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
1614     /// `Downcast` and `IncludingDowncast` is true
1615     pub(super) fn describe_place_with_options(
1616         &self,
1617         place: &Place<'tcx>,
1618         including_downcast: IncludingDowncast,
1619     ) -> Option<String> {
1620         let mut buf = String::new();
1621         match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
1622             Ok(()) => Some(buf),
1623             Err(()) => None,
1624         }
1625     }
1626
1627     /// Appends end-user visible description of `place` to `buf`.
1628     fn append_place_to_string(
1629         &self,
1630         place: &Place<'tcx>,
1631         buf: &mut String,
1632         mut autoderef: bool,
1633         including_downcast: &IncludingDowncast,
1634     ) -> Result<(), ()> {
1635         match *place {
1636             Place::Base(PlaceBase::Local(local)) => {
1637                 self.append_local_to_string(local, buf)?;
1638             }
1639             Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1640                 buf.push_str("promoted");
1641             }
1642             Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
1643                 buf.push_str(&self.infcx.tcx.item_name(def_id).to_string());
1644             }
1645             Place::Projection(ref proj) => {
1646                 match proj.elem {
1647                     ProjectionElem::Deref => {
1648                         let upvar_field_projection =
1649                             self.is_upvar_field_projection(place);
1650                         if let Some(field) = upvar_field_projection {
1651                             let var_index = field.index();
1652                             let name = self.upvars[var_index].name.to_string();
1653                             if self.upvars[var_index].by_ref {
1654                                 buf.push_str(&name);
1655                             } else {
1656                                 buf.push_str(&format!("*{}", &name));
1657                             }
1658                         } else {
1659                             if autoderef {
1660                                 self.append_place_to_string(
1661                                     &proj.base,
1662                                     buf,
1663                                     autoderef,
1664                                     &including_downcast,
1665                                 )?;
1666                             } else if let Place::Base(PlaceBase::Local(local)) = proj.base {
1667                                 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
1668                                     self.mir.local_decls[local].is_user_variable
1669                                 {
1670                                     self.append_place_to_string(
1671                                         &proj.base,
1672                                         buf,
1673                                         autoderef,
1674                                         &including_downcast,
1675                                     )?;
1676                                 } else {
1677                                     buf.push_str(&"*");
1678                                     self.append_place_to_string(
1679                                         &proj.base,
1680                                         buf,
1681                                         autoderef,
1682                                         &including_downcast,
1683                                     )?;
1684                                 }
1685                             } else {
1686                                 buf.push_str(&"*");
1687                                 self.append_place_to_string(
1688                                     &proj.base,
1689                                     buf,
1690                                     autoderef,
1691                                     &including_downcast,
1692                                 )?;
1693                             }
1694                         }
1695                     }
1696                     ProjectionElem::Downcast(..) => {
1697                         self.append_place_to_string(
1698                             &proj.base,
1699                             buf,
1700                             autoderef,
1701                             &including_downcast,
1702                         )?;
1703                         if including_downcast.0 {
1704                             return Err(());
1705                         }
1706                     }
1707                     ProjectionElem::Field(field, _ty) => {
1708                         autoderef = true;
1709
1710                         let upvar_field_projection =
1711                             self.is_upvar_field_projection(place);
1712                         if let Some(field) = upvar_field_projection {
1713                             let var_index = field.index();
1714                             let name = self.upvars[var_index].name.to_string();
1715                             buf.push_str(&name);
1716                         } else {
1717                             let field_name = self.describe_field(&proj.base, field);
1718                             self.append_place_to_string(
1719                                 &proj.base,
1720                                 buf,
1721                                 autoderef,
1722                                 &including_downcast,
1723                             )?;
1724                             buf.push_str(&format!(".{}", field_name));
1725                         }
1726                     }
1727                     ProjectionElem::Index(index) => {
1728                         autoderef = true;
1729
1730                         self.append_place_to_string(
1731                             &proj.base,
1732                             buf,
1733                             autoderef,
1734                             &including_downcast,
1735                         )?;
1736                         buf.push_str("[");
1737                         if self.append_local_to_string(index, buf).is_err() {
1738                             buf.push_str("_");
1739                         }
1740                         buf.push_str("]");
1741                     }
1742                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1743                         autoderef = true;
1744                         // Since it isn't possible to borrow an element on a particular index and
1745                         // then use another while the borrow is held, don't output indices details
1746                         // to avoid confusing the end-user
1747                         self.append_place_to_string(
1748                             &proj.base,
1749                             buf,
1750                             autoderef,
1751                             &including_downcast,
1752                         )?;
1753                         buf.push_str(&"[..]");
1754                     }
1755                 };
1756             }
1757         }
1758
1759         Ok(())
1760     }
1761
1762     /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
1763     /// a name, then `Err` is returned
1764     fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
1765         let local = &self.mir.local_decls[local_index];
1766         match local.name {
1767             Some(name) => {
1768                 buf.push_str(&name.to_string());
1769                 Ok(())
1770             }
1771             None => Err(()),
1772         }
1773     }
1774
1775     /// End-user visible description of the `field`nth field of `base`
1776     fn describe_field(&self, base: &Place<'tcx>, field: Field) -> String {
1777         match *base {
1778             Place::Base(PlaceBase::Local(local)) => {
1779                 let local = &self.mir.local_decls[local];
1780                 self.describe_field_from_ty(&local.ty, field, None)
1781             }
1782             Place::Base(PlaceBase::Static(ref static_)) =>
1783                 self.describe_field_from_ty(&static_.ty, field, None),
1784             Place::Projection(ref proj) => match proj.elem {
1785                 ProjectionElem::Deref => self.describe_field(&proj.base, field),
1786                 ProjectionElem::Downcast(_, variant_index) => {
1787                     let base_ty = base.ty(self.mir, self.infcx.tcx).ty;
1788                     self.describe_field_from_ty(&base_ty, field, Some(variant_index))
1789                 }
1790                 ProjectionElem::Field(_, field_type) => {
1791                     self.describe_field_from_ty(&field_type, field, None)
1792                 }
1793                 ProjectionElem::Index(..)
1794                 | ProjectionElem::ConstantIndex { .. }
1795                 | ProjectionElem::Subslice { .. } => {
1796                     self.describe_field(&proj.base, field)
1797                 }
1798             },
1799         }
1800     }
1801
1802     /// End-user visible description of the `field_index`nth field of `ty`
1803     fn describe_field_from_ty(
1804         &self,
1805         ty: Ty<'_>,
1806         field: Field,
1807         variant_index: Option<VariantIdx>
1808     ) -> String {
1809         if ty.is_box() {
1810             // If the type is a box, the field is described from the boxed type
1811             self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
1812         } else {
1813             match ty.sty {
1814                 ty::Adt(def, _) => {
1815                     let variant = if let Some(idx) = variant_index {
1816                         assert!(def.is_enum());
1817                         &def.variants[idx]
1818                     } else {
1819                         def.non_enum_variant()
1820                     };
1821                     variant.fields[field.index()]
1822                         .ident
1823                         .to_string()
1824                 },
1825                 ty::Tuple(_) => field.index().to_string(),
1826                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
1827                     self.describe_field_from_ty(&ty, field, variant_index)
1828                 }
1829                 ty::Array(ty, _) | ty::Slice(ty) =>
1830                     self.describe_field_from_ty(&ty, field, variant_index),
1831                 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
1832                     // `tcx.upvars(def_id)` returns an `Option`, which is `None` in case
1833                     // the closure comes from another crate. But in that case we wouldn't
1834                     // be borrowck'ing it, so we can just unwrap:
1835                     let upvar = self.infcx.tcx.upvars(def_id).unwrap()[field.index()];
1836
1837                     self.infcx.tcx.hir().name_by_hir_id(upvar.var_id()).to_string()
1838                 }
1839                 _ => {
1840                     // Might need a revision when the fields in trait RFC is implemented
1841                     // (https://github.com/rust-lang/rfcs/pull/1546)
1842                     bug!(
1843                         "End-user description not implemented for field access on `{:?}`",
1844                         ty
1845                     );
1846                 }
1847             }
1848         }
1849     }
1850
1851     /// Checks if a place is a thread-local static.
1852     pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
1853         if let Place::Base(
1854             PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })
1855         ) = place {
1856             let attrs = self.infcx.tcx.get_attrs(*def_id);
1857             let is_thread_local = attrs.iter().any(|attr| attr.check_name(sym::thread_local));
1858
1859             debug!(
1860                 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
1861                 attrs, is_thread_local
1862             );
1863             is_thread_local
1864         } else {
1865             debug!("is_place_thread_local: no");
1866             false
1867         }
1868     }
1869
1870     fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
1871         let tcx = self.infcx.tcx;
1872         match place {
1873             Place::Base(PlaceBase::Local(_)) |
1874             Place::Base(PlaceBase::Static(_)) => {
1875                 StorageDeadOrDrop::LocalStorageDead
1876             }
1877             Place::Projection(box PlaceProjection { base, elem }) => {
1878                 let base_access = self.classify_drop_access_kind(base);
1879                 match elem {
1880                     ProjectionElem::Deref => match base_access {
1881                         StorageDeadOrDrop::LocalStorageDead
1882                         | StorageDeadOrDrop::BoxedStorageDead => {
1883                             assert!(
1884                                 base.ty(self.mir, tcx).ty.is_box(),
1885                                 "Drop of value behind a reference or raw pointer"
1886                             );
1887                             StorageDeadOrDrop::BoxedStorageDead
1888                         }
1889                         StorageDeadOrDrop::Destructor(_) => base_access,
1890                     },
1891                     ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1892                         let base_ty = base.ty(self.mir, tcx).ty;
1893                         match base_ty.sty {
1894                             ty::Adt(def, _) if def.has_dtor(tcx) => {
1895                                 // Report the outermost adt with a destructor
1896                                 match base_access {
1897                                     StorageDeadOrDrop::Destructor(_) => base_access,
1898                                     StorageDeadOrDrop::LocalStorageDead
1899                                     | StorageDeadOrDrop::BoxedStorageDead => {
1900                                         StorageDeadOrDrop::Destructor(base_ty)
1901                                     }
1902                                 }
1903                             }
1904                             _ => base_access,
1905                         }
1906                     }
1907
1908                     ProjectionElem::ConstantIndex { .. }
1909                     | ProjectionElem::Subslice { .. }
1910                     | ProjectionElem::Index(_) => base_access,
1911                 }
1912             }
1913         }
1914     }
1915
1916     /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1917     /// borrow of local value that does not live long enough.
1918     fn annotate_argument_and_return_for_borrow(
1919         &self,
1920         borrow: &BorrowData<'tcx>,
1921     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1922         // Define a fallback for when we can't match a closure.
1923         let fallback = || {
1924             let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1925             if is_closure {
1926                 None
1927             } else {
1928                 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1929                 match ty.sty {
1930                     ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1931                         self.mir_def_id,
1932                         self.infcx.tcx.fn_sig(self.mir_def_id),
1933                     ),
1934                     _ => None,
1935                 }
1936             }
1937         };
1938
1939         // In order to determine whether we need to annotate, we need to check whether the reserve
1940         // place was an assignment into a temporary.
1941         //
1942         // If it was, we check whether or not that temporary is eventually assigned into the return
1943         // place. If it was, we can add annotations about the function's return type and arguments
1944         // and it'll make sense.
1945         let location = borrow.reserve_location;
1946         debug!(
1947             "annotate_argument_and_return_for_borrow: location={:?}",
1948             location
1949         );
1950         if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1951              = &self.mir[location.block].statements.get(location.statement_index)
1952         {
1953             debug!(
1954                 "annotate_argument_and_return_for_borrow: reservation={:?}",
1955                 reservation
1956             );
1957             // Check that the initial assignment of the reserve location is into a temporary.
1958             let mut target = *match reservation {
1959                 Place::Base(PlaceBase::Local(local))
1960                     if self.mir.local_kind(*local) == LocalKind::Temp => local,
1961                 _ => return None,
1962             };
1963
1964             // Next, look through the rest of the block, checking if we are assigning the
1965             // `target` (that is, the place that contains our borrow) to anything.
1966             let mut annotated_closure = None;
1967             for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1968                 debug!(
1969                     "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1970                     target, stmt
1971                 );
1972                 if let StatementKind::Assign(
1973                     Place::Base(PlaceBase::Local(assigned_to)),
1974                     box rvalue
1975                 ) = &stmt.kind {
1976                     debug!(
1977                         "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1978                          rvalue={:?}",
1979                         assigned_to, rvalue
1980                     );
1981                     // Check if our `target` was captured by a closure.
1982                     if let Rvalue::Aggregate(
1983                         box AggregateKind::Closure(def_id, substs),
1984                         operands,
1985                     ) = rvalue
1986                     {
1987                         for operand in operands {
1988                             let assigned_from = match operand {
1989                                 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1990                                     assigned_from
1991                                 }
1992                                 _ => continue,
1993                             };
1994                             debug!(
1995                                 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1996                                 assigned_from
1997                             );
1998
1999                             // Find the local from the operand.
2000                             let assigned_from_local = match assigned_from.local() {
2001                                 Some(local) => local,
2002                                 None => continue,
2003                             };
2004
2005                             if assigned_from_local != target {
2006                                 continue;
2007                             }
2008
2009                             // If a closure captured our `target` and then assigned
2010                             // into a place then we should annotate the closure in
2011                             // case it ends up being assigned into the return place.
2012                             annotated_closure = self.annotate_fn_sig(
2013                                 *def_id,
2014                                 self.infcx.closure_sig(*def_id, *substs),
2015                             );
2016                             debug!(
2017                                 "annotate_argument_and_return_for_borrow: \
2018                                  annotated_closure={:?} assigned_from_local={:?} \
2019                                  assigned_to={:?}",
2020                                 annotated_closure, assigned_from_local, assigned_to
2021                             );
2022
2023                             if *assigned_to == mir::RETURN_PLACE {
2024                                 // If it was assigned directly into the return place, then
2025                                 // return now.
2026                                 return annotated_closure;
2027                             } else {
2028                                 // Otherwise, update the target.
2029                                 target = *assigned_to;
2030                             }
2031                         }
2032
2033                         // If none of our closure's operands matched, then skip to the next
2034                         // statement.
2035                         continue;
2036                     }
2037
2038                     // Otherwise, look at other types of assignment.
2039                     let assigned_from = match rvalue {
2040                         Rvalue::Ref(_, _, assigned_from) => assigned_from,
2041                         Rvalue::Use(operand) => match operand {
2042                             Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
2043                                 assigned_from
2044                             }
2045                             _ => continue,
2046                         },
2047                         _ => continue,
2048                     };
2049                     debug!(
2050                         "annotate_argument_and_return_for_borrow: \
2051                          assigned_from={:?}",
2052                         assigned_from,
2053                     );
2054
2055                     // Find the local from the rvalue.
2056                     let assigned_from_local = match assigned_from.local() {
2057                         Some(local) => local,
2058                         None => continue,
2059                     };
2060                     debug!(
2061                         "annotate_argument_and_return_for_borrow: \
2062                          assigned_from_local={:?}",
2063                         assigned_from_local,
2064                     );
2065
2066                     // Check if our local matches the target - if so, we've assigned our
2067                     // borrow to a new place.
2068                     if assigned_from_local != target {
2069                         continue;
2070                     }
2071
2072                     // If we assigned our `target` into a new place, then we should
2073                     // check if it was the return place.
2074                     debug!(
2075                         "annotate_argument_and_return_for_borrow: \
2076                          assigned_from_local={:?} assigned_to={:?}",
2077                         assigned_from_local, assigned_to
2078                     );
2079                     if *assigned_to == mir::RETURN_PLACE {
2080                         // If it was then return the annotated closure if there was one,
2081                         // else, annotate this function.
2082                         return annotated_closure.or_else(fallback);
2083                     }
2084
2085                     // If we didn't assign into the return place, then we just update
2086                     // the target.
2087                     target = *assigned_to;
2088                 }
2089             }
2090
2091             // Check the terminator if we didn't find anything in the statements.
2092             let terminator = &self.mir[location.block].terminator();
2093             debug!(
2094                 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
2095                 target, terminator
2096             );
2097             if let TerminatorKind::Call {
2098                 destination: Some((Place::Base(PlaceBase::Local(assigned_to)), _)),
2099                 args,
2100                 ..
2101             } = &terminator.kind
2102             {
2103                 debug!(
2104                     "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
2105                     assigned_to, args
2106                 );
2107                 for operand in args {
2108                     let assigned_from = match operand {
2109                         Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
2110                             assigned_from
2111                         }
2112                         _ => continue,
2113                     };
2114                     debug!(
2115                         "annotate_argument_and_return_for_borrow: assigned_from={:?}",
2116                         assigned_from,
2117                     );
2118
2119                     if let Some(assigned_from_local) = assigned_from.local() {
2120                         debug!(
2121                             "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
2122                             assigned_from_local,
2123                         );
2124
2125                         if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
2126                             return annotated_closure.or_else(fallback);
2127                         }
2128                     }
2129                 }
2130             }
2131         }
2132
2133         // If we haven't found an assignment into the return place, then we need not add
2134         // any annotations.
2135         debug!("annotate_argument_and_return_for_borrow: none found");
2136         None
2137     }
2138
2139     /// Annotate the first argument and return type of a function signature if they are
2140     /// references.
2141     fn annotate_fn_sig(
2142         &self,
2143         did: DefId,
2144         sig: ty::PolyFnSig<'tcx>,
2145     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
2146         debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
2147         let is_closure = self.infcx.tcx.is_closure(did);
2148         let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
2149         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
2150
2151         // We need to work out which arguments to highlight. We do this by looking
2152         // at the return type, where there are three cases:
2153         //
2154         // 1. If there are named arguments, then we should highlight the return type and
2155         //    highlight any of the arguments that are also references with that lifetime.
2156         //    If there are no arguments that have the same lifetime as the return type,
2157         //    then don't highlight anything.
2158         // 2. The return type is a reference with an anonymous lifetime. If this is
2159         //    the case, then we can take advantage of (and teach) the lifetime elision
2160         //    rules.
2161         //
2162         //    We know that an error is being reported. So the arguments and return type
2163         //    must satisfy the elision rules. Therefore, if there is a single argument
2164         //    then that means the return type and first (and only) argument have the same
2165         //    lifetime and the borrow isn't meeting that, we can highlight the argument
2166         //    and return type.
2167         //
2168         //    If there are multiple arguments then the first argument must be self (else
2169         //    it would not satisfy the elision rules), so we can highlight self and the
2170         //    return type.
2171         // 3. The return type is not a reference. In this case, we don't highlight
2172         //    anything.
2173         let return_ty = sig.output();
2174         match return_ty.skip_binder().sty {
2175             ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
2176                 // This is case 1 from above, return type is a named reference so we need to
2177                 // search for relevant arguments.
2178                 let mut arguments = Vec::new();
2179                 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
2180                     if let ty::Ref(argument_region, _, _) = argument.sty {
2181                         if argument_region == return_region {
2182                             // Need to use the `rustc::ty` types to compare against the
2183                             // `return_region`. Then use the `rustc::hir` type to get only
2184                             // the lifetime span.
2185                             if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
2186                                 // With access to the lifetime, we can get
2187                                 // the span of it.
2188                                 arguments.push((*argument, lifetime.span));
2189                             } else {
2190                                 bug!("ty type is a ref but hir type is not");
2191                             }
2192                         }
2193                     }
2194                 }
2195
2196                 // We need to have arguments. This shouldn't happen, but it's worth checking.
2197                 if arguments.is_empty() {
2198                     return None;
2199                 }
2200
2201                 // We use a mix of the HIR and the Ty types to get information
2202                 // as the HIR doesn't have full types for closure arguments.
2203                 let return_ty = *sig.output().skip_binder();
2204                 let mut return_span = fn_decl.output.span();
2205                 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
2206                     if let hir::TyKind::Rptr(lifetime, _) = ty.into_inner().node {
2207                         return_span = lifetime.span;
2208                     }
2209                 }
2210
2211                 Some(AnnotatedBorrowFnSignature::NamedFunction {
2212                     arguments,
2213                     return_ty,
2214                     return_span,
2215                 })
2216             }
2217             ty::Ref(_, _, _) if is_closure => {
2218                 // This is case 2 from above but only for closures, return type is anonymous
2219                 // reference so we select
2220                 // the first argument.
2221                 let argument_span = fn_decl.inputs.first()?.span;
2222                 let argument_ty = sig.inputs().skip_binder().first()?;
2223
2224                 // Closure arguments are wrapped in a tuple, so we need to get the first
2225                 // from that.
2226                 if let ty::Tuple(elems) = argument_ty.sty {
2227                     let argument_ty = elems.first()?.expect_ty();
2228                     if let ty::Ref(_, _, _) = argument_ty.sty {
2229                         return Some(AnnotatedBorrowFnSignature::Closure {
2230                             argument_ty,
2231                             argument_span,
2232                         });
2233                     }
2234                 }
2235
2236                 None
2237             }
2238             ty::Ref(_, _, _) => {
2239                 // This is also case 2 from above but for functions, return type is still an
2240                 // anonymous reference so we select the first argument.
2241                 let argument_span = fn_decl.inputs.first()?.span;
2242                 let argument_ty = sig.inputs().skip_binder().first()?;
2243
2244                 let return_span = fn_decl.output.span();
2245                 let return_ty = *sig.output().skip_binder();
2246
2247                 // We expect the first argument to be a reference.
2248                 match argument_ty.sty {
2249                     ty::Ref(_, _, _) => {}
2250                     _ => return None,
2251                 }
2252
2253                 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2254                     argument_ty,
2255                     argument_span,
2256                     return_ty,
2257                     return_span,
2258                 })
2259             }
2260             _ => {
2261                 // This is case 3 from above, return type is not a reference so don't highlight
2262                 // anything.
2263                 None
2264             }
2265         }
2266     }
2267 }
2268
2269 #[derive(Debug)]
2270 enum AnnotatedBorrowFnSignature<'tcx> {
2271     NamedFunction {
2272         arguments: Vec<(Ty<'tcx>, Span)>,
2273         return_ty: Ty<'tcx>,
2274         return_span: Span,
2275     },
2276     AnonymousFunction {
2277         argument_ty: Ty<'tcx>,
2278         argument_span: Span,
2279         return_ty: Ty<'tcx>,
2280         return_span: Span,
2281     },
2282     Closure {
2283         argument_ty: Ty<'tcx>,
2284         argument_span: Span,
2285     },
2286 }
2287
2288 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2289     /// Annotate the provided diagnostic with information about borrow from the fn signature that
2290     /// helps explain.
2291     fn emit(
2292         &self,
2293         cx: &mut MirBorrowckCtxt<'_, '_, 'tcx>,
2294         diag: &mut DiagnosticBuilder<'_>,
2295     ) -> String {
2296         match self {
2297             AnnotatedBorrowFnSignature::Closure {
2298                 argument_ty,
2299                 argument_span,
2300             } => {
2301                 diag.span_label(
2302                     *argument_span,
2303                     format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2304                 );
2305
2306                 cx.get_region_name_for_ty(argument_ty, 0)
2307             }
2308             AnnotatedBorrowFnSignature::AnonymousFunction {
2309                 argument_ty,
2310                 argument_span,
2311                 return_ty,
2312                 return_span,
2313             } => {
2314                 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2315                 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2316
2317                 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2318                 let types_equal = return_ty_name == argument_ty_name;
2319                 diag.span_label(
2320                     *return_span,
2321                     format!(
2322                         "{}has type `{}`",
2323                         if types_equal { "also " } else { "" },
2324                         return_ty_name,
2325                     ),
2326                 );
2327
2328                 diag.note(
2329                     "argument and return type have the same lifetime due to lifetime elision rules",
2330                 );
2331                 diag.note(
2332                     "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2333                      lifetime-syntax.html#lifetime-elision>",
2334                 );
2335
2336                 cx.get_region_name_for_ty(return_ty, 0)
2337             }
2338             AnnotatedBorrowFnSignature::NamedFunction {
2339                 arguments,
2340                 return_ty,
2341                 return_span,
2342             } => {
2343                 // Region of return type and arguments checked to be the same earlier.
2344                 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2345                 for (_, argument_span) in arguments {
2346                     diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2347                 }
2348
2349                 diag.span_label(
2350                     *return_span,
2351                     format!("also has lifetime `{}`", region_name,),
2352                 );
2353
2354                 diag.help(&format!(
2355                     "use data from the highlighted arguments which match the `{}` lifetime of \
2356                      the return type",
2357                     region_name,
2358                 ));
2359
2360                 region_name
2361             }
2362         }
2363     }
2364 }
2365
2366 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2367     /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
2368     /// name where required.
2369     fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
2370         let mut s = String::new();
2371         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
2372
2373         // We need to add synthesized lifetimes where appropriate. We do
2374         // this by hooking into the pretty printer and telling it to label the
2375         // lifetimes without names with the value `'0`.
2376         match ty.sty {
2377             ty::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
2378             | ty::Ref(
2379                 ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
2380                 _,
2381                 _,
2382             ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
2383             _ => {}
2384         }
2385
2386         let _ = ty.print(printer);
2387         s
2388     }
2389
2390     /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
2391     /// synthesized lifetime name where required.
2392     fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
2393         let mut s = String::new();
2394         let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
2395
2396         let region = match ty.sty {
2397             ty::Ref(region, _, _) => {
2398                 match region {
2399                     ty::RegionKind::ReLateBound(_, br)
2400                     | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
2401                         printer.region_highlight_mode.highlighting_bound_region(*br, counter)
2402                     }
2403                     _ => {}
2404                 }
2405
2406                 region
2407             }
2408             _ => bug!("ty for annotation of borrow region is not a reference"),
2409         };
2410
2411         let _ = region.print(printer);
2412         s
2413     }
2414 }
2415
2416 // The span(s) associated to a use of a place.
2417 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2418 pub(super) enum UseSpans {
2419     // The access is caused by capturing a variable for a closure.
2420     ClosureUse {
2421         // This is true if the captured variable was from a generator.
2422         is_generator: bool,
2423         // The span of the args of the closure, including the `move` keyword if
2424         // it's present.
2425         args_span: Span,
2426         // The span of the first use of the captured variable inside the closure.
2427         var_span: Span,
2428     },
2429     // This access has a single span associated to it: common case.
2430     OtherUse(Span),
2431 }
2432
2433 impl UseSpans {
2434     pub(super) fn args_or_use(self) -> Span {
2435         match self {
2436             UseSpans::ClosureUse {
2437                 args_span: span, ..
2438             }
2439             | UseSpans::OtherUse(span) => span,
2440         }
2441     }
2442
2443     pub(super) fn var_or_use(self) -> Span {
2444         match self {
2445             UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
2446         }
2447     }
2448
2449     // Add a span label to the arguments of the closure, if it exists.
2450     pub(super) fn args_span_label(
2451         self,
2452         err: &mut DiagnosticBuilder<'_>,
2453         message: impl Into<String>,
2454     ) {
2455         if let UseSpans::ClosureUse { args_span, .. } = self {
2456             err.span_label(args_span, message);
2457         }
2458     }
2459
2460     // Add a span label to the use of the captured variable, if it exists.
2461     pub(super) fn var_span_label(
2462         self,
2463         err: &mut DiagnosticBuilder<'_>,
2464         message: impl Into<String>,
2465     ) {
2466         if let UseSpans::ClosureUse { var_span, .. } = self {
2467             err.span_label(var_span, message);
2468         }
2469     }
2470
2471     /// Returns `false` if this place is not used in a closure.
2472     fn for_closure(&self) -> bool {
2473         match *self {
2474             UseSpans::ClosureUse { is_generator, .. } => !is_generator,
2475             _ => false,
2476         }
2477     }
2478
2479     /// Returns `false` if this place is not used in a generator.
2480     fn for_generator(&self) -> bool {
2481         match *self {
2482             UseSpans::ClosureUse { is_generator, .. } => is_generator,
2483             _ => false,
2484         }
2485     }
2486
2487     /// Describe the span associated with a use of a place.
2488     fn describe(&self) -> String {
2489         match *self {
2490             UseSpans::ClosureUse { is_generator, .. } => if is_generator {
2491                 " in generator".to_string()
2492             } else {
2493                 " in closure".to_string()
2494             },
2495             _ => "".to_string(),
2496         }
2497     }
2498
2499     pub(super) fn or_else<F>(self, if_other: F) -> Self
2500     where
2501         F: FnOnce() -> Self,
2502     {
2503         match self {
2504             closure @ UseSpans::ClosureUse { .. } => closure,
2505             UseSpans::OtherUse(_) => if_other(),
2506         }
2507     }
2508 }
2509
2510 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2511     /// Finds the spans associated to a move or copy of move_place at location.
2512     pub(super) fn move_spans(
2513         &self,
2514         moved_place: &Place<'tcx>, // Could also be an upvar.
2515         location: Location,
2516     ) -> UseSpans {
2517         use self::UseSpans::*;
2518
2519         let stmt = match self.mir[location.block].statements.get(location.statement_index) {
2520             Some(stmt) => stmt,
2521             None => return OtherUse(self.mir.source_info(location).span),
2522         };
2523
2524         debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
2525         if let  StatementKind::Assign(
2526             _,
2527             box Rvalue::Aggregate(ref kind, ref places)
2528         ) = stmt.kind {
2529             let (def_id, is_generator) = match kind {
2530                 box AggregateKind::Closure(def_id, _) => (def_id, false),
2531                 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2532                 _ => return OtherUse(stmt.source_info.span),
2533             };
2534
2535             debug!(
2536                 "move_spans: def_id={:?} is_generator={:?} places={:?}",
2537                 def_id, is_generator, places
2538             );
2539             if let Some((args_span, var_span)) = self.closure_span(*def_id, moved_place, places) {
2540                 return ClosureUse {
2541                     is_generator,
2542                     args_span,
2543                     var_span,
2544                 };
2545             }
2546         }
2547
2548         OtherUse(stmt.source_info.span)
2549     }
2550
2551     /// Finds the span of arguments of a closure (within `maybe_closure_span`)
2552     /// and its usage of the local assigned at `location`.
2553     /// This is done by searching in statements succeeding `location`
2554     /// and originating from `maybe_closure_span`.
2555     pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
2556         use self::UseSpans::*;
2557         debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
2558
2559         let target = match self.mir[location.block]
2560             .statements
2561             .get(location.statement_index)
2562         {
2563             Some(&Statement {
2564                 kind: StatementKind::Assign(Place::Base(PlaceBase::Local(local)), _),
2565                 ..
2566             }) => local,
2567             _ => return OtherUse(use_span),
2568         };
2569
2570         if self.mir.local_kind(target) != LocalKind::Temp {
2571             // operands are always temporaries.
2572             return OtherUse(use_span);
2573         }
2574
2575         for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
2576             if let StatementKind::Assign(
2577                 _, box Rvalue::Aggregate(ref kind, ref places)
2578             ) = stmt.kind {
2579                 let (def_id, is_generator) = match kind {
2580                     box AggregateKind::Closure(def_id, _) => (def_id, false),
2581                     box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2582                     _ => continue,
2583                 };
2584
2585                 debug!(
2586                     "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
2587                     def_id, is_generator, places
2588                 );
2589                 if let Some((args_span, var_span)) = self.closure_span(
2590                     *def_id, &Place::Base(PlaceBase::Local(target)), places
2591                 ) {
2592                     return ClosureUse {
2593                         is_generator,
2594                         args_span,
2595                         var_span,
2596                     };
2597                 } else {
2598                     return OtherUse(use_span);
2599                 }
2600             }
2601
2602             if use_span != stmt.source_info.span {
2603                 break;
2604             }
2605         }
2606
2607         OtherUse(use_span)
2608     }
2609
2610     /// Finds the span of a captured variable within a closure or generator.
2611     fn closure_span(
2612         &self,
2613         def_id: DefId,
2614         target_place: &Place<'tcx>,
2615         places: &Vec<Operand<'tcx>>,
2616     ) -> Option<(Span, Span)> {
2617         debug!(
2618             "closure_span: def_id={:?} target_place={:?} places={:?}",
2619             def_id, target_place, places
2620         );
2621         let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id)?;
2622         let expr = &self.infcx.tcx.hir().expect_expr_by_hir_id(hir_id).node;
2623         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
2624         if let hir::ExprKind::Closure(
2625             .., args_span, _
2626         ) = expr {
2627             for (v, place) in self.infcx.tcx.upvars(def_id)?.iter().zip(places) {
2628                 match place {
2629                     Operand::Copy(place) |
2630                     Operand::Move(place) if target_place == place => {
2631                         debug!("closure_span: found captured local {:?}", place);
2632                         return Some((*args_span, v.span));
2633                     },
2634                     _ => {}
2635                 }
2636             }
2637
2638         }
2639         None
2640     }
2641
2642     /// Helper to retrieve span(s) of given borrow from the current MIR
2643     /// representation
2644     pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans {
2645         let span = self.mir.source_info(borrow.reserve_location).span;
2646         self.borrow_spans(span, borrow.reserve_location)
2647     }
2648 }