]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
Rollup merge of #106549 - wcampbell0x2a:use-fmt-named-parameters-borrowck, r=estebank
[rust.git] / compiler / rustc_borrowck / src / diagnostics / explain_borrow.rs
1 //! Print diagnostics to explain why values are borrowed.
2
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,
9 };
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};
14
15 use crate::region_infer::{BlameConstraint, ExtraConstraintInfo};
16 use crate::{
17     borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt,
18     WriteKind,
19 };
20
21 use super::{find_use, RegionName, UseSpans};
22
23 #[derive(Debug)]
24 pub(crate) enum BorrowExplanation<'tcx> {
25     UsedLater(LaterUseKind, Span, Option<Span>),
26     UsedLaterInLoop(LaterUseKind, Span, Option<Span>),
27     UsedLaterWhenDropped {
28         drop_loc: Location,
29         dropped_local: Local,
30         should_note_order: bool,
31     },
32     MustBeValidFor {
33         category: ConstraintCategory<'tcx>,
34         from_closure: bool,
35         span: Span,
36         region_name: RegionName,
37         opt_place_desc: Option<String>,
38         extra_info: Vec<ExtraConstraintInfo>,
39     },
40     Unexplained,
41 }
42
43 #[derive(Clone, Copy, Debug)]
44 pub(crate) enum LaterUseKind {
45     TraitCapture,
46     ClosureCapture,
47     Call,
48     FakeLetRead,
49     Other,
50 }
51
52 impl<'tcx> BorrowExplanation<'tcx> {
53     pub(crate) fn is_explained(&self) -> bool {
54         !matches!(self, BorrowExplanation::Unexplained)
55     }
56     pub(crate) fn add_explanation_to_diagnostic(
57         &self,
58         tcx: TyCtxt<'tcx>,
59         body: &Body<'tcx>,
60         local_names: &IndexVec<Local, Option<Symbol>>,
61         err: &mut Diagnostic,
62         borrow_desc: &str,
63         borrow_span: Option<Span>,
64         multiple_borrow_span: Option<(Span, Span)>,
65     ) {
66         match *self {
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",
74                 };
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) {
78                         err.span_label(
79                             var_or_use_span,
80                             format!("{borrow_desc}borrow later {message}"),
81                         );
82                     }
83                 } else {
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;
91                         err.span_label(
92                             var_or_use_span,
93                             format!("{borrow_desc}borrow later {capture_kind_label}"),
94                         );
95                         err.span_label(path_span, path_label);
96                     }
97                 }
98             }
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"
103                     }
104                     LaterUseKind::ClosureCapture => {
105                         "borrow captured here by closure, in later iteration of loop"
106                     }
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",
110                 };
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}"));
114                 } else {
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;
122                         err.span_label(
123                             var_or_use_span,
124                             format!("{borrow_desc}borrow later {capture_kind_label}"),
125                         );
126                         err.span_label(path_span, path_label);
127                     }
128                 }
129             }
130             BorrowExplanation::UsedLaterWhenDropped {
131                 drop_loc,
132                 dropped_local,
133                 should_note_order,
134             } => {
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);
142                         }
143                     }
144                 }
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())))
150                     }
151
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()),
156
157                     _ => ("destructor", format!("type `{}`", local_decl.ty)),
158                 };
159
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}",
165                         );
166                         err.span_label(body.source_info(drop_loc).span, message);
167
168                         if should_note_order {
169                             err.note(
170                                 "values in a scope are dropped \
171                                  in the opposite order they are defined",
172                             );
173                         }
174                     }
175                     _ => {
176                         err.span_label(
177                             local_decl.source_info.span,
178                             format!(
179                                 "a temporary with access to the {borrow_desc}borrow \
180                                  is created here ...",
181                             ),
182                         );
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}",
187                         );
188                         err.span_label(body.source_info(drop_loc).span, message);
189
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
195                                     .map(|(old, new)| {
196                                         old.to(info.span.shrink_to_hi()).contains(new)
197                                     })
198                                     .unwrap_or(false)
199                                 {
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",
205                                         ";",
206                                         Applicability::MaybeIncorrect,
207                                     );
208                                 }
209                             } else {
210                                 err.note(
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",
214                                 );
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 \
218                                      end of the block",
219                                     vec![
220                                         (info.span.shrink_to_lo(), "let x = ".to_string()),
221                                         (info.span.shrink_to_hi(), "; x".to_string()),
222                                     ],
223                                     Applicability::MaybeIncorrect,
224                                 );
225                             };
226                         }
227                     }
228                 }
229             }
230             BorrowExplanation::MustBeValidFor {
231                 category,
232                 span,
233                 ref region_name,
234                 ref opt_place_desc,
235                 from_closure: _,
236                 ref extra_info,
237             } => {
238                 region_name.highlight_region_name(err);
239
240                 if let Some(desc) = opt_place_desc {
241                     err.span_label(
242                         span,
243                         format!(
244                             "{}requires that `{desc}` is borrowed for `{region_name}`",
245                             category.description(),
246                         ),
247                     );
248                 } else {
249                     err.span_label(
250                         span,
251                         format!(
252                             "{}requires that {borrow_desc}borrow lasts for `{region_name}`",
253                             category.description(),
254                         ),
255                     );
256                 };
257
258                 for extra in extra_info {
259                     match extra {
260                         ExtraConstraintInfo::PlaceholderFromPredicate(span) => {
261                             err.span_note(*span, "due to current limitations in the borrow checker, this implies a `'static` lifetime");
262                         }
263                     }
264                 }
265
266                 self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name);
267             }
268             _ => {}
269         }
270     }
271
272     fn add_lifetime_bound_suggestion_to_diagnostic(
273         &self,
274         err: &mut Diagnostic,
275         category: &ConstraintCategory<'tcx>,
276         span: Span,
277         region_name: &RegionName,
278     ) {
279         if !span.is_desugaring(DesugaringKind::OpaqueTy) {
280             return;
281         }
282         if let ConstraintCategory::OpaqueType = category {
283             let suggestable_name =
284                 if region_name.was_named() { region_name.name } else { kw::UnderscoreLifetime };
285
286             let msg = format!(
287                 "you can add a bound to the {}to make it last less than `'static` and match `{region_name}`",
288                 category.description(),
289             );
290
291             err.span_suggestion_verbose(
292                 span.shrink_to_hi(),
293                 &msg,
294                 format!(" + {suggestable_name}"),
295                 Applicability::Unspecified,
296             );
297         }
298     }
299 }
300
301 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
302     fn free_region_constraint_info(
303         &self,
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(
308             borrow_region,
309             NllRegionVariableOrigin::FreeRegion,
310             |r| self.regioncx.provides_universal_region(r, borrow_region, outlived_region),
311         );
312         let BlameConstraint { category, from_closure, cause, .. } = blame_constraint;
313
314         let outlived_fr_name = self.give_region_a_name(outlived_region);
315
316         (category, from_closure, cause.span, outlived_fr_name, extra_info)
317     }
318
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].
322     ///
323     /// # Parameters
324     ///
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
330     ///
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(
334         &self,
335         location: Location,
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;
342
343         let borrow_region_vid = borrow.region;
344         debug!(?borrow_region_vid);
345
346         let mut region_sub = self.regioncx.find_sub_region_live_at(borrow_region_vid, location);
347         debug!(?region_sub);
348
349         let mut use_location = location;
350         let mut use_in_later_iteration_of_loop = false;
351
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)
358             {
359                 region_sub = self
360                     .regioncx
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;
365             }
366         }
367
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;
371                 let spans = self
372                     .move_spans(Place::from(local).as_ref(), location)
373                     .or_else(|| self.borrow_spans(span, location));
374
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)
378                 } else {
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)
384                 }
385             }
386
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
393                 {
394                     should_note_order = true;
395                 }
396
397                 BorrowExplanation::UsedLaterWhenDropped {
398                     drop_loc: location,
399                     dropped_local: local,
400                     should_note_order,
401                 }
402             }
403
404             None => {
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 {
411                             category,
412                             from_closure,
413                             span,
414                             region_name,
415                             opt_place_desc,
416                             extra_info,
417                         }
418                     } else {
419                         debug!("Could not generate a region name");
420                         BorrowExplanation::Unexplained
421                     }
422                 } else {
423                     debug!("Could not generate an error region vid");
424                     BorrowExplanation::Unexplained
425                 }
426             }
427         }
428     }
429
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))]
435     fn later_use_kind(
436         &self,
437         borrow: &BorrowData<'tcx>,
438         use_spans: UseSpans<'tcx>,
439         location: Location,
440     ) -> (LaterUseKind, Span, Option<Span>) {
441         match use_spans {
442             UseSpans::ClosureUse { capture_kind_span, path_span, .. } => {
443                 // Used in a closure.
444                 (LaterUseKind::ClosureCapture, capture_kind_span, Some(path_span))
445             }
446             UseSpans::PatUse(span)
447             | UseSpans::OtherUse(span)
448             | UseSpans::FnSelfUse { var_span: span, .. } => {
449                 let block = &self.body.basic_blocks[location.block];
450
451                 let kind = if let Some(&Statement {
452                     kind: StatementKind::FakeRead(box (FakeReadCause::ForLet(_), place)),
453                     ..
454                 }) = block.statements.get(location.statement_index)
455                 {
456                     if let Some(l) = place.as_local()
457                         && let local_decl = &self.body.local_decls[l]
458                         && local_decl.ty.is_closure()
459                     {
460                         LaterUseKind::ClosureCapture
461                     } else {
462                         LaterUseKind::FakeLetRead
463                     }
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
469                     {
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
478                                     } else {
479                                         span
480                                     }
481                                 } else {
482                                     span
483                                 }
484                             }
485                         };
486                         return (LaterUseKind::Call, function_span, None);
487                     } else {
488                         LaterUseKind::Other
489                     }
490                 } else {
491                     LaterUseKind::Other
492                 };
493
494                 (kind, span, None)
495             }
496         }
497     }
498
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);
508
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];
513         let mut target =
514             if let Some(Statement { kind: StatementKind::Assign(box (place, _)), .. }) = stmt {
515                 if let Some(local) = place.as_local() {
516                     local
517                 } else {
518                     return false;
519                 }
520             } else {
521                 return false;
522             };
523
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();
530             if !is_terminator {
531                 let stmt = &block.statements[current_location.statement_index];
532                 debug!("was_captured_by_trait_object: stmt={:?}", stmt);
533
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());
539                         continue;
540                     };
541
542                     match rvalue {
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() {
548                                     if from == target {
549                                         target = into;
550                                     }
551                                 }
552                             }
553                             _ => {}
554                         },
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) => {
558                             match operand {
559                                 Operand::Copy(place) | Operand::Move(place) => {
560                                     if let Some(from) = place.as_local() {
561                                         if from == target {
562                                             debug!("was_captured_by_trait_object: ty={:?}", ty);
563                                             // Check the type for a trait object.
564                                             return match ty.kind() {
565                                                 // `&dyn Trait`
566                                                 ty::Ref(_, ty, _) if ty.is_trait() => true,
567                                                 // `Box<dyn Trait>`
568                                                 _ if ty.is_box() && ty.boxed_ty().is_trait() => {
569                                                     true
570                                                 }
571                                                 // `dyn Trait`
572                                                 _ if ty.is_trait() => true,
573                                                 // Anything else.
574                                                 _ => false,
575                                             };
576                                         }
577                                     }
578                                     return false;
579                                 }
580                                 _ => return false,
581                             }
582                         }
583                         _ => {}
584                     }
585                 }
586
587                 // Continue at the next location.
588                 queue.push(current_location.successor_within_block());
589             } else {
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);
593
594                 if let TerminatorKind::Call { destination, target: Some(block), args, .. } =
595                     &terminator.kind
596                 {
597                     if let Some(dest) = destination.as_local() {
598                         debug!(
599                             "was_captured_by_trait_object: target={:?} dest={:?} args={:?}",
600                             target, dest, args
601                         );
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() {
606                                     potential == target
607                                 } else {
608                                     false
609                                 }
610                             } else {
611                                 false
612                             }
613                         });
614
615                         // If it is, follow this to the next block and update the target.
616                         if found_target {
617                             target = dest;
618                             queue.push(block.start_location());
619                         }
620                     }
621                 }
622             }
623
624             debug!("was_captured_by_trait: queue={:?}", queue);
625         }
626
627         // We didn't find anything and ran out of locations to check.
628         false
629     }
630 }