Skip to content

Commit 318ed05

Browse files
committed
Reduce code duplication
Only check for the kind of loop once instead of re-desugaring it.
1 parent 5048af7 commit 318ed05

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

clippy_lints/src/loops/needless_collect.rs

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -185,19 +185,15 @@ struct IterFunctionVisitor<'a, 'tcx> {
185185
impl<'tcx> Visitor<'tcx> for IterFunctionVisitor<'_, 'tcx> {
186186
fn visit_block(&mut self, block: &'tcx Block<'tcx>) {
187187
for (expr, hir_id) in block.stmts.iter().filter_map(get_expr_and_hir_id_from_stmt) {
188-
if is_loop(expr) {
188+
if check_loop_kind(expr).is_some() {
189189
continue;
190190
}
191191
self.visit_block_expr(expr, hir_id);
192192
}
193193
if let Some(expr) = block.expr {
194-
if is_loop(expr) {
195-
if let Some(higher::WhileLet { let_expr, .. }) = higher::WhileLet::hir(expr) {
196-
self.visit_block_expr(let_expr, None);
197-
} else if let Some(higher::While { condition, .. }) = higher::While::hir(expr) {
198-
self.visit_block_expr(condition, None);
199-
} else if let Some(higher::ForLoop { arg, .. }) = higher::ForLoop::hir(expr) {
200-
self.visit_block_expr(arg, None);
194+
if let Some(loop_kind) = check_loop_kind(expr) {
195+
if let LoopKind::Conditional(block_expr) = loop_kind {
196+
self.visit_block_expr(block_expr, None);
201197
}
202198
} else {
203199
self.visit_block_expr(expr, None);
@@ -278,21 +274,26 @@ impl<'tcx> Visitor<'tcx> for IterFunctionVisitor<'_, 'tcx> {
278274
}
279275
}
280276

281-
fn is_loop(expr: &Expr<'_>) -> bool {
282-
if let Some(higher::WhileLet { .. }) = higher::WhileLet::hir(expr) {
283-
return true;
277+
enum LoopKind<'tcx> {
278+
Conditional(&'tcx Expr<'tcx>),
279+
Loop,
280+
}
281+
282+
fn check_loop_kind<'tcx>(expr: &Expr<'tcx>) -> Option<LoopKind<'tcx>> {
283+
if let Some(higher::WhileLet { let_expr, .. }) = higher::WhileLet::hir(expr) {
284+
return Some(LoopKind::Conditional(let_expr));
284285
}
285-
if let Some(higher::While { .. }) = higher::While::hir(expr) {
286-
return true;
286+
if let Some(higher::While { condition, .. }) = higher::While::hir(expr) {
287+
return Some(LoopKind::Conditional(condition));
287288
}
288-
if let Some(higher::ForLoop { .. }) = higher::ForLoop::hir(expr) {
289-
return true;
289+
if let Some(higher::ForLoop { arg, .. }) = higher::ForLoop::hir(expr) {
290+
return Some(LoopKind::Conditional(arg));
290291
}
291292
if let ExprKind::Loop { .. } = expr.kind {
292-
return true;
293+
return Some(LoopKind::Loop);
293294
}
294295

295-
false
296+
None
296297
}
297298

298299
impl<'tcx> IterFunctionVisitor<'_, 'tcx> {

0 commit comments

Comments
 (0)