]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
Auto merge of #101784 - reitermarkus:const-memchr, r=thomcc
[rust.git] / compiler / rustc_borrowck / src / diagnostics / explain_borrow.rs
1 //! Print diagnostics to explain why values are borrowed.
2
3 use std::collections::VecDeque;
4
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,
12 };
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};
17
18 use crate::region_infer::BlameConstraint;
19 use crate::{
20     borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt,
21     WriteKind,
22 };
23
24 use super::{find_use, RegionName, UseSpans};
25
26 #[derive(Debug)]
27 pub(crate) enum BorrowExplanation<'tcx> {
28     UsedLater(LaterUseKind, Span, Option<Span>),
29     UsedLaterInLoop(LaterUseKind, Span, Option<Span>),
30     UsedLaterWhenDropped {
31         drop_loc: Location,
32         dropped_local: Local,
33         should_note_order: bool,
34     },
35     MustBeValidFor {
36         category: ConstraintCategory<'tcx>,
37         from_closure: bool,
38         span: Span,
39         region_name: RegionName,
40         opt_place_desc: Option<String>,
41     },
42     Unexplained,
43 }
44
45 #[derive(Clone, Copy, Debug)]
46 pub(crate) enum LaterUseKind {
47     TraitCapture,
48     ClosureCapture,
49     Call,
50     FakeLetRead,
51     Other,
52 }
53
54 impl<'tcx> BorrowExplanation<'tcx> {
55     pub(crate) fn is_explained(&self) -> bool {
56         !matches!(self, BorrowExplanation::Unexplained)
57     }
58     pub(crate) fn add_explanation_to_diagnostic(
59         &self,
60         tcx: TyCtxt<'tcx>,
61         body: &Body<'tcx>,
62         local_names: &IndexVec<Local, Option<Symbol>>,
63         err: &mut Diagnostic,
64         borrow_desc: &str,
65         borrow_span: Option<Span>,
66         multiple_borrow_span: Option<(Span, Span)>,
67     ) {
68         match *self {
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",
76                 };
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) {
80                         err.span_label(
81                             var_or_use_span,
82                             format!("{}borrow later {}", borrow_desc, message),
83                         );
84                     }
85                 } else {
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;
93                         err.span_label(
94                             var_or_use_span,
95                             format!("{}borrow later {}", borrow_desc, capture_kind_label),
96                         );
97                         err.span_label(path_span, path_label);
98                     }
99                 }
100             }
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"
105                     }
106                     LaterUseKind::ClosureCapture => {
107                         "borrow captured here by closure, in later iteration of loop"
108                     }
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",
112                 };
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));
116                 } else {
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;
124                         err.span_label(
125                             var_or_use_span,
126                             format!("{}borrow later {}", borrow_desc, capture_kind_label),
127                         );
128                         err.span_label(path_span, path_label);
129                     }
130                 }
131             }
132             BorrowExplanation::UsedLaterWhenDropped {
133                 drop_loc,
134                 dropped_local,
135                 should_note_order,
136             } => {
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);
144                         }
145                     }
146                 }
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())))
152                     }
153
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()),
158
159                     _ => ("destructor", format!("type `{}`", local_decl.ty)),
160                 };
161
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}",
167                             B = borrow_desc,
168                             LOC = local_name,
169                             TYPE = type_desc,
170                             DTOR = dtor_desc
171                         );
172                         err.span_label(body.source_info(drop_loc).span, message);
173
174                         if should_note_order {
175                             err.note(
176                                 "values in a scope are dropped \
177                                  in the opposite order they are defined",
178                             );
179                         }
180                     }
181                     _ => {
182                         err.span_label(
183                             local_decl.source_info.span,
184                             format!(
185                                 "a temporary with access to the {B}borrow \
186                                  is created here ...",
187                                 B = borrow_desc
188                             ),
189                         );
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}",
194                             B = borrow_desc,
195                             TYPE = type_desc,
196                             DTOR = dtor_desc
197                         );
198                         err.span_label(body.source_info(drop_loc).span, message);
199
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
205                                     .map(|(old, new)| {
206                                         old.to(info.span.shrink_to_hi()).contains(new)
207                                     })
208                                     .unwrap_or(false)
209                                 {
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",
215                                         ";",
216                                         Applicability::MaybeIncorrect,
217                                     );
218                                 }
219                             } else {
220                                 err.note(
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",
224                                 );
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 \
228                                      end of the block",
229                                     vec![
230                                         (info.span.shrink_to_lo(), "let x = ".to_string()),
231                                         (info.span.shrink_to_hi(), "; x".to_string()),
232                                     ],
233                                     Applicability::MaybeIncorrect,
234                                 );
235                             };
236                         }
237                     }
238                 }
239             }
240             BorrowExplanation::MustBeValidFor {
241                 category,
242                 span,
243                 ref region_name,
244                 ref opt_place_desc,
245                 from_closure: _,
246             } => {
247                 region_name.highlight_region_name(err);
248
249                 if let Some(desc) = opt_place_desc {
250                     err.span_label(
251                         span,
252                         format!(
253                             "{}requires that `{}` is borrowed for `{}`",
254                             category.description(),
255                             desc,
256                             region_name,
257                         ),
258                     );
259                 } else {
260                     err.span_label(
261                         span,
262                         format!(
263                             "{}requires that {}borrow lasts for `{}`",
264                             category.description(),
265                             borrow_desc,
266                             region_name,
267                         ),
268                     );
269                 };
270
271                 self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name);
272             }
273             _ => {}
274         }
275     }
276
277     fn add_lifetime_bound_suggestion_to_diagnostic(
278         &self,
279         err: &mut Diagnostic,
280         category: &ConstraintCategory<'tcx>,
281         span: Span,
282         region_name: &RegionName,
283     ) {
284         if !span.is_desugaring(DesugaringKind::OpaqueTy) {
285             return;
286         }
287         if let ConstraintCategory::OpaqueType = category {
288             let suggestable_name =
289                 if region_name.was_named() { region_name.name } else { kw::UnderscoreLifetime };
290
291             let msg = format!(
292                 "you can add a bound to the {}to make it last less than `'static` and match `{}`",
293                 category.description(),
294                 region_name,
295             );
296
297             err.span_suggestion_verbose(
298                 span.shrink_to_hi(),
299                 &msg,
300                 format!(" + {}", suggestable_name),
301                 Applicability::Unspecified,
302             );
303         }
304     }
305 }
306
307 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
308     fn free_region_constraint_info(
309         &self,
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
314             .regioncx
315             .best_blame_constraint(borrow_region, NllRegionVariableOrigin::FreeRegion, |r| {
316                 self.regioncx.provides_universal_region(r, borrow_region, outlived_region)
317             });
318
319         let outlived_fr_name = self.give_region_a_name(outlived_region);
320
321         (category, from_closure, cause.span, outlived_fr_name)
322     }
323
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].
327     ///
328     /// # Parameters
329     ///
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
335     ///
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(
339         &self,
340         location: Location,
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;
347
348         let borrow_region_vid = borrow.region;
349         debug!(?borrow_region_vid);
350
351         let region_sub = self.regioncx.find_sub_region_live_at(borrow_region_vid, location);
352         debug!(?region_sub);
353
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;
357                 let spans = self
358                     .move_spans(Place::from(local).as_ref(), location)
359                     .or_else(|| self.borrow_spans(span, location));
360
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)
365                 } else {
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)
371                 }
372             }
373
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
380                 {
381                     should_note_order = true;
382                 }
383
384                 BorrowExplanation::UsedLaterWhenDropped {
385                     drop_loc: location,
386                     dropped_local: local,
387                     should_note_order,
388                 }
389             }
390
391             None => {
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 {
398                             category,
399                             from_closure,
400                             span,
401                             region_name,
402                             opt_place_desc,
403                         }
404                     } else {
405                         debug!("Could not generate a region name");
406                         BorrowExplanation::Unexplained
407                     }
408                 } else {
409                     debug!("Could not generate an error region vid");
410                     BorrowExplanation::Unexplained
411                 }
412             }
413         }
414     }
415
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(
419         &self,
420         borrow_location: Location,
421         use_location: Location,
422     ) -> bool {
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))
425     }
426
427     /// Returns the outmost back edge if `from` location can reach `to` location passing through
428     /// that back edge
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,);
435
436         let mut outmost_back_edge = None;
437         while let Some(location) = pending_locations.pop_front() {
438             debug!(
439                 "reach_through_backedge: location={:?} outmost_back_edge={:?}
440                    pending_locations={:?} visited_locations={:?}",
441                 location, outmost_back_edge, pending_locations, visited_locations
442             );
443
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;
448             }
449
450             let block = &self.body.basic_blocks[location.block];
451
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);
456                 }
457             } else {
458                 pending_locations.extend(
459                     block
460                         .terminator()
461                         .successors()
462                         .map(|bb| Location { statement_index: 0, block: bb })
463                         .filter(|s| visited_locations.insert(*s))
464                         .map(|s| {
465                             if self.is_back_edge(location, s) {
466                                 match outmost_back_edge {
467                                     None => {
468                                         outmost_back_edge = Some(location);
469                                     }
470
471                                     Some(back_edge)
472                                         if location.dominates(back_edge, &self.dominators) =>
473                                     {
474                                         outmost_back_edge = Some(location);
475                                     }
476
477                                     Some(_) => {}
478                                 }
479                             }
480
481                             s
482                         }),
483                 );
484             }
485         }
486
487         None
488     }
489
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())
494     }
495
496     fn find_loop_head_dfs(
497         &self,
498         from: Location,
499         loop_head: Location,
500         visited_locations: &mut FxHashSet<Location>,
501     ) -> bool {
502         visited_locations.insert(from);
503
504         if from == loop_head {
505             return true;
506         }
507
508         if loop_head.dominates(from, &self.dominators) {
509             let block = &self.body.basic_blocks[from.block];
510
511             if from.statement_index < block.statements.len() {
512                 let successor = from.successor_within_block();
513
514                 if !visited_locations.contains(&successor)
515                     && self.find_loop_head_dfs(successor, loop_head, visited_locations)
516                 {
517                     return true;
518                 }
519             } else {
520                 for bb in block.terminator().successors() {
521                     let successor = Location { statement_index: 0, block: bb };
522
523                     if !visited_locations.contains(&successor)
524                         && self.find_loop_head_dfs(successor, loop_head, visited_locations)
525                     {
526                         return true;
527                     }
528                 }
529             }
530         }
531
532         false
533     }
534
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)
539     }
540
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
545     fn later_use_kind(
546         &self,
547         borrow: &BorrowData<'tcx>,
548         use_spans: UseSpans<'tcx>,
549         location: Location,
550     ) -> (LaterUseKind, Span, Option<Span>) {
551         match use_spans {
552             UseSpans::ClosureUse { capture_kind_span, path_span, .. } => {
553                 // Used in a closure.
554                 (LaterUseKind::ClosureCapture, capture_kind_span, Some(path_span))
555             }
556             UseSpans::PatUse(span)
557             | UseSpans::OtherUse(span)
558             | UseSpans::FnSelfUse { var_span: span, .. } => {
559                 let block = &self.body.basic_blocks[location.block];
560
561                 let kind = if let Some(&Statement {
562                     kind: StatementKind::FakeRead(box (FakeReadCause::ForLet(_), _)),
563                     ..
564                 }) = block.statements.get(location.statement_index)
565                 {
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
572                     {
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
581                                     } else {
582                                         span
583                                     }
584                                 } else {
585                                     span
586                                 }
587                             }
588                         };
589                         return (LaterUseKind::Call, function_span, None);
590                     } else {
591                         LaterUseKind::Other
592                     }
593                 } else {
594                     LaterUseKind::Other
595                 };
596
597                 (kind, span, None)
598             }
599         }
600     }
601
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);
611
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, _)),
618             ..
619         }) = stmt
620         {
621             if let Some(local) = place.as_local() {
622                 local
623             } else {
624                 return false;
625             }
626         } else {
627             return false;
628         };
629
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();
636             if !is_terminator {
637                 let stmt = &block.statements[current_location.statement_index];
638                 debug!("was_captured_by_trait_object: stmt={:?}", stmt);
639
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());
645                         continue;
646                     };
647
648                     match rvalue {
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() {
654                                     if from == target {
655                                         target = into;
656                                     }
657                                 }
658                             }
659                             _ => {}
660                         },
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) => {
664                             match operand {
665                                 Operand::Copy(place) | Operand::Move(place) => {
666                                     if let Some(from) = place.as_local() {
667                                         if from == target {
668                                             debug!("was_captured_by_trait_object: ty={:?}", ty);
669                                             // Check the type for a trait object.
670                                             return match ty.kind() {
671                                                 // `&dyn Trait`
672                                                 ty::Ref(_, ty, _) if ty.is_trait() => true,
673                                                 // `Box<dyn Trait>`
674                                                 _ if ty.is_box() && ty.boxed_ty().is_trait() => {
675                                                     true
676                                                 }
677                                                 // `dyn Trait`
678                                                 _ if ty.is_trait() => true,
679                                                 // Anything else.
680                                                 _ => false,
681                                             };
682                                         }
683                                     }
684                                     return false;
685                                 }
686                                 _ => return false,
687                             }
688                         }
689                         _ => {}
690                     }
691                 }
692
693                 // Continue at the next location.
694                 queue.push(current_location.successor_within_block());
695             } else {
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);
699
700                 if let TerminatorKind::Call { destination, target: Some(block), args, .. } =
701                     &terminator.kind
702                 {
703                     if let Some(dest) = destination.as_local() {
704                         debug!(
705                             "was_captured_by_trait_object: target={:?} dest={:?} args={:?}",
706                             target, dest, args
707                         );
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() {
712                                     potential == target
713                                 } else {
714                                     false
715                                 }
716                             } else {
717                                 false
718                             }
719                         });
720
721                         // If it is, follow this to the next block and update the target.
722                         if found_target {
723                             target = dest;
724                             queue.push(block.start_location());
725                         }
726                     }
727                 }
728             }
729
730             debug!("was_captured_by_trait: queue={:?}", queue);
731         }
732
733         // We didn't find anything and ran out of locations to check.
734         false
735     }
736 }