needless_collect: fix suggestion, make test rustfixable

This commit is contained in:
Manish Goregaokar 2019-09-25 05:25:31 -07:00
parent 7f822e742d
commit 980650eec2
4 changed files with 37 additions and 7 deletions

View file

@ -2427,12 +2427,17 @@ fn check_needless_collect<'a, 'tcx>(expr: &'tcx Expr, cx: &LateContext<'a, 'tcx>
let contains_arg = snippet(cx, args[1].span, "??");
let span = shorten_needless_collect_span(expr);
span_lint_and_then(cx, NEEDLESS_COLLECT, span, NEEDLESS_COLLECT_MSG, |db| {
let (arg, pred) = if contains_arg.starts_with('&') {
("x", &contains_arg[1..])
} else {
("&x", &*contains_arg)
};
db.span_suggestion(
span,
"replace with",
format!(
".any(|&x| x == {})",
if contains_arg.starts_with('&') { &contains_arg[1..] } else { &contains_arg }
".any(|{}| x == {})",
arg, pred
),
Applicability::MachineApplicable,
);

View file

@ -0,0 +1,21 @@
// run-rustfix
#![allow(unused, clippy::suspicious_map)]
use std::collections::{BTreeSet, HashMap, HashSet};
#[warn(clippy::needless_collect)]
#[allow(unused_variables, clippy::iter_cloned_collect)]
fn main() {
let sample = [1; 5];
let len = sample.iter().count();
if sample.iter().next().is_none() {
// Empty
}
sample.iter().cloned().any(|x| x == 1);
sample.iter().map(|x| (x, x)).count();
// Notice the `HashSet`--this should not be linted
sample.iter().collect::<HashSet<_>>().len();
// Neither should this
sample.iter().collect::<BTreeSet<_>>().len();
}

View file

@ -1,3 +1,7 @@
// run-rustfix
#![allow(unused, clippy::suspicious_map)]
use std::collections::{BTreeSet, HashMap, HashSet};
#[warn(clippy::needless_collect)]

View file

@ -1,5 +1,5 @@
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:7:28
--> $DIR/needless_collect.rs:11:28
|
LL | let len = sample.iter().collect::<Vec<_>>().len();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.count()`
@ -7,19 +7,19 @@ LL | let len = sample.iter().collect::<Vec<_>>().len();
= note: `-D clippy::needless-collect` implied by `-D warnings`
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:8:21
--> $DIR/needless_collect.rs:12:21
|
LL | if sample.iter().collect::<Vec<_>>().is_empty() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.next().is_none()`
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:11:27
--> $DIR/needless_collect.rs:15:27
|
LL | sample.iter().cloned().collect::<Vec<_>>().contains(&1);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.any(|&x| x == 1)`
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.any(|x| x == 1)`
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:12:34
--> $DIR/needless_collect.rs:16:34
|
LL | sample.iter().map(|x| (x, x)).collect::<HashMap<_, _>>().len();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.count()`