1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use clippy_utils::{match_def_path, paths, peel_hir_expr_refs};
4 use rustc_hir::{BinOpKind, Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 /// Detects cases where the result of a `format!` call is
12 /// appended to an existing `String`.
14 /// ### Why is this bad?
15 /// Introduces an extra, avoidable heap allocation.
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.
21 /// While using `write!` in the suggested way should never fail, this isn't necessarily clear to the programmer.
25 /// let mut s = String::new();
26 /// s += &format!("0x{:X}", 1024);
27 /// s.push_str(&format!("0x{:X}", 1024));
31 /// use std::fmt::Write as _; // import without risk of name clashing
33 /// let mut s = String::new();
34 /// let _ = write!(s, "0x{:X}", 1024);
36 #[clippy::version = "1.62.0"]
37 pub FORMAT_PUSH_STRING,
39 "`format!(..)` appended to existing `String`"
41 declare_lint_pass!(FormatPushString => [FORMAT_PUSH_STRING]);
43 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
44 is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), sym::String)
46 fn is_format(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
47 if let Some(macro_def_id) = e.span.ctxt().outer_expn_data().macro_def_id {
48 cx.tcx.get_diagnostic_name(macro_def_id) == Some(sym::format_macro)
54 impl<'tcx> LateLintPass<'tcx> for FormatPushString {
55 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
56 let arg = match expr.kind {
57 ExprKind::MethodCall(_, _, [arg], _) => {
58 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) &&
59 match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
65 ExprKind::AssignOp(op, left, arg)
66 if op.node == BinOpKind::Add && is_string(cx, left) => {
71 let (arg, _) = peel_hir_expr_refs(arg);
72 if is_format(cx, arg) {
77 "`format!(..)` appended to existing `String`",
79 "consider using `write!` to avoid the extra allocation",