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::ty::is_type_diagnostic_item;
6 use clippy_utils::visitors::LocalUsedVisitor;
7 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind};
8 use rustc_lint::LateContext;
12 /// Checks for the `FOR_KV_MAP` lint.
13 pub(super) fn check<'tcx>(
14 cx: &LateContext<'tcx>,
20 let pat_span = pat.span;
22 if let PatKind::Tuple(pat, _) = pat.kind {
24 let arg_span = arg.span;
25 let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() {
26 ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
27 (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", ty, mutbl),
28 (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", ty, Mutability::Not),
33 let mutbl = match mutbl {
34 Mutability::Not => "",
35 Mutability::Mut => "_mut",
37 let arg = match arg.kind {
38 ExprKind::AddrOf(BorrowKind::Ref, _, expr) => expr,
42 if is_type_diagnostic_item(cx, ty, sym::hashmap_type) || is_type_diagnostic_item(cx, ty, sym::BTreeMap) {
47 &format!("you seem to want to iterate on a map's {}s", kind),
49 let map = sugg::Sugg::hir(cx, arg, "map");
52 "use the corresponding method",
54 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
55 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
65 /// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
66 fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
68 PatKind::Wild => true,
69 PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => {
70 !LocalUsedVisitor::new(cx, id).check_expr(body)