]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format_args.rs
473c9a8675f13fb7dadd93858b1bec62afb98b6e
[rust.git] / clippy_lints / src / format_args.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::is_diag_trait_item;
3 use clippy_utils::macros::{is_format_macro, FormatArgsExpn};
4 use clippy_utils::source::snippet_opt;
5 use clippy_utils::ty::implements_trait;
6 use if_chain::if_chain;
7 use itertools::Itertools;
8 use rustc_errors::Applicability;
9 use rustc_hir::{Expr, ExprKind, HirId};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
12 use rustc_middle::ty::Ty;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Detects `format!` within the arguments of another macro that does
19     /// formatting such as `format!` itself, `write!` or `println!`. Suggests
20     /// inlining the `format!` call.
21     ///
22     /// ### Why is this bad?
23     /// The recommended code is both shorter and avoids a temporary allocation.
24     ///
25     /// ### Example
26     /// ```rust
27     /// # use std::panic::Location;
28     /// println!("error: {}", format!("something failed at {}", Location::caller()));
29     /// ```
30     /// Use instead:
31     /// ```rust
32     /// # use std::panic::Location;
33     /// println!("error: something failed at {}", Location::caller());
34     /// ```
35     #[clippy::version = "1.58.0"]
36     pub FORMAT_IN_FORMAT_ARGS,
37     perf,
38     "`format!` used in a macro that does formatting"
39 }
40
41 declare_clippy_lint! {
42     /// ### What it does
43     /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
44     /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
45     /// in a macro that does formatting.
46     ///
47     /// ### Why is this bad?
48     /// Since the type implements `Display`, the use of `to_string` is
49     /// unnecessary.
50     ///
51     /// ### Example
52     /// ```rust
53     /// # use std::panic::Location;
54     /// println!("error: something failed at {}", Location::caller().to_string());
55     /// ```
56     /// Use instead:
57     /// ```rust
58     /// # use std::panic::Location;
59     /// println!("error: something failed at {}", Location::caller());
60     /// ```
61     #[clippy::version = "1.58.0"]
62     pub TO_STRING_IN_FORMAT_ARGS,
63     perf,
64     "`to_string` applied to a type that implements `Display` in format args"
65 }
66
67 declare_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
68
69 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
70     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
71         if_chain! {
72             if let Some(format_args) = FormatArgsExpn::parse(cx, expr);
73             let expr_expn_data = expr.span.ctxt().outer_expn_data();
74             let outermost_expn_data = outermost_expn_data(expr_expn_data);
75             if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
76             if is_format_macro(cx, macro_def_id);
77             if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
78             then {
79                 for arg in &format_args.args {
80                     if arg.format.has_string_formatting() {
81                         continue;
82                     }
83                     if is_aliased(&format_args, arg.param.value.hir_id) {
84                         continue;
85                     }
86                     check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.param.value);
87                     check_to_string_in_format_args(cx, name, arg.param.value);
88                 }
89             }
90         }
91     }
92 }
93
94 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
95     if expn_data.call_site.from_expansion() {
96         outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
97     } else {
98         expn_data
99     }
100 }
101
102 fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &Expr<'_>) {
103     let expn_data = arg.span.ctxt().outer_expn_data();
104     if expn_data.call_site.from_expansion() {
105         return;
106     }
107     let Some(mac_id) = expn_data.macro_def_id else { return };
108     if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
109         return;
110     }
111     span_lint_and_then(
112         cx,
113         FORMAT_IN_FORMAT_ARGS,
114         call_site,
115         &format!("`format!` in `{}!` args", name),
116         |diag| {
117             diag.help(&format!(
118                 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
119                 name
120             ));
121             diag.help("or consider changing `format!` to `format_args!`");
122         },
123     );
124 }
125
126 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
127     if_chain! {
128         if !value.span.from_expansion();
129         if let ExprKind::MethodCall(_, [receiver], _) = value.kind;
130         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
131         if is_diag_trait_item(cx, method_def_id, sym::ToString);
132         let receiver_ty = cx.typeck_results().expr_ty(receiver);
133         if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
134         let (n_needed_derefs, target) =
135             count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
136         if implements_trait(cx, target, display_trait_id, &[]);
137         if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
138         if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
139         then {
140             let needed_ref = if implements_trait(cx, receiver_ty, sized_trait_id, &[]) {
141                 ""
142             } else {
143                 "&"
144             };
145             if n_needed_derefs == 0 && needed_ref.is_empty() {
146                 span_lint_and_sugg(
147                     cx,
148                     TO_STRING_IN_FORMAT_ARGS,
149                     value.span.with_lo(receiver.span.hi()),
150                     &format!(
151                         "`to_string` applied to a type that implements `Display` in `{}!` args",
152                         name
153                     ),
154                     "remove this",
155                     String::new(),
156                     Applicability::MachineApplicable,
157                 );
158             } else {
159                 span_lint_and_sugg(
160                     cx,
161                     TO_STRING_IN_FORMAT_ARGS,
162                     value.span,
163                     &format!(
164                         "`to_string` applied to a type that implements `Display` in `{}!` args",
165                         name
166                     ),
167                     "use this",
168                     format!(
169                         "{}{:*>width$}{}",
170                         needed_ref,
171                         "",
172                         receiver_snippet,
173                         width = n_needed_derefs
174                     ),
175                     Applicability::MachineApplicable,
176                 );
177             }
178         }
179     }
180 }
181
182 // Returns true if `hir_id` is referred to by multiple format params
183 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
184     args.params()
185         .filter(|param| param.value.hir_id == hir_id)
186         .at_most_one()
187         .is_err()
188 }
189
190 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
191 where
192     I: Iterator<Item = &'tcx Adjustment<'tcx>>,
193 {
194     let mut n_total = 0;
195     let mut n_needed = 0;
196     loop {
197         if let Some(Adjustment {
198             kind: Adjust::Deref(overloaded_deref),
199             target,
200         }) = iter.next()
201         {
202             n_total += 1;
203             if overloaded_deref.is_some() {
204                 n_needed = n_total;
205             }
206             ty = *target;
207         } else {
208             return (n_needed, ty);
209         }
210     }
211 }