-
Notifications
You must be signed in to change notification settings - Fork 1.8k
lint on unnecessary collections #15830
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
Open
bend-n
wants to merge
3
commits into
rust-lang:master
Choose a base branch
from
bend-n:returning_vector_produced_from_from_iterator
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
use clippy_config::Conf; | ||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use clippy_utils::sym; | ||
use clippy_utils::ty::{get_iterator_item_ty, has_non_owning_mutable_access, implements_trait}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::def_id::LocalDefId; | ||
use rustc_hir::intravisit::FnKind; | ||
use rustc_lint::LateContext; | ||
use rustc_middle::ty::{self}; | ||
use rustc_span::Span; | ||
|
||
use rustc_hir::{Body, ExprKind, FnDecl, Stmt, StmtKind}; | ||
use rustc_lint::LateLintPass; | ||
use rustc_session::impl_lint_pass; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// Checks for functions returning `Vec<T>` where the `T` is produced from a `_.collect::<Vec<T>>()` | ||
/// | ||
/// ### Why is this bad? | ||
/// | ||
/// This might not be necessary, and its more idiomatic to simply return the iterator, giving the caller the option to use it as they see fit. | ||
/// Its often silly to have the equivalent of `iterator.collect::<Vec<_>>().into_iter()` in your code. | ||
/// | ||
/// ### Potential Issues | ||
/// | ||
/// In some cases, there may be some lifetimes attached to your iterator that make it difficult, or even impossible, to avoid a collection. | ||
/// | ||
/// ### Example | ||
/// ```no_run | ||
/// fn squares() -> Vec<(u8, u8)> { | ||
/// (0..8u8) | ||
/// .flat_map(|x| (0..8).map(move |y| (x, y))) | ||
/// .collect::<Vec<_>>() | ||
/// } | ||
/// ``` | ||
/// Use instead: | ||
/// ```no_run | ||
/// fn squares() -> impl Iterator<Item = (u8, u8)> { | ||
/// (0..8u8).flat_map(|x| (0..8).map(move |y| (x, y))) | ||
/// } | ||
/// ``` | ||
#[clippy::version = "1.92.0"] | ||
pub UNNECESSARY_COLLECT, | ||
restriction, | ||
"checks for functions returning vecs produced from vec::from_iter" | ||
} | ||
|
||
pub struct UnnecessaryCollect { | ||
avoid_breaking_exported_api: bool, | ||
} | ||
|
||
impl UnnecessaryCollect { | ||
pub fn new(conf: &'static Conf) -> Self { | ||
Self { | ||
avoid_breaking_exported_api: conf.avoid_breaking_exported_api, | ||
} | ||
} | ||
} | ||
|
||
impl_lint_pass!(UnnecessaryCollect => [UNNECESSARY_COLLECT]); | ||
|
||
impl<'tcx> LateLintPass<'tcx> for UnnecessaryCollect { | ||
fn check_fn( | ||
&mut self, | ||
cx: &LateContext<'tcx>, | ||
kind: FnKind<'tcx>, | ||
decl: &'tcx FnDecl<'tcx>, | ||
body: &'tcx Body<'tcx>, | ||
_: Span, | ||
def_id: LocalDefId, | ||
) { | ||
let expr = match kind { | ||
FnKind::ItemFn(..) | FnKind::Method(..) if let ExprKind::Block(block, _) = &body.value.kind => { | ||
if let Some(block_expr) = block.expr { | ||
block_expr | ||
} else if let Some(Stmt { | ||
kind: StmtKind::Expr(expr), | ||
.. | ||
}) = block.stmts.last() | ||
{ | ||
expr | ||
} else { | ||
return; | ||
} | ||
}, | ||
_ => return, | ||
} | ||
.peel_drop_temps(); | ||
if let ExprKind::MethodCall(path, iter_expr, args, call_span) = expr.kind | ||
&& !(self.avoid_breaking_exported_api && cx.effective_visibilities.is_exported(def_id)) | ||
&& !args.iter().any(|e| e.span.from_expansion()) | ||
&& !iter_expr.span.from_expansion() | ||
&& path.ident.name == sym::collect | ||
&& let iter_ty = cx.typeck_results().expr_ty(iter_expr) | ||
&& !has_non_owning_mutable_access(cx, iter_ty) | ||
&& let Some(iterator_trait_id) = cx.tcx.get_diagnostic_item(sym::Iterator) | ||
&& implements_trait(cx, iter_ty, iterator_trait_id, &[]) | ||
&& let Some(item) = get_iterator_item_ty(cx, iter_ty) | ||
&& let vec_ty = cx.typeck_results().expr_ty(expr) | ||
&& let ty::Adt(v, args) = vec_ty.kind() | ||
&& cx.tcx.is_diagnostic_item(sym::Vec, v.did()) | ||
// make sure we're collecting to just a vec, and not a vec<result> String or other such tomfoolery | ||
&& args.first().and_then(|x| x.as_type()) == Some(item) | ||
{ | ||
span_lint_and_then( | ||
cx, | ||
UNNECESSARY_COLLECT, | ||
call_span, | ||
"this collection may not be necessary. return the iterator itself".to_string(), | ||
|diag| { | ||
diag.span_label(call_span, "remove this collect"); | ||
diag.span_suggestion( | ||
decl.output.span(), | ||
"consider", | ||
format!("impl Iterator<Item = {item}>"), | ||
Applicability::MaybeIncorrect, | ||
); | ||
}, | ||
); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
#![warn(clippy::unnecessary_collect)] | ||
//@no-rustfix | ||
|
||
fn bad() -> Vec<u32> { | ||
(0..5).collect() | ||
//~^ unnecessary_collect | ||
} | ||
unsafe fn bad2() -> Vec<(u8, u8)> { | ||
(0..8).flat_map(|x| (0..8).map(move |y| (x, y))).collect() | ||
//~^ unnecessary_collect | ||
} | ||
fn okay() -> String { | ||
('a'..='z').collect() | ||
} | ||
fn hmm() -> std::collections::HashSet<u32> { | ||
(0..5).chain(3..12).collect() | ||
} | ||
fn good() -> impl Iterator<Item = u32> { | ||
(5..10).rev() | ||
} | ||
fn main() {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
error: this collection may not be necessary. return the iterator itself | ||
--> tests/ui/unnecessary_collect.rs:5:12 | ||
| | ||
LL | fn bad() -> Vec<u32> { | ||
| -------- help: consider: `impl Iterator<Item = u32>` | ||
LL | (0..5).collect() | ||
| ^^^^^^^^^ remove this collect | ||
| | ||
= note: `-D clippy::unnecessary-collect` implied by `-D warnings` | ||
= help: to override `-D warnings` add `#[allow(clippy::unnecessary_collect)]` | ||
|
||
error: this collection may not be necessary. return the iterator itself | ||
--> tests/ui/unnecessary_collect.rs:9:54 | ||
| | ||
LL | unsafe fn bad2() -> Vec<(u8, u8)> { | ||
| ------------- help: consider: `impl Iterator<Item = (u8, u8)>` | ||
LL | (0..8).flat_map(|x| (0..8).map(move |y| (x, y))).collect() | ||
| ^^^^^^^^^ remove this collect | ||
|
||
error: aborting due to 2 previous errors | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please use
#[expect]
to ignore a lint, and put it as close as possible to the lint emission.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
bit difficult, its define_conf!