]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/usage.rs
Merge commit '928e72dd10749875cbd412f74bfbfd7765dbcd8a' into clippyup
[rust.git] / clippy_utils / src / usage.rs
1 use crate as utils;
2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_hir as hir;
4 use rustc_hir::def::Res;
5 use rustc_hir::intravisit;
6 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
7 use rustc_hir::{Expr, ExprKind, HirId, Path};
8 use rustc_infer::infer::TyCtxtInferExt;
9 use rustc_lint::LateContext;
10 use rustc_middle::hir::map::Map;
11 use rustc_middle::ty;
12 use rustc_typeck::expr_use_visitor::{ConsumeMode, 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<FxHashSet<HirId>> {
16     let mut delegate = MutVarsDelegate {
17         used_mutably: FxHashSet::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: &'tcx Path<'_>, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
38     if let Res::Local(id) = variable.res {
39         mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
40     } else {
41         true
42     }
43 }
44
45 struct MutVarsDelegate {
46     used_mutably: FxHashSet<HirId>,
47     skip: bool,
48 }
49
50 impl<'tcx> MutVarsDelegate {
51     #[allow(clippy::similar_names)]
52     fn update(&mut self, cat: &PlaceWithHirId<'tcx>) {
53         match cat.place.base {
54             PlaceBase::Local(id) => {
55                 self.used_mutably.insert(id);
56             },
57             PlaceBase::Upvar(_) => {
58                 //FIXME: This causes false negatives. We can't get the `NodeId` from
59                 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
60                 //`while`-body, not just the ones in the condition.
61                 self.skip = true
62             },
63             _ => {},
64         }
65     }
66 }
67
68 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
69     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId, _: ConsumeMode) {}
70
71     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, bk: ty::BorrowKind) {
72         if let ty::BorrowKind::MutBorrow = bk {
73             self.update(&cmt)
74         }
75     }
76
77     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
78         self.update(&cmt)
79     }
80 }
81
82 pub struct ParamBindingIdCollector {
83     binding_hir_ids: Vec<hir::HirId>,
84 }
85 impl<'tcx> ParamBindingIdCollector {
86     fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec<hir::HirId> {
87         let mut hir_ids: Vec<hir::HirId> = Vec::new();
88         for param in body.params.iter() {
89             let mut finder = ParamBindingIdCollector {
90                 binding_hir_ids: Vec::new(),
91             };
92             finder.visit_param(param);
93             for hir_id in &finder.binding_hir_ids {
94                 hir_ids.push(*hir_id);
95             }
96         }
97         hir_ids
98     }
99 }
100 impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
101     type Map = Map<'tcx>;
102
103     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
104         if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind {
105             self.binding_hir_ids.push(hir_id);
106         }
107         intravisit::walk_pat(self, pat);
108     }
109
110     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
111         intravisit::NestedVisitorMap::None
112     }
113 }
114
115 pub struct BindingUsageFinder<'a, 'tcx> {
116     cx: &'a LateContext<'tcx>,
117     binding_ids: Vec<hir::HirId>,
118     usage_found: bool,
119 }
120 impl<'a, 'tcx> BindingUsageFinder<'a, 'tcx> {
121     pub fn are_params_used(cx: &'a LateContext<'tcx>, body: &'tcx hir::Body<'tcx>) -> bool {
122         let mut finder = BindingUsageFinder {
123             cx,
124             binding_ids: ParamBindingIdCollector::collect_binding_hir_ids(body),
125             usage_found: false,
126         };
127         finder.visit_body(body);
128         finder.usage_found
129     }
130 }
131 impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> {
132     type Map = Map<'tcx>;
133
134     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
135         if !self.usage_found {
136             intravisit::walk_expr(self, expr);
137         }
138     }
139
140     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
141         if let hir::def::Res::Local(id) = path.res {
142             if self.binding_ids.contains(&id) {
143                 self.usage_found = true;
144             }
145         }
146     }
147
148     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
149         intravisit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
150     }
151 }
152
153 struct ReturnBreakContinueMacroVisitor {
154     seen_return_break_continue: bool,
155 }
156
157 impl ReturnBreakContinueMacroVisitor {
158     fn new() -> ReturnBreakContinueMacroVisitor {
159         ReturnBreakContinueMacroVisitor {
160             seen_return_break_continue: false,
161         }
162     }
163 }
164
165 impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor {
166     type Map = Map<'tcx>;
167     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
168         NestedVisitorMap::None
169     }
170
171     fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
172         if self.seen_return_break_continue {
173             // No need to look farther if we've already seen one of them
174             return;
175         }
176         match &ex.kind {
177             ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
178                 self.seen_return_break_continue = true;
179             },
180             // Something special could be done here to handle while or for loop
181             // desugaring, as this will detect a break if there's a while loop
182             // or a for loop inside the expression.
183             _ => {
184                 if utils::in_macro(ex.span) {
185                     self.seen_return_break_continue = true;
186                 } else {
187                     rustc_hir::intravisit::walk_expr(self, ex);
188                 }
189             },
190         }
191     }
192 }
193
194 pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
195     let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new();
196     recursive_visitor.visit_expr(expression);
197     recursive_visitor.seen_return_break_continue
198 }