1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::is_type_lang_item;
3 use clippy_utils::{higher, match_def_path, paths};
4 use rustc_hir::{BinOpKind, Expr, ExprKind, LangItem, MatchSource};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::sym;
8
9 declare_clippy_lint! {
10 /// ### What it does
11 /// Detects cases where the result of a `format!` call is
12 /// appended to an existing `String`.
13 ///
14 /// ### Why is this bad?
15 /// Introduces an extra, avoidable heap allocation.
16 ///
17 /// ### Known problems
18 /// `format!` returns a `String` but `write!` returns a `Result`.
19 /// Thus you are forced to ignore the `Err` variant to achieve the same API.
20 ///
21 /// While using `write!` in the suggested way should never fail, this isn't necessarily clear to the programmer.
22 ///
23 /// ### Example
24 /// ```rust
25 /// let mut s = String::new();
26 /// s += &format!("0x{:X}", 1024);
27 /// s.push_str(&format!("0x{:X}", 1024));
28 /// ```
29 /// Use instead:
30 /// ```rust
31 /// use std::fmt::Write as _; // import without risk of name clashing
32 ///
33 /// let mut s = String::new();
34 /// let _ = write!(s, "0x{:X}", 1024);
35 /// ```
36 #[clippy::version = "1.62.0"]
37 pub FORMAT_PUSH_STRING,
38 restriction,
39 "`format!(..)` appended to existing `String`"
40 }
41 declare_lint_pass!(FormatPushString => [FORMAT_PUSH_STRING]);
42
is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool43 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
44 is_type_lang_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), LangItem::String)
45 }
is_format(cx: &LateContext<'_>, e: &Expr<'_>) -> bool46 fn is_format(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
47 let e = e.peel_blocks().peel_borrows();
48
49 if e.span.from_expansion()
50 && let Some(macro_def_id) = e.span.ctxt().outer_expn_data().macro_def_id
51 {
52 cx.tcx.get_diagnostic_name(macro_def_id) == Some(sym::format_macro)
53 } else if let Some(higher::If { then, r#else, .. }) = higher::If::hir(e) {
54 is_format(cx, then) || r#else.is_some_and(|e| is_format(cx, e))
55 } else {
56 match higher::IfLetOrMatch::parse(cx, e) {
57 Some(higher::IfLetOrMatch::Match(_, arms, MatchSource::Normal)) => {
58 arms.iter().any(|arm| is_format(cx, arm.body))
59 },
60 Some(higher::IfLetOrMatch::IfLet(_, _, then, r#else)) => {
61 is_format(cx, then) ||r#else.is_some_and(|e| is_format(cx, e))
62 },
63 _ => false,
64 }
65 }
66 }
67
68 impl<'tcx> LateLintPass<'tcx> for FormatPushString {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)69 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
70 let arg = match expr.kind {
71 ExprKind::MethodCall(_, _, [arg], _) => {
72 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) &&
73 match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
74 arg
75 } else {
76 return;
77 }
78 }
79 ExprKind::AssignOp(op, left, arg)
80 if op.node == BinOpKind::Add && is_string(cx, left) => {
81 arg
82 },
83 _ => return,
84 };
85 if is_format(cx, arg) {
86 span_lint_and_help(
87 cx,
88 FORMAT_PUSH_STRING,
89 expr.span,
90 "`format!(..)` appended to existing `String`",
91 None,
92 "consider using `write!` to avoid the extra allocation",
93 );
94 }
95 }
96 }
97