]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/usage.rs
Rollup merge of #102747 - notriddle:notriddle/docblock-a-not-srclink, r=GuillaumeGomez
[rust.git] / src / tools / clippy / clippy_utils / src / usage.rs
1 use crate as utils;
2 use crate::visitors::{for_each_expr, for_each_expr_with_closures, Descend};
3 use core::ops::ControlFlow;
4 use rustc_hir as hir;
5 use rustc_hir::intravisit::{self, Visitor};
6 use rustc_hir::HirIdSet;
7 use rustc_hir::{Expr, ExprKind, HirId, Node};
8 use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
9 use rustc_infer::infer::TyCtxtInferExt;
10 use rustc_lint::LateContext;
11 use rustc_middle::hir::nested_filter;
12 use rustc_middle::mir::FakeReadCause;
13 use rustc_middle::ty;
14
15 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
16 pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option<HirIdSet> {
17     let mut delegate = MutVarsDelegate {
18         used_mutably: HirIdSet::default(),
19         skip: false,
20     };
21     cx.tcx.infer_ctxt().enter(|infcx| {
22         ExprUseVisitor::new(
23             &mut delegate,
24             &infcx,
25             expr.hir_id.owner.def_id,
26             cx.param_env,
27             cx.typeck_results(),
28         )
29         .walk_expr(expr);
30     });
31
32     if delegate.skip {
33         return None;
34     }
35     Some(delegate.used_mutably)
36 }
37
38 pub fn is_potentially_mutated<'tcx>(variable: HirId, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
39     mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&variable))
40 }
41
42 struct MutVarsDelegate {
43     used_mutably: HirIdSet,
44     skip: bool,
45 }
46
47 impl<'tcx> MutVarsDelegate {
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 bk == ty::BorrowKind::MutBorrow {
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(
78         &mut self,
79         _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>,
80         _: FakeReadCause,
81         _: HirId,
82     ) {
83     }
84 }
85
86 pub struct ParamBindingIdCollector {
87     pub binding_hir_ids: Vec<hir::HirId>,
88 }
89 impl<'tcx> ParamBindingIdCollector {
90     fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec<hir::HirId> {
91         let mut hir_ids: Vec<hir::HirId> = Vec::new();
92         for param in body.params.iter() {
93             let mut finder = ParamBindingIdCollector {
94                 binding_hir_ids: Vec::new(),
95             };
96             finder.visit_param(param);
97             for hir_id in &finder.binding_hir_ids {
98                 hir_ids.push(*hir_id);
99             }
100         }
101         hir_ids
102     }
103 }
104 impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
105     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
106         if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind {
107             self.binding_hir_ids.push(hir_id);
108         }
109         intravisit::walk_pat(self, pat);
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 NestedFilter = nested_filter::OnlyBodies;
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) -> Self::Map {
147         self.cx.tcx.hir()
148     }
149 }
150
151 pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
152     for_each_expr(expression, |e| {
153         match e.kind {
154             ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => ControlFlow::Break(()),
155             // Something special could be done here to handle while or for loop
156             // desugaring, as this will detect a break if there's a while loop
157             // or a for loop inside the expression.
158             _ if e.span.from_expansion() => ControlFlow::Break(()),
159             _ => ControlFlow::Continue(()),
160         }
161     })
162     .is_some()
163 }
164
165 pub fn local_used_after_expr(cx: &LateContext<'_>, local_id: HirId, after: &Expr<'_>) -> bool {
166     let Some(block) = utils::get_enclosing_block(cx, local_id) else { return false };
167
168     // for _ in 1..3 {
169     //    local
170     // }
171     //
172     // let closure = || local;
173     // closure();
174     // closure();
175     let in_loop_or_closure = cx
176         .tcx
177         .hir()
178         .parent_iter(after.hir_id)
179         .take_while(|&(id, _)| id != block.hir_id)
180         .any(|(_, node)| {
181             matches!(
182                 node,
183                 Node::Expr(Expr {
184                     kind: ExprKind::Loop(..) | ExprKind::Closure { .. },
185                     ..
186                 })
187             )
188         });
189     if in_loop_or_closure {
190         return true;
191     }
192
193     let mut past_expr = false;
194     for_each_expr_with_closures(cx, block, |e| {
195         if e.hir_id == after.hir_id {
196             past_expr = true;
197             ControlFlow::Continue(Descend::No)
198         } else if past_expr && utils::path_to_local_id(e, local_id) {
199             ControlFlow::Break(())
200         } else {
201             ControlFlow::Continue(Descend::Yes)
202         }
203     })
204     .is_some()
205 }