]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format_push_string.rs
Rollup merge of #103443 - mucinoab:recover-colon-as-path-separetor, r=compiler-errors
[rust.git] / src / tools / clippy / clippy_lints / src / format_push_string.rs
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};
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
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)
45 }
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)
49     } else {
50         false
51     }
52 }
53
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) {
60                     arg
61                 } else {
62                     return;
63                 }
64             }
65             ExprKind::AssignOp(op, left, arg)
66             if op.node == BinOpKind::Add && is_string(cx, left) => {
67                 arg
68             },
69             _ => return,
70         };
71         let (arg, _) = peel_hir_expr_refs(arg);
72         if is_format(cx, arg) {
73             span_lint_and_help(
74                 cx,
75                 FORMAT_PUSH_STRING,
76                 expr.span,
77                 "`format!(..)` appended to existing `String`",
78                 None,
79                 "consider using `write!` to avoid the extra allocation",
80             );
81         }
82     }
83 }