2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_errors::{Applicability, DiagnosticBuilder};
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::{AsyncGeneratorKind, GeneratorKind};
7 use rustc_index::vec::Idx;
8 use rustc_middle::mir::{
9 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
10 FakeReadCause, Local, LocalDecl, LocalInfo, LocalKind, Location, Operand, Place, PlaceRef,
11 ProjectionElem, Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
13 use rustc_middle::ty::{self, suggest_constraining_type_param, Ty};
14 use rustc_span::source_map::DesugaringKind;
17 use crate::dataflow::drop_flag_effects;
18 use crate::dataflow::indexes::{MoveOutIndex, MovePathIndex};
19 use crate::util::borrowck_errors;
21 use crate::borrow_check::{
22 borrow_set::BorrowData, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt,
27 explain_borrow::BorrowExplanation, FnSelfUseKind, IncludingDowncast, RegionName,
28 RegionNameSource, UseSpans,
33 /// Index of the "move out" that we found. The `MoveData` can
34 /// then tell us where the move occurred.
37 /// `true` if we traversed a back edge while walking from the point
38 /// of error to the move site.
39 traversed_back_edge: bool,
42 /// Which case a StorageDeadOrDrop is for.
43 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
44 enum StorageDeadOrDrop<'tcx> {
50 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
51 pub(in crate::borrow_check) fn report_use_of_moved_or_uninitialized(
54 desired_action: InitializationRequiringAction,
55 (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span),
59 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
60 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
61 location, desired_action, moved_place, used_place, span, mpi
65 self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
66 let span = use_spans.args_or_use();
68 let move_site_vec = self.get_moved_indexes(location, mpi);
70 "report_use_of_moved_or_uninitialized: move_site_vec={:?} use_spans={:?}",
71 move_site_vec, use_spans
73 let move_out_indices: Vec<_> =
74 move_site_vec.iter().map(|move_site| move_site.moi).collect();
76 if move_out_indices.is_empty() {
77 let root_place = PlaceRef { projection: &[], ..used_place };
79 if !self.uninitialized_error_reported.insert(root_place) {
81 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
88 match self.describe_place_with_options(used_place, IncludingDowncast(true)) {
89 Some(name) => format!("`{}`", name),
90 None => "value".to_owned(),
92 let mut err = self.cannot_act_on_uninitialized_variable(
94 desired_action.as_noun(),
96 .describe_place_with_options(moved_place, IncludingDowncast(true))
97 .unwrap_or_else(|| "_".to_owned()),
99 err.span_label(span, format!("use of possibly-uninitialized {}", item_msg));
101 use_spans.var_span_label(
103 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
106 err.buffer(&mut self.errors_buffer);
108 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
109 if self.prefixes(*reported_place, PrefixSet::All).any(|p| p == used_place) {
111 "report_use_of_moved_or_uninitialized place: error suppressed \
119 let is_partial_move = move_site_vec.iter().any(|move_site| {
120 let move_out = self.move_data.moves[(*move_site).moi];
121 let moved_place = &self.move_data.move_paths[move_out.path].place;
122 // `*(_1)` where `_1` is a `Box` is actually a move out.
123 let is_box_move = moved_place.as_ref().projection == &[ProjectionElem::Deref]
124 && self.body.local_decls[moved_place.local].ty.is_box();
127 && used_place != moved_place.as_ref()
128 && used_place.is_prefix_of(moved_place.as_ref())
131 let partial_str = if is_partial_move { "partial " } else { "" };
132 let partially_str = if is_partial_move { "partially " } else { "" };
134 let mut err = self.cannot_act_on_moved_value(
136 desired_action.as_noun(),
138 self.describe_place_with_options(moved_place, IncludingDowncast(true)),
141 self.add_moved_or_invoked_closure_note(location, used_place, &mut err);
143 let mut is_loop_move = false;
145 for move_site in &move_site_vec {
146 let move_out = self.move_data.moves[(*move_site).moi];
147 let moved_place = &self.move_data.move_paths[move_out.path].place;
149 let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
150 let move_span = move_spans.args_or_use();
152 let move_msg = if move_spans.for_closure() { " into closure" } else { "" };
154 if location == move_out.source {
158 "value {}moved{} here, in previous iteration of loop",
159 partially_str, move_msg
163 } else if move_site.traversed_back_edge {
167 "value {}moved{} here, in previous iteration of loop",
168 partially_str, move_msg
172 if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } =
175 let place_name = self
176 .describe_place(moved_place.as_ref())
177 .map(|n| format!("`{}`", n))
178 .unwrap_or_else(|| "value".to_owned());
180 FnSelfUseKind::FnOnceCall => {
184 "{} {}moved due to this call",
185 place_name, partially_str
190 "this value implements `FnOnce`, which causes it to be moved when called",
193 FnSelfUseKind::Operator { self_arg } => {
197 "{} {}moved due to usage in operator",
198 place_name, partially_str
201 if self.fn_self_span_reported.insert(fn_span) {
204 "calling this operator moves the left-hand side",
208 FnSelfUseKind::Normal { self_arg, implicit_into_iter } => {
209 if implicit_into_iter {
213 "{} {}moved due to this implicit call to `.into_iter()`",
214 place_name, partially_str
221 "{} {}moved due to this method call",
222 place_name, partially_str
226 // Avoid pointing to the same function in multiple different
228 if self.fn_self_span_reported.insert(self_arg.span) {
231 &format!("this function consumes the receiver `self` by taking ownership of it, which moves {}", place_name)
235 // Deref::deref takes &self, which cannot cause a move
236 FnSelfUseKind::DerefCoercion { .. } => unreachable!(),
241 format!("value {}moved{} here", partially_str, move_msg),
243 move_spans.var_span_label(
246 "variable {}moved due to use{}",
248 move_spans.describe()
253 if let UseSpans::PatUse(span) = move_spans {
254 err.span_suggestion_verbose(
257 "borrow this field in the pattern to avoid moving {}",
258 self.describe_place(moved_place.as_ref())
259 .map(|n| format!("`{}`", n))
260 .unwrap_or_else(|| "the value".to_string())
263 Applicability::MachineApplicable,
267 if let Some(DesugaringKind::ForLoop(_)) = move_span.desugaring_kind() {
268 let sess = self.infcx.tcx.sess;
269 if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
272 "consider borrowing to avoid moving into the for loop",
273 format!("&{}", snippet),
274 Applicability::MaybeIncorrect,
280 use_spans.var_span_label(
282 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
289 "value {} here after {}move",
290 desired_action.as_verb_in_past_tense(),
297 Place::ty_from(used_place.local, used_place.projection, self.body, self.infcx.tcx)
299 let needs_note = match ty.kind() {
300 ty::Closure(id, _) => {
301 let tables = self.infcx.tcx.typeck(id.expect_local());
302 let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(id.expect_local());
304 tables.closure_kind_origins().get(hir_id).is_none()
309 let mpi = self.move_data.moves[move_out_indices[0]].path;
310 let place = &self.move_data.move_paths[mpi].place;
311 let ty = place.ty(self.body, self.infcx.tcx).ty;
314 if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() {
315 // We have a `&mut` ref, we need to reborrow on each iteration (#62112).
316 err.span_suggestion_verbose(
319 "consider creating a fresh reborrow of {} here",
320 self.describe_place(moved_place)
321 .map(|n| format!("`{}`", n))
322 .unwrap_or_else(|| "the mutable reference".to_string()),
324 "&mut *".to_string(),
325 Applicability::MachineApplicable,
332 self.describe_place_with_options(place.as_ref(), IncludingDowncast(true));
333 let note_msg = match opt_name {
334 Some(ref name) => format!("`{}`", name),
335 None => "value".to_owned(),
337 if let ty::Param(param_ty) = ty.kind() {
338 let tcx = self.infcx.tcx;
339 let generics = tcx.generics_of(self.mir_def_id);
340 let param = generics.type_param(¶m_ty, tcx);
341 if let Some(generics) =
342 tcx.hir().get_generics(tcx.closure_base_def_id(self.mir_def_id.to_def_id()))
344 suggest_constraining_type_param(
348 ¶m.name.as_str(),
354 let span = if let Some(local) = place.as_local() {
355 let decl = &self.body.local_decls[local];
356 Some(decl.source_info.span)
360 self.note_type_does_not_implement_copy(&mut err, ¬e_msg, ty, span, partial_str);
363 if let UseSpans::FnSelfUse {
364 kind: FnSelfUseKind::DerefCoercion { deref_target, deref_target_ty },
369 "{} occurs due to deref coercion to `{}`",
370 desired_action.as_noun(),
374 err.span_note(deref_target, "deref defined here");
377 if let Some((_, mut old_err)) =
378 self.move_error_reported.insert(move_out_indices, (used_place, err))
380 // Cancel the old error so it doesn't ICE.
386 pub(in crate::borrow_check) fn report_move_out_while_borrowed(
389 (place, span): (Place<'tcx>, Span),
390 borrow: &BorrowData<'tcx>,
393 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
394 location, place, span, borrow
396 let value_msg = self.describe_any_place(place.as_ref());
397 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
399 let borrow_spans = self.retrieve_borrow_spans(borrow);
400 let borrow_span = borrow_spans.args_or_use();
402 let move_spans = self.move_spans(place.as_ref(), location);
403 let span = move_spans.args_or_use();
406 self.cannot_move_when_borrowed(span, &self.describe_any_place(place.as_ref()));
407 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
408 err.span_label(span, format!("move out of {} occurs here", value_msg));
410 borrow_spans.var_span_label(
412 format!("borrow occurs due to use{}", borrow_spans.describe()),
416 .var_span_label(&mut err, format!("move occurs due to use{}", move_spans.describe()));
418 self.explain_why_borrow_contains_point(location, borrow, None)
419 .add_explanation_to_diagnostic(
427 err.buffer(&mut self.errors_buffer);
430 pub(in crate::borrow_check) fn report_use_while_mutably_borrowed(
433 (place, _span): (Place<'tcx>, Span),
434 borrow: &BorrowData<'tcx>,
435 ) -> DiagnosticBuilder<'cx> {
436 let borrow_spans = self.retrieve_borrow_spans(borrow);
437 let borrow_span = borrow_spans.args_or_use();
439 // Conflicting borrows are reported separately, so only check for move
441 let use_spans = self.move_spans(place.as_ref(), location);
442 let span = use_spans.var_or_use();
444 let mut err = self.cannot_use_when_mutably_borrowed(
446 &self.describe_any_place(place.as_ref()),
448 &self.describe_any_place(borrow.borrowed_place.as_ref()),
451 borrow_spans.var_span_label(&mut err, {
452 let place = &borrow.borrowed_place;
453 let desc_place = self.describe_any_place(place.as_ref());
454 format!("borrow occurs due to use of {}{}", desc_place, borrow_spans.describe())
457 self.explain_why_borrow_contains_point(location, borrow, None)
458 .add_explanation_to_diagnostic(
469 pub(in crate::borrow_check) fn report_conflicting_borrow(
472 (place, span): (Place<'tcx>, Span),
473 gen_borrow_kind: BorrowKind,
474 issued_borrow: &BorrowData<'tcx>,
475 ) -> DiagnosticBuilder<'cx> {
476 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
477 let issued_span = issued_spans.args_or_use();
479 let borrow_spans = self.borrow_spans(span, location);
480 let span = borrow_spans.args_or_use();
482 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
488 let (desc_place, msg_place, msg_borrow, union_type_name) =
489 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
491 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
492 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
494 // FIXME: supply non-"" `opt_via` when appropriate
495 let first_borrow_desc;
496 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
497 (BorrowKind::Shared, BorrowKind::Mut { .. }) => {
498 first_borrow_desc = "mutable ";
499 self.cannot_reborrow_already_borrowed(
511 (BorrowKind::Mut { .. }, BorrowKind::Shared) => {
512 first_borrow_desc = "immutable ";
513 self.cannot_reborrow_already_borrowed(
526 (BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
527 first_borrow_desc = "first ";
528 let mut err = self.cannot_mutably_borrow_multiply(
536 self.suggest_split_at_mut_if_applicable(
539 issued_borrow.borrowed_place,
544 (BorrowKind::Unique, BorrowKind::Unique) => {
545 first_borrow_desc = "first ";
546 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
549 (BorrowKind::Mut { .. } | BorrowKind::Unique, BorrowKind::Shallow) => {
550 if let Some(immutable_section_description) =
551 self.classify_immutable_section(issued_borrow.assigned_place)
553 let mut err = self.cannot_mutate_in_immutable_section(
557 immutable_section_description,
560 borrow_spans.var_span_label(
563 "borrow occurs due to use of {}{}",
565 borrow_spans.describe(),
571 first_borrow_desc = "immutable ";
572 self.cannot_reborrow_already_borrowed(
586 (BorrowKind::Unique, _) => {
587 first_borrow_desc = "first ";
588 self.cannot_uniquely_borrow_by_one_closure(
600 (BorrowKind::Shared, BorrowKind::Unique) => {
601 first_borrow_desc = "first ";
602 self.cannot_reborrow_already_uniquely_borrowed(
615 (BorrowKind::Mut { .. }, BorrowKind::Unique) => {
616 first_borrow_desc = "first ";
617 self.cannot_reborrow_already_uniquely_borrowed(
630 (BorrowKind::Shared, BorrowKind::Shared | BorrowKind::Shallow)
633 BorrowKind::Mut { .. }
636 | BorrowKind::Shallow,
640 if issued_spans == borrow_spans {
641 borrow_spans.var_span_label(
643 format!("borrows occur due to use of {}{}", desc_place, borrow_spans.describe()),
646 let borrow_place = &issued_borrow.borrowed_place;
647 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
648 issued_spans.var_span_label(
651 "first borrow occurs due to use of {}{}",
653 issued_spans.describe(),
657 borrow_spans.var_span_label(
660 "second borrow occurs due to use of {}{}",
662 borrow_spans.describe(),
667 if union_type_name != "" {
669 "{} is a field of the union `{}`, so it overlaps the field {}",
670 msg_place, union_type_name, msg_borrow,
674 explanation.add_explanation_to_diagnostic(
686 fn suggest_split_at_mut_if_applicable(
688 err: &mut DiagnosticBuilder<'_>,
690 borrowed_place: Place<'tcx>,
692 if let ([ProjectionElem::Index(_)], [ProjectionElem::Index(_)]) =
693 (&place.projection[..], &borrowed_place.projection[..])
696 "consider using `.split_at_mut(position)` or similar method to obtain \
697 two mutable non-overlapping sub-slices",
702 /// Returns the description of the root place for a conflicting borrow and the full
703 /// descriptions of the places that caused the conflict.
705 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
706 /// attempted while a shared borrow is live, then this function will return:
710 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
711 /// a shared borrow of another field `x.y`, then this function will return:
713 /// ("x", "x.z", "x.y")
715 /// In the more complex union case, where the union is a field of a struct, then if a mutable
716 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
717 /// another field `x.u.y`, then this function will return:
719 /// ("x.u", "x.u.z", "x.u.y")
721 /// This is used when creating error messages like below:
724 /// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
725 /// mutable (via `a.u.s.b`) [E0502]
727 pub(in crate::borrow_check) fn describe_place_for_conflicting_borrow(
729 first_borrowed_place: Place<'tcx>,
730 second_borrowed_place: Place<'tcx>,
731 ) -> (String, String, String, String) {
732 // Define a small closure that we can use to check if the type of a place
734 let union_ty = |place_base, place_projection| {
735 let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
736 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
739 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
740 // code duplication (particularly around returning an empty description in the failure
744 // If we have a conflicting borrow of the same place, then we don't want to add
745 // an extraneous "via x.y" to our diagnostics, so filter out this case.
746 first_borrowed_place != second_borrowed_place
749 // We're going to want to traverse the first borrowed place to see if we can find
750 // field access to a union. If we find that, then we will keep the place of the
751 // union being accessed and the field that was being accessed so we can check the
752 // second borrowed place for the same union and a access to a different field.
753 let Place { local, projection } = first_borrowed_place;
755 let mut cursor = projection.as_ref();
756 while let [proj_base @ .., elem] = cursor {
760 ProjectionElem::Field(field, _) if union_ty(local, proj_base).is_some() => {
761 return Some((PlaceRef { local, projection: proj_base }, field));
768 .and_then(|(target_base, target_field)| {
769 // With the place of a union and a field access into it, we traverse the second
770 // borrowed place and look for a access to a different field of the same union.
771 let Place { local, ref projection } = second_borrowed_place;
773 let mut cursor = &projection[..];
774 while let [proj_base @ .., elem] = cursor {
777 if let ProjectionElem::Field(field, _) = elem {
778 if let Some(union_ty) = union_ty(local, proj_base) {
779 if field != target_field
780 && local == target_base.local
781 && proj_base == target_base.projection
784 self.describe_any_place(PlaceRef {
786 projection: proj_base,
788 self.describe_any_place(first_borrowed_place.as_ref()),
789 self.describe_any_place(second_borrowed_place.as_ref()),
790 union_ty.to_string(),
799 // If we didn't find a field access into a union, or both places match, then
800 // only return the description of the first place.
802 self.describe_any_place(first_borrowed_place.as_ref()),
810 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
812 /// This means that some data referenced by `borrow` needs to live
813 /// past the point where the StorageDeadOrDrop of `place` occurs.
814 /// This is usually interpreted as meaning that `place` has too
815 /// short a lifetime. (But sometimes it is more useful to report
816 /// it as a more direct conflict between the execution of a
817 /// `Drop::drop` with an aliasing borrow.)
818 pub(in crate::borrow_check) fn report_borrowed_value_does_not_live_long_enough(
821 borrow: &BorrowData<'tcx>,
822 place_span: (Place<'tcx>, Span),
823 kind: Option<WriteKind>,
826 "report_borrowed_value_does_not_live_long_enough(\
827 {:?}, {:?}, {:?}, {:?}\
829 location, borrow, place_span, kind
832 let drop_span = place_span.1;
834 self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
836 let borrow_spans = self.retrieve_borrow_spans(borrow);
837 let borrow_span = borrow_spans.var_or_use();
839 assert!(root_place.projection.is_empty());
840 let proper_span = self.body.local_decls[root_place.local].source_info.span;
842 let root_place_projection = self.infcx.tcx.intern_place_elems(root_place.projection);
844 if self.access_place_error_reported.contains(&(
845 Place { local: root_place.local, projection: root_place_projection },
849 "suppressing access_place error when borrow doesn't live long enough for {:?}",
855 self.access_place_error_reported.insert((
856 Place { local: root_place.local, projection: root_place_projection },
860 let borrowed_local = borrow.borrowed_place.local;
861 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
863 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
864 err.buffer(&mut self.errors_buffer);
868 if let StorageDeadOrDrop::Destructor(dropped_ty) =
869 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
871 // If a borrow of path `B` conflicts with drop of `D` (and
872 // we're not in the uninteresting case where `B` is a
873 // prefix of `D`), then report this as a more interesting
874 // destructor conflict.
875 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
876 self.report_borrow_conflicts_with_destructor(
877 location, borrow, place_span, kind, dropped_ty,
883 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
885 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
886 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
889 "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
890 place_desc, explanation
892 let err = match (place_desc, explanation) {
893 // If the outlives constraint comes from inside the closure,
898 // Box::new(|| y) as Box<Fn() -> &'static i32>
900 // then just use the normal error. The closure isn't escaping
901 // and `move` will not help here.
904 BorrowExplanation::MustBeValidFor {
908 (ConstraintCategory::Return(_)
909 | ConstraintCategory::CallArgument
910 | ConstraintCategory::OpaqueType),
916 ) if borrow_spans.for_generator() | borrow_spans.for_closure() => self
917 .report_escaping_closure_capture(
923 &format!("`{}`", name),
927 BorrowExplanation::MustBeValidFor {
928 category: ConstraintCategory::Assignment,
933 RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
939 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
940 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
948 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
958 err.buffer(&mut self.errors_buffer);
961 fn report_local_value_does_not_live_long_enough(
965 borrow: &BorrowData<'tcx>,
967 borrow_spans: UseSpans<'tcx>,
968 explanation: BorrowExplanation,
969 ) -> DiagnosticBuilder<'cx> {
971 "report_local_value_does_not_live_long_enough(\
972 {:?}, {:?}, {:?}, {:?}, {:?}\
974 location, name, borrow, drop_span, borrow_spans
977 let borrow_span = borrow_spans.var_or_use();
978 if let BorrowExplanation::MustBeValidFor {
986 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
991 opt_place_desc.as_ref(),
997 let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{}`", name));
999 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
1000 let region_name = annotation.emit(self, &mut err);
1004 format!("`{}` would have to be valid for `{}`...", name, region_name),
1007 let fn_hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(self.mir_def_id);
1011 "...but `{}` will be dropped here, when the {} returns",
1016 .opt_name(fn_hir_id)
1017 .map(|name| format!("function `{}`", name))
1018 .unwrap_or_else(|| {
1022 .typeck(self.mir_def_id)
1023 .node_type(fn_hir_id)
1026 ty::Closure(..) => "enclosing closure",
1027 ty::Generator(..) => "enclosing generator",
1028 kind => bug!("expected closure or generator, found {:?}", kind),
1036 "functions cannot return a borrow to data owned within the function's scope, \
1037 functions can only return borrows to data passed as arguments",
1040 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
1041 references-and-borrowing.html#dangling-references>",
1044 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
1046 explanation.add_explanation_to_diagnostic(
1056 err.span_label(borrow_span, "borrowed value does not live long enough");
1057 err.span_label(drop_span, format!("`{}` dropped here while still borrowed", name));
1059 let within = if borrow_spans.for_generator() { " by generator" } else { "" };
1061 borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));
1063 explanation.add_explanation_to_diagnostic(
1076 fn report_borrow_conflicts_with_destructor(
1079 borrow: &BorrowData<'tcx>,
1080 (place, drop_span): (Place<'tcx>, Span),
1081 kind: Option<WriteKind>,
1082 dropped_ty: Ty<'tcx>,
1085 "report_borrow_conflicts_with_destructor(\
1086 {:?}, {:?}, ({:?}, {:?}), {:?}\
1088 location, borrow, place, drop_span, kind,
1091 let borrow_spans = self.retrieve_borrow_spans(borrow);
1092 let borrow_span = borrow_spans.var_or_use();
1094 let mut err = self.cannot_borrow_across_destructor(borrow_span);
1096 let what_was_dropped = match self.describe_place(place.as_ref()) {
1097 Some(name) => format!("`{}`", name),
1098 None => String::from("temporary value"),
1101 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
1102 Some(borrowed) => format!(
1103 "here, drop of {D} needs exclusive access to `{B}`, \
1104 because the type `{T}` implements the `Drop` trait",
1105 D = what_was_dropped,
1110 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
1111 D = what_was_dropped,
1115 err.span_label(drop_span, label);
1117 // Only give this note and suggestion if they could be relevant.
1119 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
1121 BorrowExplanation::UsedLater { .. }
1122 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1123 err.note("consider using a `let` binding to create a longer lived value");
1128 explanation.add_explanation_to_diagnostic(
1137 err.buffer(&mut self.errors_buffer);
1140 fn report_thread_local_value_does_not_live_long_enough(
1144 ) -> DiagnosticBuilder<'cx> {
1146 "report_thread_local_value_does_not_live_long_enough(\
1149 drop_span, borrow_span
1152 let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1156 "thread-local variables cannot be borrowed beyond the end of the function",
1158 err.span_label(drop_span, "end of enclosing function is here");
1163 fn report_temporary_value_does_not_live_long_enough(
1166 borrow: &BorrowData<'tcx>,
1168 borrow_spans: UseSpans<'tcx>,
1170 explanation: BorrowExplanation,
1171 ) -> DiagnosticBuilder<'cx> {
1173 "report_temporary_value_does_not_live_long_enough(\
1174 {:?}, {:?}, {:?}, {:?}\
1176 location, borrow, drop_span, proper_span
1179 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
1182 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1193 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1194 err.span_label(proper_span, "creates a temporary which is freed while still in use");
1195 err.span_label(drop_span, "temporary value is freed at the end of this statement");
1198 BorrowExplanation::UsedLater(..)
1199 | BorrowExplanation::UsedLaterInLoop(..)
1200 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1201 // Only give this note and suggestion if it could be relevant.
1202 err.note("consider using a `let` binding to create a longer lived value");
1206 explanation.add_explanation_to_diagnostic(
1215 let within = if borrow_spans.for_generator() { " by generator" } else { "" };
1217 borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));
1222 fn try_report_cannot_return_reference_to_local(
1224 borrow: &BorrowData<'tcx>,
1227 category: ConstraintCategory,
1228 opt_place_desc: Option<&String>,
1229 ) -> Option<DiagnosticBuilder<'cx>> {
1230 let return_kind = match category {
1231 ConstraintCategory::Return(_) => "return",
1232 ConstraintCategory::Yield => "yield",
1236 // FIXME use a better heuristic than Spans
1237 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1243 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1244 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1245 match self.body.local_kind(local) {
1246 LocalKind::ReturnPointer | LocalKind::Temp => {
1247 bug!("temporary or return pointer with a name")
1249 LocalKind::Var => "local variable ",
1250 LocalKind::Arg if !self.upvars.is_empty() && local == Local::new(1) => {
1251 "variable captured by `move` "
1253 LocalKind::Arg => "function parameter ",
1259 format!("{}`{}`", local_kind, place_desc),
1260 format!("`{}` is borrowed here", place_desc),
1264 self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
1265 let local = root_place.local;
1266 match self.body.local_kind(local) {
1267 LocalKind::ReturnPointer | LocalKind::Temp => {
1268 ("temporary value".to_string(), "temporary value created here".to_string())
1271 "function parameter".to_string(),
1272 "function parameter borrowed here".to_string(),
1275 ("local binding".to_string(), "local binding introduced here".to_string())
1280 let mut err = self.cannot_return_reference_to_local(
1287 if return_span != borrow_span {
1288 err.span_label(borrow_span, note);
1294 fn report_escaping_closure_capture(
1296 use_span: UseSpans<'tcx>,
1298 fr_name: &RegionName,
1299 category: ConstraintCategory,
1300 constraint_span: Span,
1302 ) -> DiagnosticBuilder<'cx> {
1303 let tcx = self.infcx.tcx;
1304 let args_span = use_span.args_or_use();
1306 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1308 if string.starts_with("async ") {
1309 string.insert_str(6, "move ");
1310 } else if string.starts_with("async|") {
1311 string.insert_str(5, " move");
1313 string.insert_str(0, "move ");
1317 Err(_) => "move |<args>| <body>".to_string(),
1319 let kind = match use_span.generator_kind() {
1320 Some(generator_kind) => match generator_kind {
1321 GeneratorKind::Async(async_kind) => match async_kind {
1322 AsyncGeneratorKind::Block => "async block",
1323 AsyncGeneratorKind::Closure => "async closure",
1324 _ => bug!("async block/closure expected, but async function found."),
1326 GeneratorKind::Gen => "generator",
1332 self.cannot_capture_in_long_lived_closure(args_span, kind, captured_var, var_span);
1333 err.span_suggestion(
1336 "to force the {} to take ownership of {} (and any \
1337 other referenced variables), use the `move` keyword",
1341 Applicability::MachineApplicable,
1344 let msg = match category {
1345 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
1346 format!("{} is returned here", kind)
1348 ConstraintCategory::CallArgument => {
1349 fr_name.highlight_region_name(&mut err);
1350 format!("function requires argument type to outlive `{}`", fr_name)
1353 "report_escaping_closure_capture called with unexpected constraint \
1358 err.span_note(constraint_span, &msg);
1362 fn report_escaping_data(
1365 name: &Option<String>,
1369 ) -> DiagnosticBuilder<'cx> {
1370 let tcx = self.infcx.tcx;
1372 let (_, escapes_from) = tcx.article_and_description(self.mir_def_id.to_def_id());
1375 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
1379 format!("`{}` declared here, outside of the {} body", upvar_name, escapes_from),
1382 err.span_label(borrow_span, format!("borrow is only valid in the {} body", escapes_from));
1384 if let Some(name) = name {
1387 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1392 format!("reference escapes the {} body here", escapes_from),
1399 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1400 fn predecessor_locations(
1401 body: &'a mir::Body<'tcx>,
1403 ) -> impl Iterator<Item = Location> + 'a {
1404 if location.statement_index == 0 {
1405 let predecessors = body.predecessors()[location.block].to_vec();
1406 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
1408 Either::Right(std::iter::once(Location {
1409 statement_index: location.statement_index - 1,
1415 let mut stack = Vec::new();
1416 stack.extend(predecessor_locations(self.body, location).map(|predecessor| {
1417 let is_back_edge = location.dominates(predecessor, &self.dominators);
1418 (predecessor, is_back_edge)
1421 let mut visited = FxHashSet::default();
1422 let mut result = vec![];
1424 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1426 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1427 location, is_back_edge
1430 if !visited.insert(location) {
1436 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
1437 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1438 // this analysis only tries to find moves explicitly
1439 // written by the user, so we ignore the move-outs
1440 // created by `StorageDead` and at the beginning
1443 // If we are found a use of a.b.c which was in error, then we want to look for
1444 // moves not only of a.b.c but also a.b and a.
1446 // Note that the moves data already includes "parent" paths, so we don't have to
1447 // worry about the other case: that is, if there is a move of a.b.c, it is already
1448 // marked as a move of a.b and a as well, so we will generate the correct errors
1450 let mut mpis = vec![mpi];
1451 let move_paths = &self.move_data.move_paths;
1452 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
1454 for moi in &self.move_data.loc_map[location] {
1455 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1456 let path = self.move_data.moves[*moi].path;
1457 if mpis.contains(&path) {
1459 "report_use_of_moved_or_uninitialized: found {:?}",
1460 move_paths[path].place
1462 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
1464 // Strictly speaking, we could continue our DFS here. There may be
1465 // other moves that can reach the point of error. But it is kind of
1466 // confusing to highlight them.
1474 // drop(a); // <-- current point of error
1477 // Because we stop the DFS here, we only highlight `let c = a`,
1478 // and not `let b = a`. We will of course also report an error at
1479 // `let c = a` which highlights `let b = a` as the move.
1486 let mut any_match = false;
1487 drop_flag_effects::for_location_inits(
1502 stack.extend(predecessor_locations(self.body, location).map(|predecessor| {
1503 let back_edge = location.dominates(predecessor, &self.dominators);
1504 (predecessor, is_back_edge || back_edge)
1511 pub(in crate::borrow_check) fn report_illegal_mutation_of_borrowed(
1514 (place, span): (Place<'tcx>, Span),
1515 loan: &BorrowData<'tcx>,
1517 let loan_spans = self.retrieve_borrow_spans(loan);
1518 let loan_span = loan_spans.args_or_use();
1520 let descr_place = self.describe_any_place(place.as_ref());
1521 if loan.kind == BorrowKind::Shallow {
1522 if let Some(section) = self.classify_immutable_section(loan.assigned_place) {
1523 let mut err = self.cannot_mutate_in_immutable_section(
1530 loan_spans.var_span_label(
1532 format!("borrow occurs due to use{}", loan_spans.describe()),
1535 err.buffer(&mut self.errors_buffer);
1541 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
1544 .var_span_label(&mut err, format!("borrow occurs due to use{}", loan_spans.describe()));
1546 self.explain_why_borrow_contains_point(location, loan, None).add_explanation_to_diagnostic(
1555 err.buffer(&mut self.errors_buffer);
1558 /// Reports an illegal reassignment; for example, an assignment to
1559 /// (part of) a non-`mut` local that occurs potentially after that
1560 /// local has already been initialized. `place` is the path being
1561 /// assigned; `err_place` is a place providing a reason why
1562 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1563 /// assignment to `x.f`).
1564 pub(in crate::borrow_check) fn report_illegal_reassignment(
1566 _location: Location,
1567 (place, span): (Place<'tcx>, Span),
1568 assigned_span: Span,
1569 err_place: Place<'tcx>,
1571 let (from_arg, local_decl, local_name) = match err_place.as_local() {
1573 self.body.local_kind(local) == LocalKind::Arg,
1574 Some(&self.body.local_decls[local]),
1575 self.local_names[local],
1577 None => (false, None, None),
1580 // If root local is initialized immediately (everything apart from let
1581 // PATTERN;) then make the error refer to that local, rather than the
1582 // place being assigned later.
1583 let (place_description, assigned_span) = match local_decl {
1586 Some(box LocalInfo::User(
1587 ClearCrossCrate::Clear
1588 | ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1589 opt_match_place: None,
1593 | Some(box LocalInfo::StaticRef { .. })
1597 | None => (self.describe_any_place(place.as_ref()), assigned_span),
1598 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
1601 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
1602 let msg = if from_arg {
1603 "cannot assign to immutable argument"
1605 "cannot assign twice to immutable variable"
1607 if span != assigned_span {
1609 err.span_label(assigned_span, format!("first assignment to {}", place_description));
1612 if let Some(decl) = local_decl {
1613 if let Some(name) = local_name {
1614 if decl.can_be_made_mutable() {
1615 err.span_suggestion(
1616 decl.source_info.span,
1617 "make this binding mutable",
1618 format!("mut {}", name),
1619 Applicability::MachineApplicable,
1624 err.span_label(span, msg);
1625 err.buffer(&mut self.errors_buffer);
1628 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
1629 let tcx = self.infcx.tcx;
1630 match place.projection {
1631 [] => StorageDeadOrDrop::LocalStorageDead,
1632 [proj_base @ .., elem] => {
1633 // FIXME(spastorino) make this iterate
1634 let base_access = self.classify_drop_access_kind(PlaceRef {
1636 projection: proj_base,
1639 ProjectionElem::Deref => match base_access {
1640 StorageDeadOrDrop::LocalStorageDead
1641 | StorageDeadOrDrop::BoxedStorageDead => {
1643 Place::ty_from(place.local, proj_base, self.body, tcx).ty.is_box(),
1644 "Drop of value behind a reference or raw pointer"
1646 StorageDeadOrDrop::BoxedStorageDead
1648 StorageDeadOrDrop::Destructor(_) => base_access,
1650 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1651 let base_ty = Place::ty_from(place.local, proj_base, self.body, tcx).ty;
1652 match base_ty.kind() {
1653 ty::Adt(def, _) if def.has_dtor(tcx) => {
1654 // Report the outermost adt with a destructor
1656 StorageDeadOrDrop::Destructor(_) => base_access,
1657 StorageDeadOrDrop::LocalStorageDead
1658 | StorageDeadOrDrop::BoxedStorageDead => {
1659 StorageDeadOrDrop::Destructor(base_ty)
1667 ProjectionElem::ConstantIndex { .. }
1668 | ProjectionElem::Subslice { .. }
1669 | ProjectionElem::Index(_) => base_access,
1675 /// Describe the reason for the fake borrow that was assigned to `place`.
1676 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
1677 use rustc_middle::mir::visit::Visitor;
1678 struct FakeReadCauseFinder<'tcx> {
1680 cause: Option<FakeReadCause>,
1682 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
1683 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1685 Statement { kind: StatementKind::FakeRead(cause, box place), .. }
1686 if *place == self.place =>
1688 self.cause = Some(*cause);
1694 let mut visitor = FakeReadCauseFinder { place, cause: None };
1695 visitor.visit_body(&self.body);
1696 match visitor.cause {
1697 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1698 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1703 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1704 /// borrow of local value that does not live long enough.
1705 fn annotate_argument_and_return_for_borrow(
1707 borrow: &BorrowData<'tcx>,
1708 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1709 // Define a fallback for when we can't match a closure.
1711 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id.to_def_id());
1715 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1717 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1718 self.mir_def_id.to_def_id(),
1719 self.infcx.tcx.fn_sig(self.mir_def_id),
1726 // In order to determine whether we need to annotate, we need to check whether the reserve
1727 // place was an assignment into a temporary.
1729 // If it was, we check whether or not that temporary is eventually assigned into the return
1730 // place. If it was, we can add annotations about the function's return type and arguments
1731 // and it'll make sense.
1732 let location = borrow.reserve_location;
1733 debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
1734 if let Some(&Statement { kind: StatementKind::Assign(box (ref reservation, _)), .. }) =
1735 &self.body[location.block].statements.get(location.statement_index)
1737 debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
1738 // Check that the initial assignment of the reserve location is into a temporary.
1739 let mut target = match reservation.as_local() {
1740 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
1744 // Next, look through the rest of the block, checking if we are assigning the
1745 // `target` (that is, the place that contains our borrow) to anything.
1746 let mut annotated_closure = None;
1747 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1749 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1752 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind {
1753 if let Some(assigned_to) = place.as_local() {
1755 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1759 // Check if our `target` was captured by a closure.
1760 if let Rvalue::Aggregate(
1761 box AggregateKind::Closure(def_id, substs),
1765 for operand in operands {
1766 let assigned_from = match operand {
1767 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1773 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1777 // Find the local from the operand.
1778 let assigned_from_local = match assigned_from.local_or_deref_local()
1780 Some(local) => local,
1784 if assigned_from_local != target {
1788 // If a closure captured our `target` and then assigned
1789 // into a place then we should annotate the closure in
1790 // case it ends up being assigned into the return place.
1792 self.annotate_fn_sig(*def_id, substs.as_closure().sig());
1794 "annotate_argument_and_return_for_borrow: \
1795 annotated_closure={:?} assigned_from_local={:?} \
1797 annotated_closure, assigned_from_local, assigned_to
1800 if assigned_to == mir::RETURN_PLACE {
1801 // If it was assigned directly into the return place, then
1803 return annotated_closure;
1805 // Otherwise, update the target.
1806 target = assigned_to;
1810 // If none of our closure's operands matched, then skip to the next
1815 // Otherwise, look at other types of assignment.
1816 let assigned_from = match rvalue {
1817 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1818 Rvalue::Use(operand) => match operand {
1819 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1827 "annotate_argument_and_return_for_borrow: \
1828 assigned_from={:?}",
1832 // Find the local from the rvalue.
1833 let assigned_from_local = match assigned_from.local_or_deref_local() {
1834 Some(local) => local,
1838 "annotate_argument_and_return_for_borrow: \
1839 assigned_from_local={:?}",
1840 assigned_from_local,
1843 // Check if our local matches the target - if so, we've assigned our
1844 // borrow to a new place.
1845 if assigned_from_local != target {
1849 // If we assigned our `target` into a new place, then we should
1850 // check if it was the return place.
1852 "annotate_argument_and_return_for_borrow: \
1853 assigned_from_local={:?} assigned_to={:?}",
1854 assigned_from_local, assigned_to
1856 if assigned_to == mir::RETURN_PLACE {
1857 // If it was then return the annotated closure if there was one,
1858 // else, annotate this function.
1859 return annotated_closure.or_else(fallback);
1862 // If we didn't assign into the return place, then we just update
1864 target = assigned_to;
1869 // Check the terminator if we didn't find anything in the statements.
1870 let terminator = &self.body[location.block].terminator();
1872 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1875 if let TerminatorKind::Call { destination: Some((place, _)), args, .. } =
1878 if let Some(assigned_to) = place.as_local() {
1880 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1883 for operand in args {
1884 let assigned_from = match operand {
1885 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1891 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1895 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1897 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1898 assigned_from_local,
1901 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1902 return annotated_closure.or_else(fallback);
1910 // If we haven't found an assignment into the return place, then we need not add
1912 debug!("annotate_argument_and_return_for_borrow: none found");
1916 /// Annotate the first argument and return type of a function signature if they are
1921 sig: ty::PolyFnSig<'tcx>,
1922 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1923 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1924 let is_closure = self.infcx.tcx.is_closure(did);
1925 let fn_hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did.as_local()?);
1926 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1928 // We need to work out which arguments to highlight. We do this by looking
1929 // at the return type, where there are three cases:
1931 // 1. If there are named arguments, then we should highlight the return type and
1932 // highlight any of the arguments that are also references with that lifetime.
1933 // If there are no arguments that have the same lifetime as the return type,
1934 // then don't highlight anything.
1935 // 2. The return type is a reference with an anonymous lifetime. If this is
1936 // the case, then we can take advantage of (and teach) the lifetime elision
1939 // We know that an error is being reported. So the arguments and return type
1940 // must satisfy the elision rules. Therefore, if there is a single argument
1941 // then that means the return type and first (and only) argument have the same
1942 // lifetime and the borrow isn't meeting that, we can highlight the argument
1945 // If there are multiple arguments then the first argument must be self (else
1946 // it would not satisfy the elision rules), so we can highlight self and the
1948 // 3. The return type is not a reference. In this case, we don't highlight
1950 let return_ty = sig.output();
1951 match return_ty.skip_binder().kind() {
1952 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1953 // This is case 1 from above, return type is a named reference so we need to
1954 // search for relevant arguments.
1955 let mut arguments = Vec::new();
1956 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1957 if let ty::Ref(argument_region, _, _) = argument.kind() {
1958 if argument_region == return_region {
1959 // Need to use the `rustc_middle::ty` types to compare against the
1960 // `return_region`. Then use the `rustc_hir` type to get only
1961 // the lifetime span.
1962 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
1963 // With access to the lifetime, we can get
1965 arguments.push((*argument, lifetime.span));
1967 bug!("ty type is a ref but hir type is not");
1973 // We need to have arguments. This shouldn't happen, but it's worth checking.
1974 if arguments.is_empty() {
1978 // We use a mix of the HIR and the Ty types to get information
1979 // as the HIR doesn't have full types for closure arguments.
1980 let return_ty = sig.output().skip_binder();
1981 let mut return_span = fn_decl.output.span();
1982 if let hir::FnRetTy::Return(ty) = &fn_decl.output {
1983 if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
1984 return_span = lifetime.span;
1988 Some(AnnotatedBorrowFnSignature::NamedFunction {
1994 ty::Ref(_, _, _) if is_closure => {
1995 // This is case 2 from above but only for closures, return type is anonymous
1996 // reference so we select
1997 // the first argument.
1998 let argument_span = fn_decl.inputs.first()?.span;
1999 let argument_ty = sig.inputs().skip_binder().first()?;
2001 // Closure arguments are wrapped in a tuple, so we need to get the first
2003 if let ty::Tuple(elems) = argument_ty.kind() {
2004 let argument_ty = elems.first()?.expect_ty();
2005 if let ty::Ref(_, _, _) = argument_ty.kind() {
2006 return Some(AnnotatedBorrowFnSignature::Closure {
2015 ty::Ref(_, _, _) => {
2016 // This is also case 2 from above but for functions, return type is still an
2017 // anonymous reference so we select the first argument.
2018 let argument_span = fn_decl.inputs.first()?.span;
2019 let argument_ty = sig.inputs().skip_binder().first()?;
2021 let return_span = fn_decl.output.span();
2022 let return_ty = sig.output().skip_binder();
2024 // We expect the first argument to be a reference.
2025 match argument_ty.kind() {
2026 ty::Ref(_, _, _) => {}
2030 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2038 // This is case 3 from above, return type is not a reference so don't highlight
2047 enum AnnotatedBorrowFnSignature<'tcx> {
2049 arguments: Vec<(Ty<'tcx>, Span)>,
2050 return_ty: Ty<'tcx>,
2054 argument_ty: Ty<'tcx>,
2055 argument_span: Span,
2056 return_ty: Ty<'tcx>,
2060 argument_ty: Ty<'tcx>,
2061 argument_span: Span,
2065 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2066 /// Annotate the provided diagnostic with information about borrow from the fn signature that
2068 pub(in crate::borrow_check) fn emit(
2070 cx: &mut MirBorrowckCtxt<'_, 'tcx>,
2071 diag: &mut DiagnosticBuilder<'_>,
2074 AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
2077 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2080 cx.get_region_name_for_ty(argument_ty, 0)
2082 AnnotatedBorrowFnSignature::AnonymousFunction {
2088 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2089 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2091 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2092 let types_equal = return_ty_name == argument_ty_name;
2097 if types_equal { "also " } else { "" },
2103 "argument and return type have the same lifetime due to lifetime elision rules",
2106 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2107 lifetime-syntax.html#lifetime-elision>",
2110 cx.get_region_name_for_ty(return_ty, 0)
2112 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
2113 // Region of return type and arguments checked to be the same earlier.
2114 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2115 for (_, argument_span) in arguments {
2116 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2119 diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,));
2122 "use data from the highlighted arguments which match the `{}` lifetime of \