1 //! Print diagnostics to explain why values are borrowed.
3 use std::collections::VecDeque;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::{Applicability, Diagnostic};
7 use rustc_index::vec::IndexVec;
8 use rustc_infer::infer::NllRegionVariableOrigin;
9 use rustc_middle::mir::{
10 Body, CastKind, ConstraintCategory, FakeReadCause, Local, Location, Operand, Place, Rvalue,
11 Statement, StatementKind, TerminatorKind,
13 use rustc_middle::ty::adjustment::PointerCast;
14 use rustc_middle::ty::{self, RegionVid, TyCtxt};
15 use rustc_span::symbol::{kw, Symbol};
16 use rustc_span::{sym, DesugaringKind, Span};
18 use crate::region_infer::BlameConstraint;
20 borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt,
24 use super::{find_use, RegionName, UseSpans};
27 pub(crate) enum BorrowExplanation<'tcx> {
28 UsedLater(LaterUseKind, Span, Option<Span>),
29 UsedLaterInLoop(LaterUseKind, Span, Option<Span>),
30 UsedLaterWhenDropped {
33 should_note_order: bool,
36 category: ConstraintCategory<'tcx>,
39 region_name: RegionName,
40 opt_place_desc: Option<String>,
45 #[derive(Clone, Copy, Debug)]
46 pub(crate) enum LaterUseKind {
54 impl<'tcx> BorrowExplanation<'tcx> {
55 pub(crate) fn is_explained(&self) -> bool {
56 !matches!(self, BorrowExplanation::Unexplained)
58 pub(crate) fn add_explanation_to_diagnostic(
62 local_names: &IndexVec<Local, Option<Symbol>>,
65 borrow_span: Option<Span>,
66 multiple_borrow_span: Option<(Span, Span)>,
69 BorrowExplanation::UsedLater(later_use_kind, var_or_use_span, path_span) => {
70 let message = match later_use_kind {
71 LaterUseKind::TraitCapture => "captured here by trait object",
72 LaterUseKind::ClosureCapture => "captured here by closure",
73 LaterUseKind::Call => "used by call",
74 LaterUseKind::FakeLetRead => "stored here",
75 LaterUseKind::Other => "used here",
77 // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
78 if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) {
79 if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
82 format!("{}borrow later {}", borrow_desc, message),
86 // path_span must be `Some` as otherwise the if condition is true
87 let path_span = path_span.unwrap();
88 // path_span is only present in the case of closure capture
89 assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
90 if !borrow_span.map_or(false, |sp| sp.overlaps(var_or_use_span)) {
91 let path_label = "used here by closure";
92 let capture_kind_label = message;
95 format!("{}borrow later {}", borrow_desc, capture_kind_label),
97 err.span_label(path_span, path_label);
101 BorrowExplanation::UsedLaterInLoop(later_use_kind, var_or_use_span, path_span) => {
102 let message = match later_use_kind {
103 LaterUseKind::TraitCapture => {
104 "borrow captured here by trait object, in later iteration of loop"
106 LaterUseKind::ClosureCapture => {
107 "borrow captured here by closure, in later iteration of loop"
109 LaterUseKind::Call => "borrow used by call, in later iteration of loop",
110 LaterUseKind::FakeLetRead => "borrow later stored here",
111 LaterUseKind::Other => "borrow used here, in later iteration of loop",
113 // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
114 if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) {
115 err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
117 // path_span must be `Some` as otherwise the if condition is true
118 let path_span = path_span.unwrap();
119 // path_span is only present in the case of closure capture
120 assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
121 if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
122 let path_label = "used here by closure";
123 let capture_kind_label = message;
126 format!("{}borrow later {}", borrow_desc, capture_kind_label),
128 err.span_label(path_span, path_label);
132 BorrowExplanation::UsedLaterWhenDropped {
137 let local_decl = &body.local_decls[dropped_local];
138 let mut ty = local_decl.ty;
139 if local_decl.source_info.span.desugaring_kind() == Some(DesugaringKind::ForLoop) {
140 if let ty::Adt(adt, substs) = local_decl.ty.kind() {
141 if tcx.is_diagnostic_item(sym::Option, adt.did()) {
142 // in for loop desugaring, only look at the `Some(..)` inner type
143 ty = substs.type_at(0);
147 let (dtor_desc, type_desc) = match ty.kind() {
148 // If type is an ADT that implements Drop, then
149 // simplify output by reporting just the ADT name.
150 ty::Adt(adt, _substs) if adt.has_dtor(tcx) && !adt.is_box() => {
151 ("`Drop` code", format!("type `{}`", tcx.def_path_str(adt.did())))
154 // Otherwise, just report the whole type (and use
155 // the intentionally fuzzy phrase "destructor")
156 ty::Closure(..) => ("destructor", "closure".to_owned()),
157 ty::Generator(..) => ("destructor", "generator".to_owned()),
159 _ => ("destructor", format!("type `{}`", local_decl.ty)),
162 match local_names[dropped_local] {
163 Some(local_name) if !local_decl.from_compiler_desugaring() => {
164 let message = format!(
165 "{B}borrow might be used here, when `{LOC}` is dropped \
166 and runs the {DTOR} for {TYPE}",
172 err.span_label(body.source_info(drop_loc).span, message);
174 if should_note_order {
176 "values in a scope are dropped \
177 in the opposite order they are defined",
183 local_decl.source_info.span,
185 "a temporary with access to the {B}borrow \
186 is created here ...",
190 let message = format!(
191 "... and the {B}borrow might be used here, \
192 when that temporary is dropped \
193 and runs the {DTOR} for {TYPE}",
198 err.span_label(body.source_info(drop_loc).span, message);
200 if let Some(info) = &local_decl.is_block_tail {
201 if info.tail_result_is_ignored {
202 // #85581: If the first mutable borrow's scope contains
203 // the second borrow, this suggestion isn't helpful.
204 if !multiple_borrow_span
206 old.to(info.span.shrink_to_hi()).contains(new)
210 err.span_suggestion_verbose(
211 info.span.shrink_to_hi(),
212 "consider adding semicolon after the expression so its \
213 temporaries are dropped sooner, before the local variables \
214 declared by the block are dropped",
216 Applicability::MaybeIncorrect,
221 "the temporary is part of an expression at the end of a \
222 block;\nconsider forcing this temporary to be dropped sooner, \
223 before the block's local variables are dropped",
225 err.multipart_suggestion(
226 "for example, you could save the expression's value in a new \
227 local variable `x` and then make `x` be the expression at the \
230 (info.span.shrink_to_lo(), "let x = ".to_string()),
231 (info.span.shrink_to_hi(), "; x".to_string()),
233 Applicability::MaybeIncorrect,
240 BorrowExplanation::MustBeValidFor {
247 region_name.highlight_region_name(err);
249 if let Some(desc) = opt_place_desc {
253 "{}requires that `{}` is borrowed for `{}`",
254 category.description(),
263 "{}requires that {}borrow lasts for `{}`",
264 category.description(),
271 self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name);
277 fn add_lifetime_bound_suggestion_to_diagnostic(
279 err: &mut Diagnostic,
280 category: &ConstraintCategory<'tcx>,
282 region_name: &RegionName,
284 if !span.is_desugaring(DesugaringKind::OpaqueTy) {
287 if let ConstraintCategory::OpaqueType = category {
288 let suggestable_name =
289 if region_name.was_named() { region_name.name } else { kw::UnderscoreLifetime };
292 "you can add a bound to the {}to make it last less than `'static` and match `{}`",
293 category.description(),
297 err.span_suggestion_verbose(
300 format!(" + {}", suggestable_name),
301 Applicability::Unspecified,
307 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
308 fn free_region_constraint_info(
310 borrow_region: RegionVid,
311 outlived_region: RegionVid,
312 ) -> (ConstraintCategory<'tcx>, bool, Span, Option<RegionName>) {
313 let BlameConstraint { category, from_closure, cause, variance_info: _ } = self
315 .best_blame_constraint(borrow_region, NllRegionVariableOrigin::FreeRegion, |r| {
316 self.regioncx.provides_universal_region(r, borrow_region, outlived_region)
319 let outlived_fr_name = self.give_region_a_name(outlived_region);
321 (category, from_closure, cause.span, outlived_fr_name)
324 /// Returns structured explanation for *why* the borrow contains the
325 /// point from `location`. This is key for the "3-point errors"
326 /// [described in the NLL RFC][d].
330 /// - `borrow`: the borrow in question
331 /// - `location`: where the borrow occurs
332 /// - `kind_place`: if Some, this describes the statement that triggered the error.
333 /// - first half is the kind of write, if any, being performed
334 /// - second half is the place being accessed
336 /// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points
337 #[instrument(level = "debug", skip(self))]
338 pub(crate) fn explain_why_borrow_contains_point(
341 borrow: &BorrowData<'tcx>,
342 kind_place: Option<(WriteKind, Place<'tcx>)>,
343 ) -> BorrowExplanation<'tcx> {
344 let regioncx = &self.regioncx;
345 let body: &Body<'_> = &self.body;
346 let tcx = self.infcx.tcx;
348 let borrow_region_vid = borrow.region;
349 debug!(?borrow_region_vid);
351 let region_sub = self.regioncx.find_sub_region_live_at(borrow_region_vid, location);
354 match find_use::find(body, regioncx, tcx, region_sub, location) {
355 Some(Cause::LiveVar(local, location)) => {
356 let span = body.source_info(location).span;
358 .move_spans(Place::from(local).as_ref(), location)
359 .or_else(|| self.borrow_spans(span, location));
361 let borrow_location = location;
362 if self.is_use_in_later_iteration_of_loop(borrow_location, location) {
363 let later_use = self.later_use_kind(borrow, spans, location);
364 BorrowExplanation::UsedLaterInLoop(later_use.0, later_use.1, later_use.2)
366 // Check if the location represents a `FakeRead`, and adapt the error
367 // message to the `FakeReadCause` it is from: in particular,
368 // the ones inserted in optimized `let var = <expr>` patterns.
369 let later_use = self.later_use_kind(borrow, spans, location);
370 BorrowExplanation::UsedLater(later_use.0, later_use.1, later_use.2)
374 Some(Cause::DropVar(local, location)) => {
375 let mut should_note_order = false;
376 if self.local_names[local].is_some()
377 && let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place
378 && let Some(borrowed_local) = place.as_local()
379 && self.local_names[borrowed_local].is_some() && local != borrowed_local
381 should_note_order = true;
384 BorrowExplanation::UsedLaterWhenDropped {
386 dropped_local: local,
392 if let Some(region) = self.to_error_region_vid(borrow_region_vid) {
393 let (category, from_closure, span, region_name) =
394 self.free_region_constraint_info(borrow_region_vid, region);
395 if let Some(region_name) = region_name {
396 let opt_place_desc = self.describe_place(borrow.borrowed_place.as_ref());
397 BorrowExplanation::MustBeValidFor {
405 debug!("Could not generate a region name");
406 BorrowExplanation::Unexplained
409 debug!("Could not generate an error region vid");
410 BorrowExplanation::Unexplained
416 /// true if `borrow_location` can reach `use_location` by going through a loop and
417 /// `use_location` is also inside of that loop
418 fn is_use_in_later_iteration_of_loop(
420 borrow_location: Location,
421 use_location: Location,
423 let back_edge = self.reach_through_backedge(borrow_location, use_location);
424 back_edge.map_or(false, |back_edge| self.can_reach_head_of_loop(use_location, back_edge))
427 /// Returns the outmost back edge if `from` location can reach `to` location passing through
429 fn reach_through_backedge(&self, from: Location, to: Location) -> Option<Location> {
430 let mut visited_locations = FxHashSet::default();
431 let mut pending_locations = VecDeque::new();
432 visited_locations.insert(from);
433 pending_locations.push_back(from);
434 debug!("reach_through_backedge: from={:?} to={:?}", from, to,);
436 let mut outmost_back_edge = None;
437 while let Some(location) = pending_locations.pop_front() {
439 "reach_through_backedge: location={:?} outmost_back_edge={:?}
440 pending_locations={:?} visited_locations={:?}",
441 location, outmost_back_edge, pending_locations, visited_locations
444 if location == to && outmost_back_edge.is_some() {
445 // We've managed to reach the use location
446 debug!("reach_through_backedge: found!");
447 return outmost_back_edge;
450 let block = &self.body.basic_blocks[location.block];
452 if location.statement_index < block.statements.len() {
453 let successor = location.successor_within_block();
454 if visited_locations.insert(successor) {
455 pending_locations.push_back(successor);
458 pending_locations.extend(
462 .map(|bb| Location { statement_index: 0, block: bb })
463 .filter(|s| visited_locations.insert(*s))
465 if self.is_back_edge(location, s) {
466 match outmost_back_edge {
468 outmost_back_edge = Some(location);
472 if location.dominates(back_edge, &self.dominators) =>
474 outmost_back_edge = Some(location);
490 /// true if `from` location can reach `loop_head` location and `loop_head` dominates all the
491 /// intermediate nodes
492 fn can_reach_head_of_loop(&self, from: Location, loop_head: Location) -> bool {
493 self.find_loop_head_dfs(from, loop_head, &mut FxHashSet::default())
496 fn find_loop_head_dfs(
500 visited_locations: &mut FxHashSet<Location>,
502 visited_locations.insert(from);
504 if from == loop_head {
508 if loop_head.dominates(from, &self.dominators) {
509 let block = &self.body.basic_blocks[from.block];
511 if from.statement_index < block.statements.len() {
512 let successor = from.successor_within_block();
514 if !visited_locations.contains(&successor)
515 && self.find_loop_head_dfs(successor, loop_head, visited_locations)
520 for bb in block.terminator().successors() {
521 let successor = Location { statement_index: 0, block: bb };
523 if !visited_locations.contains(&successor)
524 && self.find_loop_head_dfs(successor, loop_head, visited_locations)
535 /// True if an edge `source -> target` is a backedge -- in other words, if the target
536 /// dominates the source.
537 fn is_back_edge(&self, source: Location, target: Location) -> bool {
538 target.dominates(source, &self.dominators)
541 /// Determine how the borrow was later used.
542 /// First span returned points to the location of the conflicting use
543 /// Second span if `Some` is returned in the case of closures and points
544 /// to the use of the path
547 borrow: &BorrowData<'tcx>,
548 use_spans: UseSpans<'tcx>,
550 ) -> (LaterUseKind, Span, Option<Span>) {
552 UseSpans::ClosureUse { capture_kind_span, path_span, .. } => {
553 // Used in a closure.
554 (LaterUseKind::ClosureCapture, capture_kind_span, Some(path_span))
556 UseSpans::PatUse(span)
557 | UseSpans::OtherUse(span)
558 | UseSpans::FnSelfUse { var_span: span, .. } => {
559 let block = &self.body.basic_blocks[location.block];
561 let kind = if let Some(&Statement {
562 kind: StatementKind::FakeRead(box (FakeReadCause::ForLet(_), _)),
564 }) = block.statements.get(location.statement_index)
566 LaterUseKind::FakeLetRead
567 } else if self.was_captured_by_trait_object(borrow) {
568 LaterUseKind::TraitCapture
569 } else if location.statement_index == block.statements.len() {
570 if let TerminatorKind::Call { ref func, from_hir_call: true, .. } =
571 block.terminator().kind
573 // Just point to the function, to reduce the chance of overlapping spans.
574 let function_span = match func {
575 Operand::Constant(c) => c.span,
576 Operand::Copy(place) | Operand::Move(place) => {
577 if let Some(l) = place.as_local() {
578 let local_decl = &self.body.local_decls[l];
579 if self.local_names[l].is_none() {
580 local_decl.source_info.span
589 return (LaterUseKind::Call, function_span, None);
602 /// Checks if a borrowed value was captured by a trait object. We do this by
603 /// looking forward in the MIR from the reserve location and checking if we see
604 /// an unsized cast to a trait object on our data.
605 fn was_captured_by_trait_object(&self, borrow: &BorrowData<'tcx>) -> bool {
606 // Start at the reserve location, find the place that we want to see cast to a trait object.
607 let location = borrow.reserve_location;
608 let block = &self.body[location.block];
609 let stmt = block.statements.get(location.statement_index);
610 debug!("was_captured_by_trait_object: location={:?} stmt={:?}", location, stmt);
612 // We make a `queue` vector that has the locations we want to visit. As of writing, this
613 // will only ever have one item at any given time, but by using a vector, we can pop from
614 // it which simplifies the termination logic.
615 let mut queue = vec![location];
616 let mut target = if let Some(&Statement {
617 kind: StatementKind::Assign(box (ref place, _)),
621 if let Some(local) = place.as_local() {
630 debug!("was_captured_by_trait: target={:?} queue={:?}", target, queue);
631 while let Some(current_location) = queue.pop() {
632 debug!("was_captured_by_trait: target={:?}", target);
633 let block = &self.body[current_location.block];
634 // We need to check the current location to find out if it is a terminator.
635 let is_terminator = current_location.statement_index == block.statements.len();
637 let stmt = &block.statements[current_location.statement_index];
638 debug!("was_captured_by_trait_object: stmt={:?}", stmt);
640 // The only kind of statement that we care about is assignments...
641 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind {
642 let Some(into) = place.local_or_deref_local() else {
643 // Continue at the next location.
644 queue.push(current_location.successor_within_block());
649 // If we see a use, we should check whether it is our data, and if so
650 // update the place that we're looking for to that new place.
651 Rvalue::Use(operand) => match operand {
652 Operand::Copy(place) | Operand::Move(place) => {
653 if let Some(from) = place.as_local() {
661 // If we see an unsized cast, then if it is our data we should check
662 // whether it is being cast to a trait object.
663 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, ty) => {
665 Operand::Copy(place) | Operand::Move(place) => {
666 if let Some(from) = place.as_local() {
668 debug!("was_captured_by_trait_object: ty={:?}", ty);
669 // Check the type for a trait object.
670 return match ty.kind() {
672 ty::Ref(_, ty, _) if ty.is_trait() => true,
674 _ if ty.is_box() && ty.boxed_ty().is_trait() => {
678 _ if ty.is_trait() => true,
693 // Continue at the next location.
694 queue.push(current_location.successor_within_block());
696 // The only thing we need to do for terminators is progress to the next block.
697 let terminator = block.terminator();
698 debug!("was_captured_by_trait_object: terminator={:?}", terminator);
700 if let TerminatorKind::Call { destination, target: Some(block), args, .. } =
703 if let Some(dest) = destination.as_local() {
705 "was_captured_by_trait_object: target={:?} dest={:?} args={:?}",
708 // Check if one of the arguments to this function is the target place.
709 let found_target = args.iter().any(|arg| {
710 if let Operand::Move(place) = arg {
711 if let Some(potential) = place.as_local() {
721 // If it is, follow this to the next block and update the target.
724 queue.push(block.start_location());
730 debug!("was_captured_by_trait: queue={:?}", queue);
733 // We didn't find anything and ran out of locations to check.