Skip to content

Commit 2666c38

Browse files
committed
Add [unused_peekable] lint
1 parent 868dba9 commit 2666c38

10 files changed

+386
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4152,6 +4152,7 @@ Released 2018-09-13
41524152
[`unused_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_collect
41534153
[`unused_io_amount`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount
41544154
[`unused_label`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_label
4155+
[`unused_peekable`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable
41554156
[`unused_rounding`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_rounding
41564157
[`unused_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_self
41574158
[`unused_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit

clippy_lints/src/lib.register_all.rs

+1
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
337337
LintId::of(unnecessary_sort_by::UNNECESSARY_SORT_BY),
338338
LintId::of(unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
339339
LintId::of(unused_io_amount::UNUSED_IO_AMOUNT),
340+
LintId::of(unused_peekable::UNUSED_PEEKABLE),
340341
LintId::of(unused_unit::UNUSED_UNIT),
341342
LintId::of(unwrap::PANICKING_UNWRAP),
342343
LintId::of(unwrap::UNNECESSARY_UNWRAP),

clippy_lints/src/lib.register_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,7 @@ store.register_lints(&[
573573
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
574574
unused_async::UNUSED_ASYNC,
575575
unused_io_amount::UNUSED_IO_AMOUNT,
576+
unused_peekable::UNUSED_PEEKABLE,
576577
unused_rounding::UNUSED_ROUNDING,
577578
unused_self::UNUSED_SELF,
578579
unused_unit::UNUSED_UNIT,

clippy_lints/src/lib.register_suspicious.rs

+1
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,5 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
3333
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
3434
LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF),
3535
LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS),
36+
LintId::of(unused_peekable::UNUSED_PEEKABLE),
3637
])

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@ mod unnested_or_patterns;
398398
mod unsafe_removed_from_name;
399399
mod unused_async;
400400
mod unused_io_amount;
401+
mod unused_peekable;
401402
mod unused_rounding;
402403
mod unused_self;
403404
mod unused_unit;
@@ -935,6 +936,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
935936
store.register_late_pass(|| Box::new(manual_instant_elapsed::ManualInstantElapsed));
936937
store.register_late_pass(|| Box::new(partialeq_to_none::PartialeqToNone));
937938
store.register_late_pass(|| Box::new(manual_empty_string_creations::ManualEmptyStringCreations));
939+
store.register_late_pass(|| Box::new(unused_peekable::UnusedPeekable::default()));
938940
// add lints here, do not remove this comment, it's used in `new_lint`
939941
}
940942

clippy_lints/src/unused_peekable.rs

+208
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
use clippy_utils::diagnostics::span_lint_and_help;
2+
use clippy_utils::ty::{match_type, peel_mid_ty_refs_is_mutable};
3+
use clippy_utils::{fn_def_id, path_to_local_id, paths, peel_ref_operators};
4+
use rustc_ast::Mutability;
5+
use rustc_hir::intravisit::{walk_expr, Visitor};
6+
use rustc_hir::lang_items::LangItem;
7+
use rustc_hir::{Block, Expr, ExprKind, HirId, Local, Node, PatKind, PathSegment, StmtKind};
8+
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_middle::ty::Ty;
10+
use rustc_session::{declare_tool_lint, impl_lint_pass};
11+
12+
declare_clippy_lint! {
13+
/// ### What it does
14+
/// Checks for the creation of a `peekable` iterator that is never `.peek()`ed
15+
///
16+
/// ### Why is this bad?
17+
/// Creating a peekable iterator without using any of its methods is likely a mistake,
18+
/// or just a leftover after a refactor.
19+
///
20+
/// ### Example
21+
/// ```rust
22+
/// let collection = vec![1, 2, 3];
23+
/// let iter = collection.iter().peekable();
24+
///
25+
/// for item in iter {
26+
/// // ...
27+
/// }
28+
/// ```
29+
///
30+
/// Use instead:
31+
/// ```rust
32+
/// let collection = vec![1, 2, 3];
33+
/// let iter = collection.iter();
34+
///
35+
/// for item in iter {
36+
/// // ...
37+
/// }
38+
/// ```
39+
#[clippy::version = "1.64.0"]
40+
pub UNUSED_PEEKABLE,
41+
suspicious,
42+
"creating a peekable iterator without using any of its methods"
43+
}
44+
45+
#[derive(Default)]
46+
pub struct UnusedPeekable {
47+
visited: Vec<HirId>,
48+
}
49+
50+
impl_lint_pass!(UnusedPeekable => [UNUSED_PEEKABLE]);
51+
52+
impl<'tcx> LateLintPass<'tcx> for UnusedPeekable {
53+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &Block<'tcx>) {
54+
// Don't lint `Peekable`s returned from a block
55+
if let Some(expr) = block.expr
56+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(peel_ref_operators(cx, expr))
57+
&& match_type(cx, ty, &paths::PEEKABLE)
58+
{
59+
return;
60+
}
61+
62+
for (idx, stmt) in block.stmts.iter().enumerate() {
63+
if !stmt.span.from_expansion()
64+
&& let StmtKind::Local(local) = stmt.kind
65+
&& !self.visited.contains(&local.pat.hir_id)
66+
&& let PatKind::Binding(_, _, ident, _) = local.pat.kind
67+
&& let Some(init) = local.init
68+
&& !init.span.from_expansion()
69+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(init)
70+
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
71+
&& match_type(cx, ty, &paths::PEEKABLE)
72+
{
73+
let mut vis = PeekableVisitor::new(cx, local.pat.hir_id);
74+
75+
if idx + 1 == block.stmts.len() && block.expr.is_none() {
76+
return;
77+
}
78+
79+
for stmt in &block.stmts[idx..] {
80+
vis.visit_stmt(stmt);
81+
}
82+
83+
if let Some(expr) = block.expr {
84+
vis.visit_expr(expr);
85+
}
86+
87+
if !vis.found_peek_call {
88+
span_lint_and_help(
89+
cx,
90+
UNUSED_PEEKABLE,
91+
ident.span,
92+
"`peek` never called on `Peekable` iterator",
93+
None,
94+
"consider removing the call to `peekable`"
95+
);
96+
}
97+
}
98+
}
99+
}
100+
}
101+
102+
struct PeekableVisitor<'a, 'tcx> {
103+
cx: &'a LateContext<'tcx>,
104+
expected_hir_id: HirId,
105+
found_peek_call: bool,
106+
}
107+
108+
impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> {
109+
fn new(cx: &'a LateContext<'tcx>, expected_hir_id: HirId) -> Self {
110+
Self {
111+
cx,
112+
expected_hir_id,
113+
found_peek_call: false,
114+
}
115+
}
116+
}
117+
118+
impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> {
119+
fn visit_expr(&mut self, ex: &'_ Expr<'_>) {
120+
if path_to_local_id(ex, self.expected_hir_id) {
121+
for (_, node) in self.cx.tcx.hir().parent_iter(ex.hir_id) {
122+
match node {
123+
Node::Expr(expr) => {
124+
match expr.kind {
125+
// some_function(peekable)
126+
//
127+
// If the Peekable is passed to a function, stop
128+
ExprKind::Call(_, args) => {
129+
if let Some(func_did) = fn_def_id(self.cx, expr)
130+
&& let Ok(into_iter_did) = self
131+
.cx
132+
.tcx
133+
.lang_items()
134+
.require(LangItem::IntoIterIntoIter)
135+
&& func_did == into_iter_did
136+
{
137+
// Probably a for loop desugar, stop searching
138+
return;
139+
}
140+
141+
for arg in args.iter().map(|arg| peel_ref_operators(self.cx, arg)) {
142+
if let ExprKind::Path(_) = arg.kind
143+
&& let Some(ty) = self
144+
.cx
145+
.typeck_results()
146+
.expr_ty_opt(arg)
147+
.map(Ty::peel_refs)
148+
&& match_type(self.cx, ty, &paths::PEEKABLE)
149+
{
150+
self.found_peek_call = true;
151+
return;
152+
}
153+
}
154+
},
155+
// Peekable::peek()
156+
ExprKind::MethodCall(PathSegment { ident: method_name, .. }, [arg, ..], _) => {
157+
let arg = peel_ref_operators(self.cx, arg);
158+
let method_name = method_name.name.as_str();
159+
160+
if (method_name == "peek"
161+
|| method_name == "peek_mut"
162+
|| method_name == "next_if"
163+
|| method_name == "next_if_eq")
164+
&& let ExprKind::Path(_) = arg.kind
165+
&& let Some(ty) = self.cx.typeck_results().expr_ty_opt(arg).map(Ty::peel_refs)
166+
&& match_type(self.cx, ty, &paths::PEEKABLE)
167+
{
168+
self.found_peek_call = true;
169+
return;
170+
}
171+
},
172+
// Don't bother if moved into a struct
173+
ExprKind::Struct(..) => {
174+
self.found_peek_call = true;
175+
return;
176+
},
177+
_ => {},
178+
}
179+
},
180+
Node::Local(Local { init: Some(init), .. }) => {
181+
if let Some(ty) = self.cx.typeck_results().expr_ty_opt(init)
182+
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
183+
&& match_type(self.cx, ty, &paths::PEEKABLE)
184+
{
185+
self.found_peek_call = true;
186+
return;
187+
}
188+
189+
break;
190+
},
191+
Node::Stmt(stmt) => match stmt.kind {
192+
StmtKind::Expr(_) | StmtKind::Semi(_) => {},
193+
_ => {
194+
self.found_peek_call = true;
195+
return;
196+
},
197+
},
198+
Node::Block(_) => {},
199+
_ => {
200+
break;
201+
},
202+
}
203+
}
204+
}
205+
206+
walk_expr(self, ex);
207+
}
208+
}

clippy_utils/src/paths.rs

+1
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ pub const PARKING_LOT_RWLOCK_READ_GUARD: [&str; 3] = ["lock_api", "rwlock", "RwL
9696
pub const PARKING_LOT_RWLOCK_WRITE_GUARD: [&str; 3] = ["lock_api", "rwlock", "RwLockWriteGuard"];
9797
pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
9898
pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
99+
pub const PEEKABLE: [&str; 5] = ["core", "iter", "adapters", "peekable", "Peekable"];
99100
pub const PERMISSIONS: [&str; 3] = ["std", "fs", "Permissions"];
100101
#[cfg_attr(not(unix), allow(clippy::invalid_paths))]
101102
pub const PERMISSIONS_FROM_MODE: [&str; 6] = ["std", "os", "unix", "fs", "PermissionsExt", "from_mode"];

clippy_utils/src/ty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
410410
peel(ty, 0)
411411
}
412412

413-
/// Peels off all references on the type.Returns the underlying type, the number of references
413+
/// Peels off all references on the type. Returns the underlying type, the number of references
414414
/// removed, and whether the pointer is ultimately mutable or not.
415415
pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
416416
fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {

tests/ui/unused_peekable.rs

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#![warn(clippy::unused_peekable)]
2+
#![allow(clippy::no_effect)]
3+
4+
use std::iter::Empty;
5+
use std::iter::Peekable;
6+
7+
fn main() {
8+
invalid();
9+
valid();
10+
}
11+
12+
#[allow(clippy::unused_unit)]
13+
fn invalid() {
14+
let peekable = std::iter::empty::<u32>().peekable();
15+
16+
// Only lint `new_local`
17+
let old_local = std::iter::empty::<u32>().peekable();
18+
let new_local = old_local;
19+
20+
// Behind mut ref
21+
let mut by_mut_ref_test = std::iter::empty::<u32>().peekable();
22+
let by_mut_ref = &mut by_mut_ref_test;
23+
24+
// Explicitly returns `Peekable`
25+
fn returns_peekable() -> Peekable<Empty<u32>> {
26+
std::iter::empty().peekable()
27+
}
28+
29+
let peekable_from_fn = returns_peekable();
30+
31+
// Using a method not exclusive to `Peekable`
32+
let mut peekable_using_iterator_method = std::iter::empty::<u32>().peekable();
33+
peekable_using_iterator_method.next();
34+
35+
let mut peekable_in_for_loop = std::iter::empty::<u32>().peekable();
36+
for x in peekable_in_for_loop {}
37+
}
38+
39+
fn valid() {
40+
fn takes_peekable(_peek: Peekable<Empty<u32>>) {}
41+
42+
// Passed to another function
43+
let passed_along = std::iter::empty::<u32>().peekable();
44+
takes_peekable(passed_along);
45+
46+
// `peek` called in another block
47+
let mut peekable_in_block = std::iter::empty::<u32>().peekable();
48+
{
49+
peekable_in_block.peek();
50+
}
51+
52+
// Check the other `Peekable` methods :)
53+
{
54+
let mut peekable_with_peek_mut = std::iter::empty::<u32>().peekable();
55+
peekable_with_peek_mut.peek_mut();
56+
57+
let mut peekable_with_next_if = std::iter::empty::<u32>().peekable();
58+
peekable_with_next_if.next_if(|_| true);
59+
60+
let mut peekable_with_next_if_eq = std::iter::empty::<u32>().peekable();
61+
peekable_with_next_if_eq.next_if_eq(&3);
62+
}
63+
64+
let mut peekable_in_closure = std::iter::empty::<u32>().peekable();
65+
let call_peek = |p: &mut Peekable<Empty<u32>>| {
66+
p.peek();
67+
};
68+
call_peek(&mut peekable_in_closure);
69+
70+
// From a macro
71+
macro_rules! make_me_a_peekable_please {
72+
() => {
73+
std::iter::empty::<u32>().peekable()
74+
};
75+
}
76+
77+
let _unsuspecting_macro_user = make_me_a_peekable_please!();
78+
79+
// Generic Iterator returned
80+
fn return_an_iter() -> impl Iterator<Item = u32> {
81+
std::iter::empty::<u32>().peekable()
82+
}
83+
84+
let _unsuspecting_user = return_an_iter();
85+
86+
// Call `peek` in a macro
87+
macro_rules! peek_iter {
88+
($iter:ident) => {
89+
$iter.peek();
90+
};
91+
}
92+
93+
let mut peek_in_macro = std::iter::empty::<u32>().peekable();
94+
peek_iter!(peek_in_macro);
95+
96+
// Behind mut ref
97+
let mut by_mut_ref_test = std::iter::empty::<u32>().peekable();
98+
let by_mut_ref = &mut by_mut_ref_test;
99+
by_mut_ref.peek();
100+
101+
// Behind ref
102+
let mut by_ref_test = std::iter::empty::<u32>().peekable();
103+
let by_ref = &by_ref_test;
104+
by_ref_test.peek();
105+
106+
// In struct
107+
struct PeekableWrapper {
108+
f: Peekable<Empty<u32>>,
109+
}
110+
111+
let struct_test = std::iter::empty::<u32>().peekable();
112+
PeekableWrapper { f: struct_test };
113+
114+
// `peek` called in another block as the last expression
115+
let mut peekable_last_expr = std::iter::empty::<u32>().peekable();
116+
{
117+
peekable_last_expr.peek();
118+
}
119+
}

0 commit comments

Comments
 (0)