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