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_middle::hir::nested_filter::OnlyBodies;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 declare_clippy_lint! {
15 /// Checks for the creation of a `peekable` iterator that is never `.peek()`ed
17 /// ### Why is this bad?
18 /// Creating a peekable iterator without using any of its methods is likely a mistake,
19 /// or just a leftover after a refactor.
23 /// let collection = vec![1, 2, 3];
24 /// let iter = collection.iter().peekable();
26 /// for item in iter {
33 /// let collection = vec![1, 2, 3];
34 /// let iter = collection.iter();
36 /// for item in iter {
40 #[clippy::version = "1.64.0"]
43 "creating a peekable iterator without using any of its methods"
46 declare_lint_pass!(UnusedPeekable => [UNUSED_PEEKABLE]);
48 impl<'tcx> LateLintPass<'tcx> for UnusedPeekable {
49 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &Block<'tcx>) {
50 // Don't lint `Peekable`s returned from a block
51 if let Some(expr) = block.expr
52 && let Some(ty) = cx.typeck_results().expr_ty_opt(peel_ref_operators(cx, expr))
53 && match_type(cx, ty, &paths::PEEKABLE)
58 for (idx, stmt) in block.stmts.iter().enumerate() {
59 if !stmt.span.from_expansion()
60 && let StmtKind::Local(local) = stmt.kind
61 && let PatKind::Binding(_, binding, ident, _) = local.pat.kind
62 && let Some(init) = local.init
63 && !init.span.from_expansion()
64 && let Some(ty) = cx.typeck_results().expr_ty_opt(init)
65 && let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
66 && match_type(cx, ty, &paths::PEEKABLE)
68 let mut vis = PeekableVisitor::new(cx, binding);
70 if idx + 1 == block.stmts.len() && block.expr.is_none() {
74 for stmt in &block.stmts[idx..] {
78 if let Some(expr) = block.expr {
82 if !vis.found_peek_call {
87 "`peek` never called on `Peekable` iterator",
89 "consider removing the call to `peekable`"
97 struct PeekableVisitor<'a, 'tcx> {
98 cx: &'a LateContext<'tcx>,
99 expected_hir_id: HirId,
100 found_peek_call: bool,
103 impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> {
104 fn new(cx: &'a LateContext<'tcx>, expected_hir_id: HirId) -> Self {
108 found_peek_call: false,
113 impl<'tcx> Visitor<'tcx> for PeekableVisitor<'_, 'tcx> {
114 type NestedFilter = OnlyBodies;
116 fn nested_visit_map(&mut self) -> Self::Map {
120 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
121 if self.found_peek_call {
125 if path_to_local_id(ex, self.expected_hir_id) {
126 for (_, node) in self.cx.tcx.hir().parent_iter(ex.hir_id) {
128 Node::Expr(expr) => {
130 // some_function(peekable)
132 // If the Peekable is passed to a function, stop
133 ExprKind::Call(_, args) => {
134 if let Some(func_did) = fn_def_id(self.cx, expr)
135 && let Ok(into_iter_did) = self
139 .require(LangItem::IntoIterIntoIter)
140 && func_did == into_iter_did
142 // Probably a for loop desugar, stop searching
146 if args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg)) {
147 self.found_peek_call = true;
152 // Catch anything taking a Peekable mutably
153 ExprKind::MethodCall(
155 ident: method_name_ident,
162 let method_name = method_name_ident.name.as_str();
164 // `Peekable` methods
165 if matches!(method_name, "peek" | "peek_mut" | "next_if" | "next_if_eq")
166 && arg_is_mut_peekable(self.cx, self_arg)
168 self.found_peek_call = true;
172 // foo.some_method() excluding Iterator methods
173 if remaining_args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg))
174 && !is_trait_method(self.cx, expr, sym::Iterator)
176 self.found_peek_call = true;
180 // foo.by_ref(), keep checking for `peek`
181 if method_name == "by_ref" {
187 ExprKind::AddrOf(_, Mutability::Mut, _) | ExprKind::Unary(..) | ExprKind::DropTemps(_) => {
189 ExprKind::AddrOf(_, Mutability::Not, _) => return,
191 self.found_peek_call = true;
196 Node::Local(Local { init: Some(init), .. }) => {
197 if arg_is_mut_peekable(self.cx, init) {
198 self.found_peek_call = true;
203 Node::Stmt(stmt) => {
205 StmtKind::Local(_) | StmtKind::Item(_) => self.found_peek_call = true,
206 StmtKind::Expr(_) | StmtKind::Semi(_) => {},
211 Node::Block(_) | Node::ExprField(_) => {},
223 fn arg_is_mut_peekable(cx: &LateContext<'_>, arg: &Expr<'_>) -> bool {
224 if let Some(ty) = cx.typeck_results().expr_ty_opt(arg)
225 && let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
226 && match_type(cx, ty, &paths::PEEKABLE)