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,
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};
22 declare_clippy_lint! {
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.
28 /// ### Why is this bad?
29 /// The recommended code is both shorter and avoids a temporary allocation.
33 /// # use std::panic::Location;
34 /// println!("error: {}", format!("something failed at {}", Location::caller()));
38 /// # use std::panic::Location;
39 /// println!("error: something failed at {}", Location::caller());
41 #[clippy::version = "1.58.0"]
42 pub FORMAT_IN_FORMAT_ARGS,
44 "`format!` used in a macro that does formatting"
47 declare_clippy_lint! {
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.
53 /// ### Why is this bad?
54 /// Since the type implements `Display`, the use of `to_string` is
59 /// # use std::panic::Location;
60 /// println!("error: something failed at {}", Location::caller().to_string());
64 /// # use std::panic::Location;
65 /// println!("error: something failed at {}", Location::caller());
67 #[clippy::version = "1.58.0"]
68 pub TO_STRING_IN_FORMAT_ARGS,
70 "`to_string` applied to a type that implements `Display` in format args"
73 declare_clippy_lint! {
75 /// Detect when a variable is not inlined in a format string,
76 /// and suggests to inline it.
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.
88 /// format!("{}", var);
89 /// format!("{v:?}", v = var);
90 /// format!("{0} {0}", var);
91 /// format!("{0:1$}", var, width);
92 /// format!("{:.*}", prec, var);
100 /// format!("{var:?}");
101 /// format!("{var} {var}");
102 /// format!("{var:width$}");
103 /// format!("{var:.prec$}");
106 /// ### Known Problems
108 /// There may be a false positive if the format string is expanded from certain proc macros:
111 /// println!(indoc!("{}"), var);
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,
119 "using non-inlined variables in `format!` calls"
122 declare_clippy_lint! {
124 /// Detects [formatting parameters] that have no effect on the output of
125 /// `format!()`, `println!()` or similar macros.
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.
133 /// println!("{:.}", 1.0);
135 /// println!("not padded: {:5}", format_args!("..."));
139 /// println!("{}", 1.0);
141 /// println!("not padded: {}", format_args!("..."));
143 /// println!("padded: {:5}", format!("..."));
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,
150 "use of a format specifier that has no effect"
153 impl_lint_pass!(FormatArgs => [
154 FORMAT_IN_FORMAT_ARGS,
155 TO_STRING_IN_FORMAT_ARGS,
156 UNINLINED_FORMAT_ARGS,
160 pub struct FormatArgs {
161 msrv: Option<RustcVersion>,
166 pub fn new(msrv: Option<RustcVersion>) -> Self {
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
180 for arg in &format_args.args {
181 check_unused_format_specifier(cx, arg);
182 if !arg.format.is_default() {
185 if is_aliased(&format_args, arg.param.value.hir_id) {
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);
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);
197 extract_msrv_attr!(LateContext);
200 fn check_unused_format_specifier(cx: &LateContext<'_>, arg: &FormatArg<'_>) {
201 let param_ty = cx.typeck_results().expr_ty(arg.param.value).peel_refs();
203 if let Count::Implied(Some(mut span)) = arg.format.precision
210 "empty precision specifier has no effect",
212 if param_ty.is_floating_point() {
213 diag.note("a precision specifier is not required to format floats");
216 if arg.format.is_default() {
217 // If there's no other specifiers remove the `:` too
218 span = arg.format_span();
221 diag.span_suggestion_verbose(span, "remove the `.`", "", Applicability::MachineApplicable);
226 if is_type_diagnostic_item(cx, param_ty, sym::Arguments) && !arg.format.is_default_for_trait() {
231 "format specifiers have no effect on `format_args!()`",
233 let mut suggest_format = |spec, span| {
234 let message = format!("for the {spec} to apply consider using `format!()`");
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)
240 diag.span_suggestion(
241 cx.sess().source_map().span_until_char(mac_call.span, '!'),
244 Applicability::MaybeIncorrect,
246 } else if let Some(span) = span {
247 diag.span_help(span, message);
251 if !arg.format.width.is_implied() {
252 suggest_format("width", arg.format.width.span());
255 if !arg.format.precision.is_implied() {
256 suggest_format("precision", arg.format.precision.span());
259 diag.span_suggestion_verbose(
261 "if the current behavior is intentional, remove the format specifiers",
263 Applicability::MaybeIncorrect,
270 fn check_uninlined_args(cx: &LateContext<'_>, args: &FormatArgsExpn<'_>, call_site: Span, def_id: DefId) {
271 if args.format_string.span.from_expansion() {
274 if call_site.edition() < Edition2021 && is_panic(cx, def_id) {
275 // panic! before 2021 edition considers a single string argument as non-format
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() {
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)) {
296 UNINLINED_FORMAT_ARGS,
298 "variables can be used directly in the `format!` string",
300 diag.multipart_suggestion("change this to", fixes, Applicability::MachineApplicable);
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)
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),
316 fixes.push((param.span, replacement));
317 fixes.push((arg_span, String::new()));
318 true // successful inlining, continue checking
320 // if we can't inline a numbered argument, we can't continue
321 param.kind != Numbered
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())
333 fn check_format_in_format_args(
334 cx: &LateContext<'_>,
339 let expn_data = arg.span.ctxt().outer_expn_data();
340 if expn_data.call_site.from_expansion() {
343 let Some(mac_id) = expn_data.macro_def_id else { return };
344 if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
349 FORMAT_IN_FORMAT_ARGS,
351 &format!("`format!` in `{name}!` args"),
354 "combine the `format!(..)` arguments with the outer `{name}!(..)` call"
356 diag.help("or consider changing `format!` to `format_args!`");
361 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
363 if !value.span.from_expansion();
364 if let ExprKind::MethodCall(_, receiver, [], to_string_span) = value.kind;
365 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
366 if is_diag_trait_item(cx, method_def_id, sym::ToString);
367 let receiver_ty = cx.typeck_results().expr_ty(receiver);
368 if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
369 let (n_needed_derefs, target) =
370 count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
371 if implements_trait(cx, target, display_trait_id, &[]);
372 if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
373 if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
375 let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
376 if n_needed_derefs == 0 && !needs_ref {
379 TO_STRING_IN_FORMAT_ARGS,
380 to_string_span.with_lo(receiver.span.hi()),
382 "`to_string` applied to a type that implements `Display` in `{name}!` args"
386 Applicability::MachineApplicable,
391 TO_STRING_IN_FORMAT_ARGS,
394 "`to_string` applied to a type that implements `Display` in `{name}!` args"
398 "{}{:*>n_needed_derefs$}{receiver_snippet}",
399 if needs_ref { "&" } else { "" },
402 Applicability::MachineApplicable,
409 /// Returns true if `hir_id` is referred to by multiple format params
410 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
411 args.params().filter(|param| param.value.hir_id == hir_id).at_most_one().is_err()
414 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
416 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
419 let mut n_needed = 0;
421 if let Some(Adjustment { kind: Adjust::Deref(overloaded_deref), target }) = iter.next() {
423 if overloaded_deref.is_some() {
428 return (n_needed, ty);