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