]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/visitors.rs
Fix specific code outlined in issue #7975.
[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, NestedVisitorMap, Visitor};
4 use rustc_hir::{def::Res, Arm, Block, Body, BodyId, Expr, ExprKind, HirId, Stmt};
5 use rustc_lint::LateContext;
6 use rustc_middle::hir::map::Map;
7
8 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
9 /// bodies (i.e. closures) are visited.
10 /// If the callback returns `true`, the expr just provided to the callback is walked.
11 #[must_use]
12 pub fn expr_visitor<'tcx>(cx: &LateContext<'tcx>, f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
13     struct V<'tcx, F> {
14         hir: Map<'tcx>,
15         f: F,
16     }
17     impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<'tcx, F> {
18         type Map = Map<'tcx>;
19         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
20             NestedVisitorMap::OnlyBodies(self.hir)
21         }
22
23         fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
24             if (self.f)(expr) {
25                 walk_expr(self, expr);
26             }
27         }
28     }
29     V { hir: cx.tcx.hir(), f }
30 }
31
32 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
33 /// bodies (i.e. closures) are not visited.
34 /// If the callback returns `true`, the expr just provided to the callback is walked.
35 #[must_use]
36 pub fn expr_visitor_no_bodies<'tcx>(f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
37     struct V<F>(F);
38     impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<F> {
39         type Map = intravisit::ErasedMap<'tcx>;
40         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
41             NestedVisitorMap::None
42         }
43
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         type Map = Map<'hir>;
113
114         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
115             intravisit::NestedVisitorMap::None
116         }
117
118         fn visit_stmt(&mut self, stmt: &'hir hir::Stmt<'_>) {
119             intravisit::walk_stmt(&mut *self.inside_stmt(true), stmt);
120         }
121
122         fn visit_expr(&mut self, expr: &'hir hir::Expr<'_>) {
123             if self.failed {
124                 return;
125             }
126             if self.in_stmt {
127                 match expr.kind {
128                     hir::ExprKind::Ret(Some(expr)) => self.inside_stmt(false).visit_expr(expr),
129                     _ => intravisit::walk_expr(self, expr),
130                 }
131             } else {
132                 match expr.kind {
133                     hir::ExprKind::If(cond, then, else_opt) => {
134                         self.inside_stmt(true).visit_expr(cond);
135                         self.visit_expr(then);
136                         if let Some(el) = else_opt {
137                             self.visit_expr(el);
138                         }
139                     },
140                     hir::ExprKind::Match(cond, arms, _) => {
141                         self.inside_stmt(true).visit_expr(cond);
142                         for arm in arms {
143                             self.visit_expr(arm.body);
144                         }
145                     },
146                     hir::ExprKind::Block(..) => intravisit::walk_expr(self, expr),
147                     hir::ExprKind::Ret(Some(expr)) => self.visit_expr(expr),
148                     _ => self.failed |= !(self.cb)(expr),
149                 }
150             }
151         }
152     }
153
154     !contains_try(expr) && {
155         let mut ret_finder = RetFinder {
156             in_stmt: false,
157             failed: false,
158             cb: callback,
159         };
160         ret_finder.visit_expr(expr);
161         !ret_finder.failed
162     }
163 }
164
165 /// A type which can be visited.
166 pub trait Visitable<'tcx> {
167     /// Calls the corresponding `visit_*` function on the visitor.
168     fn visit<V: Visitor<'tcx>>(self, visitor: &mut V);
169 }
170 macro_rules! visitable_ref {
171     ($t:ident, $f:ident) => {
172         impl Visitable<'tcx> for &'tcx $t<'tcx> {
173             fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
174                 visitor.$f(self);
175             }
176         }
177     };
178 }
179 visitable_ref!(Arm, visit_arm);
180 visitable_ref!(Block, visit_block);
181 visitable_ref!(Body, visit_body);
182 visitable_ref!(Expr, visit_expr);
183 visitable_ref!(Stmt, visit_stmt);
184
185 // impl<'tcx, I: IntoIterator> Visitable<'tcx> for I
186 // where
187 //     I::Item: Visitable<'tcx>,
188 // {
189 //     fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
190 //         for x in self {
191 //             x.visit(visitor);
192 //         }
193 //     }
194 // }
195
196 /// Checks if the given resolved path is used in the given body.
197 pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool {
198     let mut found = false;
199     expr_visitor(cx, |e| {
200         if found {
201             return false;
202         }
203
204         if let ExprKind::Path(p) = &e.kind {
205             if cx.qpath_res(p, e.hir_id) == res {
206                 found = true;
207             }
208         }
209         !found
210     })
211     .visit_expr(&cx.tcx.hir().body(body).value);
212     found
213 }
214
215 /// Checks if the given local is used.
216 pub fn is_local_used(cx: &LateContext<'tcx>, visitable: impl Visitable<'tcx>, id: HirId) -> bool {
217     let mut is_used = false;
218     let mut visitor = expr_visitor(cx, |expr| {
219         if !is_used {
220             is_used = path_to_local_id(expr, id);
221         }
222         !is_used
223     });
224     visitable.visit(&mut visitor);
225     drop(visitor);
226     is_used
227 }