1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use borrow_check::nll::explain_borrow::BorrowExplanation;
12 use borrow_check::prefixes::IsPrefixOf;
13 use borrow_check::WriteKind;
15 use rustc::hir::def_id::DefId;
16 use rustc::middle::region::ScopeTree;
18 self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, Constant, Field, Local,
19 LocalDecl, LocalKind, Location, Operand, Place, PlaceProjection, ProjectionElem,
20 Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
22 use rustc::ty::{self, DefIdTree};
23 use rustc::util::ppaux::with_highlight_region_for_bound_region;
24 use rustc_data_structures::fx::FxHashSet;
25 use rustc_data_structures::sync::Lrc;
26 use rustc_errors::{Applicability, DiagnosticBuilder};
29 use super::borrow_set::BorrowData;
30 use super::{Context, MirBorrowckCtxt};
31 use super::{InitializationRequiringAction, PrefixSet};
33 use dataflow::drop_flag_effects;
34 use dataflow::move_paths::indexes::MoveOutIndex;
35 use dataflow::move_paths::MovePathIndex;
36 use util::borrowck_errors::{BorrowckErrors, Origin};
40 /// Index of the "move out" that we found. The `MoveData` can
41 /// then tell us where the move occurred.
44 /// True if we traversed a back edge while walking from the point
45 /// of error to the move site.
46 traversed_back_edge: bool
49 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
50 pub(super) fn report_use_of_moved_or_uninitialized(
53 desired_action: InitializationRequiringAction,
54 (moved_place, used_place, span): (&Place<'tcx>, &Place<'tcx>, Span),
58 "report_use_of_moved_or_uninitialized: context={:?} desired_action={:?} \
59 moved_place={:?} used_place={:?} span={:?} mpi={:?}",
60 context, desired_action, moved_place, used_place, span, mpi
63 let use_spans = self.move_spans(moved_place, context.loc)
64 .or_else(|| self.borrow_spans(span, context.loc));
65 let span = use_spans.args_or_use();
67 let move_site_vec = self.get_moved_indexes(context, mpi);
69 "report_use_of_moved_or_uninitialized: move_site_vec={:?}",
72 let move_out_indices: Vec<_> = move_site_vec
74 .map(|move_site| move_site.moi)
77 if move_out_indices.is_empty() {
78 let root_place = self.prefixes(&used_place, PrefixSet::All).last().unwrap();
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.clone());
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.infcx.tcx.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()),
102 err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
104 use_spans.var_span_label(
106 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
109 err.buffer(&mut self.errors_buffer);
111 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
112 if self.prefixes(&reported_place, PrefixSet::All)
113 .any(|p| p == used_place)
116 "report_use_of_moved_or_uninitialized place: error suppressed \
124 let msg = ""; //FIXME: add "partially " or "collaterally "
126 let mut err = self.infcx.tcx.cannot_act_on_moved_value(
128 desired_action.as_noun(),
130 self.describe_place_with_options(&moved_place, IncludingDowncast(true)),
134 self.add_closure_invoked_twice_with_moved_variable_suggestion(
140 let mut is_loop_move = false;
141 for move_site in &move_site_vec {
142 let move_out = self.move_data.moves[(*move_site).moi];
143 let moved_place = &self.move_data.move_paths[move_out.path].place;
145 let move_spans = self.move_spans(moved_place, move_out.source);
146 let move_span = move_spans.args_or_use();
148 let move_msg = if move_spans.for_closure() {
154 if span == move_span {
157 format!("value moved{} here, in previous iteration of loop", move_msg),
160 } else if move_site.traversed_back_edge {
164 "value moved{} here, in previous iteration of loop",
169 err.span_label(move_span, format!("value moved{} here", move_msg));
170 move_spans.var_span_label(
172 format!("variable moved due to use{}", move_spans.describe()),
177 use_spans.var_span_label(
179 format!("{} occurs due to use{}", desired_action.as_noun(), use_spans.describe()),
186 "value {} here after move",
187 desired_action.as_verb_in_past_tense()
192 if let Some(ty) = self.retrieve_type_for_place(used_place) {
193 let needs_note = match ty.sty {
194 ty::Closure(id, _) => {
195 let tables = self.infcx.tcx.typeck_tables_of(id);
196 let node_id = self.infcx.tcx.hir.as_local_node_id(id).unwrap();
197 let hir_id = self.infcx.tcx.hir.node_to_hir_id(node_id);
199 tables.closure_kind_origins().get(hir_id).is_none()
205 let mpi = self.move_data.moves[move_out_indices[0]].path;
206 let place = &self.move_data.move_paths[mpi].place;
208 if let Some(ty) = self.retrieve_type_for_place(place) {
209 let note_msg = match self.describe_place_with_options(
211 IncludingDowncast(true),
213 Some(name) => format!("`{}`", name),
214 None => "value".to_owned(),
218 "move occurs because {} has type `{}`, \
219 which does not implement the `Copy` trait",
226 if let Some((_, mut old_err)) = self.move_error_reported
227 .insert(move_out_indices, (used_place.clone(), err))
229 // Cancel the old error so it doesn't ICE.
235 pub(super) fn report_move_out_while_borrowed(
238 (place, span): (&Place<'tcx>, Span),
239 borrow: &BorrowData<'tcx>,
242 "report_move_out_while_borrowed: context={:?} place={:?} span={:?} borrow={:?}",
243 context, place, span, borrow
245 let tcx = self.infcx.tcx;
246 let value_msg = match self.describe_place(place) {
247 Some(name) => format!("`{}`", name),
248 None => "value".to_owned(),
250 let borrow_msg = match self.describe_place(&borrow.borrowed_place) {
251 Some(name) => format!("`{}`", name),
252 None => "value".to_owned(),
255 let borrow_spans = self.retrieve_borrow_spans(borrow);
256 let borrow_span = borrow_spans.args_or_use();
258 let move_spans = self.move_spans(place, context.loc);
259 let span = move_spans.args_or_use();
261 let mut err = tcx.cannot_move_when_borrowed(
263 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
266 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
267 err.span_label(span, format!("move out of {} occurs here", value_msg));
269 borrow_spans.var_span_label(
271 format!("borrow occurs due to use{}", borrow_spans.describe())
274 move_spans.var_span_label(
276 format!("move occurs due to use{}", move_spans.describe())
279 self.explain_why_borrow_contains_point(context, borrow, None)
280 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
281 err.buffer(&mut self.errors_buffer);
284 pub(super) fn report_use_while_mutably_borrowed(
287 (place, _span): (&Place<'tcx>, Span),
288 borrow: &BorrowData<'tcx>,
290 let tcx = self.infcx.tcx;
292 let borrow_spans = self.retrieve_borrow_spans(borrow);
293 let borrow_span = borrow_spans.args_or_use();
295 // Conflicting borrows are reported separately, so only check for move
297 let use_spans = self.move_spans(place, context.loc);
298 let span = use_spans.var_or_use();
300 let mut err = tcx.cannot_use_when_mutably_borrowed(
302 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
304 &self.describe_place(&borrow.borrowed_place)
305 .unwrap_or_else(|| "_".to_owned()),
309 borrow_spans.var_span_label(&mut err, {
310 let place = &borrow.borrowed_place;
311 let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
313 format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
316 self.explain_why_borrow_contains_point(context, borrow, None)
317 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
318 err.buffer(&mut self.errors_buffer);
321 pub(super) fn report_conflicting_borrow(
324 (place, span): (&Place<'tcx>, Span),
325 gen_borrow_kind: BorrowKind,
326 issued_borrow: &BorrowData<'tcx>,
328 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
329 let issued_span = issued_spans.args_or_use();
331 let borrow_spans = self.borrow_spans(span, context.loc);
332 let span = borrow_spans.args_or_use();
334 let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() {
340 let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
341 let tcx = self.infcx.tcx;
343 let first_borrow_desc;
345 // FIXME: supply non-"" `opt_via` when appropriate
346 let mut err = match (
354 (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
355 first_borrow_desc = "mutable ";
356 tcx.cannot_reborrow_already_borrowed(
369 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
370 first_borrow_desc = "immutable ";
371 tcx.cannot_reborrow_already_borrowed(
385 (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
386 first_borrow_desc = "first ";
387 tcx.cannot_mutably_borrow_multiply(
398 (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
399 first_borrow_desc = "first ";
400 tcx.cannot_uniquely_borrow_by_two_closures(
409 (BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
410 | (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
411 let mut err = tcx.cannot_mutate_in_match_guard(
418 borrow_spans.var_span_label(
421 "borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe()
424 err.buffer(&mut self.errors_buffer);
429 (BorrowKind::Unique, _, _, _, _, _) => {
430 first_borrow_desc = "first ";
431 tcx.cannot_uniquely_borrow_by_one_closure(
444 (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
445 first_borrow_desc = "first ";
446 tcx.cannot_reborrow_already_uniquely_borrowed(
459 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
460 first_borrow_desc = "first ";
461 tcx.cannot_reborrow_already_uniquely_borrowed(
474 (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
475 | (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _) => {
476 // Shallow borrows are uses from the user's point of view.
477 self.report_use_while_mutably_borrowed(context, (place, span), issued_borrow);
480 (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
481 | (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
482 | (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
483 | (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
486 if issued_spans == borrow_spans {
487 borrow_spans.var_span_label(
489 format!("borrows occur due to use of `{}`{}", desc_place, borrow_spans.describe()),
492 let borrow_place = &issued_borrow.borrowed_place;
493 let borrow_place_desc = self.describe_place(borrow_place)
494 .unwrap_or_else(|| "_".to_owned());
495 issued_spans.var_span_label(
498 "first borrow occurs due to use of `{}`{}",
500 issued_spans.describe(),
504 borrow_spans.var_span_label(
507 "second borrow occurs due to use of `{}`{}",
509 borrow_spans.describe(),
514 self.explain_why_borrow_contains_point(context, issued_borrow, None)
515 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, first_borrow_desc);
517 err.buffer(&mut self.errors_buffer);
520 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
522 /// This means that some data referenced by `borrow` needs to live
523 /// past the point where the StorageDeadOrDrop of `place` occurs.
524 /// This is usually interpreted as meaning that `place` has too
525 /// short a lifetime. (But sometimes it is more useful to report
526 /// it as a more direct conflict between the execution of a
527 /// `Drop::drop` with an aliasing borrow.)
528 pub(super) fn report_borrowed_value_does_not_live_long_enough(
531 borrow: &BorrowData<'tcx>,
532 place_span: (&Place<'tcx>, Span),
533 kind: Option<WriteKind>,
536 "report_borrowed_value_does_not_live_long_enough(\
537 {:?}, {:?}, {:?}, {:?}\
539 context, borrow, place_span, kind
542 let drop_span = place_span.1;
543 let scope_tree = self.infcx.tcx.region_scope_tree(self.mir_def_id);
544 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
548 let borrow_spans = self.retrieve_borrow_spans(borrow);
549 let borrow_span = borrow_spans.var_or_use();
551 let proper_span = match *root_place {
552 Place::Local(local) => self.mir.local_decls[local].source_info.span,
556 if self.access_place_error_reported
557 .contains(&(root_place.clone(), borrow_span))
560 "suppressing access_place error when borrow doesn't live long enough for {:?}",
566 self.access_place_error_reported
567 .insert((root_place.clone(), borrow_span));
569 if let StorageDeadOrDrop::Destructor(dropped_ty) =
570 self.classify_drop_access_kind(&borrow.borrowed_place)
572 // If a borrow of path `B` conflicts with drop of `D` (and
573 // we're not in the uninteresting case where `B` is a
574 // prefix of `D`), then report this as a more interesting
575 // destructor conflict.
576 if !borrow.borrowed_place.is_prefix_of(place_span.0) {
577 self.report_borrow_conflicts_with_destructor(
578 context, borrow, place_span, kind, dropped_ty,
584 let err = match &self.describe_place(&borrow.borrowed_place) {
585 Some(_) if self.is_place_thread_local(root_place) => {
586 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
588 Some(name) => self.report_local_value_does_not_live_long_enough(
595 kind.map(|k| (k, place_span.0)),
597 None => self.report_temporary_value_does_not_live_long_enough(
607 err.buffer(&mut self.errors_buffer);
610 fn report_local_value_does_not_live_long_enough(
614 scope_tree: &Lrc<ScopeTree>,
615 borrow: &BorrowData<'tcx>,
617 borrow_spans: UseSpans,
618 kind_place: Option<(WriteKind, &Place<'tcx>)>,
619 ) -> DiagnosticBuilder<'cx> {
621 "report_local_value_does_not_live_long_enough(\
622 {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
624 context, name, scope_tree, borrow, drop_span, borrow_spans
627 let borrow_span = borrow_spans.var_or_use();
628 let mut err = self.infcx.tcx.path_does_not_live_long_enough(
630 &format!("`{}`", name),
634 let explanation = self.explain_why_borrow_contains_point(context, borrow, kind_place);
635 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
636 let region_name = annotation.emit(&mut err);
640 format!("`{}` would have to be valid for `{}`...", name, region_name),
643 if let Some(fn_node_id) = self.infcx.tcx.hir.as_local_node_id(self.mir_def_id) {
647 "...but `{}` will be dropped here, when the function `{}` returns",
649 self.infcx.tcx.hir.name(fn_node_id),
654 "functions cannot return a borrow to data owned within the function's scope, \
655 functions can only return borrows to data passed as arguments",
658 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch04-02-\
659 references-and-borrowing.html#dangling-references>",
664 format!("...but `{}` dropped here while still borrowed", name),
668 if let BorrowExplanation::MustBeValidFor(..) = explanation {
670 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
673 err.span_label(borrow_span, "borrowed value does not live long enough");
676 format!("`{}` dropped here while still borrowed", name),
679 let within = if borrow_spans.for_generator() {
685 borrow_spans.args_span_label(
687 format!("value captured here{}", within),
690 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
696 pub(super) fn report_borrow_conflicts_with_destructor(
699 borrow: &BorrowData<'tcx>,
700 (place, drop_span): (&Place<'tcx>, Span),
701 kind: Option<WriteKind>,
702 dropped_ty: ty::Ty<'tcx>,
705 "report_borrow_conflicts_with_destructor(\
706 {:?}, {:?}, ({:?}, {:?}), {:?}\
708 context, borrow, place, drop_span, kind,
711 let borrow_spans = self.retrieve_borrow_spans(borrow);
712 let borrow_span = borrow_spans.var_or_use();
714 let mut err = self.infcx
716 .cannot_borrow_across_destructor(borrow_span, Origin::Mir);
718 let what_was_dropped = match self.describe_place(place) {
719 Some(name) => format!("`{}`", name.as_str()),
720 None => format!("temporary value"),
723 let label = match self.describe_place(&borrow.borrowed_place) {
724 Some(borrowed) => format!(
725 "here, drop of {D} needs exclusive access to `{B}`, \
726 because the type `{T}` implements the `Drop` trait",
727 D = what_was_dropped,
732 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
733 D = what_was_dropped,
737 err.span_label(drop_span, label);
739 // Only give this note and suggestion if they could be relevant.
741 self.explain_why_borrow_contains_point(context, borrow, kind.map(|k| (k, place)));
743 BorrowExplanation::UsedLater { .. }
744 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
745 err.note("consider using a `let` binding to create a longer lived value");
750 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
752 err.buffer(&mut self.errors_buffer);
755 fn report_thread_local_value_does_not_live_long_enough(
759 ) -> DiagnosticBuilder<'cx> {
761 "report_thread_local_value_does_not_live_long_enough(\
764 drop_span, borrow_span
767 let mut err = self.infcx
769 .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
773 "thread-local variables cannot be borrowed beyond the end of the function",
775 err.span_label(drop_span, "end of enclosing function is here");
780 fn report_temporary_value_does_not_live_long_enough(
783 scope_tree: &Lrc<ScopeTree>,
784 borrow: &BorrowData<'tcx>,
786 borrow_spans: UseSpans,
788 ) -> DiagnosticBuilder<'cx> {
790 "report_temporary_value_does_not_live_long_enough(\
791 {:?}, {:?}, {:?}, {:?}, {:?}\
793 context, scope_tree, borrow, drop_span, proper_span
796 let tcx = self.infcx.tcx;
797 let mut err = tcx.temporary_value_borrowed_for_too_long(proper_span, Origin::Mir);
800 "creates a temporary which is freed while still in use",
804 "temporary value is freed at the end of this statement",
807 let explanation = self.explain_why_borrow_contains_point(context, borrow, None);
809 BorrowExplanation::UsedLater(..)
810 | BorrowExplanation::UsedLaterInLoop(..)
811 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
812 // Only give this note and suggestion if it could be relevant.
813 err.note("consider using a `let` binding to create a longer lived value");
817 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
819 let within = if borrow_spans.for_generator() {
825 borrow_spans.args_span_label(
827 format!("value captured here{}", within),
833 fn get_moved_indexes(&mut self, context: Context, mpi: MovePathIndex) -> Vec<MoveSite> {
836 let mut stack = Vec::new();
837 stack.extend(mir.predecessor_locations(context.loc).map(|predecessor| {
838 let is_back_edge = context.loc.dominates(predecessor, &self.dominators);
839 (predecessor, is_back_edge)
842 let mut visited = FxHashSet::default();
843 let mut result = vec![];
845 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
847 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
848 location, is_back_edge
851 if !visited.insert(location) {
856 let stmt_kind = mir[location.block]
858 .get(location.statement_index)
860 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
861 // this analysis only tries to find moves explicitly
862 // written by the user, so we ignore the move-outs
863 // created by `StorageDead` and at the beginning
866 // If we are found a use of a.b.c which was in error, then we want to look for
867 // moves not only of a.b.c but also a.b and a.
869 // Note that the moves data already includes "parent" paths, so we don't have to
870 // worry about the other case: that is, if there is a move of a.b.c, it is already
871 // marked as a move of a.b and a as well, so we will generate the correct errors
873 let mut mpis = vec![mpi];
874 let move_paths = &self.move_data.move_paths;
875 mpis.extend(move_paths[mpi].parents(move_paths));
877 for moi in &self.move_data.loc_map[location] {
878 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
879 if mpis.contains(&self.move_data.moves[*moi].path) {
880 debug!("report_use_of_moved_or_uninitialized: found");
881 result.push(MoveSite {
883 traversed_back_edge: is_back_edge,
886 // Strictly speaking, we could continue our DFS here. There may be
887 // other moves that can reach the point of error. But it is kind of
888 // confusing to highlight them.
896 // drop(a); // <-- current point of error
899 // Because we stop the DFS here, we only highlight `let c = a`,
900 // and not `let b = a`. We will of course also report an error at
901 // `let c = a` which highlights `let b = a` as the move.
908 let mut any_match = false;
909 drop_flag_effects::for_location_inits(
924 stack.extend(mir.predecessor_locations(location).map(|predecessor| {
925 let back_edge = location.dominates(predecessor, &self.dominators);
926 (predecessor, is_back_edge || back_edge)
933 pub(super) fn report_illegal_mutation_of_borrowed(
936 (place, span): (&Place<'tcx>, Span),
937 loan: &BorrowData<'tcx>,
939 let loan_spans = self.retrieve_borrow_spans(loan);
940 let loan_span = loan_spans.args_or_use();
942 let tcx = self.infcx.tcx;
943 let mut err = if loan.kind == BorrowKind::Shallow {
944 tcx.cannot_mutate_in_match_guard(
947 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
952 tcx.cannot_assign_to_borrowed(
955 &self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
960 loan_spans.var_span_label(
962 format!("borrow occurs due to use{}", loan_spans.describe()),
965 self.explain_why_borrow_contains_point(context, loan, None)
966 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
968 err.buffer(&mut self.errors_buffer);
971 /// Reports an illegal reassignment; for example, an assignment to
972 /// (part of) a non-`mut` local that occurs potentially after that
973 /// local has already been initialized. `place` is the path being
974 /// assigned; `err_place` is a place providing a reason why
975 /// `place` is not mutable (e.g. the non-`mut` local `x` in an
976 /// assignment to `x.f`).
977 pub(super) fn report_illegal_reassignment(
980 (place, span): (&Place<'tcx>, Span),
982 err_place: &Place<'tcx>,
984 let (from_arg, local_decl) = if let Place::Local(local) = *err_place {
985 if let LocalKind::Arg = self.mir.local_kind(local) {
986 (true, Some(&self.mir.local_decls[local]))
988 (false, Some(&self.mir.local_decls[local]))
994 // If root local is initialized immediately (everything apart from let
995 // PATTERN;) then make the error refer to that local, rather than the
996 // place being assigned later.
997 let (place_description, assigned_span) = match local_decl {
999 is_user_variable: Some(ClearCrossCrate::Clear),
1004 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1005 opt_match_place: None,
1011 is_user_variable: None,
1014 | None => (self.describe_place(place), assigned_span),
1015 Some(decl) => (self.describe_place(err_place), decl.source_info.span),
1018 let mut err = self.infcx.tcx.cannot_reassign_immutable(
1020 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1024 let msg = if from_arg {
1025 "cannot assign to immutable argument"
1027 "cannot assign twice to immutable variable"
1029 if span != assigned_span {
1031 let value_msg = match place_description {
1032 Some(name) => format!("`{}`", name),
1033 None => "value".to_owned(),
1035 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1038 if let Some(decl) = local_decl {
1039 if let Some(name) = decl.name {
1040 if decl.can_be_made_mutable() {
1041 err.span_suggestion_with_applicability(
1042 decl.source_info.span,
1043 "make this binding mutable",
1044 format!("mut {}", name),
1045 Applicability::MachineApplicable,
1050 err.span_label(span, msg);
1051 err.buffer(&mut self.errors_buffer);
1055 pub(super) struct IncludingDowncast(bool);
1057 /// Which case a StorageDeadOrDrop is for.
1058 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1059 enum StorageDeadOrDrop<'tcx> {
1062 Destructor(ty::Ty<'tcx>),
1065 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1067 /// Adds a suggestion when a closure is invoked twice with a moved variable.
1070 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
1072 /// --> $DIR/issue-42065.rs:16:29
1074 /// LL | for (key, value) in dict {
1077 pub(super) fn add_closure_invoked_twice_with_moved_variable_suggestion(
1080 place: &Place<'tcx>,
1081 diag: &mut DiagnosticBuilder<'_>,
1083 let mut target = place.local();
1085 "add_closure_invoked_twice_with_moved_variable_suggestion: location={:?} place={:?} \
1087 location, place, target,
1089 for stmt in &self.mir[location.block].statements[location.statement_index..] {
1091 "add_closure_invoked_twice_with_moved_variable_suggestion: stmt={:?} \
1095 if let StatementKind::Assign(into, box Rvalue::Use(from)) = &stmt.kind {
1097 "add_closure_invoked_twice_with_moved_variable_suggestion: into={:?} \
1102 Operand::Copy(ref place) |
1103 Operand::Move(ref place) if target == place.local() =>
1104 target = into.local(),
1111 let terminator = self.mir[location.block].terminator();
1113 "add_closure_invoked_twice_with_moved_variable_suggestion: terminator={:?}",
1116 if let TerminatorKind::Call {
1117 func: Operand::Constant(box Constant {
1118 literal: ty::Const { ty: &ty::TyS { sty: ty::TyKind::FnDef(id, _), .. }, .. },
1123 } = &terminator.kind {
1124 debug!("add_closure_invoked_twice_with_moved_variable_suggestion: id={:?}", id);
1125 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
1126 let closure = match args.first() {
1127 Some(Operand::Copy(ref place)) |
1128 Some(Operand::Move(ref place)) if target == place.local() =>
1129 place.local().unwrap(),
1133 "add_closure_invoked_twice_with_moved_variable_suggestion: closure={:?}",
1137 if let ty::TyKind::Closure(did, _substs) = self.mir.local_decls[closure].ty.sty {
1138 let node_id = match self.infcx.tcx.hir.as_local_node_id(did) {
1139 Some(node_id) => node_id,
1142 let hir_id = self.infcx.tcx.hir.node_to_hir_id(node_id);
1146 )) = self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id) {
1150 "closure cannot be invoked more than once because it \
1151 moves the variable `{}` out of its environment",
1161 /// End-user visible description of `place` if one can be found. If the
1162 /// place is a temporary for instance, None will be returned.
1163 pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
1164 self.describe_place_with_options(place, IncludingDowncast(false))
1167 /// End-user visible description of `place` if one can be found. If the
1168 /// place is a temporary for instance, None will be returned.
1169 /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
1170 /// `Downcast` and `IncludingDowncast` is true
1171 pub(super) fn describe_place_with_options(
1173 place: &Place<'tcx>,
1174 including_downcast: IncludingDowncast,
1175 ) -> Option<String> {
1176 let mut buf = String::new();
1177 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
1178 Ok(()) => Some(buf),
1183 /// Appends end-user visible description of `place` to `buf`.
1184 fn append_place_to_string(
1186 place: &Place<'tcx>,
1188 mut autoderef: bool,
1189 including_downcast: &IncludingDowncast,
1190 ) -> Result<(), ()> {
1192 Place::Promoted(_) => {
1193 buf.push_str("promoted");
1195 Place::Local(local) => {
1196 self.append_local_to_string(local, buf)?;
1198 Place::Static(ref static_) => {
1199 buf.push_str(&self.infcx.tcx.item_name(static_.def_id).to_string());
1201 Place::Projection(ref proj) => {
1203 ProjectionElem::Deref => {
1204 let upvar_field_projection =
1205 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1206 if let Some(field) = upvar_field_projection {
1207 let var_index = field.index();
1208 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1209 if self.mir.upvar_decls[var_index].by_ref {
1210 buf.push_str(&name);
1212 buf.push_str(&format!("*{}", &name));
1216 self.append_place_to_string(
1220 &including_downcast,
1222 } else if let Place::Local(local) = proj.base {
1223 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
1224 self.mir.local_decls[local].is_user_variable
1226 self.append_place_to_string(
1230 &including_downcast,
1234 self.append_place_to_string(
1238 &including_downcast,
1243 self.append_place_to_string(
1247 &including_downcast,
1252 ProjectionElem::Downcast(..) => {
1253 self.append_place_to_string(
1257 &including_downcast,
1259 if including_downcast.0 {
1263 ProjectionElem::Field(field, _ty) => {
1266 let upvar_field_projection =
1267 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1268 if let Some(field) = upvar_field_projection {
1269 let var_index = field.index();
1270 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1271 buf.push_str(&name);
1273 let field_name = self.describe_field(&proj.base, field);
1274 self.append_place_to_string(
1278 &including_downcast,
1280 buf.push_str(&format!(".{}", field_name));
1283 ProjectionElem::Index(index) => {
1286 self.append_place_to_string(
1290 &including_downcast,
1293 if self.append_local_to_string(index, buf).is_err() {
1298 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1300 // Since it isn't possible to borrow an element on a particular index and
1301 // then use another while the borrow is held, don't output indices details
1302 // to avoid confusing the end-user
1303 self.append_place_to_string(
1307 &including_downcast,
1309 buf.push_str(&"[..]");
1318 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
1319 /// a name, then `Err` is returned
1320 fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
1321 let local = &self.mir.local_decls[local_index];
1324 buf.push_str(&name.to_string());
1331 /// End-user visible description of the `field`nth field of `base`
1332 fn describe_field(&self, base: &Place, field: Field) -> String {
1334 Place::Local(local) => {
1335 let local = &self.mir.local_decls[local];
1336 self.describe_field_from_ty(&local.ty, field)
1338 Place::Promoted(ref prom) => self.describe_field_from_ty(&prom.1, field),
1339 Place::Static(ref static_) => self.describe_field_from_ty(&static_.ty, field),
1340 Place::Projection(ref proj) => match proj.elem {
1341 ProjectionElem::Deref => self.describe_field(&proj.base, field),
1342 ProjectionElem::Downcast(def, variant_index) =>
1343 def.variants[variant_index].fields[field.index()].ident.to_string(),
1344 ProjectionElem::Field(_, field_type) => {
1345 self.describe_field_from_ty(&field_type, field)
1347 ProjectionElem::Index(..)
1348 | ProjectionElem::ConstantIndex { .. }
1349 | ProjectionElem::Subslice { .. } => {
1350 self.describe_field(&proj.base, field).to_string()
1356 /// End-user visible description of the `field_index`nth field of `ty`
1357 fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String {
1359 // If the type is a box, the field is described from the boxed type
1360 self.describe_field_from_ty(&ty.boxed_ty(), field)
1363 ty::Adt(def, _) => if def.is_enum() {
1364 field.index().to_string()
1366 def.non_enum_variant().fields[field.index()]
1370 ty::Tuple(_) => field.index().to_string(),
1371 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
1372 self.describe_field_from_ty(&ty, field)
1374 ty::Array(ty, _) | ty::Slice(ty) => self.describe_field_from_ty(&ty, field),
1375 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
1376 // Convert the def-id into a node-id. node-ids are only valid for
1377 // the local code in the current crate, so this returns an `Option` in case
1378 // the closure comes from another crate. But in that case we wouldn't
1379 // be borrowck'ing it, so we can just unwrap:
1380 let node_id = self.infcx.tcx.hir.as_local_node_id(def_id).unwrap();
1381 let freevar = self.infcx
1383 .with_freevars(node_id, |fv| fv[field.index()]);
1385 self.infcx.tcx.hir.name(freevar.var_id()).to_string()
1388 // Might need a revision when the fields in trait RFC is implemented
1389 // (https://github.com/rust-lang/rfcs/pull/1546)
1391 "End-user description not implemented for field access on `{:?}`",
1399 /// Retrieve type of a place for the current MIR representation
1400 fn retrieve_type_for_place(&self, place: &Place<'tcx>) -> Option<ty::Ty> {
1402 Place::Local(local) => {
1403 let local = &self.mir.local_decls[*local];
1406 Place::Promoted(ref prom) => Some(prom.1),
1407 Place::Static(ref st) => Some(st.ty),
1408 Place::Projection(ref proj) => match proj.elem {
1409 ProjectionElem::Field(_, ty) => Some(ty),
1415 /// Check if a place is a thread-local static.
1416 pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
1417 if let Place::Static(statik) = place {
1418 let attrs = self.infcx.tcx.get_attrs(statik.def_id);
1419 let is_thread_local = attrs.iter().any(|attr| attr.check_name("thread_local"));
1422 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
1423 attrs, is_thread_local
1427 debug!("is_place_thread_local: no");
1432 fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
1433 let tcx = self.infcx.tcx;
1435 Place::Local(_) | Place::Static(_) | Place::Promoted(_) => {
1436 StorageDeadOrDrop::LocalStorageDead
1438 Place::Projection(box PlaceProjection { base, elem }) => {
1439 let base_access = self.classify_drop_access_kind(base);
1441 ProjectionElem::Deref => match base_access {
1442 StorageDeadOrDrop::LocalStorageDead
1443 | StorageDeadOrDrop::BoxedStorageDead => {
1445 base.ty(self.mir, tcx).to_ty(tcx).is_box(),
1446 "Drop of value behind a reference or raw pointer"
1448 StorageDeadOrDrop::BoxedStorageDead
1450 StorageDeadOrDrop::Destructor(_) => base_access,
1452 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1453 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1455 ty::Adt(def, _) if def.has_dtor(tcx) => {
1456 // Report the outermost adt with a destructor
1458 StorageDeadOrDrop::Destructor(_) => base_access,
1459 StorageDeadOrDrop::LocalStorageDead
1460 | StorageDeadOrDrop::BoxedStorageDead => {
1461 StorageDeadOrDrop::Destructor(base_ty)
1469 ProjectionElem::ConstantIndex { .. }
1470 | ProjectionElem::Subslice { .. }
1471 | ProjectionElem::Index(_) => base_access,
1477 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1478 /// borrow of local value that does not live long enough.
1479 fn annotate_argument_and_return_for_borrow(
1481 borrow: &BorrowData<'tcx>,
1482 ) -> Option<AnnotatedBorrowFnSignature> {
1483 // Define a fallback for when we can't match a closure.
1485 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1489 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1491 ty::TyKind::FnDef(_, _) | ty::TyKind::FnPtr(_) => self.annotate_fn_sig(
1493 self.infcx.tcx.fn_sig(self.mir_def_id),
1500 // In order to determine whether we need to annotate, we need to check whether the reserve
1501 // place was an assignment into a temporary.
1503 // If it was, we check whether or not that temporary is eventually assigned into the return
1504 // place. If it was, we can add annotations about the function's return type and arguments
1505 // and it'll make sense.
1506 let location = borrow.reserve_location;
1508 "annotate_argument_and_return_for_borrow: location={:?}",
1511 if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1512 = &self.mir[location.block].statements.get(location.statement_index)
1515 "annotate_argument_and_return_for_borrow: reservation={:?}",
1518 // Check that the initial assignment of the reserve location is into a temporary.
1519 let mut target = *match reservation {
1520 Place::Local(local) if self.mir.local_kind(*local) == LocalKind::Temp => local,
1524 // Next, look through the rest of the block, checking if we are assigning the
1525 // `target` (that is, the place that contains our borrow) to anything.
1526 let mut annotated_closure = None;
1527 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1529 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1532 if let StatementKind::Assign(Place::Local(assigned_to), box rvalue) = &stmt.kind
1535 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1539 // Check if our `target` was captured by a closure.
1540 if let Rvalue::Aggregate(
1541 box AggregateKind::Closure(def_id, substs),
1545 for operand in operands {
1546 let assigned_from = match operand {
1547 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1553 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1557 // Find the local from the operand.
1558 let assigned_from_local = match assigned_from.local() {
1559 Some(local) => local,
1563 if assigned_from_local != target {
1567 // If a closure captured our `target` and then assigned
1568 // into a place then we should annotate the closure in
1569 // case it ends up being assigned into the return place.
1570 annotated_closure = self.annotate_fn_sig(
1572 self.infcx.closure_sig(*def_id, *substs),
1575 "annotate_argument_and_return_for_borrow: \
1576 annotated_closure={:?} assigned_from_local={:?} \
1578 annotated_closure, assigned_from_local, assigned_to
1581 if *assigned_to == mir::RETURN_PLACE {
1582 // If it was assigned directly into the return place, then
1584 return annotated_closure;
1586 // Otherwise, update the target.
1587 target = *assigned_to;
1591 // If none of our closure's operands matched, then skip to the next
1596 // Otherwise, look at other types of assignment.
1597 let assigned_from = match rvalue {
1598 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1599 Rvalue::Use(operand) => match operand {
1600 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1608 "annotate_argument_and_return_for_borrow: \
1609 assigned_from={:?}",
1613 // Find the local from the rvalue.
1614 let assigned_from_local = match assigned_from.local() {
1615 Some(local) => local,
1619 "annotate_argument_and_return_for_borrow: \
1620 assigned_from_local={:?}",
1621 assigned_from_local,
1624 // Check if our local matches the target - if so, we've assigned our
1625 // borrow to a new place.
1626 if assigned_from_local != target {
1630 // If we assigned our `target` into a new place, then we should
1631 // check if it was the return place.
1633 "annotate_argument_and_return_for_borrow: \
1634 assigned_from_local={:?} assigned_to={:?}",
1635 assigned_from_local, assigned_to
1637 if *assigned_to == mir::RETURN_PLACE {
1638 // If it was then return the annotated closure if there was one,
1639 // else, annotate this function.
1640 return annotated_closure.or_else(fallback);
1643 // If we didn't assign into the return place, then we just update
1645 target = *assigned_to;
1649 // Check the terminator if we didn't find anything in the statements.
1650 let terminator = &self.mir[location.block].terminator();
1652 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1655 if let TerminatorKind::Call {
1656 destination: Some((Place::Local(assigned_to), _)),
1659 } = &terminator.kind
1662 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1665 for operand in args {
1666 let assigned_from = match operand {
1667 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1673 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1677 if let Some(assigned_from_local) = assigned_from.local() {
1679 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1680 assigned_from_local,
1683 if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1684 return annotated_closure.or_else(fallback);
1691 // If we haven't found an assignment into the return place, then we need not add
1693 debug!("annotate_argument_and_return_for_borrow: none found");
1697 /// Annotate the first argument and return type of a function signature if they are
1702 sig: ty::PolyFnSig<'tcx>,
1703 ) -> Option<AnnotatedBorrowFnSignature> {
1704 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1705 let is_closure = self.infcx.tcx.is_closure(did);
1706 let fn_node_id = self.infcx.tcx.hir.as_local_node_id(did)?;
1707 let fn_decl = self.infcx.tcx.hir.fn_decl(fn_node_id)?;
1709 // We need to work out which arguments to highlight. We do this by looking
1710 // at the return type, where there are three cases:
1712 // 1. If there are named arguments, then we should highlight the return type and
1713 // highlight any of the arguments that are also references with that lifetime.
1714 // If there are no arguments that have the same lifetime as the return type,
1715 // then don't highlight anything.
1716 // 2. The return type is a reference with an anonymous lifetime. If this is
1717 // the case, then we can take advantage of (and teach) the lifetime elision
1720 // We know that an error is being reported. So the arguments and return type
1721 // must satisfy the elision rules. Therefore, if there is a single argument
1722 // then that means the return type and first (and only) argument have the same
1723 // lifetime and the borrow isn't meeting that, we can highlight the argument
1726 // If there are multiple arguments then the first argument must be self (else
1727 // it would not satisfy the elision rules), so we can highlight self and the
1729 // 3. The return type is not a reference. In this case, we don't highlight
1731 let return_ty = sig.output();
1732 match return_ty.skip_binder().sty {
1733 ty::TyKind::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1734 // This is case 1 from above, return type is a named reference so we need to
1735 // search for relevant arguments.
1736 let mut arguments = Vec::new();
1737 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1738 if let ty::TyKind::Ref(argument_region, _, _) = argument.sty {
1739 if argument_region == return_region {
1740 // Need to use the `rustc::ty` types to compare against the
1741 // `return_region`. Then use the `rustc::hir` type to get only
1742 // the lifetime span.
1743 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
1744 // With access to the lifetime, we can get
1746 arguments.push((*argument, lifetime.span));
1748 bug!("ty type is a ref but hir type is not");
1754 // We need to have arguments. This shouldn't happen, but it's worth checking.
1755 if arguments.is_empty() {
1759 // We use a mix of the HIR and the Ty types to get information
1760 // as the HIR doesn't have full types for closure arguments.
1761 let return_ty = *sig.output().skip_binder();
1762 let mut return_span = fn_decl.output.span();
1763 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
1764 if let hir::TyKind::Rptr(lifetime, _) = ty.into_inner().node {
1765 return_span = lifetime.span;
1769 Some(AnnotatedBorrowFnSignature::NamedFunction {
1775 ty::TyKind::Ref(_, _, _) if is_closure => {
1776 // This is case 2 from above but only for closures, return type is anonymous
1777 // reference so we select
1778 // the first argument.
1779 let argument_span = fn_decl.inputs.first()?.span;
1780 let argument_ty = sig.inputs().skip_binder().first()?;
1782 // Closure arguments are wrapped in a tuple, so we need to get the first
1784 if let ty::TyKind::Tuple(elems) = argument_ty.sty {
1785 let argument_ty = elems.first()?;
1786 if let ty::TyKind::Ref(_, _, _) = argument_ty.sty {
1787 return Some(AnnotatedBorrowFnSignature::Closure {
1796 ty::TyKind::Ref(_, _, _) => {
1797 // This is also case 2 from above but for functions, return type is still an
1798 // anonymous reference so we select the first argument.
1799 let argument_span = fn_decl.inputs.first()?.span;
1800 let argument_ty = sig.inputs().skip_binder().first()?;
1802 let return_span = fn_decl.output.span();
1803 let return_ty = *sig.output().skip_binder();
1805 // We expect the first argument to be a reference.
1806 match argument_ty.sty {
1807 ty::TyKind::Ref(_, _, _) => {}
1811 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1819 // This is case 3 from above, return type is not a reference so don't highlight
1828 enum AnnotatedBorrowFnSignature<'tcx> {
1830 arguments: Vec<(ty::Ty<'tcx>, Span)>,
1831 return_ty: ty::Ty<'tcx>,
1835 argument_ty: ty::Ty<'tcx>,
1836 argument_span: Span,
1837 return_ty: ty::Ty<'tcx>,
1841 argument_ty: ty::Ty<'tcx>,
1842 argument_span: Span,
1846 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
1847 /// Annotate the provided diagnostic with information about borrow from the fn signature that
1849 fn emit(&self, diag: &mut DiagnosticBuilder<'_>) -> String {
1851 AnnotatedBorrowFnSignature::Closure {
1857 format!("has type `{}`", self.get_name_for_ty(argument_ty, 0)),
1860 self.get_region_name_for_ty(argument_ty, 0)
1862 AnnotatedBorrowFnSignature::AnonymousFunction {
1868 let argument_ty_name = self.get_name_for_ty(argument_ty, 0);
1869 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
1871 let return_ty_name = self.get_name_for_ty(return_ty, 0);
1872 let types_equal = return_ty_name == argument_ty_name;
1877 if types_equal { "also " } else { "" },
1883 "argument and return type have the same lifetime due to lifetime elision rules",
1886 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch10-03-\
1887 lifetime-syntax.html#lifetime-elision>",
1890 self.get_region_name_for_ty(return_ty, 0)
1892 AnnotatedBorrowFnSignature::NamedFunction {
1897 // Region of return type and arguments checked to be the same earlier.
1898 let region_name = self.get_region_name_for_ty(return_ty, 0);
1899 for (_, argument_span) in arguments {
1900 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
1905 format!("also has lifetime `{}`", region_name,),
1909 "use data from the highlighted arguments which match the `{}` lifetime of \
1919 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
1920 /// name where required.
1921 fn get_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
1922 // We need to add synthesized lifetimes where appropriate. We do
1923 // this by hooking into the pretty printer and telling it to label the
1924 // lifetimes without names with the value `'0`.
1926 ty::TyKind::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
1928 ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }),
1931 ) => with_highlight_region_for_bound_region(*br, counter, || ty.to_string()),
1932 _ => ty.to_string(),
1936 /// Return the name of the provided `Ty` (that must be a reference)'s region with a
1937 /// synthesized lifetime name where required.
1938 fn get_region_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
1940 ty::TyKind::Ref(region, _, _) => match region {
1941 ty::RegionKind::ReLateBound(_, br)
1942 | ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1943 with_highlight_region_for_bound_region(*br, counter, || region.to_string())
1945 _ => region.to_string(),
1947 _ => bug!("ty for annotation of borrow region is not a reference"),
1952 // The span(s) associated to a use of a place.
1953 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1954 pub(super) enum UseSpans {
1955 // The access is caused by capturing a variable for a closure.
1957 // This is true if the captured variable was from a generator.
1959 // The span of the args of the closure, including the `move` keyword if
1962 // The span of the first use of the captured variable inside the closure.
1965 // This access has a single span associated to it: common case.
1970 pub(super) fn args_or_use(self) -> Span {
1972 UseSpans::ClosureUse {
1975 | UseSpans::OtherUse(span) => span,
1979 pub(super) fn var_or_use(self) -> Span {
1981 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
1985 // Add a span label to the arguments of the closure, if it exists.
1986 pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1987 if let UseSpans::ClosureUse { args_span, .. } = self {
1988 err.span_label(args_span, message);
1992 // Add a span label to the use of the captured variable, if it exists.
1993 pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1994 if let UseSpans::ClosureUse { var_span, .. } = self {
1995 err.span_label(var_span, message);
1999 /// Return `false` if this place is not used in a closure.
2000 fn for_closure(&self) -> bool {
2002 UseSpans::ClosureUse { is_generator, .. } => !is_generator,
2007 /// Return `false` if this place is not used in a generator.
2008 fn for_generator(&self) -> bool {
2010 UseSpans::ClosureUse { is_generator, .. } => is_generator,
2015 /// Describe the span associated with a use of a place.
2016 fn describe(&self) -> String {
2018 UseSpans::ClosureUse { is_generator, .. } => if is_generator {
2019 " in generator".to_string()
2021 " in closure".to_string()
2023 _ => "".to_string(),
2027 pub(super) fn or_else<F>(self, if_other: F) -> Self
2029 F: FnOnce() -> Self,
2032 closure @ UseSpans::ClosureUse { .. } => closure,
2033 UseSpans::OtherUse(_) => if_other(),
2038 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2039 /// Finds the spans associated to a move or copy of move_place at location.
2040 pub(super) fn move_spans(
2042 moved_place: &Place<'tcx>, // Could also be an upvar.
2045 use self::UseSpans::*;
2047 let stmt = match self.mir[location.block].statements.get(location.statement_index) {
2049 None => return OtherUse(self.mir.source_info(location).span),
2052 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
2053 if let StatementKind::Assign(
2055 box Rvalue::Aggregate(ref kind, ref places)
2057 let (def_id, is_generator) = match kind {
2058 box AggregateKind::Closure(def_id, _) => (def_id, false),
2059 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2060 _ => return OtherUse(stmt.source_info.span),
2064 "move_spans: def_id={:?} is_generator={:?} places={:?}",
2065 def_id, is_generator, places
2067 if let Some((args_span, var_span)) = self.closure_span(*def_id, moved_place, places) {
2076 OtherUse(stmt.source_info.span)
2079 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
2080 /// and its usage of the local assigned at `location`.
2081 /// This is done by searching in statements succeeding `location`
2082 /// and originating from `maybe_closure_span`.
2083 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
2084 use self::UseSpans::*;
2085 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
2087 let target = match self.mir[location.block]
2089 .get(location.statement_index)
2092 kind: StatementKind::Assign(Place::Local(local), _),
2095 _ => return OtherUse(use_span),
2098 if self.mir.local_kind(target) != LocalKind::Temp {
2099 // operands are always temporaries.
2100 return OtherUse(use_span);
2103 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
2104 if let StatementKind::Assign(
2105 _, box Rvalue::Aggregate(ref kind, ref places)
2107 let (def_id, is_generator) = match kind {
2108 box AggregateKind::Closure(def_id, _) => (def_id, false),
2109 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2114 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
2115 def_id, is_generator, places
2117 if let Some((args_span, var_span)) = self.closure_span(
2118 *def_id, &Place::Local(target), places
2126 return OtherUse(use_span);
2130 if use_span != stmt.source_info.span {
2138 /// Finds the span of a captured variable within a closure or generator.
2142 target_place: &Place<'tcx>,
2143 places: &Vec<Operand<'tcx>>,
2144 ) -> Option<(Span, Span)> {
2146 "closure_span: def_id={:?} target_place={:?} places={:?}",
2147 def_id, target_place, places
2149 let node_id = self.infcx.tcx.hir.as_local_node_id(def_id)?;
2150 let expr = &self.infcx.tcx.hir.expect_expr(node_id).node;
2151 debug!("closure_span: node_id={:?} expr={:?}", node_id, expr);
2152 if let hir::ExprKind::Closure(
2155 let var_span = self.infcx.tcx.with_freevars(
2158 for (v, place) in freevars.iter().zip(places) {
2160 Operand::Copy(place) |
2161 Operand::Move(place) if target_place == place => {
2162 debug!("closure_span: found captured local {:?}", place);
2163 return Some(v.span);
2173 Some((*args_span, var_span))
2179 /// Helper to retrieve span(s) of given borrow from the current MIR
2181 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans {
2182 let span = self.mir.source_info(borrow.reserve_location).span;
2183 self.borrow_spans(span, borrow.reserve_location)