]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format_args.rs
Rollup merge of #101624 - notriddle:notriddle/search, r=GuillaumeGomez
[rust.git] / src / tools / clippy / 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(
103     cx: &LateContext<'_>,
104     call_site: Span,
105     name: Symbol,
106     arg: &Expr<'_>,
107 ) {
108     let expn_data = arg.span.ctxt().outer_expn_data();
109     if expn_data.call_site.from_expansion() {
110         return;
111     }
112     let Some(mac_id) = expn_data.macro_def_id else { return };
113     if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
114         return;
115     }
116     span_lint_and_then(
117         cx,
118         FORMAT_IN_FORMAT_ARGS,
119         call_site,
120         &format!("`format!` in `{}!` args", name),
121         |diag| {
122             diag.help(&format!(
123                 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
124                 name
125             ));
126             diag.help("or consider changing `format!` to `format_args!`");
127         },
128     );
129 }
130
131 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
132     if_chain! {
133         if !value.span.from_expansion();
134         if let ExprKind::MethodCall(_, receiver, [], _) = value.kind;
135         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
136         if is_diag_trait_item(cx, method_def_id, sym::ToString);
137         let receiver_ty = cx.typeck_results().expr_ty(receiver);
138         if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
139         let (n_needed_derefs, target) =
140             count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
141         if implements_trait(cx, target, display_trait_id, &[]);
142         if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
143         if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
144         then {
145             let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
146             if n_needed_derefs == 0 && !needs_ref {
147                 span_lint_and_sugg(
148                     cx,
149                     TO_STRING_IN_FORMAT_ARGS,
150                     value.span.with_lo(receiver.span.hi()),
151                     &format!(
152                         "`to_string` applied to a type that implements `Display` in `{}!` args",
153                         name
154                     ),
155                     "remove this",
156                     String::new(),
157                     Applicability::MachineApplicable,
158                 );
159             } else {
160                 span_lint_and_sugg(
161                     cx,
162                     TO_STRING_IN_FORMAT_ARGS,
163                     value.span,
164                     &format!(
165                         "`to_string` applied to a type that implements `Display` in `{}!` args",
166                         name
167                     ),
168                     "use this",
169                     format!(
170                         "{}{:*>width$}{}",
171                         if needs_ref { "&" } else { "" },
172                         "",
173                         receiver_snippet,
174                         width = n_needed_derefs
175                     ),
176                     Applicability::MachineApplicable,
177                 );
178             }
179         }
180     }
181 }
182
183 // Returns true if `hir_id` is referred to by multiple format params
184 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
185     args.params().filter(|param| param.value.hir_id == hir_id).at_most_one().is_err()
186 }
187
188 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
189 where
190     I: Iterator<Item = &'tcx Adjustment<'tcx>>,
191 {
192     let mut n_total = 0;
193     let mut n_needed = 0;
194     loop {
195         if let Some(Adjustment { kind: Adjust::Deref(overloaded_deref), target }) = iter.next() {
196             n_total += 1;
197             if overloaded_deref.is_some() {
198                 n_needed = n_total;
199             }
200             ty = *target;
201         } else {
202             return (n_needed, ty);
203         }
204     }
205 }