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