]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_utils/src/usage.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_utils / src / usage.rs
CommitLineData
f20569fa 1use crate as utils;
f20569fa
XL
2use rustc_hir as hir;
3use rustc_hir::def::Res;
4use rustc_hir::intravisit;
5use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
cdc7bbd5 6use rustc_hir::HirIdSet;
f20569fa
XL
7use rustc_hir::{Expr, ExprKind, HirId, Path};
8use rustc_infer::infer::TyCtxtInferExt;
9use rustc_lint::LateContext;
f20569fa 10use rustc_middle::hir::map::Map;
cdc7bbd5 11use rustc_middle::mir::FakeReadCause;
f20569fa 12use rustc_middle::ty;
136023e0 13use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
f20569fa
XL
14
15/// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
cdc7bbd5 16pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option<HirIdSet> {
f20569fa 17 let mut delegate = MutVarsDelegate {
cdc7bbd5 18 used_mutably: HirIdSet::default(),
f20569fa
XL
19 skip: false,
20 };
21 cx.tcx.infer_ctxt().enter(|infcx| {
22 ExprUseVisitor::new(
23 &mut delegate,
24 &infcx,
25 expr.hir_id.owner,
26 cx.param_env,
27 cx.typeck_results(),
28 )
29 .walk_expr(expr);
30 });
31
32 if delegate.skip {
33 return None;
34 }
35 Some(delegate.used_mutably)
36}
37
38pub fn is_potentially_mutated<'tcx>(variable: &'tcx Path<'_>, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
39 if let Res::Local(id) = variable.res {
40 mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
41 } else {
42 true
43 }
44}
45
46struct MutVarsDelegate {
cdc7bbd5 47 used_mutably: HirIdSet,
f20569fa
XL
48 skip: bool,
49}
50
51impl<'tcx> MutVarsDelegate {
52 #[allow(clippy::similar_names)]
53 fn update(&mut self, cat: &PlaceWithHirId<'tcx>) {
54 match cat.place.base {
55 PlaceBase::Local(id) => {
56 self.used_mutably.insert(id);
57 },
58 PlaceBase::Upvar(_) => {
59 //FIXME: This causes false negatives. We can't get the `NodeId` from
60 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
61 //`while`-body, not just the ones in the condition.
17df50a5 62 self.skip = true;
f20569fa
XL
63 },
64 _ => {},
65 }
66 }
67}
68
69impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
136023e0 70 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
f20569fa
XL
71
72 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, bk: ty::BorrowKind) {
73 if let ty::BorrowKind::MutBorrow = bk {
17df50a5 74 self.update(cmt);
f20569fa
XL
75 }
76 }
77
78 fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
17df50a5 79 self.update(cmt);
f20569fa
XL
80 }
81
cdc7bbd5 82 fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}
f20569fa
XL
83}
84
85pub struct ParamBindingIdCollector {
86 binding_hir_ids: Vec<hir::HirId>,
87}
88impl<'tcx> ParamBindingIdCollector {
89 fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec<hir::HirId> {
90 let mut hir_ids: Vec<hir::HirId> = Vec::new();
91 for param in body.params.iter() {
92 let mut finder = ParamBindingIdCollector {
93 binding_hir_ids: Vec::new(),
94 };
95 finder.visit_param(param);
96 for hir_id in &finder.binding_hir_ids {
97 hir_ids.push(*hir_id);
98 }
99 }
100 hir_ids
101 }
102}
103impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
104 type Map = Map<'tcx>;
105
106 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
107 if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind {
108 self.binding_hir_ids.push(hir_id);
109 }
110 intravisit::walk_pat(self, pat);
111 }
112
113 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
114 intravisit::NestedVisitorMap::None
115 }
116}
117
118pub struct BindingUsageFinder<'a, 'tcx> {
119 cx: &'a LateContext<'tcx>,
120 binding_ids: Vec<hir::HirId>,
121 usage_found: bool,
122}
123impl<'a, 'tcx> BindingUsageFinder<'a, 'tcx> {
124 pub fn are_params_used(cx: &'a LateContext<'tcx>, body: &'tcx hir::Body<'tcx>) -> bool {
125 let mut finder = BindingUsageFinder {
126 cx,
127 binding_ids: ParamBindingIdCollector::collect_binding_hir_ids(body),
128 usage_found: false,
129 };
130 finder.visit_body(body);
131 finder.usage_found
132 }
133}
134impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> {
135 type Map = Map<'tcx>;
136
137 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
138 if !self.usage_found {
139 intravisit::walk_expr(self, expr);
140 }
141 }
142
143 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
144 if let hir::def::Res::Local(id) = path.res {
145 if self.binding_ids.contains(&id) {
146 self.usage_found = true;
147 }
148 }
149 }
150
151 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
152 intravisit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
153 }
154}
155
156struct ReturnBreakContinueMacroVisitor {
157 seen_return_break_continue: bool,
158}
159
160impl ReturnBreakContinueMacroVisitor {
161 fn new() -> ReturnBreakContinueMacroVisitor {
162 ReturnBreakContinueMacroVisitor {
163 seen_return_break_continue: false,
164 }
165 }
166}
167
168impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor {
169 type Map = Map<'tcx>;
170 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
171 NestedVisitorMap::None
172 }
173
174 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
175 if self.seen_return_break_continue {
176 // No need to look farther if we've already seen one of them
177 return;
178 }
179 match &ex.kind {
180 ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
181 self.seen_return_break_continue = true;
182 },
183 // Something special could be done here to handle while or for loop
184 // desugaring, as this will detect a break if there's a while loop
185 // or a for loop inside the expression.
186 _ => {
187 if utils::in_macro(ex.span) {
188 self.seen_return_break_continue = true;
189 } else {
190 rustc_hir::intravisit::walk_expr(self, ex);
191 }
192 },
193 }
194 }
195}
196
197pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
198 let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new();
199 recursive_visitor.visit_expr(expression);
200 recursive_visitor.seen_return_break_continue
201}
136023e0
XL
202
203pub struct UsedAfterExprVisitor<'a, 'tcx> {
204 cx: &'a LateContext<'tcx>,
205 expr: &'tcx Expr<'tcx>,
206 definition: HirId,
207 past_expr: bool,
208 used_after_expr: bool,
209}
210impl<'a, 'tcx> UsedAfterExprVisitor<'a, 'tcx> {
211 pub fn is_found(cx: &'a LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
212 utils::path_to_local(expr).map_or(false, |definition| {
213 let mut visitor = UsedAfterExprVisitor {
214 cx,
215 expr,
216 definition,
217 past_expr: false,
218 used_after_expr: false,
219 };
220 utils::get_enclosing_block(cx, definition).map_or(false, |block| {
221 visitor.visit_block(block);
222 visitor.used_after_expr
223 })
224 })
225 }
226}
227
228impl<'a, 'tcx> intravisit::Visitor<'tcx> for UsedAfterExprVisitor<'a, 'tcx> {
229 type Map = Map<'tcx>;
230
231 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
232 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
233 }
234
235 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
236 if self.used_after_expr {
237 return;
238 }
239
240 if expr.hir_id == self.expr.hir_id {
241 self.past_expr = true;
242 } else if self.past_expr && utils::path_to_local_id(expr, self.definition) {
243 self.used_after_expr = true;
244 } else {
245 intravisit::walk_expr(self, expr);
246 }
247 }
248}