]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Move if_then_panic to pedantic
[rust.git] / 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     pub USELESS_FORMAT,
37     complexity,
38     "useless use of `format!`"
39 }
40
41 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
42
43 impl<'tcx> LateLintPass<'tcx> for UselessFormat {
44     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
45         let FormatExpn { call_site, format_args } = match FormatExpn::parse(expr) {
46             Some(e) if !e.call_site.from_expansion() => e,
47             _ => return,
48         };
49
50         let mut applicability = Applicability::MachineApplicable;
51         if format_args.value_args.is_empty() {
52             if format_args.format_string_parts.is_empty() {
53                 span_useless_format_empty(cx, call_site, "String::new()".to_owned(), applicability);
54             } else {
55                 if_chain! {
56                     if let [e] = &*format_args.format_string_parts;
57                     if let ExprKind::Lit(lit) = &e.kind;
58                     if let Some(s_src) = snippet_opt(cx, lit.span);
59                     then {
60                         // Simulate macro expansion, converting {{ and }} to { and }.
61                         let s_expand = s_src.replace("{{", "{").replace("}}", "}");
62                         let sugg = format!("{}.to_string()", s_expand);
63                         span_useless_format(cx, call_site, sugg, applicability);
64                     }
65                 }
66             }
67         } else if let [value] = *format_args.value_args {
68             if_chain! {
69                 if format_args.format_string_symbols == [kw::Empty];
70                 if match cx.typeck_results().expr_ty(value).peel_refs().kind() {
71                     ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(sym::String, adt.did),
72                     ty::Str => true,
73                     _ => false,
74                 };
75                 if let Some(args) = format_args.args();
76                 if args.iter().all(|arg| arg.is_display() && !arg.has_string_formatting());
77                 then {
78                     let is_new_string = match value.kind {
79                         ExprKind::Binary(..) => true,
80                         ExprKind::MethodCall(path, ..) => path.ident.name.as_str() == "to_string",
81                         _ => false,
82                     };
83                     let sugg = if is_new_string {
84                         snippet_with_applicability(cx, value.span, "..", &mut applicability).into_owned()
85                     } else {
86                         let sugg = Sugg::hir_with_applicability(cx, value, "<arg>", &mut applicability);
87                         format!("{}.to_string()", sugg.maybe_par())
88                     };
89                     span_useless_format(cx, call_site, sugg, applicability);
90                 }
91             }
92         };
93     }
94 }
95
96 fn span_useless_format_empty(cx: &LateContext<'_>, span: Span, sugg: String, applicability: Applicability) {
97     span_lint_and_sugg(
98         cx,
99         USELESS_FORMAT,
100         span,
101         "useless use of `format!`",
102         "consider using `String::new()`",
103         sugg,
104         applicability,
105     );
106 }
107
108 fn span_useless_format(cx: &LateContext<'_>, span: Span, sugg: String, applicability: Applicability) {
109     span_lint_and_sugg(
110         cx,
111         USELESS_FORMAT,
112         span,
113         "useless use of `format!`",
114         "consider using `.to_string()`",
115         sugg,
116         applicability,
117     );
118 }