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