1 use super::TrackedValue;
4 expr_use_visitor::{self, ExprUseVisitor},
6 use hir::{def_id::DefId, Body, HirId, HirIdMap};
7 use rustc_data_structures::stable_set::FxHashSet;
9 use rustc_middle::hir::map::Map;
11 pub(super) fn find_consumed_and_borrowed<'a, 'tcx>(
12 fcx: &'a FnCtxt<'a, 'tcx>,
14 body: &'tcx Body<'tcx>,
15 ) -> ConsumedAndBorrowedPlaces {
16 let mut expr_use_visitor = ExprUseDelegate::new(fcx.tcx.hir());
17 expr_use_visitor.consume_body(fcx, def_id, body);
18 expr_use_visitor.places
21 pub(super) struct ConsumedAndBorrowedPlaces {
22 /// Records the variables/expressions that are dropped by a given expression.
24 /// The key is the hir-id of the expression, and the value is a set or hir-ids for variables
25 /// or values that are consumed by that expression.
27 /// Note that this set excludes "partial drops" -- for example, a statement like `drop(x.y)` is
28 /// not considered a drop of `x`, although it would be a drop of `x.y`.
29 pub(super) consumed: HirIdMap<FxHashSet<TrackedValue>>,
30 /// A set of hir-ids of values or variables that are borrowed at some point within the body.
31 pub(super) borrowed: FxHashSet<TrackedValue>,
34 /// Works with ExprUseVisitor to find interesting values for the drop range analysis.
36 /// Interesting values are those that are either dropped or borrowed. For dropped values, we also
37 /// record the parent expression, which is the point where the drop actually takes place.
38 struct ExprUseDelegate<'tcx> {
40 places: ConsumedAndBorrowedPlaces,
43 impl<'tcx> ExprUseDelegate<'tcx> {
44 fn new(hir: Map<'tcx>) -> Self {
47 places: ConsumedAndBorrowedPlaces {
48 consumed: <_>::default(),
49 borrowed: <_>::default(),
54 fn consume_body(&mut self, fcx: &'_ FnCtxt<'_, 'tcx>, def_id: DefId, body: &'tcx Body<'tcx>) {
55 // Run ExprUseVisitor to find where values are consumed.
59 def_id.expect_local(),
61 &fcx.typeck_results.borrow(),
66 fn mark_consumed(&mut self, consumer: HirId, target: TrackedValue) {
67 if !self.places.consumed.contains_key(&consumer) {
68 self.places.consumed.insert(consumer, <_>::default());
70 self.places.consumed.get_mut(&consumer).map(|places| places.insert(target));
74 impl<'tcx> expr_use_visitor::Delegate<'tcx> for ExprUseDelegate<'tcx> {
77 place_with_id: &expr_use_visitor::PlaceWithHirId<'tcx>,
80 let parent = match self.hir.find_parent_node(place_with_id.hir_id) {
81 Some(parent) => parent,
82 None => place_with_id.hir_id,
85 "consume {:?}; diag_expr_id={:?}, using parent {:?}",
86 place_with_id, diag_expr_id, parent
90 .map_or((), |tracked_value| self.mark_consumed(parent, tracked_value));
95 place_with_id: &expr_use_visitor::PlaceWithHirId<'tcx>,
97 _bk: rustc_middle::ty::BorrowKind,
101 .insert(TrackedValue::from_place_with_projections_allowed(place_with_id));
106 _assignee_place: &expr_use_visitor::PlaceWithHirId<'tcx>,
107 _diag_expr_id: HirId,
113 _place: expr_use_visitor::Place<'tcx>,
114 _cause: rustc_middle::mir::FakeReadCause,
115 _diag_expr_id: HirId,