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