]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Better handle method/function calls
[rust.git] / clippy_lints / src / format.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::macros::{root_macro_call_first_node, FormatArgsExpn};
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     /// let foo = "foo";
29     /// format!("{}", foo);
30     /// ```
31     ///
32     /// Use instead:
33     /// ```rust
34     /// let foo = "foo";
35     /// foo.to_owned();
36     /// ```
37     #[clippy::version = "pre 1.29.0"]
38     pub USELESS_FORMAT,
39     complexity,
40     "useless use of `format!`"
41 }
42
43 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
44
45 impl<'tcx> LateLintPass<'tcx> for UselessFormat {
46     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
47         let (format_args, call_site) = if_chain! {
48             if let Some(macro_call) = root_macro_call_first_node(cx, expr);
49             if cx.tcx.is_diagnostic_item(sym::format_macro, macro_call.def_id);
50             if let Some(format_args) = FormatArgsExpn::find_nested(cx, expr, macro_call.expn);
51             then {
52                 (format_args, macro_call.span)
53             } else {
54                 return
55             }
56         };
57
58         let mut applicability = Applicability::MachineApplicable;
59         if format_args.value_args.is_empty() {
60             match *format_args.format_string_parts {
61                 [] => span_useless_format_empty(cx, call_site, "String::new()".to_owned(), applicability),
62                 [_] => {
63                     if let Some(s_src) = snippet_opt(cx, format_args.format_string_span) {
64                         // Simulate macro expansion, converting {{ and }} to { and }.
65                         let s_expand = s_src.replace("{{", "{").replace("}}", "}");
66                         let sugg = format!("{}.to_string()", s_expand);
67                         span_useless_format(cx, call_site, sugg, applicability);
68                     }
69                 },
70                 [..] => {},
71             }
72         } else if let [value] = *format_args.value_args {
73             if_chain! {
74                 if format_args.format_string_parts == [kw::Empty];
75                 if match cx.typeck_results().expr_ty(value).peel_refs().kind() {
76                     ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(sym::String, adt.did()),
77                     ty::Str => true,
78                     _ => false,
79                 };
80                 if let Some(args) = format_args.args();
81                 if args.iter().all(|arg| arg.format_trait == sym::Display && !arg.has_string_formatting());
82                 then {
83                     let is_new_string = match value.kind {
84                         ExprKind::Binary(..) => true,
85                         ExprKind::MethodCall(path, ..) => path.ident.name == sym::to_string,
86                         _ => false,
87                     };
88                     let sugg = if is_new_string {
89                         snippet_with_applicability(cx, value.span, "..", &mut applicability).into_owned()
90                     } else {
91                         let sugg = Sugg::hir_with_applicability(cx, value, "<arg>", &mut applicability);
92                         format!("{}.to_string()", sugg.maybe_par())
93                     };
94                     span_useless_format(cx, call_site, sugg, applicability);
95                 }
96             }
97         };
98     }
99 }
100
101 fn span_useless_format_empty(cx: &LateContext<'_>, span: Span, sugg: String, applicability: Applicability) {
102     span_lint_and_sugg(
103         cx,
104         USELESS_FORMAT,
105         span,
106         "useless use of `format!`",
107         "consider using `String::new()`",
108         sugg,
109         applicability,
110     );
111 }
112
113 fn span_useless_format(cx: &LateContext<'_>, span: Span, sugg: String, applicability: Applicability) {
114     span_lint_and_sugg(
115         cx,
116         USELESS_FORMAT,
117         span,
118         "useless use of `format!`",
119         "consider using `.to_string()`",
120         sugg,
121         applicability,
122     );
123 }