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