1 use super::WHILE_LET_ON_ITERATOR;
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::higher;
4 use clippy_utils::source::snippet_with_applicability;
6 get_enclosing_loop_or_multi_call_closure, is_refutable, is_trait_method, match_def_path, paths,
9 use if_chain::if_chain;
10 use rustc_errors::Applicability;
11 use rustc_hir::intravisit::{walk_expr, Visitor};
12 use rustc_hir::{def::Res, Closure, Expr, ExprKind, HirId, Local, Mutability, PatKind, QPath, UnOp};
13 use rustc_lint::LateContext;
14 use rustc_middle::hir::nested_filter::OnlyBodies;
15 use rustc_middle::ty::adjustment::Adjust;
16 use rustc_span::{symbol::sym, Symbol};
18 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
19 let (scrutinee_expr, iter_expr_struct, iter_expr, some_pat, loop_expr) = if_chain! {
20 if let Some(higher::WhileLet { if_then, let_pat, let_expr }) = higher::WhileLet::hir(expr);
21 // check for `Some(..)` pattern
22 if let PatKind::TupleStruct(QPath::Resolved(None, pat_path), some_pat, _) = let_pat.kind;
23 if let Res::Def(_, pat_did) = pat_path.res;
24 if match_def_path(cx, pat_did, &paths::OPTION_SOME);
25 // check for call to `Iterator::next`
26 if let ExprKind::MethodCall(method_name, iter_expr, [], _) = let_expr.kind;
27 if method_name.ident.name == sym::next;
28 if is_trait_method(cx, let_expr, sym::Iterator);
29 if let Some(iter_expr_struct) = try_parse_iter_expr(cx, iter_expr);
30 // get the loop containing the match expression
31 if !uses_iter(cx, &iter_expr_struct, if_then);
33 (let_expr, iter_expr_struct, iter_expr, some_pat, expr)
39 let mut applicability = Applicability::MachineApplicable;
40 let loop_var = if let Some(some_pat) = some_pat.first() {
41 if is_refutable(cx, some_pat) {
42 // Refutable patterns don't work with for loops.
45 snippet_with_applicability(cx, some_pat.span, "..", &mut applicability)
50 // If the iterator is a field or the iterator is accessed after the loop is complete it needs to be
51 // borrowed mutably. TODO: If the struct can be partially moved from and the struct isn't used
52 // afterwards a mutable borrow of a field isn't necessary.
53 let by_ref = if cx.typeck_results().expr_ty(iter_expr).ref_mutability() == Some(Mutability::Mut)
54 || !iter_expr_struct.can_move
55 || !iter_expr_struct.fields.is_empty()
56 || needs_mutable_borrow(cx, &iter_expr_struct, loop_expr)
63 let iterator = snippet_with_applicability(cx, iter_expr.span, "_", &mut applicability);
66 WHILE_LET_ON_ITERATOR,
67 expr.span.with_hi(scrutinee_expr.span.hi()),
68 "this loop could be written as a `for` loop",
70 format!("for {loop_var} in {iterator}{by_ref}"),
77 /// The fields used, in order of child to parent.
79 /// The path being used.
81 /// Whether or not the iterator can be moved.
85 /// Parses any expression to find out which field of which variable is used. Will return `None` if
86 /// the expression might have side effects.
87 fn try_parse_iter_expr(cx: &LateContext<'_>, mut e: &Expr<'_>) -> Option<IterExpr> {
88 let mut fields = Vec::new();
89 let mut can_move = true;
95 .any(|a| matches!(a.kind, Adjust::Deref(Some(..))))
97 // Custom deref impls need to borrow the whole value as it's captured by reference
102 ExprKind::Path(ref path) => {
103 break Some(IterExpr {
105 path: cx.qpath_res(path, e.hir_id),
109 ExprKind::Field(base, name) => {
110 fields.push(name.name);
113 // Dereferencing a pointer has no side effects and doesn't affect which field is being used.
114 ExprKind::Unary(UnOp::Deref, base) if cx.typeck_results().expr_ty(base).is_ref() => e = base,
116 // Shouldn't have side effects, but there's no way to trace which field is used. So forget which fields have
117 // already been seen.
118 ExprKind::Index(base, idx) if !idx.can_have_side_effects() => {
123 ExprKind::Unary(UnOp::Deref, base) => {
129 // No effect and doesn't affect which field is being used.
130 ExprKind::DropTemps(base) | ExprKind::AddrOf(_, _, base) | ExprKind::Type(base, _) => e = base,
136 fn is_expr_same_field(cx: &LateContext<'_>, mut e: &Expr<'_>, mut fields: &[Symbol], path_res: Res) -> bool {
138 match (&e.kind, fields) {
139 (&ExprKind::Field(base, name), [head_field, tail_fields @ ..]) if name.name == *head_field => {
141 fields = tail_fields;
143 (ExprKind::Path(path), []) => {
144 break cx.qpath_res(path, e.hir_id) == path_res;
146 (&(ExprKind::DropTemps(base) | ExprKind::AddrOf(_, _, base) | ExprKind::Type(base, _)), _) => e = base,
152 /// Checks if the given expression is the same field as, is a child of, or is the parent of the
153 /// given field. Used to check if the expression can be used while the given field is borrowed
154 /// mutably. e.g. if checking for `x.y`, then `x.y`, `x.y.z`, and `x` will all return true, but
155 /// `x.z`, and `y` will return false.
156 fn is_expr_same_child_or_parent_field(cx: &LateContext<'_>, expr: &Expr<'_>, fields: &[Symbol], path_res: Res) -> bool {
158 ExprKind::Field(base, name) => {
159 if let Some((head_field, tail_fields)) = fields.split_first() {
160 if name.name == *head_field && is_expr_same_field(cx, base, tail_fields, path_res) {
163 // Check if the expression is a parent field
164 let mut fields_iter = tail_fields.iter();
165 while let Some(field) = fields_iter.next() {
166 if *field == name.name && is_expr_same_field(cx, base, fields_iter.as_slice(), path_res) {
172 // Check if the expression is a child field.
176 ExprKind::Field(..) if is_expr_same_field(cx, e, fields, path_res) => break true,
177 ExprKind::Field(base, _) | ExprKind::DropTemps(base) | ExprKind::Type(base, _) => e = base,
178 ExprKind::Path(ref path) if fields.is_empty() => {
179 break cx.qpath_res(path, e.hir_id) == path_res;
185 // If the path matches, this is either an exact match, or the expression is a parent of the field.
186 ExprKind::Path(ref path) => cx.qpath_res(path, expr.hir_id) == path_res,
187 ExprKind::DropTemps(base) | ExprKind::Type(base, _) | ExprKind::AddrOf(_, _, base) => {
188 is_expr_same_child_or_parent_field(cx, base, fields, path_res)
194 /// Strips off all field and path expressions. This will return true if a field or path has been
195 /// skipped. Used to skip them after failing to check for equality.
196 fn skip_fields_and_path<'tcx>(expr: &'tcx Expr<'_>) -> (Option<&'tcx Expr<'tcx>>, bool) {
200 ExprKind::Field(base, _) | ExprKind::DropTemps(base) | ExprKind::Type(base, _) => e = base,
201 ExprKind::Path(_) => return (None, true),
205 (Some(e), e.hir_id != expr.hir_id)
208 /// Checks if the given expression uses the iterator.
209 fn uses_iter<'tcx>(cx: &LateContext<'tcx>, iter_expr: &IterExpr, container: &'tcx Expr<'_>) -> bool {
210 struct V<'a, 'b, 'tcx> {
211 cx: &'a LateContext<'tcx>,
212 iter_expr: &'b IterExpr,
215 impl<'tcx> Visitor<'tcx> for V<'_, '_, 'tcx> {
216 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
219 } else if is_expr_same_child_or_parent_field(self.cx, e, &self.iter_expr.fields, self.iter_expr.path) {
220 self.uses_iter = true;
221 } else if let (e, true) = skip_fields_and_path(e) {
225 } else if let ExprKind::Closure(&Closure { body: id, .. }) = e.kind {
226 if is_res_used(self.cx, self.iter_expr.path, id) {
227 self.uses_iter = true;
240 v.visit_expr(container);
244 #[expect(clippy::too_many_lines)]
245 fn needs_mutable_borrow(cx: &LateContext<'_>, iter_expr: &IterExpr, loop_expr: &Expr<'_>) -> bool {
246 struct AfterLoopVisitor<'a, 'b, 'tcx> {
247 cx: &'a LateContext<'tcx>,
248 iter_expr: &'b IterExpr,
253 impl<'tcx> Visitor<'tcx> for AfterLoopVisitor<'_, '_, 'tcx> {
254 type NestedFilter = OnlyBodies;
255 fn nested_visit_map(&mut self) -> Self::Map {
259 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
264 if is_expr_same_child_or_parent_field(self.cx, e, &self.iter_expr.fields, self.iter_expr.path) {
265 self.used_iter = true;
266 } else if let (e, true) = skip_fields_and_path(e) {
270 } else if let ExprKind::Closure(&Closure { body: id, .. }) = e.kind {
271 self.used_iter = is_res_used(self.cx, self.iter_expr.path, id);
275 } else if self.loop_id == e.hir_id {
276 self.after_loop = true;
283 struct NestedLoopVisitor<'a, 'b, 'tcx> {
284 cx: &'a LateContext<'tcx>,
285 iter_expr: &'b IterExpr,
292 impl<'a, 'b, 'tcx> Visitor<'tcx> for NestedLoopVisitor<'a, 'b, 'tcx> {
293 type NestedFilter = OnlyBodies;
294 fn nested_visit_map(&mut self) -> Self::Map {
298 fn visit_local(&mut self, l: &'tcx Local<'_>) {
299 if !self.after_loop {
300 l.pat.each_binding_or_first(&mut |_, id, _, _| {
301 if id == self.local_id {
302 self.found_local = true;
306 if let Some(e) = l.init {
311 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
316 if is_expr_same_child_or_parent_field(self.cx, e, &self.iter_expr.fields, self.iter_expr.path) {
317 self.used_after = true;
318 } else if let (e, true) = skip_fields_and_path(e) {
322 } else if let ExprKind::Closure(&Closure { body: id, .. }) = e.kind {
323 self.used_after = is_res_used(self.cx, self.iter_expr.path, id);
327 } else if e.hir_id == self.loop_id {
328 self.after_loop = true;
335 if let Some(e) = get_enclosing_loop_or_multi_call_closure(cx, loop_expr) {
336 let local_id = match iter_expr.path {
337 Res::Local(id) => id,
340 let mut v = NestedLoopVisitor {
344 loop_id: loop_expr.hir_id,
350 v.used_after || !v.found_local
352 let mut v = AfterLoopVisitor {
355 loop_id: loop_expr.hir_id,
359 v.visit_expr(cx.tcx.hir().body(cx.enclosing_body.unwrap()).value);