Skip to content

Commit 2091142

Browse files
committed
Auto merge of #9258 - Serial-ATA:unused-peekable, r=Alexendoo
Add [`unused_peekable`] lint changelog: Add [`unused_peekable`] lint closes: #854
2 parents 3a54117 + 0efafa4 commit 2091142

10 files changed

+444
-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
@@ -339,6 +339,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
339339
LintId::of(unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS),
340340
LintId::of(unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
341341
LintId::of(unused_io_amount::UNUSED_IO_AMOUNT),
342+
LintId::of(unused_peekable::UNUSED_PEEKABLE),
342343
LintId::of(unused_unit::UNUSED_UNIT),
343344
LintId::of(unwrap::PANICKING_UNWRAP),
344345
LintId::of(unwrap::UNNECESSARY_UNWRAP),

clippy_lints/src/lib.register_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,7 @@ store.register_lints(&[
575575
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
576576
unused_async::UNUSED_ASYNC,
577577
unused_io_amount::UNUSED_IO_AMOUNT,
578+
unused_peekable::UNUSED_PEEKABLE,
578579
unused_rounding::UNUSED_ROUNDING,
579580
unused_self::UNUSED_SELF,
580581
unused_unit::UNUSED_UNIT,

clippy_lints/src/lib.register_suspicious.rs

+1
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,6 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
3232
LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
3333
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
3434
LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF),
35+
LintId::of(unused_peekable::UNUSED_PEEKABLE),
3536
LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS),
3637
])

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ mod unnested_or_patterns;
381381
mod unsafe_removed_from_name;
382382
mod unused_async;
383383
mod unused_io_amount;
384+
mod unused_peekable;
384385
mod unused_rounding;
385386
mod unused_self;
386387
mod unused_unit;
@@ -894,6 +895,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
894895
store.register_late_pass(|| Box::new(manual_instant_elapsed::ManualInstantElapsed));
895896
store.register_late_pass(|| Box::new(partialeq_to_none::PartialeqToNone));
896897
store.register_late_pass(|| Box::new(manual_empty_string_creations::ManualEmptyStringCreations));
898+
store.register_late_pass(|| Box::new(unused_peekable::UnusedPeekable));
897899
// add lints here, do not remove this comment, it's used in `new_lint`
898900
}
899901

clippy_lints/src/unused_peekable.rs

+225
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
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, is_trait_method, 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_session::{declare_lint_pass, declare_tool_lint};
10+
use rustc_span::sym;
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+
declare_lint_pass!(UnusedPeekable => [UNUSED_PEEKABLE]);
46+
47+
impl<'tcx> LateLintPass<'tcx> for UnusedPeekable {
48+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &Block<'tcx>) {
49+
// Don't lint `Peekable`s returned from a block
50+
if let Some(expr) = block.expr
51+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(peel_ref_operators(cx, expr))
52+
&& match_type(cx, ty, &paths::PEEKABLE)
53+
{
54+
return;
55+
}
56+
57+
for (idx, stmt) in block.stmts.iter().enumerate() {
58+
if !stmt.span.from_expansion()
59+
&& let StmtKind::Local(local) = stmt.kind
60+
&& let PatKind::Binding(_, binding, ident, _) = local.pat.kind
61+
&& let Some(init) = local.init
62+
&& !init.span.from_expansion()
63+
&& let Some(ty) = cx.typeck_results().expr_ty_opt(init)
64+
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
65+
&& match_type(cx, ty, &paths::PEEKABLE)
66+
{
67+
let mut vis = PeekableVisitor::new(cx, binding);
68+
69+
if idx + 1 == block.stmts.len() && block.expr.is_none() {
70+
return;
71+
}
72+
73+
for stmt in &block.stmts[idx..] {
74+
vis.visit_stmt(stmt);
75+
}
76+
77+
if let Some(expr) = block.expr {
78+
vis.visit_expr(expr);
79+
}
80+
81+
if !vis.found_peek_call {
82+
span_lint_and_help(
83+
cx,
84+
UNUSED_PEEKABLE,
85+
ident.span,
86+
"`peek` never called on `Peekable` iterator",
87+
None,
88+
"consider removing the call to `peekable`"
89+
);
90+
}
91+
}
92+
}
93+
}
94+
}
95+
96+
struct PeekableVisitor<'a, 'tcx> {
97+
cx: &'a LateContext<'tcx>,
98+
expected_hir_id: HirId,
99+
found_peek_call: bool,
100+
}
101+
102+
impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> {
103+
fn new(cx: &'a LateContext<'tcx>, expected_hir_id: HirId) -> Self {
104+
Self {
105+
cx,
106+
expected_hir_id,
107+
found_peek_call: false,
108+
}
109+
}
110+
}
111+
112+
impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> {
113+
fn visit_expr(&mut self, ex: &'_ Expr<'_>) {
114+
if self.found_peek_call {
115+
return;
116+
}
117+
118+
if path_to_local_id(ex, self.expected_hir_id) {
119+
for (_, node) in self.cx.tcx.hir().parent_iter(ex.hir_id) {
120+
match node {
121+
Node::Expr(expr) => {
122+
match expr.kind {
123+
// some_function(peekable)
124+
//
125+
// If the Peekable is passed to a function, stop
126+
ExprKind::Call(_, args) => {
127+
if let Some(func_did) = fn_def_id(self.cx, expr)
128+
&& let Ok(into_iter_did) = self
129+
.cx
130+
.tcx
131+
.lang_items()
132+
.require(LangItem::IntoIterIntoIter)
133+
&& func_did == into_iter_did
134+
{
135+
// Probably a for loop desugar, stop searching
136+
return;
137+
}
138+
139+
if args.iter().any(|arg| {
140+
matches!(arg.kind, ExprKind::Path(_)) && arg_is_mut_peekable(self.cx, arg)
141+
}) {
142+
self.found_peek_call = true;
143+
return;
144+
}
145+
},
146+
// Catch anything taking a Peekable mutably
147+
ExprKind::MethodCall(
148+
PathSegment {
149+
ident: method_name_ident,
150+
..
151+
},
152+
[self_arg, remaining_args @ ..],
153+
_,
154+
) => {
155+
let method_name = method_name_ident.name.as_str();
156+
157+
// `Peekable` methods
158+
if matches!(method_name, "peek" | "peek_mut" | "next_if" | "next_if_eq")
159+
&& arg_is_mut_peekable(self.cx, self_arg)
160+
{
161+
self.found_peek_call = true;
162+
return;
163+
}
164+
165+
// foo.some_method() excluding Iterator methods
166+
if remaining_args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg))
167+
&& !is_trait_method(self.cx, expr, sym::Iterator)
168+
{
169+
self.found_peek_call = true;
170+
return;
171+
}
172+
173+
// foo.by_ref(), keep checking for `peek`
174+
if method_name == "by_ref" {
175+
continue;
176+
}
177+
178+
return;
179+
},
180+
ExprKind::AddrOf(_, Mutability::Mut, _) | ExprKind::Unary(..) | ExprKind::DropTemps(_) => {
181+
},
182+
ExprKind::AddrOf(_, Mutability::Not, _) => return,
183+
_ => {
184+
self.found_peek_call = true;
185+
return;
186+
},
187+
}
188+
},
189+
Node::Local(Local { init: Some(init), .. }) => {
190+
if arg_is_mut_peekable(self.cx, init) {
191+
self.found_peek_call = true;
192+
return;
193+
}
194+
195+
break;
196+
},
197+
Node::Stmt(stmt) => match stmt.kind {
198+
StmtKind::Expr(_) | StmtKind::Semi(_) => {},
199+
_ => {
200+
self.found_peek_call = true;
201+
return;
202+
},
203+
},
204+
Node::Block(_) => {},
205+
_ => {
206+
break;
207+
},
208+
}
209+
}
210+
}
211+
212+
walk_expr(self, ex);
213+
}
214+
}
215+
216+
fn arg_is_mut_peekable(cx: &LateContext<'_>, arg: &Expr<'_>) -> bool {
217+
if let Some(ty) = cx.typeck_results().expr_ty_opt(arg)
218+
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
219+
&& match_type(cx, ty, &paths::PEEKABLE)
220+
{
221+
true
222+
} else {
223+
false
224+
}
225+
}

clippy_utils/src/paths.rs

+1
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ pub const PARKING_LOT_RWLOCK_READ_GUARD: [&str; 3] = ["lock_api", "rwlock", "RwL
9595
pub const PARKING_LOT_RWLOCK_WRITE_GUARD: [&str; 3] = ["lock_api", "rwlock", "RwLockWriteGuard"];
9696
pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
9797
pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
98+
pub const PEEKABLE: [&str; 5] = ["core", "iter", "adapters", "peekable", "Peekable"];
9899
pub const PERMISSIONS: [&str; 3] = ["std", "fs", "Permissions"];
99100
#[cfg_attr(not(unix), allow(clippy::invalid_paths))]
100101
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) {

0 commit comments

Comments
 (0)