rust-lang / rust-lang/rust-clippy
clippy::needless_collect suggests rewriting to code that is semantically different
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
The needless_collect lint applied to VecDeque::drain diagnosed a call to collect, when the resulting vector was used in a subsequent iteration statement. However, it doesn't consider an intervening pop_back on the same VecDeque, which would alter the semantics of the program (removing the value from pop_back first, then draining the range, rather than draining the range, then using pop_back).
Lint Name
needless_collect
Reproducer
I tried this code:
#![deny(clippy::all)]
use std::collections::VecDeque;
fn test(vstack: &mut VecDeque<i32>, params: usize){
let vstack_len = vstack.len();
let pvals = vstack
.drain((vstack_len - params)..)
.collect::<Vec<_>>();
let function = vstack.pop_back().unwrap();
for (i, val) in pvals.into_iter().enumerate() {
match i {
0 => {}
_ => panic!(),
}
}
}
I saw this happen:
|
9 | .collect::<Vec<_>>();
| ^^^^^^^
10 | let function = vstack.pop_back().unwrap();
11 | for (i, val) in pvals.into_iter().enumerate() {
| ----------------- the iterator could be used here instead
|
note: the lint level is defined here
--> src/lib.rs:1:9
|
1 | #![deny(clippy::all)]
| ^^^^^^^^^^^
= note: `#[deny(clippy::needless_collect)]` implied by `#[deny(clippy::all)]`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
help: use the original Iterator instead of collecting it and then producing a new one
|
7 ~
8 | let function = vstack.pop_back().unwrap();
9 ~ for (i, val) in vstack
10 ~ .drain((vstack_len - params)..).enumerate() {
|
I expected to see this happen:
No Lint
Version
rustc 1.57.0 (f1edd0429 2021-11-29)
binary: rustc
commit-hash: f1edd0429582dd29cccacaf50fd134b05593bd9c
commit-date: 2021-11-29
host: x86_64-unknown-linux-gnu
release: 1.57.0
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the needless_collect lint implementation and its existing tests. Add the provided VecDeque::drain and pop_back reproducer as a regression case, then verify the lint does not suggest replacing the collection with a direct iterator when that would change evaluation order.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100