]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format_args.rs
Rollup merge of #101236 - thomcc:winfs-nozero, r=ChrisDenton
[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(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 needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
141             if n_needed_derefs == 0 && !needs_ref {
142                 span_lint_and_sugg(
143                     cx,
144                     TO_STRING_IN_FORMAT_ARGS,
145                     value.span.with_lo(receiver.span.hi()),
146                     &format!(
147                         "`to_string` applied to a type that implements `Display` in `{}!` args",
148                         name
149                     ),
150                     "remove this",
151                     String::new(),
152                     Applicability::MachineApplicable,
153                 );
154             } else {
155                 span_lint_and_sugg(
156                     cx,
157                     TO_STRING_IN_FORMAT_ARGS,
158                     value.span,
159                     &format!(
160                         "`to_string` applied to a type that implements `Display` in `{}!` args",
161                         name
162                     ),
163                     "use this",
164                     format!(
165                         "{}{:*>width$}{}",
166                         if needs_ref { "&" } else { "" },
167                         "",
168                         receiver_snippet,
169                         width = n_needed_derefs
170                     ),
171                     Applicability::MachineApplicable,
172                 );
173             }
174         }
175     }
176 }
177
178 // Returns true if `hir_id` is referred to by multiple format params
179 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
180     args.params()
181         .filter(|param| param.value.hir_id == hir_id)
182         .at_most_one()
183         .is_err()
184 }
185
186 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
187 where
188     I: Iterator<Item = &'tcx Adjustment<'tcx>>,
189 {
190     let mut n_total = 0;
191     let mut n_needed = 0;
192     loop {
193         if let Some(Adjustment {
194             kind: Adjust::Deref(overloaded_deref),
195             target,
196         }) = iter.next()
197         {
198             n_total += 1;
199             if overloaded_deref.is_some() {
200                 n_needed = n_total;
201             }
202             ty = *target;
203         } else {
204             return (n_needed, ty);
205         }
206     }
207 }