]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/visitors.rs
4a3181dd0276aece1e2408ff334c347f31a5eff0
[rust.git] / clippy_utils / src / visitors.rs
1 use crate::path_to_local_id;
2 use rustc_hir as hir;
3 use rustc_hir::intravisit::{self, walk_expr, ErasedMap, NestedVisitorMap, Visitor};
4 use rustc_hir::{def::Res, Arm, Block, Body, BodyId, Destination, Expr, ExprKind, HirId, Stmt};
5 use rustc_lint::LateContext;
6 use rustc_middle::hir::map::Map;
7 use std::ops::ControlFlow;
8
9 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
10 /// bodies (i.e. closures) are visited.
11 /// If the callback returns `true`, the expr just provided to the callback is walked.
12 #[must_use]
13 pub fn expr_visitor<'tcx>(cx: &LateContext<'tcx>, f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
14     struct V<'tcx, F> {
15         hir: Map<'tcx>,
16         f: F,
17     }
18     impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<'tcx, F> {
19         type Map = Map<'tcx>;
20         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
21             NestedVisitorMap::OnlyBodies(self.hir)
22         }
23
24         fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
25             if (self.f)(expr) {
26                 walk_expr(self, expr);
27             }
28         }
29     }
30     V { hir: cx.tcx.hir(), f }
31 }
32
33 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
34 /// bodies (i.e. closures) are not visited.
35 /// If the callback returns `true`, the expr just provided to the callback is walked.
36 #[must_use]
37 pub fn expr_visitor_no_bodies<'tcx>(f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
38     struct V<F>(F);
39     impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<F> {
40         type Map = intravisit::ErasedMap<'tcx>;
41         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
42             NestedVisitorMap::None
43         }
44
45         fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
46             if (self.0)(e) {
47                 walk_expr(self, e);
48             }
49         }
50     }
51     V(f)
52 }
53
54 /// returns `true` if expr contains match expr desugared from try
55 fn contains_try(expr: &hir::Expr<'_>) -> bool {
56     struct TryFinder {
57         found: bool,
58     }
59
60     impl<'hir> intravisit::Visitor<'hir> for TryFinder {
61         type Map = Map<'hir>;
62
63         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
64             intravisit::NestedVisitorMap::None
65         }
66
67         fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
68             if self.found {
69                 return;
70             }
71             match expr.kind {
72                 hir::ExprKind::Match(_, _, hir::MatchSource::TryDesugar) => self.found = true,
73                 _ => intravisit::walk_expr(self, expr),
74             }
75         }
76     }
77
78     let mut visitor = TryFinder { found: false };
79     visitor.visit_expr(expr);
80     visitor.found
81 }
82
83 pub fn find_all_ret_expressions<'hir, F>(_cx: &LateContext<'_>, expr: &'hir hir::Expr<'hir>, callback: F) -> bool
84 where
85     F: FnMut(&'hir hir::Expr<'hir>) -> bool,
86 {
87     struct RetFinder<F> {
88         in_stmt: bool,
89         failed: bool,
90         cb: F,
91     }
92
93     struct WithStmtGuarg<'a, F> {
94         val: &'a mut RetFinder<F>,
95         prev_in_stmt: bool,
96     }
97
98     impl<F> RetFinder<F> {
99         fn inside_stmt(&mut self, in_stmt: bool) -> WithStmtGuarg<'_, F> {
100             let prev_in_stmt = std::mem::replace(&mut self.in_stmt, in_stmt);
101             WithStmtGuarg {
102                 val: self,
103                 prev_in_stmt,
104             }
105         }
106     }
107
108     impl<F> std::ops::Deref for WithStmtGuarg<'_, F> {
109         type Target = RetFinder<F>;
110
111         fn deref(&self) -> &Self::Target {
112             self.val
113         }
114     }
115
116     impl<F> std::ops::DerefMut for WithStmtGuarg<'_, F> {
117         fn deref_mut(&mut self) -> &mut Self::Target {
118             self.val
119         }
120     }
121
122     impl<F> Drop for WithStmtGuarg<'_, F> {
123         fn drop(&mut self) {
124             self.val.in_stmt = self.prev_in_stmt;
125         }
126     }
127
128     impl<'hir, F: FnMut(&'hir hir::Expr<'hir>) -> bool> intravisit::Visitor<'hir> for RetFinder<F> {
129         type Map = Map<'hir>;
130
131         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
132             intravisit::NestedVisitorMap::None
133         }
134
135         fn visit_stmt(&mut self, stmt: &'hir hir::Stmt<'_>) {
136             intravisit::walk_stmt(&mut *self.inside_stmt(true), stmt);
137         }
138
139         fn visit_expr(&mut self, expr: &'hir hir::Expr<'_>) {
140             if self.failed {
141                 return;
142             }
143             if self.in_stmt {
144                 match expr.kind {
145                     hir::ExprKind::Ret(Some(expr)) => self.inside_stmt(false).visit_expr(expr),
146                     _ => intravisit::walk_expr(self, expr),
147                 }
148             } else {
149                 match expr.kind {
150                     hir::ExprKind::If(cond, then, else_opt) => {
151                         self.inside_stmt(true).visit_expr(cond);
152                         self.visit_expr(then);
153                         if let Some(el) = else_opt {
154                             self.visit_expr(el);
155                         }
156                     },
157                     hir::ExprKind::Match(cond, arms, _) => {
158                         self.inside_stmt(true).visit_expr(cond);
159                         for arm in arms {
160                             self.visit_expr(arm.body);
161                         }
162                     },
163                     hir::ExprKind::Block(..) => intravisit::walk_expr(self, expr),
164                     hir::ExprKind::Ret(Some(expr)) => self.visit_expr(expr),
165                     _ => self.failed |= !(self.cb)(expr),
166                 }
167             }
168         }
169     }
170
171     !contains_try(expr) && {
172         let mut ret_finder = RetFinder {
173             in_stmt: false,
174             failed: false,
175             cb: callback,
176         };
177         ret_finder.visit_expr(expr);
178         !ret_finder.failed
179     }
180 }
181
182 /// A type which can be visited.
183 pub trait Visitable<'tcx> {
184     /// Calls the corresponding `visit_*` function on the visitor.
185     fn visit<V: Visitor<'tcx>>(self, visitor: &mut V);
186 }
187 macro_rules! visitable_ref {
188     ($t:ident, $f:ident) => {
189         impl Visitable<'tcx> for &'tcx $t<'tcx> {
190             fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
191                 visitor.$f(self);
192             }
193         }
194     };
195 }
196 visitable_ref!(Arm, visit_arm);
197 visitable_ref!(Block, visit_block);
198 visitable_ref!(Body, visit_body);
199 visitable_ref!(Expr, visit_expr);
200 visitable_ref!(Stmt, visit_stmt);
201
202 // impl<'tcx, I: IntoIterator> Visitable<'tcx> for I
203 // where
204 //     I::Item: Visitable<'tcx>,
205 // {
206 //     fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
207 //         for x in self {
208 //             x.visit(visitor);
209 //         }
210 //     }
211 // }
212
213 /// Calls the given function for each break expression.
214 pub fn visit_break_exprs<'tcx>(
215     node: impl Visitable<'tcx>,
216     f: impl FnMut(&'tcx Expr<'tcx>, Destination, Option<&'tcx Expr<'tcx>>),
217 ) {
218     struct V<F>(F);
219     impl<'tcx, F: FnMut(&'tcx Expr<'tcx>, Destination, Option<&'tcx Expr<'tcx>>)> Visitor<'tcx> for V<F> {
220         type Map = ErasedMap<'tcx>;
221         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
222             NestedVisitorMap::None
223         }
224
225         fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
226             if let ExprKind::Break(dest, sub_expr) = e.kind {
227                 self.0(e, dest, sub_expr);
228             }
229             walk_expr(self, e);
230         }
231     }
232
233     node.visit(&mut V(f));
234 }
235
236 /// Checks if the given resolved path is used in the given body.
237 pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool {
238     struct V<'a, 'tcx> {
239         cx: &'a LateContext<'tcx>,
240         res: Res,
241         found: bool,
242     }
243     impl Visitor<'tcx> for V<'_, 'tcx> {
244         type Map = Map<'tcx>;
245         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
246             NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
247         }
248
249         fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
250             if self.found {
251                 return;
252             }
253
254             if let ExprKind::Path(p) = &e.kind {
255                 if self.cx.qpath_res(p, e.hir_id) == self.res {
256                     self.found = true;
257                 }
258             } else {
259                 walk_expr(self, e);
260             }
261         }
262     }
263
264     let mut v = V { cx, res, found: false };
265     v.visit_expr(&cx.tcx.hir().body(body).value);
266     v.found
267 }
268
269 /// Calls the given function for each usage of the given local.
270 pub fn for_each_local_usage<'tcx, B>(
271     cx: &LateContext<'tcx>,
272     visitable: impl Visitable<'tcx>,
273     id: HirId,
274     f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
275 ) -> ControlFlow<B> {
276     struct V<'tcx, B, F> {
277         map: Map<'tcx>,
278         id: HirId,
279         f: F,
280         res: ControlFlow<B>,
281     }
282     impl<'tcx, B, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>> Visitor<'tcx> for V<'tcx, B, F> {
283         type Map = Map<'tcx>;
284         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
285             NestedVisitorMap::OnlyBodies(self.map)
286         }
287
288         fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
289             if self.res.is_continue() {
290                 if path_to_local_id(e, self.id) {
291                     self.res = (self.f)(e);
292                 } else {
293                     walk_expr(self, e);
294                 }
295             }
296         }
297     }
298
299     let mut v = V {
300         map: cx.tcx.hir(),
301         id,
302         f,
303         res: ControlFlow::CONTINUE,
304     };
305     visitable.visit(&mut v);
306     v.res
307 }
308
309 /// Checks if the given local is used.
310 pub fn is_local_used(cx: &LateContext<'tcx>, visitable: impl Visitable<'tcx>, id: HirId) -> bool {
311     for_each_local_usage(cx, visitable, id, |_| ControlFlow::BREAK).is_break()
312 }