summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs
blob: 7b8c88235a97dd27e0a8b3b738bd37e7606b5cef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use super::EXPLICIT_ITER_LOOP;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{
    implements_trait, implements_trait_with_env, is_copy, make_normalized_projection,
    make_normalized_projection_with_regions, normalize_with_regions,
};
use rustc_errors::Applicability;
use rustc_hir::{Expr, Mutability};
use rustc_lint::LateContext;
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
use rustc_middle::ty::{self, EarlyBinder, Ty, TypeAndMut};
use rustc_span::sym;

pub(super) fn check(cx: &LateContext<'_>, self_arg: &Expr<'_>, call_expr: &Expr<'_>, msrv: &Msrv) {
    let Some((adjust, ty)) = is_ref_iterable(cx, self_arg, call_expr) else {
        return;
    };
    if let ty::Array(_, count) = *ty.peel_refs().kind() {
        if !ty.is_ref() {
            if !msrv.meets(msrvs::ARRAY_INTO_ITERATOR) {
                return;
            }
        } else if count
            .try_eval_target_usize(cx.tcx, cx.param_env)
            .map_or(true, |x| x > 32)
            && !msrv.meets(msrvs::ARRAY_IMPL_ANY_LEN)
        {
            return;
        }
    }

    let mut applicability = Applicability::MachineApplicable;
    let object = snippet_with_applicability(cx, self_arg.span, "_", &mut applicability);
    span_lint_and_sugg(
        cx,
        EXPLICIT_ITER_LOOP,
        call_expr.span,
        "it is more concise to loop over references to containers instead of using explicit \
         iteration methods",
        "to write this more concisely, try",
        format!("{}{object}", adjust.display()),
        applicability,
    );
}

#[derive(Clone, Copy)]
enum AdjustKind {
    None,
    Borrow,
    BorrowMut,
    Deref,
    Reborrow,
    ReborrowMut,
}
impl AdjustKind {
    fn borrow(mutbl: Mutability) -> Self {
        match mutbl {
            Mutability::Not => Self::Borrow,
            Mutability::Mut => Self::BorrowMut,
        }
    }

    fn auto_borrow(mutbl: AutoBorrowMutability) -> Self {
        match mutbl {
            AutoBorrowMutability::Not => Self::Borrow,
            AutoBorrowMutability::Mut { .. } => Self::BorrowMut,
        }
    }

    fn reborrow(mutbl: Mutability) -> Self {
        match mutbl {
            Mutability::Not => Self::Reborrow,
            Mutability::Mut => Self::ReborrowMut,
        }
    }

    fn auto_reborrow(mutbl: AutoBorrowMutability) -> Self {
        match mutbl {
            AutoBorrowMutability::Not => Self::Reborrow,
            AutoBorrowMutability::Mut { .. } => Self::ReborrowMut,
        }
    }

    fn display(self) -> &'static str {
        match self {
            Self::None => "",
            Self::Borrow => "&",
            Self::BorrowMut => "&mut ",
            Self::Deref => "*",
            Self::Reborrow => "&*",
            Self::ReborrowMut => "&mut *",
        }
    }
}

/// Checks if an `iter` or `iter_mut` call returns `IntoIterator::IntoIter`. Returns how the
/// argument needs to be adjusted.
#[expect(clippy::too_many_lines)]
fn is_ref_iterable<'tcx>(
    cx: &LateContext<'tcx>,
    self_arg: &Expr<'_>,
    call_expr: &Expr<'_>,
) -> Option<(AdjustKind, Ty<'tcx>)> {
    let typeck = cx.typeck_results();
    if let Some(trait_id) = cx.tcx.get_diagnostic_item(sym::IntoIterator)
        && let Some(fn_id) = typeck.type_dependent_def_id(call_expr.hir_id)
        && let sig = cx.tcx.liberate_late_bound_regions(fn_id, cx.tcx.fn_sig(fn_id).skip_binder())
        && let &[req_self_ty, req_res_ty] = &**sig.inputs_and_output
        && let param_env = cx.tcx.param_env(fn_id)
        && implements_trait_with_env(cx.tcx, param_env, req_self_ty, trait_id, &[])
        && let Some(into_iter_ty) =
            make_normalized_projection_with_regions(cx.tcx, param_env, trait_id, sym!(IntoIter), [req_self_ty])
        && let req_res_ty = normalize_with_regions(cx.tcx, param_env, req_res_ty)
        && into_iter_ty == req_res_ty
    {
        let adjustments = typeck.expr_adjustments(self_arg);
        let self_ty = typeck.expr_ty(self_arg);
        let self_is_copy = is_copy(cx, self_ty);

        if adjustments.is_empty() && self_is_copy {
            // Exact type match, already checked earlier
            return Some((AdjustKind::None, self_ty));
        }

        let res_ty = cx.tcx.erase_regions(EarlyBinder::bind(req_res_ty)
            .instantiate(cx.tcx, typeck.node_args(call_expr.hir_id)));
        let mutbl = if let ty::Ref(_, _, mutbl) = *req_self_ty.kind() {
            Some(mutbl)
        } else {
            None
        };

        if !adjustments.is_empty() {
            if self_is_copy {
                // Using by value won't consume anything
                if implements_trait(cx, self_ty, trait_id, &[])
                    && let Some(ty) =
                        make_normalized_projection(cx.tcx, cx.param_env, trait_id, sym!(IntoIter), [self_ty])
                    && ty == res_ty
                {
                    return Some((AdjustKind::None, self_ty));
                }
            } else if let ty::Ref(region, ty, Mutability::Mut) = *self_ty.kind()
                && let Some(mutbl) = mutbl
            {
                // Attempt to reborrow the mutable reference
                let self_ty = if mutbl.is_mut() {
                    self_ty
                } else {
                    Ty::new_ref(cx.tcx,region, TypeAndMut { ty, mutbl })
                };
                if implements_trait(cx, self_ty, trait_id, &[])
                    && let Some(ty) =
                        make_normalized_projection(cx.tcx, cx.param_env, trait_id, sym!(IntoIter), [self_ty])
                    && ty == res_ty
                {
                    return Some((AdjustKind::reborrow(mutbl), self_ty));
                }
            }
        }
        if let Some(mutbl) = mutbl
            && !self_ty.is_ref()
        {
            // Attempt to borrow
            let self_ty = Ty::new_ref(cx.tcx,cx.tcx.lifetimes.re_erased, TypeAndMut {
                ty: self_ty,
                mutbl,
            });
            if implements_trait(cx, self_ty, trait_id, &[])
                && let Some(ty) = make_normalized_projection(cx.tcx, cx.param_env, trait_id, sym!(IntoIter), [self_ty])
                && ty == res_ty
            {
                return Some((AdjustKind::borrow(mutbl), self_ty));
            }
        }

        match adjustments {
            [] => Some((AdjustKind::None, self_ty)),
            &[
                Adjustment { kind: Adjust::Deref(_), ..},
                Adjustment {
                    kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl)),
                    target,
                },
                ..
            ] => {
                if target != self_ty
                    && implements_trait(cx, target, trait_id, &[])
                    && let Some(ty) =
                        make_normalized_projection(cx.tcx, cx.param_env, trait_id, sym!(IntoIter), [target])
                    && ty == res_ty
                {
                    Some((AdjustKind::auto_reborrow(mutbl), target))
                } else {
                    None
                }
            }
            &[Adjustment { kind: Adjust::Deref(_), target }, ..] => {
                if is_copy(cx, target)
                    && implements_trait(cx, target, trait_id, &[])
                    && let Some(ty) =
                        make_normalized_projection(cx.tcx, cx.param_env, trait_id, sym!(IntoIter), [target])
                    && ty == res_ty
                {
                    Some((AdjustKind::Deref, target))
                } else {
                    None
                }
            }
            &[
                Adjustment {
                    kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl)),
                    target,
                },
                ..
            ] => {
                if self_ty.is_ref()
                    && implements_trait(cx, target, trait_id, &[])
                    && let Some(ty) =
                        make_normalized_projection(cx.tcx, cx.param_env, trait_id, sym!(IntoIter), [target])
                    && ty == res_ty
                {
                    Some((AdjustKind::auto_borrow(mutbl), target))
                } else {
                    None
                }
            }
            _ => None,
        }
    } else {
        None
    }
}