2 use rustc::hir::def_id::DefId;
4 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory, Local,
5 LocalDecl, LocalKind, Location, Operand, Place, PlaceBase, PlaceRef, ProjectionElem, Rvalue,
6 Statement, StatementKind, TerminatorKind, VarBindingForm,
8 use rustc::ty::{self, Ty};
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_data_structures::indexed_vec::Idx;
11 use rustc_errors::{Applicability, DiagnosticBuilder};
13 use syntax::source_map::DesugaringKind;
15 use super::nll::explain_borrow::BorrowExplanation;
16 use super::nll::region_infer::{RegionName, RegionNameSource};
17 use super::prefixes::IsPrefixOf;
19 use super::borrow_set::BorrowData;
20 use super::MirBorrowckCtxt;
21 use super::{InitializationRequiringAction, PrefixSet};
22 use super::error_reporting::{IncludingDowncast, UseSpans};
23 use crate::dataflow::drop_flag_effects;
24 use crate::dataflow::indexes::{MovePathIndex, MoveOutIndex};
25 use crate::util::borrowck_errors;
29 /// Index of the "move out" that we found. The `MoveData` can
30 /// then tell us where the move occurred.
33 /// `true` if we traversed a back edge while walking from the point
34 /// of error to the move site.
35 traversed_back_edge: bool
38 /// Which case a StorageDeadOrDrop is for.
39 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
40 enum StorageDeadOrDrop<'tcx> {
46 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
47 pub(super) fn report_use_of_moved_or_uninitialized(
50 desired_action: InitializationRequiringAction,
51 (moved_place, used_place, span): (PlaceRef<'cx, 'tcx>, PlaceRef<'cx, 'tcx>, Span),
55 "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
56 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
57 location, desired_action, moved_place, used_place, span, mpi
60 let use_spans = self.move_spans(moved_place, location)
61 .or_else(|| self.borrow_spans(span, location));
62 let span = use_spans.args_or_use();
64 let move_site_vec = self.get_moved_indexes(location, mpi);
66 "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
69 let move_out_indices: Vec<_> = move_site_vec
71 .map(|move_site| move_site.moi)
74 if move_out_indices.is_empty() {
76 .prefixes(used_place, PrefixSet::All)
80 if self.uninitialized_error_reported.contains(&root_place) {
82 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
88 self.uninitialized_error_reported.insert(root_place);
90 let item_msg = match self.describe_place_with_options(used_place,
91 IncludingDowncast(true)) {
92 Some(name) => format!("`{}`", name),
93 None => "value".to_owned(),
95 let mut err = self.cannot_act_on_uninitialized_variable(
97 desired_action.as_noun(),
98 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
99 .unwrap_or_else(|| "_".to_owned()),
101 err.span_label(span, format!("use of possibly-uninitialized {}", item_msg));
103 use_spans.var_span_label(
105 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
108 // This error should not be downgraded to a warning,
109 // even in migrate mode.
110 self.disable_error_downgrading();
111 err.buffer(&mut self.errors_buffer);
113 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
114 if self.prefixes(*reported_place, PrefixSet::All)
115 .any(|p| p == used_place)
118 "report_use_of_moved_or_uninitialized place: error suppressed \
126 let msg = ""; //FIXME: add "partially " or "collaterally "
128 let mut err = self.cannot_act_on_moved_value(
130 desired_action.as_noun(),
132 self.describe_place_with_options(moved_place, IncludingDowncast(true)),
135 self.add_moved_or_invoked_closure_note(
141 let mut is_loop_move = false;
142 let is_partial_move = move_site_vec.iter().any(|move_site| {
143 let move_out = self.move_data.moves[(*move_site).moi];
144 let moved_place = &self.move_data.move_paths[move_out.path].place;
145 used_place != moved_place.as_ref()
146 && used_place.is_prefix_of(moved_place.as_ref())
148 for move_site in &move_site_vec {
149 let move_out = self.move_data.moves[(*move_site).moi];
150 let moved_place = &self.move_data.move_paths[move_out.path].place;
152 let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
153 let move_span = move_spans.args_or_use();
155 let move_msg = if move_spans.for_closure() {
161 if span == move_span {
164 format!("value moved{} here, in previous iteration of loop", move_msg),
167 } else if move_site.traversed_back_edge {
171 "value moved{} here, in previous iteration of loop",
176 err.span_label(move_span, format!("value moved{} here", move_msg));
177 move_spans.var_span_label(
179 format!("variable moved due to use{}", move_spans.describe()),
182 if Some(DesugaringKind::ForLoop) == move_span.desugaring_kind() {
183 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
186 "consider borrowing to avoid moving into the for loop",
187 format!("&{}", snippet),
188 Applicability::MaybeIncorrect,
194 use_spans.var_span_label(
196 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
204 desired_action.as_verb_in_past_tense(),
205 if is_partial_move { "after partial move" } else { "after move" },
211 Place::ty_from(used_place.base, used_place.projection, self.body, self.infcx.tcx)
213 let needs_note = match ty.sty {
214 ty::Closure(id, _) => {
215 let tables = self.infcx.tcx.typeck_tables_of(id);
216 let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
218 tables.closure_kind_origins().get(hir_id).is_none()
224 let mpi = self.move_data.moves[move_out_indices[0]].path;
225 let place = &self.move_data.move_paths[mpi].place;
227 let ty = place.ty(self.body, self.infcx.tcx).ty;
229 self.describe_place_with_options(place.as_ref(), IncludingDowncast(true));
230 let note_msg = match opt_name {
231 Some(ref name) => format!("`{}`", name),
232 None => "value".to_owned(),
234 if let ty::Param(param_ty) = ty.sty {
235 let tcx = self.infcx.tcx;
236 let generics = tcx.generics_of(self.mir_def_id);
237 let def_id = generics.type_param(¶m_ty, tcx).def_id;
238 if let Some(sp) = tcx.hir().span_if_local(def_id) {
241 "consider adding a `Copy` constraint to this type argument",
245 let span = if let Place {
246 base: PlaceBase::Local(local),
249 let decl = &self.body.local_decls[*local];
250 Some(decl.source_info.span)
254 self.note_type_does_not_implement_copy(
262 if let Some((_, mut old_err)) = self.move_error_reported
263 .insert(move_out_indices, (used_place, err))
265 // Cancel the old error so it doesn't ICE.
271 pub(super) fn report_move_out_while_borrowed(
274 (place, span): (&Place<'tcx>, Span),
275 borrow: &BorrowData<'tcx>,
278 "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
279 location, place, span, borrow
281 let value_msg = match self.describe_place(place.as_ref()) {
282 Some(name) => format!("`{}`", name),
283 None => "value".to_owned(),
285 let borrow_msg = match self.describe_place(borrow.borrowed_place.as_ref()) {
286 Some(name) => format!("`{}`", name),
287 None => "value".to_owned(),
290 let borrow_spans = self.retrieve_borrow_spans(borrow);
291 let borrow_span = borrow_spans.args_or_use();
293 let move_spans = self.move_spans(place.as_ref(), location);
294 let span = move_spans.args_or_use();
296 let mut err = self.cannot_move_when_borrowed(
298 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
300 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
301 err.span_label(span, format!("move out of {} occurs here", value_msg));
303 borrow_spans.var_span_label(
305 format!("borrow occurs due to use{}", borrow_spans.describe())
308 move_spans.var_span_label(
310 format!("move occurs due to use{}", move_spans.describe())
313 self.explain_why_borrow_contains_point(
317 ).add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", Some(borrow_span));
318 err.buffer(&mut self.errors_buffer);
321 pub(super) fn report_use_while_mutably_borrowed(
324 (place, _span): (&Place<'tcx>, Span),
325 borrow: &BorrowData<'tcx>,
326 ) -> DiagnosticBuilder<'cx> {
327 let borrow_spans = self.retrieve_borrow_spans(borrow);
328 let borrow_span = borrow_spans.args_or_use();
330 // Conflicting borrows are reported separately, so only check for move
332 let use_spans = self.move_spans(place.as_ref(), location);
333 let span = use_spans.var_or_use();
335 let mut err = self.cannot_use_when_mutably_borrowed(
337 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
339 &self.describe_place(borrow.borrowed_place.as_ref())
340 .unwrap_or_else(|| "_".to_owned()),
343 borrow_spans.var_span_label(&mut err, {
344 let place = &borrow.borrowed_place;
346 self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned());
348 format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
351 self.explain_why_borrow_contains_point(location, borrow, None)
352 .add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
356 pub(super) fn report_conflicting_borrow(
359 (place, span): (&Place<'tcx>, Span),
360 gen_borrow_kind: BorrowKind,
361 issued_borrow: &BorrowData<'tcx>,
362 ) -> DiagnosticBuilder<'cx> {
363 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
364 let issued_span = issued_spans.args_or_use();
366 let borrow_spans = self.borrow_spans(span, location);
367 let span = borrow_spans.args_or_use();
369 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
375 let (desc_place, msg_place, msg_borrow, union_type_name) =
376 self.describe_place_for_conflicting_borrow(place, &issued_borrow.borrowed_place);
378 let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
379 let second_borrow_desc = if explanation.is_explained() {
385 // FIXME: supply non-"" `opt_via` when appropriate
386 let first_borrow_desc;
387 let mut err = match (
395 (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
396 first_borrow_desc = "mutable ";
397 self.cannot_reborrow_already_borrowed(
409 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
410 first_borrow_desc = "immutable ";
411 self.cannot_reborrow_already_borrowed(
424 (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
425 first_borrow_desc = "first ";
426 self.cannot_mutably_borrow_multiply(
436 (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
437 first_borrow_desc = "first ";
438 self.cannot_uniquely_borrow_by_two_closures(
446 (BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
447 | (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
448 let mut err = self.cannot_mutate_in_match_guard(
454 borrow_spans.var_span_label(
457 "borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe()
464 (BorrowKind::Unique, _, _, _, _, _) => {
465 first_borrow_desc = "first ";
466 self.cannot_uniquely_borrow_by_one_closure(
478 (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
479 first_borrow_desc = "first ";
480 self.cannot_reborrow_already_uniquely_borrowed(
493 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
494 first_borrow_desc = "first ";
495 self.cannot_reborrow_already_uniquely_borrowed(
508 (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
509 | (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
510 | (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _)
511 | (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
512 | (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
513 | (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
516 if issued_spans == borrow_spans {
517 borrow_spans.var_span_label(
519 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
522 let borrow_place = &issued_borrow.borrowed_place;
523 let borrow_place_desc = self.describe_place(borrow_place.as_ref())
524 .unwrap_or_else(|| "_".to_owned());
525 issued_spans.var_span_label(
528 "first borrow occurs due to use of `{}`{}",
530 issued_spans.describe(),
534 borrow_spans.var_span_label(
537 "second borrow occurs due to use of `{}`{}",
539 borrow_spans.describe(),
544 if union_type_name != "" {
546 "`{}` is a field of the union `{}`, so it overlaps the field `{}`",
547 msg_place, union_type_name, msg_borrow,
551 explanation.add_explanation_to_diagnostic(
562 /// Returns the description of the root place for a conflicting borrow and the full
563 /// descriptions of the places that caused the conflict.
565 /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
566 /// attempted while a shared borrow is live, then this function will return:
570 /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
571 /// a shared borrow of another field `x.y`, then this function will return:
573 /// ("x", "x.z", "x.y")
575 /// In the more complex union case, where the union is a field of a struct, then if a mutable
576 /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
577 /// another field `x.u.y`, then this function will return:
579 /// ("x.u", "x.u.z", "x.u.y")
581 /// This is used when creating error messages like below:
583 /// > cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
584 /// > mutable (via `a.u.s.b`) [E0502]
585 pub(super) fn describe_place_for_conflicting_borrow(
587 first_borrowed_place: &Place<'tcx>,
588 second_borrowed_place: &Place<'tcx>,
589 ) -> (String, String, String, String) {
590 // Define a small closure that we can use to check if the type of a place
592 let union_ty = |place_base, place_projection| {
593 let ty = Place::ty_from(place_base, place_projection, self.body, self.infcx.tcx).ty;
594 ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
596 let describe_place = |place| self.describe_place(place).unwrap_or_else(|| "_".to_owned());
598 // Start with an empty tuple, so we can use the functions on `Option` to reduce some
599 // code duplication (particularly around returning an empty description in the failure
603 // If we have a conflicting borrow of the same place, then we don't want to add
604 // an extraneous "via x.y" to our diagnostics, so filter out this case.
605 first_borrowed_place != second_borrowed_place
608 // We're going to want to traverse the first borrowed place to see if we can find
609 // field access to a union. If we find that, then we will keep the place of the
610 // union being accessed and the field that was being accessed so we can check the
611 // second borrowed place for the same union and a access to a different field.
615 } = first_borrowed_place;
617 for (i, elem) in projection.iter().enumerate().rev() {
618 let base_proj = &projection[..i];
621 ProjectionElem::Field(field, _) if union_ty(base, base_proj).is_some() => {
622 return Some((PlaceRef {
624 projection: base_proj,
632 .and_then(|(target_base, target_field)| {
633 // With the place of a union and a field access into it, we traverse the second
634 // borrowed place and look for a access to a different field of the same union.
638 } = second_borrowed_place;
640 for (i, elem) in projection.iter().enumerate().rev() {
641 let proj_base = &projection[..i];
643 if let ProjectionElem::Field(field, _) = elem {
644 if let Some(union_ty) = union_ty(base, proj_base) {
645 if field != target_field
646 && base == target_base.base
647 && proj_base == target_base.projection {
648 // FIXME when we avoid clone reuse describe_place closure
649 let describe_base_place = self.describe_place(PlaceRef {
651 projection: proj_base,
652 }).unwrap_or_else(|| "_".to_owned());
656 describe_place(first_borrowed_place.as_ref()),
657 describe_place(second_borrowed_place.as_ref()),
658 union_ty.to_string(),
667 // If we didn't find a field access into a union, or both places match, then
668 // only return the description of the first place.
670 describe_place(first_borrowed_place.as_ref()),
678 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
680 /// This means that some data referenced by `borrow` needs to live
681 /// past the point where the StorageDeadOrDrop of `place` occurs.
682 /// This is usually interpreted as meaning that `place` has too
683 /// short a lifetime. (But sometimes it is more useful to report
684 /// it as a more direct conflict between the execution of a
685 /// `Drop::drop` with an aliasing borrow.)
686 pub(super) fn report_borrowed_value_does_not_live_long_enough(
689 borrow: &BorrowData<'tcx>,
690 place_span: (&Place<'tcx>, Span),
691 kind: Option<WriteKind>,
694 "report_borrowed_value_does_not_live_long_enough(\
695 {:?}, {:?}, {:?}, {:?}\
697 location, borrow, place_span, kind
700 let drop_span = place_span.1;
701 let root_place = self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All)
705 let borrow_spans = self.retrieve_borrow_spans(borrow);
706 let borrow_span = borrow_spans.var_or_use();
708 assert!(root_place.projection.is_empty());
709 let proper_span = match root_place.base {
710 PlaceBase::Local(local) => self.body.local_decls[*local].source_info.span,
714 if self.access_place_error_reported
716 base: root_place.base.clone(),
717 projection: root_place.projection.to_vec().into_boxed_slice(),
721 "suppressing access_place error when borrow doesn't live long enough for {:?}",
727 self.access_place_error_reported
729 base: root_place.base.clone(),
730 projection: root_place.projection.to_vec().into_boxed_slice(),
733 if let StorageDeadOrDrop::Destructor(dropped_ty) =
734 self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
736 // If a borrow of path `B` conflicts with drop of `D` (and
737 // we're not in the uninteresting case where `B` is a
738 // prefix of `D`), then report this as a more interesting
739 // destructor conflict.
740 if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
741 self.report_borrow_conflicts_with_destructor(
742 location, borrow, place_span, kind, dropped_ty,
748 let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
750 let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
751 let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place);
753 let err = match (place_desc, explanation) {
754 (Some(_), _) if self.is_place_thread_local(root_place) => {
755 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
757 // If the outlives constraint comes from inside the closure,
762 // Box::new(|| y) as Box<Fn() -> &'static i32>
764 // then just use the normal error. The closure isn't escaping
765 // and `move` will not help here.
768 BorrowExplanation::MustBeValidFor {
769 category: category @ ConstraintCategory::Return,
778 BorrowExplanation::MustBeValidFor {
779 category: category @ ConstraintCategory::CallArgument,
785 ) if borrow_spans.for_closure() => self.report_escaping_closure_capture(
786 borrow_spans.args_or_use(),
791 &format!("`{}`", name),
795 BorrowExplanation::MustBeValidFor {
796 category: ConstraintCategory::Assignment,
798 region_name: RegionName {
799 source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name),
805 ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span),
806 (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
814 (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
824 err.buffer(&mut self.errors_buffer);
827 fn report_local_value_does_not_live_long_enough(
831 borrow: &BorrowData<'tcx>,
833 borrow_spans: UseSpans,
834 explanation: BorrowExplanation,
835 ) -> DiagnosticBuilder<'cx> {
837 "report_local_value_does_not_live_long_enough(\
838 {:?}, {:?}, {:?}, {:?}, {:?}\
840 location, name, borrow, drop_span, borrow_spans
843 let borrow_span = borrow_spans.var_or_use();
844 if let BorrowExplanation::MustBeValidFor {
851 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
856 opt_place_desc.as_ref(),
862 let mut err = self.path_does_not_live_long_enough(
864 &format!("`{}`", name),
867 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
868 let region_name = annotation.emit(self, &mut err);
872 format!("`{}` would have to be valid for `{}`...", name, region_name),
875 if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
879 "...but `{}` will be dropped here, when the function `{}` returns",
881 self.infcx.tcx.hir().name(fn_hir_id),
886 "functions cannot return a borrow to data owned within the function's scope, \
887 functions can only return borrows to data passed as arguments",
890 "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
891 references-and-borrowing.html#dangling-references>",
896 format!("...but `{}` dropped here while still borrowed", name),
900 if let BorrowExplanation::MustBeValidFor { .. } = explanation {
902 explanation.add_explanation_to_diagnostic(
911 err.span_label(borrow_span, "borrowed value does not live long enough");
914 format!("`{}` dropped here while still borrowed", name),
917 let within = if borrow_spans.for_generator() {
923 borrow_spans.args_span_label(
925 format!("value captured here{}", within),
928 explanation.add_explanation_to_diagnostic(
929 self.infcx.tcx, self.body, &mut err, "", None);
935 fn report_borrow_conflicts_with_destructor(
938 borrow: &BorrowData<'tcx>,
939 (place, drop_span): (&Place<'tcx>, Span),
940 kind: Option<WriteKind>,
941 dropped_ty: Ty<'tcx>,
944 "report_borrow_conflicts_with_destructor(\
945 {:?}, {:?}, ({:?}, {:?}), {:?}\
947 location, borrow, place, drop_span, kind,
950 let borrow_spans = self.retrieve_borrow_spans(borrow);
951 let borrow_span = borrow_spans.var_or_use();
953 let mut err = self.cannot_borrow_across_destructor(borrow_span);
955 let what_was_dropped = match self.describe_place(place.as_ref()) {
956 Some(name) => format!("`{}`", name.as_str()),
957 None => String::from("temporary value"),
960 let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
961 Some(borrowed) => format!(
962 "here, drop of {D} needs exclusive access to `{B}`, \
963 because the type `{T}` implements the `Drop` trait",
964 D = what_was_dropped,
969 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
970 D = what_was_dropped,
974 err.span_label(drop_span, label);
976 // Only give this note and suggestion if they could be relevant.
978 self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
980 BorrowExplanation::UsedLater { .. }
981 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
982 err.note("consider using a `let` binding to create a longer lived value");
987 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
989 err.buffer(&mut self.errors_buffer);
992 fn report_thread_local_value_does_not_live_long_enough(
996 ) -> DiagnosticBuilder<'cx> {
998 "report_thread_local_value_does_not_live_long_enough(\
1001 drop_span, borrow_span
1004 let mut err = self.thread_local_value_does_not_live_long_enough(borrow_span);
1008 "thread-local variables cannot be borrowed beyond the end of the function",
1010 err.span_label(drop_span, "end of enclosing function is here");
1015 fn report_temporary_value_does_not_live_long_enough(
1018 borrow: &BorrowData<'tcx>,
1020 borrow_spans: UseSpans,
1022 explanation: BorrowExplanation,
1023 ) -> DiagnosticBuilder<'cx> {
1025 "report_temporary_value_does_not_live_long_enough(\
1026 {:?}, {:?}, {:?}, {:?}\
1028 location, borrow, drop_span, proper_span
1031 if let BorrowExplanation::MustBeValidFor {
1034 from_closure: false,
1037 if let Some(diag) = self.try_report_cannot_return_reference_to_local(
1048 let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
1051 "creates a temporary which is freed while still in use",
1055 "temporary value is freed at the end of this statement",
1059 BorrowExplanation::UsedLater(..)
1060 | BorrowExplanation::UsedLaterInLoop(..)
1061 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
1062 // Only give this note and suggestion if it could be relevant.
1063 err.note("consider using a `let` binding to create a longer lived value");
1067 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1069 let within = if borrow_spans.for_generator() {
1075 borrow_spans.args_span_label(
1077 format!("value captured here{}", within),
1083 fn try_report_cannot_return_reference_to_local(
1085 borrow: &BorrowData<'tcx>,
1088 category: ConstraintCategory,
1089 opt_place_desc: Option<&String>,
1090 ) -> Option<DiagnosticBuilder<'cx>> {
1091 let return_kind = match category {
1092 ConstraintCategory::Return => "return",
1093 ConstraintCategory::Yield => "yield",
1097 // FIXME use a better heuristic than Spans
1098 let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
1104 let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
1105 let local_kind = match borrow.borrowed_place {
1107 base: PlaceBase::Local(local),
1110 match self.body.local_kind(local) {
1111 LocalKind::ReturnPointer
1112 | LocalKind::Temp => bug!("temporary or return pointer with a name"),
1113 LocalKind::Var => "local variable ",
1115 if !self.upvars.is_empty()
1116 && local == Local::new(1) => {
1117 "variable captured by `move` "
1120 "function parameter "
1127 format!("{}`{}`", local_kind, place_desc),
1128 format!("`{}` is borrowed here", place_desc),
1131 let root_place = self.prefixes(borrow.borrowed_place.as_ref(),
1135 let local = if let PlaceRef {
1136 base: PlaceBase::Local(local),
1141 bug!("try_report_cannot_return_reference_to_local: not a local")
1143 match self.body.local_kind(*local) {
1144 LocalKind::ReturnPointer | LocalKind::Temp => (
1145 "temporary value".to_string(),
1146 "temporary value created here".to_string(),
1149 "function parameter".to_string(),
1150 "function parameter borrowed here".to_string(),
1153 "local binding".to_string(),
1154 "local binding introduced here".to_string(),
1159 let mut err = self.cannot_return_reference_to_local(
1166 if return_span != borrow_span {
1167 err.span_label(borrow_span, note);
1173 fn report_escaping_closure_capture(
1177 fr_name: &RegionName,
1178 category: ConstraintCategory,
1179 constraint_span: Span,
1181 ) -> DiagnosticBuilder<'cx> {
1182 let tcx = self.infcx.tcx;
1184 let mut err = self.cannot_capture_in_long_lived_closure(
1190 let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
1192 if string.starts_with("async ") {
1193 string.insert_str(6, "move ");
1194 } else if string.starts_with("async|") {
1195 string.insert_str(5, " move");
1197 string.insert_str(0, "move ");
1201 Err(_) => "move |<args>| <body>".to_string()
1204 err.span_suggestion(
1206 &format!("to force the closure to take ownership of {} (and any \
1207 other referenced variables), use the `move` keyword",
1210 Applicability::MachineApplicable,
1214 ConstraintCategory::Return => {
1215 err.span_note(constraint_span, "closure is returned here");
1217 ConstraintCategory::CallArgument => {
1218 fr_name.highlight_region_name(&mut err);
1221 &format!("function requires argument type to outlive `{}`", fr_name),
1224 _ => bug!("report_escaping_closure_capture called with unexpected constraint \
1225 category: `{:?}`", category),
1230 fn report_escaping_data(
1233 name: &Option<String>,
1237 ) -> DiagnosticBuilder<'cx> {
1238 let tcx = self.infcx.tcx;
1240 let escapes_from = if tcx.is_closure(self.mir_def_id) {
1241 let tables = tcx.typeck_tables_of(self.mir_def_id);
1242 let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1243 match tables.node_type(mir_hir_id).sty {
1244 ty::Closure(..) => "closure",
1245 ty::Generator(..) => "generator",
1246 _ => bug!("Closure body doesn't have a closure or generator type"),
1252 let mut err = borrowck_errors::borrowed_data_escapes_closure(
1261 "`{}` is declared here, outside of the {} body",
1262 upvar_name, escapes_from
1269 "borrow is only valid in the {} body",
1274 if let Some(name) = name {
1277 format!("reference to `{}` escapes the {} body here", name, escapes_from),
1282 format!("reference escapes the {} body here", escapes_from),
1289 fn get_moved_indexes(&mut self, location: Location, mpi: MovePathIndex) -> Vec<MoveSite> {
1290 let body = self.body;
1292 let mut stack = Vec::new();
1293 stack.extend(body.predecessor_locations(location).map(|predecessor| {
1294 let is_back_edge = location.dominates(predecessor, &self.dominators);
1295 (predecessor, is_back_edge)
1298 let mut visited = FxHashSet::default();
1299 let mut result = vec![];
1301 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
1303 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
1304 location, is_back_edge
1307 if !visited.insert(location) {
1312 let stmt_kind = body[location.block]
1314 .get(location.statement_index)
1316 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
1317 // this analysis only tries to find moves explicitly
1318 // written by the user, so we ignore the move-outs
1319 // created by `StorageDead` and at the beginning
1322 // If we are found a use of a.b.c which was in error, then we want to look for
1323 // moves not only of a.b.c but also a.b and a.
1325 // Note that the moves data already includes "parent" paths, so we don't have to
1326 // worry about the other case: that is, if there is a move of a.b.c, it is already
1327 // marked as a move of a.b and a as well, so we will generate the correct errors
1329 let mut mpis = vec![mpi];
1330 let move_paths = &self.move_data.move_paths;
1331 mpis.extend(move_paths[mpi].parents(move_paths));
1333 for moi in &self.move_data.loc_map[location] {
1334 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
1335 if mpis.contains(&self.move_data.moves[*moi].path) {
1336 debug!("report_use_of_moved_or_uninitialized: found");
1337 result.push(MoveSite {
1339 traversed_back_edge: is_back_edge,
1342 // Strictly speaking, we could continue our DFS here. There may be
1343 // other moves that can reach the point of error. But it is kind of
1344 // confusing to highlight them.
1352 // drop(a); // <-- current point of error
1355 // Because we stop the DFS here, we only highlight `let c = a`,
1356 // and not `let b = a`. We will of course also report an error at
1357 // `let c = a` which highlights `let b = a` as the move.
1364 let mut any_match = false;
1365 drop_flag_effects::for_location_inits(
1380 stack.extend(body.predecessor_locations(location).map(|predecessor| {
1381 let back_edge = location.dominates(predecessor, &self.dominators);
1382 (predecessor, is_back_edge || back_edge)
1389 pub(super) fn report_illegal_mutation_of_borrowed(
1392 (place, span): (&Place<'tcx>, Span),
1393 loan: &BorrowData<'tcx>,
1395 let loan_spans = self.retrieve_borrow_spans(loan);
1396 let loan_span = loan_spans.args_or_use();
1398 if loan.kind == BorrowKind::Shallow {
1399 let mut err = self.cannot_mutate_in_match_guard(
1402 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1405 loan_spans.var_span_label(
1407 format!("borrow occurs due to use{}", loan_spans.describe()),
1410 err.buffer(&mut self.errors_buffer);
1415 let mut err = self.cannot_assign_to_borrowed(
1418 &self.describe_place(place.as_ref()).unwrap_or_else(|| "_".to_owned()),
1421 loan_spans.var_span_label(
1423 format!("borrow occurs due to use{}", loan_spans.describe()),
1426 self.explain_why_borrow_contains_point(location, loan, None)
1427 .add_explanation_to_diagnostic(self.infcx.tcx, self.body, &mut err, "", None);
1429 err.buffer(&mut self.errors_buffer);
1432 /// Reports an illegal reassignment; for example, an assignment to
1433 /// (part of) a non-`mut` local that occurs potentially after that
1434 /// local has already been initialized. `place` is the path being
1435 /// assigned; `err_place` is a place providing a reason why
1436 /// `place` is not mutable (e.g., the non-`mut` local `x` in an
1437 /// assignment to `x.f`).
1438 pub(super) fn report_illegal_reassignment(
1440 _location: Location,
1441 (place, span): (&Place<'tcx>, Span),
1442 assigned_span: Span,
1443 err_place: &Place<'tcx>,
1445 let (from_arg, local_decl) = if let Place {
1446 base: PlaceBase::Local(local),
1449 if let LocalKind::Arg = self.body.local_kind(local) {
1450 (true, Some(&self.body.local_decls[local]))
1452 (false, Some(&self.body.local_decls[local]))
1458 // If root local is initialized immediately (everything apart from let
1459 // PATTERN;) then make the error refer to that local, rather than the
1460 // place being assigned later.
1461 let (place_description, assigned_span) = match local_decl {
1463 is_user_variable: Some(ClearCrossCrate::Clear),
1468 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1469 opt_match_place: None,
1475 is_user_variable: None,
1478 | None => (self.describe_place(place.as_ref()), assigned_span),
1479 Some(decl) => (self.describe_place(err_place.as_ref()), decl.source_info.span),
1482 let mut err = self.cannot_reassign_immutable(
1484 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1487 let msg = if from_arg {
1488 "cannot assign to immutable argument"
1490 "cannot assign twice to immutable variable"
1492 if span != assigned_span {
1494 let value_msg = match place_description {
1495 Some(name) => format!("`{}`", name),
1496 None => "value".to_owned(),
1498 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1501 if let Some(decl) = local_decl {
1502 if let Some(name) = decl.name {
1503 if decl.can_be_made_mutable() {
1504 err.span_suggestion(
1505 decl.source_info.span,
1506 "make this binding mutable",
1507 format!("mut {}", name),
1508 Applicability::MachineApplicable,
1513 err.span_label(span, msg);
1514 err.buffer(&mut self.errors_buffer);
1517 fn classify_drop_access_kind(&self, place: PlaceRef<'cx, 'tcx>) -> StorageDeadOrDrop<'tcx> {
1518 let tcx = self.infcx.tcx;
1519 match place.projection {
1521 StorageDeadOrDrop::LocalStorageDead
1524 // FIXME(spastorino) revisit when we get rid of Box
1525 let base = &place.projection[..place.projection.len() - 1];
1527 // FIXME(spastorino) make this iterate
1528 let base_access = self.classify_drop_access_kind(PlaceRef {
1533 ProjectionElem::Deref => match base_access {
1534 StorageDeadOrDrop::LocalStorageDead
1535 | StorageDeadOrDrop::BoxedStorageDead => {
1537 Place::ty_from(&place.base, base, self.body, tcx).ty.is_box(),
1538 "Drop of value behind a reference or raw pointer"
1540 StorageDeadOrDrop::BoxedStorageDead
1542 StorageDeadOrDrop::Destructor(_) => base_access,
1544 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1545 let base_ty = Place::ty_from(&place.base, base, self.body, tcx).ty;
1547 ty::Adt(def, _) if def.has_dtor(tcx) => {
1548 // Report the outermost adt with a destructor
1550 StorageDeadOrDrop::Destructor(_) => base_access,
1551 StorageDeadOrDrop::LocalStorageDead
1552 | StorageDeadOrDrop::BoxedStorageDead => {
1553 StorageDeadOrDrop::Destructor(base_ty)
1561 ProjectionElem::ConstantIndex { .. }
1562 | ProjectionElem::Subslice { .. }
1563 | ProjectionElem::Index(_) => base_access,
1569 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1570 /// borrow of local value that does not live long enough.
1571 fn annotate_argument_and_return_for_borrow(
1573 borrow: &BorrowData<'tcx>,
1574 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1575 // Define a fallback for when we can't match a closure.
1577 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1581 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1583 ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
1585 self.infcx.tcx.fn_sig(self.mir_def_id),
1592 // In order to determine whether we need to annotate, we need to check whether the reserve
1593 // place was an assignment into a temporary.
1595 // If it was, we check whether or not that temporary is eventually assigned into the return
1596 // place. If it was, we can add annotations about the function's return type and arguments
1597 // and it'll make sense.
1598 let location = borrow.reserve_location;
1600 "annotate_argument_and_return_for_borrow: location={:?}",
1603 if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1604 = &self.body[location.block].statements.get(location.statement_index)
1607 "annotate_argument_and_return_for_borrow: reservation={:?}",
1610 // Check that the initial assignment of the reserve location is into a temporary.
1611 let mut target = *match reservation {
1613 base: PlaceBase::Local(local),
1615 } if self.body.local_kind(*local) == LocalKind::Temp => local,
1619 // Next, look through the rest of the block, checking if we are assigning the
1620 // `target` (that is, the place that contains our borrow) to anything.
1621 let mut annotated_closure = None;
1622 for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
1624 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1627 if let StatementKind::Assign(
1629 base: PlaceBase::Local(assigned_to),
1635 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1639 // Check if our `target` was captured by a closure.
1640 if let Rvalue::Aggregate(
1641 box AggregateKind::Closure(def_id, substs),
1645 for operand in operands {
1646 let assigned_from = match operand {
1647 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1653 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1657 // Find the local from the operand.
1658 let assigned_from_local = match assigned_from.local_or_deref_local() {
1659 Some(local) => local,
1663 if assigned_from_local != target {
1667 // If a closure captured our `target` and then assigned
1668 // into a place then we should annotate the closure in
1669 // case it ends up being assigned into the return place.
1670 annotated_closure = self.annotate_fn_sig(
1672 self.infcx.closure_sig(*def_id, *substs),
1675 "annotate_argument_and_return_for_borrow: \
1676 annotated_closure={:?} assigned_from_local={:?} \
1678 annotated_closure, assigned_from_local, assigned_to
1681 if *assigned_to == mir::RETURN_PLACE {
1682 // If it was assigned directly into the return place, then
1684 return annotated_closure;
1686 // Otherwise, update the target.
1687 target = *assigned_to;
1691 // If none of our closure's operands matched, then skip to the next
1696 // Otherwise, look at other types of assignment.
1697 let assigned_from = match rvalue {
1698 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1699 Rvalue::Use(operand) => match operand {
1700 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1708 "annotate_argument_and_return_for_borrow: \
1709 assigned_from={:?}",
1713 // Find the local from the rvalue.
1714 let assigned_from_local = match assigned_from.local_or_deref_local() {
1715 Some(local) => local,
1719 "annotate_argument_and_return_for_borrow: \
1720 assigned_from_local={:?}",
1721 assigned_from_local,
1724 // Check if our local matches the target - if so, we've assigned our
1725 // borrow to a new place.
1726 if assigned_from_local != target {
1730 // If we assigned our `target` into a new place, then we should
1731 // check if it was the return place.
1733 "annotate_argument_and_return_for_borrow: \
1734 assigned_from_local={:?} assigned_to={:?}",
1735 assigned_from_local, assigned_to
1737 if *assigned_to == mir::RETURN_PLACE {
1738 // If it was then return the annotated closure if there was one,
1739 // else, annotate this function.
1740 return annotated_closure.or_else(fallback);
1743 // If we didn't assign into the return place, then we just update
1745 target = *assigned_to;
1749 // Check the terminator if we didn't find anything in the statements.
1750 let terminator = &self.body[location.block].terminator();
1752 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1755 if let TerminatorKind::Call {
1756 destination: Some((Place {
1757 base: PlaceBase::Local(assigned_to),
1762 } = &terminator.kind
1765 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1768 for operand in args {
1769 let assigned_from = match operand {
1770 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1776 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1780 if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
1782 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1783 assigned_from_local,
1786 if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1787 return annotated_closure.or_else(fallback);
1794 // If we haven't found an assignment into the return place, then we need not add
1796 debug!("annotate_argument_and_return_for_borrow: none found");
1800 /// Annotate the first argument and return type of a function signature if they are
1805 sig: ty::PolyFnSig<'tcx>,
1806 ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
1807 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1808 let is_closure = self.infcx.tcx.is_closure(did);
1809 let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
1810 let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
1812 // We need to work out which arguments to highlight. We do this by looking
1813 // at the return type, where there are three cases:
1815 // 1. If there are named arguments, then we should highlight the return type and
1816 // highlight any of the arguments that are also references with that lifetime.
1817 // If there are no arguments that have the same lifetime as the return type,
1818 // then don't highlight anything.
1819 // 2. The return type is a reference with an anonymous lifetime. If this is
1820 // the case, then we can take advantage of (and teach) the lifetime elision
1823 // We know that an error is being reported. So the arguments and return type
1824 // must satisfy the elision rules. Therefore, if there is a single argument
1825 // then that means the return type and first (and only) argument have the same
1826 // lifetime and the borrow isn't meeting that, we can highlight the argument
1829 // If there are multiple arguments then the first argument must be self (else
1830 // it would not satisfy the elision rules), so we can highlight self and the
1832 // 3. The return type is not a reference. In this case, we don't highlight
1834 let return_ty = sig.output();
1835 match return_ty.skip_binder().sty {
1836 ty::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1837 // This is case 1 from above, return type is a named reference so we need to
1838 // search for relevant arguments.
1839 let mut arguments = Vec::new();
1840 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1841 if let ty::Ref(argument_region, _, _) = argument.sty {
1842 if argument_region == return_region {
1843 // Need to use the `rustc::ty` types to compare against the
1844 // `return_region`. Then use the `rustc::hir` type to get only
1845 // the lifetime span.
1846 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
1847 // With access to the lifetime, we can get
1849 arguments.push((*argument, lifetime.span));
1851 bug!("ty type is a ref but hir type is not");
1857 // We need to have arguments. This shouldn't happen, but it's worth checking.
1858 if arguments.is_empty() {
1862 // We use a mix of the HIR and the Ty types to get information
1863 // as the HIR doesn't have full types for closure arguments.
1864 let return_ty = *sig.output().skip_binder();
1865 let mut return_span = fn_decl.output.span();
1866 if let hir::FunctionRetTy::Return(ty) = &fn_decl.output {
1867 if let hir::TyKind::Rptr(lifetime, _) = ty.node {
1868 return_span = lifetime.span;
1872 Some(AnnotatedBorrowFnSignature::NamedFunction {
1878 ty::Ref(_, _, _) if is_closure => {
1879 // This is case 2 from above but only for closures, return type is anonymous
1880 // reference so we select
1881 // the first argument.
1882 let argument_span = fn_decl.inputs.first()?.span;
1883 let argument_ty = sig.inputs().skip_binder().first()?;
1885 // Closure arguments are wrapped in a tuple, so we need to get the first
1887 if let ty::Tuple(elems) = argument_ty.sty {
1888 let argument_ty = elems.first()?.expect_ty();
1889 if let ty::Ref(_, _, _) = argument_ty.sty {
1890 return Some(AnnotatedBorrowFnSignature::Closure {
1899 ty::Ref(_, _, _) => {
1900 // This is also case 2 from above but for functions, return type is still an
1901 // anonymous reference so we select the first argument.
1902 let argument_span = fn_decl.inputs.first()?.span;
1903 let argument_ty = sig.inputs().skip_binder().first()?;
1905 let return_span = fn_decl.output.span();
1906 let return_ty = *sig.output().skip_binder();
1908 // We expect the first argument to be a reference.
1909 match argument_ty.sty {
1910 ty::Ref(_, _, _) => {}
1914 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1922 // This is case 3 from above, return type is not a reference so don't highlight
1931 enum AnnotatedBorrowFnSignature<'tcx> {
1933 arguments: Vec<(Ty<'tcx>, Span)>,
1934 return_ty: Ty<'tcx>,
1938 argument_ty: Ty<'tcx>,
1939 argument_span: Span,
1940 return_ty: Ty<'tcx>,
1944 argument_ty: Ty<'tcx>,
1945 argument_span: Span,
1949 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
1950 /// Annotate the provided diagnostic with information about borrow from the fn signature that
1954 cx: &mut MirBorrowckCtxt<'_, 'tcx>,
1955 diag: &mut DiagnosticBuilder<'_>,
1958 AnnotatedBorrowFnSignature::Closure {
1964 format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
1967 cx.get_region_name_for_ty(argument_ty, 0)
1969 AnnotatedBorrowFnSignature::AnonymousFunction {
1975 let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
1976 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
1978 let return_ty_name = cx.get_name_for_ty(return_ty, 0);
1979 let types_equal = return_ty_name == argument_ty_name;
1984 if types_equal { "also " } else { "" },
1990 "argument and return type have the same lifetime due to lifetime elision rules",
1993 "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
1994 lifetime-syntax.html#lifetime-elision>",
1997 cx.get_region_name_for_ty(return_ty, 0)
1999 AnnotatedBorrowFnSignature::NamedFunction {
2004 // Region of return type and arguments checked to be the same earlier.
2005 let region_name = cx.get_region_name_for_ty(return_ty, 0);
2006 for (_, argument_span) in arguments {
2007 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
2012 format!("also has lifetime `{}`", region_name,),
2016 "use data from the highlighted arguments which match the `{}` lifetime of \