1 use crate::borrow_check::borrow_set::BorrowData;
2 use crate::borrow_check::error_reporting::UseSpans;
3 use crate::borrow_check::nll::ConstraintDescription;
4 use crate::borrow_check::nll::region_infer::{Cause, RegionName};
5 use crate::borrow_check::{Context, MirBorrowckCtxt, WriteKind};
6 use rustc::ty::{self, TyCtxt};
8 CastKind, ConstraintCategory, FakeReadCause, Local, Location, Mir, Operand,
9 Place, Projection, ProjectionElem, Rvalue, Statement, StatementKind,
12 use rustc_errors::DiagnosticBuilder;
17 pub(in crate::borrow_check) enum BorrowExplanation {
18 UsedLater(LaterUseKind, Span),
19 UsedLaterInLoop(LaterUseKind, Span),
20 UsedLaterWhenDropped {
23 should_note_order: bool,
26 category: ConstraintCategory,
29 region_name: RegionName,
30 opt_place_desc: Option<String>,
35 #[derive(Clone, Copy)]
36 pub(in crate::borrow_check) enum LaterUseKind {
44 impl BorrowExplanation {
45 pub(in crate::borrow_check) fn is_explained(&self) -> bool {
47 BorrowExplanation::Unexplained => false,
51 pub(in crate::borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx, 'tcx>(
53 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
55 err: &mut DiagnosticBuilder<'_>,
59 BorrowExplanation::UsedLater(later_use_kind, var_or_use_span) => {
60 let message = match later_use_kind {
61 LaterUseKind::TraitCapture => "borrow later captured here by trait object",
62 LaterUseKind::ClosureCapture => "borrow later captured here by closure",
63 LaterUseKind::Call => "borrow later used by call",
64 LaterUseKind::FakeLetRead => "borrow later stored here",
65 LaterUseKind::Other => "borrow later used here",
67 err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
69 BorrowExplanation::UsedLaterInLoop(later_use_kind, var_or_use_span) => {
70 let message = match later_use_kind {
71 LaterUseKind::TraitCapture =>
72 "borrow captured here by trait object, in later iteration of loop",
73 LaterUseKind::ClosureCapture =>
74 "borrow captured here by closure, in later iteration of loop",
75 LaterUseKind::Call => "borrow used by call, in later iteration of loop",
76 LaterUseKind::FakeLetRead => "borrow later stored here",
77 LaterUseKind::Other => "borrow used here, in later iteration of loop",
79 err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
81 BorrowExplanation::UsedLaterWhenDropped { drop_loc, dropped_local,
82 should_note_order } =>
84 let local_decl = &mir.local_decls[dropped_local];
85 let (dtor_desc, type_desc) = match local_decl.ty.sty {
86 // If type is an ADT that implements Drop, then
87 // simplify output by reporting just the ADT name.
88 ty::Adt(adt, _substs) if adt.has_dtor(tcx) && !adt.is_box() =>
89 ("`Drop` code", format!("type `{}`", tcx.item_path_str(adt.did))),
91 // Otherwise, just report the whole type (and use
92 // the intentionally fuzzy phrase "destructor")
94 ("destructor", "closure".to_owned()),
96 ("destructor", "generator".to_owned()),
98 _ => ("destructor", format!("type `{}`", local_decl.ty)),
101 match local_decl.name {
102 Some(local_name) => {
104 format!("{B}borrow might be used here, when `{LOC}` is dropped \
105 and runs the {DTOR} for {TYPE}",
106 B=borrow_desc, LOC=local_name, TYPE=type_desc, DTOR=dtor_desc);
107 err.span_label(mir.source_info(drop_loc).span, message);
109 if should_note_order {
111 "values in a scope are dropped \
112 in the opposite order they are defined",
117 err.span_label(local_decl.source_info.span,
118 format!("a temporary with access to the {B}borrow \
119 is created here ...",
122 format!("... and the {B}borrow might be used here, \
123 when that temporary is dropped \
124 and runs the {DTOR} for {TYPE}",
125 B=borrow_desc, TYPE=type_desc, DTOR=dtor_desc);
126 err.span_label(mir.source_info(drop_loc).span, message);
128 if let Some(info) = &local_decl.is_block_tail {
129 // FIXME: use span_suggestion instead, highlighting the
130 // whole block tail expression.
131 let msg = if info.tail_result_is_ignored {
132 "The temporary is part of an expression at the end of a block. \
133 Consider adding semicolon after the expression so its temporaries \
134 are dropped sooner, before the local variables declared by the \
137 "The temporary is part of an expression at the end of a block. \
138 Consider forcing this temporary to be dropped sooner, before \
139 the block's local variables are dropped. \
140 For example, you could save the expression's value in a new \
141 local variable `x` and then make `x` be the expression \
142 at the end of the block."
150 BorrowExplanation::MustBeValidFor {
157 region_name.highlight_region_name(err);
159 if let Some(desc) = opt_place_desc {
160 err.span_label(span, format!(
161 "{}requires that `{}` is borrowed for `{}`",
162 category.description(), desc, region_name,
165 err.span_label(span, format!(
166 "{}requires that {}borrow lasts for `{}`",
167 category.description(), borrow_desc, region_name,
176 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
177 /// Returns structured explanation for *why* the borrow contains the
178 /// point from `context`. This is key for the "3-point errors"
179 /// [described in the NLL RFC][d].
183 /// - `borrow`: the borrow in question
184 /// - `context`: where the borrow occurs
185 /// - `kind_place`: if Some, this describes the statement that triggered the error.
186 /// - first half is the kind of write, if any, being performed
187 /// - second half is the place being accessed
189 /// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points
190 pub(in crate::borrow_check) fn explain_why_borrow_contains_point(
193 borrow: &BorrowData<'tcx>,
194 kind_place: Option<(WriteKind, &Place<'tcx>)>,
195 ) -> BorrowExplanation {
197 "explain_why_borrow_contains_point(context={:?}, borrow={:?}, kind_place={:?})",
198 context, borrow, kind_place
201 let regioncx = &self.nonlexical_regioncx;
203 let tcx = self.infcx.tcx;
205 let borrow_region_vid = borrow.region;
207 "explain_why_borrow_contains_point: borrow_region_vid={:?}",
211 let region_sub = regioncx.find_sub_region_live_at(borrow_region_vid, context.loc);
213 "explain_why_borrow_contains_point: region_sub={:?}",
217 match find_use::find(mir, regioncx, tcx, region_sub, context.loc) {
218 Some(Cause::LiveVar(local, location)) => {
219 let span = mir.source_info(location).span;
220 let spans = self.move_spans(&Place::Local(local), location)
221 .or_else(|| self.borrow_spans(span, location));
223 if self.is_borrow_location_in_loop(context.loc) {
224 let later_use = self.later_use_kind(borrow, spans, location);
225 BorrowExplanation::UsedLaterInLoop(later_use.0, later_use.1)
227 // Check if the location represents a `FakeRead`, and adapt the error
228 // message to the `FakeReadCause` it is from: in particular,
229 // the ones inserted in optimized `let var = <expr>` patterns.
230 let later_use = self.later_use_kind(borrow, spans, location);
231 BorrowExplanation::UsedLater(later_use.0, later_use.1)
235 Some(Cause::DropVar(local, location)) => {
236 let mut should_note_order = false;
237 if mir.local_decls[local].name.is_some() {
238 if let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place {
239 if let Place::Local(borrowed_local) = place {
240 let dropped_local_scope = mir.local_decls[local].visibility_scope;
241 let borrowed_local_scope =
242 mir.local_decls[*borrowed_local].visibility_scope;
244 if mir.is_sub_scope(borrowed_local_scope, dropped_local_scope)
245 && local != *borrowed_local
247 should_note_order = true;
253 BorrowExplanation::UsedLaterWhenDropped {
255 dropped_local: local,
260 None => if let Some(region) = regioncx.to_error_region_vid(borrow_region_vid) {
261 let (category, from_closure, span, region_name) = self
263 .free_region_constraint_info(
270 if let Some(region_name) = region_name {
271 let opt_place_desc = self.describe_place(&borrow.borrowed_place);
272 BorrowExplanation::MustBeValidFor {
280 BorrowExplanation::Unexplained
283 BorrowExplanation::Unexplained
288 /// Checks if a borrow location is within a loop.
289 fn is_borrow_location_in_loop(
291 borrow_location: Location,
293 let mut visited_locations = Vec::new();
294 let mut pending_locations = vec![ borrow_location ];
295 debug!("is_in_loop: borrow_location={:?}", borrow_location);
297 while let Some(location) = pending_locations.pop() {
298 debug!("is_in_loop: location={:?} pending_locations={:?} visited_locations={:?}",
299 location, pending_locations, visited_locations);
300 if location == borrow_location && visited_locations.contains(&borrow_location) {
301 // We've managed to return to where we started (and this isn't the start of the
303 debug!("is_in_loop: found!");
307 // Skip locations we've been.
308 if visited_locations.contains(&location) { continue; }
310 let block = &self.mir.basic_blocks()[location.block];
311 if location.statement_index == block.statements.len() {
312 // Add start location of the next blocks to pending locations.
313 match block.terminator().kind {
314 TerminatorKind::Goto { target } => {
315 pending_locations.push(target.start_location());
317 TerminatorKind::SwitchInt { ref targets, .. } => {
318 pending_locations.extend(
319 targets.into_iter().map(|target| target.start_location()));
321 TerminatorKind::Drop { target, unwind, .. } |
322 TerminatorKind::DropAndReplace { target, unwind, .. } |
323 TerminatorKind::Assert { target, cleanup: unwind, .. } |
324 TerminatorKind::Yield { resume: target, drop: unwind, .. } |
325 TerminatorKind::FalseUnwind { real_target: target, unwind, .. } => {
326 pending_locations.push(target.start_location());
327 if let Some(unwind) = unwind {
328 pending_locations.push(unwind.start_location());
331 TerminatorKind::Call { ref destination, cleanup, .. } => {
332 if let Some((_, destination)) = destination {
333 pending_locations.push(destination.start_location());
335 if let Some(cleanup) = cleanup {
336 pending_locations.push(cleanup.start_location());
339 TerminatorKind::FalseEdges { real_target, ref imaginary_targets, .. } => {
340 pending_locations.push(real_target.start_location());
341 pending_locations.extend(
342 imaginary_targets.into_iter().map(|target| target.start_location()));
347 // Add the next statement to pending locations.
348 pending_locations.push(location.successor_within_block());
351 // Keep track of where we have visited.
352 visited_locations.push(location);
358 /// Determine how the borrow was later used.
361 borrow: &BorrowData<'tcx>,
364 ) -> (LaterUseKind, Span) {
366 UseSpans::ClosureUse { var_span, .. } => {
367 // Used in a closure.
368 (LaterUseKind::ClosureCapture, var_span)
370 UseSpans::OtherUse(span) => {
371 let block = &self.mir.basic_blocks()[location.block];
373 let kind = if let Some(&Statement {
374 kind: StatementKind::FakeRead(FakeReadCause::ForLet, _),
376 }) = block.statements.get(location.statement_index) {
377 LaterUseKind::FakeLetRead
378 } else if self.was_captured_by_trait_object(borrow) {
379 LaterUseKind::TraitCapture
380 } else if location.statement_index == block.statements.len() {
381 if let TerminatorKind::Call {
382 ref func, from_hir_call: true, ..
383 } = block.terminator().kind {
384 // Just point to the function, to reduce the chance of overlapping spans.
385 let function_span = match func {
386 Operand::Constant(c) => c.span,
387 Operand::Copy(Place::Local(l)) | Operand::Move(Place::Local(l)) => {
388 let local_decl = &self.mir.local_decls[*l];
389 if local_decl.name.is_none() {
390 local_decl.source_info.span
397 return (LaterUseKind::Call, function_span);
410 /// Checks if a borrowed value was captured by a trait object. We do this by
411 /// looking forward in the MIR from the reserve location and checking if we see
412 /// a unsized cast to a trait object on our data.
413 fn was_captured_by_trait_object(&self, borrow: &BorrowData<'tcx>) -> bool {
414 // Start at the reserve location, find the place that we want to see cast to a trait object.
415 let location = borrow.reserve_location;
416 let block = &self.mir[location.block];
417 let stmt = block.statements.get(location.statement_index);
418 debug!("was_captured_by_trait_object: location={:?} stmt={:?}", location, stmt);
420 // We make a `queue` vector that has the locations we want to visit. As of writing, this
421 // will only ever have one item at any given time, but by using a vector, we can pop from
422 // it which simplifies the termination logic.
423 let mut queue = vec![location];
424 let mut target = if let Some(&Statement {
425 kind: StatementKind::Assign(Place::Local(local), _),
433 debug!("was_captured_by_trait: target={:?} queue={:?}", target, queue);
434 while let Some(current_location) = queue.pop() {
435 debug!("was_captured_by_trait: target={:?}", target);
436 let block = &self.mir[current_location.block];
437 // We need to check the current location to find out if it is a terminator.
438 let is_terminator = current_location.statement_index == block.statements.len();
440 let stmt = &block.statements[current_location.statement_index];
441 debug!("was_captured_by_trait_object: stmt={:?}", stmt);
443 // The only kind of statement that we care about is assignments...
444 if let StatementKind::Assign(
448 let into = match place {
449 Place::Local(into) => into,
450 Place::Projection(box Projection {
451 base: Place::Local(into),
452 elem: ProjectionElem::Deref,
455 // Continue at the next location.
456 queue.push(current_location.successor_within_block());
462 // If we see a use, we should check whether it is our data, and if so
463 // update the place that we're looking for to that new place.
464 Rvalue::Use(operand) => match operand {
465 Operand::Copy(Place::Local(from)) |
466 Operand::Move(Place::Local(from)) if *from == target => {
471 // If we see a unsized cast, then if it is our data we should check
472 // whether it is being cast to a trait object.
473 Rvalue::Cast(CastKind::Unsize, operand, ty) => match operand {
474 Operand::Copy(Place::Local(from)) |
475 Operand::Move(Place::Local(from)) if *from == target => {
476 debug!("was_captured_by_trait_object: ty={:?}", ty);
477 // Check the type for a trait object.
478 return match ty.sty {
480 ty::TyKind::Ref(_, ty, _) if ty.is_trait() => true,
482 _ if ty.is_box() && ty.boxed_ty().is_trait() =>
485 _ if ty.is_trait() => true,
496 // Continue at the next location.
497 queue.push(current_location.successor_within_block());
499 // The only thing we need to do for terminators is progress to the next block.
500 let terminator = block.terminator();
501 debug!("was_captured_by_trait_object: terminator={:?}", terminator);
503 if let TerminatorKind::Call {
504 destination: Some((Place::Local(dest), block)),
507 } = &terminator.kind {
509 "was_captured_by_trait_object: target={:?} dest={:?} args={:?}",
512 // Check if one of the arguments to this function is the target place.
513 let found_target = args.iter().any(|arg| {
514 if let Operand::Move(Place::Local(potential)) = arg {
521 // If it is, follow this to the next block and update the target.
524 queue.push(block.start_location());
529 debug!("was_captured_by_trait: queue={:?}", queue);
532 // We didn't find anything and ran out of locations to check.