]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format_args.rs
Auto merge of #105701 - RedDocMD:bug-105634, r=cjgillot
[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::FormatParamKind::{Implicit, Named, NamedInline, Numbered, Starred};
4 use clippy_utils::macros::{
5     is_assert_macro, is_format_macro, is_panic, root_macro_call, Count, FormatArg, FormatArgsExpn, FormatParam,
6     FormatParamUsage,
7 };
8 use clippy_utils::msrvs::{self, Msrv};
9 use clippy_utils::source::snippet_opt;
10 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
11 use if_chain::if_chain;
12 use itertools::Itertools;
13 use rustc_errors::{
14     Applicability,
15     SuggestionStyle::{CompletelyHidden, ShowCode},
16 };
17 use rustc_hir::{Expr, ExprKind, HirId, QPath};
18 use rustc_lint::{LateContext, LateLintPass, LintContext};
19 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
20 use rustc_middle::ty::Ty;
21 use rustc_session::{declare_tool_lint, impl_lint_pass};
22 use rustc_span::def_id::DefId;
23 use rustc_span::edition::Edition::Edition2021;
24 use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
25
26 declare_clippy_lint! {
27     /// ### What it does
28     /// Detects `format!` within the arguments of another macro that does
29     /// formatting such as `format!` itself, `write!` or `println!`. Suggests
30     /// inlining the `format!` call.
31     ///
32     /// ### Why is this bad?
33     /// The recommended code is both shorter and avoids a temporary allocation.
34     ///
35     /// ### Example
36     /// ```rust
37     /// # use std::panic::Location;
38     /// println!("error: {}", format!("something failed at {}", Location::caller()));
39     /// ```
40     /// Use instead:
41     /// ```rust
42     /// # use std::panic::Location;
43     /// println!("error: something failed at {}", Location::caller());
44     /// ```
45     #[clippy::version = "1.58.0"]
46     pub FORMAT_IN_FORMAT_ARGS,
47     perf,
48     "`format!` used in a macro that does formatting"
49 }
50
51 declare_clippy_lint! {
52     /// ### What it does
53     /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
54     /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
55     /// in a macro that does formatting.
56     ///
57     /// ### Why is this bad?
58     /// Since the type implements `Display`, the use of `to_string` is
59     /// unnecessary.
60     ///
61     /// ### Example
62     /// ```rust
63     /// # use std::panic::Location;
64     /// println!("error: something failed at {}", Location::caller().to_string());
65     /// ```
66     /// Use instead:
67     /// ```rust
68     /// # use std::panic::Location;
69     /// println!("error: something failed at {}", Location::caller());
70     /// ```
71     #[clippy::version = "1.58.0"]
72     pub TO_STRING_IN_FORMAT_ARGS,
73     perf,
74     "`to_string` applied to a type that implements `Display` in format args"
75 }
76
77 declare_clippy_lint! {
78     /// ### What it does
79     /// Detect when a variable is not inlined in a format string,
80     /// and suggests to inline it.
81     ///
82     /// ### Why is this bad?
83     /// Non-inlined code is slightly more difficult to read and understand,
84     /// as it requires arguments to be matched against the format string.
85     /// The inlined syntax, where allowed, is simpler.
86     ///
87     /// ### Example
88     /// ```rust
89     /// # let var = 42;
90     /// # let width = 1;
91     /// # let prec = 2;
92     /// format!("{}", var);
93     /// format!("{v:?}", v = var);
94     /// format!("{0} {0}", var);
95     /// format!("{0:1$}", var, width);
96     /// format!("{:.*}", prec, var);
97     /// ```
98     /// Use instead:
99     /// ```rust
100     /// # let var = 42;
101     /// # let width = 1;
102     /// # let prec = 2;
103     /// format!("{var}");
104     /// format!("{var:?}");
105     /// format!("{var} {var}");
106     /// format!("{var:width$}");
107     /// format!("{var:.prec$}");
108     /// ```
109     ///
110     /// If allow-mixed-uninlined-format-args is set to false in clippy.toml,
111     /// the following code will also trigger the lint:
112     /// ```rust
113     /// # let var = 42;
114     /// format!("{} {}", var, 1+2);
115     /// ```
116     /// Use instead:
117     /// ```rust
118     /// # let var = 42;
119     /// format!("{var} {}", 1+2);
120     /// ```
121     ///
122     /// ### Known Problems
123     ///
124     /// If a format string contains a numbered argument that cannot be inlined
125     /// nothing will be suggested, e.g. `println!("{0}={1}", var, 1+2)`.
126     #[clippy::version = "1.66.0"]
127     pub UNINLINED_FORMAT_ARGS,
128     style,
129     "using non-inlined variables in `format!` calls"
130 }
131
132 declare_clippy_lint! {
133     /// ### What it does
134     /// Detects [formatting parameters] that have no effect on the output of
135     /// `format!()`, `println!()` or similar macros.
136     ///
137     /// ### Why is this bad?
138     /// Shorter format specifiers are easier to read, it may also indicate that
139     /// an expected formatting operation such as adding padding isn't happening.
140     ///
141     /// ### Example
142     /// ```rust
143     /// println!("{:.}", 1.0);
144     ///
145     /// println!("not padded: {:5}", format_args!("..."));
146     /// ```
147     /// Use instead:
148     /// ```rust
149     /// println!("{}", 1.0);
150     ///
151     /// println!("not padded: {}", format_args!("..."));
152     /// // OR
153     /// println!("padded: {:5}", format!("..."));
154     /// ```
155     ///
156     /// [formatting parameters]: https://doc.rust-lang.org/std/fmt/index.html#formatting-parameters
157     #[clippy::version = "1.66.0"]
158     pub UNUSED_FORMAT_SPECS,
159     complexity,
160     "use of a format specifier that has no effect"
161 }
162
163 impl_lint_pass!(FormatArgs => [
164     FORMAT_IN_FORMAT_ARGS,
165     TO_STRING_IN_FORMAT_ARGS,
166     UNINLINED_FORMAT_ARGS,
167     UNUSED_FORMAT_SPECS,
168 ]);
169
170 pub struct FormatArgs {
171     msrv: Msrv,
172     ignore_mixed: bool,
173 }
174
175 impl FormatArgs {
176     #[must_use]
177     pub fn new(msrv: Msrv, allow_mixed_uninlined_format_args: bool) -> Self {
178         Self {
179             msrv,
180             ignore_mixed: allow_mixed_uninlined_format_args,
181         }
182     }
183 }
184
185 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
186     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
187         if let Some(format_args) = FormatArgsExpn::parse(cx, expr)
188             && let expr_expn_data = expr.span.ctxt().outer_expn_data()
189             && let outermost_expn_data = outermost_expn_data(expr_expn_data)
190             && let Some(macro_def_id) = outermost_expn_data.macro_def_id
191             && is_format_macro(cx, macro_def_id)
192             && let ExpnKind::Macro(_, name) = outermost_expn_data.kind
193         {
194             for arg in &format_args.args {
195                 check_unused_format_specifier(cx, arg);
196                 if !arg.format.is_default() {
197                     continue;
198                 }
199                 if is_aliased(&format_args, arg.param.value.hir_id) {
200                     continue;
201                 }
202                 check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.param.value);
203                 check_to_string_in_format_args(cx, name, arg.param.value);
204             }
205             if self.msrv.meets(msrvs::FORMAT_ARGS_CAPTURE) {
206                 check_uninlined_args(cx, &format_args, outermost_expn_data.call_site, macro_def_id, self.ignore_mixed);
207             }
208         }
209     }
210
211     extract_msrv_attr!(LateContext);
212 }
213
214 fn check_unused_format_specifier(cx: &LateContext<'_>, arg: &FormatArg<'_>) {
215     let param_ty = cx.typeck_results().expr_ty(arg.param.value).peel_refs();
216
217     if let Count::Implied(Some(mut span)) = arg.format.precision
218         && !span.is_empty()
219     {
220         span_lint_and_then(
221             cx,
222             UNUSED_FORMAT_SPECS,
223             span,
224             "empty precision specifier has no effect",
225             |diag| {
226                 if param_ty.is_floating_point() {
227                     diag.note("a precision specifier is not required to format floats");
228                 }
229
230                 if arg.format.is_default() {
231                     // If there's no other specifiers remove the `:` too
232                     span = arg.format_span();
233                 }
234
235                 diag.span_suggestion_verbose(span, "remove the `.`", "", Applicability::MachineApplicable);
236             },
237         );
238     }
239
240     if is_type_diagnostic_item(cx, param_ty, sym::Arguments) && !arg.format.is_default_for_trait() {
241         span_lint_and_then(
242             cx,
243             UNUSED_FORMAT_SPECS,
244             arg.span,
245             "format specifiers have no effect on `format_args!()`",
246             |diag| {
247                 let mut suggest_format = |spec, span| {
248                     let message = format!("for the {spec} to apply consider using `format!()`");
249
250                     if let Some(mac_call) = root_macro_call(arg.param.value.span)
251                         && cx.tcx.is_diagnostic_item(sym::format_args_macro, mac_call.def_id)
252                         && arg.span.eq_ctxt(mac_call.span)
253                     {
254                         diag.span_suggestion(
255                             cx.sess().source_map().span_until_char(mac_call.span, '!'),
256                             message,
257                             "format",
258                             Applicability::MaybeIncorrect,
259                         );
260                     } else if let Some(span) = span {
261                         diag.span_help(span, message);
262                     }
263                 };
264
265                 if !arg.format.width.is_implied() {
266                     suggest_format("width", arg.format.width.span());
267                 }
268
269                 if !arg.format.precision.is_implied() {
270                     suggest_format("precision", arg.format.precision.span());
271                 }
272
273                 diag.span_suggestion_verbose(
274                     arg.format_span(),
275                     "if the current behavior is intentional, remove the format specifiers",
276                     "",
277                     Applicability::MaybeIncorrect,
278                 );
279             },
280         );
281     }
282 }
283
284 fn check_uninlined_args(
285     cx: &LateContext<'_>,
286     args: &FormatArgsExpn<'_>,
287     call_site: Span,
288     def_id: DefId,
289     ignore_mixed: bool,
290 ) {
291     if args.format_string.span.from_expansion() {
292         return;
293     }
294     if call_site.edition() < Edition2021 && (is_panic(cx, def_id) || is_assert_macro(cx, def_id)) {
295         // panic!, assert!, and debug_assert! before 2021 edition considers a single string argument as
296         // non-format
297         return;
298     }
299
300     let mut fixes = Vec::new();
301     // If any of the arguments are referenced by an index number,
302     // and that argument is not a simple variable and cannot be inlined,
303     // we cannot remove any other arguments in the format string,
304     // because the index numbers might be wrong after inlining.
305     // Example of an un-inlinable format:  print!("{}{1}", foo, 2)
306     if !args.params().all(|p| check_one_arg(args, &p, &mut fixes, ignore_mixed)) || fixes.is_empty() {
307         return;
308     }
309
310     // multiline span display suggestion is sometimes broken: https://github.com/rust-lang/rust/pull/102729#discussion_r988704308
311     // in those cases, make the code suggestion hidden
312     let multiline_fix = fixes.iter().any(|(span, _)| cx.sess().source_map().is_multiline(*span));
313
314     span_lint_and_then(
315         cx,
316         UNINLINED_FORMAT_ARGS,
317         call_site,
318         "variables can be used directly in the `format!` string",
319         |diag| {
320             diag.multipart_suggestion_with_style(
321                 "change this to",
322                 fixes,
323                 Applicability::MachineApplicable,
324                 if multiline_fix { CompletelyHidden } else { ShowCode },
325             );
326         },
327     );
328 }
329
330 fn check_one_arg(
331     args: &FormatArgsExpn<'_>,
332     param: &FormatParam<'_>,
333     fixes: &mut Vec<(Span, String)>,
334     ignore_mixed: bool,
335 ) -> bool {
336     if matches!(param.kind, Implicit | Starred | Named(_) | Numbered)
337         && let ExprKind::Path(QPath::Resolved(None, path)) = param.value.kind
338         && let [segment] = path.segments
339         && let Some(arg_span) = args.value_with_prev_comma_span(param.value.hir_id)
340     {
341         let replacement = match param.usage {
342             FormatParamUsage::Argument => segment.ident.name.to_string(),
343             FormatParamUsage::Width => format!("{}$", segment.ident.name),
344             FormatParamUsage::Precision => format!(".{}$", segment.ident.name),
345         };
346         fixes.push((param.span, replacement));
347         fixes.push((arg_span, String::new()));
348         true  // successful inlining, continue checking
349     } else {
350         // Do not continue inlining (return false) in case
351         // * if we can't inline a numbered argument, e.g. `print!("{0} ...", foo.bar, ...)`
352         // * if allow_mixed_uninlined_format_args is false and this arg hasn't been inlined already
353         param.kind != Numbered && (!ignore_mixed || matches!(param.kind, NamedInline(_)))
354     }
355 }
356
357 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
358     if expn_data.call_site.from_expansion() {
359         outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
360     } else {
361         expn_data
362     }
363 }
364
365 fn check_format_in_format_args(
366     cx: &LateContext<'_>,
367     call_site: Span,
368     name: Symbol,
369     arg: &Expr<'_>,
370 ) {
371     let expn_data = arg.span.ctxt().outer_expn_data();
372     if expn_data.call_site.from_expansion() {
373         return;
374     }
375     let Some(mac_id) = expn_data.macro_def_id else { return };
376     if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
377         return;
378     }
379     span_lint_and_then(
380         cx,
381         FORMAT_IN_FORMAT_ARGS,
382         call_site,
383         &format!("`format!` in `{name}!` args"),
384         |diag| {
385             diag.help(&format!(
386                 "combine the `format!(..)` arguments with the outer `{name}!(..)` call"
387             ));
388             diag.help("or consider changing `format!` to `format_args!`");
389         },
390     );
391 }
392
393 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
394     if_chain! {
395         if !value.span.from_expansion();
396         if let ExprKind::MethodCall(_, receiver, [], to_string_span) = value.kind;
397         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
398         if is_diag_trait_item(cx, method_def_id, sym::ToString);
399         let receiver_ty = cx.typeck_results().expr_ty(receiver);
400         if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
401         let (n_needed_derefs, target) =
402             count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
403         if implements_trait(cx, target, display_trait_id, &[]);
404         if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
405         if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
406         then {
407             let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
408             if n_needed_derefs == 0 && !needs_ref {
409                 span_lint_and_sugg(
410                     cx,
411                     TO_STRING_IN_FORMAT_ARGS,
412                     to_string_span.with_lo(receiver.span.hi()),
413                     &format!(
414                         "`to_string` applied to a type that implements `Display` in `{name}!` args"
415                     ),
416                     "remove this",
417                     String::new(),
418                     Applicability::MachineApplicable,
419                 );
420             } else {
421                 span_lint_and_sugg(
422                     cx,
423                     TO_STRING_IN_FORMAT_ARGS,
424                     value.span,
425                     &format!(
426                         "`to_string` applied to a type that implements `Display` in `{name}!` args"
427                     ),
428                     "use this",
429                     format!(
430                         "{}{:*>n_needed_derefs$}{receiver_snippet}",
431                         if needs_ref { "&" } else { "" },
432                         ""
433                     ),
434                     Applicability::MachineApplicable,
435                 );
436             }
437         }
438     }
439 }
440
441 /// Returns true if `hir_id` is referred to by multiple format params
442 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
443     args.params().filter(|param| param.value.hir_id == hir_id).at_most_one().is_err()
444 }
445
446 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
447 where
448     I: Iterator<Item = &'tcx Adjustment<'tcx>>,
449 {
450     let mut n_total = 0;
451     let mut n_needed = 0;
452     loop {
453         if let Some(Adjustment { kind: Adjust::Deref(overloaded_deref), target }) = iter.next() {
454             n_total += 1;
455             if overloaded_deref.is_some() {
456                 n_needed = n_total;
457             }
458             ty = *target;
459         } else {
460             return (n_needed, ty);
461         }
462     }
463 }