1 //! Print diagnostics to explain why values are borrowed.
3 use rustc_errors::{Applicability, Diagnostic};
4 use rustc_index::vec::IndexVec;
5 use rustc_infer::infer::NllRegionVariableOrigin;
6 use rustc_middle::mir::{
7 Body, CastKind, ConstraintCategory, FakeReadCause, Local, Location, Operand, Place, Rvalue,
8 Statement, StatementKind, TerminatorKind,
10 use rustc_middle::ty::adjustment::PointerCast;
11 use rustc_middle::ty::{self, RegionVid, TyCtxt};
12 use rustc_span::symbol::{kw, Symbol};
13 use rustc_span::{sym, DesugaringKind, Span};
15 use crate::region_infer::{BlameConstraint, ExtraConstraintInfo};
17 borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt,
21 use super::{find_use, RegionName, UseSpans};
24 pub(crate) enum BorrowExplanation<'tcx> {
25 UsedLater(LaterUseKind, Span, Option<Span>),
26 UsedLaterInLoop(LaterUseKind, Span, Option<Span>),
27 UsedLaterWhenDropped {
30 should_note_order: bool,
33 category: ConstraintCategory<'tcx>,
36 region_name: RegionName,
37 opt_place_desc: Option<String>,
38 extra_info: Vec<ExtraConstraintInfo>,
43 #[derive(Clone, Copy, Debug)]
44 pub(crate) enum LaterUseKind {
52 impl<'tcx> BorrowExplanation<'tcx> {
53 pub(crate) fn is_explained(&self) -> bool {
54 !matches!(self, BorrowExplanation::Unexplained)
56 pub(crate) fn add_explanation_to_diagnostic(
60 local_names: &IndexVec<Local, Option<Symbol>>,
63 borrow_span: Option<Span>,
64 multiple_borrow_span: Option<(Span, Span)>,
67 BorrowExplanation::UsedLater(later_use_kind, var_or_use_span, path_span) => {
68 let message = match later_use_kind {
69 LaterUseKind::TraitCapture => "captured here by trait object",
70 LaterUseKind::ClosureCapture => "captured here by closure",
71 LaterUseKind::Call => "used by call",
72 LaterUseKind::FakeLetRead => "stored here",
73 LaterUseKind::Other => "used here",
75 // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
76 if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) {
77 if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
80 format!("{borrow_desc}borrow later {message}"),
84 // path_span must be `Some` as otherwise the if condition is true
85 let path_span = path_span.unwrap();
86 // path_span is only present in the case of closure capture
87 assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
88 if !borrow_span.map_or(false, |sp| sp.overlaps(var_or_use_span)) {
89 let path_label = "used here by closure";
90 let capture_kind_label = message;
93 format!("{borrow_desc}borrow later {capture_kind_label}"),
95 err.span_label(path_span, path_label);
99 BorrowExplanation::UsedLaterInLoop(later_use_kind, var_or_use_span, path_span) => {
100 let message = match later_use_kind {
101 LaterUseKind::TraitCapture => {
102 "borrow captured here by trait object, in later iteration of loop"
104 LaterUseKind::ClosureCapture => {
105 "borrow captured here by closure, in later iteration of loop"
107 LaterUseKind::Call => "borrow used by call, in later iteration of loop",
108 LaterUseKind::FakeLetRead => "borrow later stored here",
109 LaterUseKind::Other => "borrow used here, in later iteration of loop",
111 // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
112 if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) {
113 err.span_label(var_or_use_span, format!("{borrow_desc}{message}"));
115 // path_span must be `Some` as otherwise the if condition is true
116 let path_span = path_span.unwrap();
117 // path_span is only present in the case of closure capture
118 assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
119 if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
120 let path_label = "used here by closure";
121 let capture_kind_label = message;
124 format!("{borrow_desc}borrow later {capture_kind_label}"),
126 err.span_label(path_span, path_label);
130 BorrowExplanation::UsedLaterWhenDropped {
135 let local_decl = &body.local_decls[dropped_local];
136 let mut ty = local_decl.ty;
137 if local_decl.source_info.span.desugaring_kind() == Some(DesugaringKind::ForLoop) {
138 if let ty::Adt(adt, substs) = local_decl.ty.kind() {
139 if tcx.is_diagnostic_item(sym::Option, adt.did()) {
140 // in for loop desugaring, only look at the `Some(..)` inner type
141 ty = substs.type_at(0);
145 let (dtor_desc, type_desc) = match ty.kind() {
146 // If type is an ADT that implements Drop, then
147 // simplify output by reporting just the ADT name.
148 ty::Adt(adt, _substs) if adt.has_dtor(tcx) && !adt.is_box() => {
149 ("`Drop` code", format!("type `{}`", tcx.def_path_str(adt.did())))
152 // Otherwise, just report the whole type (and use
153 // the intentionally fuzzy phrase "destructor")
154 ty::Closure(..) => ("destructor", "closure".to_owned()),
155 ty::Generator(..) => ("destructor", "generator".to_owned()),
157 _ => ("destructor", format!("type `{}`", local_decl.ty)),
160 match local_names[dropped_local] {
161 Some(local_name) if !local_decl.from_compiler_desugaring() => {
162 let message = format!(
163 "{borrow_desc}borrow might be used here, when `{local_name}` is dropped \
164 and runs the {dtor_desc} for {type_desc}",
166 err.span_label(body.source_info(drop_loc).span, message);
168 if should_note_order {
170 "values in a scope are dropped \
171 in the opposite order they are defined",
177 local_decl.source_info.span,
179 "a temporary with access to the {borrow_desc}borrow \
180 is created here ...",
183 let message = format!(
184 "... and the {borrow_desc}borrow might be used here, \
185 when that temporary is dropped \
186 and runs the {dtor_desc} for {type_desc}",
188 err.span_label(body.source_info(drop_loc).span, message);
190 if let Some(info) = &local_decl.is_block_tail {
191 if info.tail_result_is_ignored {
192 // #85581: If the first mutable borrow's scope contains
193 // the second borrow, this suggestion isn't helpful.
194 if !multiple_borrow_span
196 old.to(info.span.shrink_to_hi()).contains(new)
200 err.span_suggestion_verbose(
201 info.span.shrink_to_hi(),
202 "consider adding semicolon after the expression so its \
203 temporaries are dropped sooner, before the local variables \
204 declared by the block are dropped",
206 Applicability::MaybeIncorrect,
211 "the temporary is part of an expression at the end of a \
212 block;\nconsider forcing this temporary to be dropped sooner, \
213 before the block's local variables are dropped",
215 err.multipart_suggestion(
216 "for example, you could save the expression's value in a new \
217 local variable `x` and then make `x` be the expression at the \
220 (info.span.shrink_to_lo(), "let x = ".to_string()),
221 (info.span.shrink_to_hi(), "; x".to_string()),
223 Applicability::MaybeIncorrect,
230 BorrowExplanation::MustBeValidFor {
238 region_name.highlight_region_name(err);
240 if let Some(desc) = opt_place_desc {
244 "{}requires that `{desc}` is borrowed for `{region_name}`",
245 category.description(),
252 "{}requires that {borrow_desc}borrow lasts for `{region_name}`",
253 category.description(),
258 for extra in extra_info {
260 ExtraConstraintInfo::PlaceholderFromPredicate(span) => {
261 err.span_note(*span, "due to current limitations in the borrow checker, this implies a `'static` lifetime");
266 self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name);
272 fn add_lifetime_bound_suggestion_to_diagnostic(
274 err: &mut Diagnostic,
275 category: &ConstraintCategory<'tcx>,
277 region_name: &RegionName,
279 if !span.is_desugaring(DesugaringKind::OpaqueTy) {
282 if let ConstraintCategory::OpaqueType = category {
283 let suggestable_name =
284 if region_name.was_named() { region_name.name } else { kw::UnderscoreLifetime };
287 "you can add a bound to the {}to make it last less than `'static` and match `{region_name}`",
288 category.description(),
291 err.span_suggestion_verbose(
294 format!(" + {suggestable_name}"),
295 Applicability::Unspecified,
301 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
302 fn free_region_constraint_info(
304 borrow_region: RegionVid,
305 outlived_region: RegionVid,
306 ) -> (ConstraintCategory<'tcx>, bool, Span, Option<RegionName>, Vec<ExtraConstraintInfo>) {
307 let (blame_constraint, extra_info) = self.regioncx.best_blame_constraint(
309 NllRegionVariableOrigin::FreeRegion,
310 |r| self.regioncx.provides_universal_region(r, borrow_region, outlived_region),
312 let BlameConstraint { category, from_closure, cause, .. } = blame_constraint;
314 let outlived_fr_name = self.give_region_a_name(outlived_region);
316 (category, from_closure, cause.span, outlived_fr_name, extra_info)
319 /// Returns structured explanation for *why* the borrow contains the
320 /// point from `location`. This is key for the "3-point errors"
321 /// [described in the NLL RFC][d].
325 /// - `borrow`: the borrow in question
326 /// - `location`: where the borrow occurs
327 /// - `kind_place`: if Some, this describes the statement that triggered the error.
328 /// - first half is the kind of write, if any, being performed
329 /// - second half is the place being accessed
331 /// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points
332 #[instrument(level = "debug", skip(self))]
333 pub(crate) fn explain_why_borrow_contains_point(
336 borrow: &BorrowData<'tcx>,
337 kind_place: Option<(WriteKind, Place<'tcx>)>,
338 ) -> BorrowExplanation<'tcx> {
339 let regioncx = &self.regioncx;
340 let body: &Body<'_> = &self.body;
341 let tcx = self.infcx.tcx;
343 let borrow_region_vid = borrow.region;
344 debug!(?borrow_region_vid);
346 let mut region_sub = self.regioncx.find_sub_region_live_at(borrow_region_vid, location);
349 let mut use_location = location;
350 let mut use_in_later_iteration_of_loop = false;
352 if region_sub == borrow_region_vid {
353 // When `region_sub` is the same as `borrow_region_vid` (the location where the borrow is
354 // issued is the same location that invalidates the reference), this is likely a loop iteration
355 // - in this case, try using the loop terminator location in `find_sub_region_live_at`.
356 if let Some(loop_terminator_location) =
357 regioncx.find_loop_terminator_location(borrow.region, body)
361 .find_sub_region_live_at(borrow_region_vid, loop_terminator_location);
362 debug!("explain_why_borrow_contains_point: region_sub in loop={:?}", region_sub);
363 use_location = loop_terminator_location;
364 use_in_later_iteration_of_loop = true;
368 match find_use::find(body, regioncx, tcx, region_sub, use_location) {
369 Some(Cause::LiveVar(local, location)) => {
370 let span = body.source_info(location).span;
372 .move_spans(Place::from(local).as_ref(), location)
373 .or_else(|| self.borrow_spans(span, location));
375 if use_in_later_iteration_of_loop {
376 let later_use = self.later_use_kind(borrow, spans, use_location);
377 BorrowExplanation::UsedLaterInLoop(later_use.0, later_use.1, later_use.2)
379 // Check if the location represents a `FakeRead`, and adapt the error
380 // message to the `FakeReadCause` it is from: in particular,
381 // the ones inserted in optimized `let var = <expr>` patterns.
382 let later_use = self.later_use_kind(borrow, spans, location);
383 BorrowExplanation::UsedLater(later_use.0, later_use.1, later_use.2)
387 Some(Cause::DropVar(local, location)) => {
388 let mut should_note_order = false;
389 if self.local_names[local].is_some()
390 && let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place
391 && let Some(borrowed_local) = place.as_local()
392 && self.local_names[borrowed_local].is_some() && local != borrowed_local
394 should_note_order = true;
397 BorrowExplanation::UsedLaterWhenDropped {
399 dropped_local: local,
405 if let Some(region) = self.to_error_region_vid(borrow_region_vid) {
406 let (category, from_closure, span, region_name, extra_info) =
407 self.free_region_constraint_info(borrow_region_vid, region);
408 if let Some(region_name) = region_name {
409 let opt_place_desc = self.describe_place(borrow.borrowed_place.as_ref());
410 BorrowExplanation::MustBeValidFor {
419 debug!("Could not generate a region name");
420 BorrowExplanation::Unexplained
423 debug!("Could not generate an error region vid");
424 BorrowExplanation::Unexplained
430 /// Determine how the borrow was later used.
431 /// First span returned points to the location of the conflicting use
432 /// Second span if `Some` is returned in the case of closures and points
433 /// to the use of the path
434 #[instrument(level = "debug", skip(self))]
437 borrow: &BorrowData<'tcx>,
438 use_spans: UseSpans<'tcx>,
440 ) -> (LaterUseKind, Span, Option<Span>) {
442 UseSpans::ClosureUse { capture_kind_span, path_span, .. } => {
443 // Used in a closure.
444 (LaterUseKind::ClosureCapture, capture_kind_span, Some(path_span))
446 UseSpans::PatUse(span)
447 | UseSpans::OtherUse(span)
448 | UseSpans::FnSelfUse { var_span: span, .. } => {
449 let block = &self.body.basic_blocks[location.block];
451 let kind = if let Some(&Statement {
452 kind: StatementKind::FakeRead(box (FakeReadCause::ForLet(_), place)),
454 }) = block.statements.get(location.statement_index)
456 if let Some(l) = place.as_local()
457 && let local_decl = &self.body.local_decls[l]
458 && local_decl.ty.is_closure()
460 LaterUseKind::ClosureCapture
462 LaterUseKind::FakeLetRead
464 } else if self.was_captured_by_trait_object(borrow) {
465 LaterUseKind::TraitCapture
466 } else if location.statement_index == block.statements.len() {
467 if let TerminatorKind::Call { func, from_hir_call: true, .. } =
468 &block.terminator().kind
470 // Just point to the function, to reduce the chance of overlapping spans.
471 let function_span = match func {
472 Operand::Constant(c) => c.span,
473 Operand::Copy(place) | Operand::Move(place) => {
474 if let Some(l) = place.as_local() {
475 let local_decl = &self.body.local_decls[l];
476 if self.local_names[l].is_none() {
477 local_decl.source_info.span
486 return (LaterUseKind::Call, function_span, None);
499 /// Checks if a borrowed value was captured by a trait object. We do this by
500 /// looking forward in the MIR from the reserve location and checking if we see
501 /// an unsized cast to a trait object on our data.
502 fn was_captured_by_trait_object(&self, borrow: &BorrowData<'tcx>) -> bool {
503 // Start at the reserve location, find the place that we want to see cast to a trait object.
504 let location = borrow.reserve_location;
505 let block = &self.body[location.block];
506 let stmt = block.statements.get(location.statement_index);
507 debug!("was_captured_by_trait_object: location={:?} stmt={:?}", location, stmt);
509 // We make a `queue` vector that has the locations we want to visit. As of writing, this
510 // will only ever have one item at any given time, but by using a vector, we can pop from
511 // it which simplifies the termination logic.
512 let mut queue = vec![location];
514 if let Some(Statement { kind: StatementKind::Assign(box (place, _)), .. }) = stmt {
515 if let Some(local) = place.as_local() {
524 debug!("was_captured_by_trait: target={:?} queue={:?}", target, queue);
525 while let Some(current_location) = queue.pop() {
526 debug!("was_captured_by_trait: target={:?}", target);
527 let block = &self.body[current_location.block];
528 // We need to check the current location to find out if it is a terminator.
529 let is_terminator = current_location.statement_index == block.statements.len();
531 let stmt = &block.statements[current_location.statement_index];
532 debug!("was_captured_by_trait_object: stmt={:?}", stmt);
534 // The only kind of statement that we care about is assignments...
535 if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind {
536 let Some(into) = place.local_or_deref_local() else {
537 // Continue at the next location.
538 queue.push(current_location.successor_within_block());
543 // If we see a use, we should check whether it is our data, and if so
544 // update the place that we're looking for to that new place.
545 Rvalue::Use(operand) => match operand {
546 Operand::Copy(place) | Operand::Move(place) => {
547 if let Some(from) = place.as_local() {
555 // If we see an unsized cast, then if it is our data we should check
556 // whether it is being cast to a trait object.
557 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, ty) => {
559 Operand::Copy(place) | Operand::Move(place) => {
560 if let Some(from) = place.as_local() {
562 debug!("was_captured_by_trait_object: ty={:?}", ty);
563 // Check the type for a trait object.
564 return match ty.kind() {
566 ty::Ref(_, ty, _) if ty.is_trait() => true,
568 _ if ty.is_box() && ty.boxed_ty().is_trait() => {
572 _ if ty.is_trait() => true,
587 // Continue at the next location.
588 queue.push(current_location.successor_within_block());
590 // The only thing we need to do for terminators is progress to the next block.
591 let terminator = block.terminator();
592 debug!("was_captured_by_trait_object: terminator={:?}", terminator);
594 if let TerminatorKind::Call { destination, target: Some(block), args, .. } =
597 if let Some(dest) = destination.as_local() {
599 "was_captured_by_trait_object: target={:?} dest={:?} args={:?}",
602 // Check if one of the arguments to this function is the target place.
603 let found_target = args.iter().any(|arg| {
604 if let Operand::Move(place) = arg {
605 if let Some(potential) = place.as_local() {
615 // If it is, follow this to the next block and update the target.
618 queue.push(block.start_location());
624 debug!("was_captured_by_trait: queue={:?}", queue);
627 // We didn't find anything and ran out of locations to check.