|
| 1 | +use super::UNUSED_ENUMERATE_INDEX; |
| 2 | +use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then}; |
| 3 | +use clippy_utils::source::snippet; |
| 4 | +use clippy_utils::sugg; |
| 5 | +use clippy_utils::visitors::is_local_used; |
| 6 | +use rustc_hir::{Expr, ExprKind, Pat, PatKind}; |
| 7 | +use rustc_lint::LateContext; |
| 8 | +use rustc_middle::ty; |
| 9 | + |
| 10 | +/// Checks for the `UNUSED_ENUMERATE_INDEX` lint. |
| 11 | +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, arg: &'tcx Expr<'_>, body: &'tcx Expr<'_>) { |
| 12 | + let pat_span = pat.span; |
| 13 | + |
| 14 | + let PatKind::Tuple(pat, _) = pat.kind else { |
| 15 | + return; |
| 16 | + }; |
| 17 | + |
| 18 | + if pat.len() != 2 { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + let arg_span = arg.span; |
| 23 | + |
| 24 | + let ExprKind::MethodCall(method, self_arg, [], _) = arg.kind else { |
| 25 | + return; |
| 26 | + }; |
| 27 | + |
| 28 | + if method.ident.as_str() != "enumerate" { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + let ty = cx.typeck_results().expr_ty(arg); |
| 33 | + |
| 34 | + if !pat_is_wild(cx, &pat[0].kind, body) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + let new_pat_span = pat[1].span; |
| 39 | + |
| 40 | + let name = match *ty.kind() { |
| 41 | + ty::Adt(base, _substs) => cx.tcx.def_path_str(base.did()), |
| 42 | + _ => return, |
| 43 | + }; |
| 44 | + |
| 45 | + if name != "std::iter::Enumerate" && name != "core::iter::Enumerate" { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + span_lint_and_then( |
| 50 | + cx, |
| 51 | + UNUSED_ENUMERATE_INDEX, |
| 52 | + arg_span, |
| 53 | + "you seem to use `.enumerate()` and immediately discard the index", |
| 54 | + |diag| { |
| 55 | + let base_iter = sugg::Sugg::hir(cx, self_arg, "base iter"); |
| 56 | + multispan_sugg( |
| 57 | + diag, |
| 58 | + "remove the `.enumerate()` call", |
| 59 | + vec![ |
| 60 | + (pat_span, snippet(cx, new_pat_span, "value").into_owned()), |
| 61 | + (arg_span, base_iter.to_string()), |
| 62 | + ], |
| 63 | + ); |
| 64 | + }, |
| 65 | + ); |
| 66 | +} |
| 67 | + |
| 68 | +/// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`. |
| 69 | +fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool { |
| 70 | + match *pat { |
| 71 | + PatKind::Wild => true, |
| 72 | + PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => !is_local_used(cx, body, id), |
| 73 | + _ => false, |
| 74 | + } |
| 75 | +} |
0 commit comments