2 use rustc::hir::def_id::DefId;
3 use rustc::hir::{AsyncGeneratorKind, GeneratorKind};
5 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
6 FakeReadCause, Local, LocalDecl, LocalInfo, LocalKind, Location, Operand, Place, PlaceBase,
7 PlaceRef, 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 param = generics.type_param(¶m_ty, tcx);
235 let generics = tcx.hir().get_generics(self.mir_def_id).unwrap();
236 let msg = "consider adding a `Copy` constraint to this type argument";
237 for param in generics.params.iter().filter(|p| {
238 p.name.ident().as_str() == param.name.as_str()
240 let param_name = param.name.ident().as_str();
241 if param_name.starts_with("impl ") {
242 // `impl Trait` in argument:
243 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
247 // `impl CurrentTrait + MissingTrait`
248 format!("{} + Copy", param_name),
249 Applicability::MachineApplicable,
251 } else if generics.where_clause.predicates.is_empty() &&
252 param.bounds.is_empty()
254 // If there are no bounds whatsoever, suggest adding a constraint
255 // to the type parameter:
256 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
260 format!("{}: Copy", param_name),
261 Applicability::MachineApplicable,
263 } else if !generics.where_clause.predicates.is_empty() {
264 // There is a `where` clause, so suggest expanding it:
265 // `fn foo<T>(t: T) where T: Debug {}` →
266 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
268 generics.where_clause.span().unwrap().shrink_to_hi(),
270 format!(", {}: Copy", param_name),
271 Applicability::MachineApplicable,
274 // If there is no `where` clause lean towards constraining to the
276 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
277 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
278 let sp = param.span.with_hi(span.hi());
279 let span = tcx.sess.source_map()
280 .span_through_char(sp, ':');
281 if sp != param.span && sp != span {
282 // Only suggest if we have high certainty that the span
283 // covers the colon in `foo<T: Trait>`.
284 err.span_suggestion(span, msg, format!(
287 ), Applicability::MachineApplicable);
289 err.span_label(param.span, msg);
294 let span = if let Some(local) = place.as_local() {
295 let decl = &self.body.local_decls[local];
296 Some(decl.source_info.span)
300 self.note_type_does_not_implement_copy(
308 if let Some((_, mut old_err)) = self.move_error_reported
309 .insert(move_out_indices, (used_place, err))
311 // Cancel the old error so it doesn't ICE.
317 pub(super) fn report_move_out_while_borrowed(
320 (place, span): (&Place<'tcx>, Span),
321 borrow: &BorrowData<'tcx>,
324 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
325 location, place, span, borrow
327 let value_msg = match self.describe_place(place.as_ref()) {
328 Some(name) => format!("`{}`", name),
329 None => "value".to_owned(),
331 let borrow_msg = match self.describe_place(borrow.borrowed_place.as_ref()) {
332 Some(name) => format!("`{}`", name),
333 None => "value".to_owned(),
336 let borrow_spans = self.retrieve_borrow_spans(borrow);
337 let borrow_span = borrow_spans.args_or_use();
339 let move_spans = self.move_spans(place.as_ref(), location);
340 let span = move_spans.args_or_use();
342 let mut err = self.cannot_move_when_borrowed(
344 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
346 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
347 err.span_label(span, format!("move out of {} occurs here", value_msg));
349 borrow_spans.var_span_label(
351 format!("borrow occurs due to use{}", borrow_spans.describe())
354 move_spans.var_span_label(
356 format!("move occurs due to use{}", move_spans.describe())
359 self.explain_why_borrow_contains_point(
363 ).add_explanation_to_diagnostic(
371 err.buffer(&mut self.errors_buffer);
374 pub(super) fn report_use_while_mutably_borrowed(
377 (place, _span): (&Place<'tcx>, Span),
378 borrow: &BorrowData<'tcx>,
379 ) -> DiagnosticBuilder<'cx> {
380 let borrow_spans = self.retrieve_borrow_spans(borrow);
381 let borrow_span = borrow_spans.args_or_use();
383 // Conflicting borrows are reported separately, so only check for move
385 let use_spans = self.move_spans(place.as_ref(), location);
386 let span = use_spans.var_or_use();
388 let mut err = self.cannot_use_when_mutably_borrowed(
390 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
392 &self.describe_place(borrow.borrowed_place.as_ref())
393 .unwrap_or_else(|| "_".to_owned()),
396 borrow_spans.var_span_label(&mut err, {
397 let place = &borrow.borrowed_place;
399 self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned());
401 format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
404 self.explain_why_borrow_contains_point(location, borrow, None)
405 .add_explanation_to_diagnostic(
416 pub(super) fn report_conflicting_borrow(
419 (place, span): (&Place<'tcx>, Span),
420 gen_borrow_kind: BorrowKind,
421 issued_borrow: &BorrowData<'tcx>,
422 ) -> DiagnosticBuilder<'cx> {
423 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
424 let issued_span = issued_spans.args_or_use();
426 let borrow_spans = self.borrow_spans(span, location);
427 let span = borrow_spans.args_or_use();
429 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
435 let (desc_place, msg_place, msg_borrow, union_type_name) =
436 self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
438 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
439 let second_borrow_desc = if explanation.is_explained() {
445 // FIXME: supply non-"" `opt_via` when appropriate
446 let first_borrow_desc;
447 let mut err = match (
451 (BorrowKind::Shared, BorrowKind::Mut { .. }) => {
452 first_borrow_desc = "mutable ";
453 self.cannot_reborrow_already_borrowed(
465 (BorrowKind::Mut { .. }, BorrowKind::Shared) => {
466 first_borrow_desc = "immutable ";
467 self.cannot_reborrow_already_borrowed(
480 (BorrowKind::Mut { .. }, BorrowKind::Mut { .. }) => {
481 first_borrow_desc = "first ";
482 self.cannot_mutably_borrow_multiply(
492 (BorrowKind::Unique, BorrowKind::Unique) => {
493 first_borrow_desc = "first ";
494 self.cannot_uniquely_borrow_by_two_closures(
502 (BorrowKind::Mut { .. }, BorrowKind::Shallow)
503 | (BorrowKind::Unique, BorrowKind::Shallow) => {
504 if let Some(immutable_section_description) = self.classify_immutable_section(
505 &issued_borrow.assigned_place,
507 let mut err = self.cannot_mutate_in_immutable_section(
511 immutable_section_description,
514 borrow_spans.var_span_label(
517 "borrow occurs due to use of `{}`{}",
519 borrow_spans.describe(),
525 first_borrow_desc = "immutable ";
526 self.cannot_reborrow_already_borrowed(
540 (BorrowKind::Unique, _) => {
541 first_borrow_desc = "first ";
542 self.cannot_uniquely_borrow_by_one_closure(
554 (BorrowKind::Shared, BorrowKind::Unique) => {
555 first_borrow_desc = "first ";
556 self.cannot_reborrow_already_uniquely_borrowed(
569 (BorrowKind::Mut { .. }, BorrowKind::Unique) => {
570 first_borrow_desc = "first ";
571 self.cannot_reborrow_already_uniquely_borrowed(
584 (BorrowKind::Shared, BorrowKind::Shared)
585 | (BorrowKind::Shared, BorrowKind::Shallow)
586 | (BorrowKind::Shallow, BorrowKind::Mut { .. })
587 | (BorrowKind::Shallow, BorrowKind::Unique)
588 | (BorrowKind::Shallow, BorrowKind::Shared)
589 | (BorrowKind::Shallow, BorrowKind::Shallow) => unreachable!(),
592 if issued_spans == borrow_spans {
593 borrow_spans.var_span_label(
595 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
598 let borrow_place = &issued_borrow.borrowed_place;
599 let borrow_place_desc = self.describe_place(borrow_place.as_ref())
600 .unwrap_or_else(|| "_".to_owned());
601 issued_spans.var_span_label(
604 "first borrow occurs due to use of `{}`{}",
606 issued_spans.describe(),
610 borrow_spans.var_span_label(
613 "second borrow occurs due to use of `{}`{}",
615 borrow_spans.describe(),
620 if union_type_name != "" {
622 "`{}` is a field of the union `{}`, so it overlaps the field `{}`",
623 msg_place, union_type_name, msg_borrow,
627 explanation.add_explanation_to_diagnostic(
639 /// Returns the description of the root place for a conflicting borrow and the full
640 /// descriptions of the places that caused the conflict.
642 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
643 /// attempted while a shared borrow is live, then this function will return:
647 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
648 /// a shared borrow of another field `x.y`, then this function will return:
650 /// ("x", "x.z", "x.y")
652 /// In the more complex union case, where the union is a field of a struct, then if a mutable
653 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
654 /// another field `x.u.y`, then this function will return:
656 /// ("x.u", "x.u.z", "x.u.y")
658 /// This is used when creating error messages like below:
660 /// > cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
661 /// > mutable (via `a.u.s.b`) [E0502]
662 pub(super) fn describe_place_for_conflicting_borrow(
664 first_borrowed_place: &Place<'tcx>,
665 second_borrowed_place: &Place<'tcx>,
666 ) -> (String, String, String, String) {
667 // Define a small closure that we can use to check if the type of a place
669 let union_ty = |place_base, place_projection| {
670 let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
671 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
673 let describe_place = |place| self.describe_place(place).unwrap_or_else(|| "_".to_owned());
675 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
676 // code duplication (particularly around returning an empty description in the failure
680 // If we have a conflicting borrow of the same place, then we don't want to add
681 // an extraneous "via x.y" to our diagnostics, so filter out this case.
682 first_borrowed_place != second_borrowed_place
685 // We're going to want to traverse the first borrowed place to see if we can find
686 // field access to a union. If we find that, then we will keep the place of the
687 // union being accessed and the field that was being accessed so we can check the
688 // second borrowed place for the same union and a access to a different field.
692 } = first_borrowed_place;
694 let mut cursor = projection.as_ref();
695 while let [proj_base @ .., elem] = cursor {
699 ProjectionElem::Field(field, _) if union_ty(base, proj_base).is_some() => {
700 return Some((PlaceRef {
702 projection: proj_base,
710 .and_then(|(target_base, target_field)| {
711 // With the place of a union and a field access into it, we traverse the second
712 // borrowed place and look for a access to a different field of the same union.
716 } = second_borrowed_place;
718 let mut cursor = projection.as_ref();
719 while let [proj_base @ .., elem] = cursor {
722 if let ProjectionElem::Field(field, _) = elem {
723 if let Some(union_ty) = union_ty(base, proj_base) {
724 if field != target_field
725 && base == target_base.base
726 && proj_base == target_base.projection {
727 // FIXME when we avoid clone reuse describe_place closure
728 let describe_base_place = self.describe_place(PlaceRef {
730 projection: proj_base,
731 }).unwrap_or_else(|| "_".to_owned());
735 describe_place(first_borrowed_place.as_ref()),
736 describe_place(second_borrowed_place.as_ref()),
737 union_ty.to_string(),
746 // If we didn't find a field access into a union, or both places match, then
747 // only return the description of the first place.
749 describe_place(first_borrowed_place.as_ref()),
757 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
759 /// This means that some data referenced by `borrow` needs to live
760 /// past the point where the StorageDeadOrDrop of `place` occurs.
761 /// This is usually interpreted as meaning that `place` has too
762 /// short a lifetime. (But sometimes it is more useful to report
763 /// it as a more direct conflict between the execution of a
764 /// `Drop::drop` with an aliasing borrow.)
765 pub(super) fn report_borrowed_value_does_not_live_long_enough(
768 borrow: &BorrowData<'tcx>,
769 place_span: (&Place<'tcx>, Span),
770 kind: Option<WriteKind>,
773 "report_borrowed_value_does_not_live_long_enough(\
774 {:?}, {:?}, {:?}, {:?}\
776 location, borrow, place_span, kind
779 let drop_span = place_span.1;
780 let root_place = self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All)
784 let borrow_spans = self.retrieve_borrow_spans(borrow);
785 let borrow_span = borrow_spans.var_or_use();
787 assert!(root_place.projection.is_empty());
788 let proper_span = match root_place.base {
789 PlaceBase::Local(local) => self.body.local_decls[*local].source_info.span,
793 let root_place_projection = self.infcx.tcx.intern_place_elems(root_place.projection);
795 if self.access_place_error_reported
797 base: root_place.base.clone(),
798 projection: root_place_projection,
802 "suppressing access_place error when borrow doesn't live long enough for {:?}",
808 self.access_place_error_reported
810 base: root_place.base.clone(),
811 projection: root_place_projection,
814 if let PlaceBase::Local(local) = borrow.borrowed_place.base {
815 if self.body.local_decls[local].is_ref_to_thread_local() {
816 let err = self.report_thread_local_value_does_not_live_long_enough(
820 err.buffer(&mut self.errors_buffer);
825 if let StorageDeadOrDrop::Destructor(dropped_ty) =
826 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
828 // If a borrow of path `B` conflicts with drop of `D` (and
829 // we're not in the uninteresting case where `B` is a
830 // prefix of `D`), then report this as a more interesting
831 // destructor conflict.
832 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
833 self.report_borrow_conflicts_with_destructor(
834 location, borrow, place_span, kind, dropped_ty,
840 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
842 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
843 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
846 "report_borrowed_value_does_not_live_long_enough(place_desc: {:?}, explanation: {:?})",
850 let err = match (place_desc, explanation) {
851 // If the outlives constraint comes from inside the closure,
856 // Box::new(|| y) as Box<Fn() -> &'static i32>
858 // then just use the normal error. The closure isn't escaping
859 // and `move` will not help here.
862 BorrowExplanation::MustBeValidFor {
863 category: category @ ConstraintCategory::Return,
872 BorrowExplanation::MustBeValidFor {
873 category: category @ ConstraintCategory::CallArgument,
879 ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
885 &format!("`{}`", name),
889 BorrowExplanation::MustBeValidFor {
890 category: category @ ConstraintCategory::OpaqueType,
897 ) if borrow_spans.for_generator() => self.report_escaping_closure_capture(
903 &format!("`{}`", name),
907 BorrowExplanation::MustBeValidFor {
908 category: ConstraintCategory::Assignment,
910 region_name: RegionName {
911 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
917 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
918 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
926 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
936 err.buffer(&mut self.errors_buffer);
939 fn report_local_value_does_not_live_long_enough(
943 borrow: &BorrowData<'tcx>,
945 borrow_spans: UseSpans,
946 explanation: BorrowExplanation,
947 ) -> DiagnosticBuilder<'cx> {
949 "report_local_value_does_not_live_long_enough(\
950 {:?}, {:?}, {:?}, {:?}, {:?}\
952 location, name, borrow, drop_span, borrow_spans
955 let borrow_span = borrow_spans.var_or_use();
956 if let BorrowExplanation::MustBeValidFor {
963 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
968 opt_place_desc.as_ref(),
974 let mut err = self.path_does_not_live_long_enough(
976 &format!("`{}`", name),
979 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
980 let region_name = annotation.emit(self, &mut err);
984 format!("`{}` would have to be valid for `{}`...", name, region_name),
987 if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
991 "...but `{}` will be dropped here, when the function `{}` returns",
993 self.infcx.tcx.hir().name(fn_hir_id),
998 "functions cannot return a borrow to data owned within the function's scope, \
999 functions can only return borrows to data passed as arguments",
1002 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
1003 references-and-borrowing.html#dangling-references>",
1008 format!("...but `{}` dropped here while still borrowed", name),
1012 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
1014 explanation.add_explanation_to_diagnostic(
1024 err.span_label(borrow_span, "borrowed value does not live long enough");
1027 format!("`{}` dropped here while still borrowed", name),
1030 let within = if borrow_spans.for_generator() {
1036 borrow_spans.args_span_label(
1038 format!("value captured here{}", within),
1041 explanation.add_explanation_to_diagnostic(
1042 self.infcx.tcx, self.body, &self.local_names, &mut err, "", None);
1048 fn report_borrow_conflicts_with_destructor(
1051 borrow: &BorrowData<'tcx>,
1052 (place, drop_span): (&Place<'tcx>, Span),
1053 kind: Option<WriteKind>,
1054 dropped_ty: Ty<'tcx>,
1057 "report_borrow_conflicts_with_destructor(\
1058 {:?}, {:?}, ({:?}, {:?}), {:?}\
1060 location, borrow, place, drop_span, kind,
1063 let borrow_spans = self.retrieve_borrow_spans(borrow);
1064 let borrow_span = borrow_spans.var_or_use();
1066 let mut err = self.cannot_borrow_across_destructor(borrow_span);
1068 let what_was_dropped = match self.describe_place(place.as_ref()) {
1069 Some(name) => format!("`{}`", name),
1070 None => String::from("temporary value"),
1073 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
1074 Some(borrowed) => format!(
1075 "here, drop of {D} needs exclusive access to `{B}`, \
1076 because the type `{T}` implements the `Drop` trait",
1077 D = what_was_dropped,
1082 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
1083 D = what_was_dropped,
1087 err.span_label(drop_span, label);
1089 // Only give this note and suggestion if they could be relevant.
1091 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
1093 BorrowExplanation::UsedLater { .. }
1094 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1095 err.note("consider using a `let` binding to create a longer lived value");
1100 explanation.add_explanation_to_diagnostic(
1109 err.buffer(&mut self.errors_buffer);
1112 fn report_thread_local_value_does_not_live_long_enough(
1116 ) -> DiagnosticBuilder<'cx> {
1118 "report_thread_local_value_does_not_live_long_enough(\
1121 drop_span, borrow_span
1124 let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1128 "thread-local variables cannot be borrowed beyond the end of the function",
1130 err.span_label(drop_span, "end of enclosing function is here");
1135 fn report_temporary_value_does_not_live_long_enough(
1138 borrow: &BorrowData<'tcx>,
1140 borrow_spans: UseSpans,
1142 explanation: BorrowExplanation,
1143 ) -> DiagnosticBuilder<'cx> {
1145 "report_temporary_value_does_not_live_long_enough(\
1146 {:?}, {:?}, {:?}, {:?}\
1148 location, borrow, drop_span, proper_span
1151 if let BorrowExplanation::MustBeValidFor {
1154 from_closure: false,
1157 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1168 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1171 "creates a temporary which is freed while still in use",
1175 "temporary value is freed at the end of this statement",
1179 BorrowExplanation::UsedLater(..)
1180 | BorrowExplanation::UsedLaterInLoop(..)
1181 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1182 // Only give this note and suggestion if it could be relevant.
1183 err.note("consider using a `let` binding to create a longer lived value");
1187 explanation.add_explanation_to_diagnostic(
1196 let within = if borrow_spans.for_generator() {
1202 borrow_spans.args_span_label(
1204 format!("value captured here{}", within),
1210 fn try_report_cannot_return_reference_to_local(
1212 borrow: &BorrowData<'tcx>,
1215 category: ConstraintCategory,
1216 opt_place_desc: Option<&String>,
1217 ) -> Option<DiagnosticBuilder<'cx>> {
1218 let return_kind = match category {
1219 ConstraintCategory::Return => "return",
1220 ConstraintCategory::Yield => "yield",
1224 // FIXME use a better heuristic than Spans
1225 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1231 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1232 let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
1233 match self.body.local_kind(local) {
1234 LocalKind::ReturnPointer
1235 | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1236 LocalKind::Var => "local variable ",
1238 if !self.upvars.is_empty()
1239 && local == Local::new(1) => {
1240 "variable captured by `move` "
1243 "function parameter "
1250 format!("{}`{}`", local_kind, place_desc),
1251 format!("`{}` is borrowed here", place_desc),
1254 let root_place = self.prefixes(borrow.borrowed_place.as_ref(),
1258 let local = if let PlaceRef {
1259 base: PlaceBase::Local(local),
1264 bug!("try_report_cannot_return_reference_to_local: not a local")
1266 match self.body.local_kind(*local) {
1267 LocalKind::ReturnPointer | LocalKind::Temp => (
1268 "temporary value".to_string(),
1269 "temporary value created here".to_string(),
1272 "function parameter".to_string(),
1273 "function parameter borrowed here".to_string(),
1276 "local binding".to_string(),
1277 "local binding introduced here".to_string(),
1282 let mut err = self.cannot_return_reference_to_local(
1289 if return_span != borrow_span {
1290 err.span_label(borrow_span, note);
1296 fn report_escaping_closure_capture(
1300 fr_name: &RegionName,
1301 category: ConstraintCategory,
1302 constraint_span: Span,
1304 ) -> DiagnosticBuilder<'cx> {
1305 let tcx = self.infcx.tcx;
1306 let args_span = use_span.args_or_use();
1307 let mut err = self.cannot_capture_in_long_lived_closure(
1313 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1315 if string.starts_with("async ") {
1316 string.insert_str(6, "move ");
1317 } else if string.starts_with("async|") {
1318 string.insert_str(5, " move");
1320 string.insert_str(0, "move ");
1324 Err(_) => "move |<args>| <body>".to_string()
1326 let kind = match use_span.generator_kind() {
1327 Some(generator_kind) => match generator_kind {
1328 GeneratorKind::Async(async_kind) => match async_kind {
1329 AsyncGeneratorKind::Block => "async block",
1330 AsyncGeneratorKind::Closure => "async closure",
1331 _ => bug!("async block/closure expected, but async funtion found."),
1333 GeneratorKind::Gen => "generator",
1337 err.span_suggestion(
1340 "to force the {} to take ownership of {} (and any \
1341 other referenced variables), use the `move` keyword",
1346 Applicability::MachineApplicable,
1349 let msg = match category {
1350 ConstraintCategory::Return => "closure is returned here".to_string(),
1351 ConstraintCategory::OpaqueType => "generator is returned here".to_string(),
1352 ConstraintCategory::CallArgument => {
1353 fr_name.highlight_region_name(&mut err);
1354 format!("function requires argument type to outlive `{}`", fr_name)
1356 _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1357 category: `{:?}`", category),
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 = if tcx.is_closure(self.mir_def_id) {
1374 let tables = tcx.typeck_tables_of(self.mir_def_id);
1375 let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1376 match tables.node_type(mir_hir_id).kind {
1377 ty::Closure(..) => "closure",
1378 ty::Generator(..) => "generator",
1379 _ => bug!("Closure body doesn't have a closure or generator type"),
1385 let mut err = borrowck_errors::borrowed_data_escapes_closure(
1394 "`{}` is declared here, outside of the {} body",
1395 upvar_name, escapes_from
1402 "borrow is only valid in the {} body",
1407 if let Some(name) = name {
1410 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1415 format!("reference escapes the {} body here", escapes_from),
1422 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1423 let body = self.body;
1425 let mut stack = Vec::new();
1426 stack.extend(body.predecessor_locations(location).map(|predecessor| {
1427 let is_back_edge = location.dominates(predecessor, &self.dominators);
1428 (predecessor, is_back_edge)
1431 let mut visited = FxHashSet::default();
1432 let mut result = vec![];
1434 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1436 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1437 location, is_back_edge
1440 if !visited.insert(location) {
1445 let stmt_kind = body[location.block]
1447 .get(location.statement_index)
1449 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1450 // this analysis only tries to find moves explicitly
1451 // written by the user, so we ignore the move-outs
1452 // created by `StorageDead` and at the beginning
1455 // If we are found a use of a.b.c which was in error, then we want to look for
1456 // moves not only of a.b.c but also a.b and a.
1458 // Note that the moves data already includes "parent" paths, so we don't have to
1459 // worry about the other case: that is, if there is a move of a.b.c, it is already
1460 // marked as a move of a.b and a as well, so we will generate the correct errors
1462 let mut mpis = vec![mpi];
1463 let move_paths = &self.move_data.move_paths;
1464 mpis.extend(move_paths[mpi].parents(move_paths));
1466 for moi in &self.move_data.loc_map[location] {
1467 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1468 if mpis.contains(&self.move_data.moves[*moi].path) {
1469 debug!("report_use_of_moved_or_uninitialized: found");
1470 result.push(MoveSite {
1472 traversed_back_edge: is_back_edge,
1475 // Strictly speaking, we could continue our DFS here. There may be
1476 // other moves that can reach the point of error. But it is kind of
1477 // confusing to highlight them.
1485 // drop(a); // <-- current point of error
1488 // Because we stop the DFS here, we only highlight `let c = a`,
1489 // and not `let b = a`. We will of course also report an error at
1490 // `let c = a` which highlights `let b = a` as the move.
1497 let mut any_match = false;
1498 drop_flag_effects::for_location_inits(
1513 stack.extend(body.predecessor_locations(location).map(|predecessor| {
1514 let back_edge = location.dominates(predecessor, &self.dominators);
1515 (predecessor, is_back_edge || back_edge)
1522 pub(super) fn report_illegal_mutation_of_borrowed(
1525 (place, span): (&Place<'tcx>, Span),
1526 loan: &BorrowData<'tcx>,
1528 let loan_spans = self.retrieve_borrow_spans(loan);
1529 let loan_span = loan_spans.args_or_use();
1531 if loan.kind == BorrowKind::Shallow {
1532 if let Some(section) = self.classify_immutable_section(&loan.assigned_place) {
1533 let mut err = self.cannot_mutate_in_immutable_section(
1536 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1540 loan_spans.var_span_label(
1542 format!("borrow occurs due to use{}", loan_spans.describe()),
1545 err.buffer(&mut self.errors_buffer);
1551 let mut err = self.cannot_assign_to_borrowed(
1554 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1557 loan_spans.var_span_label(
1559 format!("borrow occurs due to use{}", loan_spans.describe()),
1562 self.explain_why_borrow_contains_point(location, loan, None)
1563 .add_explanation_to_diagnostic(
1572 err.buffer(&mut self.errors_buffer);
1575 /// Reports an illegal reassignment; for example, an assignment to
1576 /// (part of) a non-`mut` local that occurs potentially after that
1577 /// local has already been initialized. `place` is the path being
1578 /// assigned; `err_place` is a place providing a reason why
1579 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1580 /// assignment to `x.f`).
1581 pub(super) fn report_illegal_reassignment(
1583 _location: Location,
1584 (place, span): (&Place<'tcx>, Span),
1585 assigned_span: Span,
1586 err_place: &Place<'tcx>,
1588 let (from_arg, local_decl, local_name) = match err_place.as_local() {
1590 self.body.local_kind(local) == LocalKind::Arg,
1591 Some(&self.body.local_decls[local]),
1592 self.local_names[local],
1594 None => (false, None, None),
1597 // If root local is initialized immediately (everything apart from let
1598 // PATTERN;) then make the error refer to that local, rather than the
1599 // place being assigned later.
1600 let (place_description, assigned_span) = match local_decl {
1602 local_info: LocalInfo::User(ClearCrossCrate::Clear),
1606 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1607 opt_match_place: None,
1613 local_info: LocalInfo::StaticRef { .. },
1617 local_info: LocalInfo::Other,
1620 | None => (self.describe_place(place.as_ref()), assigned_span),
1621 Some(decl) => (self.describe_place(err_place.as_ref()), decl.source_info.span),
1624 let mut err = self.cannot_reassign_immutable(
1626 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1629 let msg = if from_arg {
1630 "cannot assign to immutable argument"
1632 "cannot assign twice to immutable variable"
1634 if span != assigned_span {
1636 let value_msg = match place_description {
1637 Some(name) => format!("`{}`", name),
1638 None => "value".to_owned(),
1640 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1643 if let Some(decl) = local_decl {
1644 if let Some(name) = local_name {
1645 if decl.can_be_made_mutable() {
1646 err.span_suggestion(
1647 decl.source_info.span,
1648 "make this binding mutable",
1649 format!("mut {}", name),
1650 Applicability::MachineApplicable,
1655 err.span_label(span, msg);
1656 err.buffer(&mut self.errors_buffer);
1659 fn classify_drop_access_kind(&self, place: PlaceRef<'cx, 'tcx>) -> StorageDeadOrDrop<'tcx> {
1660 let tcx = self.infcx.tcx;
1661 match place.projection {
1663 StorageDeadOrDrop::LocalStorageDead
1665 [proj_base @ .., elem] => {
1666 // FIXME(spastorino) make this iterate
1667 let base_access = self.classify_drop_access_kind(PlaceRef {
1669 projection: proj_base,
1672 ProjectionElem::Deref => match base_access {
1673 StorageDeadOrDrop::LocalStorageDead
1674 | StorageDeadOrDrop::BoxedStorageDead => {
1676 Place::ty_from(&place.base, proj_base, self.body, tcx).ty.is_box(),
1677 "Drop of value behind a reference or raw pointer"
1679 StorageDeadOrDrop::BoxedStorageDead
1681 StorageDeadOrDrop::Destructor(_) => base_access,
1683 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1684 let base_ty = Place::ty_from(&place.base, proj_base, self.body, tcx).ty;
1685 match base_ty.kind {
1686 ty::Adt(def, _) if def.has_dtor(tcx) => {
1687 // Report the outermost adt with a destructor
1689 StorageDeadOrDrop::Destructor(_) => base_access,
1690 StorageDeadOrDrop::LocalStorageDead
1691 | StorageDeadOrDrop::BoxedStorageDead => {
1692 StorageDeadOrDrop::Destructor(base_ty)
1700 ProjectionElem::ConstantIndex { .. }
1701 | ProjectionElem::Subslice { .. }
1702 | ProjectionElem::Index(_) => base_access,
1708 /// Describe the reason for the fake borrow that was assigned to `place`.
1709 fn classify_immutable_section(&self, place: &Place<'tcx>) -> Option<&'static str> {
1710 use rustc::mir::visit::Visitor;
1711 struct FakeReadCauseFinder<'a, 'tcx> {
1712 place: &'a Place<'tcx>,
1713 cause: Option<FakeReadCause>,
1715 impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'_, 'tcx> {
1716 fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
1719 kind: StatementKind::FakeRead(cause, box ref place),
1721 } if *place == *self.place => {
1722 self.cause = Some(*cause);
1728 let mut visitor = FakeReadCauseFinder { place, cause: None };
1729 visitor.visit_body(&self.body);
1730 match visitor.cause {
1731 Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
1732 Some(FakeReadCause::ForIndex) => Some("indexing expression"),
1737 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1738 /// borrow of local value that does not live long enough.
1739 fn annotate_argument_and_return_for_borrow(
1741 borrow: &BorrowData<'tcx>,
1742 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1743 // Define a fallback for when we can't match a closure.
1745 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1749 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1751 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1753 self.infcx.tcx.fn_sig(self.mir_def_id),
1760 // In order to determine whether we need to annotate, we need to check whether the reserve
1761 // place was an assignment into a temporary.
1763 // If it was, we check whether or not that temporary is eventually assigned into the return
1764 // place. If it was, we can add annotations about the function's return type and arguments
1765 // and it'll make sense.
1766 let location = borrow.reserve_location;
1768 "annotate_argument_and_return_for_borrow: location={:?}",
1771 if let Some(&Statement { kind: StatementKind::Assign(box(ref reservation, _)), ..})
1772 = &self.body[location.block].statements.get(location.statement_index)
1775 "annotate_argument_and_return_for_borrow: reservation={:?}",
1778 // Check that the initial assignment of the reserve location is into a temporary.
1779 let mut target = match reservation.as_local() {
1780 Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
1784 // Next, look through the rest of the block, checking if we are assigning the
1785 // `target` (that is, the place that contains our borrow) to anything.
1786 let mut annotated_closure = None;
1787 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1789 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1792 if let StatementKind::Assign(box(place, rvalue)) = &stmt.kind {
1793 if let Some(assigned_to) = place.as_local() {
1795 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1799 // Check if our `target` was captured by a closure.
1800 if let Rvalue::Aggregate(
1801 box AggregateKind::Closure(def_id, substs),
1805 for operand in operands {
1806 let assigned_from = match operand {
1807 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1813 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1817 // Find the local from the operand.
1818 let assigned_from_local = match assigned_from.local_or_deref_local()
1820 Some(local) => local,
1824 if assigned_from_local != target {
1828 // If a closure captured our `target` and then assigned
1829 // into a place then we should annotate the closure in
1830 // case it ends up being assigned into the return place.
1831 annotated_closure = self.annotate_fn_sig(
1833 self.infcx.closure_sig(*def_id, *substs),
1836 "annotate_argument_and_return_for_borrow: \
1837 annotated_closure={:?} assigned_from_local={:?} \
1839 annotated_closure, assigned_from_local, assigned_to
1842 if assigned_to == mir::RETURN_PLACE {
1843 // If it was assigned directly into the return place, then
1845 return annotated_closure;
1847 // Otherwise, update the target.
1848 target = assigned_to;
1852 // If none of our closure's operands matched, then skip to the next
1857 // Otherwise, look at other types of assignment.
1858 let assigned_from = match rvalue {
1859 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1860 Rvalue::Use(operand) => match operand {
1861 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1869 "annotate_argument_and_return_for_borrow: \
1870 assigned_from={:?}",
1874 // Find the local from the rvalue.
1875 let assigned_from_local = match assigned_from.local_or_deref_local() {
1876 Some(local) => local,
1880 "annotate_argument_and_return_for_borrow: \
1881 assigned_from_local={:?}",
1882 assigned_from_local,
1885 // Check if our local matches the target - if so, we've assigned our
1886 // borrow to a new place.
1887 if assigned_from_local != target {
1891 // If we assigned our `target` into a new place, then we should
1892 // check if it was the return place.
1894 "annotate_argument_and_return_for_borrow: \
1895 assigned_from_local={:?} assigned_to={:?}",
1896 assigned_from_local, assigned_to
1898 if assigned_to == mir::RETURN_PLACE {
1899 // If it was then return the annotated closure if there was one,
1900 // else, annotate this function.
1901 return annotated_closure.or_else(fallback);
1904 // If we didn't assign into the return place, then we just update
1906 target = assigned_to;
1911 // Check the terminator if we didn't find anything in the statements.
1912 let terminator = &self.body[location.block].terminator();
1914 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1917 if let TerminatorKind::Call {
1918 destination: Some((place, _)),
1921 } = &terminator.kind
1923 if let Some(assigned_to) = place.as_local() {
1925 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1928 for operand in args {
1929 let assigned_from = match operand {
1930 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1936 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1940 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1942 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1943 assigned_from_local,
1946 if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1947 return annotated_closure.or_else(fallback);
1955 // If we haven't found an assignment into the return place, then we need not add
1957 debug!("annotate_argument_and_return_for_borrow: none found");
1961 /// Annotate the first argument and return type of a function signature if they are
1966 sig: ty::PolyFnSig<'tcx>,
1967 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1968 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1969 let is_closure = self.infcx.tcx.is_closure(did);
1970 let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
1971 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1973 // We need to work out which arguments to highlight. We do this by looking
1974 // at the return type, where there are three cases:
1976 // 1. If there are named arguments, then we should highlight the return type and
1977 // highlight any of the arguments that are also references with that lifetime.
1978 // If there are no arguments that have the same lifetime as the return type,
1979 // then don't highlight anything.
1980 // 2. The return type is a reference with an anonymous lifetime. If this is
1981 // the case, then we can take advantage of (and teach) the lifetime elision
1984 // We know that an error is being reported. So the arguments and return type
1985 // must satisfy the elision rules. Therefore, if there is a single argument
1986 // then that means the return type and first (and only) argument have the same
1987 // lifetime and the borrow isn't meeting that, we can highlight the argument
1990 // If there are multiple arguments then the first argument must be self (else
1991 // it would not satisfy the elision rules), so we can highlight self and the
1993 // 3. The return type is not a reference. In this case, we don't highlight
1995 let return_ty = sig.output();
1996 match return_ty.skip_binder().kind {
1997 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1998 // This is case 1 from above, return type is a named reference so we need to
1999 // search for relevant arguments.
2000 let mut arguments = Vec::new();
2001 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
2002 if let ty::Ref(argument_region, _, _) = argument.kind {
2003 if argument_region == return_region {
2004 // Need to use the `rustc::ty` types to compare against the
2005 // `return_region`. Then use the `rustc::hir` type to get only
2006 // the lifetime span.
2007 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind {
2008 // With access to the lifetime, we can get
2010 arguments.push((*argument, lifetime.span));
2012 bug!("ty type is a ref but hir type is not");
2018 // We need to have arguments. This shouldn't happen, but it's worth checking.
2019 if arguments.is_empty() {
2023 // We use a mix of the HIR and the Ty types to get information
2024 // as the HIR doesn't have full types for closure arguments.
2025 let return_ty = *sig.output().skip_binder();
2026 let mut return_span = fn_decl.output.span();
2027 if let hir::FunctionRetTy::Return(ty) = &fn_decl.output {
2028 if let hir::TyKind::Rptr(lifetime, _) = ty.kind {
2029 return_span = lifetime.span;
2033 Some(AnnotatedBorrowFnSignature::NamedFunction {
2039 ty::Ref(_, _, _) if is_closure => {
2040 // This is case 2 from above but only for closures, return type is anonymous
2041 // reference so we select
2042 // the first argument.
2043 let argument_span = fn_decl.inputs.first()?.span;
2044 let argument_ty = sig.inputs().skip_binder().first()?;
2046 // Closure arguments are wrapped in a tuple, so we need to get the first
2048 if let ty::Tuple(elems) = argument_ty.kind {
2049 let argument_ty = elems.first()?.expect_ty();
2050 if let ty::Ref(_, _, _) = argument_ty.kind {
2051 return Some(AnnotatedBorrowFnSignature::Closure {
2060 ty::Ref(_, _, _) => {
2061 // This is also case 2 from above but for functions, return type is still an
2062 // anonymous reference so we select the first argument.
2063 let argument_span = fn_decl.inputs.first()?.span;
2064 let argument_ty = sig.inputs().skip_binder().first()?;
2066 let return_span = fn_decl.output.span();
2067 let return_ty = *sig.output().skip_binder();
2069 // We expect the first argument to be a reference.
2070 match argument_ty.kind {
2071 ty::Ref(_, _, _) => {}
2075 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
2083 // This is case 3 from above, return type is not a reference so don't highlight
2092 enum AnnotatedBorrowFnSignature<'tcx> {
2094 arguments: Vec<(Ty<'tcx>, Span)>,
2095 return_ty: Ty<'tcx>,
2099 argument_ty: Ty<'tcx>,
2100 argument_span: Span,
2101 return_ty: Ty<'tcx>,
2105 argument_ty: Ty<'tcx>,
2106 argument_span: Span,
2110 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
2111 /// Annotate the provided diagnostic with information about borrow from the fn signature that
2115 cx: &mut MirBorrowckCtxt<'_, 'tcx>,
2116 diag: &mut DiagnosticBuilder<'_>,
2119 AnnotatedBorrowFnSignature::Closure {
2125 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
2128 cx.get_region_name_for_ty(argument_ty, 0)
2130 AnnotatedBorrowFnSignature::AnonymousFunction {
2136 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
2137 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
2139 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
2140 let types_equal = return_ty_name == argument_ty_name;
2145 if types_equal { "also " } else { "" },
2151 "argument and return type have the same lifetime due to lifetime elision rules",
2154 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
2155 lifetime-syntax.html#lifetime-elision>",
2158 cx.get_region_name_for_ty(return_ty, 0)
2160 AnnotatedBorrowFnSignature::NamedFunction {
2165 // Region of return type and arguments checked to be the same earlier.
2166 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2167 for (_, argument_span) in arguments {
2168 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2173 format!("also has lifetime `{}`", region_name,),
2177 "use data from the highlighted arguments which match the `{}` lifetime of \