Skip to content

unnecessary_join lint #8573

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 38 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
5210a05
add unnecessary join lint
yoav-lavi Mar 22, 2022
0cc0d3d
Merge branch 'rust-lang:master' into master
yoav-lavi Mar 22, 2022
4546e1c
update lints
yoav-lavi Mar 22, 2022
3c8a92d
Merge branch 'master' of https://github.com/yoav-lavi/rust-clippy
yoav-lavi Mar 22, 2022
b47aefd
fix description
yoav-lavi Mar 22, 2022
40f2e0e
fix description
yoav-lavi Mar 22, 2022
12a4632
cleanup
yoav-lavi Mar 22, 2022
a03ee32
fixes
yoav-lavi Mar 22, 2022
d801dd4
fix desc
yoav-lavi Mar 22, 2022
d34f5db
move comment
yoav-lavi Mar 22, 2022
907e913
change explanation
yoav-lavi Mar 22, 2022
9ff0ddd
Update tests/ui/unnecessary_join.rs
yoav-lavi Mar 22, 2022
3fd4266
fix redundant message
yoav-lavi Mar 22, 2022
345cde6
Merge branch 'master' of https://github.com/yoav-lavi/rust-clippy
yoav-lavi Mar 22, 2022
6c02771
add version
yoav-lavi Mar 22, 2022
ac1fab4
move up check
yoav-lavi Mar 22, 2022
98c8c26
pass arguments, fix span
yoav-lavi Mar 22, 2022
ee7791b
cleanup
yoav-lavi Mar 22, 2022
3322ba9
fix spans
yoav-lavi Mar 22, 2022
52f47ef
cleanup
yoav-lavi Mar 22, 2022
7b40cfa
update test
yoav-lavi Mar 22, 2022
14405eb
move lets out of if chain
yoav-lavi Mar 22, 2022
8d41a8f
fix span
yoav-lavi Mar 23, 2022
bcdc558
remove intellij settings
yoav-lavi Mar 23, 2022
b4fa64d
fix message
yoav-lavi Mar 23, 2022
78c107b
cleanup
yoav-lavi Mar 23, 2022
caddb9f
cleanup
yoav-lavi Mar 23, 2022
86b6523
update lints
yoav-lavi Mar 23, 2022
dccddd6
temporarily remove unknown lint
yoav-lavi Mar 23, 2022
c4de8cf
update tests
yoav-lavi Mar 23, 2022
fbe086f
cleanup
yoav-lavi Mar 23, 2022
95a7aa2
remove unneeded ref
yoav-lavi Mar 23, 2022
88be265
order arguments
yoav-lavi Mar 23, 2022
509031f
normalize argument names
yoav-lavi Mar 23, 2022
ecfffb1
cleanup
yoav-lavi Mar 23, 2022
53dfc75
fix version
yoav-lavi Mar 24, 2022
61bc156
switch to pedantic, add warning
yoav-lavi Mar 24, 2022
8f706ef
fix tests and update lints
yoav-lavi Mar 24, 2022
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 @@ -3508,6 +3508,7 @@ Released 2018-09-13
[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
[`unnecessary_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_find_map
[`unnecessary_fold`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fold
[`unnecessary_join`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_join
[`unnecessary_lazy_evaluations`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations
[`unnecessary_mut_passed`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_mut_passed
[`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
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 @@ -334,6 +334,7 @@ store.register_lints(&[
methods::UNNECESSARY_FILTER_MAP,
methods::UNNECESSARY_FIND_MAP,
methods::UNNECESSARY_FOLD,
methods::UNNECESSARY_JOIN,
methods::UNNECESSARY_LAZY_EVALUATIONS,
methods::UNNECESSARY_TO_OWNED,
methods::UNWRAP_OR_ELSE_DEFAULT,
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_pedantic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ store.register_group(true, "clippy::pedantic", Some("clippy_pedantic"), vec![
LintId::of(methods::IMPLICIT_CLONE),
LintId::of(methods::INEFFICIENT_TO_STRING),
LintId::of(methods::MAP_UNWRAP_OR),
LintId::of(methods::UNNECESSARY_JOIN),
LintId::of(misc::FLOAT_CMP),
LintId::of(misc::USED_UNDERSCORE_BINDING),
LintId::of(mut_mut::MUT_MUT),
Expand Down
36 changes: 36 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ mod uninit_assumed_init;
mod unnecessary_filter_map;
mod unnecessary_fold;
mod unnecessary_iter_cloned;
mod unnecessary_join;
mod unnecessary_lazy_eval;
mod unnecessary_to_owned;
mod unwrap_or_else_default;
Expand Down Expand Up @@ -2049,6 +2050,35 @@ declare_clippy_lint! {
"unnecessary calls to `to_owned`-like functions"
}

declare_clippy_lint! {
/// ### What it does
/// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
///
/// ### Why is this bad?
/// `.collect::<String>()` is more concise and usually more performant
///
/// ### Example
/// ```rust
/// let vector = vec!["hello", "world"];
/// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
/// println!("{}", output);
/// ```
/// The correct use would be:
/// ```rust
/// let vector = vec!["hello", "world"];
/// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
/// println!("{}", output);
/// ```
/// ### Known problems
/// While `.collect::<String>()` is more performant in most cases, there are cases where
/// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
/// will prevent loop unrolling and will result in a negative performance impact.
#[clippy::version = "1.61.0"]
pub UNNECESSARY_JOIN,
pedantic,
"using `.collect::<Vec<String>>().join(\"\")` on an iterator"
}

pub struct Methods {
avoid_breaking_exported_api: bool,
msrv: Option<RustcVersion>,
Expand Down Expand Up @@ -2134,6 +2164,7 @@ impl_lint_pass!(Methods => [
MANUAL_SPLIT_ONCE,
NEEDLESS_SPLITN,
UNNECESSARY_TO_OWNED,
UNNECESSARY_JOIN,
]);

/// Extracts a method call name, args, and `Span` of the method name.
Expand Down Expand Up @@ -2429,6 +2460,11 @@ fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Optio
("is_file", []) => filetype_is_file::check(cx, expr, recv),
("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
("join", [join_arg]) => {
if let Some(("collect", _, span)) = method_call(recv) {
unnecessary_join::check(cx, expr, recv, join_arg, span);
}
},
("last", args @ []) | ("skip", args @ [_]) => {
if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
if let ("cloned", []) = (name2, args2) {
Expand Down
41 changes: 41 additions & 0 deletions clippy_lints/src/methods/unnecessary_join.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use clippy_utils::{diagnostics::span_lint_and_sugg, ty::is_type_diagnostic_item};
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{Ref, Slice};
use rustc_span::{sym, Span};

use super::UNNECESSARY_JOIN;

pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx Expr<'tcx>,
join_self_arg: &'tcx Expr<'tcx>,
join_arg: &'tcx Expr<'tcx>,
span: Span,
) {
let applicability = Applicability::MachineApplicable;
let collect_output_adjusted_type = cx.typeck_results().expr_ty_adjusted(join_self_arg);
if_chain! {
// the turbofish for collect is ::<Vec<String>>
if let Ref(_, ref_type, _) = collect_output_adjusted_type.kind();
if let Slice(slice) = ref_type.kind();
if is_type_diagnostic_item(cx, *slice, sym::String);
// the argument for join is ""
if let ExprKind::Lit(spanned) = &join_arg.kind;
if let LitKind::Str(symbol, _) = spanned.node;
if symbol.is_empty();
then {
span_lint_and_sugg(
cx,
UNNECESSARY_JOIN,
span.with_hi(expr.span.hi()),
r#"called `.collect<Vec<String>>().join("")` on an iterator"#,
"try using",
"collect::<String>()".to_owned(),
applicability,
);
}
}
}
35 changes: 35 additions & 0 deletions tests/ui/unnecessary_join.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// run-rustfix

#![warn(clippy::unnecessary_join)]

fn main() {
// should be linted
let vector = vec!["hello", "world"];
let output = vector
.iter()
.map(|item| item.to_uppercase())
.collect::<String>();
println!("{}", output);

// should be linted
let vector = vec!["hello", "world"];
let output = vector
.iter()
.map(|item| item.to_uppercase())
.collect::<String>();
println!("{}", output);

// should not be linted
let vector = vec!["hello", "world"];
let output = vector
.iter()
.map(|item| item.to_uppercase())
.collect::<Vec<String>>()
.join("\n");
println!("{}", output);

// should not be linted
let vector = vec!["hello", "world"];
let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
println!("{}", output);
}
37 changes: 37 additions & 0 deletions tests/ui/unnecessary_join.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// run-rustfix

#![warn(clippy::unnecessary_join)]

fn main() {
// should be linted
let vector = vec!["hello", "world"];
let output = vector
.iter()
.map(|item| item.to_uppercase())
.collect::<Vec<String>>()
.join("");
println!("{}", output);

// should be linted
let vector = vec!["hello", "world"];
let output = vector
.iter()
.map(|item| item.to_uppercase())
.collect::<Vec<_>>()
.join("");
println!("{}", output);

// should not be linted
let vector = vec!["hello", "world"];
let output = vector
.iter()
.map(|item| item.to_uppercase())
.collect::<Vec<String>>()
.join("\n");
println!("{}", output);

// should not be linted
let vector = vec!["hello", "world"];
let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
println!("{}", output);
}
20 changes: 20 additions & 0 deletions tests/ui/unnecessary_join.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
error: called `.collect<Vec<String>>().join("")` on an iterator
--> $DIR/unnecessary_join.rs:11:10
|
LL | .collect::<Vec<String>>()
| __________^
LL | | .join("");
| |_________________^ help: try using: `collect::<String>()`
|
= note: `-D clippy::unnecessary-join` implied by `-D warnings`

error: called `.collect<Vec<String>>().join("")` on an iterator
--> $DIR/unnecessary_join.rs:20:10
|
LL | .collect::<Vec<_>>()
| __________^
LL | | .join("");
| |_________________^ help: try using: `collect::<String>()`

error: aborting due to 2 previous errors