]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format_args.rs
Merge commit 'ac0e10aa68325235069a842f47499852b2dee79e' 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::macros::FormatParamKind::{Implicit, Named, Numbered, Starred};
3 use clippy_utils::macros::{is_format_macro, FormatArgsExpn, FormatParam, FormatParamUsage};
4 use clippy_utils::source::snippet_opt;
5 use clippy_utils::ty::implements_trait;
6 use clippy_utils::{is_diag_trait_item, meets_msrv, msrvs};
7 use if_chain::if_chain;
8 use itertools::Itertools;
9 use rustc_errors::Applicability;
10 use rustc_hir::{Expr, ExprKind, HirId, QPath};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
13 use rustc_middle::ty::Ty;
14 use rustc_semver::RustcVersion;
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// Detects `format!` within the arguments of another macro that does
21     /// formatting such as `format!` itself, `write!` or `println!`. Suggests
22     /// inlining the `format!` call.
23     ///
24     /// ### Why is this bad?
25     /// The recommended code is both shorter and avoids a temporary allocation.
26     ///
27     /// ### Example
28     /// ```rust
29     /// # use std::panic::Location;
30     /// println!("error: {}", format!("something failed at {}", Location::caller()));
31     /// ```
32     /// Use instead:
33     /// ```rust
34     /// # use std::panic::Location;
35     /// println!("error: something failed at {}", Location::caller());
36     /// ```
37     #[clippy::version = "1.58.0"]
38     pub FORMAT_IN_FORMAT_ARGS,
39     perf,
40     "`format!` used in a macro that does formatting"
41 }
42
43 declare_clippy_lint! {
44     /// ### What it does
45     /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
46     /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
47     /// in a macro that does formatting.
48     ///
49     /// ### Why is this bad?
50     /// Since the type implements `Display`, the use of `to_string` is
51     /// unnecessary.
52     ///
53     /// ### Example
54     /// ```rust
55     /// # use std::panic::Location;
56     /// println!("error: something failed at {}", Location::caller().to_string());
57     /// ```
58     /// Use instead:
59     /// ```rust
60     /// # use std::panic::Location;
61     /// println!("error: something failed at {}", Location::caller());
62     /// ```
63     #[clippy::version = "1.58.0"]
64     pub TO_STRING_IN_FORMAT_ARGS,
65     perf,
66     "`to_string` applied to a type that implements `Display` in format args"
67 }
68
69 declare_clippy_lint! {
70     /// ### What it does
71     /// Detect when a variable is not inlined in a format string,
72     /// and suggests to inline it.
73     ///
74     /// ### Why is this bad?
75     /// Non-inlined code is slightly more difficult to read and understand,
76     /// as it requires arguments to be matched against the format string.
77     /// The inlined syntax, where allowed, is simpler.
78     ///
79     /// ### Example
80     /// ```rust
81     /// # let var = 42;
82     /// # let width = 1;
83     /// # let prec = 2;
84     /// format!("{}", var);
85     /// format!("{v:?}", v = var);
86     /// format!("{0} {0}", var);
87     /// format!("{0:1$}", var, width);
88     /// format!("{:.*}", prec, var);
89     /// ```
90     /// Use instead:
91     /// ```rust
92     /// # let var = 42;
93     /// # let width = 1;
94     /// # let prec = 2;
95     /// format!("{var}");
96     /// format!("{var:?}");
97     /// format!("{var} {var}");
98     /// format!("{var:width$}");
99     /// format!("{var:.prec$}");
100     /// ```
101     ///
102     /// ### Known Problems
103     ///
104     /// There may be a false positive if the format string is expanded from certain proc macros:
105     ///
106     /// ```ignore
107     /// println!(indoc!("{}"), var);
108     /// ```
109     ///
110     /// If a format string contains a numbered argument that cannot be inlined
111     /// nothing will be suggested, e.g. `println!("{0}={1}", var, 1+2)`.
112     #[clippy::version = "1.65.0"]
113     pub UNINLINED_FORMAT_ARGS,
114     pedantic,
115     "using non-inlined variables in `format!` calls"
116 }
117
118 impl_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, UNINLINED_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
119
120 pub struct FormatArgs {
121     msrv: Option<RustcVersion>,
122 }
123
124 impl FormatArgs {
125     #[must_use]
126     pub fn new(msrv: Option<RustcVersion>) -> Self {
127         Self { msrv }
128     }
129 }
130
131 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
132     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
133         if_chain! {
134             if let Some(format_args) = FormatArgsExpn::parse(cx, expr);
135             let expr_expn_data = expr.span.ctxt().outer_expn_data();
136             let outermost_expn_data = outermost_expn_data(expr_expn_data);
137             if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
138             if is_format_macro(cx, macro_def_id);
139             if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
140             then {
141                 for arg in &format_args.args {
142                     if !arg.format.is_default() {
143                         continue;
144                     }
145                     if is_aliased(&format_args, arg.param.value.hir_id) {
146                         continue;
147                     }
148                     check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.param.value);
149                     check_to_string_in_format_args(cx, name, arg.param.value);
150                 }
151                 if meets_msrv(self.msrv, msrvs::FORMAT_ARGS_CAPTURE) {
152                     check_uninlined_args(cx, &format_args, outermost_expn_data.call_site);
153                 }
154             }
155         }
156     }
157
158     extract_msrv_attr!(LateContext);
159 }
160
161 fn check_uninlined_args(cx: &LateContext<'_>, args: &FormatArgsExpn<'_>, call_site: Span) {
162     if args.format_string.span.from_expansion() {
163         return;
164     }
165
166     let mut fixes = Vec::new();
167     // If any of the arguments are referenced by an index number,
168     // and that argument is not a simple variable and cannot be inlined,
169     // we cannot remove any other arguments in the format string,
170     // because the index numbers might be wrong after inlining.
171     // Example of an un-inlinable format:  print!("{}{1}", foo, 2)
172     if !args.params().all(|p| check_one_arg(args, &p, &mut fixes)) || fixes.is_empty() {
173         return;
174     }
175
176     // FIXME: Properly ignore a rare case where the format string is wrapped in a macro.
177     // Example:  `format!(indoc!("{}"), foo);`
178     // If inlined, they will cause a compilation error:
179     //     > to avoid ambiguity, `format_args!` cannot capture variables
180     //     > when the format string is expanded from a macro
181     // @Alexendoo explanation:
182     //     > indoc! is a proc macro that is producing a string literal with its span
183     //     > set to its input it's not marked as from expansion, and since it's compatible
184     //     > tokenization wise clippy_utils::is_from_proc_macro wouldn't catch it either
185     // This might be a relatively expensive test, so do it only we are ready to replace.
186     // See more examples in tests/ui/uninlined_format_args.rs
187
188     span_lint_and_then(
189         cx,
190         UNINLINED_FORMAT_ARGS,
191         call_site,
192         "variables can be used directly in the `format!` string",
193         |diag| {
194             diag.multipart_suggestion("change this to", fixes, Applicability::MachineApplicable);
195         },
196     );
197 }
198
199 fn check_one_arg(args: &FormatArgsExpn<'_>, param: &FormatParam<'_>, fixes: &mut Vec<(Span, String)>) -> bool {
200     if matches!(param.kind, Implicit | Starred | Named(_) | Numbered)
201         && let ExprKind::Path(QPath::Resolved(None, path)) = param.value.kind
202         && let [segment] = path.segments
203         && let Some(arg_span) = args.value_with_prev_comma_span(param.value.hir_id)
204     {
205         let replacement = match param.usage {
206             FormatParamUsage::Argument => segment.ident.name.to_string(),
207             FormatParamUsage::Width => format!("{}$", segment.ident.name),
208             FormatParamUsage::Precision => format!(".{}$", segment.ident.name),
209         };
210         fixes.push((param.span, replacement));
211         fixes.push((arg_span, String::new()));
212         true  // successful inlining, continue checking
213     } else {
214         // if we can't inline a numbered argument, we can't continue
215         param.kind != Numbered
216     }
217 }
218
219 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
220     if expn_data.call_site.from_expansion() {
221         outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
222     } else {
223         expn_data
224     }
225 }
226
227 fn check_format_in_format_args(
228     cx: &LateContext<'_>,
229     call_site: Span,
230     name: Symbol,
231     arg: &Expr<'_>,
232 ) {
233     let expn_data = arg.span.ctxt().outer_expn_data();
234     if expn_data.call_site.from_expansion() {
235         return;
236     }
237     let Some(mac_id) = expn_data.macro_def_id else { return };
238     if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
239         return;
240     }
241     span_lint_and_then(
242         cx,
243         FORMAT_IN_FORMAT_ARGS,
244         call_site,
245         &format!("`format!` in `{name}!` args"),
246         |diag| {
247             diag.help(&format!(
248                 "combine the `format!(..)` arguments with the outer `{name}!(..)` call"
249             ));
250             diag.help("or consider changing `format!` to `format_args!`");
251         },
252     );
253 }
254
255 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
256     if_chain! {
257         if !value.span.from_expansion();
258         if let ExprKind::MethodCall(_, receiver, [], _) = value.kind;
259         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
260         if is_diag_trait_item(cx, method_def_id, sym::ToString);
261         let receiver_ty = cx.typeck_results().expr_ty(receiver);
262         if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
263         let (n_needed_derefs, target) =
264             count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
265         if implements_trait(cx, target, display_trait_id, &[]);
266         if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
267         if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
268         then {
269             let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
270             if n_needed_derefs == 0 && !needs_ref {
271                 span_lint_and_sugg(
272                     cx,
273                     TO_STRING_IN_FORMAT_ARGS,
274                     value.span.with_lo(receiver.span.hi()),
275                     &format!(
276                         "`to_string` applied to a type that implements `Display` in `{name}!` args"
277                     ),
278                     "remove this",
279                     String::new(),
280                     Applicability::MachineApplicable,
281                 );
282             } else {
283                 span_lint_and_sugg(
284                     cx,
285                     TO_STRING_IN_FORMAT_ARGS,
286                     value.span,
287                     &format!(
288                         "`to_string` applied to a type that implements `Display` in `{name}!` args"
289                     ),
290                     "use this",
291                     format!(
292                         "{}{:*>n_needed_derefs$}{receiver_snippet}",
293                         if needs_ref { "&" } else { "" },
294                         ""
295                     ),
296                     Applicability::MachineApplicable,
297                 );
298             }
299         }
300     }
301 }
302
303 /// Returns true if `hir_id` is referred to by multiple format params
304 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
305     args.params().filter(|param| param.value.hir_id == hir_id).at_most_one().is_err()
306 }
307
308 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
309 where
310     I: Iterator<Item = &'tcx Adjustment<'tcx>>,
311 {
312     let mut n_total = 0;
313     let mut n_needed = 0;
314     loop {
315         if let Some(Adjustment { kind: Adjust::Deref(overloaded_deref), target }) = iter.next() {
316             n_total += 1;
317             if overloaded_deref.is_some() {
318                 n_needed = n_total;
319             }
320             ty = *target;
321         } else {
322             return (n_needed, ty);
323         }
324     }
325 }