Skip to content

Commit d3c06f7

Browse files
author
Joshua Holmer
committed
Exclude pattern guards from unnecessary_fold lint
Methods like `Iterator::any` borrow the iterator mutably, which is not allowed within a pattern guard and will fail to compile. This commit prevents clippy from suggesting this type of change. Closes #3069
1 parent d445dbf commit d3c06f7

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

clippy_lints/src/methods/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010

1111
use crate::rustc::hir;
12+
use crate::rustc::hir::{ExprKind, Guard, Node};
1213
use crate::rustc::hir::def::Def;
1314
use crate::rustc::lint::{in_external_macro, LateContext, LateLintPass, Lint, LintArray, LintContext, LintPass};
1415
use crate::rustc::ty::{self, Ty};
@@ -1428,6 +1429,23 @@ fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args:
14281429
return;
14291430
}
14301431

1432+
// `Iterator::any` cannot be used within a pattern guard
1433+
// See https://github.com/rust-lang-nursery/rust-clippy/issues/3069
1434+
if_chain! {
1435+
if let Some(fold_parent) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(expr.id));
1436+
if let Node::Expr(fold_parent) = fold_parent;
1437+
if let ExprKind::Match(_, ref arms, _) = fold_parent.node;
1438+
if arms.iter().any(|arm| {
1439+
if let Some(Guard::If(ref guard)) = arm.guard {
1440+
return guard.id == expr.id;
1441+
}
1442+
false
1443+
});
1444+
then {
1445+
return;
1446+
}
1447+
}
1448+
14311449
assert!(fold_args.len() == 3,
14321450
"Expected fold_args to have three entries - the receiver, the initial value and the closure");
14331451

tests/ui/unnecessary_fold.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,13 @@ fn unnecessary_fold_should_ignore() {
4545

4646
let _ = [(0..2), (0..3)].iter().fold(0, |a, b| a + b.len());
4747
let _ = [(0..2), (0..3)].iter().fold(1, |a, b| a * b.len());
48+
49+
// Because `any` takes the iterator as a mutable reference,
50+
// it cannot be used in a pattern guard, and we must use `fold`.
51+
match 1 {
52+
_ if (0..3).fold(false, |acc, x| acc || x > 2) => {}
53+
_ => {}
54+
}
4855
}
4956

5057
fn main() {}

0 commit comments

Comments
 (0)