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,
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;
15 SuggestionStyle::{CompletelyHidden, ShowCode},
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};
26 declare_clippy_lint! {
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.
32 /// ### Why is this bad?
33 /// The recommended code is both shorter and avoids a temporary allocation.
37 /// # use std::panic::Location;
38 /// println!("error: {}", format!("something failed at {}", Location::caller()));
42 /// # use std::panic::Location;
43 /// println!("error: something failed at {}", Location::caller());
45 #[clippy::version = "1.58.0"]
46 pub FORMAT_IN_FORMAT_ARGS,
48 "`format!` used in a macro that does formatting"
51 declare_clippy_lint! {
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.
57 /// ### Why is this bad?
58 /// Since the type implements `Display`, the use of `to_string` is
63 /// # use std::panic::Location;
64 /// println!("error: something failed at {}", Location::caller().to_string());
68 /// # use std::panic::Location;
69 /// println!("error: something failed at {}", Location::caller());
71 #[clippy::version = "1.58.0"]
72 pub TO_STRING_IN_FORMAT_ARGS,
74 "`to_string` applied to a type that implements `Display` in format args"
77 declare_clippy_lint! {
79 /// Detect when a variable is not inlined in a format string,
80 /// and suggests to inline it.
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.
92 /// format!("{}", var);
93 /// format!("{v:?}", v = var);
94 /// format!("{0} {0}", var);
95 /// format!("{0:1$}", var, width);
96 /// format!("{:.*}", prec, var);
103 /// format!("{var}");
104 /// format!("{var:?}");
105 /// format!("{var} {var}");
106 /// format!("{var:width$}");
107 /// format!("{var:.prec$}");
110 /// If allow-mixed-uninlined-format-args is set to false in clippy.toml,
111 /// the following code will also trigger the lint:
114 /// format!("{} {}", var, 1+2);
119 /// format!("{var} {}", 1+2);
122 /// ### Known Problems
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,
129 "using non-inlined variables in `format!` calls"
132 declare_clippy_lint! {
134 /// Detects [formatting parameters] that have no effect on the output of
135 /// `format!()`, `println!()` or similar macros.
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.
143 /// println!("{:.}", 1.0);
145 /// println!("not padded: {:5}", format_args!("..."));
149 /// println!("{}", 1.0);
151 /// println!("not padded: {}", format_args!("..."));
153 /// println!("padded: {:5}", format!("..."));
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,
160 "use of a format specifier that has no effect"
163 impl_lint_pass!(FormatArgs => [
164 FORMAT_IN_FORMAT_ARGS,
165 TO_STRING_IN_FORMAT_ARGS,
166 UNINLINED_FORMAT_ARGS,
170 pub struct FormatArgs {
177 pub fn new(msrv: Msrv, allow_mixed_uninlined_format_args: bool) -> Self {
180 ignore_mixed: allow_mixed_uninlined_format_args,
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
194 for arg in &format_args.args {
195 check_unused_format_specifier(cx, arg);
196 if !arg.format.is_default() {
199 if is_aliased(&format_args, arg.param.value.hir_id) {
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);
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);
211 extract_msrv_attr!(LateContext);
214 fn check_unused_format_specifier(cx: &LateContext<'_>, arg: &FormatArg<'_>) {
215 let param_ty = cx.typeck_results().expr_ty(arg.param.value).peel_refs();
217 if let Count::Implied(Some(mut span)) = arg.format.precision
224 "empty precision specifier has no effect",
226 if param_ty.is_floating_point() {
227 diag.note("a precision specifier is not required to format floats");
230 if arg.format.is_default() {
231 // If there's no other specifiers remove the `:` too
232 span = arg.format_span();
235 diag.span_suggestion_verbose(span, "remove the `.`", "", Applicability::MachineApplicable);
240 if is_type_diagnostic_item(cx, param_ty, sym::Arguments) && !arg.format.is_default_for_trait() {
245 "format specifiers have no effect on `format_args!()`",
247 let mut suggest_format = |spec, span| {
248 let message = format!("for the {spec} to apply consider using `format!()`");
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)
254 diag.span_suggestion(
255 cx.sess().source_map().span_until_char(mac_call.span, '!'),
258 Applicability::MaybeIncorrect,
260 } else if let Some(span) = span {
261 diag.span_help(span, message);
265 if !arg.format.width.is_implied() {
266 suggest_format("width", arg.format.width.span());
269 if !arg.format.precision.is_implied() {
270 suggest_format("precision", arg.format.precision.span());
273 diag.span_suggestion_verbose(
275 "if the current behavior is intentional, remove the format specifiers",
277 Applicability::MaybeIncorrect,
284 fn check_uninlined_args(
285 cx: &LateContext<'_>,
286 args: &FormatArgsExpn<'_>,
291 if args.format_string.span.from_expansion() {
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
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() {
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));
316 UNINLINED_FORMAT_ARGS,
318 "variables can be used directly in the `format!` string",
320 diag.multipart_suggestion_with_style(
323 Applicability::MachineApplicable,
324 if multiline_fix { CompletelyHidden } else { ShowCode },
331 args: &FormatArgsExpn<'_>,
332 param: &FormatParam<'_>,
333 fixes: &mut Vec<(Span, String)>,
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)
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),
346 fixes.push((param.span, replacement));
347 fixes.push((arg_span, String::new()));
348 true // successful inlining, continue checking
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(_)))
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())
365 fn check_format_in_format_args(
366 cx: &LateContext<'_>,
371 let expn_data = arg.span.ctxt().outer_expn_data();
372 if expn_data.call_site.from_expansion() {
375 let Some(mac_id) = expn_data.macro_def_id else { return };
376 if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
381 FORMAT_IN_FORMAT_ARGS,
383 &format!("`format!` in `{name}!` args"),
386 "combine the `format!(..)` arguments with the outer `{name}!(..)` call"
388 diag.help("or consider changing `format!` to `format_args!`");
393 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
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);
407 let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
408 if n_needed_derefs == 0 && !needs_ref {
411 TO_STRING_IN_FORMAT_ARGS,
412 to_string_span.with_lo(receiver.span.hi()),
414 "`to_string` applied to a type that implements `Display` in `{name}!` args"
418 Applicability::MachineApplicable,
423 TO_STRING_IN_FORMAT_ARGS,
426 "`to_string` applied to a type that implements `Display` in `{name}!` args"
430 "{}{:*>n_needed_derefs$}{receiver_snippet}",
431 if needs_ref { "&" } else { "" },
434 Applicability::MachineApplicable,
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()
446 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
448 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
451 let mut n_needed = 0;
453 if let Some(Adjustment { kind: Adjust::Deref(overloaded_deref), target }) = iter.next() {
455 if overloaded_deref.is_some() {
460 return (n_needed, ty);