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