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