Move RepeatOnce into Methods lint pass

This commit is contained in:
Jason Newcomb 2022-06-05 20:49:03 -04:00
parent fd5376194a
commit 06d752e28d
7 changed files with 92 additions and 94 deletions

View file

@ -65,6 +65,7 @@ mod or_fun_call;
mod or_then_unwrap;
mod path_buf_push_overwrite;
mod range_zip_with_len;
mod repeat_once;
mod search_is_some;
mod single_char_add_str;
mod single_char_insert_string;
@ -2760,6 +2761,38 @@ declare_clippy_lint! {
"zipping iterator with a range when `enumerate()` would do"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `.repeat(1)` and suggest the following method for each types.
/// - `.to_string()` for `str`
/// - `.clone()` for `String`
/// - `.to_vec()` for `slice`
///
/// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
/// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
///
/// ### Why is this bad?
/// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
/// the string is the intention behind this, `clone()` should be used.
///
/// ### Example
/// ```rust
/// fn main() {
/// let x = String::from("hello world").repeat(1);
/// }
/// ```
/// Use instead:
/// ```rust
/// fn main() {
/// let x = String::from("hello world").clone();
/// }
/// ```
#[clippy::version = "1.47.0"]
pub REPEAT_ONCE,
complexity,
"using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
}
pub struct Methods {
avoid_breaking_exported_api: bool,
msrv: Option<RustcVersion>,
@ -2875,6 +2908,7 @@ impl_lint_pass!(Methods => [
NONSENSICAL_OPEN_OPTIONS,
PATH_BUF_PUSH_OVERWRITE,
RANGE_ZIP_WITH_LEN,
REPEAT_ONCE,
]);
/// Extracts a method call name, args, and `Span` of the method name.
@ -3263,6 +3297,9 @@ impl Methods {
("push", [arg]) => {
path_buf_push_overwrite::check(cx, expr, arg);
},
("repeat", [arg]) => {
repeat_once::check(cx, expr, recv, arg);
},
("splitn" | "rsplitn", [count_arg, pat_arg]) => {
if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
suspicious_splitn::check(cx, name, expr, recv, count);