Skip to content

Commit fcdaf93

Browse files
committed
new lint: drain_collect
1 parent f1fd467 commit fcdaf93

File tree

8 files changed

+249
-2
lines changed

8 files changed

+249
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4610,6 +4610,7 @@ Released 2018-09-13
46104610
[`double_must_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_must_use
46114611
[`double_neg`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_neg
46124612
[`double_parens`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_parens
4613+
[`drain_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#drain_collect
46134614
[`drop_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#drop_bounds
46144615
[`drop_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#drop_copy
46154616
[`drop_non_drop`]: https://rust-lang.github.io/rust-clippy/master/index.html#drop_non_drop

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
317317
crate::methods::CLONE_ON_COPY_INFO,
318318
crate::methods::CLONE_ON_REF_PTR_INFO,
319319
crate::methods::COLLAPSIBLE_STR_REPLACE_INFO,
320+
crate::methods::DRAIN_COLLECT_INFO,
320321
crate::methods::ERR_EXPECT_INFO,
321322
crate::methods::EXPECT_FUN_CALL_INFO,
322323
crate::methods::EXPECT_USED_INFO,
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
use crate::methods::DRAIN_COLLECT;
2+
use clippy_utils::diagnostics::span_lint_and_sugg;
3+
use clippy_utils::is_range_full;
4+
use clippy_utils::source::snippet;
5+
use clippy_utils::ty::is_type_lang_item;
6+
use rustc_errors::Applicability;
7+
use rustc_hir::Expr;
8+
use rustc_hir::ExprKind;
9+
use rustc_hir::LangItem;
10+
use rustc_hir::Path;
11+
use rustc_hir::QPath;
12+
use rustc_lint::LateContext;
13+
use rustc_middle::query::Key;
14+
use rustc_middle::ty::Ty;
15+
use rustc_span::sym;
16+
use rustc_span::Symbol;
17+
18+
/// Checks if both types match the given diagnostic item, e.g.:
19+
///
20+
/// `vec![1,2].drain(..).collect::<Vec<_>>()`
21+
/// ^^^^^^^^^ ^^^^^^ true
22+
/// `vec![1,2].drain(..).collect::<HashSet<_>>()`
23+
/// ^^^^^^^^^ ^^^^^^^^^^ false
24+
fn types_match_diagnostic_item(cx: &LateContext<'_>, expr: Ty<'_>, recv: Ty<'_>, sym: Symbol) -> bool {
25+
if let Some(expr_adt_did) = expr.ty_adt_id()
26+
&& let Some(recv_adt_did) = recv.ty_adt_id()
27+
{
28+
cx.tcx.is_diagnostic_item(sym, expr_adt_did) && cx.tcx.is_diagnostic_item(sym, recv_adt_did)
29+
} else {
30+
false
31+
}
32+
}
33+
34+
/// Checks `std::{vec::Vec, collections::VecDeque}`.
35+
fn check_vec(cx: &LateContext<'_>, args: &[Expr<'_>], expr: Ty<'_>, recv: Ty<'_>, recv_path: &Path<'_>) -> bool {
36+
(types_match_diagnostic_item(cx, expr, recv, sym::Vec)
37+
|| types_match_diagnostic_item(cx, expr, recv, sym::VecDeque))
38+
&& matches!(args, [arg] if is_range_full(cx, arg, Some(recv_path)))
39+
}
40+
41+
/// Checks `std::string::String`
42+
fn check_string(cx: &LateContext<'_>, args: &[Expr<'_>], expr: Ty<'_>, recv: Ty<'_>, recv_path: &Path<'_>) -> bool {
43+
is_type_lang_item(cx, expr, LangItem::String)
44+
&& is_type_lang_item(cx, recv, LangItem::String)
45+
&& matches!(args, [arg] if is_range_full(cx, arg, Some(recv_path)))
46+
}
47+
48+
/// Checks `std::collections::{HashSet, HashMap, BinaryHeap}`.
49+
fn check_collections(cx: &LateContext<'_>, expr: Ty<'_>, recv: Ty<'_>) -> Option<&'static str> {
50+
types_match_diagnostic_item(cx, expr, recv, sym::HashSet)
51+
.then_some("HashSet")
52+
.or_else(|| types_match_diagnostic_item(cx, expr, recv, sym::HashMap).then_some("HashMap"))
53+
.or_else(|| types_match_diagnostic_item(cx, expr, recv, sym::BinaryHeap).then_some("BinaryHeap"))
54+
}
55+
56+
pub(super) fn check(cx: &LateContext<'_>, args: &[Expr<'_>], expr: &Expr<'_>, recv: &Expr<'_>) {
57+
let expr_ty = cx.typeck_results().expr_ty(expr);
58+
let recv_ty = cx.typeck_results().expr_ty(recv).peel_refs();
59+
60+
if let ExprKind::Path(QPath::Resolved(_, recv_path)) = recv.kind
61+
&& let Some(typename) = check_vec(cx, args, expr_ty, recv_ty, recv_path)
62+
.then_some("Vec")
63+
.or_else(|| check_string(cx, args, expr_ty, recv_ty, recv_path).then_some("String"))
64+
.or_else(|| check_collections(cx, expr_ty, recv_ty))
65+
{
66+
let recv = snippet(cx, recv.span, "<expr>");
67+
span_lint_and_sugg(
68+
cx,
69+
DRAIN_COLLECT,
70+
expr.span,
71+
&format!("you seem to be trying to move all elements into a new `{typename}`"),
72+
"consider using `mem::take`",
73+
format!("std::mem::take(&mut {recv})"),
74+
Applicability::MachineApplicable,
75+
);
76+
}
77+
}

clippy_lints/src/methods/mod.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ mod clone_on_copy;
1414
mod clone_on_ref_ptr;
1515
mod cloned_instead_of_copied;
1616
mod collapsible_str_replace;
17+
mod drain_collect;
1718
mod err_expect;
1819
mod expect_fun_call;
1920
mod expect_used;
@@ -3220,6 +3221,42 @@ declare_clippy_lint! {
32203221
"manual reverse iteration of `DoubleEndedIterator`"
32213222
}
32223223

3224+
declare_clippy_lint! {
3225+
/// ### What it does
3226+
/// Checks for calls to `.drain()` that clear the collection, immediately followed by a call to `.collect()`.
3227+
///
3228+
/// > "Collection" in this context refers to any type with a `drain` method:
3229+
/// > `Vec`, `VecDeque`, `BinaryHeap`, `HashSet`,`HashMap`, `String`
3230+
///
3231+
/// ### Why is this bad?
3232+
/// Using `mem::take` is faster as it avoids the allocation.
3233+
/// When using `mem::take`, the old collection is replaced with an empty one and ownership of
3234+
/// the old collection is returned.
3235+
///
3236+
/// ### Drawback
3237+
/// `mem::take(&mut vec)` is almost equivalent to `vec.drain(..).collect()`, except that
3238+
/// it also moves the **capacity**. The user might have explicitly written it this way
3239+
/// to keep the capacity on the original `Vec`.
3240+
///
3241+
/// ### Example
3242+
/// ```rust
3243+
/// fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
3244+
/// v.drain(..).collect()
3245+
/// }
3246+
/// ```
3247+
/// Use instead:
3248+
/// ```rust
3249+
/// use std::mem;
3250+
/// fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
3251+
/// mem::take(v)
3252+
/// }
3253+
/// ```
3254+
#[clippy::version = "1.71.0"]
3255+
pub DRAIN_COLLECT,
3256+
perf,
3257+
"description"
3258+
}
3259+
32233260
pub struct Methods {
32243261
avoid_breaking_exported_api: bool,
32253262
msrv: Msrv,
@@ -3349,6 +3386,7 @@ impl_lint_pass!(Methods => [
33493386
SUSPICIOUS_COMMAND_ARG_SPACE,
33503387
CLEAR_WITH_DRAIN,
33513388
MANUAL_NEXT_BACK,
3389+
DRAIN_COLLECT
33523390
]);
33533391

33543392
/// Extracts a method call name, args, and `Span` of the method name.
@@ -3578,6 +3616,9 @@ impl Methods {
35783616
manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
35793617
}
35803618
},
3619+
Some(("drain", recv, args, ..)) => {
3620+
drain_collect::check(cx, args, expr, recv);
3621+
}
35813622
_ => {},
35823623
}
35833624
},

tests/ui/drain_collect.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#![deny(clippy::drain_collect)]
2+
3+
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
4+
5+
fn binaryheap(b: &mut BinaryHeap<i32>) -> BinaryHeap<i32> {
6+
b.drain().collect()
7+
}
8+
9+
fn binaryheap_dont_lint(b: &mut BinaryHeap<i32>) -> HashSet<i32> {
10+
b.drain().collect()
11+
}
12+
13+
fn hashmap(b: &mut HashMap<i32, i32>) -> HashMap<i32, i32> {
14+
b.drain().collect()
15+
}
16+
17+
fn hashmap_dont_lint(b: &mut HashMap<i32, i32>) -> Vec<(i32, i32)> {
18+
b.drain().collect()
19+
}
20+
21+
fn hashset(b: &mut HashSet<i32>) -> HashSet<i32> {
22+
b.drain().collect()
23+
}
24+
25+
fn hashset_dont_lint(b: &mut HashSet<i32>) -> Vec<i32> {
26+
b.drain().collect()
27+
}
28+
29+
fn vecdeque(b: &mut VecDeque<i32>) -> VecDeque<i32> {
30+
b.drain(..).collect()
31+
}
32+
33+
fn vecdeque_dont_lint(b: &mut VecDeque<i32>) -> HashSet<i32> {
34+
b.drain(..).collect()
35+
}
36+
37+
fn vec(b: &mut Vec<i32>) -> Vec<i32> {
38+
b.drain(..).collect()
39+
}
40+
41+
fn vec2(b: &mut Vec<i32>) -> Vec<i32> {
42+
b.drain(0..).collect()
43+
}
44+
45+
fn vec3(b: &mut Vec<i32>) -> Vec<i32> {
46+
b.drain(..b.len()).collect()
47+
}
48+
49+
fn vec4(b: &mut Vec<i32>) -> Vec<i32> {
50+
b.drain(0..b.len()).collect()
51+
}
52+
53+
fn vec_dont_lint(b: &mut Vec<i32>) -> HashSet<i32> {
54+
b.drain(..).collect()
55+
}
56+
57+
fn string(b: &mut String) -> String {
58+
b.drain(..).collect()
59+
}
60+
61+
fn string_dont_lint(b: &mut String) -> HashSet<char> {
62+
b.drain(..).collect()
63+
}
64+
65+
fn main() {}

tests/ui/drain_collect.stderr

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
error: you seem to be trying to move all elements into a new `BinaryHeap`
2+
--> $DIR/drain_collect.rs:6:5
3+
|
4+
LL | b.drain().collect()
5+
| ^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/drain_collect.rs:1:9
9+
|
10+
LL | #![deny(clippy::drain_collect)]
11+
| ^^^^^^^^^^^^^^^^^^^^^
12+
13+
error: you seem to be trying to move all elements into a new `HashMap`
14+
--> $DIR/drain_collect.rs:14:5
15+
|
16+
LL | b.drain().collect()
17+
| ^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
18+
19+
error: you seem to be trying to move all elements into a new `HashSet`
20+
--> $DIR/drain_collect.rs:22:5
21+
|
22+
LL | b.drain().collect()
23+
| ^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
24+
25+
error: you seem to be trying to move all elements into a new `Vec`
26+
--> $DIR/drain_collect.rs:30:5
27+
|
28+
LL | b.drain(..).collect()
29+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
30+
31+
error: you seem to be trying to move all elements into a new `Vec`
32+
--> $DIR/drain_collect.rs:38:5
33+
|
34+
LL | b.drain(..).collect()
35+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
36+
37+
error: you seem to be trying to move all elements into a new `Vec`
38+
--> $DIR/drain_collect.rs:42:5
39+
|
40+
LL | b.drain(0..).collect()
41+
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
42+
43+
error: you seem to be trying to move all elements into a new `Vec`
44+
--> $DIR/drain_collect.rs:46:5
45+
|
46+
LL | b.drain(..b.len()).collect()
47+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
48+
49+
error: you seem to be trying to move all elements into a new `Vec`
50+
--> $DIR/drain_collect.rs:50:5
51+
|
52+
LL | b.drain(0..b.len()).collect()
53+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
54+
55+
error: you seem to be trying to move all elements into a new `String`
56+
--> $DIR/drain_collect.rs:58:5
57+
|
58+
LL | b.drain(..).collect()
59+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `std::mem::take(&mut b)`
60+
61+
error: aborting due to 9 previous errors
62+

tests/ui/iter_with_drain.fixed

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// will emits unused mut warnings after fixing
33
#![allow(unused_mut)]
44
// will emits needless collect warnings after fixing
5-
#![allow(clippy::needless_collect)]
5+
#![allow(clippy::needless_collect, clippy::drain_collect)]
66
#![warn(clippy::iter_with_drain)]
77
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
88

tests/ui/iter_with_drain.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// will emits unused mut warnings after fixing
33
#![allow(unused_mut)]
44
// will emits needless collect warnings after fixing
5-
#![allow(clippy::needless_collect)]
5+
#![allow(clippy::needless_collect, clippy::drain_collect)]
66
#![warn(clippy::iter_with_drain)]
77
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
88

0 commit comments

Comments
 (0)