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