]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unused_peekable.rs
Rollup merge of #102846 - zertosh:update-syn, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / unused_peekable.rs
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};
11 use rustc_span::sym;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for the creation of a `peekable` iterator that is never `.peek()`ed
16     ///
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.
20     ///
21     /// ### Example
22     /// ```rust
23     /// let collection = vec![1, 2, 3];
24     /// let iter = collection.iter().peekable();
25     ///
26     /// for item in iter {
27     ///     // ...
28     /// }
29     /// ```
30     ///
31     /// Use instead:
32     /// ```rust
33     /// let collection = vec![1, 2, 3];
34     /// let iter = collection.iter();
35     ///
36     /// for item in iter {
37     ///     // ...
38     /// }
39     /// ```
40     #[clippy::version = "1.64.0"]
41     pub UNUSED_PEEKABLE,
42     nursery,
43     "creating a peekable iterator without using any of its methods"
44 }
45
46 declare_lint_pass!(UnusedPeekable => [UNUSED_PEEKABLE]);
47
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)
54         {
55             return;
56         }
57
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)
67             {
68                 let mut vis = PeekableVisitor::new(cx, binding);
69
70                 if idx + 1 == block.stmts.len() && block.expr.is_none() {
71                     return;
72                 }
73
74                 for stmt in &block.stmts[idx..] {
75                     vis.visit_stmt(stmt);
76                 }
77
78                 if let Some(expr) = block.expr {
79                     vis.visit_expr(expr);
80                 }
81
82                 if !vis.found_peek_call {
83                     span_lint_and_help(
84                         cx,
85                         UNUSED_PEEKABLE,
86                         ident.span,
87                         "`peek` never called on `Peekable` iterator",
88                         None,
89                         "consider removing the call to `peekable`"
90                    );
91                 }
92             }
93         }
94     }
95 }
96
97 struct PeekableVisitor<'a, 'tcx> {
98     cx: &'a LateContext<'tcx>,
99     expected_hir_id: HirId,
100     found_peek_call: bool,
101 }
102
103 impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> {
104     fn new(cx: &'a LateContext<'tcx>, expected_hir_id: HirId) -> Self {
105         Self {
106             cx,
107             expected_hir_id,
108             found_peek_call: false,
109         }
110     }
111 }
112
113 impl<'tcx> Visitor<'tcx> for PeekableVisitor<'_, 'tcx> {
114     type NestedFilter = OnlyBodies;
115
116     fn nested_visit_map(&mut self) -> Self::Map {
117         self.cx.tcx.hir()
118     }
119
120     fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
121         if self.found_peek_call {
122             return;
123         }
124
125         if path_to_local_id(ex, self.expected_hir_id) {
126             for (_, node) in self.cx.tcx.hir().parent_iter(ex.hir_id) {
127                 match node {
128                     Node::Expr(expr) => {
129                         match expr.kind {
130                             // some_function(peekable)
131                             //
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
136                                         .cx
137                                         .tcx
138                                         .lang_items()
139                                         .require(LangItem::IntoIterIntoIter)
140                                     && func_did == into_iter_did
141                                 {
142                                     // Probably a for loop desugar, stop searching
143                                     return;
144                                 }
145
146                                 if args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg)) {
147                                     self.found_peek_call = true;
148                                 }
149
150                                 return;
151                             },
152                             // Catch anything taking a Peekable mutably
153                             ExprKind::MethodCall(
154                                 PathSegment {
155                                     ident: method_name_ident,
156                                     ..
157                                 },
158                                 self_arg,
159                                 remaining_args,
160                                 _,
161                             ) => {
162                                 let method_name = method_name_ident.name.as_str();
163
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)
167                                 {
168                                     self.found_peek_call = true;
169                                     return;
170                                 }
171
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)
175                                 {
176                                     self.found_peek_call = true;
177                                     return;
178                                 }
179
180                                 // foo.by_ref(), keep checking for `peek`
181                                 if method_name == "by_ref" {
182                                     continue;
183                                 }
184
185                                 return;
186                             },
187                             ExprKind::AddrOf(_, Mutability::Mut, _) | ExprKind::Unary(..) | ExprKind::DropTemps(_) => {
188                             },
189                             ExprKind::AddrOf(_, Mutability::Not, _) => return,
190                             _ => {
191                                 self.found_peek_call = true;
192                                 return;
193                             },
194                         }
195                     },
196                     Node::Local(Local { init: Some(init), .. }) => {
197                         if arg_is_mut_peekable(self.cx, init) {
198                             self.found_peek_call = true;
199                         }
200
201                         return;
202                     },
203                     Node::Stmt(stmt) => {
204                         match stmt.kind {
205                             StmtKind::Local(_) | StmtKind::Item(_) => self.found_peek_call = true,
206                             StmtKind::Expr(_) | StmtKind::Semi(_) => {},
207                         }
208
209                         return;
210                     },
211                     Node::Block(_) | Node::ExprField(_) => {},
212                     _ => {
213                         return;
214                     },
215                 }
216             }
217         }
218
219         walk_expr(self, ex);
220     }
221 }
222
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)
227     {
228         true
229     } else {
230         false
231     }
232 }