Skip to content

Commit df646a8

Browse files
authored
Merge pull request #3109 from shssoichiro/3034-needless-collect
Lint against needless uses of `collect()`
2 parents c051309 + f7d2aee commit df646a8

File tree

4 files changed

+143
-0
lines changed

4 files changed

+143
-0
lines changed

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
554554
loops::ITER_NEXT_LOOP,
555555
loops::MANUAL_MEMCPY,
556556
loops::MUT_RANGE_BOUND,
557+
loops::NEEDLESS_COLLECT,
557558
loops::NEEDLESS_RANGE_LOOP,
558559
loops::NEVER_LOOP,
559560
loops::REVERSE_RANGE_LOOP,
@@ -904,6 +905,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
904905
escape::BOXED_LOCAL,
905906
large_enum_variant::LARGE_ENUM_VARIANT,
906907
loops::MANUAL_MEMCPY,
908+
loops::NEEDLESS_COLLECT,
907909
loops::UNUSED_COLLECT,
908910
methods::EXPECT_FUN_CALL,
909911
methods::ITER_NTH,

clippy_lints/src/loops.rs

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ use rustc::middle::mem_categorization::Categorization;
1414
use rustc::middle::mem_categorization::cmt_;
1515
use rustc::ty::{self, Ty};
1616
use rustc::ty::subst::Subst;
17+
use rustc_errors::Applicability;
1718
use std::collections::{HashMap, HashSet};
1819
use std::iter::{once, Iterator};
1920
use syntax::ast;
2021
use syntax::source_map::Span;
22+
use syntax_pos::BytePos;
2123
use crate::utils::{sugg, sext};
2224
use crate::utils::usage::mutated_variables;
2325
use crate::consts::{constant, Constant};
@@ -223,6 +225,27 @@ declare_clippy_lint! {
223225
written as a for loop"
224226
}
225227

228+
/// **What it does:** Checks for functions collecting an iterator when collect
229+
/// is not needed.
230+
///
231+
/// **Why is this bad?** `collect` causes the allocation of a new data structure,
232+
/// when this allocation may not be needed.
233+
///
234+
/// **Known problems:**
235+
/// None
236+
///
237+
/// **Example:**
238+
/// ```rust
239+
/// let len = iterator.collect::<Vec<_>>().len();
240+
/// // should be
241+
/// let len = iterator.count();
242+
/// ```
243+
declare_clippy_lint! {
244+
pub NEEDLESS_COLLECT,
245+
perf,
246+
"collecting an iterator when collect is not needed"
247+
}
248+
226249
/// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
227250
/// are constant and `x` is greater or equal to `y`, unless the range is
228251
/// reversed or has a negative `.step_by(_)`.
@@ -400,6 +423,7 @@ impl LintPass for Pass {
400423
FOR_LOOP_OVER_OPTION,
401424
WHILE_LET_LOOP,
402425
UNUSED_COLLECT,
426+
NEEDLESS_COLLECT,
403427
REVERSE_RANGE_LOOP,
404428
EXPLICIT_COUNTER_LOOP,
405429
EMPTY_LOOP,
@@ -523,6 +547,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
523547
if let ExprKind::While(ref cond, _, _) = expr.node {
524548
check_infinite_loop(cx, cond, expr);
525549
}
550+
551+
check_needless_collect(expr, cx);
526552
}
527553

528554
fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
@@ -2241,3 +2267,71 @@ impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
22412267
NestedVisitorMap::None
22422268
}
22432269
}
2270+
2271+
const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
2272+
2273+
fn check_needless_collect<'a, 'tcx>(expr: &'tcx Expr, cx: &LateContext<'a, 'tcx>) {
2274+
if_chain! {
2275+
if let ExprKind::MethodCall(ref method, _, ref args) = expr.node;
2276+
if let ExprKind::MethodCall(ref chain_method, _, _) = args[0].node;
2277+
if chain_method.ident.name == "collect" && match_trait_method(cx, &args[0], &paths::ITERATOR);
2278+
if let Some(ref generic_args) = chain_method.args;
2279+
if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2280+
then {
2281+
let ty = cx.tables.node_id_to_type(ty.hir_id);
2282+
if match_type(cx, ty, &paths::VEC) ||
2283+
match_type(cx, ty, &paths::VEC_DEQUE) ||
2284+
match_type(cx, ty, &paths::BTREEMAP) ||
2285+
match_type(cx, ty, &paths::HASHMAP) {
2286+
if method.ident.name == "len" {
2287+
let span = shorten_needless_collect_span(expr);
2288+
span_lint_and_then(cx, NEEDLESS_COLLECT, span, NEEDLESS_COLLECT_MSG, |db| {
2289+
db.span_suggestion_with_applicability(
2290+
span,
2291+
"replace with",
2292+
".count()".to_string(),
2293+
Applicability::MachineApplicable,
2294+
);
2295+
});
2296+
}
2297+
if method.ident.name == "is_empty" {
2298+
let span = shorten_needless_collect_span(expr);
2299+
span_lint_and_then(cx, NEEDLESS_COLLECT, span, NEEDLESS_COLLECT_MSG, |db| {
2300+
db.span_suggestion_with_applicability(
2301+
span,
2302+
"replace with",
2303+
".next().is_none()".to_string(),
2304+
Applicability::MachineApplicable,
2305+
);
2306+
});
2307+
}
2308+
if method.ident.name == "contains" {
2309+
let contains_arg = snippet(cx, args[1].span, "??");
2310+
let span = shorten_needless_collect_span(expr);
2311+
span_lint_and_then(cx, NEEDLESS_COLLECT, span, NEEDLESS_COLLECT_MSG, |db| {
2312+
db.span_suggestion_with_applicability(
2313+
span,
2314+
"replace with",
2315+
format!(
2316+
".any(|&x| x == {})",
2317+
if contains_arg.starts_with('&') { &contains_arg[1..] } else { &contains_arg }
2318+
),
2319+
Applicability::MachineApplicable,
2320+
);
2321+
});
2322+
}
2323+
}
2324+
}
2325+
}
2326+
}
2327+
2328+
fn shorten_needless_collect_span(expr: &Expr) -> Span {
2329+
if_chain! {
2330+
if let ExprKind::MethodCall(_, _, ref args) = expr.node;
2331+
if let ExprKind::MethodCall(_, ref span, _) = args[0].node;
2332+
then {
2333+
return expr.span.with_lo(span.lo() - BytePos(1));
2334+
}
2335+
}
2336+
unreachable!()
2337+
}

tests/ui/needless_collect.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#![feature(tool_lints)]
2+
3+
use std::collections::{HashMap, HashSet, BTreeSet};
4+
5+
#[warn(clippy::needless_collect)]
6+
#[allow(unused_variables, clippy::iter_cloned_collect)]
7+
fn main() {
8+
let sample = [1; 5];
9+
let len = sample.iter().collect::<Vec<_>>().len();
10+
if sample.iter().collect::<Vec<_>>().is_empty() {
11+
// Empty
12+
}
13+
sample.iter().cloned().collect::<Vec<_>>().contains(&1);
14+
sample.iter().map(|x| (x, x)).collect::<HashMap<_, _>>().len();
15+
// Notice the `HashSet`--this should not be linted
16+
sample.iter().collect::<HashSet<_>>().len();
17+
// Neither should this
18+
sample.iter().collect::<BTreeSet<_>>().len();
19+
}

tests/ui/needless_collect.stderr

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
error: avoid using `collect()` when not needed
2+
--> $DIR/needless_collect.rs:9:28
3+
|
4+
9 | let len = sample.iter().collect::<Vec<_>>().len();
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.count()`
6+
|
7+
= note: `-D clippy::needless-collect` implied by `-D warnings`
8+
9+
error: avoid using `collect()` when not needed
10+
--> $DIR/needless_collect.rs:10:21
11+
|
12+
10 | if sample.iter().collect::<Vec<_>>().is_empty() {
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.next().is_none()`
14+
15+
error: avoid using `collect()` when not needed
16+
--> $DIR/needless_collect.rs:13:27
17+
|
18+
13 | sample.iter().cloned().collect::<Vec<_>>().contains(&1);
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.any(|&x| x == 1)`
20+
21+
error: avoid using `collect()` when not needed
22+
--> $DIR/needless_collect.rs:14:34
23+
|
24+
14 | sample.iter().map(|x| (x, x)).collect::<HashMap<_, _>>().len();
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `.count()`
26+
27+
error: aborting due to 4 previous errors
28+

0 commit comments

Comments
 (0)