Skip to content

Commit a89eb85

Browse files
committed
Auto merge of #11987 - torfsen:8733-Suggest-str.lines-when-splitting-at-newlines, r=Jarcho
Issue 8733: Suggest `str.lines` when splitting at hard-coded newlines Fixes #8733. ``` changelog: [`splitting_strings_at_newlines`]: New lint that suggests `str.lines` over splitting at hard-coded newlines ``` This is my first PR to Clippy and one of my first Rust PRs in general -- please feel free to nitpick, I'm thankful for any opportunity to learn! I'd be especially interested in feedback to the following points: * Is checking for `'\n'`, `"\n"`, and `"\r\n"` as arguments to `split` enough, or should we do more (e.g. checking for constants that have those values if that is possible)? * Could the code be written in a more idiomatic way? * Is the default `".."` for `snippet` a good choice? I copied it from other uses of `snippet` in the code base, but I'm not entirely sure. * Is the category `suspicious` a good choice? * Is the suggestion applicability `MaybeIncorrect` a good choice? I used it because the return type of `lines` is not exactly the same as that of `split`.
2 parents eca3932 + fe35e08 commit a89eb85

File tree

7 files changed

+430
-0
lines changed

7 files changed

+430
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5583,6 +5583,7 @@ Released 2018-09-13
55835583
[`stable_sort_primitive`]: https://rust-lang.github.io/rust-clippy/master/index.html#stable_sort_primitive
55845584
[`std_instead_of_alloc`]: https://rust-lang.github.io/rust-clippy/master/index.html#std_instead_of_alloc
55855585
[`std_instead_of_core`]: https://rust-lang.github.io/rust-clippy/master/index.html#std_instead_of_core
5586+
[`str_split_at_newline`]: https://rust-lang.github.io/rust-clippy/master/index.html#str_split_at_newline
55865587
[`str_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#str_to_string
55875588
[`string_add`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_add
55885589
[`string_add_assign`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_add_assign

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
435435
crate::methods::STABLE_SORT_PRIMITIVE_INFO,
436436
crate::methods::STRING_EXTEND_CHARS_INFO,
437437
crate::methods::STRING_LIT_CHARS_ANY_INFO,
438+
crate::methods::STR_SPLIT_AT_NEWLINE_INFO,
438439
crate::methods::SUSPICIOUS_COMMAND_ARG_SPACE_INFO,
439440
crate::methods::SUSPICIOUS_MAP_INFO,
440441
crate::methods::SUSPICIOUS_SPLITN_INFO,

clippy_lints/src/methods/mod.rs

+35
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ mod single_char_pattern;
9494
mod single_char_push_string;
9595
mod skip_while_next;
9696
mod stable_sort_primitive;
97+
mod str_split;
9798
mod str_splitn;
9899
mod string_extend_chars;
99100
mod string_lit_chars_any;
@@ -3856,6 +3857,36 @@ declare_clippy_lint! {
38563857
"using `.map(f).unwrap_or_default()`, which is more succinctly expressed as `is_some_and(f)` or `is_ok_and(f)`"
38573858
}
38583859

3860+
declare_clippy_lint! {
3861+
/// ### What it does
3862+
///
3863+
/// Checks for usages of `str.trim().split("\n")` and `str.trim().split("\r\n")`.
3864+
///
3865+
/// ### Why is this bad?
3866+
///
3867+
/// Hard-coding the line endings makes the code less compatible. `str.lines` should be used instead.
3868+
///
3869+
/// ### Example
3870+
/// ```no_run
3871+
/// "some\ntext\nwith\nnewlines\n".trim().split('\n');
3872+
/// ```
3873+
/// Use instead:
3874+
/// ```no_run
3875+
/// "some\ntext\nwith\nnewlines\n".lines();
3876+
/// ```
3877+
///
3878+
/// ### Known Problems
3879+
///
3880+
/// This lint cannot detect if the split is intentionally restricted to a single type of newline (`"\n"` or
3881+
/// `"\r\n"`), for example during the parsing of a specific file format in which precisely one newline type is
3882+
/// valid.
3883+
/// ```
3884+
#[clippy::version = "1.76.0"]
3885+
pub STR_SPLIT_AT_NEWLINE,
3886+
pedantic,
3887+
"splitting a trimmed string at hard-coded newlines"
3888+
}
3889+
38593890
pub struct Methods {
38603891
avoid_breaking_exported_api: bool,
38613892
msrv: Msrv,
@@ -4011,6 +4042,7 @@ impl_lint_pass!(Methods => [
40114042
ITER_FILTER_IS_SOME,
40124043
ITER_FILTER_IS_OK,
40134044
MANUAL_IS_VARIANT_AND,
4045+
STR_SPLIT_AT_NEWLINE,
40144046
]);
40154047

40164048
/// Extracts a method call name, args, and `Span` of the method name.
@@ -4597,6 +4629,9 @@ impl Methods {
45974629
("sort_unstable_by", [arg]) => {
45984630
unnecessary_sort_by::check(cx, expr, recv, arg, true);
45994631
},
4632+
("split", [arg]) => {
4633+
str_split::check(cx, expr, recv, arg);
4634+
},
46004635
("splitn" | "rsplitn", [count_arg, pat_arg]) => {
46014636
if let Some(Constant::Int(count)) = constant(cx, cx.typeck_results(), count_arg) {
46024637
suspicious_splitn::check(cx, name, expr, recv, count);

clippy_lints/src/methods/str_split.rs

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::source::snippet_with_context;
3+
use clippy_utils::visitors::is_const_evaluatable;
4+
use rustc_ast::ast::LitKind;
5+
use rustc_errors::Applicability;
6+
use rustc_hir::{Expr, ExprKind};
7+
use rustc_lint::LateContext;
8+
9+
use super::STR_SPLIT_AT_NEWLINE;
10+
11+
pub(super) fn check<'a>(cx: &LateContext<'a>, expr: &'_ Expr<'_>, split_recv: &'a Expr<'_>, split_arg: &'_ Expr<'_>) {
12+
// We're looking for `A.trim().split(B)`, where the adjusted type of `A` is `&str` (e.g. an
13+
// expression returning `String`), and `B` is a `Pattern` that hard-codes a newline (either `"\n"`
14+
// or `"\r\n"`). There are a lot of ways to specify a pattern, and this lint only checks the most
15+
// basic ones: a `'\n'`, `"\n"`, and `"\r\n"`.
16+
if let ExprKind::MethodCall(trim_method_name, trim_recv, [], _) = split_recv.kind
17+
&& trim_method_name.ident.as_str() == "trim"
18+
&& cx.typeck_results().expr_ty_adjusted(trim_recv).peel_refs().is_str()
19+
&& !is_const_evaluatable(cx, trim_recv)
20+
&& let ExprKind::Lit(split_lit) = split_arg.kind
21+
&& (matches!(split_lit.node, LitKind::Char('\n'))
22+
|| matches!(split_lit.node, LitKind::Str(sym, _) if (sym.as_str() == "\n" || sym.as_str() == "\r\n")))
23+
{
24+
let mut app = Applicability::MaybeIncorrect;
25+
span_lint_and_sugg(
26+
cx,
27+
STR_SPLIT_AT_NEWLINE,
28+
expr.span,
29+
"using `str.trim().split()` with hard-coded newlines",
30+
"use `str.lines()` instead",
31+
format!(
32+
"{}.lines()",
33+
snippet_with_context(cx, trim_recv.span, expr.span.ctxt(), "..", &mut app).0
34+
),
35+
app,
36+
);
37+
}
38+
}

tests/ui/str_split.fixed

+145
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
#![warn(clippy::str_split_at_newline)]
2+
3+
use core::str::Split;
4+
use std::ops::Deref;
5+
6+
struct NotStr<'a> {
7+
s: &'a str,
8+
}
9+
10+
impl<'a> NotStr<'a> {
11+
fn trim(&'a self) -> &'a str {
12+
self.s
13+
}
14+
}
15+
16+
struct DerefsIntoNotStr<'a> {
17+
not_str: &'a NotStr<'a>,
18+
}
19+
20+
impl<'a> Deref for DerefsIntoNotStr<'a> {
21+
type Target = NotStr<'a>;
22+
23+
fn deref(&self) -> &Self::Target {
24+
self.not_str
25+
}
26+
}
27+
28+
struct DerefsIntoStr<'a> {
29+
s: &'a str,
30+
}
31+
32+
impl<'a> Deref for DerefsIntoStr<'a> {
33+
type Target = str;
34+
35+
fn deref(&self) -> &Self::Target {
36+
self.s
37+
}
38+
}
39+
40+
macro_rules! trim_split {
41+
( $x:expr, $y:expr ) => {
42+
$x.trim().split($y);
43+
};
44+
}
45+
46+
macro_rules! make_str {
47+
( $x: expr ) => {
48+
format!("x={}", $x)
49+
};
50+
}
51+
52+
fn main() {
53+
let s1 = "hello\nworld\n";
54+
let s2 = s1.to_owned();
55+
56+
// CASES THAT SHOULD EMIT A LINT
57+
58+
// Splitting a `str` variable at "\n" or "\r\n" after trimming should warn
59+
let _ = s1.lines();
60+
#[allow(clippy::single_char_pattern)]
61+
let _ = s1.lines();
62+
let _ = s1.lines();
63+
64+
// Splitting a `String` variable at "\n" or "\r\n" after trimming should warn
65+
let _ = s2.lines();
66+
#[allow(clippy::single_char_pattern)]
67+
let _ = s2.lines();
68+
let _ = s2.lines();
69+
70+
// Splitting a variable that derefs into `str` at "\n" or "\r\n" after trimming should warn.
71+
let s3 = DerefsIntoStr { s: s1 };
72+
let _ = s3.lines();
73+
#[allow(clippy::single_char_pattern)]
74+
let _ = s3.lines();
75+
let _ = s3.lines();
76+
77+
// If the `&str` is generated by a macro then the macro should not be expanded in the suggested fix.
78+
let _ = make_str!(s1).lines();
79+
80+
// CASES THAT SHOULD NOT EMIT A LINT
81+
82+
// Splitting a `str` constant at "\n" or "\r\n" after trimming should not warn
83+
let _ = "hello\nworld\n".trim().split('\n');
84+
#[allow(clippy::single_char_pattern)]
85+
let _ = "hello\nworld\n".trim().split("\n");
86+
let _ = "hello\nworld\n".trim().split("\r\n");
87+
88+
// Splitting a `str` variable at "\n" or "\r\n" without trimming should not warn, since it is not
89+
// equivalent
90+
let _ = s1.split('\n');
91+
#[allow(clippy::single_char_pattern)]
92+
let _ = s1.split("\n");
93+
let _ = s1.split("\r\n");
94+
95+
// Splitting a `String` variable at "\n" or "\r\n" without trimming should not warn.
96+
let _ = s2.split('\n');
97+
#[allow(clippy::single_char_pattern)]
98+
let _ = s2.split("\n");
99+
100+
// Splitting a variable that derefs into `str` at "\n" or "\r\n" without trimming should not warn.
101+
let _ = s3.split('\n');
102+
#[allow(clippy::single_char_pattern)]
103+
let _ = s3.split("\n");
104+
let _ = s3.split("\r\n");
105+
let _ = s2.split("\r\n");
106+
107+
// Splitting a `str` variable at other separators should not warn
108+
let _ = s1.trim().split('\r');
109+
#[allow(clippy::single_char_pattern)]
110+
let _ = s1.trim().split("\r");
111+
let _ = s1.trim().split("\n\r");
112+
let _ = s1.trim().split("\r \n");
113+
114+
// Splitting a `String` variable at other separators should not warn
115+
let _ = s2.trim().split('\r');
116+
#[allow(clippy::single_char_pattern)]
117+
let _ = s2.trim().split("\r");
118+
let _ = s2.trim().split("\n\r");
119+
120+
// Splitting a variable that derefs into `str` at other separators should not warn
121+
let _ = s3.trim().split('\r');
122+
#[allow(clippy::single_char_pattern)]
123+
let _ = s3.trim().split("\r");
124+
let _ = s3.trim().split("\n\r");
125+
let _ = s3.trim().split("\r \n");
126+
let _ = s2.trim().split("\r \n");
127+
128+
// Using `trim` and `split` on other types should not warn
129+
let not_str = NotStr { s: s1 };
130+
let _ = not_str.trim().split('\n');
131+
#[allow(clippy::single_char_pattern)]
132+
let _ = not_str.trim().split("\n");
133+
let _ = not_str.trim().split("\r\n");
134+
let derefs_into_not_str = DerefsIntoNotStr { not_str: &not_str };
135+
let _ = derefs_into_not_str.trim().split('\n');
136+
#[allow(clippy::single_char_pattern)]
137+
let _ = derefs_into_not_str.trim().split("\n");
138+
let _ = derefs_into_not_str.trim().split("\r\n");
139+
140+
// Code generated by macros should not create a warning
141+
trim_split!(s1, "\r\n");
142+
trim_split!("hello\nworld\n", "\r\n");
143+
trim_split!(s2, "\r\n");
144+
trim_split!(s3, "\r\n");
145+
}

0 commit comments

Comments
 (0)