]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format.rs
Auto merge of #81156 - DrMeepster:read_buf, r=joshtriplett
[rust.git] / src / tools / clippy / clippy_lints / src / format.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher::FormatExpn;
3 use clippy_utils::source::{snippet_opt, snippet_with_applicability};
4 use clippy_utils::sugg::Sugg;
5 use if_chain::if_chain;
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, declare_tool_lint};
11 use rustc_span::symbol::kw;
12 use rustc_span::{sym, Span};
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for the use of `format!("string literal with no
17     /// argument")` and `format!("{}", foo)` where `foo` is a string.
18     ///
19     /// ### Why is this bad?
20     /// There is no point of doing that. `format!("foo")` can
21     /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
22     /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
23     /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
24     /// if `foo: &str`.
25     ///
26     /// ### Examples
27     /// ```rust
28     ///
29     /// // Bad
30     /// let foo = "foo";
31     /// format!("{}", foo);
32     ///
33     /// // Good
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         let FormatExpn { call_site, format_args } = match FormatExpn::parse(expr) {
47             Some(e) if !e.call_site.from_expansion() => e,
48             _ => return,
49         };
50
51         let mut applicability = Applicability::MachineApplicable;
52         if format_args.value_args.is_empty() {
53             if format_args.format_string_parts.is_empty() {
54                 span_useless_format_empty(cx, call_site, "String::new()".to_owned(), applicability);
55             } else {
56                 if_chain! {
57                     if let [e] = &*format_args.format_string_parts;
58                     if let ExprKind::Lit(lit) = &e.kind;
59                     if let Some(s_src) = snippet_opt(cx, lit.span);
60                     then {
61                         // Simulate macro expansion, converting {{ and }} to { and }.
62                         let s_expand = s_src.replace("{{", "{").replace("}}", "}");
63                         let sugg = format!("{}.to_string()", s_expand);
64                         span_useless_format(cx, call_site, sugg, applicability);
65                     }
66                 }
67             }
68         } else if let [value] = *format_args.value_args {
69             if_chain! {
70                 if format_args.format_string_symbols == [kw::Empty];
71                 if match cx.typeck_results().expr_ty(value).peel_refs().kind() {
72                     ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(sym::String, adt.did),
73                     ty::Str => true,
74                     _ => false,
75                 };
76                 if let Some(args) = format_args.args();
77                 if args.iter().all(|arg| arg.is_display() && !arg.has_string_formatting());
78                 then {
79                     let is_new_string = match value.kind {
80                         ExprKind::Binary(..) => true,
81                         ExprKind::MethodCall(path, ..) => path.ident.name.as_str() == "to_string",
82                         _ => false,
83                     };
84                     let sugg = if is_new_string {
85                         snippet_with_applicability(cx, value.span, "..", &mut applicability).into_owned()
86                     } else {
87                         let sugg = Sugg::hir_with_applicability(cx, value, "<arg>", &mut applicability);
88                         format!("{}.to_string()", sugg.maybe_par())
89                     };
90                     span_useless_format(cx, call_site, sugg, applicability);
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 }