1 use crate::consts::{constant_context, Constant};
2 use crate::utils::{in_macro, is_type_diagnostic_item, snippet, span_lint_and_sugg};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for usage of `.repeat(1)` and suggest the following method for each types.
12 /// - `.to_string()` for `str`
13 /// - `.clone()` for `String`
14 /// - `.to_vec()` for `slice`
16 /// **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.
18 /// **Known problems:** None.
24 /// let x = String::from("hello world").repeat(1);
30 /// let x = String::from("hello world").clone();
35 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
38 declare_lint_pass!(RepeatOnce => [REPEAT_ONCE]);
40 impl<'tcx> LateLintPass<'tcx> for RepeatOnce {
41 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
43 if let ExprKind::MethodCall(path, _, [receiver, count], _) = &expr.kind;
44 if path.ident.name == sym!(repeat);
45 if let Some(Constant::Int(1)) = constant_context(cx, cx.typeck_results()).expr(&count);
46 if !in_macro(receiver.span);
48 let ty = cx.typeck_results().expr_ty(&receiver).peel_refs();
54 "calling `repeat(1)` on str",
55 "consider using `.to_string()` instead",
56 format!("{}.to_string()", snippet(cx, receiver.span, r#""...""#)),
57 Applicability::MachineApplicable,
59 } else if ty.builtin_index().is_some() {
64 "calling `repeat(1)` on slice",
65 "consider using `.to_vec()` instead",
66 format!("{}.to_vec()", snippet(cx, receiver.span, r#""...""#)),
67 Applicability::MachineApplicable,
69 } else if is_type_diagnostic_item(cx, ty, sym::string_type) {
74 "calling `repeat(1)` on a string literal",
75 "consider using `.clone()` instead",
76 format!("{}.clone()", snippet(cx, receiver.span, r#""...""#)),
77 Applicability::MachineApplicable,