]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/usage.rs
Rollup merge of #103610 - wesleywiser:thinlto_cgu1, r=michaelwoerister
[rust.git] / src / tools / clippy / clippy_utils / src / usage.rs
1 use crate as utils;
2 use crate::visitors::{for_each_expr, for_each_expr_with_closures, Descend};
3 use core::ops::ControlFlow;
4 use rustc_hir as hir;
5 use rustc_hir::intravisit::{self, Visitor};
6 use rustc_hir::HirIdSet;
7 use rustc_hir::{Expr, ExprKind, HirId, Node};
8 use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
9 use rustc_infer::infer::TyCtxtInferExt;
10 use rustc_lint::LateContext;
11 use rustc_middle::hir::nested_filter;
12 use rustc_middle::mir::FakeReadCause;
13 use rustc_middle::ty;
14
15 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
16 pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option<HirIdSet> {
17     let mut delegate = MutVarsDelegate {
18         used_mutably: HirIdSet::default(),
19         skip: false,
20     };
21     let infcx = cx.tcx.infer_ctxt().build();
22     ExprUseVisitor::new(
23         &mut delegate,
24         &infcx,
25         expr.hir_id.owner.def_id,
26         cx.param_env,
27         cx.typeck_results(),
28     )
29     .walk_expr(expr);
30
31     if delegate.skip {
32         return None;
33     }
34     Some(delegate.used_mutably)
35 }
36
37 pub fn is_potentially_mutated<'tcx>(variable: HirId, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
38     mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&variable))
39 }
40
41 struct MutVarsDelegate {
42     used_mutably: HirIdSet,
43     skip: bool,
44 }
45
46 impl<'tcx> MutVarsDelegate {
47     fn update(&mut self, cat: &PlaceWithHirId<'tcx>) {
48         match cat.place.base {
49             PlaceBase::Local(id) => {
50                 self.used_mutably.insert(id);
51             },
52             PlaceBase::Upvar(_) => {
53                 //FIXME: This causes false negatives. We can't get the `NodeId` from
54                 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
55                 //`while`-body, not just the ones in the condition.
56                 self.skip = true;
57             },
58             _ => {},
59         }
60     }
61 }
62
63 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
64     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
65
66     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, bk: ty::BorrowKind) {
67         if bk == ty::BorrowKind::MutBorrow {
68             self.update(cmt);
69         }
70     }
71
72     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
73         self.update(cmt);
74     }
75
76     fn fake_read(
77         &mut self,
78         _: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>,
79         _: FakeReadCause,
80         _: HirId,
81     ) {}
82 }
83
84 pub struct ParamBindingIdCollector {
85     pub binding_hir_ids: Vec<hir::HirId>,
86 }
87 impl<'tcx> ParamBindingIdCollector {
88     fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec<hir::HirId> {
89         let mut hir_ids: Vec<hir::HirId> = Vec::new();
90         for param in body.params.iter() {
91             let mut finder = ParamBindingIdCollector {
92                 binding_hir_ids: Vec::new(),
93             };
94             finder.visit_param(param);
95             for hir_id in &finder.binding_hir_ids {
96                 hir_ids.push(*hir_id);
97             }
98         }
99         hir_ids
100     }
101 }
102 impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
103     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
104         if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind {
105             self.binding_hir_ids.push(hir_id);
106         }
107         intravisit::walk_pat(self, pat);
108     }
109 }
110
111 pub struct BindingUsageFinder<'a, 'tcx> {
112     cx: &'a LateContext<'tcx>,
113     binding_ids: Vec<hir::HirId>,
114     usage_found: bool,
115 }
116 impl<'a, 'tcx> BindingUsageFinder<'a, 'tcx> {
117     pub fn are_params_used(cx: &'a LateContext<'tcx>, body: &'tcx hir::Body<'tcx>) -> bool {
118         let mut finder = BindingUsageFinder {
119             cx,
120             binding_ids: ParamBindingIdCollector::collect_binding_hir_ids(body),
121             usage_found: false,
122         };
123         finder.visit_body(body);
124         finder.usage_found
125     }
126 }
127 impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> {
128     type NestedFilter = nested_filter::OnlyBodies;
129
130     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
131         if !self.usage_found {
132             intravisit::walk_expr(self, expr);
133         }
134     }
135
136     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
137         if let hir::def::Res::Local(id) = path.res {
138             if self.binding_ids.contains(&id) {
139                 self.usage_found = true;
140             }
141         }
142     }
143
144     fn nested_visit_map(&mut self) -> Self::Map {
145         self.cx.tcx.hir()
146     }
147 }
148
149 pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
150     for_each_expr(expression, |e| {
151         match e.kind {
152             ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => ControlFlow::Break(()),
153             // Something special could be done here to handle while or for loop
154             // desugaring, as this will detect a break if there's a while loop
155             // or a for loop inside the expression.
156             _ if e.span.from_expansion() => ControlFlow::Break(()),
157             _ => ControlFlow::Continue(()),
158         }
159     })
160     .is_some()
161 }
162
163 pub fn local_used_after_expr(cx: &LateContext<'_>, local_id: HirId, after: &Expr<'_>) -> bool {
164     let Some(block) = utils::get_enclosing_block(cx, local_id) else { return false };
165
166     // for _ in 1..3 {
167     //    local
168     // }
169     //
170     // let closure = || local;
171     // closure();
172     // closure();
173     let in_loop_or_closure = cx
174         .tcx
175         .hir()
176         .parent_iter(after.hir_id)
177         .take_while(|&(id, _)| id != block.hir_id)
178         .any(|(_, node)| {
179             matches!(
180                 node,
181                 Node::Expr(Expr {
182                     kind: ExprKind::Loop(..) | ExprKind::Closure { .. },
183                     ..
184                 })
185             )
186         });
187     if in_loop_or_closure {
188         return true;
189     }
190
191     let mut past_expr = false;
192     for_each_expr_with_closures(cx, block, |e| {
193         if e.hir_id == after.hir_id {
194             past_expr = true;
195             ControlFlow::Continue(Descend::No)
196         } else if past_expr && utils::path_to_local_id(e, local_id) {
197             ControlFlow::Break(())
198         } else {
199             ControlFlow::Continue(Descend::Yes)
200         }
201     })
202     .is_some()
203 }