Skip to content

Add new lint, checking for .to_string().parse().unwrap() #14214

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
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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 @@ -5945,6 +5945,7 @@ Released 2018-09-13
[`panic_params`]: https://rust-lang.github.io/rust-clippy/master/index.html#panic_params
[`panicking_overflow_checks`]: https://rust-lang.github.io/rust-clippy/master/index.html#panicking_overflow_checks
[`panicking_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#panicking_unwrap
[`parse_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#parse_to_string
[`partial_pub_fields`]: https://rust-lang.github.io/rust-clippy/master/index.html#partial_pub_fields
[`partialeq_ne_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_ne_impl
[`partialeq_to_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_to_none
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::methods::OPTION_MAP_OR_NONE_INFO,
crate::methods::OR_FUN_CALL_INFO,
crate::methods::OR_THEN_UNWRAP_INFO,
crate::methods::PARSE_TO_STRING_INFO,
crate::methods::PATH_BUF_PUSH_OVERWRITE_INFO,
crate::methods::PATH_ENDS_WITH_EXT_INFO,
crate::methods::RANGE_ZIP_WITH_LEN_INFO,
Expand Down
29 changes: 29 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ mod option_map_or_none;
mod option_map_unwrap_or;
mod or_fun_call;
mod or_then_unwrap;
mod parse_to_string;
mod path_buf_push_overwrite;
mod path_ends_with_ext;
mod range_zip_with_len;
Expand Down Expand Up @@ -4434,6 +4435,28 @@ declare_clippy_lint! {
"calling .bytes() is very inefficient when data is not in memory"
}

declare_clippy_lint! {
/// ### What it does
/// Finds places where something is converted to string and then parsed.
///
/// ### Why is this bad?
/// Converting between types through string is often lossy
/// and has usually worse performance than a direct approach.
///
/// ### Example
/// ```no_run
/// let bad: u64 = 42_u32.to_string().parse().unwrap();
/// ```
/// Use instead:
/// ```no_run
/// let good: u64 = 42_u32.into();
/// ```
#[clippy::version = "1.86.0"]
pub PARSE_TO_STRING,
suspicious,
"parsing after converting to string"
}

#[expect(clippy::struct_excessive_bools)]
pub struct Methods {
avoid_breaking_exported_api: bool,
Expand Down Expand Up @@ -4609,6 +4632,7 @@ impl_lint_pass!(Methods => [
SLICED_STRING_AS_BYTES,
RETURN_AND_THEN,
UNBUFFERED_BYTES,
PARSE_TO_STRING,
]);

/// Extracts a method call name, args, and `Span` of the method name.
Expand Down Expand Up @@ -5333,6 +5357,11 @@ impl Methods {
Some(("or", recv, [or_arg], or_span, _)) => {
or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
},
Some(("parse", recv, _, _, _)) => {
if let Some(("to_string", _, _, _, span)) = method_call(recv) {
parse_to_string::check(cx, expr, span);
}
},
_ => {},
}
unnecessary_literal_unwrap::check(cx, expr, recv, name, args);
Expand Down
12 changes: 12 additions & 0 deletions clippy_lints/src/methods/parse_to_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_span::Span;

pub fn check(cx: &LateContext<'_>, expr: &Expr<'_>, span: Span) {
Copy link
Contributor

Choose a reason for hiding this comment

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

You should at least check that the intermediate type is String.

Copy link
Author

Choose a reason for hiding this comment

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

Wouldn't it make more sense to check that

  • the receiver of to_string isn't &str, since impl ToString for &str + str::parse is not actually suspicious
  • the receiver of parse is &str (delegating to FromStr)

Copy link
Author

Choose a reason for hiding this comment

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

On second thought, impl ToString for &str + str::parse is indeed suspicious, as the allocation as owned string is unnecessary when parsing only requires a string slice.

Am I missing something in the search result I had deemed not suspicious?

https://github.com/clearloop/leetcode-cli/blob/04a611b7996d8a6d8b622feecb844f248c465bd1/src/helper.rs#L147

It should be using <Captures as Index>::index, which yields a string slice already, making the to_string call suspicious.

clippy_utils::diagnostics::span_lint(
cx,
super::PARSE_TO_STRING,
expr.span.with_lo(span.lo()),
"parsing a the output of `.to_string()`",
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
"parsing a the output of `.to_string()`",
"parsing the output of `.to_string()`",

);
}
6 changes: 6 additions & 0 deletions tests/ui/parse_to_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#![warn(clippy::parse_to_string)]

fn main() {
let bad: u64 = 42_u32.to_string().parse().unwrap();
//~^ ERROR: parsing
}
11 changes: 11 additions & 0 deletions tests/ui/parse_to_string.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error: parsing a the output of `.to_string()`
--> tests/ui/parse_to_string.rs:4:27
|
LL | let bad: u64 = 42_u32.to_string().parse().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `-D clippy::parse-to-string` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::parse_to_string)]`

error: aborting due to 1 previous error

Loading