Skip to content

add [`unnecessary_vec_drain] lint #9623

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

Closed
wants to merge 4 commits into from
Closed
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 @@ -4298,6 +4298,7 @@ Released 2018-09-13
[`unnecessary_sort_by`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_sort_by
[`unnecessary_to_owned`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_to_owned
[`unnecessary_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_unwrap
[`unnecessary_vec_drain`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_vec_drain
[`unnecessary_wraps`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_wraps
[`unneeded_field_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unneeded_field_pattern
[`unneeded_wildcard_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unneeded_wildcard_pattern
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
LintId::of(unnamed_address::FN_ADDRESS_COMPARISONS),
LintId::of(unnamed_address::VTABLE_ADDRESS_COMPARISONS),
LintId::of(unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS),
LintId::of(unnecessary_vec_drain::UNNECESSARY_VEC_DRAIN),
LintId::of(unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
LintId::of(unused_io_amount::UNUSED_IO_AMOUNT),
LintId::of(unused_unit::UNUSED_UNIT),
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@ store.register_lints(&[
unnamed_address::VTABLE_ADDRESS_COMPARISONS,
unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS,
unnecessary_self_imports::UNNECESSARY_SELF_IMPORTS,
unnecessary_vec_drain::UNNECESSARY_VEC_DRAIN,
unnecessary_wraps::UNNECESSARY_WRAPS,
unnested_or_patterns::UNNESTED_OR_PATTERNS,
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
LintId::of(to_digit_is_some::TO_DIGIT_IS_SOME),
LintId::of(unit_types::LET_UNIT_VALUE),
LintId::of(unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS),
LintId::of(unnecessary_vec_drain::UNNECESSARY_VEC_DRAIN),
LintId::of(unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
LintId::of(unused_unit::UNUSED_UNIT),
LintId::of(upper_case_acronyms::UPPER_CASE_ACRONYMS),
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ mod unit_types;
mod unnamed_address;
mod unnecessary_owned_empty_strings;
mod unnecessary_self_imports;
mod unnecessary_vec_drain;
mod unnecessary_wraps;
mod unnested_or_patterns;
mod unsafe_removed_from_name;
Expand Down Expand Up @@ -908,6 +909,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|_| Box::new(bool_to_int_with_if::BoolToIntWithIf));
store.register_late_pass(|_| Box::new(box_default::BoxDefault));
store.register_late_pass(|_| Box::new(implicit_saturating_add::ImplicitSaturatingAdd));
store.register_late_pass(|_| Box::new(unnecessary_vec_drain::UnnecessaryVecDrain));
// add lints here, do not remove this comment, it's used in `new_lint`
}

Expand Down
96 changes: 96 additions & 0 deletions clippy_lints/src/unnecessary_vec_drain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item};
use rustc_ast::LitKind::Int;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::{LangItem, Stmt};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::symbol::sym;

declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `vec.drain(..)` with RangeFull that is not bound to a value `let`.
///
/// ### Why is this bad?
/// This creates an iterator that is dropped immediately.
///
/// `vec.clear()` also shows clearer intention.
///
/// ### Example
/// ```rust
/// let mut vec: Vec<i32> = Vec::new();
/// vec.drain(..);
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
/// vec.drain(..);
/// vec.drain(..);

/// ```
/// Use instead:
/// ```rust
/// let mut vec: Vec<i32> = Vec::new();
/// vec.clear();
/// ```
#[clippy::version = "1.66.0"]
pub UNNECESSARY_VEC_DRAIN,
Copy link
Member

Choose a reason for hiding this comment

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

Please rename it to

Suggested change
pub UNNECESSARY_VEC_DRAIN,
pub NEEDLESS_VEC_DRAIN,

style,
"unnecessary `vec.drain(..)`"
}
declare_lint_pass!(UnnecessaryVecDrain => [UNNECESSARY_VEC_DRAIN]);

impl LateLintPass<'_> for UnnecessaryVecDrain {
fn check_stmt<'tcx>(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'tcx>) {
if let hir::StmtKind::Semi(semi_expr) = &stmt.kind {
if let hir::ExprKind::MethodCall(path, rcvr, method_args,drain_span) = &semi_expr.kind
Copy link
Member

Choose a reason for hiding this comment

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

We abbreviate receiver with recv usually. Would be great if you could do this also in this lint impl.

&& path.ident.name == sym!(drain)
{
let ty = cx.typeck_results().expr_ty(rcvr);
if let [expr_element] = &**method_args
Copy link
Member

Choose a reason for hiding this comment

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

You can pull this into the check above and already match for the single argument in methods_args.

&& is_type_diagnostic_item(cx, ty, sym::Vec)
Copy link
Member

Choose a reason for hiding this comment

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

You're combining if let chains with the if_chain macro. Please use if let chains everywhere.

You can also use irrefutable patterns in if let chains, so this can be all in one chain up until here.

{
let ty = cx.typeck_results().expr_ty(expr_element);
if is_type_lang_item(cx, ty, LangItem::RangeFull)
{
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
UNNECESSARY_VEC_DRAIN,
semi_expr.span,
"unnecessary iterator `Drain` is created and dropped immedietly",
"consider calling `clear()`",
format!("{}.clear()", snippet_with_applicability(cx, rcvr.span, "", &mut applicability)),
applicability
);
}
if let hir::ExprKind::Struct(_, expr_fields, _) = &expr_element.kind
&& is_type_lang_item(cx, ty, LangItem::Range)
{
if_chain! {
if let hir::ExprKind::Lit(lit) = &expr_fields[0].expr.kind;
if let hir::ExprKind::MethodCall(path_seg, vec_expr, _, _) = expr_fields[1].expr.kind;

if let hir::hir_id::HirId{owner: owner_expr,..} = &vec_expr.hir_id;
if let hir::hir_id::HirId{owner: owner_rcvr,..} = &rcvr.hir_id;

then {
if let Int(start,_) = lit.node
&& path_seg.ident.name == sym!(len)
&& owner_rcvr == owner_expr
&& start == 0
Comment on lines +73 to +76
Copy link
Member

Choose a reason for hiding this comment

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

NIT: The order of these checks are a bit weird. This check should be done right after matching it to ExprKind::Lit.

{
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
UNNECESSARY_VEC_DRAIN,
*drain_span,
"unnecessary iterator `Drain` is created and dropped immediately",
"consider calling `clear()`",
format!("{}.clear()", snippet_with_applicability(cx, rcvr.span, "", &mut applicability)),
applicability
);
}
}
}
}
}
}
}
}
}
1 change: 1 addition & 0 deletions src/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ docs! {
"unnecessary_sort_by",
"unnecessary_to_owned",
"unnecessary_unwrap",
"unnecessary_vec_drain",
"unnecessary_wraps",
"unneeded_field_pattern",
"unneeded_wildcard_pattern",
Expand Down
18 changes: 18 additions & 0 deletions src/docs/unnecessary_vec_drain.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
### What it does
Checks for usage of `vec.drain(..)` with RangeFull that is not bound to a value `let`.

### Why is this bad?
This creates an iterator that is dropped immediately.

`vec.clear()` also shows clearer intention.

### Example
```
let mut vec: Vec<i32> = Vec::new();
vec.drain(..);
```
Use instead:
```
let mut vec: Vec<i32> = Vec::new();
vec.clear();
```
1 change: 1 addition & 0 deletions tests/ui/range_plus_minus_one.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#![allow(unused_parens)]
#![allow(clippy::iter_with_drain)]
#![allow(clippy::unnecessary_vec_drain)]
fn f() -> usize {
42
}
Expand Down
1 change: 1 addition & 0 deletions tests/ui/range_plus_minus_one.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#![allow(unused_parens)]
#![allow(clippy::iter_with_drain)]
#![allow(clippy::unnecessary_vec_drain)]
fn f() -> usize {
42
}
Expand Down
18 changes: 9 additions & 9 deletions tests/ui/range_plus_minus_one.stderr
Original file line number Diff line number Diff line change
@@ -1,57 +1,57 @@
error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:31:14
--> $DIR/range_plus_minus_one.rs:32:14
|
LL | for _ in 0..3 + 1 {}
| ^^^^^^^^ help: use: `0..=3`
|
= note: `-D clippy::range-plus-one` implied by `-D warnings`

error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:34:14
--> $DIR/range_plus_minus_one.rs:35:14
|
LL | for _ in 0..1 + 5 {}
| ^^^^^^^^ help: use: `0..=5`

error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:37:14
--> $DIR/range_plus_minus_one.rs:38:14
|
LL | for _ in 1..1 + 1 {}
| ^^^^^^^^ help: use: `1..=1`

error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:43:14
--> $DIR/range_plus_minus_one.rs:44:14
|
LL | for _ in 0..(1 + f()) {}
| ^^^^^^^^^^^^ help: use: `0..=f()`

error: an exclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:47:13
--> $DIR/range_plus_minus_one.rs:48:13
|
LL | let _ = ..=11 - 1;
| ^^^^^^^^^ help: use: `..11`
|
= note: `-D clippy::range-minus-one` implied by `-D warnings`

error: an exclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:48:13
--> $DIR/range_plus_minus_one.rs:49:13
|
LL | let _ = ..=(11 - 1);
| ^^^^^^^^^^^ help: use: `..11`

error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:49:13
--> $DIR/range_plus_minus_one.rs:50:13
|
LL | let _ = (1..11 + 1);
| ^^^^^^^^^^^ help: use: `(1..=11)`

error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:50:13
--> $DIR/range_plus_minus_one.rs:51:13
|
LL | let _ = (f() + 1)..(f() + 1);
| ^^^^^^^^^^^^^^^^^^^^ help: use: `((f() + 1)..=f())`

error: an inclusive range would be more readable
--> $DIR/range_plus_minus_one.rs:54:14
--> $DIR/range_plus_minus_one.rs:55:14
|
LL | for _ in 1..ONE + ONE {}
| ^^^^^^^^^^^^ help: use: `1..=ONE`
Expand Down
12 changes: 12 additions & 0 deletions tests/ui/unnecessary_vec_drain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#![allow(unused)]
#![warn(clippy::unnecessary_vec_drain)]

fn main() {
let mut vec: Vec<i32> = Vec::new();
//Lint
vec.drain(..);
vec.drain(0..vec.len());

// Dont Lint
let iter = vec.drain(..);
}
16 changes: 16 additions & 0 deletions tests/ui/unnecessary_vec_drain.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
error: unnecessary iterator `Drain` is created and dropped immedietly
--> $DIR/unnecessary_vec_drain.rs:7:5
|
LL | vec.drain(..);
| ^^^^^^^^^^^^^ help: consider calling `clear()`: `vec.clear()`
|
= note: `-D clippy::unnecessary-vec-drain` implied by `-D warnings`

error: unnecessary iterator `Drain` is created and dropped immediately
--> $DIR/unnecessary_vec_drain.rs:8:9
|
LL | vec.drain(0..vec.len());
| ^^^^^^^^^^^^^^^^^^^ help: consider calling `clear()`: `vec.clear()`
Comment on lines +12 to +13
Copy link
Member

Choose a reason for hiding this comment

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

This suggestion won't work. The code after applying this suggestion would be vec.vec.clear(). You'll have to fix the span your using when producing this suggestion to also include vec.


error: aborting due to 2 previous errors