1 use borrow_check::nll::explain_borrow::BorrowExplanation;
2 use borrow_check::nll::region_infer::{RegionName, RegionNameSource};
3 use borrow_check::prefixes::IsPrefixOf;
4 use borrow_check::WriteKind;
6 use rustc::hir::def_id::DefId;
7 use rustc::middle::region::ScopeTree;
9 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, Constant,
10 ConstraintCategory, Field, Local, LocalDecl, LocalKind, Location, Operand,
11 Place, PlaceProjection, ProjectionElem, Rvalue, Statement, StatementKind,
12 TerminatorKind, VarBindingForm,
14 use rustc::ty::{self, DefIdTree};
15 use rustc::util::ppaux::RegionHighlightMode;
16 use rustc_data_structures::fx::FxHashSet;
17 use rustc_data_structures::indexed_vec::Idx;
18 use rustc_data_structures::sync::Lrc;
19 use rustc_errors::{Applicability, DiagnosticBuilder};
22 use super::borrow_set::BorrowData;
23 use super::{Context, MirBorrowckCtxt};
24 use super::{InitializationRequiringAction, PrefixSet};
25 use dataflow::drop_flag_effects;
26 use dataflow::move_paths::indexes::MoveOutIndex;
27 use dataflow::move_paths::MovePathIndex;
28 use util::borrowck_errors::{BorrowckErrors, Origin};
32 /// Index of the "move out" that we found. The `MoveData` can
33 /// then tell us where the move occurred.
36 /// True if we traversed a back edge while walking from the point
37 /// of error to the move site.
38 traversed_back_edge: bool
41 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
42 pub(super) fn report_use_of_moved_or_uninitialized(
45 desired_action: InitializationRequiringAction,
46 (moved_place, used_place, span): (&Place<'tcx>, &Place<'tcx>, Span),
50 "report_use_of_moved_or_uninitialized: context={:?} desired_action={:?} \
51 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
52 context, desired_action, moved_place, used_place, span, mpi
55 let use_spans = self.move_spans(moved_place, context.loc)
56 .or_else(|| self.borrow_spans(span, context.loc));
57 let span = use_spans.args_or_use();
59 let move_site_vec = self.get_moved_indexes(context, mpi);
61 "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
64 let move_out_indices: Vec<_> = move_site_vec
66 .map(|move_site| move_site.moi)
69 if move_out_indices.is_empty() {
70 let root_place = self.prefixes(&used_place, PrefixSet::All).last().unwrap();
72 if self.uninitialized_error_reported.contains(root_place) {
74 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
80 self.uninitialized_error_reported.insert(root_place.clone());
82 let item_msg = match self.describe_place_with_options(used_place,
83 IncludingDowncast(true)) {
84 Some(name) => format!("`{}`", name),
85 None => "value".to_owned(),
87 let mut err = self.infcx.tcx.cannot_act_on_uninitialized_variable(
89 desired_action.as_noun(),
90 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
91 .unwrap_or_else(|| "_".to_owned()),
94 err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
96 use_spans.var_span_label(
98 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
101 err.buffer(&mut self.errors_buffer);
103 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
104 if self.prefixes(&reported_place, PrefixSet::All)
105 .any(|p| p == used_place)
108 "report_use_of_moved_or_uninitialized place: error suppressed \
116 let msg = ""; //FIXME: add "partially " or "collaterally "
118 let mut err = self.infcx.tcx.cannot_act_on_moved_value(
120 desired_action.as_noun(),
122 self.describe_place_with_options(&moved_place, IncludingDowncast(true)),
126 self.add_closure_invoked_twice_with_moved_variable_suggestion(
132 let mut is_loop_move = false;
133 for move_site in &move_site_vec {
134 let move_out = self.move_data.moves[(*move_site).moi];
135 let moved_place = &self.move_data.move_paths[move_out.path].place;
137 let move_spans = self.move_spans(moved_place, move_out.source);
138 let move_span = move_spans.args_or_use();
140 let move_msg = if move_spans.for_closure() {
146 if span == move_span {
149 format!("value moved{} here, in previous iteration of loop", move_msg),
152 } else if move_site.traversed_back_edge {
156 "value moved{} here, in previous iteration of loop",
161 err.span_label(move_span, format!("value moved{} here", move_msg));
162 move_spans.var_span_label(
164 format!("variable moved due to use{}", move_spans.describe()),
169 use_spans.var_span_label(
171 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
178 "value {} here after move",
179 desired_action.as_verb_in_past_tense()
184 let ty = used_place.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
185 let needs_note = match ty.sty {
186 ty::Closure(id, _) => {
187 let tables = self.infcx.tcx.typeck_tables_of(id);
188 let node_id = self.infcx.tcx.hir().as_local_node_id(id).unwrap();
189 let hir_id = self.infcx.tcx.hir().node_to_hir_id(node_id);
191 tables.closure_kind_origins().get(hir_id).is_none()
197 let mpi = self.move_data.moves[move_out_indices[0]].path;
198 let place = &self.move_data.move_paths[mpi].place;
200 let ty = place.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
201 let note_msg = match self.describe_place_with_options(
203 IncludingDowncast(true),
205 Some(name) => format!("`{}`", name),
206 None => "value".to_owned(),
210 "move occurs because {} has type `{}`, \
211 which does not implement the `Copy` trait",
216 if let Some((_, mut old_err)) = self.move_error_reported
217 .insert(move_out_indices, (used_place.clone(), err))
219 // Cancel the old error so it doesn't ICE.
225 pub(super) fn report_move_out_while_borrowed(
228 (place, span): (&Place<'tcx>, Span),
229 borrow: &BorrowData<'tcx>,
232 "report_move_out_while_borrowed: context={:?} place={:?} span={:?} borrow={:?}",
233 context, place, span, borrow
235 let tcx = self.infcx.tcx;
236 let value_msg = match self.describe_place(place) {
237 Some(name) => format!("`{}`", name),
238 None => "value".to_owned(),
240 let borrow_msg = match self.describe_place(&borrow.borrowed_place) {
241 Some(name) => format!("`{}`", name),
242 None => "value".to_owned(),
245 let borrow_spans = self.retrieve_borrow_spans(borrow);
246 let borrow_span = borrow_spans.args_or_use();
248 let move_spans = self.move_spans(place, context.loc);
249 let span = move_spans.args_or_use();
251 let mut err = tcx.cannot_move_when_borrowed(
253 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
256 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
257 err.span_label(span, format!("move out of {} occurs here", value_msg));
259 borrow_spans.var_span_label(
261 format!("borrow occurs due to use{}", borrow_spans.describe())
264 move_spans.var_span_label(
266 format!("move occurs due to use{}", move_spans.describe())
269 self.explain_why_borrow_contains_point(context, borrow, None)
270 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
271 err.buffer(&mut self.errors_buffer);
274 pub(super) fn report_use_while_mutably_borrowed(
277 (place, _span): (&Place<'tcx>, Span),
278 borrow: &BorrowData<'tcx>,
280 let tcx = self.infcx.tcx;
282 let borrow_spans = self.retrieve_borrow_spans(borrow);
283 let borrow_span = borrow_spans.args_or_use();
285 // Conflicting borrows are reported separately, so only check for move
287 let use_spans = self.move_spans(place, context.loc);
288 let span = use_spans.var_or_use();
290 let mut err = tcx.cannot_use_when_mutably_borrowed(
292 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
294 &self.describe_place(&borrow.borrowed_place)
295 .unwrap_or_else(|| "_".to_owned()),
299 borrow_spans.var_span_label(&mut err, {
300 let place = &borrow.borrowed_place;
301 let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
303 format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
306 self.explain_why_borrow_contains_point(context, borrow, None)
307 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
308 err.buffer(&mut self.errors_buffer);
311 pub(super) fn report_conflicting_borrow(
314 (place, span): (&Place<'tcx>, Span),
315 gen_borrow_kind: BorrowKind,
316 issued_borrow: &BorrowData<'tcx>,
318 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
319 let issued_span = issued_spans.args_or_use();
321 let borrow_spans = self.borrow_spans(span, context.loc);
322 let span = borrow_spans.args_or_use();
324 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
330 let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
331 let tcx = self.infcx.tcx;
333 let first_borrow_desc;
335 let explanation = self.explain_why_borrow_contains_point(context, issued_borrow, None);
336 let second_borrow_desc = if explanation.is_explained() {
342 // FIXME: supply non-"" `opt_via` when appropriate
343 let mut err = match (
351 (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
352 first_borrow_desc = "mutable ";
353 tcx.cannot_reborrow_already_borrowed(
366 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
367 first_borrow_desc = "immutable ";
368 tcx.cannot_reborrow_already_borrowed(
382 (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
383 first_borrow_desc = "first ";
384 tcx.cannot_mutably_borrow_multiply(
395 (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
396 first_borrow_desc = "first ";
397 tcx.cannot_uniquely_borrow_by_two_closures(
406 (BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
407 | (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
408 let mut err = tcx.cannot_mutate_in_match_guard(
415 borrow_spans.var_span_label(
418 "borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe()
421 err.buffer(&mut self.errors_buffer);
426 (BorrowKind::Unique, _, _, _, _, _) => {
427 first_borrow_desc = "first ";
428 tcx.cannot_uniquely_borrow_by_one_closure(
441 (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
442 first_borrow_desc = "first ";
443 tcx.cannot_reborrow_already_uniquely_borrowed(
457 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
458 first_borrow_desc = "first ";
459 tcx.cannot_reborrow_already_uniquely_borrowed(
473 (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
474 | (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _) => {
475 // Shallow borrows are uses from the user's point of view.
476 self.report_use_while_mutably_borrowed(context, (place, span), issued_borrow);
479 (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
480 | (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
481 | (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
482 | (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
485 if issued_spans == borrow_spans {
486 borrow_spans.var_span_label(
488 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
491 let borrow_place = &issued_borrow.borrowed_place;
492 let borrow_place_desc = self.describe_place(borrow_place)
493 .unwrap_or_else(|| "_".to_owned());
494 issued_spans.var_span_label(
497 "first borrow occurs due to use of `{}`{}",
499 issued_spans.describe(),
503 borrow_spans.var_span_label(
506 "second borrow occurs due to use of `{}`{}",
508 borrow_spans.describe(),
514 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, first_borrow_desc);
516 err.buffer(&mut self.errors_buffer);
519 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
521 /// This means that some data referenced by `borrow` needs to live
522 /// past the point where the StorageDeadOrDrop of `place` occurs.
523 /// This is usually interpreted as meaning that `place` has too
524 /// short a lifetime. (But sometimes it is more useful to report
525 /// it as a more direct conflict between the execution of a
526 /// `Drop::drop` with an aliasing borrow.)
527 pub(super) fn report_borrowed_value_does_not_live_long_enough(
530 borrow: &BorrowData<'tcx>,
531 place_span: (&Place<'tcx>, Span),
532 kind: Option<WriteKind>,
535 "report_borrowed_value_does_not_live_long_enough(\
536 {:?}, {:?}, {:?}, {:?}\
538 context, borrow, place_span, kind
541 let drop_span = place_span.1;
542 let scope_tree = self.infcx.tcx.region_scope_tree(self.mir_def_id);
543 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
547 let borrow_spans = self.retrieve_borrow_spans(borrow);
548 let borrow_span = borrow_spans.var_or_use();
550 let proper_span = match *root_place {
551 Place::Local(local) => self.mir.local_decls[local].source_info.span,
555 if self.access_place_error_reported
556 .contains(&(root_place.clone(), borrow_span))
559 "suppressing access_place error when borrow doesn't live long enough for {:?}",
565 self.access_place_error_reported
566 .insert((root_place.clone(), borrow_span));
568 if let StorageDeadOrDrop::Destructor(dropped_ty) =
569 self.classify_drop_access_kind(&borrow.borrowed_place)
571 // If a borrow of path `B` conflicts with drop of `D` (and
572 // we're not in the uninteresting case where `B` is a
573 // prefix of `D`), then report this as a more interesting
574 // destructor conflict.
575 if !borrow.borrowed_place.is_prefix_of(place_span.0) {
576 self.report_borrow_conflicts_with_destructor(
577 context, borrow, place_span, kind, dropped_ty,
583 let place_desc = self.describe_place(&borrow.borrowed_place);
585 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
586 let explanation = self.explain_why_borrow_contains_point(context, &borrow, kind_place);
588 let err = match (place_desc, explanation) {
589 (Some(_), _) if self.is_place_thread_local(root_place) => {
590 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
592 // If the outlives constraint comes from inside the closure,
597 // Box::new(|| y) as Box<Fn() -> &'static i32>
599 // then just use the normal error. The closure isn't escaping
600 // and `move` will not help here.
603 BorrowExplanation::MustBeValidFor {
604 category: category @ ConstraintCategory::Return,
613 BorrowExplanation::MustBeValidFor {
614 category: category @ ConstraintCategory::CallArgument,
620 ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
621 borrow_spans.args_or_use(),
626 &format!("`{}`", name),
630 BorrowExplanation::MustBeValidFor {
631 category: ConstraintCategory::Assignment,
633 region_name: RegionName {
634 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
640 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
641 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
650 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
661 err.buffer(&mut self.errors_buffer);
664 fn report_local_value_does_not_live_long_enough(
668 scope_tree: &Lrc<ScopeTree>,
669 borrow: &BorrowData<'tcx>,
671 borrow_spans: UseSpans,
672 explanation: BorrowExplanation,
673 ) -> DiagnosticBuilder<'cx> {
675 "report_local_value_does_not_live_long_enough(\
676 {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
678 context, name, scope_tree, borrow, drop_span, borrow_spans
681 let borrow_span = borrow_spans.var_or_use();
682 if let BorrowExplanation::MustBeValidFor {
683 category: ConstraintCategory::Return,
689 return self.report_cannot_return_reference_to_local(
693 opt_place_desc.as_ref(),
697 let mut err = self.infcx.tcx.path_does_not_live_long_enough(
699 &format!("`{}`", name),
703 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
704 let region_name = annotation.emit(&mut err);
708 format!("`{}` would have to be valid for `{}`...", name, region_name),
711 if let Some(fn_node_id) = self.infcx.tcx.hir().as_local_node_id(self.mir_def_id) {
715 "...but `{}` will be dropped here, when the function `{}` returns",
717 self.infcx.tcx.hir().name(fn_node_id),
722 "functions cannot return a borrow to data owned within the function's scope, \
723 functions can only return borrows to data passed as arguments",
726 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch04-02-\
727 references-and-borrowing.html#dangling-references>",
732 format!("...but `{}` dropped here while still borrowed", name),
736 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
738 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
741 err.span_label(borrow_span, "borrowed value does not live long enough");
744 format!("`{}` dropped here while still borrowed", name),
747 let within = if borrow_spans.for_generator() {
753 borrow_spans.args_span_label(
755 format!("value captured here{}", within),
758 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
764 fn report_borrow_conflicts_with_destructor(
767 borrow: &BorrowData<'tcx>,
768 (place, drop_span): (&Place<'tcx>, Span),
769 kind: Option<WriteKind>,
770 dropped_ty: ty::Ty<'tcx>,
773 "report_borrow_conflicts_with_destructor(\
774 {:?}, {:?}, ({:?}, {:?}), {:?}\
776 context, borrow, place, drop_span, kind,
779 let borrow_spans = self.retrieve_borrow_spans(borrow);
780 let borrow_span = borrow_spans.var_or_use();
782 let mut err = self.infcx
784 .cannot_borrow_across_destructor(borrow_span, Origin::Mir);
786 let what_was_dropped = match self.describe_place(place) {
787 Some(name) => format!("`{}`", name.as_str()),
788 None => String::from("temporary value"),
791 let label = match self.describe_place(&borrow.borrowed_place) {
792 Some(borrowed) => format!(
793 "here, drop of {D} needs exclusive access to `{B}`, \
794 because the type `{T}` implements the `Drop` trait",
795 D = what_was_dropped,
800 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
801 D = what_was_dropped,
805 err.span_label(drop_span, label);
807 // Only give this note and suggestion if they could be relevant.
809 self.explain_why_borrow_contains_point(context, borrow, kind.map(|k| (k, place)));
811 BorrowExplanation::UsedLater { .. }
812 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
813 err.note("consider using a `let` binding to create a longer lived value");
818 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
820 err.buffer(&mut self.errors_buffer);
823 fn report_thread_local_value_does_not_live_long_enough(
827 ) -> DiagnosticBuilder<'cx> {
829 "report_thread_local_value_does_not_live_long_enough(\
832 drop_span, borrow_span
835 let mut err = self.infcx
837 .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
841 "thread-local variables cannot be borrowed beyond the end of the function",
843 err.span_label(drop_span, "end of enclosing function is here");
848 fn report_temporary_value_does_not_live_long_enough(
851 scope_tree: &Lrc<ScopeTree>,
852 borrow: &BorrowData<'tcx>,
854 borrow_spans: UseSpans,
856 explanation: BorrowExplanation,
857 ) -> DiagnosticBuilder<'cx> {
859 "report_temporary_value_does_not_live_long_enough(\
860 {:?}, {:?}, {:?}, {:?}, {:?}\
862 context, scope_tree, borrow, drop_span, proper_span
865 if let BorrowExplanation::MustBeValidFor {
866 category: ConstraintCategory::Return,
871 return self.report_cannot_return_reference_to_local(
879 let tcx = self.infcx.tcx;
880 let mut err = tcx.temporary_value_borrowed_for_too_long(proper_span, Origin::Mir);
883 "creates a temporary which is freed while still in use",
887 "temporary value is freed at the end of this statement",
891 BorrowExplanation::UsedLater(..)
892 | BorrowExplanation::UsedLaterInLoop(..)
893 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
894 // Only give this note and suggestion if it could be relevant.
895 err.note("consider using a `let` binding to create a longer lived value");
899 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
901 let within = if borrow_spans.for_generator() {
907 borrow_spans.args_span_label(
909 format!("value captured here{}", within),
915 fn report_cannot_return_reference_to_local(
917 borrow: &BorrowData<'tcx>,
920 opt_place_desc: Option<&String>,
921 ) -> DiagnosticBuilder<'cx> {
922 let tcx = self.infcx.tcx;
924 // FIXME use a better heuristic than Spans
925 let reference_desc = if return_span == self.mir.source_info(borrow.reserve_location).span {
931 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
932 let local_kind = match borrow.borrowed_place {
933 Place::Local(local) => {
934 match self.mir.local_kind(local) {
935 LocalKind::ReturnPointer
936 | LocalKind::Temp => bug!("temporary or return pointer with a name"),
937 LocalKind::Var => "local variable ",
939 if !self.mir.upvar_decls.is_empty()
940 && local == Local::new(1) => {
941 "variable captured by `move` "
944 "function parameter "
951 format!("{}`{}`", local_kind, place_desc),
952 format!("`{}` is borrowed here", place_desc),
955 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
958 let local = if let Place::Local(local) = *root_place {
961 bug!("report_cannot_return_reference_to_local: not a local")
963 match self.mir.local_kind(local) {
964 LocalKind::ReturnPointer | LocalKind::Temp => {
966 "temporary value".to_string(),
967 "temporary value created here".to_string(),
972 "function parameter".to_string(),
973 "function parameter borrowed here".to_string(),
976 LocalKind::Var => bug!("local variable without a name"),
980 let mut err = tcx.cannot_return_reference_to_local(
987 if return_span != borrow_span {
988 err.span_label(borrow_span, note);
994 fn report_escaping_closure_capture(
998 fr_name: &RegionName,
999 category: ConstraintCategory,
1000 constraint_span: Span,
1002 ) -> DiagnosticBuilder<'cx> {
1003 let tcx = self.infcx.tcx;
1005 let mut err = tcx.cannot_capture_in_long_lived_closure(
1012 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1013 Ok(string) => format!("move {}", string),
1014 Err(_) => "move |<args>| <body>".to_string()
1017 err.span_suggestion_with_applicability(
1019 &format!("to force the closure to take ownership of {} (and any \
1020 other referenced variables), use the `move` keyword",
1023 Applicability::MachineApplicable,
1027 ConstraintCategory::Return => {
1028 err.span_note(constraint_span, "closure is returned here");
1030 ConstraintCategory::CallArgument => {
1031 fr_name.highlight_region_name(&mut err);
1034 &format!("function requires argument type to outlive `{}`", fr_name),
1037 _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1038 category: `{:?}`", category),
1043 fn report_escaping_data(
1046 name: &Option<String>,
1050 ) -> DiagnosticBuilder<'cx> {
1051 let tcx = self.infcx.tcx;
1053 let escapes_from = if tcx.is_closure(self.mir_def_id) {
1054 let tables = tcx.typeck_tables_of(self.mir_def_id);
1055 let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1056 match tables.node_id_to_type(mir_hir_id).sty {
1057 ty::Closure(..) => "closure",
1058 ty::Generator(..) => "generator",
1059 _ => bug!("Closure body doesn't have a closure or generator type"),
1065 let mut err = tcx.borrowed_data_escapes_closure(escape_span, escapes_from, Origin::Mir);
1070 "`{}` is declared here, outside of the {} body",
1071 upvar_name, escapes_from
1078 "borrow is only valid in the {} body",
1083 if let Some(name) = name {
1086 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1091 format!("reference escapes the {} body here", escapes_from),
1098 fn get_moved_indexes(&mut self, context: Context, mpi: MovePathIndex) -> Vec<MoveSite> {
1101 let mut stack = Vec::new();
1102 stack.extend(mir.predecessor_locations(context.loc).map(|predecessor| {
1103 let is_back_edge = context.loc.dominates(predecessor, &self.dominators);
1104 (predecessor, is_back_edge)
1107 let mut visited = FxHashSet::default();
1108 let mut result = vec![];
1110 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1112 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1113 location, is_back_edge
1116 if !visited.insert(location) {
1121 let stmt_kind = mir[location.block]
1123 .get(location.statement_index)
1125 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1126 // this analysis only tries to find moves explicitly
1127 // written by the user, so we ignore the move-outs
1128 // created by `StorageDead` and at the beginning
1131 // If we are found a use of a.b.c which was in error, then we want to look for
1132 // moves not only of a.b.c but also a.b and a.
1134 // Note that the moves data already includes "parent" paths, so we don't have to
1135 // worry about the other case: that is, if there is a move of a.b.c, it is already
1136 // marked as a move of a.b and a as well, so we will generate the correct errors
1138 let mut mpis = vec![mpi];
1139 let move_paths = &self.move_data.move_paths;
1140 mpis.extend(move_paths[mpi].parents(move_paths));
1142 for moi in &self.move_data.loc_map[location] {
1143 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1144 if mpis.contains(&self.move_data.moves[*moi].path) {
1145 debug!("report_use_of_moved_or_uninitialized: found");
1146 result.push(MoveSite {
1148 traversed_back_edge: is_back_edge,
1151 // Strictly speaking, we could continue our DFS here. There may be
1152 // other moves that can reach the point of error. But it is kind of
1153 // confusing to highlight them.
1161 // drop(a); // <-- current point of error
1164 // Because we stop the DFS here, we only highlight `let c = a`,
1165 // and not `let b = a`. We will of course also report an error at
1166 // `let c = a` which highlights `let b = a` as the move.
1173 let mut any_match = false;
1174 drop_flag_effects::for_location_inits(
1189 stack.extend(mir.predecessor_locations(location).map(|predecessor| {
1190 let back_edge = location.dominates(predecessor, &self.dominators);
1191 (predecessor, is_back_edge || back_edge)
1198 pub(super) fn report_illegal_mutation_of_borrowed(
1201 (place, span): (&Place<'tcx>, Span),
1202 loan: &BorrowData<'tcx>,
1204 let loan_spans = self.retrieve_borrow_spans(loan);
1205 let loan_span = loan_spans.args_or_use();
1207 let tcx = self.infcx.tcx;
1208 let mut err = if loan.kind == BorrowKind::Shallow {
1209 tcx.cannot_mutate_in_match_guard(
1212 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
1217 tcx.cannot_assign_to_borrowed(
1220 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
1225 loan_spans.var_span_label(
1227 format!("borrow occurs due to use{}", loan_spans.describe()),
1230 self.explain_why_borrow_contains_point(context, loan, None)
1231 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
1233 err.buffer(&mut self.errors_buffer);
1236 /// Reports an illegal reassignment; for example, an assignment to
1237 /// (part of) a non-`mut` local that occurs potentially after that
1238 /// local has already been initialized. `place` is the path being
1239 /// assigned; `err_place` is a place providing a reason why
1240 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1241 /// assignment to `x.f`).
1242 pub(super) fn report_illegal_reassignment(
1245 (place, span): (&Place<'tcx>, Span),
1246 assigned_span: Span,
1247 err_place: &Place<'tcx>,
1249 let (from_arg, local_decl) = if let Place::Local(local) = *err_place {
1250 if let LocalKind::Arg = self.mir.local_kind(local) {
1251 (true, Some(&self.mir.local_decls[local]))
1253 (false, Some(&self.mir.local_decls[local]))
1259 // If root local is initialized immediately (everything apart from let
1260 // PATTERN;) then make the error refer to that local, rather than the
1261 // place being assigned later.
1262 let (place_description, assigned_span) = match local_decl {
1264 is_user_variable: Some(ClearCrossCrate::Clear),
1269 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1270 opt_match_place: None,
1276 is_user_variable: None,
1279 | None => (self.describe_place(place), assigned_span),
1280 Some(decl) => (self.describe_place(err_place), decl.source_info.span),
1283 let mut err = self.infcx.tcx.cannot_reassign_immutable(
1285 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1289 let msg = if from_arg {
1290 "cannot assign to immutable argument"
1292 "cannot assign twice to immutable variable"
1294 if span != assigned_span {
1296 let value_msg = match place_description {
1297 Some(name) => format!("`{}`", name),
1298 None => "value".to_owned(),
1300 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1303 if let Some(decl) = local_decl {
1304 if let Some(name) = decl.name {
1305 if decl.can_be_made_mutable() {
1306 err.span_suggestion_with_applicability(
1307 decl.source_info.span,
1308 "make this binding mutable",
1309 format!("mut {}", name),
1310 Applicability::MachineApplicable,
1315 err.span_label(span, msg);
1316 err.buffer(&mut self.errors_buffer);
1320 pub(super) struct IncludingDowncast(bool);
1322 /// Which case a StorageDeadOrDrop is for.
1323 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1324 enum StorageDeadOrDrop<'tcx> {
1327 Destructor(ty::Ty<'tcx>),
1330 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1332 /// Adds a suggestion when a closure is invoked twice with a moved variable.
1335 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
1337 /// --> $DIR/issue-42065.rs:16:29
1339 /// LL | for (key, value) in dict {
1342 pub(super) fn add_closure_invoked_twice_with_moved_variable_suggestion(
1345 place: &Place<'tcx>,
1346 diag: &mut DiagnosticBuilder<'_>,
1348 let mut target = place.local();
1350 "add_closure_invoked_twice_with_moved_variable_suggestion: location={:?} place={:?} \
1352 location, place, target,
1354 for stmt in &self.mir[location.block].statements[location.statement_index..] {
1356 "add_closure_invoked_twice_with_moved_variable_suggestion: stmt={:?} \
1360 if let StatementKind::Assign(into, box Rvalue::Use(from)) = &stmt.kind {
1362 "add_closure_invoked_twice_with_moved_variable_suggestion: into={:?} \
1367 Operand::Copy(ref place) |
1368 Operand::Move(ref place) if target == place.local() =>
1369 target = into.local(),
1376 let terminator = self.mir[location.block].terminator();
1378 "add_closure_invoked_twice_with_moved_variable_suggestion: terminator={:?}",
1381 if let TerminatorKind::Call {
1382 func: Operand::Constant(box Constant {
1383 literal: ty::Const { ty: &ty::TyS { sty: ty::TyKind::FnDef(id, _), .. }, .. },
1388 } = &terminator.kind {
1389 debug!("add_closure_invoked_twice_with_moved_variable_suggestion: id={:?}", id);
1390 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
1391 let closure = match args.first() {
1392 Some(Operand::Copy(ref place)) |
1393 Some(Operand::Move(ref place)) if target == place.local() =>
1394 place.local().unwrap(),
1398 "add_closure_invoked_twice_with_moved_variable_suggestion: closure={:?}",
1402 if let ty::TyKind::Closure(did, _substs) = self.mir.local_decls[closure].ty.sty {
1403 let node_id = match self.infcx.tcx.hir().as_local_node_id(did) {
1404 Some(node_id) => node_id,
1407 let hir_id = self.infcx.tcx.hir().node_to_hir_id(node_id);
1411 )) = self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id) {
1415 "closure cannot be invoked more than once because it \
1416 moves the variable `{}` out of its environment",
1426 /// End-user visible description of `place` if one can be found. If the
1427 /// place is a temporary for instance, None will be returned.
1428 pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
1429 self.describe_place_with_options(place, IncludingDowncast(false))
1432 /// End-user visible description of `place` if one can be found. If the
1433 /// place is a temporary for instance, None will be returned.
1434 /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
1435 /// `Downcast` and `IncludingDowncast` is true
1436 pub(super) fn describe_place_with_options(
1438 place: &Place<'tcx>,
1439 including_downcast: IncludingDowncast,
1440 ) -> Option<String> {
1441 let mut buf = String::new();
1442 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
1443 Ok(()) => Some(buf),
1448 /// Appends end-user visible description of `place` to `buf`.
1449 fn append_place_to_string(
1451 place: &Place<'tcx>,
1453 mut autoderef: bool,
1454 including_downcast: &IncludingDowncast,
1455 ) -> Result<(), ()> {
1457 Place::Promoted(_) => {
1458 buf.push_str("promoted");
1460 Place::Local(local) => {
1461 self.append_local_to_string(local, buf)?;
1463 Place::Static(ref static_) => {
1464 buf.push_str(&self.infcx.tcx.item_name(static_.def_id).to_string());
1466 Place::Projection(ref proj) => {
1468 ProjectionElem::Deref => {
1469 let upvar_field_projection =
1470 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1471 if let Some(field) = upvar_field_projection {
1472 let var_index = field.index();
1473 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1474 if self.mir.upvar_decls[var_index].by_ref {
1475 buf.push_str(&name);
1477 buf.push_str(&format!("*{}", &name));
1481 self.append_place_to_string(
1485 &including_downcast,
1487 } else if let Place::Local(local) = proj.base {
1488 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
1489 self.mir.local_decls[local].is_user_variable
1491 self.append_place_to_string(
1495 &including_downcast,
1499 self.append_place_to_string(
1503 &including_downcast,
1508 self.append_place_to_string(
1512 &including_downcast,
1517 ProjectionElem::Downcast(..) => {
1518 self.append_place_to_string(
1522 &including_downcast,
1524 if including_downcast.0 {
1528 ProjectionElem::Field(field, _ty) => {
1531 let upvar_field_projection =
1532 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1533 if let Some(field) = upvar_field_projection {
1534 let var_index = field.index();
1535 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1536 buf.push_str(&name);
1538 let field_name = self.describe_field(&proj.base, field);
1539 self.append_place_to_string(
1543 &including_downcast,
1545 buf.push_str(&format!(".{}", field_name));
1548 ProjectionElem::Index(index) => {
1551 self.append_place_to_string(
1555 &including_downcast,
1558 if self.append_local_to_string(index, buf).is_err() {
1563 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1565 // Since it isn't possible to borrow an element on a particular index and
1566 // then use another while the borrow is held, don't output indices details
1567 // to avoid confusing the end-user
1568 self.append_place_to_string(
1572 &including_downcast,
1574 buf.push_str(&"[..]");
1583 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
1584 /// a name, then `Err` is returned
1585 fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
1586 let local = &self.mir.local_decls[local_index];
1589 buf.push_str(&name.to_string());
1596 /// End-user visible description of the `field`nth field of `base`
1597 fn describe_field(&self, base: &Place, field: Field) -> String {
1599 Place::Local(local) => {
1600 let local = &self.mir.local_decls[local];
1601 self.describe_field_from_ty(&local.ty, field)
1603 Place::Promoted(ref prom) => self.describe_field_from_ty(&prom.1, field),
1604 Place::Static(ref static_) => self.describe_field_from_ty(&static_.ty, field),
1605 Place::Projection(ref proj) => match proj.elem {
1606 ProjectionElem::Deref => self.describe_field(&proj.base, field),
1607 ProjectionElem::Downcast(def, variant_index) =>
1608 def.variants[variant_index].fields[field.index()].ident.to_string(),
1609 ProjectionElem::Field(_, field_type) => {
1610 self.describe_field_from_ty(&field_type, field)
1612 ProjectionElem::Index(..)
1613 | ProjectionElem::ConstantIndex { .. }
1614 | ProjectionElem::Subslice { .. } => {
1615 self.describe_field(&proj.base, field)
1621 /// End-user visible description of the `field_index`nth field of `ty`
1622 fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String {
1624 // If the type is a box, the field is described from the boxed type
1625 self.describe_field_from_ty(&ty.boxed_ty(), field)
1628 ty::Adt(def, _) => if def.is_enum() {
1629 field.index().to_string()
1631 def.non_enum_variant().fields[field.index()]
1635 ty::Tuple(_) => field.index().to_string(),
1636 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
1637 self.describe_field_from_ty(&ty, field)
1639 ty::Array(ty, _) | ty::Slice(ty) => self.describe_field_from_ty(&ty, field),
1640 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
1641 // Convert the def-id into a node-id. node-ids are only valid for
1642 // the local code in the current crate, so this returns an `Option` in case
1643 // the closure comes from another crate. But in that case we wouldn't
1644 // be borrowck'ing it, so we can just unwrap:
1645 let node_id = self.infcx.tcx.hir().as_local_node_id(def_id).unwrap();
1646 let freevar = self.infcx
1648 .with_freevars(node_id, |fv| fv[field.index()]);
1650 self.infcx.tcx.hir().name(freevar.var_id()).to_string()
1653 // Might need a revision when the fields in trait RFC is implemented
1654 // (https://github.com/rust-lang/rfcs/pull/1546)
1656 "End-user description not implemented for field access on `{:?}`",
1664 /// Check if a place is a thread-local static.
1665 pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
1666 if let Place::Static(statik) = place {
1667 let attrs = self.infcx.tcx.get_attrs(statik.def_id);
1668 let is_thread_local = attrs.iter().any(|attr| attr.check_name("thread_local"));
1671 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
1672 attrs, is_thread_local
1676 debug!("is_place_thread_local: no");
1681 fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
1682 let tcx = self.infcx.tcx;
1684 Place::Local(_) | Place::Static(_) | Place::Promoted(_) => {
1685 StorageDeadOrDrop::LocalStorageDead
1687 Place::Projection(box PlaceProjection { base, elem }) => {
1688 let base_access = self.classify_drop_access_kind(base);
1690 ProjectionElem::Deref => match base_access {
1691 StorageDeadOrDrop::LocalStorageDead
1692 | StorageDeadOrDrop::BoxedStorageDead => {
1694 base.ty(self.mir, tcx).to_ty(tcx).is_box(),
1695 "Drop of value behind a reference or raw pointer"
1697 StorageDeadOrDrop::BoxedStorageDead
1699 StorageDeadOrDrop::Destructor(_) => base_access,
1701 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1702 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1704 ty::Adt(def, _) if def.has_dtor(tcx) => {
1705 // Report the outermost adt with a destructor
1707 StorageDeadOrDrop::Destructor(_) => base_access,
1708 StorageDeadOrDrop::LocalStorageDead
1709 | StorageDeadOrDrop::BoxedStorageDead => {
1710 StorageDeadOrDrop::Destructor(base_ty)
1718 ProjectionElem::ConstantIndex { .. }
1719 | ProjectionElem::Subslice { .. }
1720 | ProjectionElem::Index(_) => base_access,
1726 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1727 /// borrow of local value that does not live long enough.
1728 fn annotate_argument_and_return_for_borrow(
1730 borrow: &BorrowData<'tcx>,
1731 ) -> Option<AnnotatedBorrowFnSignature> {
1732 // Define a fallback for when we can't match a closure.
1734 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1738 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1740 ty::TyKind::FnDef(_, _) | ty::TyKind::FnPtr(_) => self.annotate_fn_sig(
1742 self.infcx.tcx.fn_sig(self.mir_def_id),
1749 // In order to determine whether we need to annotate, we need to check whether the reserve
1750 // place was an assignment into a temporary.
1752 // If it was, we check whether or not that temporary is eventually assigned into the return
1753 // place. If it was, we can add annotations about the function's return type and arguments
1754 // and it'll make sense.
1755 let location = borrow.reserve_location;
1757 "annotate_argument_and_return_for_borrow: location={:?}",
1760 if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1761 = &self.mir[location.block].statements.get(location.statement_index)
1764 "annotate_argument_and_return_for_borrow: reservation={:?}",
1767 // Check that the initial assignment of the reserve location is into a temporary.
1768 let mut target = *match reservation {
1769 Place::Local(local) if self.mir.local_kind(*local) == LocalKind::Temp => local,
1773 // Next, look through the rest of the block, checking if we are assigning the
1774 // `target` (that is, the place that contains our borrow) to anything.
1775 let mut annotated_closure = None;
1776 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1778 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1781 if let StatementKind::Assign(Place::Local(assigned_to), box rvalue) = &stmt.kind
1784 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1788 // Check if our `target` was captured by a closure.
1789 if let Rvalue::Aggregate(
1790 box AggregateKind::Closure(def_id, substs),
1794 for operand in operands {
1795 let assigned_from = match operand {
1796 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1802 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1806 // Find the local from the operand.
1807 let assigned_from_local = match assigned_from.local() {
1808 Some(local) => local,
1812 if assigned_from_local != target {
1816 // If a closure captured our `target` and then assigned
1817 // into a place then we should annotate the closure in
1818 // case it ends up being assigned into the return place.
1819 annotated_closure = self.annotate_fn_sig(
1821 self.infcx.closure_sig(*def_id, *substs),
1824 "annotate_argument_and_return_for_borrow: \
1825 annotated_closure={:?} assigned_from_local={:?} \
1827 annotated_closure, assigned_from_local, assigned_to
1830 if *assigned_to == mir::RETURN_PLACE {
1831 // If it was assigned directly into the return place, then
1833 return annotated_closure;
1835 // Otherwise, update the target.
1836 target = *assigned_to;
1840 // If none of our closure's operands matched, then skip to the next
1845 // Otherwise, look at other types of assignment.
1846 let assigned_from = match rvalue {
1847 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1848 Rvalue::Use(operand) => match operand {
1849 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1857 "annotate_argument_and_return_for_borrow: \
1858 assigned_from={:?}",
1862 // Find the local from the rvalue.
1863 let assigned_from_local = match assigned_from.local() {
1864 Some(local) => local,
1868 "annotate_argument_and_return_for_borrow: \
1869 assigned_from_local={:?}",
1870 assigned_from_local,
1873 // Check if our local matches the target - if so, we've assigned our
1874 // borrow to a new place.
1875 if assigned_from_local != target {
1879 // If we assigned our `target` into a new place, then we should
1880 // check if it was the return place.
1882 "annotate_argument_and_return_for_borrow: \
1883 assigned_from_local={:?} assigned_to={:?}",
1884 assigned_from_local, assigned_to
1886 if *assigned_to == mir::RETURN_PLACE {
1887 // If it was then return the annotated closure if there was one,
1888 // else, annotate this function.
1889 return annotated_closure.or_else(fallback);
1892 // If we didn't assign into the return place, then we just update
1894 target = *assigned_to;
1898 // Check the terminator if we didn't find anything in the statements.
1899 let terminator = &self.mir[location.block].terminator();
1901 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1904 if let TerminatorKind::Call {
1905 destination: Some((Place::Local(assigned_to), _)),
1908 } = &terminator.kind
1911 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1914 for operand in args {
1915 let assigned_from = match operand {
1916 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1922 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1926 if let Some(assigned_from_local) = assigned_from.local() {
1928 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1929 assigned_from_local,
1932 if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1933 return annotated_closure.or_else(fallback);
1940 // If we haven't found an assignment into the return place, then we need not add
1942 debug!("annotate_argument_and_return_for_borrow: none found");
1946 /// Annotate the first argument and return type of a function signature if they are
1951 sig: ty::PolyFnSig<'tcx>,
1952 ) -> Option<AnnotatedBorrowFnSignature> {
1953 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1954 let is_closure = self.infcx.tcx.is_closure(did);
1955 let fn_node_id = self.infcx.tcx.hir().as_local_node_id(did)?;
1956 let fn_decl = self.infcx.tcx.hir().fn_decl(fn_node_id)?;
1958 // We need to work out which arguments to highlight. We do this by looking
1959 // at the return type, where there are three cases:
1961 // 1. If there are named arguments, then we should highlight the return type and
1962 // highlight any of the arguments that are also references with that lifetime.
1963 // If there are no arguments that have the same lifetime as the return type,
1964 // then don't highlight anything.
1965 // 2. The return type is a reference with an anonymous lifetime. If this is
1966 // the case, then we can take advantage of (and teach) the lifetime elision
1969 // We know that an error is being reported. So the arguments and return type
1970 // must satisfy the elision rules. Therefore, if there is a single argument
1971 // then that means the return type and first (and only) argument have the same
1972 // lifetime and the borrow isn't meeting that, we can highlight the argument
1975 // If there are multiple arguments then the first argument must be self (else
1976 // it would not satisfy the elision rules), so we can highlight self and the
1978 // 3. The return type is not a reference. In this case, we don't highlight
1980 let return_ty = sig.output();
1981 match return_ty.skip_binder().sty {
1982 ty::TyKind::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1983 // This is case 1 from above, return type is a named reference so we need to
1984 // search for relevant arguments.
1985 let mut arguments = Vec::new();
1986 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1987 if let ty::TyKind::Ref(argument_region, _, _) = argument.sty {
1988 if argument_region == return_region {
1989 // Need to use the `rustc::ty` types to compare against the
1990 // `return_region`. Then use the `rustc::hir` type to get only
1991 // the lifetime span.
1992 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
1993 // With access to the lifetime, we can get
1995 arguments.push((*argument, lifetime.span));
1997 bug!("ty type is a ref but hir type is not");
2003 // We need to have arguments. This shouldn't happen, but it's worth checking.
2004 if arguments.is_empty() {
2008 // We use a mix of the HIR and the Ty types to get information
2009 // as the HIR doesn't have full types for closure arguments.
2010 let return_ty = *sig.output().skip_binder();
2011 let mut return_span = fn_decl.output.span();
2012 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
2013 if let hir::TyKind::Rptr(lifetime, _) = ty.into_inner().node {
2014 return_span = lifetime.span;
2018 Some(AnnotatedBorrowFnSignature::NamedFunction {
2024 ty::TyKind::Ref(_, _, _) if is_closure => {
2025 // This is case 2 from above but only for closures, return type is anonymous
2026 // reference so we select
2027 // the first argument.
2028 let argument_span = fn_decl.inputs.first()?.span;
2029 let argument_ty = sig.inputs().skip_binder().first()?;
2031 // Closure arguments are wrapped in a tuple, so we need to get the first
2033 if let ty::TyKind::Tuple(elems) = argument_ty.sty {
2034 let argument_ty = elems.first()?;
2035 if let ty::TyKind::Ref(_, _, _) = argument_ty.sty {
2036 return Some(AnnotatedBorrowFnSignature::Closure {
2045 ty::TyKind::Ref(_, _, _) => {
2046 // This is also case 2 from above but for functions, return type is still an
2047 // anonymous reference so we select the first argument.
2048 let argument_span = fn_decl.inputs.first()?.span;
2049 let argument_ty = sig.inputs().skip_binder().first()?;
2051 let return_span = fn_decl.output.span();
2052 let return_ty = *sig.output().skip_binder();
2054 // We expect the first argument to be a reference.
2055 match argument_ty.sty {
2056 ty::TyKind::Ref(_, _, _) => {}
2060 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2068 // This is case 3 from above, return type is not a reference so don't highlight
2077 enum AnnotatedBorrowFnSignature<'tcx> {
2079 arguments: Vec<(ty::Ty<'tcx>, Span)>,
2080 return_ty: ty::Ty<'tcx>,
2084 argument_ty: ty::Ty<'tcx>,
2085 argument_span: Span,
2086 return_ty: ty::Ty<'tcx>,
2090 argument_ty: ty::Ty<'tcx>,
2091 argument_span: Span,
2095 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2096 /// Annotate the provided diagnostic with information about borrow from the fn signature that
2098 fn emit(&self, diag: &mut DiagnosticBuilder<'_>) -> String {
2100 AnnotatedBorrowFnSignature::Closure {
2106 format!("has type `{}`", self.get_name_for_ty(argument_ty, 0)),
2109 self.get_region_name_for_ty(argument_ty, 0)
2111 AnnotatedBorrowFnSignature::AnonymousFunction {
2117 let argument_ty_name = self.get_name_for_ty(argument_ty, 0);
2118 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2120 let return_ty_name = self.get_name_for_ty(return_ty, 0);
2121 let types_equal = return_ty_name == argument_ty_name;
2126 if types_equal { "also " } else { "" },
2132 "argument and return type have the same lifetime due to lifetime elision rules",
2135 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch10-03-\
2136 lifetime-syntax.html#lifetime-elision>",
2139 self.get_region_name_for_ty(return_ty, 0)
2141 AnnotatedBorrowFnSignature::NamedFunction {
2146 // Region of return type and arguments checked to be the same earlier.
2147 let region_name = self.get_region_name_for_ty(return_ty, 0);
2148 for (_, argument_span) in arguments {
2149 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2154 format!("also has lifetime `{}`", region_name,),
2158 "use data from the highlighted arguments which match the `{}` lifetime of \
2168 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
2169 /// name where required.
2170 fn get_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
2171 // We need to add synthesized lifetimes where appropriate. We do
2172 // this by hooking into the pretty printer and telling it to label the
2173 // lifetimes without names with the value `'0`.
2175 ty::TyKind::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
2177 ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
2180 ) => RegionHighlightMode::highlighting_bound_region(*br, counter, || ty.to_string()),
2181 _ => ty.to_string(),
2185 /// Return the name of the provided `Ty` (that must be a reference)'s region with a
2186 /// synthesized lifetime name where required.
2187 fn get_region_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
2189 ty::TyKind::Ref(region, _, _) => match region {
2190 ty::RegionKind::ReLateBound(_, br)
2191 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
2192 RegionHighlightMode::highlighting_bound_region(
2195 || region.to_string(),
2198 _ => region.to_string(),
2200 _ => bug!("ty for annotation of borrow region is not a reference"),
2205 // The span(s) associated to a use of a place.
2206 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2207 pub(super) enum UseSpans {
2208 // The access is caused by capturing a variable for a closure.
2210 // This is true if the captured variable was from a generator.
2212 // The span of the args of the closure, including the `move` keyword if
2215 // The span of the first use of the captured variable inside the closure.
2218 // This access has a single span associated to it: common case.
2223 pub(super) fn args_or_use(self) -> Span {
2225 UseSpans::ClosureUse {
2228 | UseSpans::OtherUse(span) => span,
2232 pub(super) fn var_or_use(self) -> Span {
2234 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
2238 // Add a span label to the arguments of the closure, if it exists.
2239 pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
2240 if let UseSpans::ClosureUse { args_span, .. } = self {
2241 err.span_label(args_span, message);
2245 // Add a span label to the use of the captured variable, if it exists.
2246 pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
2247 if let UseSpans::ClosureUse { var_span, .. } = self {
2248 err.span_label(var_span, message);
2252 /// Return `false` if this place is not used in a closure.
2253 fn for_closure(&self) -> bool {
2255 UseSpans::ClosureUse { is_generator, .. } => !is_generator,
2260 /// Return `false` if this place is not used in a generator.
2261 fn for_generator(&self) -> bool {
2263 UseSpans::ClosureUse { is_generator, .. } => is_generator,
2268 /// Describe the span associated with a use of a place.
2269 fn describe(&self) -> String {
2271 UseSpans::ClosureUse { is_generator, .. } => if is_generator {
2272 " in generator".to_string()
2274 " in closure".to_string()
2276 _ => "".to_string(),
2280 pub(super) fn or_else<F>(self, if_other: F) -> Self
2282 F: FnOnce() -> Self,
2285 closure @ UseSpans::ClosureUse { .. } => closure,
2286 UseSpans::OtherUse(_) => if_other(),
2291 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2292 /// Finds the spans associated to a move or copy of move_place at location.
2293 pub(super) fn move_spans(
2295 moved_place: &Place<'tcx>, // Could also be an upvar.
2298 use self::UseSpans::*;
2300 let stmt = match self.mir[location.block].statements.get(location.statement_index) {
2302 None => return OtherUse(self.mir.source_info(location).span),
2305 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
2306 if let StatementKind::Assign(
2308 box Rvalue::Aggregate(ref kind, ref places)
2310 let (def_id, is_generator) = match kind {
2311 box AggregateKind::Closure(def_id, _) => (def_id, false),
2312 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2313 _ => return OtherUse(stmt.source_info.span),
2317 "move_spans: def_id={:?} is_generator={:?} places={:?}",
2318 def_id, is_generator, places
2320 if let Some((args_span, var_span)) = self.closure_span(*def_id, moved_place, places) {
2329 OtherUse(stmt.source_info.span)
2332 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
2333 /// and its usage of the local assigned at `location`.
2334 /// This is done by searching in statements succeeding `location`
2335 /// and originating from `maybe_closure_span`.
2336 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
2337 use self::UseSpans::*;
2338 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
2340 let target = match self.mir[location.block]
2342 .get(location.statement_index)
2345 kind: StatementKind::Assign(Place::Local(local), _),
2348 _ => return OtherUse(use_span),
2351 if self.mir.local_kind(target) != LocalKind::Temp {
2352 // operands are always temporaries.
2353 return OtherUse(use_span);
2356 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
2357 if let StatementKind::Assign(
2358 _, box Rvalue::Aggregate(ref kind, ref places)
2360 let (def_id, is_generator) = match kind {
2361 box AggregateKind::Closure(def_id, _) => (def_id, false),
2362 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2367 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
2368 def_id, is_generator, places
2370 if let Some((args_span, var_span)) = self.closure_span(
2371 *def_id, &Place::Local(target), places
2379 return OtherUse(use_span);
2383 if use_span != stmt.source_info.span {
2391 /// Finds the span of a captured variable within a closure or generator.
2395 target_place: &Place<'tcx>,
2396 places: &Vec<Operand<'tcx>>,
2397 ) -> Option<(Span, Span)> {
2399 "closure_span: def_id={:?} target_place={:?} places={:?}",
2400 def_id, target_place, places
2402 let node_id = self.infcx.tcx.hir().as_local_node_id(def_id)?;
2403 let expr = &self.infcx.tcx.hir().expect_expr(node_id).node;
2404 debug!("closure_span: node_id={:?} expr={:?}", node_id, expr);
2405 if let hir::ExprKind::Closure(
2408 let var_span = self.infcx.tcx.with_freevars(
2411 for (v, place) in freevars.iter().zip(places) {
2413 Operand::Copy(place) |
2414 Operand::Move(place) if target_place == place => {
2415 debug!("closure_span: found captured local {:?}", place);
2416 return Some(v.span);
2426 Some((*args_span, var_span))
2432 /// Helper to retrieve span(s) of given borrow from the current MIR
2434 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans {
2435 let span = self.mir.source_info(borrow.reserve_location).span;
2436 self.borrow_spans(span, borrow.reserve_location)