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;
6 use rustc::hir::def::Namespace;
7 use rustc::hir::def_id::DefId;
8 use rustc::middle::region::ScopeTree;
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,
15 use rustc::ty::{self, DefIdTree, Ty};
16 use rustc::ty::layout::VariantIdx;
17 use rustc::ty::print::Print;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_data_structures::indexed_vec::Idx;
20 use rustc_errors::{Applicability, DiagnosticBuilder};
22 use syntax::source_map::CompilerDesugaringKind;
23 use syntax::symbol::sym;
25 use super::borrow_set::BorrowData;
26 use super::{MirBorrowckCtxt};
27 use super::{InitializationRequiringAction, PrefixSet};
28 use crate::dataflow::drop_flag_effects;
29 use crate::dataflow::indexes::{MovePathIndex, MoveOutIndex};
30 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
34 /// Index of the "move out" that we found. The `MoveData` can
35 /// then tell us where the move occurred.
38 /// `true` if we traversed a back edge while walking from the point
39 /// of error to the move site.
40 traversed_back_edge: bool
43 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
44 pub(super) fn report_use_of_moved_or_uninitialized(
47 desired_action: InitializationRequiringAction,
48 (moved_place, used_place, span): (&Place<'tcx>, &Place<'tcx>, Span),
52 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
53 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
54 location, desired_action, moved_place, used_place, span, mpi
57 let use_spans = self.move_spans(moved_place, location)
58 .or_else(|| self.borrow_spans(span, location));
59 let span = use_spans.args_or_use();
61 let move_site_vec = self.get_moved_indexes(location, mpi);
63 "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
66 let move_out_indices: Vec<_> = move_site_vec
68 .map(|move_site| move_site.moi)
71 if move_out_indices.is_empty() {
72 let root_place = self.prefixes(&used_place, PrefixSet::All).last().unwrap();
74 if self.uninitialized_error_reported.contains(root_place) {
76 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
82 self.uninitialized_error_reported.insert(root_place.clone());
84 let item_msg = match self.describe_place_with_options(used_place,
85 IncludingDowncast(true)) {
86 Some(name) => format!("`{}`", name),
87 None => "value".to_owned(),
89 let mut err = self.infcx.tcx.cannot_act_on_uninitialized_variable(
91 desired_action.as_noun(),
92 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
93 .unwrap_or_else(|| "_".to_owned()),
96 err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
98 use_spans.var_span_label(
100 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
103 err.buffer(&mut self.errors_buffer);
105 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
106 if self.prefixes(&reported_place, PrefixSet::All)
107 .any(|p| p == used_place)
110 "report_use_of_moved_or_uninitialized place: error suppressed \
118 let msg = ""; //FIXME: add "partially " or "collaterally "
120 let mut err = self.infcx.tcx.cannot_act_on_moved_value(
122 desired_action.as_noun(),
124 self.describe_place_with_options(&moved_place, IncludingDowncast(true)),
128 self.add_moved_or_invoked_closure_note(
134 let mut is_loop_move = false;
135 let is_partial_move = move_site_vec.iter().any(|move_site| {
136 let move_out = self.move_data.moves[(*move_site).moi];
137 let moved_place = &self.move_data.move_paths[move_out.path].place;
138 used_place != moved_place && used_place.is_prefix_of(moved_place)
140 for move_site in &move_site_vec {
141 let move_out = self.move_data.moves[(*move_site).moi];
142 let moved_place = &self.move_data.move_paths[move_out.path].place;
144 let move_spans = self.move_spans(moved_place, move_out.source);
145 let move_span = move_spans.args_or_use();
147 let move_msg = if move_spans.for_closure() {
153 if span == move_span {
156 format!("value moved{} here, in previous iteration of loop", move_msg),
158 if Some(CompilerDesugaringKind::ForLoop) == span.compiler_desugaring_kind() {
159 if let Ok(snippet) = self.infcx.tcx.sess.source_map()
160 .span_to_snippet(span)
164 "consider borrowing this to avoid moving it into the for loop",
165 format!("&{}", snippet),
166 Applicability::MaybeIncorrect,
171 } else if move_site.traversed_back_edge {
175 "value moved{} here, in previous iteration of loop",
180 err.span_label(move_span, format!("value moved{} here", move_msg));
181 move_spans.var_span_label(
183 format!("variable moved due to use{}", move_spans.describe()),
188 use_spans.var_span_label(
190 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
198 desired_action.as_verb_in_past_tense(),
199 if is_partial_move { "after partial move" } else { "after move" },
204 let ty = used_place.ty(self.mir, self.infcx.tcx).ty;
205 let needs_note = match ty.sty {
206 ty::Closure(id, _) => {
207 let tables = self.infcx.tcx.typeck_tables_of(id);
208 let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
210 tables.closure_kind_origins().get(hir_id).is_none()
216 let mpi = self.move_data.moves[move_out_indices[0]].path;
217 let place = &self.move_data.move_paths[mpi].place;
219 let ty = place.ty(self.mir, self.infcx.tcx).ty;
220 let opt_name = self.describe_place_with_options(place, IncludingDowncast(true));
221 let note_msg = match opt_name {
222 Some(ref name) => format!("`{}`", name),
223 None => "value".to_owned(),
225 if let ty::Param(param_ty) = ty.sty {
226 let tcx = self.infcx.tcx;
227 let generics = tcx.generics_of(self.mir_def_id);
228 let def_id = generics.type_param(¶m_ty, tcx).def_id;
229 if let Some(sp) = tcx.hir().span_if_local(def_id) {
232 "consider adding a `Copy` constraint to this type argument",
236 if let Place::Base(PlaceBase::Local(local)) = place {
237 let decl = &self.mir.local_decls[*local];
239 decl.source_info.span,
241 "move occurs because {} has type `{}`, \
242 which does not implement the `Copy` trait",
247 "move occurs because {} has type `{}`, \
248 which does not implement the `Copy` trait",
254 if let Some((_, mut old_err)) = self.move_error_reported
255 .insert(move_out_indices, (used_place.clone(), err))
257 // Cancel the old error so it doesn't ICE.
263 pub(super) fn report_move_out_while_borrowed(
266 (place, span): (&Place<'tcx>, Span),
267 borrow: &BorrowData<'tcx>,
270 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
271 location, place, span, borrow
273 let tcx = self.infcx.tcx;
274 let value_msg = match self.describe_place(place) {
275 Some(name) => format!("`{}`", name),
276 None => "value".to_owned(),
278 let borrow_msg = match self.describe_place(&borrow.borrowed_place) {
279 Some(name) => format!("`{}`", name),
280 None => "value".to_owned(),
283 let borrow_spans = self.retrieve_borrow_spans(borrow);
284 let borrow_span = borrow_spans.args_or_use();
286 let move_spans = self.move_spans(place, location);
287 let span = move_spans.args_or_use();
289 let mut err = tcx.cannot_move_when_borrowed(
291 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
294 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
295 err.span_label(span, format!("move out of {} occurs here", value_msg));
297 borrow_spans.var_span_label(
299 format!("borrow occurs due to use{}", borrow_spans.describe())
302 move_spans.var_span_label(
304 format!("move occurs due to use{}", move_spans.describe())
307 self.explain_why_borrow_contains_point(
311 ).add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", Some(borrow_span));
312 err.buffer(&mut self.errors_buffer);
315 pub(super) fn report_use_while_mutably_borrowed(
318 (place, _span): (&Place<'tcx>, Span),
319 borrow: &BorrowData<'tcx>,
320 ) -> DiagnosticBuilder<'cx> {
321 let tcx = self.infcx.tcx;
323 let borrow_spans = self.retrieve_borrow_spans(borrow);
324 let borrow_span = borrow_spans.args_or_use();
326 // Conflicting borrows are reported separately, so only check for move
328 let use_spans = self.move_spans(place, location);
329 let span = use_spans.var_or_use();
331 let mut err = tcx.cannot_use_when_mutably_borrowed(
333 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
335 &self.describe_place(&borrow.borrowed_place)
336 .unwrap_or_else(|| "_".to_owned()),
340 borrow_spans.var_span_label(&mut err, {
341 let place = &borrow.borrowed_place;
342 let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
344 format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
347 self.explain_why_borrow_contains_point(location, borrow, None)
348 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
352 pub(super) fn report_conflicting_borrow(
355 (place, span): (&Place<'tcx>, Span),
356 gen_borrow_kind: BorrowKind,
357 issued_borrow: &BorrowData<'tcx>,
358 ) -> DiagnosticBuilder<'cx> {
359 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
360 let issued_span = issued_spans.args_or_use();
362 let borrow_spans = self.borrow_spans(span, location);
363 let span = borrow_spans.args_or_use();
365 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
371 let (desc_place, msg_place, msg_borrow, union_type_name) =
372 self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
374 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
375 let second_borrow_desc = if explanation.is_explained() {
381 // FIXME: supply non-"" `opt_via` when appropriate
382 let tcx = self.infcx.tcx;
383 let first_borrow_desc;
384 let mut err = match (
392 (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
393 first_borrow_desc = "mutable ";
394 tcx.cannot_reborrow_already_borrowed(
407 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
408 first_borrow_desc = "immutable ";
409 tcx.cannot_reborrow_already_borrowed(
423 (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
424 first_borrow_desc = "first ";
425 tcx.cannot_mutably_borrow_multiply(
436 (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
437 first_borrow_desc = "first ";
438 tcx.cannot_uniquely_borrow_by_two_closures(
447 (BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
448 | (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
449 let mut err = tcx.cannot_mutate_in_match_guard(
456 borrow_spans.var_span_label(
459 "borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe()
466 (BorrowKind::Unique, _, _, _, _, _) => {
467 first_borrow_desc = "first ";
468 tcx.cannot_uniquely_borrow_by_one_closure(
481 (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
482 first_borrow_desc = "first ";
483 tcx.cannot_reborrow_already_uniquely_borrowed(
497 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
498 first_borrow_desc = "first ";
499 tcx.cannot_reborrow_already_uniquely_borrowed(
513 (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
514 | (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
515 | (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _)
516 | (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
517 | (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
518 | (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
521 if issued_spans == borrow_spans {
522 borrow_spans.var_span_label(
524 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
527 let borrow_place = &issued_borrow.borrowed_place;
528 let borrow_place_desc = self.describe_place(borrow_place)
529 .unwrap_or_else(|| "_".to_owned());
530 issued_spans.var_span_label(
533 "first borrow occurs due to use of `{}`{}",
535 issued_spans.describe(),
539 borrow_spans.var_span_label(
542 "second borrow occurs due to use of `{}`{}",
544 borrow_spans.describe(),
549 if union_type_name != "" {
551 "`{}` is a field of the union `{}`, so it overlaps the field `{}`",
552 msg_place, union_type_name, msg_borrow,
556 explanation.add_explanation_to_diagnostic(
567 /// Returns the description of the root place for a conflicting borrow and the full
568 /// descriptions of the places that caused the conflict.
570 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
571 /// attempted while a shared borrow is live, then this function will return:
575 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
576 /// a shared borrow of another field `x.y`, then this function will return:
578 /// ("x", "x.z", "x.y")
580 /// In the more complex union case, where the union is a field of a struct, then if a mutable
581 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
582 /// another field `x.u.y`, then this function will return:
584 /// ("x.u", "x.u.z", "x.u.y")
586 /// This is used when creating error messages like below:
588 /// > cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
589 /// > mutable (via `a.u.s.b`) [E0502]
590 pub(super) fn describe_place_for_conflicting_borrow(
592 first_borrowed_place: &Place<'tcx>,
593 second_borrowed_place: &Place<'tcx>,
594 ) -> (String, String, String, String) {
595 // Define a small closure that we can use to check if the type of a place
597 let is_union = |place: &Place<'tcx>| -> bool {
598 place.ty(self.mir, self.infcx.tcx).ty
600 .map(|adt| adt.is_union())
604 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
605 // code duplication (particularly around returning an empty description in the failure
609 // If we have a conflicting borrow of the same place, then we don't want to add
610 // an extraneous "via x.y" to our diagnostics, so filter out this case.
611 first_borrowed_place != second_borrowed_place
614 // We're going to want to traverse the first borrowed place to see if we can find
615 // field access to a union. If we find that, then we will keep the place of the
616 // union being accessed and the field that was being accessed so we can check the
617 // second borrowed place for the same union and a access to a different field.
618 let mut current = first_borrowed_place;
619 while let Place::Projection(box PlaceProjection { base, elem }) = current {
621 ProjectionElem::Field(field, _) if is_union(base) => {
622 return Some((base, field));
629 .and_then(|(target_base, target_field)| {
630 // With the place of a union and a field access into it, we traverse the second
631 // borrowed place and look for a access to a different field of the same union.
632 let mut current = second_borrowed_place;
633 while let Place::Projection(box PlaceProjection { base, elem }) = current {
635 ProjectionElem::Field(field, _) if {
636 is_union(base) && field != target_field && base == target_base
638 let desc_base = self.describe_place(base)
639 .unwrap_or_else(|| "_".to_owned());
640 let desc_first = self.describe_place(first_borrowed_place)
641 .unwrap_or_else(|| "_".to_owned());
642 let desc_second = self.describe_place(second_borrowed_place)
643 .unwrap_or_else(|| "_".to_owned());
645 // Also compute the name of the union type, eg. `Foo` so we
646 // can add a helpful note with it.
647 let ty = base.ty(self.mir, self.infcx.tcx).ty;
649 return Some((desc_base, desc_first, desc_second, ty.to_string()));
657 // If we didn't find a field access into a union, or both places match, then
658 // only return the description of the first place.
659 let desc_place = self.describe_place(first_borrowed_place)
660 .unwrap_or_else(|| "_".to_owned());
661 (desc_place, "".to_string(), "".to_string(), "".to_string())
665 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
667 /// This means that some data referenced by `borrow` needs to live
668 /// past the point where the StorageDeadOrDrop of `place` occurs.
669 /// This is usually interpreted as meaning that `place` has too
670 /// short a lifetime. (But sometimes it is more useful to report
671 /// it as a more direct conflict between the execution of a
672 /// `Drop::drop` with an aliasing borrow.)
673 pub(super) fn report_borrowed_value_does_not_live_long_enough(
676 borrow: &BorrowData<'tcx>,
677 place_span: (&Place<'tcx>, Span),
678 kind: Option<WriteKind>,
681 "report_borrowed_value_does_not_live_long_enough(\
682 {:?}, {:?}, {:?}, {:?}\
684 location, borrow, place_span, kind
687 let drop_span = place_span.1;
688 let scope_tree = self.infcx.tcx.region_scope_tree(self.mir_def_id);
689 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
693 let borrow_spans = self.retrieve_borrow_spans(borrow);
694 let borrow_span = borrow_spans.var_or_use();
696 let proper_span = match *root_place {
697 Place::Base(PlaceBase::Local(local)) => self.mir.local_decls[local].source_info.span,
701 if self.access_place_error_reported
702 .contains(&(root_place.clone(), borrow_span))
705 "suppressing access_place error when borrow doesn't live long enough for {:?}",
711 self.access_place_error_reported
712 .insert((root_place.clone(), borrow_span));
714 if let StorageDeadOrDrop::Destructor(dropped_ty) =
715 self.classify_drop_access_kind(&borrow.borrowed_place)
717 // If a borrow of path `B` conflicts with drop of `D` (and
718 // we're not in the uninteresting case where `B` is a
719 // prefix of `D`), then report this as a more interesting
720 // destructor conflict.
721 if !borrow.borrowed_place.is_prefix_of(place_span.0) {
722 self.report_borrow_conflicts_with_destructor(
723 location, borrow, place_span, kind, dropped_ty,
729 let place_desc = self.describe_place(&borrow.borrowed_place);
731 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
732 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
734 let err = match (place_desc, explanation) {
735 (Some(_), _) if self.is_place_thread_local(root_place) => {
736 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
738 // If the outlives constraint comes from inside the closure,
743 // Box::new(|| y) as Box<Fn() -> &'static i32>
745 // then just use the normal error. The closure isn't escaping
746 // and `move` will not help here.
749 BorrowExplanation::MustBeValidFor {
750 category: category @ ConstraintCategory::Return,
759 BorrowExplanation::MustBeValidFor {
760 category: category @ ConstraintCategory::CallArgument,
766 ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
767 borrow_spans.args_or_use(),
772 &format!("`{}`", name),
776 BorrowExplanation::MustBeValidFor {
777 category: ConstraintCategory::Assignment,
779 region_name: RegionName {
780 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
786 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
787 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
796 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
807 err.buffer(&mut self.errors_buffer);
810 fn report_local_value_does_not_live_long_enough(
814 scope_tree: &'tcx ScopeTree,
815 borrow: &BorrowData<'tcx>,
817 borrow_spans: UseSpans,
818 explanation: BorrowExplanation,
819 ) -> DiagnosticBuilder<'cx> {
821 "report_local_value_does_not_live_long_enough(\
822 {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
824 location, name, scope_tree, borrow, drop_span, borrow_spans
827 let borrow_span = borrow_spans.var_or_use();
828 if let BorrowExplanation::MustBeValidFor {
835 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
840 opt_place_desc.as_ref(),
846 let mut err = self.infcx.tcx.path_does_not_live_long_enough(
848 &format!("`{}`", name),
852 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
853 let region_name = annotation.emit(self, &mut err);
857 format!("`{}` would have to be valid for `{}`...", name, region_name),
860 if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
864 "...but `{}` will be dropped here, when the function `{}` returns",
866 self.infcx.tcx.hir().name_by_hir_id(fn_hir_id),
871 "functions cannot return a borrow to data owned within the function's scope, \
872 functions can only return borrows to data passed as arguments",
875 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
876 references-and-borrowing.html#dangling-references>",
881 format!("...but `{}` dropped here while still borrowed", name),
885 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
887 explanation.add_explanation_to_diagnostic(
896 err.span_label(borrow_span, "borrowed value does not live long enough");
899 format!("`{}` dropped here while still borrowed", name),
902 let within = if borrow_spans.for_generator() {
908 borrow_spans.args_span_label(
910 format!("value captured here{}", within),
913 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
919 fn report_borrow_conflicts_with_destructor(
922 borrow: &BorrowData<'tcx>,
923 (place, drop_span): (&Place<'tcx>, Span),
924 kind: Option<WriteKind>,
925 dropped_ty: Ty<'tcx>,
928 "report_borrow_conflicts_with_destructor(\
929 {:?}, {:?}, ({:?}, {:?}), {:?}\
931 location, borrow, place, drop_span, kind,
934 let borrow_spans = self.retrieve_borrow_spans(borrow);
935 let borrow_span = borrow_spans.var_or_use();
937 let mut err = self.infcx
939 .cannot_borrow_across_destructor(borrow_span, Origin::Mir);
941 let what_was_dropped = match self.describe_place(place) {
942 Some(name) => format!("`{}`", name.as_str()),
943 None => String::from("temporary value"),
946 let label = match self.describe_place(&borrow.borrowed_place) {
947 Some(borrowed) => format!(
948 "here, drop of {D} needs exclusive access to `{B}`, \
949 because the type `{T}` implements the `Drop` trait",
950 D = what_was_dropped,
955 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
956 D = what_was_dropped,
960 err.span_label(drop_span, label);
962 // Only give this note and suggestion if they could be relevant.
964 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
966 BorrowExplanation::UsedLater { .. }
967 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
968 err.note("consider using a `let` binding to create a longer lived value");
973 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
975 err.buffer(&mut self.errors_buffer);
978 fn report_thread_local_value_does_not_live_long_enough(
982 ) -> DiagnosticBuilder<'cx> {
984 "report_thread_local_value_does_not_live_long_enough(\
987 drop_span, borrow_span
990 let mut err = self.infcx
992 .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
996 "thread-local variables cannot be borrowed beyond the end of the function",
998 err.span_label(drop_span, "end of enclosing function is here");
1003 fn report_temporary_value_does_not_live_long_enough(
1006 scope_tree: &'tcx ScopeTree,
1007 borrow: &BorrowData<'tcx>,
1009 borrow_spans: UseSpans,
1011 explanation: BorrowExplanation,
1012 ) -> DiagnosticBuilder<'cx> {
1014 "report_temporary_value_does_not_live_long_enough(\
1015 {:?}, {:?}, {:?}, {:?}, {:?}\
1017 location, scope_tree, borrow, drop_span, proper_span
1020 if let BorrowExplanation::MustBeValidFor {
1023 from_closure: false,
1026 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1037 let tcx = self.infcx.tcx;
1038 let mut err = tcx.temporary_value_borrowed_for_too_long(proper_span, Origin::Mir);
1041 "creates a temporary which is freed while still in use",
1045 "temporary value is freed at the end of this statement",
1049 BorrowExplanation::UsedLater(..)
1050 | BorrowExplanation::UsedLaterInLoop(..)
1051 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1052 // Only give this note and suggestion if it could be relevant.
1053 err.note("consider using a `let` binding to create a longer lived value");
1057 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
1059 let within = if borrow_spans.for_generator() {
1065 borrow_spans.args_span_label(
1067 format!("value captured here{}", within),
1073 fn try_report_cannot_return_reference_to_local(
1075 borrow: &BorrowData<'tcx>,
1078 category: ConstraintCategory,
1079 opt_place_desc: Option<&String>,
1080 ) -> Option<DiagnosticBuilder<'cx>> {
1081 let tcx = self.infcx.tcx;
1083 let return_kind = match category {
1084 ConstraintCategory::Return => "return",
1085 ConstraintCategory::Yield => "yield",
1089 // FIXME use a better heuristic than Spans
1090 let reference_desc = if return_span == self.mir.source_info(borrow.reserve_location).span {
1096 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1097 let local_kind = match borrow.borrowed_place {
1098 Place::Base(PlaceBase::Local(local)) => {
1099 match self.mir.local_kind(local) {
1100 LocalKind::ReturnPointer
1101 | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1102 LocalKind::Var => "local variable ",
1104 if !self.upvars.is_empty()
1105 && local == Local::new(1) => {
1106 "variable captured by `move` "
1109 "function parameter "
1116 format!("{}`{}`", local_kind, place_desc),
1117 format!("`{}` is borrowed here", place_desc),
1120 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
1123 let local = if let Place::Base(PlaceBase::Local(local)) = *root_place {
1126 bug!("try_report_cannot_return_reference_to_local: not a local")
1128 match self.mir.local_kind(local) {
1129 LocalKind::ReturnPointer | LocalKind::Temp => {
1131 "temporary value".to_string(),
1132 "temporary value created here".to_string(),
1137 "function parameter".to_string(),
1138 "function parameter borrowed here".to_string(),
1141 LocalKind::Var => bug!("local variable without a name"),
1145 let mut err = tcx.cannot_return_reference_to_local(
1153 if return_span != borrow_span {
1154 err.span_label(borrow_span, note);
1160 fn report_escaping_closure_capture(
1164 fr_name: &RegionName,
1165 category: ConstraintCategory,
1166 constraint_span: Span,
1168 ) -> DiagnosticBuilder<'cx> {
1169 let tcx = self.infcx.tcx;
1171 let mut err = tcx.cannot_capture_in_long_lived_closure(
1178 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1179 Ok(string) => format!("move {}", string),
1180 Err(_) => "move |<args>| <body>".to_string()
1183 err.span_suggestion(
1185 &format!("to force the closure to take ownership of {} (and any \
1186 other referenced variables), use the `move` keyword",
1189 Applicability::MachineApplicable,
1193 ConstraintCategory::Return => {
1194 err.span_note(constraint_span, "closure is returned here");
1196 ConstraintCategory::CallArgument => {
1197 fr_name.highlight_region_name(&mut err);
1200 &format!("function requires argument type to outlive `{}`", fr_name),
1203 _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1204 category: `{:?}`", category),
1209 fn report_escaping_data(
1212 name: &Option<String>,
1216 ) -> DiagnosticBuilder<'cx> {
1217 let tcx = self.infcx.tcx;
1219 let escapes_from = if tcx.is_closure(self.mir_def_id) {
1220 let tables = tcx.typeck_tables_of(self.mir_def_id);
1221 let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1222 match tables.node_type(mir_hir_id).sty {
1223 ty::Closure(..) => "closure",
1224 ty::Generator(..) => "generator",
1225 _ => bug!("Closure body doesn't have a closure or generator type"),
1231 let mut err = tcx.borrowed_data_escapes_closure(escape_span, escapes_from, Origin::Mir);
1236 "`{}` is declared here, outside of the {} body",
1237 upvar_name, escapes_from
1244 "borrow is only valid in the {} body",
1249 if let Some(name) = name {
1252 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1257 format!("reference escapes the {} body here", escapes_from),
1264 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1267 let mut stack = Vec::new();
1268 stack.extend(mir.predecessor_locations(location).map(|predecessor| {
1269 let is_back_edge = location.dominates(predecessor, &self.dominators);
1270 (predecessor, is_back_edge)
1273 let mut visited = FxHashSet::default();
1274 let mut result = vec![];
1276 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1278 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1279 location, is_back_edge
1282 if !visited.insert(location) {
1287 let stmt_kind = mir[location.block]
1289 .get(location.statement_index)
1291 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1292 // this analysis only tries to find moves explicitly
1293 // written by the user, so we ignore the move-outs
1294 // created by `StorageDead` and at the beginning
1297 // If we are found a use of a.b.c which was in error, then we want to look for
1298 // moves not only of a.b.c but also a.b and a.
1300 // Note that the moves data already includes "parent" paths, so we don't have to
1301 // worry about the other case: that is, if there is a move of a.b.c, it is already
1302 // marked as a move of a.b and a as well, so we will generate the correct errors
1304 let mut mpis = vec![mpi];
1305 let move_paths = &self.move_data.move_paths;
1306 mpis.extend(move_paths[mpi].parents(move_paths));
1308 for moi in &self.move_data.loc_map[location] {
1309 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1310 if mpis.contains(&self.move_data.moves[*moi].path) {
1311 debug!("report_use_of_moved_or_uninitialized: found");
1312 result.push(MoveSite {
1314 traversed_back_edge: is_back_edge,
1317 // Strictly speaking, we could continue our DFS here. There may be
1318 // other moves that can reach the point of error. But it is kind of
1319 // confusing to highlight them.
1327 // drop(a); // <-- current point of error
1330 // Because we stop the DFS here, we only highlight `let c = a`,
1331 // and not `let b = a`. We will of course also report an error at
1332 // `let c = a` which highlights `let b = a` as the move.
1339 let mut any_match = false;
1340 drop_flag_effects::for_location_inits(
1355 stack.extend(mir.predecessor_locations(location).map(|predecessor| {
1356 let back_edge = location.dominates(predecessor, &self.dominators);
1357 (predecessor, is_back_edge || back_edge)
1364 pub(super) fn report_illegal_mutation_of_borrowed(
1367 (place, span): (&Place<'tcx>, Span),
1368 loan: &BorrowData<'tcx>,
1370 let loan_spans = self.retrieve_borrow_spans(loan);
1371 let loan_span = loan_spans.args_or_use();
1373 let tcx = self.infcx.tcx;
1374 if loan.kind == BorrowKind::Shallow {
1375 let mut err = tcx.cannot_mutate_in_match_guard(
1378 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
1382 loan_spans.var_span_label(
1384 format!("borrow occurs due to use{}", loan_spans.describe()),
1387 err.buffer(&mut self.errors_buffer);
1392 let mut err = tcx.cannot_assign_to_borrowed(
1395 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
1399 loan_spans.var_span_label(
1401 format!("borrow occurs due to use{}", loan_spans.describe()),
1404 self.explain_why_borrow_contains_point(location, loan, None)
1405 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "", None);
1407 err.buffer(&mut self.errors_buffer);
1410 /// Reports an illegal reassignment; for example, an assignment to
1411 /// (part of) a non-`mut` local that occurs potentially after that
1412 /// local has already been initialized. `place` is the path being
1413 /// assigned; `err_place` is a place providing a reason why
1414 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1415 /// assignment to `x.f`).
1416 pub(super) fn report_illegal_reassignment(
1418 _location: Location,
1419 (place, span): (&Place<'tcx>, Span),
1420 assigned_span: Span,
1421 err_place: &Place<'tcx>,
1423 let (from_arg, local_decl) = if let Place::Base(PlaceBase::Local(local)) = *err_place {
1424 if let LocalKind::Arg = self.mir.local_kind(local) {
1425 (true, Some(&self.mir.local_decls[local]))
1427 (false, Some(&self.mir.local_decls[local]))
1433 // If root local is initialized immediately (everything apart from let
1434 // PATTERN;) then make the error refer to that local, rather than the
1435 // place being assigned later.
1436 let (place_description, assigned_span) = match local_decl {
1438 is_user_variable: Some(ClearCrossCrate::Clear),
1443 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1444 opt_match_place: None,
1450 is_user_variable: None,
1453 | None => (self.describe_place(place), assigned_span),
1454 Some(decl) => (self.describe_place(err_place), decl.source_info.span),
1457 let mut err = self.infcx.tcx.cannot_reassign_immutable(
1459 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1463 let msg = if from_arg {
1464 "cannot assign to immutable argument"
1466 "cannot assign twice to immutable variable"
1468 if span != assigned_span {
1470 let value_msg = match place_description {
1471 Some(name) => format!("`{}`", name),
1472 None => "value".to_owned(),
1474 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1477 if let Some(decl) = local_decl {
1478 if let Some(name) = decl.name {
1479 if decl.can_be_made_mutable() {
1480 err.span_suggestion(
1481 decl.source_info.span,
1482 "make this binding mutable",
1483 format!("mut {}", name),
1484 Applicability::MachineApplicable,
1489 err.span_label(span, msg);
1490 err.buffer(&mut self.errors_buffer);
1494 pub(super) struct IncludingDowncast(bool);
1496 /// Which case a StorageDeadOrDrop is for.
1497 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1498 enum StorageDeadOrDrop<'tcx> {
1501 Destructor(Ty<'tcx>),
1504 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1505 /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
1506 /// is moved after being invoked.
1509 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
1511 /// --> $DIR/issue-42065.rs:16:29
1513 /// LL | for (key, value) in dict {
1516 pub(super) fn add_moved_or_invoked_closure_note(
1519 place: &Place<'tcx>,
1520 diag: &mut DiagnosticBuilder<'_>,
1522 debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
1523 let mut target = place.local();
1524 for stmt in &self.mir[location.block].statements[location.statement_index..] {
1525 debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
1526 if let StatementKind::Assign(into, box Rvalue::Use(from)) = &stmt.kind {
1527 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
1529 Operand::Copy(ref place) |
1530 Operand::Move(ref place) if target == place.local() =>
1531 target = into.local(),
1537 // Check if we are attempting to call a closure after it has been invoked.
1538 let terminator = self.mir[location.block].terminator();
1539 debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
1540 if let TerminatorKind::Call {
1541 func: Operand::Constant(box Constant {
1542 literal: ty::Const {
1543 ty: &ty::TyS { sty: ty::FnDef(id, _), .. },
1550 } = &terminator.kind {
1551 debug!("add_moved_or_invoked_closure_note: id={:?}", id);
1552 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
1553 let closure = match args.first() {
1554 Some(Operand::Copy(ref place)) |
1555 Some(Operand::Move(ref place)) if target == place.local() =>
1556 place.local().unwrap(),
1560 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
1561 if let ty::Closure(did, _) = self.mir.local_decls[closure].ty.sty {
1562 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
1564 if let Some((span, name)) = self.infcx.tcx.typeck_tables_of(did)
1565 .closure_kind_origins()
1571 "closure cannot be invoked more than once because it moves the \
1572 variable `{}` out of its environment",
1582 // Check if we are just moving a closure after it has been invoked.
1583 if let Some(target) = target {
1584 if let ty::Closure(did, _) = self.mir.local_decls[target].ty.sty {
1585 let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
1587 if let Some((span, name)) = self.infcx.tcx.typeck_tables_of(did)
1588 .closure_kind_origins()
1594 "closure cannot be moved more than once as it is not `Copy` due to \
1595 moving the variable `{}` out of its environment",
1604 /// End-user visible description of `place` if one can be found. If the
1605 /// place is a temporary for instance, None will be returned.
1606 pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
1607 self.describe_place_with_options(place, IncludingDowncast(false))
1610 /// End-user visible description of `place` if one can be found. If the
1611 /// place is a temporary for instance, None will be returned.
1612 /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
1613 /// `Downcast` and `IncludingDowncast` is true
1614 pub(super) fn describe_place_with_options(
1616 place: &Place<'tcx>,
1617 including_downcast: IncludingDowncast,
1618 ) -> Option<String> {
1619 let mut buf = String::new();
1620 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
1621 Ok(()) => Some(buf),
1626 /// Appends end-user visible description of `place` to `buf`.
1627 fn append_place_to_string(
1629 place: &Place<'tcx>,
1631 mut autoderef: bool,
1632 including_downcast: &IncludingDowncast,
1633 ) -> Result<(), ()> {
1635 Place::Base(PlaceBase::Local(local)) => {
1636 self.append_local_to_string(local, buf)?;
1638 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_), .. })) => {
1639 buf.push_str("promoted");
1641 Place::Base(PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })) => {
1642 buf.push_str(&self.infcx.tcx.item_name(def_id).to_string());
1644 Place::Projection(ref proj) => {
1646 ProjectionElem::Deref => {
1647 let upvar_field_projection =
1648 self.is_upvar_field_projection(place);
1649 if let Some(field) = upvar_field_projection {
1650 let var_index = field.index();
1651 let name = self.upvars[var_index].name.to_string();
1652 if self.upvars[var_index].by_ref {
1653 buf.push_str(&name);
1655 buf.push_str(&format!("*{}", &name));
1659 self.append_place_to_string(
1663 &including_downcast,
1665 } else if let Place::Base(PlaceBase::Local(local)) = proj.base {
1666 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
1667 self.mir.local_decls[local].is_user_variable
1669 self.append_place_to_string(
1673 &including_downcast,
1677 self.append_place_to_string(
1681 &including_downcast,
1686 self.append_place_to_string(
1690 &including_downcast,
1695 ProjectionElem::Downcast(..) => {
1696 self.append_place_to_string(
1700 &including_downcast,
1702 if including_downcast.0 {
1706 ProjectionElem::Field(field, _ty) => {
1709 let upvar_field_projection =
1710 self.is_upvar_field_projection(place);
1711 if let Some(field) = upvar_field_projection {
1712 let var_index = field.index();
1713 let name = self.upvars[var_index].name.to_string();
1714 buf.push_str(&name);
1716 let field_name = self.describe_field(&proj.base, field);
1717 self.append_place_to_string(
1721 &including_downcast,
1723 buf.push_str(&format!(".{}", field_name));
1726 ProjectionElem::Index(index) => {
1729 self.append_place_to_string(
1733 &including_downcast,
1736 if self.append_local_to_string(index, buf).is_err() {
1741 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1743 // Since it isn't possible to borrow an element on a particular index and
1744 // then use another while the borrow is held, don't output indices details
1745 // to avoid confusing the end-user
1746 self.append_place_to_string(
1750 &including_downcast,
1752 buf.push_str(&"[..]");
1761 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
1762 /// a name, then `Err` is returned
1763 fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
1764 let local = &self.mir.local_decls[local_index];
1767 buf.push_str(&name.to_string());
1774 /// End-user visible description of the `field`nth field of `base`
1775 fn describe_field(&self, base: &Place<'tcx>, field: Field) -> String {
1777 Place::Base(PlaceBase::Local(local)) => {
1778 let local = &self.mir.local_decls[local];
1779 self.describe_field_from_ty(&local.ty, field, None)
1781 Place::Base(PlaceBase::Static(ref static_)) =>
1782 self.describe_field_from_ty(&static_.ty, field, None),
1783 Place::Projection(ref proj) => match proj.elem {
1784 ProjectionElem::Deref => self.describe_field(&proj.base, field),
1785 ProjectionElem::Downcast(_, variant_index) => {
1786 let base_ty = base.ty(self.mir, self.infcx.tcx).ty;
1787 self.describe_field_from_ty(&base_ty, field, Some(variant_index))
1789 ProjectionElem::Field(_, field_type) => {
1790 self.describe_field_from_ty(&field_type, field, None)
1792 ProjectionElem::Index(..)
1793 | ProjectionElem::ConstantIndex { .. }
1794 | ProjectionElem::Subslice { .. } => {
1795 self.describe_field(&proj.base, field)
1801 /// End-user visible description of the `field_index`nth field of `ty`
1802 fn describe_field_from_ty(
1806 variant_index: Option<VariantIdx>
1809 // If the type is a box, the field is described from the boxed type
1810 self.describe_field_from_ty(&ty.boxed_ty(), field, variant_index)
1813 ty::Adt(def, _) => {
1814 let variant = if let Some(idx) = variant_index {
1815 assert!(def.is_enum());
1818 def.non_enum_variant()
1820 variant.fields[field.index()]
1824 ty::Tuple(_) => field.index().to_string(),
1825 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
1826 self.describe_field_from_ty(&ty, field, variant_index)
1828 ty::Array(ty, _) | ty::Slice(ty) =>
1829 self.describe_field_from_ty(&ty, field, variant_index),
1830 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
1831 // `tcx.upvars(def_id)` returns an `Option`, which is `None` in case
1832 // the closure comes from another crate. But in that case we wouldn't
1833 // be borrowck'ing it, so we can just unwrap:
1834 let upvar = self.infcx.tcx.upvars(def_id).unwrap()[field.index()];
1836 self.infcx.tcx.hir().name_by_hir_id(upvar.var_id()).to_string()
1839 // Might need a revision when the fields in trait RFC is implemented
1840 // (https://github.com/rust-lang/rfcs/pull/1546)
1842 "End-user description not implemented for field access on `{:?}`",
1850 /// Checks if a place is a thread-local static.
1851 pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
1853 PlaceBase::Static(box Static{ kind: StaticKind::Static(def_id), .. })
1855 let attrs = self.infcx.tcx.get_attrs(*def_id);
1856 let is_thread_local = attrs.iter().any(|attr| attr.check_name(sym::thread_local));
1859 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
1860 attrs, is_thread_local
1864 debug!("is_place_thread_local: no");
1869 fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
1870 let tcx = self.infcx.tcx;
1872 Place::Base(PlaceBase::Local(_)) |
1873 Place::Base(PlaceBase::Static(_)) => {
1874 StorageDeadOrDrop::LocalStorageDead
1876 Place::Projection(box PlaceProjection { base, elem }) => {
1877 let base_access = self.classify_drop_access_kind(base);
1879 ProjectionElem::Deref => match base_access {
1880 StorageDeadOrDrop::LocalStorageDead
1881 | StorageDeadOrDrop::BoxedStorageDead => {
1883 base.ty(self.mir, tcx).ty.is_box(),
1884 "Drop of value behind a reference or raw pointer"
1886 StorageDeadOrDrop::BoxedStorageDead
1888 StorageDeadOrDrop::Destructor(_) => base_access,
1890 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1891 let base_ty = base.ty(self.mir, tcx).ty;
1893 ty::Adt(def, _) if def.has_dtor(tcx) => {
1894 // Report the outermost adt with a destructor
1896 StorageDeadOrDrop::Destructor(_) => base_access,
1897 StorageDeadOrDrop::LocalStorageDead
1898 | StorageDeadOrDrop::BoxedStorageDead => {
1899 StorageDeadOrDrop::Destructor(base_ty)
1907 ProjectionElem::ConstantIndex { .. }
1908 | ProjectionElem::Subslice { .. }
1909 | ProjectionElem::Index(_) => base_access,
1915 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1916 /// borrow of local value that does not live long enough.
1917 fn annotate_argument_and_return_for_borrow(
1919 borrow: &BorrowData<'tcx>,
1920 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1921 // Define a fallback for when we can't match a closure.
1923 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1927 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1929 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1931 self.infcx.tcx.fn_sig(self.mir_def_id),
1938 // In order to determine whether we need to annotate, we need to check whether the reserve
1939 // place was an assignment into a temporary.
1941 // If it was, we check whether or not that temporary is eventually assigned into the return
1942 // place. If it was, we can add annotations about the function's return type and arguments
1943 // and it'll make sense.
1944 let location = borrow.reserve_location;
1946 "annotate_argument_and_return_for_borrow: location={:?}",
1949 if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1950 = &self.mir[location.block].statements.get(location.statement_index)
1953 "annotate_argument_and_return_for_borrow: reservation={:?}",
1956 // Check that the initial assignment of the reserve location is into a temporary.
1957 let mut target = *match reservation {
1958 Place::Base(PlaceBase::Local(local))
1959 if self.mir.local_kind(*local) == LocalKind::Temp => local,
1963 // Next, look through the rest of the block, checking if we are assigning the
1964 // `target` (that is, the place that contains our borrow) to anything.
1965 let mut annotated_closure = None;
1966 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1968 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1971 if let StatementKind::Assign(
1972 Place::Base(PlaceBase::Local(assigned_to)),
1976 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1980 // Check if our `target` was captured by a closure.
1981 if let Rvalue::Aggregate(
1982 box AggregateKind::Closure(def_id, substs),
1986 for operand in operands {
1987 let assigned_from = match operand {
1988 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1994 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1998 // Find the local from the operand.
1999 let assigned_from_local = match assigned_from.local() {
2000 Some(local) => local,
2004 if assigned_from_local != target {
2008 // If a closure captured our `target` and then assigned
2009 // into a place then we should annotate the closure in
2010 // case it ends up being assigned into the return place.
2011 annotated_closure = self.annotate_fn_sig(
2013 self.infcx.closure_sig(*def_id, *substs),
2016 "annotate_argument_and_return_for_borrow: \
2017 annotated_closure={:?} assigned_from_local={:?} \
2019 annotated_closure, assigned_from_local, assigned_to
2022 if *assigned_to == mir::RETURN_PLACE {
2023 // If it was assigned directly into the return place, then
2025 return annotated_closure;
2027 // Otherwise, update the target.
2028 target = *assigned_to;
2032 // If none of our closure's operands matched, then skip to the next
2037 // Otherwise, look at other types of assignment.
2038 let assigned_from = match rvalue {
2039 Rvalue::Ref(_, _, assigned_from) => assigned_from,
2040 Rvalue::Use(operand) => match operand {
2041 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
2049 "annotate_argument_and_return_for_borrow: \
2050 assigned_from={:?}",
2054 // Find the local from the rvalue.
2055 let assigned_from_local = match assigned_from.local() {
2056 Some(local) => local,
2060 "annotate_argument_and_return_for_borrow: \
2061 assigned_from_local={:?}",
2062 assigned_from_local,
2065 // Check if our local matches the target - if so, we've assigned our
2066 // borrow to a new place.
2067 if assigned_from_local != target {
2071 // If we assigned our `target` into a new place, then we should
2072 // check if it was the return place.
2074 "annotate_argument_and_return_for_borrow: \
2075 assigned_from_local={:?} assigned_to={:?}",
2076 assigned_from_local, assigned_to
2078 if *assigned_to == mir::RETURN_PLACE {
2079 // If it was then return the annotated closure if there was one,
2080 // else, annotate this function.
2081 return annotated_closure.or_else(fallback);
2084 // If we didn't assign into the return place, then we just update
2086 target = *assigned_to;
2090 // Check the terminator if we didn't find anything in the statements.
2091 let terminator = &self.mir[location.block].terminator();
2093 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
2096 if let TerminatorKind::Call {
2097 destination: Some((Place::Base(PlaceBase::Local(assigned_to)), _)),
2100 } = &terminator.kind
2103 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
2106 for operand in args {
2107 let assigned_from = match operand {
2108 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
2114 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
2118 if let Some(assigned_from_local) = assigned_from.local() {
2120 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
2121 assigned_from_local,
2124 if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
2125 return annotated_closure.or_else(fallback);
2132 // If we haven't found an assignment into the return place, then we need not add
2134 debug!("annotate_argument_and_return_for_borrow: none found");
2138 /// Annotate the first argument and return type of a function signature if they are
2143 sig: ty::PolyFnSig<'tcx>,
2144 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
2145 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
2146 let is_closure = self.infcx.tcx.is_closure(did);
2147 let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
2148 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
2150 // We need to work out which arguments to highlight. We do this by looking
2151 // at the return type, where there are three cases:
2153 // 1. If there are named arguments, then we should highlight the return type and
2154 // highlight any of the arguments that are also references with that lifetime.
2155 // If there are no arguments that have the same lifetime as the return type,
2156 // then don't highlight anything.
2157 // 2. The return type is a reference with an anonymous lifetime. If this is
2158 // the case, then we can take advantage of (and teach) the lifetime elision
2161 // We know that an error is being reported. So the arguments and return type
2162 // must satisfy the elision rules. Therefore, if there is a single argument
2163 // then that means the return type and first (and only) argument have the same
2164 // lifetime and the borrow isn't meeting that, we can highlight the argument
2167 // If there are multiple arguments then the first argument must be self (else
2168 // it would not satisfy the elision rules), so we can highlight self and the
2170 // 3. The return type is not a reference. In this case, we don't highlight
2172 let return_ty = sig.output();
2173 match return_ty.skip_binder().sty {
2174 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
2175 // This is case 1 from above, return type is a named reference so we need to
2176 // search for relevant arguments.
2177 let mut arguments = Vec::new();
2178 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
2179 if let ty::Ref(argument_region, _, _) = argument.sty {
2180 if argument_region == return_region {
2181 // Need to use the `rustc::ty` types to compare against the
2182 // `return_region`. Then use the `rustc::hir` type to get only
2183 // the lifetime span.
2184 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
2185 // With access to the lifetime, we can get
2187 arguments.push((*argument, lifetime.span));
2189 bug!("ty type is a ref but hir type is not");
2195 // We need to have arguments. This shouldn't happen, but it's worth checking.
2196 if arguments.is_empty() {
2200 // We use a mix of the HIR and the Ty types to get information
2201 // as the HIR doesn't have full types for closure arguments.
2202 let return_ty = *sig.output().skip_binder();
2203 let mut return_span = fn_decl.output.span();
2204 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
2205 if let hir::TyKind::Rptr(lifetime, _) = ty.into_inner().node {
2206 return_span = lifetime.span;
2210 Some(AnnotatedBorrowFnSignature::NamedFunction {
2216 ty::Ref(_, _, _) if is_closure => {
2217 // This is case 2 from above but only for closures, return type is anonymous
2218 // reference so we select
2219 // the first argument.
2220 let argument_span = fn_decl.inputs.first()?.span;
2221 let argument_ty = sig.inputs().skip_binder().first()?;
2223 // Closure arguments are wrapped in a tuple, so we need to get the first
2225 if let ty::Tuple(elems) = argument_ty.sty {
2226 let argument_ty = elems.first()?.expect_ty();
2227 if let ty::Ref(_, _, _) = argument_ty.sty {
2228 return Some(AnnotatedBorrowFnSignature::Closure {
2237 ty::Ref(_, _, _) => {
2238 // This is also case 2 from above but for functions, return type is still an
2239 // anonymous reference so we select the first argument.
2240 let argument_span = fn_decl.inputs.first()?.span;
2241 let argument_ty = sig.inputs().skip_binder().first()?;
2243 let return_span = fn_decl.output.span();
2244 let return_ty = *sig.output().skip_binder();
2246 // We expect the first argument to be a reference.
2247 match argument_ty.sty {
2248 ty::Ref(_, _, _) => {}
2252 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2260 // This is case 3 from above, return type is not a reference so don't highlight
2269 enum AnnotatedBorrowFnSignature<'tcx> {
2271 arguments: Vec<(Ty<'tcx>, Span)>,
2272 return_ty: Ty<'tcx>,
2276 argument_ty: Ty<'tcx>,
2277 argument_span: Span,
2278 return_ty: Ty<'tcx>,
2282 argument_ty: Ty<'tcx>,
2283 argument_span: Span,
2287 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2288 /// Annotate the provided diagnostic with information about borrow from the fn signature that
2292 cx: &mut MirBorrowckCtxt<'_, '_, 'tcx>,
2293 diag: &mut DiagnosticBuilder<'_>,
2296 AnnotatedBorrowFnSignature::Closure {
2302 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2305 cx.get_region_name_for_ty(argument_ty, 0)
2307 AnnotatedBorrowFnSignature::AnonymousFunction {
2313 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2314 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2316 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2317 let types_equal = return_ty_name == argument_ty_name;
2322 if types_equal { "also " } else { "" },
2328 "argument and return type have the same lifetime due to lifetime elision rules",
2331 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2332 lifetime-syntax.html#lifetime-elision>",
2335 cx.get_region_name_for_ty(return_ty, 0)
2337 AnnotatedBorrowFnSignature::NamedFunction {
2342 // Region of return type and arguments checked to be the same earlier.
2343 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2344 for (_, argument_span) in arguments {
2345 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2350 format!("also has lifetime `{}`", region_name,),
2354 "use data from the highlighted arguments which match the `{}` lifetime of \
2365 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2366 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
2367 /// name where required.
2368 fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
2369 let mut s = String::new();
2370 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
2372 // We need to add synthesized lifetimes where appropriate. We do
2373 // this by hooking into the pretty printer and telling it to label the
2374 // lifetimes without names with the value `'0`.
2376 ty::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
2378 ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }),
2381 ) => printer.region_highlight_mode.highlighting_bound_region(*br, counter),
2385 let _ = ty.print(printer);
2389 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
2390 /// synthesized lifetime name where required.
2391 fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
2392 let mut s = String::new();
2393 let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, &mut s, Namespace::TypeNS);
2395 let region = match ty.sty {
2396 ty::Ref(region, _, _) => {
2398 ty::RegionKind::ReLateBound(_, br)
2399 | ty::RegionKind::RePlaceholder(ty::PlaceholderRegion { name: br, .. }) => {
2400 printer.region_highlight_mode.highlighting_bound_region(*br, counter)
2407 _ => bug!("ty for annotation of borrow region is not a reference"),
2410 let _ = region.print(printer);
2415 // The span(s) associated to a use of a place.
2416 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2417 pub(super) enum UseSpans {
2418 // The access is caused by capturing a variable for a closure.
2420 // This is true if the captured variable was from a generator.
2422 // The span of the args of the closure, including the `move` keyword if
2425 // The span of the first use of the captured variable inside the closure.
2428 // This access has a single span associated to it: common case.
2433 pub(super) fn args_or_use(self) -> Span {
2435 UseSpans::ClosureUse {
2438 | UseSpans::OtherUse(span) => span,
2442 pub(super) fn var_or_use(self) -> Span {
2444 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
2448 // Add a span label to the arguments of the closure, if it exists.
2449 pub(super) fn args_span_label(
2451 err: &mut DiagnosticBuilder<'_>,
2452 message: impl Into<String>,
2454 if let UseSpans::ClosureUse { args_span, .. } = self {
2455 err.span_label(args_span, message);
2459 // Add a span label to the use of the captured variable, if it exists.
2460 pub(super) fn var_span_label(
2462 err: &mut DiagnosticBuilder<'_>,
2463 message: impl Into<String>,
2465 if let UseSpans::ClosureUse { var_span, .. } = self {
2466 err.span_label(var_span, message);
2470 /// Returns `false` if this place is not used in a closure.
2471 fn for_closure(&self) -> bool {
2473 UseSpans::ClosureUse { is_generator, .. } => !is_generator,
2478 /// Returns `false` if this place is not used in a generator.
2479 fn for_generator(&self) -> bool {
2481 UseSpans::ClosureUse { is_generator, .. } => is_generator,
2486 /// Describe the span associated with a use of a place.
2487 fn describe(&self) -> String {
2489 UseSpans::ClosureUse { is_generator, .. } => if is_generator {
2490 " in generator".to_string()
2492 " in closure".to_string()
2494 _ => "".to_string(),
2498 pub(super) fn or_else<F>(self, if_other: F) -> Self
2500 F: FnOnce() -> Self,
2503 closure @ UseSpans::ClosureUse { .. } => closure,
2504 UseSpans::OtherUse(_) => if_other(),
2509 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2510 /// Finds the spans associated to a move or copy of move_place at location.
2511 pub(super) fn move_spans(
2513 moved_place: &Place<'tcx>, // Could also be an upvar.
2516 use self::UseSpans::*;
2518 let stmt = match self.mir[location.block].statements.get(location.statement_index) {
2520 None => return OtherUse(self.mir.source_info(location).span),
2523 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
2524 if let StatementKind::Assign(
2526 box Rvalue::Aggregate(ref kind, ref places)
2528 let (def_id, is_generator) = match kind {
2529 box AggregateKind::Closure(def_id, _) => (def_id, false),
2530 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2531 _ => return OtherUse(stmt.source_info.span),
2535 "move_spans: def_id={:?} is_generator={:?} places={:?}",
2536 def_id, is_generator, places
2538 if let Some((args_span, var_span)) = self.closure_span(*def_id, moved_place, places) {
2547 OtherUse(stmt.source_info.span)
2550 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
2551 /// and its usage of the local assigned at `location`.
2552 /// This is done by searching in statements succeeding `location`
2553 /// and originating from `maybe_closure_span`.
2554 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
2555 use self::UseSpans::*;
2556 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
2558 let target = match self.mir[location.block]
2560 .get(location.statement_index)
2563 kind: StatementKind::Assign(Place::Base(PlaceBase::Local(local)), _),
2566 _ => return OtherUse(use_span),
2569 if self.mir.local_kind(target) != LocalKind::Temp {
2570 // operands are always temporaries.
2571 return OtherUse(use_span);
2574 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
2575 if let StatementKind::Assign(
2576 _, box Rvalue::Aggregate(ref kind, ref places)
2578 let (def_id, is_generator) = match kind {
2579 box AggregateKind::Closure(def_id, _) => (def_id, false),
2580 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2585 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
2586 def_id, is_generator, places
2588 if let Some((args_span, var_span)) = self.closure_span(
2589 *def_id, &Place::Base(PlaceBase::Local(target)), places
2597 return OtherUse(use_span);
2601 if use_span != stmt.source_info.span {
2609 /// Finds the span of a captured variable within a closure or generator.
2613 target_place: &Place<'tcx>,
2614 places: &Vec<Operand<'tcx>>,
2615 ) -> Option<(Span, Span)> {
2617 "closure_span: def_id={:?} target_place={:?} places={:?}",
2618 def_id, target_place, places
2620 let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id)?;
2621 let expr = &self.infcx.tcx.hir().expect_expr_by_hir_id(hir_id).node;
2622 debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
2623 if let hir::ExprKind::Closure(
2626 for (v, place) in self.infcx.tcx.upvars(def_id)?.iter().zip(places) {
2628 Operand::Copy(place) |
2629 Operand::Move(place) if target_place == place => {
2630 debug!("closure_span: found captured local {:?}", place);
2631 return Some((*args_span, v.span));
2641 /// Helper to retrieve span(s) of given borrow from the current MIR
2643 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans {
2644 let span = self.mir.source_info(borrow.reserve_location).span;
2645 self.borrow_spans(span, borrow.reserve_location)