]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/usage.rs
Arrays of sizes from 0 to 32 (inclusive) implement [Default] trait, edit method is_de...
[rust.git] / clippy_utils / src / usage.rs
1 use crate as utils;
2 use rustc_hir as hir;
3 use rustc_hir::intravisit;
4 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
5 use rustc_hir::HirIdSet;
6 use rustc_hir::{Expr, ExprKind, HirId};
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_lint::LateContext;
9 use rustc_middle::hir::map::Map;
10 use rustc_middle::mir::FakeReadCause;
11 use rustc_middle::ty;
12 use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
13
14 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
15 pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option<HirIdSet> {
16     let mut delegate = MutVarsDelegate {
17         used_mutably: HirIdSet::default(),
18         skip: false,
19     };
20     cx.tcx.infer_ctxt().enter(|infcx| {
21         ExprUseVisitor::new(
22             &mut delegate,
23             &infcx,
24             expr.hir_id.owner,
25             cx.param_env,
26             cx.typeck_results(),
27         )
28         .walk_expr(expr);
29     });
30
31     if delegate.skip {
32         return None;
33     }
34     Some(delegate.used_mutably)
35 }
36
37 pub fn is_potentially_mutated<'tcx>(variable: HirId, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
38     mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&variable))
39 }
40
41 struct MutVarsDelegate {
42     used_mutably: HirIdSet,
43     skip: bool,
44 }
45
46 impl<'tcx> MutVarsDelegate {
47     #[allow(clippy::similar_names)]
48     fn update(&mut self, cat: &PlaceWithHirId<'tcx>) {
49         match cat.place.base {
50             PlaceBase::Local(id) => {
51                 self.used_mutably.insert(id);
52             },
53             PlaceBase::Upvar(_) => {
54                 //FIXME: This causes false negatives. We can't get the `NodeId` from
55                 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
56                 //`while`-body, not just the ones in the condition.
57                 self.skip = true;
58             },
59             _ => {},
60         }
61     }
62 }
63
64 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
65     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
66
67     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, bk: ty::BorrowKind) {
68         if let ty::BorrowKind::MutBorrow = bk {
69             self.update(cmt);
70         }
71     }
72
73     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
74         self.update(cmt);
75     }
76
77     fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}
78 }
79
80 pub struct ParamBindingIdCollector {
81     binding_hir_ids: Vec<hir::HirId>,
82 }
83 impl<'tcx> ParamBindingIdCollector {
84     fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec<hir::HirId> {
85         let mut hir_ids: Vec<hir::HirId> = Vec::new();
86         for param in body.params.iter() {
87             let mut finder = ParamBindingIdCollector {
88                 binding_hir_ids: Vec::new(),
89             };
90             finder.visit_param(param);
91             for hir_id in &finder.binding_hir_ids {
92                 hir_ids.push(*hir_id);
93             }
94         }
95         hir_ids
96     }
97 }
98 impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
99     type Map = Map<'tcx>;
100
101     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
102         if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind {
103             self.binding_hir_ids.push(hir_id);
104         }
105         intravisit::walk_pat(self, pat);
106     }
107
108     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
109         intravisit::NestedVisitorMap::None
110     }
111 }
112
113 pub struct BindingUsageFinder<'a, 'tcx> {
114     cx: &'a LateContext<'tcx>,
115     binding_ids: Vec<hir::HirId>,
116     usage_found: bool,
117 }
118 impl<'a, 'tcx> BindingUsageFinder<'a, 'tcx> {
119     pub fn are_params_used(cx: &'a LateContext<'tcx>, body: &'tcx hir::Body<'tcx>) -> bool {
120         let mut finder = BindingUsageFinder {
121             cx,
122             binding_ids: ParamBindingIdCollector::collect_binding_hir_ids(body),
123             usage_found: false,
124         };
125         finder.visit_body(body);
126         finder.usage_found
127     }
128 }
129 impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> {
130     type Map = Map<'tcx>;
131
132     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
133         if !self.usage_found {
134             intravisit::walk_expr(self, expr);
135         }
136     }
137
138     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
139         if let hir::def::Res::Local(id) = path.res {
140             if self.binding_ids.contains(&id) {
141                 self.usage_found = true;
142             }
143         }
144     }
145
146     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
147         intravisit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
148     }
149 }
150
151 struct ReturnBreakContinueMacroVisitor {
152     seen_return_break_continue: bool,
153 }
154
155 impl ReturnBreakContinueMacroVisitor {
156     fn new() -> ReturnBreakContinueMacroVisitor {
157         ReturnBreakContinueMacroVisitor {
158             seen_return_break_continue: false,
159         }
160     }
161 }
162
163 impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor {
164     type Map = Map<'tcx>;
165     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
166         NestedVisitorMap::None
167     }
168
169     fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
170         if self.seen_return_break_continue {
171             // No need to look farther if we've already seen one of them
172             return;
173         }
174         match &ex.kind {
175             ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
176                 self.seen_return_break_continue = true;
177             },
178             // Something special could be done here to handle while or for loop
179             // desugaring, as this will detect a break if there's a while loop
180             // or a for loop inside the expression.
181             _ => {
182                 if utils::in_macro(ex.span) {
183                     self.seen_return_break_continue = true;
184                 } else {
185                     rustc_hir::intravisit::walk_expr(self, ex);
186                 }
187             },
188         }
189     }
190 }
191
192 pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
193     let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new();
194     recursive_visitor.visit_expr(expression);
195     recursive_visitor.seen_return_break_continue
196 }
197
198 pub struct UsedAfterExprVisitor<'a, 'tcx> {
199     cx: &'a LateContext<'tcx>,
200     expr: &'tcx Expr<'tcx>,
201     definition: HirId,
202     past_expr: bool,
203     used_after_expr: bool,
204 }
205 impl<'a, 'tcx> UsedAfterExprVisitor<'a, 'tcx> {
206     pub fn is_found(cx: &'a LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
207         utils::path_to_local(expr).map_or(false, |definition| {
208             let mut visitor = UsedAfterExprVisitor {
209                 cx,
210                 expr,
211                 definition,
212                 past_expr: false,
213                 used_after_expr: false,
214             };
215             utils::get_enclosing_block(cx, definition).map_or(false, |block| {
216                 visitor.visit_block(block);
217                 visitor.used_after_expr
218             })
219         })
220     }
221 }
222
223 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UsedAfterExprVisitor<'a, 'tcx> {
224     type Map = Map<'tcx>;
225
226     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
227         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
228     }
229
230     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
231         if self.used_after_expr {
232             return;
233         }
234
235         if expr.hir_id == self.expr.hir_id {
236             self.past_expr = true;
237         } else if self.past_expr && utils::path_to_local_id(expr, self.definition) {
238             self.used_after_expr = true;
239         } else {
240             intravisit::walk_expr(self, expr);
241         }
242     }
243 }