]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/format.rs
bump version to 1.80.1+dfsg1-1~bpo12+pve1
[rustc.git] / src / tools / clippy / clippy_lints / src / format.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::macros::{find_format_arg_expr, find_format_args, root_macro_call_first_node};
3 use clippy_utils::source::{snippet_opt, snippet_with_context};
4 use clippy_utils::sugg::Sugg;
5 use rustc_ast::{FormatArgsPiece, FormatOptions, FormatTrait};
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty;
10 use rustc_session::declare_lint_pass;
11 use rustc_span::{sym, Span};
12
13 declare_clippy_lint! {
14 /// ### What it does
15 /// Checks for the use of `format!("string literal with no
16 /// argument")` and `format!("{}", foo)` where `foo` is a string.
17 ///
18 /// ### Why is this bad?
19 /// There is no point of doing that. `format!("foo")` can
20 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
21 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
22 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
23 /// if `foo: &str`.
24 ///
25 /// ### Examples
26 /// ```no_run
27 /// let foo = "foo";
28 /// format!("{}", foo);
29 /// ```
30 ///
31 /// Use instead:
32 /// ```no_run
33 /// let foo = "foo";
34 /// foo.to_owned();
35 /// ```
36 #[clippy::version = "pre 1.29.0"]
37 pub USELESS_FORMAT,
38 complexity,
39 "useless use of `format!`"
40 }
41
42 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
43
44 impl<'tcx> LateLintPass<'tcx> for UselessFormat {
45 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
46 if let Some(macro_call) = root_macro_call_first_node(cx, expr)
47 && cx.tcx.is_diagnostic_item(sym::format_macro, macro_call.def_id)
48 && let Some(format_args) = find_format_args(cx, expr, macro_call.expn)
49 {
50 let mut applicability = Applicability::MachineApplicable;
51 let call_site = macro_call.span;
52
53 match (format_args.arguments.all_args(), &format_args.template[..]) {
54 ([], []) => span_useless_format_empty(cx, call_site, "String::new()".to_owned(), applicability),
55 ([], [_]) => {
56 // Simulate macro expansion, converting {{ and }} to { and }.
57 let Some(snippet) = snippet_opt(cx, format_args.span) else {
58 return;
59 };
60 let s_expand = snippet.replace("{{", "{").replace("}}", "}");
61 let sugg = format!("{s_expand}.to_string()");
62 span_useless_format(cx, call_site, sugg, applicability);
63 },
64 ([arg], [piece]) => {
65 if let Ok(value) = find_format_arg_expr(expr, arg)
66 && let FormatArgsPiece::Placeholder(placeholder) = piece
67 && placeholder.format_trait == FormatTrait::Display
68 && placeholder.format_options == FormatOptions::default()
69 && match cx.typeck_results().expr_ty(value).peel_refs().kind() {
70 ty::Adt(adt, _) => Some(adt.did()) == cx.tcx.lang_items().string(),
71 ty::Str => true,
72 _ => false,
73 }
74 {
75 let is_new_string = match value.kind {
76 ExprKind::Binary(..) => true,
77 ExprKind::MethodCall(path, ..) => path.ident.name == sym::to_string,
78 _ => false,
79 };
80 let sugg = if is_new_string {
81 snippet_with_context(cx, value.span, call_site.ctxt(), "..", &mut applicability)
82 .0
83 .into_owned()
84 } else {
85 let sugg = Sugg::hir_with_context(cx, value, call_site.ctxt(), "<arg>", &mut applicability);
86 format!("{}.to_string()", sugg.maybe_par())
87 };
88 span_useless_format(cx, call_site, sugg, applicability);
89 }
90 },
91 _ => {},
92 }
93 }
94 }
95 }
96
97 fn span_useless_format_empty(cx: &LateContext<'_>, span: Span, sugg: String, applicability: Applicability) {
98 span_lint_and_sugg(
99 cx,
100 USELESS_FORMAT,
101 span,
102 "useless use of `format!`",
103 "consider using `String::new()`",
104 sugg,
105 applicability,
106 );
107 }
108
109 fn span_useless_format(cx: &LateContext<'_>, span: Span, sugg: String, applicability: Applicability) {
110 span_lint_and_sugg(
111 cx,
112 USELESS_FORMAT,
113 span,
114 "useless use of `format!`",
115 "consider using `.to_string()`",
116 sugg,
117 applicability,
118 );
119 }