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) = tcx
343 .get_generics(tcx.closure_base_def_id(self.mir_def_id().to_def_id()))
345 suggest_constraining_type_param(
349 ¶m.name.as_str(),
355 let span = if let Some(local) = place.as_local() {
356 let decl = &self.body.local_decls[local];
357 Some(decl.source_info.span)
361 self.note_type_does_not_implement_copy(&mut err, ¬e_msg, ty, span, partial_str);
364 if let UseSpans::FnSelfUse {
365 kind: FnSelfUseKind::DerefCoercion { deref_target, deref_target_ty },
370 "{} occurs due to deref coercion to `{}`",
371 desired_action.as_noun(),
375 err.span_note(deref_target, "deref defined here");
378 if let Some((_, mut old_err)) =
379 self.move_error_reported.insert(move_out_indices, (used_place, err))
381 // Cancel the old error so it doesn't ICE.
387 pub(in crate::borrow_check) fn report_move_out_while_borrowed(
390 (place, span): (Place<'tcx>, Span),
391 borrow: &BorrowData<'tcx>,
394 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
395 location, place, span, borrow
397 let value_msg = self.describe_any_place(place.as_ref());
398 let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
400 let borrow_spans = self.retrieve_borrow_spans(borrow);
401 let borrow_span = borrow_spans.args_or_use();
403 let move_spans = self.move_spans(place.as_ref(), location);
404 let span = move_spans.args_or_use();
407 self.cannot_move_when_borrowed(span, &self.describe_any_place(place.as_ref()));
408 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
409 err.span_label(span, format!("move out of {} occurs here", value_msg));
411 borrow_spans.var_span_label(
413 format!("borrow occurs due to use{}", borrow_spans.describe()),
417 .var_span_label(&mut err, format!("move occurs due to use{}", move_spans.describe()));
419 self.explain_why_borrow_contains_point(location, borrow, None)
420 .add_explanation_to_diagnostic(
428 err.buffer(&mut self.errors_buffer);
431 pub(in crate::borrow_check) fn report_use_while_mutably_borrowed(
434 (place, _span): (Place<'tcx>, Span),
435 borrow: &BorrowData<'tcx>,
436 ) -> DiagnosticBuilder<'cx> {
437 let borrow_spans = self.retrieve_borrow_spans(borrow);
438 let borrow_span = borrow_spans.args_or_use();
440 // Conflicting borrows are reported separately, so only check for move
442 let use_spans = self.move_spans(place.as_ref(), location);
443 let span = use_spans.var_or_use();
445 let mut err = self.cannot_use_when_mutably_borrowed(
447 &self.describe_any_place(place.as_ref()),
449 &self.describe_any_place(borrow.borrowed_place.as_ref()),
452 borrow_spans.var_span_label(&mut err, {
453 let place = &borrow.borrowed_place;
454 let desc_place = self.describe_any_place(place.as_ref());
455 format!("borrow occurs due to use of {}{}", desc_place, borrow_spans.describe())
458 self.explain_why_borrow_contains_point(location, borrow, None)
459 .add_explanation_to_diagnostic(
470 pub(in crate::borrow_check) fn report_conflicting_borrow(
473 (place, span): (Place<'tcx>, Span),
474 gen_borrow_kind: BorrowKind,
475 issued_borrow: &BorrowData<'tcx>,
476 ) -> DiagnosticBuilder<'cx> {
477 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
478 let issued_span = issued_spans.args_or_use();
480 let borrow_spans = self.borrow_spans(span, location);
481 let span = borrow_spans.args_or_use();
483 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
489 let (desc_place, msg_place, msg_borrow, union_type_name) =
490 self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
492 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
493 let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
495 // FIXME: supply non-"" `opt_via` when appropriate
496 let first_borrow_desc;
497 let mut err = match (gen_borrow_kind, issued_borrow.kind) {
498 (BorrowKind::Shared, BorrowKind::Mut { .. }) => {
499 first_borrow_desc = "mutable ";
500 self.cannot_reborrow_already_borrowed(
512 (BorrowKind::Mut { .. }, BorrowKind::Shared) => {
513 first_borrow_desc = "immutable ";
514 self.cannot_reborrow_already_borrowed(
527 (BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
528 first_borrow_desc = "first ";
529 let mut err = self.cannot_mutably_borrow_multiply(
537 self.suggest_split_at_mut_if_applicable(
540 issued_borrow.borrowed_place,
545 (BorrowKind::Unique, BorrowKind::Unique) => {
546 first_borrow_desc = "first ";
547 self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
550 (BorrowKind::Mut { .. } | BorrowKind::Unique, BorrowKind::Shallow) => {
551 if let Some(immutable_section_description) =
552 self.classify_immutable_section(issued_borrow.assigned_place)
554 let mut err = self.cannot_mutate_in_immutable_section(
558 immutable_section_description,
561 borrow_spans.var_span_label(
564 "borrow occurs due to use of {}{}",
566 borrow_spans.describe(),
572 first_borrow_desc = "immutable ";
573 self.cannot_reborrow_already_borrowed(
587 (BorrowKind::Unique, _) => {
588 first_borrow_desc = "first ";
589 self.cannot_uniquely_borrow_by_one_closure(
601 (BorrowKind::Shared, BorrowKind::Unique) => {
602 first_borrow_desc = "first ";
603 self.cannot_reborrow_already_uniquely_borrowed(
616 (BorrowKind::Mut { .. }, BorrowKind::Unique) => {
617 first_borrow_desc = "first ";
618 self.cannot_reborrow_already_uniquely_borrowed(
631 (BorrowKind::Shared, BorrowKind::Shared | BorrowKind::Shallow)
634 BorrowKind::Mut { .. }
637 | BorrowKind::Shallow,
641 if issued_spans == borrow_spans {
642 borrow_spans.var_span_label(
644 format!("borrows occur due to use of {}{}", desc_place, borrow_spans.describe()),
647 let borrow_place = &issued_borrow.borrowed_place;
648 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
649 issued_spans.var_span_label(
652 "first borrow occurs due to use of {}{}",
654 issued_spans.describe(),
658 borrow_spans.var_span_label(
661 "second borrow occurs due to use of {}{}",
663 borrow_spans.describe(),
668 if union_type_name != "" {
670 "{} is a field of the union `{}`, so it overlaps the field {}",
671 msg_place, union_type_name, msg_borrow,
675 explanation.add_explanation_to_diagnostic(
687 fn suggest_split_at_mut_if_applicable(
689 err: &mut DiagnosticBuilder<'_>,
691 borrowed_place: Place<'tcx>,
693 if let ([ProjectionElem::Index(_)], [ProjectionElem::Index(_)]) =
694 (&place.projection[..], &borrowed_place.projection[..])
697 "consider using `.split_at_mut(position)` or similar method to obtain \
698 two mutable non-overlapping sub-slices",
703 /// Returns the description of the root place for a conflicting borrow and the full
704 /// descriptions of the places that caused the conflict.
706 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
707 /// attempted while a shared borrow is live, then this function will return:
711 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
712 /// a shared borrow of another field `x.y`, then this function will return:
714 /// ("x", "x.z", "x.y")
716 /// In the more complex union case, where the union is a field of a struct, then if a mutable
717 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
718 /// another field `x.u.y`, then this function will return:
720 /// ("x.u", "x.u.z", "x.u.y")
722 /// This is used when creating error messages like below:
725 /// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
726 /// mutable (via `a.u.s.b`) [E0502]
728 pub(in crate::borrow_check) fn describe_place_for_conflicting_borrow(
730 first_borrowed_place: Place<'tcx>,
731 second_borrowed_place: Place<'tcx>,
732 ) -> (String, String, String, String) {
733 // Define a small closure that we can use to check if the type of a place
735 let union_ty = |place_base, place_projection| {
736 let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
737 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
740 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
741 // code duplication (particularly around returning an empty description in the failure
745 // If we have a conflicting borrow of the same place, then we don't want to add
746 // an extraneous "via x.y" to our diagnostics, so filter out this case.
747 first_borrowed_place != second_borrowed_place
750 // We're going to want to traverse the first borrowed place to see if we can find
751 // field access to a union. If we find that, then we will keep the place of the
752 // union being accessed and the field that was being accessed so we can check the
753 // second borrowed place for the same union and a access to a different field.
754 let Place { local, projection } = first_borrowed_place;
756 let mut cursor = projection.as_ref();
757 while let [proj_base @ .., elem] = cursor {
761 ProjectionElem::Field(field, _) if union_ty(local, proj_base).is_some() => {
762 return Some((PlaceRef { local, projection: proj_base }, field));
769 .and_then(|(target_base, target_field)| {
770 // With the place of a union and a field access into it, we traverse the second
771 // borrowed place and look for a access to a different field of the same union.
772 let Place { local, ref projection } = second_borrowed_place;
774 let mut cursor = &projection[..];
775 while let [proj_base @ .., elem] = cursor {
778 if let ProjectionElem::Field(field, _) = elem {
779 if let Some(union_ty) = union_ty(local, proj_base) {
780 if field != target_field
781 && local == target_base.local
782 && proj_base == target_base.projection
785 self.describe_any_place(PlaceRef {
787 projection: proj_base,
789 self.describe_any_place(first_borrowed_place.as_ref()),
790 self.describe_any_place(second_borrowed_place.as_ref()),
791 union_ty.to_string(),
800 // If we didn't find a field access into a union, or both places match, then
801 // only return the description of the first place.
803 self.describe_any_place(first_borrowed_place.as_ref()),
811 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
813 /// This means that some data referenced by `borrow` needs to live
814 /// past the point where the StorageDeadOrDrop of `place` occurs.
815 /// This is usually interpreted as meaning that `place` has too
816 /// short a lifetime. (But sometimes it is more useful to report
817 /// it as a more direct conflict between the execution of a
818 /// `Drop::drop` with an aliasing borrow.)
819 pub(in crate::borrow_check) fn report_borrowed_value_does_not_live_long_enough(
822 borrow: &BorrowData<'tcx>,
823 place_span: (Place<'tcx>, Span),
824 kind: Option<WriteKind>,
827 "report_borrowed_value_does_not_live_long_enough(\
828 {:?}, {:?}, {:?}, {:?}\
830 location, borrow, place_span, kind
833 let drop_span = place_span.1;
835 self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
837 let borrow_spans = self.retrieve_borrow_spans(borrow);
838 let borrow_span = borrow_spans.var_or_use();
840 assert!(root_place.projection.is_empty());
841 let proper_span = self.body.local_decls[root_place.local].source_info.span;
843 let root_place_projection = self.infcx.tcx.intern_place_elems(root_place.projection);
845 if self.access_place_error_reported.contains(&(
846 Place { local: root_place.local, projection: root_place_projection },
850 "suppressing access_place error when borrow doesn't live long enough for {:?}",
856 self.access_place_error_reported.insert((
857 Place { local: root_place.local, projection: root_place_projection },
861 let borrowed_local = borrow.borrowed_place.local;
862 if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
864 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
865 err.buffer(&mut self.errors_buffer);
869 if let StorageDeadOrDrop::Destructor(dropped_ty) =
870 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
872 // If a borrow of path `B` conflicts with drop of `D` (and
873 // we're not in the uninteresting case where `B` is a
874 // prefix of `D`), then report this as a more interesting
875 // destructor conflict.
876 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
877 self.report_borrow_conflicts_with_destructor(
878 location, borrow, place_span, kind, dropped_ty,
884 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
886 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
887 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
890 "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
891 place_desc, explanation
893 let err = match (place_desc, explanation) {
894 // If the outlives constraint comes from inside the closure,
899 // Box::new(|| y) as Box<Fn() -> &'static i32>
901 // then just use the normal error. The closure isn't escaping
902 // and `move` will not help here.
905 BorrowExplanation::MustBeValidFor {
909 (ConstraintCategory::Return(_)
910 | ConstraintCategory::CallArgument
911 | ConstraintCategory::OpaqueType),
917 ) if borrow_spans.for_generator() | borrow_spans.for_closure() => self
918 .report_escaping_closure_capture(
924 &format!("`{}`", name),
928 BorrowExplanation::MustBeValidFor {
929 category: ConstraintCategory::Assignment,
934 RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
940 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
941 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
949 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
959 err.buffer(&mut self.errors_buffer);
962 fn report_local_value_does_not_live_long_enough(
966 borrow: &BorrowData<'tcx>,
968 borrow_spans: UseSpans<'tcx>,
969 explanation: BorrowExplanation,
970 ) -> DiagnosticBuilder<'cx> {
972 "report_local_value_does_not_live_long_enough(\
973 {:?}, {:?}, {:?}, {:?}, {:?}\
975 location, name, borrow, drop_span, borrow_spans
978 let borrow_span = borrow_spans.var_or_use();
979 if let BorrowExplanation::MustBeValidFor {
987 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
992 opt_place_desc.as_ref(),
998 let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{}`", name));
1000 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
1001 let region_name = annotation.emit(self, &mut err);
1005 format!("`{}` would have to be valid for `{}`...", name, region_name),
1008 let fn_hir_id = self.mir_hir_id();
1012 "...but `{}` will be dropped here, when the {} returns",
1017 .opt_name(fn_hir_id)
1018 .map(|name| format!("function `{}`", name))
1019 .unwrap_or_else(|| {
1023 .typeck(self.mir_def_id())
1024 .node_type(fn_hir_id)
1027 ty::Closure(..) => "enclosing closure",
1028 ty::Generator(..) => "enclosing generator",
1029 kind => bug!("expected closure or generator, found {:?}", kind),
1037 "functions cannot return a borrow to data owned within the function's scope, \
1038 functions can only return borrows to data passed as arguments",
1041 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
1042 references-and-borrowing.html#dangling-references>",
1045 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
1047 explanation.add_explanation_to_diagnostic(
1057 err.span_label(borrow_span, "borrowed value does not live long enough");
1058 err.span_label(drop_span, format!("`{}` dropped here while still borrowed", name));
1060 let within = if borrow_spans.for_generator() { " by generator" } else { "" };
1062 borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));
1064 explanation.add_explanation_to_diagnostic(
1077 fn report_borrow_conflicts_with_destructor(
1080 borrow: &BorrowData<'tcx>,
1081 (place, drop_span): (Place<'tcx>, Span),
1082 kind: Option<WriteKind>,
1083 dropped_ty: Ty<'tcx>,
1086 "report_borrow_conflicts_with_destructor(\
1087 {:?}, {:?}, ({:?}, {:?}), {:?}\
1089 location, borrow, place, drop_span, kind,
1092 let borrow_spans = self.retrieve_borrow_spans(borrow);
1093 let borrow_span = borrow_spans.var_or_use();
1095 let mut err = self.cannot_borrow_across_destructor(borrow_span);
1097 let what_was_dropped = match self.describe_place(place.as_ref()) {
1098 Some(name) => format!("`{}`", name),
1099 None => String::from("temporary value"),
1102 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
1103 Some(borrowed) => format!(
1104 "here, drop of {D} needs exclusive access to `{B}`, \
1105 because the type `{T}` implements the `Drop` trait",
1106 D = what_was_dropped,
1111 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
1112 D = what_was_dropped,
1116 err.span_label(drop_span, label);
1118 // Only give this note and suggestion if they could be relevant.
1120 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
1122 BorrowExplanation::UsedLater { .. }
1123 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1124 err.note("consider using a `let` binding to create a longer lived value");
1129 explanation.add_explanation_to_diagnostic(
1138 err.buffer(&mut self.errors_buffer);
1141 fn report_thread_local_value_does_not_live_long_enough(
1145 ) -> DiagnosticBuilder<'cx> {
1147 "report_thread_local_value_does_not_live_long_enough(\
1150 drop_span, borrow_span
1153 let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1157 "thread-local variables cannot be borrowed beyond the end of the function",
1159 err.span_label(drop_span, "end of enclosing function is here");
1164 fn report_temporary_value_does_not_live_long_enough(
1167 borrow: &BorrowData<'tcx>,
1169 borrow_spans: UseSpans<'tcx>,
1171 explanation: BorrowExplanation,
1172 ) -> DiagnosticBuilder<'cx> {
1174 "report_temporary_value_does_not_live_long_enough(\
1175 {:?}, {:?}, {:?}, {:?}\
1177 location, borrow, drop_span, proper_span
1180 if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
1183 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1194 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1195 err.span_label(proper_span, "creates a temporary which is freed while still in use");
1196 err.span_label(drop_span, "temporary value is freed at the end of this statement");
1199 BorrowExplanation::UsedLater(..)
1200 | BorrowExplanation::UsedLaterInLoop(..)
1201 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1202 // Only give this note and suggestion if it could be relevant.
1203 err.note("consider using a `let` binding to create a longer lived value");
1207 explanation.add_explanation_to_diagnostic(
1216 let within = if borrow_spans.for_generator() { " by generator" } else { "" };
1218 borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));
1223 fn try_report_cannot_return_reference_to_local(
1225 borrow: &BorrowData<'tcx>,
1228 category: ConstraintCategory,
1229 opt_place_desc: Option<&String>,
1230 ) -> Option<DiagnosticBuilder<'cx>> {
1231 let return_kind = match category {
1232 ConstraintCategory::Return(_) => "return",
1233 ConstraintCategory::Yield => "yield",
1237 // FIXME use a better heuristic than Spans
1238 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1244 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1245 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1246 match self.body.local_kind(local) {
1247 LocalKind::ReturnPointer | LocalKind::Temp => {
1248 bug!("temporary or return pointer with a name")
1250 LocalKind::Var => "local variable ",
1251 LocalKind::Arg if !self.upvars.is_empty() && local == Local::new(1) => {
1252 "variable captured by `move` "
1254 LocalKind::Arg => "function parameter ",
1260 format!("{}`{}`", local_kind, place_desc),
1261 format!("`{}` is borrowed here", place_desc),
1265 self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
1266 let local = root_place.local;
1267 match self.body.local_kind(local) {
1268 LocalKind::ReturnPointer | LocalKind::Temp => {
1269 ("temporary value".to_string(), "temporary value created here".to_string())
1272 "function parameter".to_string(),
1273 "function parameter borrowed here".to_string(),
1276 ("local binding".to_string(), "local binding introduced here".to_string())
1281 let mut err = self.cannot_return_reference_to_local(
1288 if return_span != borrow_span {
1289 err.span_label(borrow_span, note);
1295 fn report_escaping_closure_capture(
1297 use_span: UseSpans<'tcx>,
1299 fr_name: &RegionName,
1300 category: ConstraintCategory,
1301 constraint_span: Span,
1303 ) -> DiagnosticBuilder<'cx> {
1304 let tcx = self.infcx.tcx;
1305 let args_span = use_span.args_or_use();
1307 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1309 if string.starts_with("async ") {
1310 string.insert_str(6, "move ");
1311 } else if string.starts_with("async|") {
1312 string.insert_str(5, " move");
1314 string.insert_str(0, "move ");
1318 Err(_) => "move |<args>| <body>".to_string(),
1320 let kind = match use_span.generator_kind() {
1321 Some(generator_kind) => match generator_kind {
1322 GeneratorKind::Async(async_kind) => match async_kind {
1323 AsyncGeneratorKind::Block => "async block",
1324 AsyncGeneratorKind::Closure => "async closure",
1325 _ => bug!("async block/closure expected, but async function found."),
1327 GeneratorKind::Gen => "generator",
1333 self.cannot_capture_in_long_lived_closure(args_span, kind, captured_var, var_span);
1334 err.span_suggestion(
1337 "to force the {} to take ownership of {} (and any \
1338 other referenced variables), use the `move` keyword",
1342 Applicability::MachineApplicable,
1345 let msg = match category {
1346 ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
1347 format!("{} is returned here", kind)
1349 ConstraintCategory::CallArgument => {
1350 fr_name.highlight_region_name(&mut err);
1351 format!("function requires argument type to outlive `{}`", fr_name)
1354 "report_escaping_closure_capture called with unexpected constraint \
1359 err.span_note(constraint_span, &msg);
1363 fn report_escaping_data(
1366 name: &Option<String>,
1370 ) -> DiagnosticBuilder<'cx> {
1371 let tcx = self.infcx.tcx;
1373 let (_, escapes_from) = tcx.article_and_description(self.mir_def_id().to_def_id());
1376 borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
1380 format!("`{}` declared here, outside of the {} body", upvar_name, escapes_from),
1383 err.span_label(borrow_span, format!("borrow is only valid in the {} body", escapes_from));
1385 if let Some(name) = name {
1388 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1393 format!("reference escapes the {} body here", escapes_from),
1400 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1401 fn predecessor_locations(
1402 body: &'a mir::Body<'tcx>,
1404 ) -> impl Iterator<Item = Location> + 'a {
1405 if location.statement_index == 0 {
1406 let predecessors = body.predecessors()[location.block].to_vec();
1407 Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
1409 Either::Right(std::iter::once(Location {
1410 statement_index: location.statement_index - 1,
1416 let mut stack = Vec::new();
1417 stack.extend(predecessor_locations(self.body, location).map(|predecessor| {
1418 let is_back_edge = location.dominates(predecessor, &self.dominators);
1419 (predecessor, is_back_edge)
1422 let mut visited = FxHashSet::default();
1423 let mut result = vec![];
1425 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1427 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1428 location, is_back_edge
1431 if !visited.insert(location) {
1437 self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
1438 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1439 // this analysis only tries to find moves explicitly
1440 // written by the user, so we ignore the move-outs
1441 // created by `StorageDead` and at the beginning
1444 // If we are found a use of a.b.c which was in error, then we want to look for
1445 // moves not only of a.b.c but also a.b and a.
1447 // Note that the moves data already includes "parent" paths, so we don't have to
1448 // worry about the other case: that is, if there is a move of a.b.c, it is already
1449 // marked as a move of a.b and a as well, so we will generate the correct errors
1451 let mut mpis = vec![mpi];
1452 let move_paths = &self.move_data.move_paths;
1453 mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
1455 for moi in &self.move_data.loc_map[location] {
1456 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1457 let path = self.move_data.moves[*moi].path;
1458 if mpis.contains(&path) {
1460 "report_use_of_moved_or_uninitialized: found {:?}",
1461 move_paths[path].place
1463 result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
1465 // Strictly speaking, we could continue our DFS here. There may be
1466 // other moves that can reach the point of error. But it is kind of
1467 // confusing to highlight them.
1475 // drop(a); // <-- current point of error
1478 // Because we stop the DFS here, we only highlight `let c = a`,
1479 // and not `let b = a`. We will of course also report an error at
1480 // `let c = a` which highlights `let b = a` as the move.
1487 let mut any_match = false;
1488 drop_flag_effects::for_location_inits(
1503 stack.extend(predecessor_locations(self.body, location).map(|predecessor| {
1504 let back_edge = location.dominates(predecessor, &self.dominators);
1505 (predecessor, is_back_edge || back_edge)
1512 pub(in crate::borrow_check) fn report_illegal_mutation_of_borrowed(
1515 (place, span): (Place<'tcx>, Span),
1516 loan: &BorrowData<'tcx>,
1518 let loan_spans = self.retrieve_borrow_spans(loan);
1519 let loan_span = loan_spans.args_or_use();
1521 let descr_place = self.describe_any_place(place.as_ref());
1522 if loan.kind == BorrowKind::Shallow {
1523 if let Some(section) = self.classify_immutable_section(loan.assigned_place) {
1524 let mut err = self.cannot_mutate_in_immutable_section(
1531 loan_spans.var_span_label(
1533 format!("borrow occurs due to use{}", loan_spans.describe()),
1536 err.buffer(&mut self.errors_buffer);
1542 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
1545 .var_span_label(&mut err, format!("borrow occurs due to use{}", loan_spans.describe()));
1547 self.explain_why_borrow_contains_point(location, loan, None).add_explanation_to_diagnostic(
1556 err.buffer(&mut self.errors_buffer);
1559 /// Reports an illegal reassignment; for example, an assignment to
1560 /// (part of) a non-`mut` local that occurs potentially after that
1561 /// local has already been initialized. `place` is the path being
1562 /// assigned; `err_place` is a place providing a reason why
1563 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1564 /// assignment to `x.f`).
1565 pub(in crate::borrow_check) fn report_illegal_reassignment(
1567 _location: Location,
1568 (place, span): (Place<'tcx>, Span),
1569 assigned_span: Span,
1570 err_place: Place<'tcx>,
1572 let (from_arg, local_decl, local_name) = match err_place.as_local() {
1574 self.body.local_kind(local) == LocalKind::Arg,
1575 Some(&self.body.local_decls[local]),
1576 self.local_names[local],
1578 None => (false, None, None),
1581 // If root local is initialized immediately (everything apart from let
1582 // PATTERN;) then make the error refer to that local, rather than the
1583 // place being assigned later.
1584 let (place_description, assigned_span) = match local_decl {
1587 Some(box LocalInfo::User(
1588 ClearCrossCrate::Clear
1589 | ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1590 opt_match_place: None,
1594 | Some(box LocalInfo::StaticRef { .. })
1598 | None => (self.describe_any_place(place.as_ref()), assigned_span),
1599 Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
1602 let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
1603 let msg = if from_arg {
1604 "cannot assign to immutable argument"
1606 "cannot assign twice to immutable variable"
1608 if span != assigned_span {
1610 err.span_label(assigned_span, format!("first assignment to {}", place_description));
1613 if let Some(decl) = local_decl {
1614 if let Some(name) = local_name {
1615 if decl.can_be_made_mutable() {
1616 err.span_suggestion(
1617 decl.source_info.span,
1618 "make this binding mutable",
1619 format!("mut {}", name),
1620 Applicability::MachineApplicable,
1625 err.span_label(span, msg);
1626 err.buffer(&mut self.errors_buffer);
1629 fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
1630 let tcx = self.infcx.tcx;
1631 match place.projection {
1632 [] => StorageDeadOrDrop::LocalStorageDead,
1633 [proj_base @ .., elem] => {
1634 // FIXME(spastorino) make this iterate
1635 let base_access = self.classify_drop_access_kind(PlaceRef {
1637 projection: proj_base,
1640 ProjectionElem::Deref => match base_access {
1641 StorageDeadOrDrop::LocalStorageDead
1642 | StorageDeadOrDrop::BoxedStorageDead => {
1644 Place::ty_from(place.local, proj_base, self.body, tcx).ty.is_box(),
1645 "Drop of value behind a reference or raw pointer"
1647 StorageDeadOrDrop::BoxedStorageDead
1649 StorageDeadOrDrop::Destructor(_) => base_access,
1651 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1652 let base_ty = Place::ty_from(place.local, proj_base, self.body, tcx).ty;
1653 match base_ty.kind() {
1654 ty::Adt(def, _) if def.has_dtor(tcx) => {
1655 // Report the outermost adt with a destructor
1657 StorageDeadOrDrop::Destructor(_) => base_access,
1658 StorageDeadOrDrop::LocalStorageDead
1659 | StorageDeadOrDrop::BoxedStorageDead => {
1660 StorageDeadOrDrop::Destructor(base_ty)
1668 ProjectionElem::ConstantIndex { .. }
1669 | ProjectionElem::Subslice { .. }
1670 | ProjectionElem::Index(_) => base_access,
1676 /// Describe the reason for the fake borrow that was assigned to `place`.
1677 fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
1678 use rustc_middle::mir::visit::Visitor;
1679 struct FakeReadCauseFinder<'tcx> {
1681 cause: Option<FakeReadCause>,
1683 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
1684 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1686 Statement { kind: StatementKind::FakeRead(cause, box place), .. }
1687 if *place == self.place =>
1689 self.cause = Some(*cause);
1695 let mut visitor = FakeReadCauseFinder { place, cause: None };
1696 visitor.visit_body(&self.body);
1697 match visitor.cause {
1698 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1699 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1704 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1705 /// borrow of local value that does not live long enough.
1706 fn annotate_argument_and_return_for_borrow(
1708 borrow: &BorrowData<'tcx>,
1709 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1710 // Define a fallback for when we can't match a closure.
1712 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id().to_def_id());
1716 let ty = self.infcx.tcx.type_of(self.mir_def_id());
1718 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1719 self.mir_def_id().to_def_id(),
1720 self.infcx.tcx.fn_sig(self.mir_def_id()),
1727 // In order to determine whether we need to annotate, we need to check whether the reserve
1728 // place was an assignment into a temporary.
1730 // If it was, we check whether or not that temporary is eventually assigned into the return
1731 // place. If it was, we can add annotations about the function's return type and arguments
1732 // and it'll make sense.
1733 let location = borrow.reserve_location;
1734 debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
1735 if let Some(&Statement { kind: StatementKind::Assign(box (ref reservation, _)), .. }) =
1736 &self.body[location.block].statements.get(location.statement_index)
1738 debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
1739 // Check that the initial assignment of the reserve location is into a temporary.
1740 let mut target = match reservation.as_local() {
1741 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
1745 // Next, look through the rest of the block, checking if we are assigning the
1746 // `target` (that is, the place that contains our borrow) to anything.
1747 let mut annotated_closure = None;
1748 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1750 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1753 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind {
1754 if let Some(assigned_to) = place.as_local() {
1756 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1760 // Check if our `target` was captured by a closure.
1761 if let Rvalue::Aggregate(
1762 box AggregateKind::Closure(def_id, substs),
1766 for operand in operands {
1767 let assigned_from = match operand {
1768 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1774 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1778 // Find the local from the operand.
1779 let assigned_from_local = match assigned_from.local_or_deref_local()
1781 Some(local) => local,
1785 if assigned_from_local != target {
1789 // If a closure captured our `target` and then assigned
1790 // into a place then we should annotate the closure in
1791 // case it ends up being assigned into the return place.
1793 self.annotate_fn_sig(*def_id, substs.as_closure().sig());
1795 "annotate_argument_and_return_for_borrow: \
1796 annotated_closure={:?} assigned_from_local={:?} \
1798 annotated_closure, assigned_from_local, assigned_to
1801 if assigned_to == mir::RETURN_PLACE {
1802 // If it was assigned directly into the return place, then
1804 return annotated_closure;
1806 // Otherwise, update the target.
1807 target = assigned_to;
1811 // If none of our closure's operands matched, then skip to the next
1816 // Otherwise, look at other types of assignment.
1817 let assigned_from = match rvalue {
1818 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1819 Rvalue::Use(operand) => match operand {
1820 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1828 "annotate_argument_and_return_for_borrow: \
1829 assigned_from={:?}",
1833 // Find the local from the rvalue.
1834 let assigned_from_local = match assigned_from.local_or_deref_local() {
1835 Some(local) => local,
1839 "annotate_argument_and_return_for_borrow: \
1840 assigned_from_local={:?}",
1841 assigned_from_local,
1844 // Check if our local matches the target - if so, we've assigned our
1845 // borrow to a new place.
1846 if assigned_from_local != target {
1850 // If we assigned our `target` into a new place, then we should
1851 // check if it was the return place.
1853 "annotate_argument_and_return_for_borrow: \
1854 assigned_from_local={:?} assigned_to={:?}",
1855 assigned_from_local, assigned_to
1857 if assigned_to == mir::RETURN_PLACE {
1858 // If it was then return the annotated closure if there was one,
1859 // else, annotate this function.
1860 return annotated_closure.or_else(fallback);
1863 // If we didn't assign into the return place, then we just update
1865 target = assigned_to;
1870 // Check the terminator if we didn't find anything in the statements.
1871 let terminator = &self.body[location.block].terminator();
1873 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1876 if let TerminatorKind::Call { destination: Some((place, _)), args, .. } =
1879 if let Some(assigned_to) = place.as_local() {
1881 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1884 for operand in args {
1885 let assigned_from = match operand {
1886 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1892 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1896 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1898 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1899 assigned_from_local,
1902 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1903 return annotated_closure.or_else(fallback);
1911 // If we haven't found an assignment into the return place, then we need not add
1913 debug!("annotate_argument_and_return_for_borrow: none found");
1917 /// Annotate the first argument and return type of a function signature if they are
1922 sig: ty::PolyFnSig<'tcx>,
1923 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1924 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1925 let is_closure = self.infcx.tcx.is_closure(did);
1926 let fn_hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did.as_local()?);
1927 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1929 // We need to work out which arguments to highlight. We do this by looking
1930 // at the return type, where there are three cases:
1932 // 1. If there are named arguments, then we should highlight the return type and
1933 // highlight any of the arguments that are also references with that lifetime.
1934 // If there are no arguments that have the same lifetime as the return type,
1935 // then don't highlight anything.
1936 // 2. The return type is a reference with an anonymous lifetime. If this is
1937 // the case, then we can take advantage of (and teach) the lifetime elision
1940 // We know that an error is being reported. So the arguments and return type
1941 // must satisfy the elision rules. Therefore, if there is a single argument
1942 // then that means the return type and first (and only) argument have the same
1943 // lifetime and the borrow isn't meeting that, we can highlight the argument
1946 // If there are multiple arguments then the first argument must be self (else
1947 // it would not satisfy the elision rules), so we can highlight self and the
1949 // 3. The return type is not a reference. In this case, we don't highlight
1951 let return_ty = sig.output();
1952 match return_ty.skip_binder().kind() {
1953 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1954 // This is case 1 from above, return type is a named reference so we need to
1955 // search for relevant arguments.
1956 let mut arguments = Vec::new();
1957 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1958 if let ty::Ref(argument_region, _, _) = argument.kind() {
1959 if argument_region == return_region {
1960 // Need to use the `rustc_middle::ty` types to compare against the
1961 // `return_region`. Then use the `rustc_hir` type to get only
1962 // the lifetime span.
1963 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
1964 // With access to the lifetime, we can get
1966 arguments.push((*argument, lifetime.span));
1968 bug!("ty type is a ref but hir type is not");
1974 // We need to have arguments. This shouldn't happen, but it's worth checking.
1975 if arguments.is_empty() {
1979 // We use a mix of the HIR and the Ty types to get information
1980 // as the HIR doesn't have full types for closure arguments.
1981 let return_ty = sig.output().skip_binder();
1982 let mut return_span = fn_decl.output.span();
1983 if let hir::FnRetTy::Return(ty) = &fn_decl.output {
1984 if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
1985 return_span = lifetime.span;
1989 Some(AnnotatedBorrowFnSignature::NamedFunction {
1995 ty::Ref(_, _, _) if is_closure => {
1996 // This is case 2 from above but only for closures, return type is anonymous
1997 // reference so we select
1998 // the first argument.
1999 let argument_span = fn_decl.inputs.first()?.span;
2000 let argument_ty = sig.inputs().skip_binder().first()?;
2002 // Closure arguments are wrapped in a tuple, so we need to get the first
2004 if let ty::Tuple(elems) = argument_ty.kind() {
2005 let argument_ty = elems.first()?.expect_ty();
2006 if let ty::Ref(_, _, _) = argument_ty.kind() {
2007 return Some(AnnotatedBorrowFnSignature::Closure {
2016 ty::Ref(_, _, _) => {
2017 // This is also case 2 from above but for functions, return type is still an
2018 // anonymous reference so we select the first argument.
2019 let argument_span = fn_decl.inputs.first()?.span;
2020 let argument_ty = sig.inputs().skip_binder().first()?;
2022 let return_span = fn_decl.output.span();
2023 let return_ty = sig.output().skip_binder();
2025 // We expect the first argument to be a reference.
2026 match argument_ty.kind() {
2027 ty::Ref(_, _, _) => {}
2031 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2039 // This is case 3 from above, return type is not a reference so don't highlight
2048 enum AnnotatedBorrowFnSignature<'tcx> {
2050 arguments: Vec<(Ty<'tcx>, Span)>,
2051 return_ty: Ty<'tcx>,
2055 argument_ty: Ty<'tcx>,
2056 argument_span: Span,
2057 return_ty: Ty<'tcx>,
2061 argument_ty: Ty<'tcx>,
2062 argument_span: Span,
2066 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2067 /// Annotate the provided diagnostic with information about borrow from the fn signature that
2069 pub(in crate::borrow_check) fn emit(
2071 cx: &mut MirBorrowckCtxt<'_, 'tcx>,
2072 diag: &mut DiagnosticBuilder<'_>,
2075 AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
2078 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2081 cx.get_region_name_for_ty(argument_ty, 0)
2083 AnnotatedBorrowFnSignature::AnonymousFunction {
2089 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2090 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2092 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2093 let types_equal = return_ty_name == argument_ty_name;
2098 if types_equal { "also " } else { "" },
2104 "argument and return type have the same lifetime due to lifetime elision rules",
2107 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2108 lifetime-syntax.html#lifetime-elision>",
2111 cx.get_region_name_for_ty(return_ty, 0)
2113 AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
2114 // Region of return type and arguments checked to be the same earlier.
2115 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2116 for (_, argument_span) in arguments {
2117 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2120 diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,));
2123 "use data from the highlighted arguments which match the `{}` lifetime of \