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