Skip to content

Commit 23b7547

Browse files
committed
Add [unused_peekable] lint
1 parent 3c7e7db commit 23b7547

File tree

9 files changed

+275
-0
lines changed

9 files changed

+275
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3998,6 +3998,7 @@ Released 2018-09-13
39983998
[`unused_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_collect
39993999
[`unused_io_amount`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount
40004000
[`unused_label`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_label
4001+
[`unused_peekable`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable
40014002
[`unused_rounding`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_rounding
40024003
[`unused_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_self
40034004
[`unused_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 0 deletions
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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,7 @@ store.register_lints(&[
568568
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
569569
unused_async::UNUSED_ASYNC,
570570
unused_io_amount::UNUSED_IO_AMOUNT,
571+
unused_peekable::UNUSED_PEEKABLE,
571572
unused_rounding::UNUSED_ROUNDING,
572573
unused_self::UNUSED_SELF,
573574
unused_unit::UNUSED_UNIT,

clippy_lints/src/lib.register_suspicious.rs

Lines changed: 1 addition & 0 deletions
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_ARITHMETIC_IMPL),
3434
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
3535
LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF),
36+
LintId::of(unused_peekable::UNUSED_PEEKABLE),
3637
])

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,7 @@ mod unnested_or_patterns;
395395
mod unsafe_removed_from_name;
396396
mod unused_async;
397397
mod unused_io_amount;
398+
mod unused_peekable;
398399
mod unused_rounding;
399400
mod unused_self;
400401
mod unused_unit;
@@ -920,6 +921,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
920921
store.register_late_pass(move || Box::new(operators::Operators::new(verbose_bit_mask_threshold)));
921922
store.register_late_pass(|| Box::new(invalid_utf8_in_unchecked::InvalidUtf8InUnchecked));
922923
store.register_late_pass(|| Box::new(std_instead_of_core::StdReexports::default()));
924+
store.register_late_pass(|| Box::new(unused_peekable::UnusedPeekable));
923925
// add lints here, do not remove this comment, it's used in `new_lint`
924926
}
925927

clippy_lints/src/unused_peekable.rs

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
use clippy_utils::diagnostics::span_lint_and_help;
2+
use clippy_utils::ty::match_type;
3+
use clippy_utils::{match_qpath, paths, peel_ref_operators};
4+
use rustc_hir::intravisit::{walk_expr, Visitor};
5+
use rustc_hir::{Block, Expr, ExprKind, PatKind, PathSegment, StmtKind};
6+
use rustc_lint::{LateContext, LateLintPass};
7+
use rustc_middle::ty::Ty;
8+
use rustc_session::{declare_lint_pass, declare_tool_lint};
9+
10+
declare_clippy_lint! {
11+
/// ### What it does
12+
/// Checks for the creation of a `peekable` iterator that is never `.peek()`ed
13+
///
14+
/// ### Why is this bad?
15+
/// Creating a peekable iterator without using any of its methods is likely a mistake,
16+
/// or just a leftover after a refactor.
17+
///
18+
/// ### Example
19+
/// ```rust
20+
/// let collection = vec![1, 2, 3];
21+
/// let iter = collection.iter().peekable();
22+
///
23+
/// for item in iter {
24+
/// // ...
25+
/// }
26+
/// ```
27+
///
28+
/// Use instead:
29+
/// ```rust
30+
/// let collection = vec![1, 2, 3];
31+
/// let iter = collection.iter();
32+
///
33+
/// for item in iter {
34+
/// // ...
35+
/// }
36+
/// ```
37+
#[clippy::version = "1.64.0"]
38+
pub UNUSED_PEEKABLE,
39+
suspicious,
40+
"creating a peekable iterator without using any of its methods"
41+
}
42+
43+
declare_lint_pass!(UnusedPeekable => [UNUSED_PEEKABLE]);
44+
45+
impl<'tcx> LateLintPass<'tcx> for UnusedPeekable {
46+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &Block<'tcx>) {
47+
// Don't lint `Peekable`s returned from a block
48+
if let Some(expr) = block.expr
49+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(peel_ref_operators(cx, expr))
50+
&& match_type(cx, ty, &paths::PEEKABLE)
51+
{
52+
return;
53+
}
54+
55+
for (idx, stmt) in block.stmts.iter().enumerate() {
56+
if !stmt.span.from_expansion()
57+
&& let StmtKind::Local(local) = stmt.kind
58+
&& let PatKind::Binding(_, _, ident, _) = local.pat.kind
59+
&& let Some(init) = local.init
60+
&& !init.span.from_expansion()
61+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(init)
62+
&& match_type(cx, ty, &paths::PEEKABLE)
63+
{
64+
let ident_str = ident.name.as_str();
65+
let mut vis = PeekableVisitor::new(cx, ident_str);
66+
67+
if idx + 1 == block.stmts.len() {
68+
if let Some(expr) = block.expr {
69+
vis.visit_expr(expr);
70+
} else {
71+
return;
72+
}
73+
} else {
74+
for stmt in &block.stmts[idx..] {
75+
vis.visit_stmt(stmt);
76+
}
77+
}
78+
79+
if !vis.found_peek_call {
80+
span_lint_and_help(
81+
cx,
82+
UNUSED_PEEKABLE,
83+
ident.span,
84+
"`peek` never called on `Peekable` iterator",
85+
None,
86+
"consider removing the call to `peekable`"
87+
);
88+
}
89+
}
90+
}
91+
}
92+
}
93+
94+
struct PeekableVisitor<'a, 'tcx> {
95+
cx: &'a LateContext<'tcx>,
96+
expected_ident: &'a str,
97+
found_peek_call: bool,
98+
}
99+
100+
impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> {
101+
fn new(cx: &'a LateContext<'tcx>, expected_ident: &'a str) -> Self {
102+
Self {
103+
cx,
104+
expected_ident,
105+
found_peek_call: false,
106+
}
107+
}
108+
}
109+
110+
impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> {
111+
fn visit_expr(&mut self, ex: &'_ Expr<'_>) {
112+
match ex.kind {
113+
// some_function(peekable)
114+
//
115+
// If the Peekable is passed to a function, stop
116+
ExprKind::Call(_, args) => {
117+
for arg in args.iter().map(|arg| peel_ref_operators(self.cx, arg)) {
118+
if let ExprKind::Path(ref qpath) = arg.kind
119+
&& match_qpath(qpath, &[self.expected_ident])
120+
&& let Some(ty) = self.cx.typeck_results().expr_ty_opt(arg).map(Ty::peel_refs)
121+
&& match_type(self.cx, ty.peel_refs(), &paths::PEEKABLE)
122+
{
123+
self.found_peek_call = true;
124+
return;
125+
}
126+
}
127+
},
128+
// Peekable::peek()
129+
ExprKind::MethodCall(PathSegment { ident: method_name, .. }, [arg, ..], _) => {
130+
let arg = peel_ref_operators(self.cx, arg);
131+
let method_name = method_name.name.as_str();
132+
133+
if (method_name == "peek"
134+
|| method_name == "peek_mut"
135+
|| method_name == "next_if"
136+
|| method_name == "next_if_eq")
137+
&& let ExprKind::Path(ref qpath) = arg.kind
138+
&& match_qpath(qpath, &[self.expected_ident])
139+
&& let Some(ty) = self.cx.typeck_results().expr_ty_opt(arg).map(Ty::peel_refs)
140+
&& match_type(self.cx, ty, &paths::PEEKABLE)
141+
{
142+
self.found_peek_call = true;
143+
return;
144+
}
145+
},
146+
_ => {},
147+
}
148+
149+
walk_expr(self, ex);
150+
}
151+
}

clippy_utils/src/paths.rs

Lines changed: 1 addition & 0 deletions
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"];

tests/ui/unused_peekable.rs

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#![warn(clippy::unused_peekable)]
2+
3+
use std::iter::Empty;
4+
use std::iter::Peekable;
5+
6+
fn main() {
7+
invalid();
8+
valid();
9+
}
10+
11+
#[allow(clippy::unused_unit)]
12+
fn invalid() {
13+
let peekable = std::iter::empty::<u32>().peekable();
14+
15+
// Lint both
16+
let old_local = std::iter::empty::<u32>().peekable();
17+
let new_local = old_local;
18+
19+
// Explicitly returns `Peekable`
20+
fn returns_peekable() -> Peekable<Empty<u32>> {
21+
std::iter::empty().peekable()
22+
}
23+
24+
let my_peekable = returns_peekable();
25+
26+
// Just so the local isn't the last statement
27+
()
28+
}
29+
30+
fn valid() {
31+
fn takes_peekable(_peek: Peekable<Empty<u32>>) {}
32+
33+
// Passed to another function
34+
let passed_along = std::iter::empty::<u32>().peekable();
35+
takes_peekable(passed_along);
36+
37+
// `peek` called in another block
38+
let mut peekable_in_block = std::iter::empty::<u32>().peekable();
39+
{
40+
peekable_in_block.peek();
41+
}
42+
43+
// Check the other `Peekable` methods :)
44+
{
45+
let mut peekable_with_peek_mut = std::iter::empty::<u32>().peekable();
46+
peekable_with_peek_mut.peek_mut();
47+
48+
let mut peekable_with_next_if = std::iter::empty::<u32>().peekable();
49+
peekable_with_next_if.next_if(|_| true);
50+
51+
let mut peekable_with_next_if_eq = std::iter::empty::<u32>().peekable();
52+
peekable_with_next_if_eq.next_if_eq(&3);
53+
}
54+
55+
let mut peekable_in_closure = std::iter::empty::<u32>().peekable();
56+
let call_peek = |p: &mut Peekable<Empty<u32>>| {
57+
p.peek();
58+
};
59+
call_peek(&mut peekable_in_closure);
60+
61+
// From a macro
62+
macro_rules! make_me_a_peekable_please {
63+
() => {
64+
std::iter::empty::<u32>().peekable()
65+
};
66+
}
67+
68+
let _unsuspecting_macro_user = make_me_a_peekable_please!();
69+
70+
// Generic Iterator returned
71+
fn return_an_iter() -> impl Iterator<Item = u32> {
72+
std::iter::empty::<u32>().peekable()
73+
}
74+
75+
let _unsuspecting_user = return_an_iter();
76+
77+
// `peek` called in another block as the last expression
78+
let mut peekable_last_expr = std::iter::empty::<u32>().peekable();
79+
{
80+
peekable_last_expr.peek();
81+
}
82+
}

tests/ui/unused_peekable.stderr

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
error: `peek` never called on `Peekable` iterator
2+
--> $DIR/unused_peekable.rs:13:9
3+
|
4+
LL | let peekable = std::iter::empty::<u32>().peekable();
5+
| ^^^^^^^^
6+
|
7+
= note: `-D clippy::unused-peekable` implied by `-D warnings`
8+
= help: consider removing the call to `peekable`
9+
10+
error: `peek` never called on `Peekable` iterator
11+
--> $DIR/unused_peekable.rs:16:9
12+
|
13+
LL | let old_local = std::iter::empty::<u32>().peekable();
14+
| ^^^^^^^^^
15+
|
16+
= help: consider removing the call to `peekable`
17+
18+
error: `peek` never called on `Peekable` iterator
19+
--> $DIR/unused_peekable.rs:17:9
20+
|
21+
LL | let new_local = old_local;
22+
| ^^^^^^^^^
23+
|
24+
= help: consider removing the call to `peekable`
25+
26+
error: `peek` never called on `Peekable` iterator
27+
--> $DIR/unused_peekable.rs:24:9
28+
|
29+
LL | let my_peekable = returns_peekable();
30+
| ^^^^^^^^^^^
31+
|
32+
= help: consider removing the call to `peekable`
33+
34+
error: aborting due to 4 previous errors
35+

0 commit comments

Comments
 (0)