]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs
a6a6962bb151709fbd418c175a766a112e592ca1
[rust.git] / src / librustc_mir / borrow_check / nll / explain_borrow / mod.rs
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};
7 use rustc::mir::{
8     CastKind, ConstraintCategory, FakeReadCause, Local, Location, Mir, Operand,
9     Place, Projection, ProjectionElem, Rvalue, Statement, StatementKind,
10     TerminatorKind
11 };
12 use rustc_errors::DiagnosticBuilder;
13 use syntax_pos::Span;
14
15 mod find_use;
16
17 pub(in crate::borrow_check) enum BorrowExplanation {
18     UsedLater(LaterUseKind, Span),
19     UsedLaterInLoop(LaterUseKind, Span),
20     UsedLaterWhenDropped {
21         drop_loc: Location,
22         dropped_local: Local,
23         should_note_order: bool,
24     },
25     MustBeValidFor {
26         category: ConstraintCategory,
27         from_closure: bool,
28         span: Span,
29         region_name: RegionName,
30         opt_place_desc: Option<String>,
31     },
32     Unexplained,
33 }
34
35 #[derive(Clone, Copy)]
36 pub(in crate::borrow_check) enum LaterUseKind {
37     TraitCapture,
38     ClosureCapture,
39     Call,
40     FakeLetRead,
41     Other,
42 }
43
44 impl BorrowExplanation {
45     pub(in crate::borrow_check) fn is_explained(&self) -> bool {
46         match self {
47             BorrowExplanation::Unexplained => false,
48             _ => true,
49         }
50     }
51     pub(in crate::borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx, 'tcx>(
52         &self,
53         tcx: TyCtxt<'cx, 'gcx, 'tcx>,
54         mir: &Mir<'tcx>,
55         err: &mut DiagnosticBuilder<'_>,
56         borrow_desc: &str,
57     ) {
58         match *self {
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",
66                 };
67                 err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
68             },
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",
78                 };
79                 err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
80             },
81             BorrowExplanation::UsedLaterWhenDropped { drop_loc, dropped_local,
82                                                       should_note_order } =>
83             {
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))),
90
91                     // Otherwise, just report the whole type (and use
92                     // the intentionally fuzzy phrase "destructor")
93                     ty::Closure(..) =>
94                         ("destructor", "closure".to_owned()),
95                     ty::Generator(..) =>
96                         ("destructor", "generator".to_owned()),
97
98                     _ => ("destructor", format!("type `{}`", local_decl.ty)),
99                 };
100
101                 match local_decl.name {
102                     Some(local_name) => {
103                         let message =
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);
108
109                         if should_note_order {
110                             err.note(
111                                 "values in a scope are dropped \
112                                  in the opposite order they are defined",
113                             );
114                         }
115                     }
116                     None => {
117                         err.span_label(local_decl.source_info.span,
118                                        format!("a temporary with access to the {B}borrow \
119                                                 is created here ...",
120                                                B=borrow_desc));
121                         let message =
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);
127
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 \
135                                  block are dropped."
136                             } else {
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."
143                             };
144
145                             err.note(msg);
146                         }
147                     }
148                 }
149             },
150             BorrowExplanation::MustBeValidFor {
151                 category,
152                 span,
153                 ref region_name,
154                 ref opt_place_desc,
155                 from_closure: _,
156             } => {
157                 region_name.highlight_region_name(err);
158
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,
163                     ));
164                 } else {
165                     err.span_label(span, format!(
166                         "{}requires that {}borrow lasts for `{}`",
167                         category.description(), borrow_desc, region_name,
168                     ));
169                 };
170             },
171             _ => {},
172         }
173     }
174 }
175
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].
180     ///
181     /// # Parameters
182     ///
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
188     ///
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(
191         &self,
192         context: Context,
193         borrow: &BorrowData<'tcx>,
194         kind_place: Option<(WriteKind, &Place<'tcx>)>,
195     ) -> BorrowExplanation {
196         debug!(
197             "explain_why_borrow_contains_point(context={:?}, borrow={:?}, kind_place={:?})",
198             context, borrow, kind_place
199         );
200
201         let regioncx = &self.nonlexical_regioncx;
202         let mir = self.mir;
203         let tcx = self.infcx.tcx;
204
205         let borrow_region_vid = borrow.region;
206         debug!(
207             "explain_why_borrow_contains_point: borrow_region_vid={:?}",
208             borrow_region_vid
209         );
210
211         let region_sub = regioncx.find_sub_region_live_at(borrow_region_vid, context.loc);
212         debug!(
213             "explain_why_borrow_contains_point: region_sub={:?}",
214             region_sub
215         );
216
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));
222
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)
226                 } else {
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)
232                 }
233             }
234
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;
243
244                              if mir.is_sub_scope(borrowed_local_scope, dropped_local_scope)
245                                  && local != *borrowed_local
246                              {
247                                  should_note_order = true;
248                              }
249                          }
250                      }
251                  }
252
253                  BorrowExplanation::UsedLaterWhenDropped {
254                      drop_loc: location,
255                      dropped_local: local,
256                      should_note_order,
257                  }
258             }
259
260             None => if let Some(region) = regioncx.to_error_region_vid(borrow_region_vid) {
261                 let (category, from_closure, span, region_name) = self
262                     .nonlexical_regioncx
263                     .free_region_constraint_info(
264                         self.mir,
265                         self.mir_def_id,
266                         self.infcx,
267                         borrow_region_vid,
268                         region,
269                     );
270                 if let Some(region_name) = region_name {
271                     let opt_place_desc = self.describe_place(&borrow.borrowed_place);
272                     BorrowExplanation::MustBeValidFor {
273                         category,
274                         from_closure,
275                         span,
276                         region_name,
277                         opt_place_desc,
278                     }
279                 } else {
280                     BorrowExplanation::Unexplained
281                 }
282             } else {
283                 BorrowExplanation::Unexplained
284             }
285         }
286     }
287
288     /// Checks if a borrow location is within a loop.
289     fn is_borrow_location_in_loop(
290         &self,
291         borrow_location: Location,
292     ) -> bool {
293         let mut visited_locations = Vec::new();
294         let mut pending_locations = vec![ borrow_location ];
295         debug!("is_in_loop: borrow_location={:?}", borrow_location);
296
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
302                 // search).
303                 debug!("is_in_loop: found!");
304                 return true;
305             }
306
307             // Skip locations we've been.
308             if visited_locations.contains(&location) { continue; }
309
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());
316                     },
317                     TerminatorKind::SwitchInt { ref targets, .. } => {
318                         pending_locations.extend(
319                             targets.into_iter().map(|target| target.start_location()));
320                     },
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());
329                         }
330                     },
331                     TerminatorKind::Call { ref destination, cleanup, .. } => {
332                         if let Some((_, destination)) = destination {
333                             pending_locations.push(destination.start_location());
334                         }
335                         if let Some(cleanup) = cleanup {
336                             pending_locations.push(cleanup.start_location());
337                         }
338                     },
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()));
343                     },
344                     _ => {},
345                 }
346             } else {
347                 // Add the next statement to pending locations.
348                 pending_locations.push(location.successor_within_block());
349             }
350
351             // Keep track of where we have visited.
352             visited_locations.push(location);
353         }
354
355         false
356     }
357
358     /// Determine how the borrow was later used.
359     fn later_use_kind(
360         &self,
361         borrow: &BorrowData<'tcx>,
362         use_spans: UseSpans,
363         location: Location
364     ) -> (LaterUseKind, Span) {
365         match use_spans {
366             UseSpans::ClosureUse { var_span, .. } => {
367                 // Used in a closure.
368                 (LaterUseKind::ClosureCapture, var_span)
369             },
370             UseSpans::OtherUse(span) => {
371                 let block = &self.mir.basic_blocks()[location.block];
372
373                 let kind = if let Some(&Statement {
374                     kind: StatementKind::FakeRead(FakeReadCause::ForLet, _),
375                     ..
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
391                                 } else {
392                                     span
393                                 }
394                             },
395                             _ => span,
396                         };
397                         return (LaterUseKind::Call, function_span);
398                     } else {
399                         LaterUseKind::Other
400                     }
401                 } else {
402                     LaterUseKind::Other
403                 };
404
405                 (kind, span)
406             }
407         }
408     }
409
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);
419
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), _),
426             ..
427         }) = stmt {
428             local
429         } else {
430             return false;
431         };
432
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();
439             if !is_terminator {
440                 let stmt = &block.statements[current_location.statement_index];
441                 debug!("was_captured_by_trait_object: stmt={:?}", stmt);
442
443                 // The only kind of statement that we care about is assignments...
444                 if let StatementKind::Assign(
445                     place,
446                     box rvalue,
447                 ) = &stmt.kind {
448                     let into = match place {
449                         Place::Local(into) => into,
450                         Place::Projection(box Projection {
451                             base: Place::Local(into),
452                             elem: ProjectionElem::Deref,
453                         }) => into,
454                         _ =>  {
455                             // Continue at the next location.
456                             queue.push(current_location.successor_within_block());
457                             continue;
458                         },
459                     };
460
461                     match rvalue {
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 => {
467                                 target = *into;
468                             },
469                             _ => {},
470                         },
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 {
479                                     // `&dyn Trait`
480                                     ty::TyKind::Ref(_, ty, _) if ty.is_trait() => true,
481                                     // `Box<dyn Trait>`
482                                     _ if ty.is_box() && ty.boxed_ty().is_trait() =>
483                                         true,
484                                     // `dyn Trait`
485                                     _ if ty.is_trait() => true,
486                                     // Anything else.
487                                     _ => false,
488                                 };
489                             },
490                             _ => return false,
491                         },
492                         _ => {},
493                     }
494                 }
495
496                 // Continue at the next location.
497                 queue.push(current_location.successor_within_block());
498             } else {
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);
502
503                 if let TerminatorKind::Call {
504                     destination: Some((Place::Local(dest), block)),
505                     args,
506                     ..
507                 } = &terminator.kind {
508                     debug!(
509                         "was_captured_by_trait_object: target={:?} dest={:?} args={:?}",
510                         target, dest, args
511                     );
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 {
515                             *potential == target
516                         } else {
517                             false
518                         }
519                     });
520
521                     // If it is, follow this to the next block and update the target.
522                     if found_target {
523                         target = *dest;
524                         queue.push(block.start_location());
525                     }
526                 }
527             }
528
529             debug!("was_captured_by_trait: queue={:?}", queue);
530         }
531
532         // We didn't find anything and ran out of locations to check.
533         false
534     }
535 }