]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/usage.rs
Merge 'rust-clippy/master' into clippyup
[rust.git] / src / tools / clippy / clippy_utils / src / usage.rs
1 use crate as utils;
2 use crate::visitors::{expr_visitor, expr_visitor_no_bodies};
3 use rustc_hir as hir;
4 use rustc_hir::intravisit::{self, Visitor};
5 use rustc_hir::HirIdSet;
6 use rustc_hir::{Expr, ExprKind, HirId, Node};
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_lint::LateContext;
9 use rustc_middle::hir::nested_filter;
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     fn update(&mut self, cat: &PlaceWithHirId<'tcx>) {
48         match cat.place.base {
49             PlaceBase::Local(id) => {
50                 self.used_mutably.insert(id);
51             },
52             PlaceBase::Upvar(_) => {
53                 //FIXME: This causes false negatives. We can't get the `NodeId` from
54                 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
55                 //`while`-body, not just the ones in the condition.
56                 self.skip = true;
57             },
58             _ => {},
59         }
60     }
61 }
62
63 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
64     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
65
66     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, bk: ty::BorrowKind) {
67         if bk == ty::BorrowKind::MutBorrow {
68             self.update(cmt);
69         }
70     }
71
72     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
73         self.update(cmt);
74     }
75
76     fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
77 }
78
79 pub struct ParamBindingIdCollector {
80     pub binding_hir_ids: Vec<hir::HirId>,
81 }
82 impl<'tcx> ParamBindingIdCollector {
83     fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec<hir::HirId> {
84         let mut hir_ids: Vec<hir::HirId> = Vec::new();
85         for param in body.params.iter() {
86             let mut finder = ParamBindingIdCollector {
87                 binding_hir_ids: Vec::new(),
88             };
89             finder.visit_param(param);
90             for hir_id in &finder.binding_hir_ids {
91                 hir_ids.push(*hir_id);
92             }
93         }
94         hir_ids
95     }
96 }
97 impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
98     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
99         if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind {
100             self.binding_hir_ids.push(hir_id);
101         }
102         intravisit::walk_pat(self, pat);
103     }
104 }
105
106 pub struct BindingUsageFinder<'a, 'tcx> {
107     cx: &'a LateContext<'tcx>,
108     binding_ids: Vec<hir::HirId>,
109     usage_found: bool,
110 }
111 impl<'a, 'tcx> BindingUsageFinder<'a, 'tcx> {
112     pub fn are_params_used(cx: &'a LateContext<'tcx>, body: &'tcx hir::Body<'tcx>) -> bool {
113         let mut finder = BindingUsageFinder {
114             cx,
115             binding_ids: ParamBindingIdCollector::collect_binding_hir_ids(body),
116             usage_found: false,
117         };
118         finder.visit_body(body);
119         finder.usage_found
120     }
121 }
122 impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> {
123     type NestedFilter = nested_filter::OnlyBodies;
124
125     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
126         if !self.usage_found {
127             intravisit::walk_expr(self, expr);
128         }
129     }
130
131     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
132         if let hir::def::Res::Local(id) = path.res {
133             if self.binding_ids.contains(&id) {
134                 self.usage_found = true;
135             }
136         }
137     }
138
139     fn nested_visit_map(&mut self) -> Self::Map {
140         self.cx.tcx.hir()
141     }
142 }
143
144 pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
145     let mut seen_return_break_continue = false;
146     expr_visitor_no_bodies(|ex| {
147         if seen_return_break_continue {
148             return false;
149         }
150         match &ex.kind {
151             ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
152                 seen_return_break_continue = true;
153             },
154             // Something special could be done here to handle while or for loop
155             // desugaring, as this will detect a break if there's a while loop
156             // or a for loop inside the expression.
157             _ => {
158                 if ex.span.from_expansion() {
159                     seen_return_break_continue = true;
160                 }
161             },
162         }
163         !seen_return_break_continue
164     })
165     .visit_expr(expression);
166     seen_return_break_continue
167 }
168
169 pub fn local_used_after_expr(cx: &LateContext<'_>, local_id: HirId, after: &Expr<'_>) -> bool {
170     let Some(block) = utils::get_enclosing_block(cx, local_id) else { return false };
171
172     // for _ in 1..3 {
173     //    local
174     // }
175     //
176     // let closure = || local;
177     // closure();
178     // closure();
179     let in_loop_or_closure = cx
180         .tcx
181         .hir()
182         .parent_iter(after.hir_id)
183         .take_while(|&(id, _)| id != block.hir_id)
184         .any(|(_, node)| {
185             matches!(
186                 node,
187                 Node::Expr(Expr {
188                     kind: ExprKind::Loop(..) | ExprKind::Closure(..),
189                     ..
190                 })
191             )
192         });
193     if in_loop_or_closure {
194         return true;
195     }
196
197     let mut used_after_expr = false;
198     let mut past_expr = false;
199     expr_visitor(cx, |expr| {
200         if used_after_expr {
201             return false;
202         }
203
204         if expr.hir_id == after.hir_id {
205             past_expr = true;
206             return false;
207         }
208
209         if past_expr && utils::path_to_local_id(expr, local_id) {
210             used_after_expr = true;
211         }
212         !used_after_expr
213     })
214     .visit_block(block);
215     used_after_expr
216 }