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("_".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("_".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("_".to_owned()),
304 &self.describe_place(&borrow.borrowed_place)
305 .unwrap_or("_".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("_".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("_".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).unwrap_or("_".to_owned());
494 issued_spans.var_span_label(
497 "first borrow occurs due to use of `{}`{}",
499 issued_spans.describe(),
503 borrow_spans.var_span_label(
506 "second borrow occurs due to use of `{}`{}",
508 borrow_spans.describe(),
513 self.explain_why_borrow_contains_point(context, issued_borrow, None)
514 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, first_borrow_desc);
516 err.buffer(&mut self.errors_buffer);
519 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
521 /// This means that some data referenced by `borrow` needs to live
522 /// past the point where the StorageDeadOrDrop of `place` occurs.
523 /// This is usually interpreted as meaning that `place` has too
524 /// short a lifetime. (But sometimes it is more useful to report
525 /// it as a more direct conflict between the execution of a
526 /// `Drop::drop` with an aliasing borrow.)
527 pub(super) fn report_borrowed_value_does_not_live_long_enough(
530 borrow: &BorrowData<'tcx>,
531 place_span: (&Place<'tcx>, Span),
532 kind: Option<WriteKind>,
535 "report_borrowed_value_does_not_live_long_enough(\
536 {:?}, {:?}, {:?}, {:?}\
538 context, borrow, place_span, kind
541 let drop_span = place_span.1;
542 let scope_tree = self.infcx.tcx.region_scope_tree(self.mir_def_id);
543 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
547 let borrow_spans = self.retrieve_borrow_spans(borrow);
548 let borrow_span = borrow_spans.var_or_use();
550 let proper_span = match *root_place {
551 Place::Local(local) => self.mir.local_decls[local].source_info.span,
555 if self.access_place_error_reported
556 .contains(&(root_place.clone(), borrow_span))
559 "suppressing access_place error when borrow doesn't live long enough for {:?}",
565 self.access_place_error_reported
566 .insert((root_place.clone(), borrow_span));
568 if let StorageDeadOrDrop::Destructor(dropped_ty) =
569 self.classify_drop_access_kind(&borrow.borrowed_place)
571 // If a borrow of path `B` conflicts with drop of `D` (and
572 // we're not in the uninteresting case where `B` is a
573 // prefix of `D`), then report this as a more interesting
574 // destructor conflict.
575 if !borrow.borrowed_place.is_prefix_of(place_span.0) {
576 self.report_borrow_conflicts_with_destructor(
577 context, borrow, place_span, kind, dropped_ty,
583 let err = match &self.describe_place(&borrow.borrowed_place) {
584 Some(_) if self.is_place_thread_local(root_place) => {
585 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
587 Some(name) => self.report_local_value_does_not_live_long_enough(
594 kind.map(|k| (k, place_span.0)),
596 None => self.report_temporary_value_does_not_live_long_enough(
606 err.buffer(&mut self.errors_buffer);
609 fn report_local_value_does_not_live_long_enough(
613 scope_tree: &Lrc<ScopeTree>,
614 borrow: &BorrowData<'tcx>,
616 borrow_spans: UseSpans,
617 kind_place: Option<(WriteKind, &Place<'tcx>)>,
618 ) -> DiagnosticBuilder<'cx> {
620 "report_local_value_does_not_live_long_enough(\
621 {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
623 context, name, scope_tree, borrow, drop_span, borrow_spans
626 let borrow_span = borrow_spans.var_or_use();
627 let mut err = self.infcx.tcx.path_does_not_live_long_enough(
629 &format!("`{}`", name),
633 let explanation = self.explain_why_borrow_contains_point(context, borrow, kind_place);
634 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
635 let region_name = annotation.emit(&mut err);
639 format!("`{}` would have to be valid for `{}`...", name, region_name),
642 if let Some(fn_node_id) = self.infcx.tcx.hir.as_local_node_id(self.mir_def_id) {
646 "...but `{}` will be dropped here, when the function `{}` returns",
648 self.infcx.tcx.hir.name(fn_node_id),
653 "functions cannot return a borrow to data owned within the function's scope, \
654 functions can only return borrows to data passed as arguments",
657 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch04-02-\
658 references-and-borrowing.html#dangling-references>",
663 format!("...but `{}` dropped here while still borrowed", name),
667 if let BorrowExplanation::MustBeValidFor(..) = explanation {
669 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
672 err.span_label(borrow_span, "borrowed value does not live long enough");
675 format!("`{}` dropped here while still borrowed", name),
678 let within = if borrow_spans.for_generator() {
684 borrow_spans.args_span_label(
686 format!("value captured here{}", within),
689 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
695 pub(super) fn report_borrow_conflicts_with_destructor(
698 borrow: &BorrowData<'tcx>,
699 (place, drop_span): (&Place<'tcx>, Span),
700 kind: Option<WriteKind>,
701 dropped_ty: ty::Ty<'tcx>,
704 "report_borrow_conflicts_with_destructor(\
705 {:?}, {:?}, ({:?}, {:?}), {:?}\
707 context, borrow, place, drop_span, kind,
710 let borrow_spans = self.retrieve_borrow_spans(borrow);
711 let borrow_span = borrow_spans.var_or_use();
713 let mut err = self.infcx
715 .cannot_borrow_across_destructor(borrow_span, Origin::Mir);
717 let what_was_dropped = match self.describe_place(place) {
718 Some(name) => format!("`{}`", name.as_str()),
719 None => format!("temporary value"),
722 let label = match self.describe_place(&borrow.borrowed_place) {
723 Some(borrowed) => format!(
724 "here, drop of {D} needs exclusive access to `{B}`, \
725 because the type `{T}` implements the `Drop` trait",
726 D = what_was_dropped,
731 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
732 D = what_was_dropped,
736 err.span_label(drop_span, label);
738 // Only give this note and suggestion if they could be relevant.
740 self.explain_why_borrow_contains_point(context, borrow, kind.map(|k| (k, place)));
742 BorrowExplanation::UsedLater { .. }
743 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
744 err.note("consider using a `let` binding to create a longer lived value");
749 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
751 err.buffer(&mut self.errors_buffer);
754 fn report_thread_local_value_does_not_live_long_enough(
758 ) -> DiagnosticBuilder<'cx> {
760 "report_thread_local_value_does_not_live_long_enough(\
763 drop_span, borrow_span
766 let mut err = self.infcx
768 .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
772 "thread-local variables cannot be borrowed beyond the end of the function",
774 err.span_label(drop_span, "end of enclosing function is here");
779 fn report_temporary_value_does_not_live_long_enough(
782 scope_tree: &Lrc<ScopeTree>,
783 borrow: &BorrowData<'tcx>,
785 borrow_spans: UseSpans,
787 ) -> DiagnosticBuilder<'cx> {
789 "report_temporary_value_does_not_live_long_enough(\
790 {:?}, {:?}, {:?}, {:?}, {:?}\
792 context, scope_tree, borrow, drop_span, proper_span
795 let tcx = self.infcx.tcx;
796 let mut err = tcx.temporary_value_borrowed_for_too_long(proper_span, Origin::Mir);
799 "creates a temporary which is freed while still in use",
803 "temporary value is freed at the end of this statement",
806 let explanation = self.explain_why_borrow_contains_point(context, borrow, None);
808 BorrowExplanation::UsedLater(..)
809 | BorrowExplanation::UsedLaterInLoop(..)
810 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
811 // Only give this note and suggestion if it could be relevant.
812 err.note("consider using a `let` binding to create a longer lived value");
816 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
818 let within = if borrow_spans.for_generator() {
824 borrow_spans.args_span_label(
826 format!("value captured here{}", within),
832 fn get_moved_indexes(&mut self, context: Context, mpi: MovePathIndex) -> Vec<MoveSite> {
835 let mut stack = Vec::new();
836 stack.extend(mir.predecessor_locations(context.loc).map(|predecessor| {
837 let is_back_edge = context.loc.dominates(predecessor, &self.dominators);
838 (predecessor, is_back_edge)
841 let mut visited = FxHashSet();
842 let mut result = vec![];
844 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
846 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
847 location, is_back_edge
850 if !visited.insert(location) {
855 let stmt_kind = mir[location.block]
857 .get(location.statement_index)
859 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
860 // this analysis only tries to find moves explicitly
861 // written by the user, so we ignore the move-outs
862 // created by `StorageDead` and at the beginning
865 // If we are found a use of a.b.c which was in error, then we want to look for
866 // moves not only of a.b.c but also a.b and a.
868 // Note that the moves data already includes "parent" paths, so we don't have to
869 // worry about the other case: that is, if there is a move of a.b.c, it is already
870 // marked as a move of a.b and a as well, so we will generate the correct errors
872 let mut mpis = vec![mpi];
873 let move_paths = &self.move_data.move_paths;
874 mpis.extend(move_paths[mpi].parents(move_paths));
876 for moi in &self.move_data.loc_map[location] {
877 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
878 if mpis.contains(&self.move_data.moves[*moi].path) {
879 debug!("report_use_of_moved_or_uninitialized: found");
880 result.push(MoveSite {
882 traversed_back_edge: is_back_edge,
885 // Strictly speaking, we could continue our DFS here. There may be
886 // other moves that can reach the point of error. But it is kind of
887 // confusing to highlight them.
895 // drop(a); // <-- current point of error
898 // Because we stop the DFS here, we only highlight `let c = a`,
899 // and not `let b = a`. We will of course also report an error at
900 // `let c = a` which highlights `let b = a` as the move.
907 let mut any_match = false;
908 drop_flag_effects::for_location_inits(
923 stack.extend(mir.predecessor_locations(location).map(|predecessor| {
924 let back_edge = location.dominates(predecessor, &self.dominators);
925 (predecessor, is_back_edge || back_edge)
932 pub(super) fn report_illegal_mutation_of_borrowed(
935 (place, span): (&Place<'tcx>, Span),
936 loan: &BorrowData<'tcx>,
938 let loan_spans = self.retrieve_borrow_spans(loan);
939 let loan_span = loan_spans.args_or_use();
941 let tcx = self.infcx.tcx;
942 let mut err = if loan.kind == BorrowKind::Shallow {
943 tcx.cannot_mutate_in_match_guard(
946 &self.describe_place(place).unwrap_or("_".to_owned()),
951 tcx.cannot_assign_to_borrowed(
954 &self.describe_place(place).unwrap_or("_".to_owned()),
959 loan_spans.var_span_label(
961 format!("borrow occurs due to use{}", loan_spans.describe()),
964 self.explain_why_borrow_contains_point(context, loan, None)
965 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
967 err.buffer(&mut self.errors_buffer);
970 /// Reports an illegal reassignment; for example, an assignment to
971 /// (part of) a non-`mut` local that occurs potentially after that
972 /// local has already been initialized. `place` is the path being
973 /// assigned; `err_place` is a place providing a reason why
974 /// `place` is not mutable (e.g. the non-`mut` local `x` in an
975 /// assignment to `x.f`).
976 pub(super) fn report_illegal_reassignment(
979 (place, span): (&Place<'tcx>, Span),
981 err_place: &Place<'tcx>,
983 let (from_arg, local_decl) = if let Place::Local(local) = *err_place {
984 if let LocalKind::Arg = self.mir.local_kind(local) {
985 (true, Some(&self.mir.local_decls[local]))
987 (false, Some(&self.mir.local_decls[local]))
993 // If root local is initialized immediately (everything apart from let
994 // PATTERN;) then make the error refer to that local, rather than the
995 // place being assigned later.
996 let (place_description, assigned_span) = match local_decl {
998 is_user_variable: Some(ClearCrossCrate::Clear),
1003 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1004 opt_match_place: None,
1010 is_user_variable: None,
1013 | None => (self.describe_place(place), assigned_span),
1014 Some(decl) => (self.describe_place(err_place), decl.source_info.span),
1017 let mut err = self.infcx.tcx.cannot_reassign_immutable(
1019 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
1023 let msg = if from_arg {
1024 "cannot assign to immutable argument"
1026 "cannot assign twice to immutable variable"
1028 if span != assigned_span {
1030 let value_msg = match place_description {
1031 Some(name) => format!("`{}`", name),
1032 None => "value".to_owned(),
1034 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
1037 if let Some(decl) = local_decl {
1038 if let Some(name) = decl.name {
1039 if decl.can_be_made_mutable() {
1040 err.span_suggestion_with_applicability(
1041 decl.source_info.span,
1042 "make this binding mutable",
1043 format!("mut {}", name),
1044 Applicability::MachineApplicable,
1049 err.span_label(span, msg);
1050 err.buffer(&mut self.errors_buffer);
1054 pub(super) struct IncludingDowncast(bool);
1056 /// Which case a StorageDeadOrDrop is for.
1057 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1058 enum StorageDeadOrDrop<'tcx> {
1061 Destructor(ty::Ty<'tcx>),
1064 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1066 /// Adds a suggestion when a closure is invoked twice with a moved variable.
1069 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
1071 /// --> $DIR/issue-42065.rs:16:29
1073 /// LL | for (key, value) in dict {
1076 pub(super) fn add_closure_invoked_twice_with_moved_variable_suggestion(
1079 place: &Place<'tcx>,
1080 diag: &mut DiagnosticBuilder<'_>,
1082 let mut target = place.local();
1084 "add_closure_invoked_twice_with_moved_variable_suggestion: location={:?} place={:?} \
1086 location, place, target,
1088 for stmt in &self.mir[location.block].statements[location.statement_index..] {
1090 "add_closure_invoked_twice_with_moved_variable_suggestion: stmt={:?} \
1094 if let StatementKind::Assign(into, box Rvalue::Use(from)) = &stmt.kind {
1096 "add_closure_invoked_twice_with_moved_variable_suggestion: into={:?} \
1101 Operand::Copy(ref place) |
1102 Operand::Move(ref place) if target == place.local() =>
1103 target = into.local(),
1110 let terminator = self.mir[location.block].terminator();
1112 "add_closure_invoked_twice_with_moved_variable_suggestion: terminator={:?}",
1115 if let TerminatorKind::Call {
1116 func: Operand::Constant(box Constant {
1117 literal: ty::Const { ty: &ty::TyS { sty: ty::TyKind::FnDef(id, _), .. }, .. },
1122 } = &terminator.kind {
1123 debug!("add_closure_invoked_twice_with_moved_variable_suggestion: id={:?}", id);
1124 if self.infcx.tcx.parent(id) == self.infcx.tcx.lang_items().fn_once_trait() {
1125 let closure = match args.first() {
1126 Some(Operand::Copy(ref place)) |
1127 Some(Operand::Move(ref place)) if target == place.local() =>
1128 place.local().unwrap(),
1132 "add_closure_invoked_twice_with_moved_variable_suggestion: closure={:?}",
1136 if let ty::TyKind::Closure(did, _substs) = self.mir.local_decls[closure].ty.sty {
1137 let node_id = match self.infcx.tcx.hir.as_local_node_id(did) {
1138 Some(node_id) => node_id,
1141 let hir_id = self.infcx.tcx.hir.node_to_hir_id(node_id);
1145 )) = self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id) {
1149 "closure cannot be invoked more than once because it \
1150 moves the variable `{}` out of its environment",
1160 /// End-user visible description of `place` if one can be found. If the
1161 /// place is a temporary for instance, None will be returned.
1162 pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
1163 self.describe_place_with_options(place, IncludingDowncast(false))
1166 /// End-user visible description of `place` if one can be found. If the
1167 /// place is a temporary for instance, None will be returned.
1168 /// `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
1169 /// `Downcast` and `IncludingDowncast` is true
1170 pub(super) fn describe_place_with_options(
1172 place: &Place<'tcx>,
1173 including_downcast: IncludingDowncast,
1174 ) -> Option<String> {
1175 let mut buf = String::new();
1176 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
1177 Ok(()) => Some(buf),
1182 /// Appends end-user visible description of `place` to `buf`.
1183 fn append_place_to_string(
1185 place: &Place<'tcx>,
1187 mut autoderef: bool,
1188 including_downcast: &IncludingDowncast,
1189 ) -> Result<(), ()> {
1191 Place::Promoted(_) => {
1192 buf.push_str("promoted");
1194 Place::Local(local) => {
1195 self.append_local_to_string(local, buf)?;
1197 Place::Static(ref static_) => {
1198 buf.push_str(&self.infcx.tcx.item_name(static_.def_id).to_string());
1200 Place::Projection(ref proj) => {
1202 ProjectionElem::Deref => {
1203 let upvar_field_projection =
1204 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1205 if let Some(field) = upvar_field_projection {
1206 let var_index = field.index();
1207 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1208 if self.mir.upvar_decls[var_index].by_ref {
1209 buf.push_str(&name);
1211 buf.push_str(&format!("*{}", &name));
1215 self.append_place_to_string(
1219 &including_downcast,
1221 } else if let Place::Local(local) = proj.base {
1222 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
1223 self.mir.local_decls[local].is_user_variable
1225 self.append_place_to_string(
1229 &including_downcast,
1233 self.append_place_to_string(
1237 &including_downcast,
1242 self.append_place_to_string(
1246 &including_downcast,
1251 ProjectionElem::Downcast(..) => {
1252 self.append_place_to_string(
1256 &including_downcast,
1258 if including_downcast.0 {
1262 ProjectionElem::Field(field, _ty) => {
1265 let upvar_field_projection =
1266 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1267 if let Some(field) = upvar_field_projection {
1268 let var_index = field.index();
1269 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1270 buf.push_str(&name);
1272 let field_name = self.describe_field(&proj.base, field);
1273 self.append_place_to_string(
1277 &including_downcast,
1279 buf.push_str(&format!(".{}", field_name));
1282 ProjectionElem::Index(index) => {
1285 self.append_place_to_string(
1289 &including_downcast,
1292 if self.append_local_to_string(index, buf).is_err() {
1297 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1299 // Since it isn't possible to borrow an element on a particular index and
1300 // then use another while the borrow is held, don't output indices details
1301 // to avoid confusing the end-user
1302 self.append_place_to_string(
1306 &including_downcast,
1308 buf.push_str(&"[..]");
1317 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
1318 /// a name, then `Err` is returned
1319 fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
1320 let local = &self.mir.local_decls[local_index];
1323 buf.push_str(&name.to_string());
1330 /// End-user visible description of the `field`nth field of `base`
1331 fn describe_field(&self, base: &Place, field: Field) -> String {
1333 Place::Local(local) => {
1334 let local = &self.mir.local_decls[local];
1335 self.describe_field_from_ty(&local.ty, field)
1337 Place::Promoted(ref prom) => self.describe_field_from_ty(&prom.1, field),
1338 Place::Static(ref static_) => self.describe_field_from_ty(&static_.ty, field),
1339 Place::Projection(ref proj) => match proj.elem {
1340 ProjectionElem::Deref => self.describe_field(&proj.base, field),
1341 ProjectionElem::Downcast(def, variant_index) =>
1342 def.variants[variant_index].fields[field.index()].ident.to_string(),
1343 ProjectionElem::Field(_, field_type) => {
1344 self.describe_field_from_ty(&field_type, field)
1346 ProjectionElem::Index(..)
1347 | ProjectionElem::ConstantIndex { .. }
1348 | ProjectionElem::Subslice { .. } => {
1349 self.describe_field(&proj.base, field).to_string()
1355 /// End-user visible description of the `field_index`nth field of `ty`
1356 fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String {
1358 // If the type is a box, the field is described from the boxed type
1359 self.describe_field_from_ty(&ty.boxed_ty(), field)
1362 ty::Adt(def, _) => if def.is_enum() {
1363 field.index().to_string()
1365 def.non_enum_variant().fields[field.index()]
1369 ty::Tuple(_) => field.index().to_string(),
1370 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
1371 self.describe_field_from_ty(&ty, field)
1373 ty::Array(ty, _) | ty::Slice(ty) => self.describe_field_from_ty(&ty, field),
1374 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
1375 // Convert the def-id into a node-id. node-ids are only valid for
1376 // the local code in the current crate, so this returns an `Option` in case
1377 // the closure comes from another crate. But in that case we wouldn't
1378 // be borrowck'ing it, so we can just unwrap:
1379 let node_id = self.infcx.tcx.hir.as_local_node_id(def_id).unwrap();
1380 let freevar = self.infcx
1382 .with_freevars(node_id, |fv| fv[field.index()]);
1384 self.infcx.tcx.hir.name(freevar.var_id()).to_string()
1387 // Might need a revision when the fields in trait RFC is implemented
1388 // (https://github.com/rust-lang/rfcs/pull/1546)
1390 "End-user description not implemented for field access on `{:?}`",
1398 /// Retrieve type of a place for the current MIR representation
1399 fn retrieve_type_for_place(&self, place: &Place<'tcx>) -> Option<ty::Ty> {
1401 Place::Local(local) => {
1402 let local = &self.mir.local_decls[*local];
1405 Place::Promoted(ref prom) => Some(prom.1),
1406 Place::Static(ref st) => Some(st.ty),
1407 Place::Projection(ref proj) => match proj.elem {
1408 ProjectionElem::Field(_, ty) => Some(ty),
1414 /// Check if a place is a thread-local static.
1415 pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
1416 if let Place::Static(statik) = place {
1417 let attrs = self.infcx.tcx.get_attrs(statik.def_id);
1418 let is_thread_local = attrs.iter().any(|attr| attr.check_name("thread_local"));
1421 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
1422 attrs, is_thread_local
1426 debug!("is_place_thread_local: no");
1431 fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
1432 let tcx = self.infcx.tcx;
1434 Place::Local(_) | Place::Static(_) | Place::Promoted(_) => {
1435 StorageDeadOrDrop::LocalStorageDead
1437 Place::Projection(box PlaceProjection { base, elem }) => {
1438 let base_access = self.classify_drop_access_kind(base);
1440 ProjectionElem::Deref => match base_access {
1441 StorageDeadOrDrop::LocalStorageDead
1442 | StorageDeadOrDrop::BoxedStorageDead => {
1444 base.ty(self.mir, tcx).to_ty(tcx).is_box(),
1445 "Drop of value behind a reference or raw pointer"
1447 StorageDeadOrDrop::BoxedStorageDead
1449 StorageDeadOrDrop::Destructor(_) => base_access,
1451 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1452 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1454 ty::Adt(def, _) if def.has_dtor(tcx) => {
1455 // Report the outermost adt with a destructor
1457 StorageDeadOrDrop::Destructor(_) => base_access,
1458 StorageDeadOrDrop::LocalStorageDead
1459 | StorageDeadOrDrop::BoxedStorageDead => {
1460 StorageDeadOrDrop::Destructor(base_ty)
1468 ProjectionElem::ConstantIndex { .. }
1469 | ProjectionElem::Subslice { .. }
1470 | ProjectionElem::Index(_) => base_access,
1476 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1477 /// borrow of local value that does not live long enough.
1478 fn annotate_argument_and_return_for_borrow(
1480 borrow: &BorrowData<'tcx>,
1481 ) -> Option<AnnotatedBorrowFnSignature> {
1482 // Define a fallback for when we can't match a closure.
1484 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1488 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1490 ty::TyKind::FnDef(_, _) | ty::TyKind::FnPtr(_) => self.annotate_fn_sig(
1492 self.infcx.tcx.fn_sig(self.mir_def_id),
1499 // In order to determine whether we need to annotate, we need to check whether the reserve
1500 // place was an assignment into a temporary.
1502 // If it was, we check whether or not that temporary is eventually assigned into the return
1503 // place. If it was, we can add annotations about the function's return type and arguments
1504 // and it'll make sense.
1505 let location = borrow.reserve_location;
1507 "annotate_argument_and_return_for_borrow: location={:?}",
1510 if let Some(&Statement { kind: StatementKind::Assign(ref reservation, _), ..})
1511 = &self.mir[location.block].statements.get(location.statement_index)
1514 "annotate_argument_and_return_for_borrow: reservation={:?}",
1517 // Check that the initial assignment of the reserve location is into a temporary.
1518 let mut target = *match reservation {
1519 Place::Local(local) if self.mir.local_kind(*local) == LocalKind::Temp => local,
1523 // Next, look through the rest of the block, checking if we are assigning the
1524 // `target` (that is, the place that contains our borrow) to anything.
1525 let mut annotated_closure = None;
1526 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1528 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1531 if let StatementKind::Assign(Place::Local(assigned_to), box rvalue) = &stmt.kind
1534 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1538 // Check if our `target` was captured by a closure.
1539 if let Rvalue::Aggregate(
1540 box AggregateKind::Closure(def_id, substs),
1544 for operand in operands {
1545 let assigned_from = match operand {
1546 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1552 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1556 // Find the local from the operand.
1557 let assigned_from_local = match assigned_from.local() {
1558 Some(local) => local,
1562 if assigned_from_local != target {
1566 // If a closure captured our `target` and then assigned
1567 // into a place then we should annotate the closure in
1568 // case it ends up being assigned into the return place.
1569 annotated_closure = self.annotate_fn_sig(
1571 self.infcx.closure_sig(*def_id, *substs),
1574 "annotate_argument_and_return_for_borrow: \
1575 annotated_closure={:?} assigned_from_local={:?} \
1577 annotated_closure, assigned_from_local, assigned_to
1580 if *assigned_to == mir::RETURN_PLACE {
1581 // If it was assigned directly into the return place, then
1583 return annotated_closure;
1585 // Otherwise, update the target.
1586 target = *assigned_to;
1590 // If none of our closure's operands matched, then skip to the next
1595 // Otherwise, look at other types of assignment.
1596 let assigned_from = match rvalue {
1597 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1598 Rvalue::Use(operand) => match operand {
1599 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1607 "annotate_argument_and_return_for_borrow: \
1608 assigned_from={:?}",
1612 // Find the local from the rvalue.
1613 let assigned_from_local = match assigned_from.local() {
1614 Some(local) => local,
1618 "annotate_argument_and_return_for_borrow: \
1619 assigned_from_local={:?}",
1620 assigned_from_local,
1623 // Check if our local matches the target - if so, we've assigned our
1624 // borrow to a new place.
1625 if assigned_from_local != target {
1629 // If we assigned our `target` into a new place, then we should
1630 // check if it was the return place.
1632 "annotate_argument_and_return_for_borrow: \
1633 assigned_from_local={:?} assigned_to={:?}",
1634 assigned_from_local, assigned_to
1636 if *assigned_to == mir::RETURN_PLACE {
1637 // If it was then return the annotated closure if there was one,
1638 // else, annotate this function.
1639 return annotated_closure.or_else(fallback);
1642 // If we didn't assign into the return place, then we just update
1644 target = *assigned_to;
1648 // Check the terminator if we didn't find anything in the statements.
1649 let terminator = &self.mir[location.block].terminator();
1651 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1654 if let TerminatorKind::Call {
1655 destination: Some((Place::Local(assigned_to), _)),
1658 } = &terminator.kind
1661 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1664 for operand in args {
1665 let assigned_from = match operand {
1666 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1672 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1676 if let Some(assigned_from_local) = assigned_from.local() {
1678 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1679 assigned_from_local,
1682 if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1683 return annotated_closure.or_else(fallback);
1690 // If we haven't found an assignment into the return place, then we need not add
1692 debug!("annotate_argument_and_return_for_borrow: none found");
1696 /// Annotate the first argument and return type of a function signature if they are
1701 sig: ty::PolyFnSig<'tcx>,
1702 ) -> Option<AnnotatedBorrowFnSignature> {
1703 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1704 let is_closure = self.infcx.tcx.is_closure(did);
1705 let fn_node_id = self.infcx.tcx.hir.as_local_node_id(did)?;
1706 let fn_decl = self.infcx.tcx.hir.fn_decl(fn_node_id)?;
1708 // We need to work out which arguments to highlight. We do this by looking
1709 // at the return type, where there are three cases:
1711 // 1. If there are named arguments, then we should highlight the return type and
1712 // highlight any of the arguments that are also references with that lifetime.
1713 // If there are no arguments that have the same lifetime as the return type,
1714 // then don't highlight anything.
1715 // 2. The return type is a reference with an anonymous lifetime. If this is
1716 // the case, then we can take advantage of (and teach) the lifetime elision
1719 // We know that an error is being reported. So the arguments and return type
1720 // must satisfy the elision rules. Therefore, if there is a single argument
1721 // then that means the return type and first (and only) argument have the same
1722 // lifetime and the borrow isn't meeting that, we can highlight the argument
1725 // If there are multiple arguments then the first argument must be self (else
1726 // it would not satisfy the elision rules), so we can highlight self and the
1728 // 3. The return type is not a reference. In this case, we don't highlight
1730 let return_ty = sig.output();
1731 match return_ty.skip_binder().sty {
1732 ty::TyKind::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1733 // This is case 1 from above, return type is a named reference so we need to
1734 // search for relevant arguments.
1735 let mut arguments = Vec::new();
1736 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1737 if let ty::TyKind::Ref(argument_region, _, _) = argument.sty {
1738 if argument_region == return_region {
1739 // Need to use the `rustc::ty` types to compare against the
1740 // `return_region`. Then use the `rustc::hir` type to get only
1741 // the lifetime span.
1742 if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].node {
1743 // With access to the lifetime, we can get
1745 arguments.push((*argument, lifetime.span));
1747 bug!("ty type is a ref but hir type is not");
1753 // We need to have arguments. This shouldn't happen, but it's worth checking.
1754 if arguments.is_empty() {
1758 // We use a mix of the HIR and the Ty types to get information
1759 // as the HIR doesn't have full types for closure arguments.
1760 let return_ty = *sig.output().skip_binder();
1761 let mut return_span = fn_decl.output.span();
1762 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
1763 if let hir::TyKind::Rptr(lifetime, _) = ty.into_inner().node {
1764 return_span = lifetime.span;
1768 Some(AnnotatedBorrowFnSignature::NamedFunction {
1774 ty::TyKind::Ref(_, _, _) if is_closure => {
1775 // This is case 2 from above but only for closures, return type is anonymous
1776 // reference so we select
1777 // the first argument.
1778 let argument_span = fn_decl.inputs.first()?.span;
1779 let argument_ty = sig.inputs().skip_binder().first()?;
1781 // Closure arguments are wrapped in a tuple, so we need to get the first
1783 if let ty::TyKind::Tuple(elems) = argument_ty.sty {
1784 let argument_ty = elems.first()?;
1785 if let ty::TyKind::Ref(_, _, _) = argument_ty.sty {
1786 return Some(AnnotatedBorrowFnSignature::Closure {
1795 ty::TyKind::Ref(_, _, _) => {
1796 // This is also case 2 from above but for functions, return type is still an
1797 // anonymous reference so we select the first argument.
1798 let argument_span = fn_decl.inputs.first()?.span;
1799 let argument_ty = sig.inputs().skip_binder().first()?;
1801 let return_span = fn_decl.output.span();
1802 let return_ty = *sig.output().skip_binder();
1804 // We expect the first argument to be a reference.
1805 match argument_ty.sty {
1806 ty::TyKind::Ref(_, _, _) => {}
1810 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1818 // This is case 3 from above, return type is not a reference so don't highlight
1827 enum AnnotatedBorrowFnSignature<'tcx> {
1829 arguments: Vec<(ty::Ty<'tcx>, Span)>,
1830 return_ty: ty::Ty<'tcx>,
1834 argument_ty: ty::Ty<'tcx>,
1835 argument_span: Span,
1836 return_ty: ty::Ty<'tcx>,
1840 argument_ty: ty::Ty<'tcx>,
1841 argument_span: Span,
1845 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
1846 /// Annotate the provided diagnostic with information about borrow from the fn signature that
1848 fn emit(&self, diag: &mut DiagnosticBuilder<'_>) -> String {
1850 AnnotatedBorrowFnSignature::Closure {
1856 format!("has type `{}`", self.get_name_for_ty(argument_ty, 0)),
1859 self.get_region_name_for_ty(argument_ty, 0)
1861 AnnotatedBorrowFnSignature::AnonymousFunction {
1867 let argument_ty_name = self.get_name_for_ty(argument_ty, 0);
1868 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
1870 let return_ty_name = self.get_name_for_ty(return_ty, 0);
1871 let types_equal = return_ty_name == argument_ty_name;
1876 if types_equal { "also " } else { "" },
1882 "argument and return type have the same lifetime due to lifetime elision rules",
1885 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch10-03-\
1886 lifetime-syntax.html#lifetime-elision>",
1889 self.get_region_name_for_ty(return_ty, 0)
1891 AnnotatedBorrowFnSignature::NamedFunction {
1896 // Region of return type and arguments checked to be the same earlier.
1897 let region_name = self.get_region_name_for_ty(return_ty, 0);
1898 for (_, argument_span) in arguments {
1899 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
1904 format!("also has lifetime `{}`", region_name,),
1908 "use data from the highlighted arguments which match the `{}` lifetime of \
1918 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
1919 /// name where required.
1920 fn get_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
1921 // We need to add synthesized lifetimes where appropriate. We do
1922 // this by hooking into the pretty printer and telling it to label the
1923 // lifetimes without names with the value `'0`.
1925 ty::TyKind::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
1927 ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }),
1930 ) => with_highlight_region_for_bound_region(*br, counter, || ty.to_string()),
1931 _ => ty.to_string(),
1935 /// Return the name of the provided `Ty` (that must be a reference)'s region with a
1936 /// synthesized lifetime name where required.
1937 fn get_region_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
1939 ty::TyKind::Ref(region, _, _) => match region {
1940 ty::RegionKind::ReLateBound(_, br)
1941 | ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1942 with_highlight_region_for_bound_region(*br, counter, || region.to_string())
1944 _ => region.to_string(),
1946 _ => bug!("ty for annotation of borrow region is not a reference"),
1951 // The span(s) associated to a use of a place.
1952 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1953 pub(super) enum UseSpans {
1954 // The access is caused by capturing a variable for a closure.
1956 // This is true if the captured variable was from a generator.
1958 // The span of the args of the closure, including the `move` keyword if
1961 // The span of the first use of the captured variable inside the closure.
1964 // This access has a single span associated to it: common case.
1969 pub(super) fn args_or_use(self) -> Span {
1971 UseSpans::ClosureUse {
1974 | UseSpans::OtherUse(span) => span,
1978 pub(super) fn var_or_use(self) -> Span {
1980 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
1984 // Add a span label to the arguments of the closure, if it exists.
1985 pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1986 if let UseSpans::ClosureUse { args_span, .. } = self {
1987 err.span_label(args_span, message);
1991 // Add a span label to the use of the captured variable, if it exists.
1992 pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1993 if let UseSpans::ClosureUse { var_span, .. } = self {
1994 err.span_label(var_span, message);
1998 /// Return `false` if this place is not used in a closure.
1999 fn for_closure(&self) -> bool {
2001 UseSpans::ClosureUse { is_generator, .. } => !is_generator,
2006 /// Return `false` if this place is not used in a generator.
2007 fn for_generator(&self) -> bool {
2009 UseSpans::ClosureUse { is_generator, .. } => is_generator,
2014 /// Describe the span associated with a use of a place.
2015 fn describe(&self) -> String {
2017 UseSpans::ClosureUse { is_generator, .. } => if is_generator {
2018 " in generator".to_string()
2020 " in closure".to_string()
2022 _ => "".to_string(),
2026 pub(super) fn or_else<F>(self, if_other: F) -> Self
2028 F: FnOnce() -> Self,
2031 closure @ UseSpans::ClosureUse { .. } => closure,
2032 UseSpans::OtherUse(_) => if_other(),
2037 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2038 /// Finds the spans associated to a move or copy of move_place at location.
2039 pub(super) fn move_spans(
2041 moved_place: &Place<'tcx>, // Could also be an upvar.
2044 use self::UseSpans::*;
2046 let stmt = match self.mir[location.block].statements.get(location.statement_index) {
2048 None => return OtherUse(self.mir.source_info(location).span),
2051 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
2052 if let StatementKind::Assign(
2054 box Rvalue::Aggregate(ref kind, ref places)
2056 let (def_id, is_generator) = match kind {
2057 box AggregateKind::Closure(def_id, _) => (def_id, false),
2058 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2059 _ => return OtherUse(stmt.source_info.span),
2063 "move_spans: def_id={:?} is_generator={:?} places={:?}",
2064 def_id, is_generator, places
2066 if let Some((args_span, var_span)) = self.closure_span(*def_id, moved_place, places) {
2075 OtherUse(stmt.source_info.span)
2078 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
2079 /// and its usage of the local assigned at `location`.
2080 /// This is done by searching in statements succeeding `location`
2081 /// and originating from `maybe_closure_span`.
2082 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
2083 use self::UseSpans::*;
2084 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
2086 let target = match self.mir[location.block]
2088 .get(location.statement_index)
2091 kind: StatementKind::Assign(Place::Local(local), _),
2094 _ => return OtherUse(use_span),
2097 if self.mir.local_kind(target) != LocalKind::Temp {
2098 // operands are always temporaries.
2099 return OtherUse(use_span);
2102 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
2103 if let StatementKind::Assign(
2104 _, box Rvalue::Aggregate(ref kind, ref places)
2106 let (def_id, is_generator) = match kind {
2107 box AggregateKind::Closure(def_id, _) => (def_id, false),
2108 box AggregateKind::Generator(def_id, _, _) => (def_id, true),
2113 "borrow_spans: def_id={:?} is_generator={:?} places={:?}",
2114 def_id, is_generator, places
2116 if let Some((args_span, var_span)) = self.closure_span(
2117 *def_id, &Place::Local(target), places
2125 return OtherUse(use_span);
2129 if use_span != stmt.source_info.span {
2137 /// Finds the span of a captured variable within a closure or generator.
2141 target_place: &Place<'tcx>,
2142 places: &Vec<Operand<'tcx>>,
2143 ) -> Option<(Span, Span)> {
2145 "closure_span: def_id={:?} target_place={:?} places={:?}",
2146 def_id, target_place, places
2148 let node_id = self.infcx.tcx.hir.as_local_node_id(def_id)?;
2149 let expr = &self.infcx.tcx.hir.expect_expr(node_id).node;
2150 debug!("closure_span: node_id={:?} expr={:?}", node_id, expr);
2151 if let hir::ExprKind::Closure(
2154 let var_span = self.infcx.tcx.with_freevars(
2157 for (v, place) in freevars.iter().zip(places) {
2159 Operand::Copy(place) |
2160 Operand::Move(place) if target_place == place => {
2161 debug!("closure_span: found captured local {:?}", place);
2162 return Some(v.span);
2172 Some((*args_span, var_span))
2178 /// Helper to retrieve span(s) of given borrow from the current MIR
2180 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans {
2181 let span = self.mir.source_info(borrow.reserve_location).span;
2182 self.borrow_spans(span, borrow.reserve_location)