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