Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new lint to detect inefficient iter().any() #13817

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6020,6 +6020,7 @@ Released 2018-09-13
[`size_of_in_element_count`]: https://rust-lang.github.io/rust-clippy/master/index.html#size_of_in_element_count
[`size_of_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#size_of_ref
[`skip_while_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#skip_while_next
[`slice_iter_any`]: https://rust-lang.github.io/rust-clippy/master/index.html#slice_iter_any
[`slow_vector_initialization`]: https://rust-lang.github.io/rust-clippy/master/index.html#slow_vector_initialization
[`stable_sort_primitive`]: https://rust-lang.github.io/rust-clippy/master/index.html#stable_sort_primitive
[`std_instead_of_alloc`]: https://rust-lang.github.io/rust-clippy/master/index.html#std_instead_of_alloc
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::methods::SHOULD_IMPLEMENT_TRAIT_INFO,
crate::methods::SINGLE_CHAR_ADD_STR_INFO,
crate::methods::SKIP_WHILE_NEXT_INFO,
crate::methods::SLICE_ITER_ANY_INFO,
crate::methods::STABLE_SORT_PRIMITIVE_INFO,
crate::methods::STRING_EXTEND_CHARS_INFO,
crate::methods::STRING_LIT_CHARS_ANY_INFO,
Expand Down
28 changes: 28 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ mod single_char_add_str;
mod single_char_insert_string;
mod single_char_push_string;
mod skip_while_next;
mod slice_iter_any;
mod stable_sort_primitive;
mod str_split;
mod str_splitn;
Expand Down Expand Up @@ -4284,6 +4285,31 @@ declare_clippy_lint! {
"map of a trivial closure (not dependent on parameter) over a range"
}

declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `iter().any()` on numeric slices when it can be replaced with `contains()` and suggests doing so.
///
/// ### Why is this bad?
/// `contains()` on numeric slices is faster than `iter().any()`.
///
/// ### Example
/// ```no_run
/// fn foo(values: &[u8]) -> bool {
/// values.iter().any(|&v| v == 10)
/// }
/// ```
/// Use instead:
/// ```no_run
/// fn foo(values: &[u8]) -> bool {
/// values.contains(&10)
/// }
/// ```
#[clippy::version = "1.85.0"]
pub SLICE_ITER_ANY,
perf,
"detect use of `iter().any()` on numeric slices and suggest using `contains()`"
}

pub struct Methods {
avoid_breaking_exported_api: bool,
msrv: Msrv,
Expand Down Expand Up @@ -4449,6 +4475,7 @@ impl_lint_pass!(Methods => [
MAP_ALL_ANY_IDENTITY,
MAP_WITH_UNUSED_ARGUMENT_OVER_RANGES,
UNNECESSARY_MAP_OR,
SLICE_ITER_ANY,
]);

/// Extracts a method call name, args, and `Span` of the method name.
Expand Down Expand Up @@ -4683,6 +4710,7 @@ impl Methods {
("any", [arg]) => {
unused_enumerate_index::check(cx, expr, recv, arg);
needless_character_iteration::check(cx, expr, recv, arg, false);
slice_iter_any::check(cx, expr, &self.msrv);
match method_call(recv) {
Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(
cx,
Expand Down
66 changes: 66 additions & 0 deletions clippy_lints/src/methods/slice_iter_any.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use clippy_utils::diagnostics::span_lint;
use clippy_utils::msrvs::Msrv;
use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self};
use rustc_session::RustcVersion;
use rustc_span::source_map::Spanned;

use super::{SLICE_ITER_ANY, method_call};

pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, msrv: &Msrv) {
if !expr.span.from_expansion()
// any()
&& let Some((name, recv, args, _, _)) = method_call(expr)
&& name == "any"
// check if `iter().any()` can be replaced with `contains()`
&& args.len() == 1
&& let ExprKind::Closure(closure) = args[0].kind
&& let body = cx.tcx.hir().body(closure.body)
&& let ExprKind::Binary(op, lhs, rhs) = body.value.kind
&& can_replace_with_contains(op, lhs, rhs)
// iter()
&& let Some((name, recv, _, _, _)) = method_call(recv)
&& name == "iter"
{
let ref_type = cx.typeck_results().expr_ty_adjusted(recv);

match ref_type.kind() {
ty::Ref(_, inner_type, _) if inner_type.is_slice() => {
// check if the receiver is a numeric slice
if let ty::Slice(slice_type) = inner_type.kind()
&& ((slice_type.to_string() == "u8" || slice_type.to_string() == "i8")
|| (slice_type.is_numeric()
&& msrv.meets(RustcVersion {
major: 1,
minor: 84,
patch: 0,
})))
{
span_lint(
cx,
SLICE_ITER_ANY,
expr.span,
"using `contains()` instead of `iter().any()` is more efficient",
);
}
},
_ => {},
}
}
}

fn can_replace_with_contains(op: Spanned<BinOpKind>, lhs: &Expr<'_>, rhs: &Expr<'_>) -> bool {
matches!(
(op.node, &lhs.kind, &rhs.kind),
(
BinOpKind::Eq,
ExprKind::Path(_) | ExprKind::Unary(_, _),
ExprKind::Lit(_) | ExprKind::Path(_)
) | (
BinOpKind::Eq,
ExprKind::Lit(_),
ExprKind::Path(_) | ExprKind::Unary(_, _)
)
)
}
Comment on lines +53 to +66
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For example, the following code uses == inside closures, but cannot simply be replaced by contains():

let _ = values.iter().any(|&v| v % 2 == 0);

Therefore, this function exclude such cases.

8 changes: 7 additions & 1 deletion tests/ui/needless_collect.fixed
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
#![allow(unused, clippy::needless_if, clippy::suspicious_map, clippy::iter_count)]
#![allow(
unused,
clippy::needless_if,
clippy::suspicious_map,
clippy::iter_count,
clippy::slice_iter_any
)]

use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList};

Expand Down
8 changes: 7 additions & 1 deletion tests/ui/needless_collect.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
#![allow(unused, clippy::needless_if, clippy::suspicious_map, clippy::iter_count)]
#![allow(
unused,
clippy::needless_if,
clippy::suspicious_map,
clippy::iter_count,
clippy::slice_iter_any
)]

use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList};

Expand Down
38 changes: 19 additions & 19 deletions tests/ui/needless_collect.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:9:29
--> tests/ui/needless_collect.rs:15:29
|
LL | let len = sample.iter().collect::<Vec<_>>().len();
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `count()`
Expand All @@ -8,109 +8,109 @@ LL | let len = sample.iter().collect::<Vec<_>>().len();
= help: to override `-D warnings` add `#[allow(clippy::needless_collect)]`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:10:22
--> tests/ui/needless_collect.rs:16:22
|
LL | if sample.iter().collect::<Vec<_>>().is_empty() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:13:28
--> tests/ui/needless_collect.rs:19:28
|
LL | sample.iter().cloned().collect::<Vec<_>>().contains(&1);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `any(|x| x == 1)`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:18:35
--> tests/ui/needless_collect.rs:24:35
|
LL | sample.iter().map(|x| (x, x)).collect::<HashMap<_, _>>().is_empty();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:19:35
--> tests/ui/needless_collect.rs:25:35
|
LL | sample.iter().map(|x| (x, x)).collect::<BTreeMap<_, _>>().is_empty();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:26:19
--> tests/ui/needless_collect.rs:32:19
|
LL | sample.iter().collect::<LinkedList<_>>().len();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `count()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:27:19
--> tests/ui/needless_collect.rs:33:19
|
LL | sample.iter().collect::<LinkedList<_>>().is_empty();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:28:28
--> tests/ui/needless_collect.rs:34:28
|
LL | sample.iter().cloned().collect::<LinkedList<_>>().contains(&1);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `any(|x| x == 1)`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:29:19
--> tests/ui/needless_collect.rs:35:19
|
LL | sample.iter().collect::<LinkedList<_>>().contains(&&1);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `any(|x| x == &1)`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:32:19
--> tests/ui/needless_collect.rs:38:19
|
LL | sample.iter().collect::<BinaryHeap<_>>().len();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `count()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:33:19
--> tests/ui/needless_collect.rs:39:19
|
LL | sample.iter().collect::<BinaryHeap<_>>().is_empty();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:38:27
--> tests/ui/needless_collect.rs:44:27
|
LL | let _ = sample.iter().collect::<HashSet<_>>().is_empty();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:39:27
--> tests/ui/needless_collect.rs:45:27
|
LL | let _ = sample.iter().collect::<HashSet<_>>().contains(&&0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `any(|x| x == &0)`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:61:27
--> tests/ui/needless_collect.rs:67:27
|
LL | let _ = sample.iter().collect::<VecWrapper<_>>().is_empty();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `next().is_none()`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:62:27
--> tests/ui/needless_collect.rs:68:27
|
LL | let _ = sample.iter().collect::<VecWrapper<_>>().contains(&&0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `any(|x| x == &0)`

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:66:40
--> tests/ui/needless_collect.rs:72:40
|
LL | Vec::<u8>::new().extend((0..10).collect::<Vec<_>>());
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:67:20
--> tests/ui/needless_collect.rs:73:20
|
LL | foo((0..10).collect::<Vec<_>>());
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:68:49
--> tests/ui/needless_collect.rs:74:49
|
LL | bar((0..10).collect::<Vec<_>>(), (0..10).collect::<Vec<_>>());
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call

error: avoid using `collect()` when not needed
--> tests/ui/needless_collect.rs:69:37
--> tests/ui/needless_collect.rs:75:37
|
LL | baz((0..10), (), ('a'..='z').collect::<Vec<_>>())
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/search_is_some_fixable_none.fixed
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec)]
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec, clippy::slice_iter_any)]
#![warn(clippy::search_is_some)]

fn main() {
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/search_is_some_fixable_none.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec)]
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec, clippy::slice_iter_any)]
#![warn(clippy::search_is_some)]

fn main() {
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/search_is_some_fixable_some.fixed
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec)]
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec, clippy::slice_iter_any)]
#![warn(clippy::search_is_some)]

fn main() {
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/search_is_some_fixable_some.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec)]
#![allow(dead_code, clippy::explicit_auto_deref, clippy::useless_vec, clippy::slice_iter_any)]
#![warn(clippy::search_is_some)]

fn main() {
Expand Down
Loading
Loading