Skip to content

Commit 8151a17

Browse files
committed
Auto merge of #4049 - airt:fix-4033-search_is_some, r=flip1995
Fix #4033 search_is_some Fixes #4033. Suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()` (Lint [search_is_some](https://rust-lang.github.io/rust-clippy/master/index.html#search_is_some)) FnDecl of `find`: ```rust fn find<P>(&mut self, mut p: P) -> Option<Self::Item> where P: FnMut(&Self::Item) -> bool ``` FnDecl of `any`: ```rust fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool ``` If match on `|&_|` in closure of `find`, only use `|_|` in the suggestion. PS. It's the first time that I have used the `hir` API, please correct me if there is any mistake 😺
2 parents 1cf5d7f + d063516 commit 8151a17

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

clippy_lints/src/methods/mod.rs

+17-2
Original file line numberDiff line numberDiff line change
@@ -2059,6 +2059,19 @@ fn lint_search_is_some<'a, 'tcx>(
20592059
);
20602060
let search_snippet = snippet(cx, search_args[1].span, "..");
20612061
if search_snippet.lines().count() <= 1 {
2062+
// suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2063+
let any_search_snippet = if_chain! {
2064+
if search_method == "find";
2065+
if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].node;
2066+
let closure_body = cx.tcx.hir().body(body_id);
2067+
if let Some(closure_arg) = closure_body.arguments.get(0);
2068+
if let hir::PatKind::Ref(..) = closure_arg.pat.node;
2069+
then {
2070+
Some(search_snippet.replacen('&', "", 1))
2071+
} else {
2072+
None
2073+
}
2074+
};
20622075
// add note if not multi-line
20632076
span_note_and_lint(
20642077
cx,
@@ -2067,8 +2080,10 @@ fn lint_search_is_some<'a, 'tcx>(
20672080
&msg,
20682081
expr.span,
20692082
&format!(
2070-
"replace `{0}({1}).is_some()` with `any({1})`",
2071-
search_method, search_snippet
2083+
"replace `{0}({1}).is_some()` with `any({2})`",
2084+
search_method,
2085+
search_snippet,
2086+
any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
20722087
),
20732088
);
20742089
} else {

tests/ui/methods.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ LL | let _ = v.iter().find(|&x| *x < 0).is_some();
155155
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
156156
|
157157
= note: `-D clippy::search-is-some` implied by `-D warnings`
158-
= note: replace `find(|&x| *x < 0).is_some()` with `any(|&x| *x < 0)`
158+
= note: replace `find(|&x| *x < 0).is_some()` with `any(|x| *x < 0)`
159159

160160
error: called `is_some()` after searching an `Iterator` with find. This is more succinctly expressed by calling `any()`.
161161
--> $DIR/methods.rs:236:13

0 commit comments

Comments
 (0)