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, Field, Local,
19 LocalDecl, LocalKind, Location, Operand, Place, PlaceProjection, ProjectionElem,
20 Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
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
81 .contains(&root_place.clone())
84 "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
90 self.uninitialized_error_reported.insert(root_place.clone());
92 let item_msg = match self.describe_place_with_options(used_place,
93 IncludingDowncast(true)) {
94 Some(name) => format!("`{}`", name),
95 None => "value".to_owned(),
97 let mut err = self.infcx.tcx.cannot_act_on_uninitialized_variable(
99 desired_action.as_noun(),
100 &self.describe_place_with_options(moved_place, IncludingDowncast(true))
101 .unwrap_or("_".to_owned()),
104 err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
106 use_spans.var_span_label(
108 format!("{} occurs due to use in closure", desired_action.as_noun()),
111 err.buffer(&mut self.errors_buffer);
113 if let Some((reported_place, _)) = self.move_error_reported.get(&move_out_indices) {
114 if self.prefixes(&reported_place, PrefixSet::All)
115 .any(|p| p == used_place)
118 "report_use_of_moved_or_uninitialized place: error suppressed \
126 let msg = ""; //FIXME: add "partially " or "collaterally "
128 let mut err = self.infcx.tcx.cannot_act_on_moved_value(
130 desired_action.as_noun(),
132 self.describe_place_with_options(&moved_place, IncludingDowncast(true)),
136 let mut is_loop_move = false;
137 for move_site in &move_site_vec {
138 let move_out = self.move_data.moves[(*move_site).moi];
139 let moved_place = &self.move_data.move_paths[move_out.path].place;
141 let move_spans = self.move_spans(moved_place, move_out.source);
142 let move_span = move_spans.args_or_use();
144 let move_msg = if move_spans.for_closure() {
150 if span == move_span {
153 format!("value moved{} here, in previous iteration of loop", move_msg),
156 } else if move_site.traversed_back_edge {
160 "value moved{} here, in previous iteration of loop",
165 err.span_label(move_span, format!("value moved{} here", move_msg));
166 move_spans.var_span_label(&mut err, "variable moved due to use in closure");
170 use_spans.var_span_label(
172 format!("{} occurs due to use in closure", desired_action.as_noun()),
179 "value {} here after move",
180 desired_action.as_verb_in_past_tense()
185 if let Some(ty) = self.retrieve_type_for_place(used_place) {
186 let needs_note = match ty.sty {
187 ty::Closure(id, _) => {
188 let tables = self.infcx.tcx.typeck_tables_of(id);
189 let node_id = self.infcx.tcx.hir.as_local_node_id(id).unwrap();
190 let hir_id = self.infcx.tcx.hir.node_to_hir_id(node_id);
191 if tables.closure_kind_origins().get(hir_id).is_some() {
201 let mpi = self.move_data.moves[move_out_indices[0]].path;
202 let place = &self.move_data.move_paths[mpi].place;
204 if let Some(ty) = self.retrieve_type_for_place(place) {
205 let note_msg = match self.describe_place_with_options(
207 IncludingDowncast(true),
209 Some(name) => format!("`{}`", name),
210 None => "value".to_owned(),
214 "move occurs because {} has type `{}`, \
215 which does not implement the `Copy` trait",
222 if let Some((_, mut old_err)) = self.move_error_reported
223 .insert(move_out_indices, (used_place.clone(), err))
225 // Cancel the old error so it doesn't ICE.
231 pub(super) fn report_move_out_while_borrowed(
234 (place, _span): (&Place<'tcx>, Span),
235 borrow: &BorrowData<'tcx>,
237 let tcx = self.infcx.tcx;
238 let value_msg = match self.describe_place(place) {
239 Some(name) => format!("`{}`", name),
240 None => "value".to_owned(),
242 let borrow_msg = match self.describe_place(&borrow.borrowed_place) {
243 Some(name) => format!("`{}`", name),
244 None => "value".to_owned(),
247 let borrow_spans = self.retrieve_borrow_spans(borrow);
248 let borrow_span = borrow_spans.args_or_use();
250 let move_spans = self.move_spans(place, context.loc);
251 let span = move_spans.args_or_use();
253 let mut err = tcx.cannot_move_when_borrowed(
255 &self.describe_place(place).unwrap_or("_".to_owned()),
258 err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
259 err.span_label(span, format!("move out of {} occurs here", value_msg));
261 borrow_spans.var_span_label(&mut err, "borrow occurs due to use in closure");
263 move_spans.var_span_label(&mut err, "move occurs due to use in closure");
265 self.explain_why_borrow_contains_point(context, borrow, None)
266 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
267 err.buffer(&mut self.errors_buffer);
270 pub(super) fn report_use_while_mutably_borrowed(
273 (place, _span): (&Place<'tcx>, Span),
274 borrow: &BorrowData<'tcx>,
276 let tcx = self.infcx.tcx;
278 let borrow_spans = self.retrieve_borrow_spans(borrow);
279 let borrow_span = borrow_spans.args_or_use();
281 // Conflicting borrows are reported separately, so only check for move
283 let use_spans = self.move_spans(place, context.loc);
284 let span = use_spans.var_or_use();
286 let mut err = tcx.cannot_use_when_mutably_borrowed(
288 &self.describe_place(place).unwrap_or("_".to_owned()),
290 &self.describe_place(&borrow.borrowed_place)
291 .unwrap_or("_".to_owned()),
295 borrow_spans.var_span_label(&mut err, {
296 let place = &borrow.borrowed_place;
297 let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
299 format!("borrow occurs due to use of `{}` in closure", desc_place)
302 self.explain_why_borrow_contains_point(context, borrow, None)
303 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
304 err.buffer(&mut self.errors_buffer);
307 pub(super) fn report_conflicting_borrow(
310 (place, span): (&Place<'tcx>, Span),
311 gen_borrow_kind: BorrowKind,
312 issued_borrow: &BorrowData<'tcx>,
314 let issued_spans = self.retrieve_borrow_spans(issued_borrow);
315 let issued_span = issued_spans.args_or_use();
317 let borrow_spans = self.borrow_spans(span, context.loc);
318 let span = borrow_spans.args_or_use();
320 let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
321 let tcx = self.infcx.tcx;
323 let first_borrow_desc;
325 // FIXME: supply non-"" `opt_via` when appropriate
326 let mut err = match (
334 (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
335 first_borrow_desc = "mutable ";
336 tcx.cannot_reborrow_already_borrowed(
349 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
350 first_borrow_desc = "immutable ";
351 tcx.cannot_reborrow_already_borrowed(
365 (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
366 first_borrow_desc = "first ";
367 tcx.cannot_mutably_borrow_multiply(
378 (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
379 first_borrow_desc = "first ";
380 tcx.cannot_uniquely_borrow_by_two_closures(
389 (BorrowKind::Mut { .. }, _, _, BorrowKind::Shallow, _, _)
390 | (BorrowKind::Unique, _, _, BorrowKind::Shallow, _, _) => {
391 let mut err = tcx.cannot_mutate_in_match_guard(
398 borrow_spans.var_span_label(
400 format!("borrow occurs due to use of `{}` in closure", desc_place),
402 err.buffer(&mut self.errors_buffer);
407 (BorrowKind::Unique, _, _, _, _, _) => {
408 first_borrow_desc = "first ";
409 tcx.cannot_uniquely_borrow_by_one_closure(
421 (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
422 first_borrow_desc = "first ";
423 tcx.cannot_reborrow_already_uniquely_borrowed(
435 (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
436 first_borrow_desc = "first ";
437 tcx.cannot_reborrow_already_uniquely_borrowed(
449 (BorrowKind::Shallow, _, _, BorrowKind::Unique, _, _)
450 | (BorrowKind::Shallow, _, _, BorrowKind::Mut { .. }, _, _) => {
451 // Shallow borrows are uses from the user's point of view.
452 self.report_use_while_mutably_borrowed(context, (place, span), issued_borrow);
455 (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _)
456 | (BorrowKind::Shared, _, _, BorrowKind::Shallow, _, _)
457 | (BorrowKind::Shallow, _, _, BorrowKind::Shared, _, _)
458 | (BorrowKind::Shallow, _, _, BorrowKind::Shallow, _, _) => unreachable!(),
461 if issued_spans == borrow_spans {
462 borrow_spans.var_span_label(
464 format!("borrows occur due to use of `{}` in closure", desc_place),
467 let borrow_place = &issued_borrow.borrowed_place;
468 let borrow_place_desc = self.describe_place(borrow_place).unwrap_or("_".to_owned());
469 issued_spans.var_span_label(
472 "first borrow occurs due to use of `{}` in closure",
477 borrow_spans.var_span_label(
480 "second borrow occurs due to use of `{}` in closure",
486 self.explain_why_borrow_contains_point(context, issued_borrow, None)
487 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, first_borrow_desc);
489 err.buffer(&mut self.errors_buffer);
492 /// Reports StorageDeadOrDrop of `place` conflicts with `borrow`.
494 /// This means that some data referenced by `borrow` needs to live
495 /// past the point where the StorageDeadOrDrop of `place` occurs.
496 /// This is usually interpreted as meaning that `place` has too
497 /// short a lifetime. (But sometimes it is more useful to report
498 /// it as a more direct conflict between the execution of a
499 /// `Drop::drop` with an aliasing borrow.)
500 pub(super) fn report_borrowed_value_does_not_live_long_enough(
503 borrow: &BorrowData<'tcx>,
504 place_span: (&Place<'tcx>, Span),
505 kind: Option<WriteKind>,
508 "report_borrowed_value_does_not_live_long_enough(\
509 {:?}, {:?}, {:?}, {:?}\
511 context, borrow, place_span, kind
514 let drop_span = place_span.1;
515 let scope_tree = self.infcx.tcx.region_scope_tree(self.mir_def_id);
516 let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
520 let borrow_spans = self.retrieve_borrow_spans(borrow);
521 let borrow_span = borrow_spans.var_or_use();
523 let proper_span = match *root_place {
524 Place::Local(local) => self.mir.local_decls[local].source_info.span,
528 if self.access_place_error_reported
529 .contains(&(root_place.clone(), borrow_span))
532 "suppressing access_place error when borrow doesn't live long enough for {:?}",
538 self.access_place_error_reported
539 .insert((root_place.clone(), borrow_span));
541 if let StorageDeadOrDrop::Destructor(dropped_ty) =
542 self.classify_drop_access_kind(&borrow.borrowed_place)
544 // If a borrow of path `B` conflicts with drop of `D` (and
545 // we're not in the uninteresting case where `B` is a
546 // prefix of `D`), then report this as a more interesting
547 // destructor conflict.
548 if !borrow.borrowed_place.is_prefix_of(place_span.0) {
549 self.report_borrow_conflicts_with_destructor(
550 context, borrow, place_span, kind, dropped_ty,
556 let err = match &self.describe_place(&borrow.borrowed_place) {
557 Some(_) if self.is_place_thread_local(root_place) => {
558 self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span)
560 Some(name) => self.report_local_value_does_not_live_long_enough(
567 kind.map(|k| (k, place_span.0)),
569 None => self.report_temporary_value_does_not_live_long_enough(
579 err.buffer(&mut self.errors_buffer);
582 fn report_local_value_does_not_live_long_enough(
586 scope_tree: &Lrc<ScopeTree>,
587 borrow: &BorrowData<'tcx>,
589 borrow_spans: UseSpans,
590 kind_place: Option<(WriteKind, &Place<'tcx>)>,
591 ) -> DiagnosticBuilder<'cx> {
593 "report_local_value_does_not_live_long_enough(\
594 {:?}, {:?}, {:?}, {:?}, {:?}, {:?}\
596 context, name, scope_tree, borrow, drop_span, borrow_spans
599 let borrow_span = borrow_spans.var_or_use();
600 let mut err = self.infcx.tcx.path_does_not_live_long_enough(
602 &format!("`{}`", name),
606 let explanation = self.explain_why_borrow_contains_point(context, borrow, kind_place);
607 if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
608 let region_name = annotation.emit(&mut err);
612 format!("`{}` would have to be valid for `{}`...", name, region_name),
615 if let Some(fn_node_id) = self.infcx.tcx.hir.as_local_node_id(self.mir_def_id) {
619 "...but `{}` will be dropped here, when the function `{}` returns",
621 self.infcx.tcx.hir.name(fn_node_id),
626 "functions cannot return a borrow to data owned within the function's scope, \
627 functions can only return borrows to data passed as arguments",
630 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch04-02-\
631 references-and-borrowing.html#dangling-references>",
636 format!("...but `{}` dropped here while still borrowed", name),
640 if let BorrowExplanation::MustBeValidFor(..) = explanation {
642 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
645 err.span_label(borrow_span, "borrowed value does not live long enough");
648 format!("`{}` dropped here while still borrowed", name),
651 borrow_spans.args_span_label(&mut err, "value captured here");
653 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
659 pub(super) fn report_borrow_conflicts_with_destructor(
662 borrow: &BorrowData<'tcx>,
663 (place, drop_span): (&Place<'tcx>, Span),
664 kind: Option<WriteKind>,
665 dropped_ty: ty::Ty<'tcx>,
668 "report_borrow_conflicts_with_destructor(\
669 {:?}, {:?}, ({:?}, {:?}), {:?}\
671 context, borrow, place, drop_span, kind,
674 let borrow_spans = self.retrieve_borrow_spans(borrow);
675 let borrow_span = borrow_spans.var_or_use();
677 let mut err = self.infcx
679 .cannot_borrow_across_destructor(borrow_span, Origin::Mir);
681 let what_was_dropped = match self.describe_place(place) {
682 Some(name) => format!("`{}`", name.as_str()),
683 None => format!("temporary value"),
686 let label = match self.describe_place(&borrow.borrowed_place) {
687 Some(borrowed) => format!(
688 "here, drop of {D} needs exclusive access to `{B}`, \
689 because the type `{T}` implements the `Drop` trait",
690 D = what_was_dropped,
695 "here is drop of {D}; whose type `{T}` implements the `Drop` trait",
696 D = what_was_dropped,
700 err.span_label(drop_span, label);
702 // Only give this note and suggestion if they could be relevant.
704 self.explain_why_borrow_contains_point(context, borrow, kind.map(|k| (k, place)));
706 BorrowExplanation::UsedLater { .. }
707 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
708 err.note("consider using a `let` binding to create a longer lived value");
713 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
715 err.buffer(&mut self.errors_buffer);
718 fn report_thread_local_value_does_not_live_long_enough(
722 ) -> DiagnosticBuilder<'cx> {
724 "report_thread_local_value_does_not_live_long_enough(\
727 drop_span, borrow_span
730 let mut err = self.infcx
732 .thread_local_value_does_not_live_long_enough(borrow_span, Origin::Mir);
736 "thread-local variables cannot be borrowed beyond the end of the function",
738 err.span_label(drop_span, "end of enclosing function is here");
743 fn report_temporary_value_does_not_live_long_enough(
746 scope_tree: &Lrc<ScopeTree>,
747 borrow: &BorrowData<'tcx>,
749 borrow_spans: UseSpans,
751 ) -> DiagnosticBuilder<'cx> {
753 "report_temporary_value_does_not_live_long_enough(\
754 {:?}, {:?}, {:?}, {:?}, {:?}\
756 context, scope_tree, borrow, drop_span, proper_span
759 let tcx = self.infcx.tcx;
760 let mut err = tcx.temporary_value_borrowed_for_too_long(proper_span, Origin::Mir);
763 "creates a temporary which is freed while still in use",
767 "temporary value is freed at the end of this statement",
770 let explanation = self.explain_why_borrow_contains_point(context, borrow, None);
772 BorrowExplanation::UsedLater(..)
773 | BorrowExplanation::UsedLaterInLoop(..)
774 | BorrowExplanation::UsedLaterWhenDropped { .. } => {
775 // Only give this note and suggestion if it could be relevant.
776 err.note("consider using a `let` binding to create a longer lived value");
780 explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
782 borrow_spans.args_span_label(&mut err, "value captured here");
787 fn get_moved_indexes(&mut self, context: Context, mpi: MovePathIndex) -> Vec<MoveSite> {
790 let mut stack = Vec::new();
791 stack.extend(mir.predecessor_locations(context.loc).map(|predecessor| {
792 let is_back_edge = context.loc.dominates(predecessor, &self.dominators);
793 (predecessor, is_back_edge)
796 let mut visited = FxHashSet();
797 let mut result = vec![];
799 'dfs: while let Some((location, is_back_edge)) = stack.pop() {
801 "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
802 location, is_back_edge
805 if !visited.insert(location) {
810 let stmt_kind = mir[location.block]
812 .get(location.statement_index)
814 if let Some(StatementKind::StorageDead(..)) = stmt_kind {
815 // this analysis only tries to find moves explicitly
816 // written by the user, so we ignore the move-outs
817 // created by `StorageDead` and at the beginning
820 // If we are found a use of a.b.c which was in error, then we want to look for
821 // moves not only of a.b.c but also a.b and a.
823 // Note that the moves data already includes "parent" paths, so we don't have to
824 // worry about the other case: that is, if there is a move of a.b.c, it is already
825 // marked as a move of a.b and a as well, so we will generate the correct errors
827 let mut mpis = vec![mpi];
828 let move_paths = &self.move_data.move_paths;
829 mpis.extend(move_paths[mpi].parents(move_paths));
831 for moi in &self.move_data.loc_map[location] {
832 debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
833 if mpis.contains(&self.move_data.moves[*moi].path) {
834 debug!("report_use_of_moved_or_uninitialized: found");
835 result.push(MoveSite {
837 traversed_back_edge: is_back_edge,
840 // Strictly speaking, we could continue our DFS here. There may be
841 // other moves that can reach the point of error. But it is kind of
842 // confusing to highlight them.
850 // drop(a); // <-- current point of error
853 // Because we stop the DFS here, we only highlight `let c = a`,
854 // and not `let b = a`. We will of course also report an error at
855 // `let c = a` which highlights `let b = a` as the move.
862 let mut any_match = false;
863 drop_flag_effects::for_location_inits(
878 stack.extend(mir.predecessor_locations(location).map(|predecessor| {
879 let back_edge = location.dominates(predecessor, &self.dominators);
880 (predecessor, is_back_edge || back_edge)
887 pub(super) fn report_illegal_mutation_of_borrowed(
890 (place, span): (&Place<'tcx>, Span),
891 loan: &BorrowData<'tcx>,
893 let loan_spans = self.retrieve_borrow_spans(loan);
894 let loan_span = loan_spans.args_or_use();
896 let tcx = self.infcx.tcx;
897 let mut err = if loan.kind == BorrowKind::Shallow {
898 tcx.cannot_mutate_in_match_guard(
901 &self.describe_place(place).unwrap_or("_".to_owned()),
906 tcx.cannot_assign_to_borrowed(
909 &self.describe_place(place).unwrap_or("_".to_owned()),
914 loan_spans.var_span_label(&mut err, "borrow occurs due to use in closure");
916 self.explain_why_borrow_contains_point(context, loan, None)
917 .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
919 err.buffer(&mut self.errors_buffer);
922 /// Reports an illegal reassignment; for example, an assignment to
923 /// (part of) a non-`mut` local that occurs potentially after that
924 /// local has already been initialized. `place` is the path being
925 /// assigned; `err_place` is a place providing a reason why
926 /// `place` is not mutable (e.g. the non-`mut` local `x` in an
927 /// assignment to `x.f`).
928 pub(super) fn report_illegal_reassignment(
931 (place, span): (&Place<'tcx>, Span),
933 err_place: &Place<'tcx>,
935 let (from_arg, local_decl) = if let Place::Local(local) = *err_place {
936 if let LocalKind::Arg = self.mir.local_kind(local) {
937 (true, Some(&self.mir.local_decls[local]))
939 (false, Some(&self.mir.local_decls[local]))
945 // If root local is initialized immediately (everything apart from let
946 // PATTERN;) then make the error refer to that local, rather than the
947 // place being assigned later.
948 let (place_description, assigned_span) = match local_decl {
950 is_user_variable: Some(ClearCrossCrate::Clear),
955 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
956 opt_match_place: None,
962 is_user_variable: None,
965 | None => (self.describe_place(place), assigned_span),
966 Some(decl) => (self.describe_place(err_place), decl.source_info.span),
969 let mut err = self.infcx.tcx.cannot_reassign_immutable(
971 place_description.as_ref().map(AsRef::as_ref).unwrap_or("_"),
975 let msg = if from_arg {
976 "cannot assign to immutable argument"
978 "cannot assign twice to immutable variable"
980 if span != assigned_span {
982 let value_msg = match place_description {
983 Some(name) => format!("`{}`", name),
984 None => "value".to_owned(),
986 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
989 if let Some(decl) = local_decl {
990 if let Some(name) = decl.name {
991 if decl.can_be_made_mutable() {
992 err.span_suggestion_with_applicability(
993 decl.source_info.span,
994 "make this binding mutable",
995 format!("mut {}", name),
996 Applicability::MachineApplicable,
1001 err.span_label(span, msg);
1002 err.buffer(&mut self.errors_buffer);
1006 pub(super) struct IncludingDowncast(bool);
1008 /// Which case a StorageDeadOrDrop is for.
1009 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1010 enum StorageDeadOrDrop<'tcx> {
1013 Destructor(ty::Ty<'tcx>),
1016 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1017 // End-user visible description of `place` if one can be found. If the
1018 // place is a temporary for instance, None will be returned.
1019 pub(super) fn describe_place(&self, place: &Place<'tcx>) -> Option<String> {
1020 self.describe_place_with_options(place, IncludingDowncast(false))
1023 // End-user visible description of `place` if one can be found. If the
1024 // place is a temporary for instance, None will be returned.
1025 // `IncludingDowncast` parameter makes the function return `Err` if `ProjectionElem` is
1026 // `Downcast` and `IncludingDowncast` is true
1027 pub(super) fn describe_place_with_options(
1029 place: &Place<'tcx>,
1030 including_downcast: IncludingDowncast,
1031 ) -> Option<String> {
1032 let mut buf = String::new();
1033 match self.append_place_to_string(place, &mut buf, false, &including_downcast) {
1034 Ok(()) => Some(buf),
1039 // Appends end-user visible description of `place` to `buf`.
1040 fn append_place_to_string(
1042 place: &Place<'tcx>,
1044 mut autoderef: bool,
1045 including_downcast: &IncludingDowncast,
1046 ) -> Result<(), ()> {
1048 Place::Promoted(_) => {
1049 buf.push_str("promoted");
1051 Place::Local(local) => {
1052 self.append_local_to_string(local, buf)?;
1054 Place::Static(ref static_) => {
1055 buf.push_str(&self.infcx.tcx.item_name(static_.def_id).to_string());
1057 Place::Projection(ref proj) => {
1059 ProjectionElem::Deref => {
1060 let upvar_field_projection =
1061 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1062 if let Some(field) = upvar_field_projection {
1063 let var_index = field.index();
1064 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1065 if self.mir.upvar_decls[var_index].by_ref {
1066 buf.push_str(&name);
1068 buf.push_str(&format!("*{}", &name));
1072 self.append_place_to_string(
1076 &including_downcast,
1078 } else if let Place::Local(local) = proj.base {
1079 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
1080 self.mir.local_decls[local].is_user_variable
1082 self.append_place_to_string(
1086 &including_downcast,
1090 self.append_place_to_string(
1094 &including_downcast,
1099 self.append_place_to_string(
1103 &including_downcast,
1108 ProjectionElem::Downcast(..) => {
1109 self.append_place_to_string(
1113 &including_downcast,
1115 if including_downcast.0 {
1119 ProjectionElem::Field(field, _ty) => {
1122 let upvar_field_projection =
1123 place.is_upvar_field_projection(self.mir, &self.infcx.tcx);
1124 if let Some(field) = upvar_field_projection {
1125 let var_index = field.index();
1126 let name = self.mir.upvar_decls[var_index].debug_name.to_string();
1127 buf.push_str(&name);
1129 let field_name = self.describe_field(&proj.base, field);
1130 self.append_place_to_string(
1134 &including_downcast,
1136 buf.push_str(&format!(".{}", field_name));
1139 ProjectionElem::Index(index) => {
1142 self.append_place_to_string(
1146 &including_downcast,
1149 if self.append_local_to_string(index, buf).is_err() {
1154 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1156 // Since it isn't possible to borrow an element on a particular index and
1157 // then use another while the borrow is held, don't output indices details
1158 // to avoid confusing the end-user
1159 self.append_place_to_string(
1163 &including_downcast,
1165 buf.push_str(&"[..]");
1174 // Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
1175 // a name, then `Err` is returned
1176 fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> {
1177 let local = &self.mir.local_decls[local_index];
1180 buf.push_str(&name.to_string());
1187 // End-user visible description of the `field`nth field of `base`
1188 fn describe_field(&self, base: &Place, field: Field) -> String {
1190 Place::Local(local) => {
1191 let local = &self.mir.local_decls[local];
1192 self.describe_field_from_ty(&local.ty, field)
1194 Place::Promoted(ref prom) => self.describe_field_from_ty(&prom.1, field),
1195 Place::Static(ref static_) => self.describe_field_from_ty(&static_.ty, field),
1196 Place::Projection(ref proj) => match proj.elem {
1197 ProjectionElem::Deref => self.describe_field(&proj.base, field),
1198 ProjectionElem::Downcast(def, variant_index) => format!(
1200 def.variants[variant_index].fields[field.index()].ident
1202 ProjectionElem::Field(_, field_type) => {
1203 self.describe_field_from_ty(&field_type, field)
1205 ProjectionElem::Index(..)
1206 | ProjectionElem::ConstantIndex { .. }
1207 | ProjectionElem::Subslice { .. } => {
1208 self.describe_field(&proj.base, field).to_string()
1214 // End-user visible description of the `field_index`nth field of `ty`
1215 fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String {
1217 // If the type is a box, the field is described from the boxed type
1218 self.describe_field_from_ty(&ty.boxed_ty(), field)
1221 ty::Adt(def, _) => if def.is_enum() {
1222 field.index().to_string()
1224 def.non_enum_variant().fields[field.index()]
1228 ty::Tuple(_) => field.index().to_string(),
1229 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
1230 self.describe_field_from_ty(&ty, field)
1232 ty::Array(ty, _) | ty::Slice(ty) => self.describe_field_from_ty(&ty, field),
1233 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
1234 // Convert the def-id into a node-id. node-ids are only valid for
1235 // the local code in the current crate, so this returns an `Option` in case
1236 // the closure comes from another crate. But in that case we wouldn't
1237 // be borrowck'ing it, so we can just unwrap:
1238 let node_id = self.infcx.tcx.hir.as_local_node_id(def_id).unwrap();
1239 let freevar = self.infcx
1241 .with_freevars(node_id, |fv| fv[field.index()]);
1243 self.infcx.tcx.hir.name(freevar.var_id()).to_string()
1246 // Might need a revision when the fields in trait RFC is implemented
1247 // (https://github.com/rust-lang/rfcs/pull/1546)
1249 "End-user description not implemented for field access on `{:?}`",
1257 // Retrieve type of a place for the current MIR representation
1258 fn retrieve_type_for_place(&self, place: &Place<'tcx>) -> Option<ty::Ty> {
1260 Place::Local(local) => {
1261 let local = &self.mir.local_decls[*local];
1264 Place::Promoted(ref prom) => Some(prom.1),
1265 Place::Static(ref st) => Some(st.ty),
1266 Place::Projection(ref proj) => match proj.elem {
1267 ProjectionElem::Field(_, ty) => Some(ty),
1273 /// Check if a place is a thread-local static.
1274 pub fn is_place_thread_local(&self, place: &Place<'tcx>) -> bool {
1275 if let Place::Static(statik) = place {
1276 let attrs = self.infcx.tcx.get_attrs(statik.def_id);
1277 let is_thread_local = attrs.iter().any(|attr| attr.check_name("thread_local"));
1280 "is_place_thread_local: attrs={:?} is_thread_local={:?}",
1281 attrs, is_thread_local
1285 debug!("is_place_thread_local: no");
1290 fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
1291 let tcx = self.infcx.tcx;
1293 Place::Local(_) | Place::Static(_) | Place::Promoted(_) => {
1294 StorageDeadOrDrop::LocalStorageDead
1296 Place::Projection(box PlaceProjection { base, elem }) => {
1297 let base_access = self.classify_drop_access_kind(base);
1299 ProjectionElem::Deref => match base_access {
1300 StorageDeadOrDrop::LocalStorageDead
1301 | StorageDeadOrDrop::BoxedStorageDead => {
1303 base.ty(self.mir, tcx).to_ty(tcx).is_box(),
1304 "Drop of value behind a reference or raw pointer"
1306 StorageDeadOrDrop::BoxedStorageDead
1308 StorageDeadOrDrop::Destructor(_) => base_access,
1310 ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => {
1311 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1313 ty::Adt(def, _) if def.has_dtor(tcx) => {
1314 // Report the outermost adt with a destructor
1316 StorageDeadOrDrop::Destructor(_) => base_access,
1317 StorageDeadOrDrop::LocalStorageDead
1318 | StorageDeadOrDrop::BoxedStorageDead => {
1319 StorageDeadOrDrop::Destructor(base_ty)
1327 ProjectionElem::ConstantIndex { .. }
1328 | ProjectionElem::Subslice { .. }
1329 | ProjectionElem::Index(_) => base_access,
1335 /// Annotate argument and return type of function and closure with (synthesized) lifetime for
1336 /// borrow of local value that does not live long enough.
1337 fn annotate_argument_and_return_for_borrow(
1339 borrow: &BorrowData<'tcx>,
1340 ) -> Option<AnnotatedBorrowFnSignature> {
1341 // Define a fallback for when we can't match a closure.
1343 let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
1347 let ty = self.infcx.tcx.type_of(self.mir_def_id);
1349 ty::TyKind::FnDef(_, _) | ty::TyKind::FnPtr(_) => self.annotate_fn_sig(
1351 self.infcx.tcx.fn_sig(self.mir_def_id),
1358 // In order to determine whether we need to annotate, we need to check whether the reserve
1359 // place was an assignment into a temporary.
1361 // If it was, we check whether or not that temporary is eventually assigned into the return
1362 // place. If it was, we can add annotations about the function's return type and arguments
1363 // and it'll make sense.
1364 let location = borrow.reserve_location;
1366 "annotate_argument_and_return_for_borrow: location={:?}",
1369 match &self.mir[location.block]
1371 .get(location.statement_index)
1374 kind: StatementKind::Assign(ref reservation, _),
1378 "annotate_argument_and_return_for_borrow: reservation={:?}",
1381 // Check that the initial assignment of the reserve location is into a temporary.
1382 let mut target = *match reservation {
1383 Place::Local(local) if self.mir.local_kind(*local) == LocalKind::Temp => local,
1387 // Next, look through the rest of the block, checking if we are assigning the
1388 // `target` (that is, the place that contains our borrow) to anything.
1389 let mut annotated_closure = None;
1390 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1392 "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
1395 if let StatementKind::Assign(Place::Local(assigned_to), box rvalue) = &stmt.kind
1398 "annotate_argument_and_return_for_borrow: assigned_to={:?} \
1402 // Check if our `target` was captured by a closure.
1403 if let Rvalue::Aggregate(
1404 box AggregateKind::Closure(def_id, substs),
1408 for operand in operands {
1409 let assigned_from = match operand {
1410 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1416 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1420 // Find the local from the operand.
1421 let assigned_from_local = match assigned_from.local() {
1422 Some(local) => local,
1426 if assigned_from_local != target {
1430 // If a closure captured our `target` and then assigned
1431 // into a place then we should annotate the closure in
1432 // case it ends up being assigned into the return place.
1433 annotated_closure = self.annotate_fn_sig(
1435 self.infcx.closure_sig(*def_id, *substs),
1438 "annotate_argument_and_return_for_borrow: \
1439 annotated_closure={:?} assigned_from_local={:?} \
1441 annotated_closure, assigned_from_local, assigned_to
1444 if *assigned_to == mir::RETURN_PLACE {
1445 // If it was assigned directly into the return place, then
1447 return annotated_closure;
1449 // Otherwise, update the target.
1450 target = *assigned_to;
1454 // If none of our closure's operands matched, then skip to the next
1459 // Otherwise, look at other types of assignment.
1460 let assigned_from = match rvalue {
1461 Rvalue::Ref(_, _, assigned_from) => assigned_from,
1462 Rvalue::Use(operand) => match operand {
1463 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1471 "annotate_argument_and_return_for_borrow: \
1472 assigned_from={:?}",
1476 // Find the local from the rvalue.
1477 let assigned_from_local = match assigned_from.local() {
1478 Some(local) => local,
1482 "annotate_argument_and_return_for_borrow: \
1483 assigned_from_local={:?}",
1484 assigned_from_local,
1487 // Check if our local matches the target - if so, we've assigned our
1488 // borrow to a new place.
1489 if assigned_from_local != target {
1493 // If we assigned our `target` into a new place, then we should
1494 // check if it was the return place.
1496 "annotate_argument_and_return_for_borrow: \
1497 assigned_from_local={:?} assigned_to={:?}",
1498 assigned_from_local, assigned_to
1500 if *assigned_to == mir::RETURN_PLACE {
1501 // If it was then return the annotated closure if there was one,
1502 // else, annotate this function.
1503 return annotated_closure.or_else(fallback);
1506 // If we didn't assign into the return place, then we just update
1508 target = *assigned_to;
1512 // Check the terminator if we didn't find anything in the statements.
1513 let terminator = &self.mir[location.block].terminator();
1515 "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
1518 if let TerminatorKind::Call {
1519 destination: Some((Place::Local(assigned_to), _)),
1522 } = &terminator.kind
1525 "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
1528 for operand in args {
1529 let assigned_from = match operand {
1530 Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
1536 "annotate_argument_and_return_for_borrow: assigned_from={:?}",
1540 if let Some(assigned_from_local) = assigned_from.local() {
1542 "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
1543 assigned_from_local,
1546 if *assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
1547 return annotated_closure.or_else(fallback);
1556 // If we haven't found an assignment into the return place, then we need not add
1558 debug!("annotate_argument_and_return_for_borrow: none found");
1562 /// Annotate the first argument and return type of a function signature if they are
1567 sig: ty::PolyFnSig<'tcx>,
1568 ) -> Option<AnnotatedBorrowFnSignature> {
1569 debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
1570 let is_closure = self.infcx.tcx.is_closure(did);
1571 let fn_node_id = self.infcx.tcx.hir.as_local_node_id(did)?;
1572 let fn_decl = self.infcx.tcx.hir.fn_decl(fn_node_id)?;
1574 // We need to work out which arguments to highlight. We do this by looking
1575 // at the return type, where there are three cases:
1577 // 1. If there are named arguments, then we should highlight the return type and
1578 // highlight any of the arguments that are also references with that lifetime.
1579 // If there are no arguments that have the same lifetime as the return type,
1580 // then don't highlight anything.
1581 // 2. The return type is a reference with an anonymous lifetime. If this is
1582 // the case, then we can take advantage of (and teach) the lifetime elision
1585 // We know that an error is being reported. So the arguments and return type
1586 // must satisfy the elision rules. Therefore, if there is a single argument
1587 // then that means the return type and first (and only) argument have the same
1588 // lifetime and the borrow isn't meeting that, we can highlight the argument
1591 // If there are multiple arguments then the first argument must be self (else
1592 // it would not satisfy the elision rules), so we can highlight self and the
1594 // 3. The return type is not a reference. In this case, we don't highlight
1596 let return_ty = sig.output();
1597 match return_ty.skip_binder().sty {
1598 ty::TyKind::Ref(return_region, _, _) if return_region.has_name() && !is_closure => {
1599 // This is case 1 from above, return type is a named reference so we need to
1600 // search for relevant arguments.
1601 let mut arguments = Vec::new();
1602 for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
1603 if let ty::TyKind::Ref(argument_region, _, _) = argument.sty {
1604 if argument_region == return_region {
1605 // Need to use the `rustc::ty` types to compare against the
1606 // `return_region`. Then use the `rustc::hir` type to get only
1607 // the lifetime span.
1608 match &fn_decl.inputs[index].node {
1609 hir::TyKind::Rptr(lifetime, _) => {
1610 // With access to the lifetime, we can get
1612 arguments.push((*argument, lifetime.span));
1614 _ => bug!("ty type is a ref but hir type is not"),
1620 // We need to have arguments. This shouldn't happen, but it's worth checking.
1621 if arguments.is_empty() {
1625 // We use a mix of the HIR and the Ty types to get information
1626 // as the HIR doesn't have full types for closure arguments.
1627 let return_ty = *sig.output().skip_binder();
1628 let mut return_span = fn_decl.output.span();
1629 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
1630 if let hir::TyKind::Rptr(lifetime, _) = ty.into_inner().node {
1631 return_span = lifetime.span;
1635 Some(AnnotatedBorrowFnSignature::NamedFunction {
1641 ty::TyKind::Ref(_, _, _) if is_closure => {
1642 // This is case 2 from above but only for closures, return type is anonymous
1643 // reference so we select
1644 // the first argument.
1645 let argument_span = fn_decl.inputs.first()?.span;
1646 let argument_ty = sig.inputs().skip_binder().first()?;
1648 // Closure arguments are wrapped in a tuple, so we need to get the first
1650 if let ty::TyKind::Tuple(elems) = argument_ty.sty {
1651 let argument_ty = elems.first()?;
1652 if let ty::TyKind::Ref(_, _, _) = argument_ty.sty {
1653 return Some(AnnotatedBorrowFnSignature::Closure {
1662 ty::TyKind::Ref(_, _, _) => {
1663 // This is also case 2 from above but for functions, return type is still an
1664 // anonymous reference so we select the first argument.
1665 let argument_span = fn_decl.inputs.first()?.span;
1666 let argument_ty = sig.inputs().skip_binder().first()?;
1668 let return_span = fn_decl.output.span();
1669 let return_ty = *sig.output().skip_binder();
1671 // We expect the first argument to be a reference.
1672 match argument_ty.sty {
1673 ty::TyKind::Ref(_, _, _) => {}
1677 Some(AnnotatedBorrowFnSignature::AnonymousFunction {
1685 // This is case 3 from above, return type is not a reference so don't highlight
1694 enum AnnotatedBorrowFnSignature<'tcx> {
1696 arguments: Vec<(ty::Ty<'tcx>, Span)>,
1697 return_ty: ty::Ty<'tcx>,
1701 argument_ty: ty::Ty<'tcx>,
1702 argument_span: Span,
1703 return_ty: ty::Ty<'tcx>,
1707 argument_ty: ty::Ty<'tcx>,
1708 argument_span: Span,
1712 impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
1713 /// Annotate the provided diagnostic with information about borrow from the fn signature that
1715 fn emit(&self, diag: &mut DiagnosticBuilder<'_>) -> String {
1717 AnnotatedBorrowFnSignature::Closure {
1723 format!("has type `{}`", self.get_name_for_ty(argument_ty, 0)),
1726 self.get_region_name_for_ty(argument_ty, 0)
1728 AnnotatedBorrowFnSignature::AnonymousFunction {
1734 let argument_ty_name = self.get_name_for_ty(argument_ty, 0);
1735 diag.span_label(*argument_span, format!("has type `{}`", argument_ty_name));
1737 let return_ty_name = self.get_name_for_ty(return_ty, 0);
1738 let types_equal = return_ty_name == argument_ty_name;
1743 if types_equal { "also " } else { "" },
1749 "argument and return type have the same lifetime due to lifetime elision rules",
1752 "to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch10-03-\
1753 lifetime-syntax.html#lifetime-elision>",
1756 self.get_region_name_for_ty(return_ty, 0)
1758 AnnotatedBorrowFnSignature::NamedFunction {
1763 // Region of return type and arguments checked to be the same earlier.
1764 let region_name = self.get_region_name_for_ty(return_ty, 0);
1765 for (_, argument_span) in arguments {
1766 diag.span_label(*argument_span, format!("has lifetime `{}`", region_name));
1771 format!("also has lifetime `{}`", region_name,),
1775 "use data from the highlighted arguments which match the `{}` lifetime of \
1785 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
1786 /// name where required.
1787 fn get_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
1788 // We need to add synthesized lifetimes where appropriate. We do
1789 // this by hooking into the pretty printer and telling it to label the
1790 // lifetimes without names with the value `'0`.
1792 ty::TyKind::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
1794 ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }),
1797 ) => with_highlight_region_for_bound_region(*br, counter, || format!("{}", ty)),
1798 _ => format!("{}", ty),
1802 /// Return the name of the provided `Ty` (that must be a reference)'s region with a
1803 /// synthesized lifetime name where required.
1804 fn get_region_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
1806 ty::TyKind::Ref(region, _, _) => match region {
1807 ty::RegionKind::ReLateBound(_, br)
1808 | ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1809 with_highlight_region_for_bound_region(*br, counter, || format!("{}", region))
1811 _ => format!("{}", region),
1813 _ => bug!("ty for annotation of borrow region is not a reference"),
1818 // The span(s) associated to a use of a place.
1819 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1820 pub(super) enum UseSpans {
1821 // The access is caused by capturing a variable for a closure.
1823 // The span of the args of the closure, including the `move` keyword if
1826 // The span of the first use of the captured variable inside the closure.
1829 // This access has a single span associated to it: common case.
1834 pub(super) fn args_or_use(self) -> Span {
1836 UseSpans::ClosureUse {
1839 | UseSpans::OtherUse(span) => span,
1843 pub(super) fn var_or_use(self) -> Span {
1845 UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span,
1849 // Add a span label to the arguments of the closure, if it exists.
1850 pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1851 if let UseSpans::ClosureUse { args_span, .. } = self {
1852 err.span_label(args_span, message);
1856 // Add a span label to the use of the captured variable, if it exists.
1857 pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
1858 if let UseSpans::ClosureUse { var_span, .. } = self {
1859 err.span_label(var_span, message);
1863 pub(super) fn for_closure(self) -> bool {
1865 UseSpans::ClosureUse { .. } => true,
1866 UseSpans::OtherUse(_) => false,
1870 pub(super) fn or_else<F>(self, if_other: F) -> Self
1872 F: FnOnce() -> Self,
1875 closure @ UseSpans::ClosureUse { .. } => closure,
1876 UseSpans::OtherUse(_) => if_other(),
1881 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1882 /// Finds the spans associated to a move or copy of move_place at location.
1883 pub(super) fn move_spans(
1885 moved_place: &Place<'tcx>, // Could also be an upvar.
1888 use self::UseSpans::*;
1889 use rustc::hir::ExprKind::Closure;
1890 use rustc::mir::AggregateKind;
1892 let stmt = match self.mir[location.block]
1894 .get(location.statement_index)
1897 None => return OtherUse(self.mir.source_info(location).span),
1900 if let StatementKind::Assign(_, box Rvalue::Aggregate(ref kind, ref places)) = stmt.kind {
1901 if let AggregateKind::Closure(def_id, _) = **kind {
1902 debug!("find_closure_move_span: found closure {:?}", places);
1904 if let Some(node_id) = self.infcx.tcx.hir.as_local_node_id(def_id) {
1905 if let Closure(_, _, _, args_span, _) =
1906 self.infcx.tcx.hir.expect_expr(node_id).node
1908 if let Some(var_span) = self.infcx.tcx.with_freevars(node_id, |freevars| {
1909 for (v, place) in freevars.iter().zip(places) {
1911 Operand::Copy(place) | Operand::Move(place)
1912 if moved_place == place =>
1915 "find_closure_move_span: found captured local {:?}",
1918 return Some(v.span);
1935 return OtherUse(stmt.source_info.span);
1938 /// Finds the span of arguments of a closure (within `maybe_closure_span`)
1939 /// and its usage of the local assigned at `location`.
1940 /// This is done by searching in statements succeeding `location`
1941 /// and originating from `maybe_closure_span`.
1942 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans {
1943 use self::UseSpans::*;
1944 use rustc::hir::ExprKind::Closure;
1946 let local = match self.mir[location.block]
1948 .get(location.statement_index)
1951 kind: StatementKind::Assign(Place::Local(local), _),
1954 _ => return OtherUse(use_span),
1957 if self.mir.local_kind(local) != LocalKind::Temp {
1958 // operands are always temporaries.
1959 return OtherUse(use_span);
1962 for stmt in &self.mir[location.block].statements[location.statement_index + 1..] {
1963 if let StatementKind::Assign(_, box Rvalue::Aggregate(ref kind, ref places)) = stmt.kind
1965 if let AggregateKind::Closure(def_id, _) = **kind {
1966 debug!("find_closure_borrow_span: found closure {:?}", places);
1968 return if let Some(node_id) = self.infcx.tcx.hir.as_local_node_id(def_id) {
1969 let args_span = if let Closure(_, _, _, span, _) =
1970 self.infcx.tcx.hir.expect_expr(node_id).node
1974 return OtherUse(use_span);
1979 .with_freevars(node_id, |freevars| {
1980 for (v, place) in freevars.iter().zip(places) {
1982 Operand::Copy(Place::Local(l))
1983 | Operand::Move(Place::Local(l)) if local == l =>
1986 "find_closure_borrow_span: found captured local \
1990 return Some(v.span);
1997 .map(|var_span| ClosureUse {
2001 .unwrap_or(OtherUse(use_span))
2008 if use_span != stmt.source_info.span {
2016 /// Helper to retrieve span(s) of given borrow from the current MIR
2018 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans {
2019 let span = self.mir.source_info(borrow.reserve_location).span;
2020 self.borrow_spans(span, borrow.reserve_location)