Skip to content

Commit 8cf6dae

Browse files
committed
Add for_each_local_usage. Switch LocalUsedVisitor to a function.
1 parent 983e5b8 commit 8cf6dae

File tree

10 files changed

+91
-104
lines changed

10 files changed

+91
-104
lines changed

clippy_lints/src/bytecount.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::source::snippet_with_applicability;
33
use clippy_utils::ty::match_type;
4-
use clippy_utils::visitors::LocalUsedVisitor;
4+
use clippy_utils::visitors::is_local_used;
55
use clippy_utils::{path_to_local_id, paths, peel_ref_operators, remove_blocks, strip_pat_refs};
66
use if_chain::if_chain;
77
use rustc_errors::Applicability;
@@ -65,7 +65,7 @@ impl<'tcx> LateLintPass<'tcx> for ByteCount {
6565
return;
6666
};
6767
if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
68-
if !LocalUsedVisitor::new(cx, arg_id).check_expr(needle);
68+
if !is_local_used(cx, needle, arg_id);
6969
then {
7070
let haystack = if let ExprKind::MethodCall(path, _, args, _) =
7171
filter_recv.kind {

clippy_lints/src/collapsible_match.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
2-
use clippy_utils::visitors::LocalUsedVisitor;
2+
use clippy_utils::visitors::is_local_used;
33
use clippy_utils::{is_lang_ctor, path_to_local, peel_ref_operators, SpanlessEq};
44
use if_chain::if_chain;
55
use rustc_hir::LangItem::OptionNone;
@@ -83,13 +83,12 @@ fn check_arm<'tcx>(arm: &Arm<'tcx>, wild_outer_arm: &Arm<'tcx>, cx: &LateContext
8383
// the "wild-like" branches must be equal
8484
if SpanlessEq::new(cx).eq_expr(wild_inner_arm.body, wild_outer_arm.body);
8585
// the binding must not be used in the if guard
86-
let mut used_visitor = LocalUsedVisitor::new(cx, binding_id);
8786
if match arm.guard {
8887
None => true,
89-
Some(Guard::If(expr) | Guard::IfLet(_, expr)) => !used_visitor.check_expr(expr),
88+
Some(Guard::If(expr) | Guard::IfLet(_, expr)) => !is_local_used(cx, expr, binding_id),
9089
};
9190
// ...or anywhere in the inner match
92-
if !arms_inner.iter().any(|arm| used_visitor.check_arm(arm));
91+
if !arms_inner.iter().any(|arm| is_local_used(cx, arm, binding_id));
9392
then {
9493
span_lint_and_then(
9594
cx,

clippy_lints/src/let_if_seq.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
22
use clippy_utils::source::snippet;
3-
use clippy_utils::{path_to_local_id, visitors::LocalUsedVisitor};
3+
use clippy_utils::{path_to_local_id, visitors::is_local_used};
44
use if_chain::if_chain;
55
use rustc_errors::Applicability;
66
use rustc_hir as hir;
@@ -65,11 +65,10 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
6565
if let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.kind;
6666
if let hir::StmtKind::Expr(if_) = expr.kind;
6767
if let hir::ExprKind::If(cond, then, ref else_) = if_.kind;
68-
let mut used_visitor = LocalUsedVisitor::new(cx, canonical_id);
69-
if !used_visitor.check_expr(cond);
68+
if !is_local_used(cx, cond, canonical_id);
7069
if let hir::ExprKind::Block(then, _) = then.kind;
7170
if let Some(value) = check_assign(cx, canonical_id, &*then);
72-
if !used_visitor.check_expr(value);
71+
if !is_local_used(cx, value, canonical_id);
7372
then {
7473
let span = stmt.span.to(if_.span);
7574

@@ -148,15 +147,13 @@ fn check_assign<'tcx>(
148147
if let hir::ExprKind::Assign(var, value, _) = expr.kind;
149148
if path_to_local_id(var, decl);
150149
then {
151-
let mut v = LocalUsedVisitor::new(cx, decl);
152-
153-
if block.stmts.iter().take(block.stmts.len()-1).any(|stmt| v.check_stmt(stmt)) {
154-
return None;
150+
if block.stmts.iter().take(block.stmts.len()-1).any(|stmt| is_local_used(cx, stmt, decl)) {
151+
None
152+
} else {
153+
Some(value)
155154
}
156-
157-
return Some(value);
155+
} else {
156+
None
158157
}
159158
}
160-
161-
None
162159
}

clippy_lints/src/loops/for_kv_map.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then};
33
use clippy_utils::source::snippet;
44
use clippy_utils::sugg;
55
use clippy_utils::ty::is_type_diagnostic_item;
6-
use clippy_utils::visitors::LocalUsedVisitor;
6+
use clippy_utils::visitors::is_local_used;
77
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind};
88
use rustc_lint::LateContext;
99
use rustc_middle::ty;
@@ -66,9 +66,7 @@ pub(super) fn check<'tcx>(
6666
fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
6767
match *pat {
6868
PatKind::Wild => true,
69-
PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => {
70-
!LocalUsedVisitor::new(cx, id).check_expr(body)
71-
},
69+
PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => !is_local_used(cx, body, id),
7270
_ => false,
7371
}
7472
}

clippy_lints/src/loops/manual_flatten.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::utils::make_iterator_snippet;
22
use super::MANUAL_FLATTEN;
33
use clippy_utils::diagnostics::span_lint_and_then;
4-
use clippy_utils::visitors::LocalUsedVisitor;
4+
use clippy_utils::visitors::is_local_used;
55
use clippy_utils::{is_lang_ctor, path_to_local_id};
66
use if_chain::if_chain;
77
use rustc_errors::Applicability;
@@ -49,7 +49,7 @@ pub(super) fn check<'tcx>(
4949
let ok_ctor = is_lang_ctor(cx, qpath, ResultOk);
5050
if some_ctor || ok_ctor;
5151
// Ensure epxr in `if let` is not used afterwards
52-
if !LocalUsedVisitor::new(cx, pat_hir_id).check_arm(true_arm);
52+
if !is_local_used(cx, true_arm, pat_hir_id);
5353
then {
5454
let if_let_type = if some_ctor { "Some" } else { "Ok" };
5555
// Prepare the error message

clippy_lints/src/loops/needless_range_loop.rs

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@ use super::NEEDLESS_RANGE_LOOP;
22
use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then};
33
use clippy_utils::source::snippet;
44
use clippy_utils::ty::has_iter_method;
5-
use clippy_utils::visitors::LocalUsedVisitor;
6-
use clippy_utils::{
7-
contains_name, higher, is_integer_const, match_trait_method, path_to_local_id, paths, sugg, SpanlessEq,
8-
};
5+
use clippy_utils::visitors::is_local_used;
6+
use clippy_utils::{contains_name, higher, is_integer_const, match_trait_method, paths, sugg, SpanlessEq};
97
use if_chain::if_chain;
108
use rustc_ast::ast;
119
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
@@ -256,43 +254,36 @@ impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
256254
if let ExprKind::Path(ref seqpath) = seqexpr.kind;
257255
if let QPath::Resolved(None, seqvar) = *seqpath;
258256
if seqvar.segments.len() == 1;
259-
let index_used_directly = path_to_local_id(idx, self.var);
260-
let indexed_indirectly = {
261-
let mut used_visitor = LocalUsedVisitor::new(self.cx, self.var);
262-
walk_expr(&mut used_visitor, idx);
263-
used_visitor.used
264-
};
265-
if indexed_indirectly || index_used_directly;
257+
if is_local_used(self.cx, idx, self.var);
266258
then {
267259
if self.prefer_mutable {
268260
self.indexed_mut.insert(seqvar.segments[0].ident.name);
269261
}
262+
let index_used_directly = matches!(idx.kind, ExprKind::Path(_));
270263
let res = self.cx.qpath_res(seqpath, seqexpr.hir_id);
271264
match res {
272265
Res::Local(hir_id) => {
273266
let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
274267
let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
275268
let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
276-
if indexed_indirectly {
277-
self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
278-
}
279269
if index_used_directly {
280270
self.indexed_directly.insert(
281271
seqvar.segments[0].ident.name,
282272
(Some(extent), self.cx.typeck_results().node_type(seqexpr.hir_id)),
283273
);
274+
} else {
275+
self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
284276
}
285277
return false; // no need to walk further *on the variable*
286278
}
287279
Res::Def(DefKind::Static | DefKind::Const, ..) => {
288-
if indexed_indirectly {
289-
self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
290-
}
291280
if index_used_directly {
292281
self.indexed_directly.insert(
293282
seqvar.segments[0].ident.name,
294283
(None, self.cx.typeck_results().node_type(seqexpr.hir_id)),
295284
);
285+
} else {
286+
self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
296287
}
297288
return false; // no need to walk further *on the variable*
298289
}

clippy_lints/src/matches.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use clippy_utils::diagnostics::{
55
use clippy_utils::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
66
use clippy_utils::sugg::Sugg;
77
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
8-
use clippy_utils::visitors::LocalUsedVisitor;
8+
use clippy_utils::visitors::is_local_used;
99
use clippy_utils::{
1010
get_parent_expr, in_macro, is_expn_of, is_lang_ctor, is_lint_allowed, is_refutable, is_wild, meets_msrv, msrvs,
1111
path_to_local, path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks,
@@ -953,9 +953,7 @@ fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm
953953
// Looking for unused bindings (i.e.: `_e`)
954954
for pat in inner.iter() {
955955
if let PatKind::Binding(_, id, ident, None) = pat.kind {
956-
if ident.as_str().starts_with('_')
957-
&& !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
958-
{
956+
if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
959957
ident_bind_name = (&ident.name.as_str()).to_string();
960958
matching_wild = true;
961959
}

clippy_lints/src/unused_self.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use clippy_utils::diagnostics::span_lint_and_help;
2-
use clippy_utils::visitors::LocalUsedVisitor;
2+
use clippy_utils::visitors::is_local_used;
33
use if_chain::if_chain;
44
use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind};
55
use rustc_lint::{LateContext, LateLintPass};
@@ -50,8 +50,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf {
5050
if let ImplItemKind::Fn(.., body_id) = &impl_item.kind;
5151
let body = cx.tcx.hir().body(*body_id);
5252
if let [self_param, ..] = body.params;
53-
let self_hir_id = self_param.pat.hir_id;
54-
if !LocalUsedVisitor::new(cx, self_hir_id).check_body(body);
53+
if !is_local_used(cx, body, self_param.pat.hir_id);
5554
then {
5655
span_lint_and_help(
5756
cx,

clippy_utils/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#![feature(in_band_lifetimes)]
33
#![feature(iter_zip)]
44
#![feature(rustc_private)]
5+
#![feature(control_flow_enum)]
56
#![recursion_limit = "512"]
67
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
78
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate)]

clippy_utils/src/visitors.rs

Lines changed: 60 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use rustc_hir::intravisit::{self, walk_expr, ErasedMap, NestedVisitorMap, Visito
44
use rustc_hir::{def::Res, Arm, Block, Body, BodyId, Destination, Expr, ExprKind, HirId, Stmt};
55
use rustc_lint::LateContext;
66
use rustc_middle::hir::map::Map;
7+
use std::ops::ControlFlow;
78

89
/// returns `true` if expr contains match expr desugared from try
910
fn contains_try(expr: &hir::Expr<'_>) -> bool {
@@ -133,62 +134,6 @@ where
133134
}
134135
}
135136

136-
pub struct LocalUsedVisitor<'hir> {
137-
hir: Map<'hir>,
138-
pub local_hir_id: HirId,
139-
pub used: bool,
140-
}
141-
142-
impl<'hir> LocalUsedVisitor<'hir> {
143-
pub fn new(cx: &LateContext<'hir>, local_hir_id: HirId) -> Self {
144-
Self {
145-
hir: cx.tcx.hir(),
146-
local_hir_id,
147-
used: false,
148-
}
149-
}
150-
151-
fn check<T>(&mut self, t: T, visit: fn(&mut Self, T)) -> bool {
152-
visit(self, t);
153-
std::mem::replace(&mut self.used, false)
154-
}
155-
156-
pub fn check_arm(&mut self, arm: &'hir Arm<'_>) -> bool {
157-
self.check(arm, Self::visit_arm)
158-
}
159-
160-
pub fn check_body(&mut self, body: &'hir Body<'_>) -> bool {
161-
self.check(body, Self::visit_body)
162-
}
163-
164-
pub fn check_expr(&mut self, expr: &'hir Expr<'_>) -> bool {
165-
self.check(expr, Self::visit_expr)
166-
}
167-
168-
pub fn check_stmt(&mut self, stmt: &'hir Stmt<'_>) -> bool {
169-
self.check(stmt, Self::visit_stmt)
170-
}
171-
}
172-
173-
impl<'v> Visitor<'v> for LocalUsedVisitor<'v> {
174-
type Map = Map<'v>;
175-
176-
fn visit_expr(&mut self, expr: &'v Expr<'v>) {
177-
if self.used {
178-
return;
179-
}
180-
if path_to_local_id(expr, self.local_hir_id) {
181-
self.used = true;
182-
} else {
183-
walk_expr(self, expr);
184-
}
185-
}
186-
187-
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
188-
NestedVisitorMap::OnlyBodies(self.hir)
189-
}
190-
}
191-
192137
/// A type which can be visited.
193138
pub trait Visitable<'tcx> {
194139
/// Calls the corresponding `visit_*` function on the visitor.
@@ -202,8 +147,22 @@ macro_rules! visitable_ref {
202147
}
203148
}
204149
};
150+
([$t:ident], $f:ident) => {
151+
impl Visitable<'tcx> for &'tcx [$t<'tcx>] {
152+
fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
153+
for x in self {
154+
visitor.$f(x);
155+
}
156+
}
157+
}
158+
};
205159
}
160+
visitable_ref!(Arm, visit_arm);
206161
visitable_ref!(Block, visit_block);
162+
visitable_ref!(Body, visit_body);
163+
visitable_ref!(Expr, visit_expr);
164+
visitable_ref!(Stmt, visit_stmt);
165+
visitable_ref!([Stmt], visit_stmt);
207166

208167
/// Calls the given function for each break expression.
209168
pub fn visit_break_exprs<'tcx>(
@@ -260,3 +219,48 @@ pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool {
260219
v.visit_expr(&cx.tcx.hir().body(body).value);
261220
v.found
262221
}
222+
223+
/// Calls the given function for each usage of the given local.
224+
pub fn for_each_local_usage<'tcx, B>(
225+
cx: &LateContext<'tcx>,
226+
visitable: impl Visitable<'tcx>,
227+
id: HirId,
228+
f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
229+
) -> ControlFlow<B> {
230+
struct V<'tcx, B, F> {
231+
map: Map<'tcx>,
232+
id: HirId,
233+
f: F,
234+
res: ControlFlow<B>,
235+
}
236+
impl<'tcx, B, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>> Visitor<'tcx> for V<'tcx, B, F> {
237+
type Map = Map<'tcx>;
238+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
239+
NestedVisitorMap::OnlyBodies(self.map)
240+
}
241+
242+
fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
243+
if self.res.is_continue() {
244+
if path_to_local_id(e, self.id) {
245+
self.res = (self.f)(e);
246+
} else {
247+
walk_expr(self, e);
248+
}
249+
}
250+
}
251+
}
252+
253+
let mut v = V {
254+
map: cx.tcx.hir(),
255+
id,
256+
f,
257+
res: ControlFlow::CONTINUE,
258+
};
259+
visitable.visit(&mut v);
260+
v.res
261+
}
262+
263+
/// Checks if the given local is used.
264+
pub fn is_local_used(cx: &LateContext<'tcx>, visitable: impl Visitable<'tcx>, id: HirId) -> bool {
265+
for_each_local_usage(cx, visitable, id, |_| ControlFlow::BREAK).is_break()
266+
}

0 commit comments

Comments
 (0)