Skip to content

Commit ca570f9

Browse files
committed
Auto merge of rust-lang#7265 - Jarcho:manual_str_repeat, r=giraffate
Add lint `manual_str_repeat` fixes: rust-lang#7260 There's a similar function for slices. Should this be renamed to include it, or should that be a separate lint? If we are going to have them as one lint a better name will be needed. `manual_repeat` isn't exactly clear as it's replacing a call to `iter::repeat`. changelog: Add new lint `manual_str_repeat`
2 parents 860cb8f + cfddf09 commit ca570f9

12 files changed

+359
-10
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2493,6 +2493,7 @@ Released 2018-09-13
24932493
[`manual_ok_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_ok_or
24942494
[`manual_range_contains`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_range_contains
24952495
[`manual_saturating_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_saturating_arithmetic
2496+
[`manual_str_repeat`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_str_repeat
24962497
[`manual_strip`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_strip
24972498
[`manual_swap`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_swap
24982499
[`manual_unwrap_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_unwrap_or

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
762762
methods::MANUAL_FILTER_MAP,
763763
methods::MANUAL_FIND_MAP,
764764
methods::MANUAL_SATURATING_ARITHMETIC,
765+
methods::MANUAL_STR_REPEAT,
765766
methods::MAP_COLLECT_RESULT_UNIT,
766767
methods::MAP_FLATTEN,
767768
methods::MAP_UNWRAP_OR,
@@ -1298,6 +1299,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12981299
LintId::of(methods::MANUAL_FILTER_MAP),
12991300
LintId::of(methods::MANUAL_FIND_MAP),
13001301
LintId::of(methods::MANUAL_SATURATING_ARITHMETIC),
1302+
LintId::of(methods::MANUAL_STR_REPEAT),
13011303
LintId::of(methods::MAP_COLLECT_RESULT_UNIT),
13021304
LintId::of(methods::NEW_RET_NO_SELF),
13031305
LintId::of(methods::OK_EXPECT),
@@ -1735,6 +1737,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
17351737
LintId::of(loops::NEEDLESS_COLLECT),
17361738
LintId::of(methods::EXPECT_FUN_CALL),
17371739
LintId::of(methods::ITER_NTH),
1740+
LintId::of(methods::MANUAL_STR_REPEAT),
17381741
LintId::of(methods::OR_FUN_CALL),
17391742
LintId::of(methods::SINGLE_CHAR_PATTERN),
17401743
LintId::of(misc::CMP_OWNED),

clippy_lints/src/mem_discriminant.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use rustc_errors::Applicability;
77
use rustc_hir::{BorrowKind, Expr, ExprKind};
88
use rustc_lint::{LateContext, LateLintPass};
99
use rustc_session::{declare_lint_pass, declare_tool_lint};
10-
use std::iter;
1110

1211
declare_clippy_lint! {
1312
/// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
@@ -67,7 +66,7 @@ impl<'tcx> LateLintPass<'tcx> for MemDiscriminant {
6766
}
6867
}
6968

70-
let derefs: String = iter::repeat('*').take(derefs_needed).collect();
69+
let derefs = "*".repeat(derefs_needed);
7170
diag.span_suggestion(
7271
param.span,
7372
"try dereferencing",

clippy_lints/src/methods/clone_on_copy.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKind};
88
use rustc_lint::LateContext;
99
use rustc_middle::ty::{self, adjustment::Adjust};
1010
use rustc_span::symbol::{sym, Symbol};
11-
use std::iter;
1211

1312
use super::CLONE_DOUBLE_REF;
1413
use super::CLONE_ON_COPY;
@@ -54,8 +53,8 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: Symbol,
5453
ty = inner;
5554
n += 1;
5655
}
57-
let refs: String = iter::repeat('&').take(n + 1).collect();
58-
let derefs: String = iter::repeat('*').take(n).collect();
56+
let refs = "&".repeat(n + 1);
57+
let derefs = "*".repeat(n);
5958
let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
6059
diag.span_suggestion(
6160
expr.span,
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
3+
use clippy_utils::sugg::Sugg;
4+
use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item, match_type};
5+
use clippy_utils::{is_expr_path_def_path, paths};
6+
use if_chain::if_chain;
7+
use rustc_ast::LitKind;
8+
use rustc_errors::Applicability;
9+
use rustc_hir::{Expr, ExprKind, LangItem};
10+
use rustc_lint::LateContext;
11+
use rustc_middle::ty::{self, Ty, TyS};
12+
use rustc_span::symbol::sym;
13+
use std::borrow::Cow;
14+
15+
use super::MANUAL_STR_REPEAT;
16+
17+
enum RepeatKind {
18+
String,
19+
Char(char),
20+
}
21+
22+
fn get_ty_param(ty: Ty<'_>) -> Option<Ty<'_>> {
23+
if let ty::Adt(_, subs) = ty.kind() {
24+
subs.types().next()
25+
} else {
26+
None
27+
}
28+
}
29+
30+
fn parse_repeat_arg(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<RepeatKind> {
31+
if let ExprKind::Lit(lit) = &e.kind {
32+
match lit.node {
33+
LitKind::Str(..) => Some(RepeatKind::String),
34+
LitKind::Char(c) => Some(RepeatKind::Char(c)),
35+
_ => None,
36+
}
37+
} else {
38+
let ty = cx.typeck_results().expr_ty(e);
39+
if is_type_diagnostic_item(cx, ty, sym::string_type)
40+
|| (is_type_lang_item(cx, ty, LangItem::OwnedBox) && get_ty_param(ty).map_or(false, TyS::is_str))
41+
|| (match_type(cx, ty, &paths::COW) && get_ty_param(ty).map_or(false, TyS::is_str))
42+
{
43+
Some(RepeatKind::String)
44+
} else {
45+
let ty = ty.peel_refs();
46+
(ty.is_str() || is_type_diagnostic_item(cx, ty, sym::string_type)).then(|| RepeatKind::String)
47+
}
48+
}
49+
}
50+
51+
pub(super) fn check(
52+
cx: &LateContext<'_>,
53+
collect_expr: &Expr<'_>,
54+
take_expr: &Expr<'_>,
55+
take_self_arg: &Expr<'_>,
56+
take_arg: &Expr<'_>,
57+
) {
58+
if_chain! {
59+
if let ExprKind::Call(repeat_fn, [repeat_arg]) = take_self_arg.kind;
60+
if is_expr_path_def_path(cx, repeat_fn, &paths::ITER_REPEAT);
61+
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(collect_expr), sym::string_type);
62+
if let Some(collect_id) = cx.typeck_results().type_dependent_def_id(collect_expr.hir_id);
63+
if let Some(take_id) = cx.typeck_results().type_dependent_def_id(take_expr.hir_id);
64+
if let Some(iter_trait_id) = cx.tcx.get_diagnostic_item(sym::Iterator);
65+
if cx.tcx.trait_of_item(collect_id) == Some(iter_trait_id);
66+
if cx.tcx.trait_of_item(take_id) == Some(iter_trait_id);
67+
if let Some(repeat_kind) = parse_repeat_arg(cx, repeat_arg);
68+
let ctxt = collect_expr.span.ctxt();
69+
if ctxt == take_expr.span.ctxt();
70+
if ctxt == take_self_arg.span.ctxt();
71+
then {
72+
let mut app = Applicability::MachineApplicable;
73+
let count_snip = snippet_with_context(cx, take_arg.span, ctxt, "..", &mut app).0;
74+
75+
let val_str = match repeat_kind {
76+
RepeatKind::Char(_) if repeat_arg.span.ctxt() != ctxt => return,
77+
RepeatKind::Char('\'') => r#""'""#.into(),
78+
RepeatKind::Char('"') => r#""\"""#.into(),
79+
RepeatKind::Char(_) =>
80+
match snippet_with_applicability(cx, repeat_arg.span, "..", &mut app) {
81+
Cow::Owned(s) => Cow::Owned(format!("\"{}\"", &s[1..s.len() - 1])),
82+
s @ Cow::Borrowed(_) => s,
83+
},
84+
RepeatKind::String =>
85+
Sugg::hir_with_context(cx, repeat_arg, ctxt, "..", &mut app).maybe_par().to_string().into(),
86+
};
87+
88+
span_lint_and_sugg(
89+
cx,
90+
MANUAL_STR_REPEAT,
91+
collect_expr.span,
92+
"manual implementation of `str::repeat` using iterators",
93+
"try this",
94+
format!("{}.repeat({})", val_str, count_snip),
95+
app
96+
)
97+
}
98+
}
99+
}

clippy_lints/src/methods/mod.rs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ mod iter_nth_zero;
3232
mod iter_skip_next;
3333
mod iterator_step_by_zero;
3434
mod manual_saturating_arithmetic;
35+
mod manual_str_repeat;
3536
mod map_collect_result_unit;
3637
mod map_flatten;
3738
mod map_unwrap_or;
@@ -62,7 +63,7 @@ mod zst_offset;
6263
use bind_instead_of_map::BindInsteadOfMap;
6364
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
6465
use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
65-
use clippy_utils::{contains_return, get_trait_def_id, in_macro, iter_input_pats, paths, return_ty};
66+
use clippy_utils::{contains_return, get_trait_def_id, in_macro, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
6667
use if_chain::if_chain;
6768
use rustc_hir as hir;
6869
use rustc_hir::def::Res;
@@ -1664,6 +1665,27 @@ declare_clippy_lint! {
16641665
"checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
16651666
}
16661667

1668+
declare_clippy_lint! {
1669+
/// **What it does:** Checks for manual implementations of `str::repeat`
1670+
///
1671+
/// **Why is this bad?** These are both harder to read, as well as less performant.
1672+
///
1673+
/// **Known problems:** None.
1674+
///
1675+
/// **Example:**
1676+
///
1677+
/// ```rust
1678+
/// // Bad
1679+
/// let x: String = std::iter::repeat('x').take(10).collect();
1680+
///
1681+
/// // Good
1682+
/// let x: String = "x".repeat(10);
1683+
/// ```
1684+
pub MANUAL_STR_REPEAT,
1685+
perf,
1686+
"manual implementation of `str::repeat`"
1687+
}
1688+
16671689
pub struct Methods {
16681690
avoid_breaking_exported_api: bool,
16691691
msrv: Option<RustcVersion>,
@@ -1737,7 +1759,8 @@ impl_lint_pass!(Methods => [
17371759
FROM_ITER_INSTEAD_OF_COLLECT,
17381760
INSPECT_FOR_EACH,
17391761
IMPLICIT_CLONE,
1740-
SUSPICIOUS_SPLITN
1762+
SUSPICIOUS_SPLITN,
1763+
MANUAL_STR_REPEAT
17411764
]);
17421765

17431766
/// Extracts a method call name, args, and `Span` of the method name.
@@ -1981,6 +2004,11 @@ fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Optio
19812004
Some(("map", [m_recv, m_arg], _)) => {
19822005
map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
19832006
},
2007+
Some(("take", [take_self_arg, take_arg], _)) => {
2008+
if meets_msrv(msrv, &msrvs::STR_REPEAT) {
2009+
manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2010+
}
2011+
},
19842012
_ => {},
19852013
},
19862014
("count", []) => match method_call!(recv) {

clippy_lints/src/utils/conf.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ macro_rules! define_Conf {
124124
define_Conf! {
125125
/// Lint: ENUM_VARIANT_NAMES, LARGE_TYPES_PASSED_BY_VALUE, TRIVIALLY_COPY_PASS_BY_REF, UNNECESSARY_WRAPS, UPPER_CASE_ACRONYMS, WRONG_SELF_CONVENTION. Suppress lints whenever the suggested change would cause breakage for other crates.
126126
(avoid_breaking_exported_api: bool = true),
127-
/// Lint: CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE. The minimum rust version that the project supports
127+
/// Lint: MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE. The minimum rust version that the project supports
128128
(msrv: Option<String> = None),
129129
/// Lint: BLACKLISTED_NAME. The list of blacklisted names to lint about. NB: `bar` is not here since it has legitimate uses
130130
(blacklisted_names: Vec<String> = ["foo", "baz", "quux"].iter().map(ToString::to_string).collect()),

clippy_utils/src/msrvs.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,5 @@ msrv_aliases! {
2626
1,34,0 { TRY_FROM }
2727
1,30,0 { ITERATOR_FIND_MAP }
2828
1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST }
29+
1,16,0 { STR_REPEAT }
2930
}

clippy_utils/src/sugg.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22
#![deny(clippy::missing_docs_in_private_items)]
33

44
use crate::higher;
5-
use crate::source::{snippet, snippet_opt, snippet_with_macro_callsite};
5+
use crate::source::{snippet, snippet_opt, snippet_with_context, snippet_with_macro_callsite};
66
use rustc_ast::util::parser::AssocOp;
77
use rustc_ast::{ast, token};
88
use rustc_ast_pretty::pprust::token_kind_to_string;
99
use rustc_errors::Applicability;
1010
use rustc_hir as hir;
1111
use rustc_lint::{EarlyContext, LateContext, LintContext};
1212
use rustc_span::source_map::{CharPos, Span};
13-
use rustc_span::{BytePos, Pos};
13+
use rustc_span::{BytePos, Pos, SyntaxContext};
1414
use std::borrow::Cow;
1515
use std::convert::TryInto;
1616
use std::fmt::Display;
@@ -90,6 +90,29 @@ impl<'a> Sugg<'a> {
9090
Self::hir_from_snippet(expr, snippet)
9191
}
9292

93+
/// Same as `hir`, but first walks the span up to the given context. This will result in the
94+
/// macro call, rather then the expansion, if the span is from a child context. If the span is
95+
/// not from a child context, it will be used directly instead.
96+
///
97+
/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR
98+
/// node would result in `box []`. If given the context of the address of expression, this
99+
/// function will correctly get a snippet of `vec![]`.
100+
pub fn hir_with_context(
101+
cx: &LateContext<'_>,
102+
expr: &hir::Expr<'_>,
103+
ctxt: SyntaxContext,
104+
default: &'a str,
105+
applicability: &mut Applicability,
106+
) -> Self {
107+
let (snippet, in_macro) = snippet_with_context(cx, expr.span, ctxt, default, applicability);
108+
109+
if in_macro {
110+
Sugg::NonParen(snippet)
111+
} else {
112+
Self::hir_from_snippet(expr, snippet)
113+
}
114+
}
115+
93116
/// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
94117
/// function variants of `Sugg`, since these use different snippet functions.
95118
fn hir_from_snippet(expr: &hir::Expr<'_>, snippet: Cow<'a, str>) -> Self {

tests/ui/manual_str_repeat.fixed

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// run-rustfix
2+
3+
#![feature(custom_inner_attributes)]
4+
#![warn(clippy::manual_str_repeat)]
5+
6+
use std::borrow::Cow;
7+
use std::iter::{repeat, FromIterator};
8+
9+
fn main() {
10+
let _: String = "test".repeat(10);
11+
let _: String = "x".repeat(10);
12+
let _: String = "'".repeat(10);
13+
let _: String = "\"".repeat(10);
14+
15+
let x = "test";
16+
let count = 10;
17+
let _ = x.repeat(count + 2);
18+
19+
macro_rules! m {
20+
($e:expr) => {{ $e }};
21+
}
22+
// FIXME: macro args are fine
23+
let _: String = repeat(m!("test")).take(m!(count)).collect();
24+
25+
let x = &x;
26+
let _: String = (*x).repeat(count);
27+
28+
macro_rules! repeat_m {
29+
($e:expr) => {{ repeat($e) }};
30+
}
31+
// Don't lint, repeat is from a macro.
32+
let _: String = repeat_m!("test").take(count).collect();
33+
34+
let x: Box<str> = Box::from("test");
35+
let _: String = x.repeat(count);
36+
37+
#[derive(Clone)]
38+
struct S;
39+
impl FromIterator<Box<S>> for String {
40+
fn from_iter<T: IntoIterator<Item = Box<S>>>(_: T) -> Self {
41+
Self::new()
42+
}
43+
}
44+
// Don't lint, wrong box type
45+
let _: String = repeat(Box::new(S)).take(count).collect();
46+
47+
let _: String = Cow::Borrowed("test").repeat(count);
48+
49+
let x = "x".to_owned();
50+
let _: String = x.repeat(count);
51+
52+
let x = 'x';
53+
// Don't lint, not char literal
54+
let _: String = repeat(x).take(count).collect();
55+
}
56+
57+
fn _msrv_1_15() {
58+
#![clippy::msrv = "1.15"]
59+
// `str::repeat` was stabilized in 1.16. Do not lint this
60+
let _: String = std::iter::repeat("test").take(10).collect();
61+
}
62+
63+
fn _msrv_1_16() {
64+
#![clippy::msrv = "1.16"]
65+
let _: String = "test".repeat(10);
66+
}

0 commit comments

Comments
 (0)