]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unused_peekable.rs
Auto merge of #103690 - GuillaumeGomez:visibility-on-demand, r=notriddle
[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::{Block, Expr, ExprKind, HirId, Local, Node, PatKind, PathSegment, StmtKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::hir::nested_filter::OnlyBodies;
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     nursery,
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<'tcx> for PeekableVisitor<'_, 'tcx> {
113     type NestedFilter = OnlyBodies;
114
115     fn nested_visit_map(&mut self) -> Self::Map {
116         self.cx.tcx.hir()
117     }
118
119     fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
120         if self.found_peek_call {
121             return;
122         }
123
124         if path_to_local_id(ex, self.expected_hir_id) {
125             for (_, node) in self.cx.tcx.hir().parent_iter(ex.hir_id) {
126                 match node {
127                     Node::Expr(expr) => {
128                         match expr.kind {
129                             // some_function(peekable)
130                             //
131                             // If the Peekable is passed to a function, stop
132                             ExprKind::Call(_, args) => {
133                                 if let Some(func_did) = fn_def_id(self.cx, expr)
134                                     && let Some(into_iter_did) = self
135                                         .cx
136                                         .tcx
137                                         .lang_items()
138                                         .into_iter_fn()
139                                     && func_did == into_iter_did
140                                 {
141                                     // Probably a for loop desugar, stop searching
142                                     return;
143                                 }
144
145                                 if args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg)) {
146                                     self.found_peek_call = true;
147                                 }
148
149                                 return;
150                             },
151                             // Catch anything taking a Peekable mutably
152                             ExprKind::MethodCall(
153                                 PathSegment {
154                                     ident: method_name_ident,
155                                     ..
156                                 },
157                                 self_arg,
158                                 remaining_args,
159                                 _,
160                             ) => {
161                                 let method_name = method_name_ident.name.as_str();
162
163                                 // `Peekable` methods
164                                 if matches!(method_name, "peek" | "peek_mut" | "next_if" | "next_if_eq")
165                                     && arg_is_mut_peekable(self.cx, self_arg)
166                                 {
167                                     self.found_peek_call = true;
168                                     return;
169                                 }
170
171                                 // foo.some_method() excluding Iterator methods
172                                 if remaining_args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg))
173                                     && !is_trait_method(self.cx, expr, sym::Iterator)
174                                 {
175                                     self.found_peek_call = true;
176                                     return;
177                                 }
178
179                                 // foo.by_ref(), keep checking for `peek`
180                                 if method_name == "by_ref" {
181                                     continue;
182                                 }
183
184                                 return;
185                             },
186                             ExprKind::AddrOf(_, Mutability::Mut, _) | ExprKind::Unary(..) | ExprKind::DropTemps(_) => {
187                             },
188                             ExprKind::AddrOf(_, Mutability::Not, _) => return,
189                             _ => {
190                                 self.found_peek_call = true;
191                                 return;
192                             },
193                         }
194                     },
195                     Node::Local(Local { init: Some(init), .. }) => {
196                         if arg_is_mut_peekable(self.cx, init) {
197                             self.found_peek_call = true;
198                         }
199
200                         return;
201                     },
202                     Node::Stmt(stmt) => {
203                         match stmt.kind {
204                             StmtKind::Local(_) | StmtKind::Item(_) => self.found_peek_call = true,
205                             StmtKind::Expr(_) | StmtKind::Semi(_) => {},
206                         }
207
208                         return;
209                     },
210                     Node::Block(_) | Node::ExprField(_) => {},
211                     _ => {
212                         return;
213                     },
214                 }
215             }
216         }
217
218         walk_expr(self, ex);
219     }
220 }
221
222 fn arg_is_mut_peekable(cx: &LateContext<'_>, arg: &Expr<'_>) -> bool {
223     if let Some(ty) = cx.typeck_results().expr_ty_opt(arg)
224         && let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
225         && match_type(cx, ty, &paths::PEEKABLE)
226     {
227         true
228     } else {
229         false
230     }
231 }