2 use rustc::hir::def_id::DefId;
3 use rustc::hir::{AsyncGeneratorKind, GeneratorKind};
5 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
6 FakeReadCause, Local, LocalDecl, LocalKind, Location, Operand, Place, PlaceBase, PlaceRef,
7 ProjectionElem, Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
9 use rustc::ty::{self, Ty};
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_index::vec::Idx;
12 use rustc_errors::{Applicability, DiagnosticBuilder};
14 use syntax::source_map::DesugaringKind;
16 use super::nll::explain_borrow::BorrowExplanation;
17 use super::nll::region_infer::{RegionName, RegionNameSource};
18 use super::prefixes::IsPrefixOf;
20 use super::borrow_set::BorrowData;
21 use super::MirBorrowckCtxt;
22 use super::{InitializationRequiringAction, PrefixSet};
23 use super::error_reporting::{IncludingDowncast, UseSpans};
24 use crate::dataflow::drop_flag_effects;
25 use crate::dataflow::indexes::{MovePathIndex, MoveOutIndex};
26 use crate::util::borrowck_errors;
30 /// Index of the "move out" that we found. The `MoveData` can
31 /// then tell us where the move occurred.
34 /// `true` if we traversed a back edge while walking from the point
35 /// of error to the move site.
36 traversed_back_edge: bool
39 /// Which case a StorageDeadOrDrop is for.
40 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
41 enum StorageDeadOrDrop<'tcx> {
47 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
48 pub(super) fn report_use_of_moved_or_uninitialized(
51 desired_action: InitializationRequiringAction,
52 (moved_place, used_place, span): (PlaceRef<'cx, 'tcx>, PlaceRef<'cx, 'tcx>, Span),
56 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
57 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
58 location, desired_action, moved_place, used_place, span, mpi
61 let use_spans = self.move_spans(moved_place, location)
62 .or_else(|| self.borrow_spans(span, location));
63 let span = use_spans.args_or_use();
65 let move_site_vec = self.get_moved_indexes(location, mpi);
67 "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
70 let move_out_indices: Vec<_> = move_site_vec
72 .map(|move_site| move_site.moi)
75 if move_out_indices.is_empty() {
77 .prefixes(used_place, PrefixSet::All)
81 if !self.uninitialized_error_reported.insert(root_place) {
83 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
89 let item_msg = match self.describe_place_with_options(used_place,
90 IncludingDowncast(true)) {
91 Some(name) => format!("`{}`", name),
92 None => "value".to_owned(),
94 let mut err = self.cannot_act_on_uninitialized_variable(
96 desired_action.as_noun(),
97 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
98 .unwrap_or_else(|| "_".to_owned()),
100 err.span_label(span, format!("use of possibly-uninitialized {}", item_msg));
102 use_spans.var_span_label(
104 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
107 err.buffer(&mut self.errors_buffer);
109 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
110 if self.prefixes(*reported_place, PrefixSet::All)
111 .any(|p| p == used_place)
114 "report_use_of_moved_or_uninitialized place: error suppressed \
122 let msg = ""; //FIXME: add "partially " or "collaterally "
124 let mut err = self.cannot_act_on_moved_value(
126 desired_action.as_noun(),
128 self.describe_place_with_options(moved_place, IncludingDowncast(true)),
131 self.add_moved_or_invoked_closure_note(
137 let mut is_loop_move = false;
138 let is_partial_move = move_site_vec.iter().any(|move_site| {
139 let move_out = self.move_data.moves[(*move_site).moi];
140 let moved_place = &self.move_data.move_paths[move_out.path].place;
141 used_place != moved_place.as_ref()
142 && used_place.is_prefix_of(moved_place.as_ref())
144 for move_site in &move_site_vec {
145 let move_out = self.move_data.moves[(*move_site).moi];
146 let moved_place = &self.move_data.move_paths[move_out.path].place;
148 let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
149 let move_span = move_spans.args_or_use();
151 let move_msg = if move_spans.for_closure() {
157 if span == move_span {
160 format!("value moved{} here, in previous iteration of loop", move_msg),
163 } else if move_site.traversed_back_edge {
167 "value moved{} here, in previous iteration of loop",
172 err.span_label(move_span, format!("value moved{} here", move_msg));
173 move_spans.var_span_label(
175 format!("variable moved due to use{}", move_spans.describe()),
178 if Some(DesugaringKind::ForLoop) == move_span.desugaring_kind() {
179 let sess = self.infcx.tcx.sess;
180 if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
183 "consider borrowing to avoid moving into the for loop",
184 format!("&{}", snippet),
185 Applicability::MaybeIncorrect,
191 use_spans.var_span_label(
193 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
201 desired_action.as_verb_in_past_tense(),
202 if is_partial_move { "after partial move" } else { "after move" },
208 Place::ty_from(used_place.base, used_place.projection, self.body, self.infcx.tcx)
210 let needs_note = match ty.kind {
211 ty::Closure(id, _) => {
212 let tables = self.infcx.tcx.typeck_tables_of(id);
213 let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
215 tables.closure_kind_origins().get(hir_id).is_none()
221 let mpi = self.move_data.moves[move_out_indices[0]].path;
222 let place = &self.move_data.move_paths[mpi].place;
224 let ty = place.ty(self.body, self.infcx.tcx).ty;
226 self.describe_place_with_options(place.as_ref(), IncludingDowncast(true));
227 let note_msg = match opt_name {
228 Some(ref name) => format!("`{}`", name),
229 None => "value".to_owned(),
231 if let ty::Param(param_ty) = ty.kind {
232 let tcx = self.infcx.tcx;
233 let generics = tcx.generics_of(self.mir_def_id);
234 let def_id = generics.type_param(¶m_ty, tcx).def_id;
235 if let Some(sp) = tcx.hir().span_if_local(def_id) {
238 "consider adding a `Copy` constraint to this type argument",
242 let span = if let Some(local) = place.as_local() {
243 let decl = &self.body.local_decls[local];
244 Some(decl.source_info.span)
248 self.note_type_does_not_implement_copy(
256 if let Some((_, mut old_err)) = self.move_error_reported
257 .insert(move_out_indices, (used_place, err))
259 // Cancel the old error so it doesn't ICE.
265 pub(super) fn report_move_out_while_borrowed(
268 (place, span): (&Place<'tcx>, Span),
269 borrow: &BorrowData<'tcx>,
272 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
273 location, place, span, borrow
275 let value_msg = match self.describe_place(place.as_ref()) {
276 Some(name) => format!("`{}`", name),
277 None => "value".to_owned(),
279 let borrow_msg = match self.describe_place(borrow.borrowed_place.as_ref()) {
280 Some(name) => format!("`{}`", name),
281 None => "value".to_owned(),
284 let borrow_spans = self.retrieve_borrow_spans(borrow);
285 let borrow_span = borrow_spans.args_or_use();
287 let move_spans = self.move_spans(place.as_ref(), location);
288 let span = move_spans.args_or_use();
290 let mut err = self.cannot_move_when_borrowed(
292 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
294 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
295 err.span_label(span, format!("move out of {} occurs here", value_msg));
297 borrow_spans.var_span_label(
299 format!("borrow occurs due to use{}", borrow_spans.describe())
302 move_spans.var_span_label(
304 format!("move occurs due to use{}", move_spans.describe())
307 self.explain_why_borrow_contains_point(
311 ).add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", Some(borrow_span));
312 err.buffer(&mut self.errors_buffer);
315 pub(super) fn report_use_while_mutably_borrowed(
318 (place, _span): (&Place<'tcx>, Span),
319 borrow: &BorrowData<'tcx>,
320 ) -> DiagnosticBuilder<'cx> {
321 let borrow_spans = self.retrieve_borrow_spans(borrow);
322 let borrow_span = borrow_spans.args_or_use();
324 // Conflicting borrows are reported separately, so only check for move
326 let use_spans = self.move_spans(place.as_ref(), location);
327 let span = use_spans.var_or_use();
329 let mut err = self.cannot_use_when_mutably_borrowed(
331 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
333 &self.describe_place(borrow.borrowed_place.as_ref())
334 .unwrap_or_else(|| "_".to_owned()),
337 borrow_spans.var_span_label(&mut err, {
338 let place = &borrow.borrowed_place;
340 self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned());
342 format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
345 self.explain_why_borrow_contains_point(location, borrow, None)
346 .add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
350 pub(super) fn report_conflicting_borrow(
353 (place, span): (&Place<'tcx>, Span),
354 gen_borrow_kind: BorrowKind,
355 issued_borrow: &BorrowData<'tcx>,
356 ) -> DiagnosticBuilder<'cx> {
357 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
358 let issued_span = issued_spans.args_or_use();
360 let borrow_spans = self.borrow_spans(span, location);
361 let span = borrow_spans.args_or_use();
363 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
369 let (desc_place, msg_place, msg_borrow, union_type_name) =
370 self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
372 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
373 let second_borrow_desc = if explanation.is_explained() {
379 // FIXME: supply non-"" `opt_via` when appropriate
380 let first_borrow_desc;
381 let mut err = match (
385 (BorrowKind::Shared, BorrowKind::Mut { .. }) => {
386 first_borrow_desc = "mutable ";
387 self.cannot_reborrow_already_borrowed(
399 (BorrowKind::Mut { .. }, BorrowKind::Shared) => {
400 first_borrow_desc = "immutable ";
401 self.cannot_reborrow_already_borrowed(
414 (BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
415 first_borrow_desc = "first ";
416 self.cannot_mutably_borrow_multiply(
426 (BorrowKind::Unique, BorrowKind::Unique) => {
427 first_borrow_desc = "first ";
428 self.cannot_uniquely_borrow_by_two_closures(
436 (BorrowKind::Mut { .. }, BorrowKind::Shallow)
437 | (BorrowKind::Unique, BorrowKind::Shallow) => {
438 if let Some(immutable_section_description) = self.classify_immutable_section(
439 &issued_borrow.assigned_place,
441 let mut err = self.cannot_mutate_in_immutable_section(
445 immutable_section_description,
448 borrow_spans.var_span_label(
451 "borrow occurs due to use of `{}`{}",
453 borrow_spans.describe(),
459 first_borrow_desc = "immutable ";
460 self.cannot_reborrow_already_borrowed(
474 (BorrowKind::Unique, _) => {
475 first_borrow_desc = "first ";
476 self.cannot_uniquely_borrow_by_one_closure(
488 (BorrowKind::Shared, BorrowKind::Unique) => {
489 first_borrow_desc = "first ";
490 self.cannot_reborrow_already_uniquely_borrowed(
503 (BorrowKind::Mut { .. }, BorrowKind::Unique) => {
504 first_borrow_desc = "first ";
505 self.cannot_reborrow_already_uniquely_borrowed(
518 (BorrowKind::Shared, BorrowKind::Shared)
519 | (BorrowKind::Shared, BorrowKind::Shallow)
520 | (BorrowKind::Shallow, BorrowKind::Mut { .. })
521 | (BorrowKind::Shallow, BorrowKind::Unique)
522 | (BorrowKind::Shallow, BorrowKind::Shared)
523 | (BorrowKind::Shallow, BorrowKind::Shallow) => unreachable!(),
526 if issued_spans == borrow_spans {
527 borrow_spans.var_span_label(
529 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
532 let borrow_place = &issued_borrow.borrowed_place;
533 let borrow_place_desc = self.describe_place(borrow_place.as_ref())
534 .unwrap_or_else(|| "_".to_owned());
535 issued_spans.var_span_label(
538 "first borrow occurs due to use of `{}`{}",
540 issued_spans.describe(),
544 borrow_spans.var_span_label(
547 "second borrow occurs due to use of `{}`{}",
549 borrow_spans.describe(),
554 if union_type_name != "" {
556 "`{}` is a field of the union `{}`, so it overlaps the field `{}`",
557 msg_place, union_type_name, msg_borrow,
561 explanation.add_explanation_to_diagnostic(
572 /// Returns the description of the root place for a conflicting borrow and the full
573 /// descriptions of the places that caused the conflict.
575 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
576 /// attempted while a shared borrow is live, then this function will return:
580 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
581 /// a shared borrow of another field `x.y`, then this function will return:
583 /// ("x", "x.z", "x.y")
585 /// In the more complex union case, where the union is a field of a struct, then if a mutable
586 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
587 /// another field `x.u.y`, then this function will return:
589 /// ("x.u", "x.u.z", "x.u.y")
591 /// This is used when creating error messages like below:
593 /// > cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
594 /// > mutable (via `a.u.s.b`) [E0502]
595 pub(super) fn describe_place_for_conflicting_borrow(
597 first_borrowed_place: &Place<'tcx>,
598 second_borrowed_place: &Place<'tcx>,
599 ) -> (String, String, String, String) {
600 // Define a small closure that we can use to check if the type of a place
602 let union_ty = |place_base, place_projection| {
603 let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
604 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
606 let describe_place = |place| self.describe_place(place).unwrap_or_else(|| "_".to_owned());
608 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
609 // code duplication (particularly around returning an empty description in the failure
613 // If we have a conflicting borrow of the same place, then we don't want to add
614 // an extraneous "via x.y" to our diagnostics, so filter out this case.
615 first_borrowed_place != second_borrowed_place
618 // We're going to want to traverse the first borrowed place to see if we can find
619 // field access to a union. If we find that, then we will keep the place of the
620 // union being accessed and the field that was being accessed so we can check the
621 // second borrowed place for the same union and a access to a different field.
625 } = first_borrowed_place;
627 let mut cursor = projection.as_ref();
628 while let [proj_base @ .., elem] = cursor {
632 ProjectionElem::Field(field, _) if union_ty(base, proj_base).is_some() => {
633 return Some((PlaceRef {
635 projection: proj_base,
643 .and_then(|(target_base, target_field)| {
644 // With the place of a union and a field access into it, we traverse the second
645 // borrowed place and look for a access to a different field of the same union.
649 } = second_borrowed_place;
651 let mut cursor = projection.as_ref();
652 while let [proj_base @ .., elem] = cursor {
655 if let ProjectionElem::Field(field, _) = elem {
656 if let Some(union_ty) = union_ty(base, proj_base) {
657 if field != target_field
658 && base == target_base.base
659 && proj_base == target_base.projection {
660 // FIXME when we avoid clone reuse describe_place closure
661 let describe_base_place = self.describe_place(PlaceRef {
663 projection: proj_base,
664 }).unwrap_or_else(|| "_".to_owned());
668 describe_place(first_borrowed_place.as_ref()),
669 describe_place(second_borrowed_place.as_ref()),
670 union_ty.to_string(),
679 // If we didn't find a field access into a union, or both places match, then
680 // only return the description of the first place.
682 describe_place(first_borrowed_place.as_ref()),
690 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
692 /// This means that some data referenced by `borrow` needs to live
693 /// past the point where the StorageDeadOrDrop of `place` occurs.
694 /// This is usually interpreted as meaning that `place` has too
695 /// short a lifetime. (But sometimes it is more useful to report
696 /// it as a more direct conflict between the execution of a
697 /// `Drop::drop` with an aliasing borrow.)
698 pub(super) fn report_borrowed_value_does_not_live_long_enough(
701 borrow: &BorrowData<'tcx>,
702 place_span: (&Place<'tcx>, Span),
703 kind: Option<WriteKind>,
706 "report_borrowed_value_does_not_live_long_enough(\
707 {:?}, {:?}, {:?}, {:?}\
709 location, borrow, place_span, kind
712 let drop_span = place_span.1;
713 let root_place = self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All)
717 let borrow_spans = self.retrieve_borrow_spans(borrow);
718 let borrow_span = borrow_spans.var_or_use();
720 assert!(root_place.projection.is_empty());
721 let proper_span = match root_place.base {
722 PlaceBase::Local(local) => self.body.local_decls[*local].source_info.span,
726 let root_place_projection = self.infcx.tcx.intern_place_elems(root_place.projection);
728 if self.access_place_error_reported
730 base: root_place.base.clone(),
731 projection: root_place_projection,
735 "suppressing access_place error when borrow doesn't live long enough for {:?}",
741 self.access_place_error_reported
743 base: root_place.base.clone(),
744 projection: root_place_projection,
747 if let StorageDeadOrDrop::Destructor(dropped_ty) =
748 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
750 // If a borrow of path `B` conflicts with drop of `D` (and
751 // we're not in the uninteresting case where `B` is a
752 // prefix of `D`), then report this as a more interesting
753 // destructor conflict.
754 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
755 self.report_borrow_conflicts_with_destructor(
756 location, borrow, place_span, kind, dropped_ty,
762 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
764 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
765 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
768 "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
772 let err = match (place_desc, explanation) {
773 (Some(_), _) if self.is_place_thread_local(root_place) => {
774 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
776 // If the outlives constraint comes from inside the closure,
781 // Box::new(|| y) as Box<Fn() -> &'static i32>
783 // then just use the normal error. The closure isn't escaping
784 // and `move` will not help here.
787 BorrowExplanation::MustBeValidFor {
788 category: category @ ConstraintCategory::Return,
797 BorrowExplanation::MustBeValidFor {
798 category: category @ ConstraintCategory::CallArgument,
804 ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
810 &format!("`{}`", name),
814 BorrowExplanation::MustBeValidFor {
815 category: category @ ConstraintCategory::OpaqueType,
822 ) if borrow_spans.for_generator() => self.report_escaping_closure_capture(
828 &format!("`{}`", name),
832 BorrowExplanation::MustBeValidFor {
833 category: ConstraintCategory::Assignment,
835 region_name: RegionName {
836 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
842 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
843 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
851 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
861 err.buffer(&mut self.errors_buffer);
864 fn report_local_value_does_not_live_long_enough(
868 borrow: &BorrowData<'tcx>,
870 borrow_spans: UseSpans,
871 explanation: BorrowExplanation,
872 ) -> DiagnosticBuilder<'cx> {
874 "report_local_value_does_not_live_long_enough(\
875 {:?}, {:?}, {:?}, {:?}, {:?}\
877 location, name, borrow, drop_span, borrow_spans
880 let borrow_span = borrow_spans.var_or_use();
881 if let BorrowExplanation::MustBeValidFor {
888 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
893 opt_place_desc.as_ref(),
899 let mut err = self.path_does_not_live_long_enough(
901 &format!("`{}`", name),
904 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
905 let region_name = annotation.emit(self, &mut err);
909 format!("`{}` would have to be valid for `{}`...", name, region_name),
912 if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
916 "...but `{}` will be dropped here, when the function `{}` returns",
918 self.infcx.tcx.hir().name(fn_hir_id),
923 "functions cannot return a borrow to data owned within the function's scope, \
924 functions can only return borrows to data passed as arguments",
927 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
928 references-and-borrowing.html#dangling-references>",
933 format!("...but `{}` dropped here while still borrowed", name),
937 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
939 explanation.add_explanation_to_diagnostic(
948 err.span_label(borrow_span, "borrowed value does not live long enough");
951 format!("`{}` dropped here while still borrowed", name),
954 let within = if borrow_spans.for_generator() {
960 borrow_spans.args_span_label(
962 format!("value captured here{}", within),
965 explanation.add_explanation_to_diagnostic(
966 self.infcx.tcx, self.body, &mut err, "", None);
972 fn report_borrow_conflicts_with_destructor(
975 borrow: &BorrowData<'tcx>,
976 (place, drop_span): (&Place<'tcx>, Span),
977 kind: Option<WriteKind>,
978 dropped_ty: Ty<'tcx>,
981 "report_borrow_conflicts_with_destructor(\
982 {:?}, {:?}, ({:?}, {:?}), {:?}\
984 location, borrow, place, drop_span, kind,
987 let borrow_spans = self.retrieve_borrow_spans(borrow);
988 let borrow_span = borrow_spans.var_or_use();
990 let mut err = self.cannot_borrow_across_destructor(borrow_span);
992 let what_was_dropped = match self.describe_place(place.as_ref()) {
993 Some(name) => format!("`{}`", name),
994 None => String::from("temporary value"),
997 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
998 Some(borrowed) => format!(
999 "here, drop of {D} needs exclusive access to `{B}`, \
1000 because the type `{T}` implements the `Drop` trait",
1001 D = what_was_dropped,
1006 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
1007 D = what_was_dropped,
1011 err.span_label(drop_span, label);
1013 // Only give this note and suggestion if they could be relevant.
1015 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
1017 BorrowExplanation::UsedLater { .. }
1018 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1019 err.note("consider using a `let` binding to create a longer lived value");
1024 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1026 err.buffer(&mut self.errors_buffer);
1029 fn report_thread_local_value_does_not_live_long_enough(
1033 ) -> DiagnosticBuilder<'cx> {
1035 "report_thread_local_value_does_not_live_long_enough(\
1038 drop_span, borrow_span
1041 let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1045 "thread-local variables cannot be borrowed beyond the end of the function",
1047 err.span_label(drop_span, "end of enclosing function is here");
1052 fn report_temporary_value_does_not_live_long_enough(
1055 borrow: &BorrowData<'tcx>,
1057 borrow_spans: UseSpans,
1059 explanation: BorrowExplanation,
1060 ) -> DiagnosticBuilder<'cx> {
1062 "report_temporary_value_does_not_live_long_enough(\
1063 {:?}, {:?}, {:?}, {:?}\
1065 location, borrow, drop_span, proper_span
1068 if let BorrowExplanation::MustBeValidFor {
1071 from_closure: false,
1074 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1085 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1088 "creates a temporary which is freed while still in use",
1092 "temporary value is freed at the end of this statement",
1096 BorrowExplanation::UsedLater(..)
1097 | BorrowExplanation::UsedLaterInLoop(..)
1098 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1099 // Only give this note and suggestion if it could be relevant.
1100 err.note("consider using a `let` binding to create a longer lived value");
1104 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1106 let within = if borrow_spans.for_generator() {
1112 borrow_spans.args_span_label(
1114 format!("value captured here{}", within),
1120 fn try_report_cannot_return_reference_to_local(
1122 borrow: &BorrowData<'tcx>,
1125 category: ConstraintCategory,
1126 opt_place_desc: Option<&String>,
1127 ) -> Option<DiagnosticBuilder<'cx>> {
1128 let return_kind = match category {
1129 ConstraintCategory::Return => "return",
1130 ConstraintCategory::Yield => "yield",
1134 // FIXME use a better heuristic than Spans
1135 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1141 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1142 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1143 match self.body.local_kind(local) {
1144 LocalKind::ReturnPointer
1145 | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1146 LocalKind::Var => "local variable ",
1148 if !self.upvars.is_empty()
1149 && local == Local::new(1) => {
1150 "variable captured by `move` "
1153 "function parameter "
1160 format!("{}`{}`", local_kind, place_desc),
1161 format!("`{}` is borrowed here", place_desc),
1164 let root_place = self.prefixes(borrow.borrowed_place.as_ref(),
1168 let local = if let PlaceRef {
1169 base: PlaceBase::Local(local),
1174 bug!("try_report_cannot_return_reference_to_local: not a local")
1176 match self.body.local_kind(*local) {
1177 LocalKind::ReturnPointer | LocalKind::Temp => (
1178 "temporary value".to_string(),
1179 "temporary value created here".to_string(),
1182 "function parameter".to_string(),
1183 "function parameter borrowed here".to_string(),
1186 "local binding".to_string(),
1187 "local binding introduced here".to_string(),
1192 let mut err = self.cannot_return_reference_to_local(
1199 if return_span != borrow_span {
1200 err.span_label(borrow_span, note);
1206 fn report_escaping_closure_capture(
1210 fr_name: &RegionName,
1211 category: ConstraintCategory,
1212 constraint_span: Span,
1214 ) -> DiagnosticBuilder<'cx> {
1215 let tcx = self.infcx.tcx;
1216 let args_span = use_span.args_or_use();
1217 let mut err = self.cannot_capture_in_long_lived_closure(
1223 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1225 if string.starts_with("async ") {
1226 string.insert_str(6, "move ");
1227 } else if string.starts_with("async|") {
1228 string.insert_str(5, " move");
1230 string.insert_str(0, "move ");
1234 Err(_) => "move |<args>| <body>".to_string()
1236 let kind = match use_span.generator_kind() {
1237 Some(generator_kind) => match generator_kind {
1238 GeneratorKind::Async(async_kind) => match async_kind {
1239 AsyncGeneratorKind::Block => "async block",
1240 AsyncGeneratorKind::Closure => "async closure",
1241 _ => bug!("async block/closure expected, but async funtion found."),
1243 GeneratorKind::Gen => "generator",
1247 err.span_suggestion(
1250 "to force the {} to take ownership of {} (and any \
1251 other referenced variables), use the `move` keyword",
1256 Applicability::MachineApplicable,
1259 let msg = match category {
1260 ConstraintCategory::Return => "closure is returned here".to_string(),
1261 ConstraintCategory::OpaqueType => "generator is returned here".to_string(),
1262 ConstraintCategory::CallArgument => {
1263 fr_name.highlight_region_name(&mut err);
1264 format!("function requires argument type to outlive `{}`", fr_name)
1266 _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1267 category: `{:?}`", category),
1269 err.span_note(constraint_span, &msg);
1273 fn report_escaping_data(
1276 name: &Option<String>,
1280 ) -> DiagnosticBuilder<'cx> {
1281 let tcx = self.infcx.tcx;
1283 let escapes_from = if tcx.is_closure(self.mir_def_id) {
1284 let tables = tcx.typeck_tables_of(self.mir_def_id);
1285 let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1286 match tables.node_type(mir_hir_id).kind {
1287 ty::Closure(..) => "closure",
1288 ty::Generator(..) => "generator",
1289 _ => bug!("Closure body doesn't have a closure or generator type"),
1295 let mut err = borrowck_errors::borrowed_data_escapes_closure(
1304 "`{}` is declared here, outside of the {} body",
1305 upvar_name, escapes_from
1312 "borrow is only valid in the {} body",
1317 if let Some(name) = name {
1320 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1325 format!("reference escapes the {} body here", escapes_from),
1332 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1333 let body = self.body;
1335 let mut stack = Vec::new();
1336 stack.extend(body.predecessor_locations(location).map(|predecessor| {
1337 let is_back_edge = location.dominates(predecessor, &self.dominators);
1338 (predecessor, is_back_edge)
1341 let mut visited = FxHashSet::default();
1342 let mut result = vec![];
1344 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1346 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1347 location, is_back_edge
1350 if !visited.insert(location) {
1355 let stmt_kind = body[location.block]
1357 .get(location.statement_index)
1359 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1360 // this analysis only tries to find moves explicitly
1361 // written by the user, so we ignore the move-outs
1362 // created by `StorageDead` and at the beginning
1365 // If we are found a use of a.b.c which was in error, then we want to look for
1366 // moves not only of a.b.c but also a.b and a.
1368 // Note that the moves data already includes "parent" paths, so we don't have to
1369 // worry about the other case: that is, if there is a move of a.b.c, it is already
1370 // marked as a move of a.b and a as well, so we will generate the correct errors
1372 let mut mpis = vec![mpi];
1373 let move_paths = &self.move_data.move_paths;
1374 mpis.extend(move_paths[mpi].parents(move_paths));
1376 for moi in &self.move_data.loc_map[location] {
1377 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1378 if mpis.contains(&self.move_data.moves[*moi].path) {
1379 debug!("report_use_of_moved_or_uninitialized: found");
1380 result.push(MoveSite {
1382 traversed_back_edge: is_back_edge,
1385 // Strictly speaking, we could continue our DFS here. There may be
1386 // other moves that can reach the point of error. But it is kind of
1387 // confusing to highlight them.
1395 // drop(a); // <-- current point of error
1398 // Because we stop the DFS here, we only highlight `let c = a`,
1399 // and not `let b = a`. We will of course also report an error at
1400 // `let c = a` which highlights `let b = a` as the move.
1407 let mut any_match = false;
1408 drop_flag_effects::for_location_inits(
1423 stack.extend(body.predecessor_locations(location).map(|predecessor| {
1424 let back_edge = location.dominates(predecessor, &self.dominators);
1425 (predecessor, is_back_edge || back_edge)
1432 pub(super) fn report_illegal_mutation_of_borrowed(
1435 (place, span): (&Place<'tcx>, Span),
1436 loan: &BorrowData<'tcx>,
1438 let loan_spans = self.retrieve_borrow_spans(loan);
1439 let loan_span = loan_spans.args_or_use();
1441 if loan.kind == BorrowKind::Shallow {
1442 if let Some(section) = self.classify_immutable_section(&loan.assigned_place) {
1443 let mut err = self.cannot_mutate_in_immutable_section(
1446 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1450 loan_spans.var_span_label(
1452 format!("borrow occurs due to use{}", loan_spans.describe()),
1455 err.buffer(&mut self.errors_buffer);
1461 let mut err = self.cannot_assign_to_borrowed(
1464 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1467 loan_spans.var_span_label(
1469 format!("borrow occurs due to use{}", loan_spans.describe()),
1472 self.explain_why_borrow_contains_point(location, loan, None)
1473 .add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1475 err.buffer(&mut self.errors_buffer);
1478 /// Reports an illegal reassignment; for example, an assignment to
1479 /// (part of) a non-`mut` local that occurs potentially after that
1480 /// local has already been initialized. `place` is the path being
1481 /// assigned; `err_place` is a place providing a reason why
1482 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1483 /// assignment to `x.f`).
1484 pub(super) fn report_illegal_reassignment(
1486 _location: Location,
1487 (place, span): (&Place<'tcx>, Span),
1488 assigned_span: Span,
1489 err_place: &Place<'tcx>,
1491 let (from_arg, local_decl) = if let Some(local) = err_place.as_local() {
1492 if let LocalKind::Arg = self.body.local_kind(local) {
1493 (true, Some(&self.body.local_decls[local]))
1495 (false, Some(&self.body.local_decls[local]))
1501 // If root local is initialized immediately (everything apart from let
1502 // PATTERN;) then make the error refer to that local, rather than the
1503 // place being assigned later.
1504 let (place_description, assigned_span) = match local_decl {
1506 is_user_variable: Some(ClearCrossCrate::Clear),
1511 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1512 opt_match_place: None,
1518 is_user_variable: None,
1521 | None => (self.describe_place(place.as_ref()), assigned_span),
1522 Some(decl) => (self.describe_place(err_place.as_ref()), decl.source_info.span),
1525 let mut err = self.cannot_reassign_immutable(
1527 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1530 let msg = if from_arg {
1531 "cannot assign to immutable argument"
1533 "cannot assign twice to immutable variable"
1535 if span != assigned_span {
1537 let value_msg = match place_description {
1538 Some(name) => format!("`{}`", name),
1539 None => "value".to_owned(),
1541 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1544 if let Some(decl) = local_decl {
1545 if let Some(name) = decl.name {
1546 if decl.can_be_made_mutable() {
1547 err.span_suggestion(
1548 decl.source_info.span,
1549 "make this binding mutable",
1550 format!("mut {}", name),
1551 Applicability::MachineApplicable,
1556 err.span_label(span, msg);
1557 err.buffer(&mut self.errors_buffer);
1560 fn classify_drop_access_kind(&self, place: PlaceRef<'cx, 'tcx>) -> StorageDeadOrDrop<'tcx> {
1561 let tcx = self.infcx.tcx;
1562 match place.projection {
1564 StorageDeadOrDrop::LocalStorageDead
1566 [proj_base @ .., elem] => {
1567 // FIXME(spastorino) make this iterate
1568 let base_access = self.classify_drop_access_kind(PlaceRef {
1570 projection: proj_base,
1573 ProjectionElem::Deref => match base_access {
1574 StorageDeadOrDrop::LocalStorageDead
1575 | StorageDeadOrDrop::BoxedStorageDead => {
1577 Place::ty_from(&place.base, proj_base, self.body, tcx).ty.is_box(),
1578 "Drop of value behind a reference or raw pointer"
1580 StorageDeadOrDrop::BoxedStorageDead
1582 StorageDeadOrDrop::Destructor(_) => base_access,
1584 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1585 let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1586 match base_ty.kind {
1587 ty::Adt(def, _) if def.has_dtor(tcx) => {
1588 // Report the outermost adt with a destructor
1590 StorageDeadOrDrop::Destructor(_) => base_access,
1591 StorageDeadOrDrop::LocalStorageDead
1592 | StorageDeadOrDrop::BoxedStorageDead => {
1593 StorageDeadOrDrop::Destructor(base_ty)
1601 ProjectionElem::ConstantIndex { .. }
1602 | ProjectionElem::Subslice { .. }
1603 | ProjectionElem::Index(_) => base_access,
1609 /// Describe the reason for the fake borrow that was assigned to `place`.
1610 fn classify_immutable_section(&self, place: &Place<'tcx>) -> Option<&'static str> {
1611 use rustc::mir::visit::Visitor;
1612 struct FakeReadCauseFinder<'a, 'tcx> {
1613 place: &'a Place<'tcx>,
1614 cause: Option<FakeReadCause>,
1616 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'_, 'tcx> {
1617 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1620 kind: StatementKind::FakeRead(cause, box ref place),
1622 } if *place == *self.place => {
1623 self.cause = Some(*cause);
1629 let mut visitor = FakeReadCauseFinder { place, cause: None };
1630 visitor.visit_body(&self.body);
1631 match visitor.cause {
1632 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1633 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1638 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1639 /// borrow of local value that does not live long enough.
1640 fn annotate_argument_and_return_for_borrow(
1642 borrow: &BorrowData<'tcx>,
1643 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1644 // Define a fallback for when we can't match a closure.
1646 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1650 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1652 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1654 self.infcx.tcx.fn_sig(self.mir_def_id),
1661 // In order to determine whether we need to annotate, we need to check whether the reserve
1662 // place was an assignment into a temporary.
1664 // If it was, we check whether or not that temporary is eventually assigned into the return
1665 // place. If it was, we can add annotations about the function's return type and arguments
1666 // and it'll make sense.
1667 let location = borrow.reserve_location;
1669 "annotate_argument_and_return_for_borrow: location={:?}",
1672 if let Some(&Statement { kind: StatementKind::Assign(box(ref reservation, _)), ..})
1673 = &self.body[location.block].statements.get(location.statement_index)
1676 "annotate_argument_and_return_for_borrow: reservation={:?}",
1679 // Check that the initial assignment of the reserve location is into a temporary.
1680 let mut target = match reservation.as_local() {
1681 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
1685 // Next, look through the rest of the block, checking if we are assigning the
1686 // `target` (that is, the place that contains our borrow) to anything.
1687 let mut annotated_closure = None;
1688 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1690 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1693 if let StatementKind::Assign(box(place, rvalue)) = &stmt.kind {
1694 if let Some(assigned_to) = place.as_local() {
1696 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1700 // Check if our `target` was captured by a closure.
1701 if let Rvalue::Aggregate(
1702 box AggregateKind::Closure(def_id, substs),
1706 for operand in operands {
1707 let assigned_from = match operand {
1708 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1714 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1718 // Find the local from the operand.
1719 let assigned_from_local = match assigned_from.local_or_deref_local()
1721 Some(local) => local,
1725 if assigned_from_local != target {
1729 // If a closure captured our `target` and then assigned
1730 // into a place then we should annotate the closure in
1731 // case it ends up being assigned into the return place.
1732 annotated_closure = self.annotate_fn_sig(
1734 self.infcx.closure_sig(*def_id, *substs),
1737 "annotate_argument_and_return_for_borrow: \
1738 annotated_closure={:?} assigned_from_local={:?} \
1740 annotated_closure, assigned_from_local, assigned_to
1743 if assigned_to == mir::RETURN_PLACE {
1744 // If it was assigned directly into the return place, then
1746 return annotated_closure;
1748 // Otherwise, update the target.
1749 target = assigned_to;
1753 // If none of our closure's operands matched, then skip to the next
1758 // Otherwise, look at other types of assignment.
1759 let assigned_from = match rvalue {
1760 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1761 Rvalue::Use(operand) => match operand {
1762 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1770 "annotate_argument_and_return_for_borrow: \
1771 assigned_from={:?}",
1775 // Find the local from the rvalue.
1776 let assigned_from_local = match assigned_from.local_or_deref_local() {
1777 Some(local) => local,
1781 "annotate_argument_and_return_for_borrow: \
1782 assigned_from_local={:?}",
1783 assigned_from_local,
1786 // Check if our local matches the target - if so, we've assigned our
1787 // borrow to a new place.
1788 if assigned_from_local != target {
1792 // If we assigned our `target` into a new place, then we should
1793 // check if it was the return place.
1795 "annotate_argument_and_return_for_borrow: \
1796 assigned_from_local={:?} assigned_to={:?}",
1797 assigned_from_local, assigned_to
1799 if assigned_to == mir::RETURN_PLACE {
1800 // If it was then return the annotated closure if there was one,
1801 // else, annotate this function.
1802 return annotated_closure.or_else(fallback);
1805 // If we didn't assign into the return place, then we just update
1807 target = assigned_to;
1812 // Check the terminator if we didn't find anything in the statements.
1813 let terminator = &self.body[location.block].terminator();
1815 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1818 if let TerminatorKind::Call {
1819 destination: Some((place, _)),
1822 } = &terminator.kind
1824 if let Some(assigned_to) = place.as_local() {
1826 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1829 for operand in args {
1830 let assigned_from = match operand {
1831 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1837 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1841 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1843 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1844 assigned_from_local,
1847 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1848 return annotated_closure.or_else(fallback);
1856 // If we haven't found an assignment into the return place, then we need not add
1858 debug!("annotate_argument_and_return_for_borrow: none found");
1862 /// Annotate the first argument and return type of a function signature if they are
1867 sig: ty::PolyFnSig<'tcx>,
1868 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1869 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1870 let is_closure = self.infcx.tcx.is_closure(did);
1871 let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
1872 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1874 // We need to work out which arguments to highlight. We do this by looking
1875 // at the return type, where there are three cases:
1877 // 1. If there are named arguments, then we should highlight the return type and
1878 // highlight any of the arguments that are also references with that lifetime.
1879 // If there are no arguments that have the same lifetime as the return type,
1880 // then don't highlight anything.
1881 // 2. The return type is a reference with an anonymous lifetime. If this is
1882 // the case, then we can take advantage of (and teach) the lifetime elision
1885 // We know that an error is being reported. So the arguments and return type
1886 // must satisfy the elision rules. Therefore, if there is a single argument
1887 // then that means the return type and first (and only) argument have the same
1888 // lifetime and the borrow isn't meeting that, we can highlight the argument
1891 // If there are multiple arguments then the first argument must be self (else
1892 // it would not satisfy the elision rules), so we can highlight self and the
1894 // 3. The return type is not a reference. In this case, we don't highlight
1896 let return_ty = sig.output();
1897 match return_ty.skip_binder().kind {
1898 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1899 // This is case 1 from above, return type is a named reference so we need to
1900 // search for relevant arguments.
1901 let mut arguments = Vec::new();
1902 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1903 if let ty::Ref(argument_region, _, _) = argument.kind {
1904 if argument_region == return_region {
1905 // Need to use the `rustc::ty` types to compare against the
1906 // `return_region`. Then use the `rustc::hir` type to get only
1907 // the lifetime span.
1908 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
1909 // With access to the lifetime, we can get
1911 arguments.push((*argument, lifetime.span));
1913 bug!("ty type is a ref but hir type is not");
1919 // We need to have arguments. This shouldn't happen, but it's worth checking.
1920 if arguments.is_empty() {
1924 // We use a mix of the HIR and the Ty types to get information
1925 // as the HIR doesn't have full types for closure arguments.
1926 let return_ty = *sig.output().skip_binder();
1927 let mut return_span = fn_decl.output.span();
1928 if let hir::FunctionRetTy::Return(ty) = &fn_decl.output {
1929 if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
1930 return_span = lifetime.span;
1934 Some(AnnotatedBorrowFnSignature::NamedFunction {
1940 ty::Ref(_, _, _) if is_closure => {
1941 // This is case 2 from above but only for closures, return type is anonymous
1942 // reference so we select
1943 // the first argument.
1944 let argument_span = fn_decl.inputs.first()?.span;
1945 let argument_ty = sig.inputs().skip_binder().first()?;
1947 // Closure arguments are wrapped in a tuple, so we need to get the first
1949 if let ty::Tuple(elems) = argument_ty.kind {
1950 let argument_ty = elems.first()?.expect_ty();
1951 if let ty::Ref(_, _, _) = argument_ty.kind {
1952 return Some(AnnotatedBorrowFnSignature::Closure {
1961 ty::Ref(_, _, _) => {
1962 // This is also case 2 from above but for functions, return type is still an
1963 // anonymous reference so we select the first argument.
1964 let argument_span = fn_decl.inputs.first()?.span;
1965 let argument_ty = sig.inputs().skip_binder().first()?;
1967 let return_span = fn_decl.output.span();
1968 let return_ty = *sig.output().skip_binder();
1970 // We expect the first argument to be a reference.
1971 match argument_ty.kind {
1972 ty::Ref(_, _, _) => {}
1976 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1984 // This is case 3 from above, return type is not a reference so don't highlight
1993 enum AnnotatedBorrowFnSignature<'tcx> {
1995 arguments: Vec<(Ty<'tcx>, Span)>,
1996 return_ty: Ty<'tcx>,
2000 argument_ty: Ty<'tcx>,
2001 argument_span: Span,
2002 return_ty: Ty<'tcx>,
2006 argument_ty: Ty<'tcx>,
2007 argument_span: Span,
2011 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2012 /// Annotate the provided diagnostic with information about borrow from the fn signature that
2016 cx: &mut MirBorrowckCtxt<'_, 'tcx>,
2017 diag: &mut DiagnosticBuilder<'_>,
2020 AnnotatedBorrowFnSignature::Closure {
2026 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2029 cx.get_region_name_for_ty(argument_ty, 0)
2031 AnnotatedBorrowFnSignature::AnonymousFunction {
2037 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2038 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2040 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2041 let types_equal = return_ty_name == argument_ty_name;
2046 if types_equal { "also " } else { "" },
2052 "argument and return type have the same lifetime due to lifetime elision rules",
2055 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2056 lifetime-syntax.html#lifetime-elision>",
2059 cx.get_region_name_for_ty(return_ty, 0)
2061 AnnotatedBorrowFnSignature::NamedFunction {
2066 // Region of return type and arguments checked to be the same earlier.
2067 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2068 for (_, argument_span) in arguments {
2069 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2074 format!("also has lifetime `{}`", region_name,),
2078 "use data from the highlighted arguments which match the `{}` lifetime of \