1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::macros::{FormatArgsArg, FormatArgsExpn};
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::implements_trait;
5 use clippy_utils::{is_diag_trait_item, match_def_path, paths};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{Expr, ExprKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
11 use rustc_middle::ty::Ty;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
15 declare_clippy_lint! {
17 /// Detects `format!` within the arguments of another macro that does
18 /// formatting such as `format!` itself, `write!` or `println!`. Suggests
19 /// inlining the `format!` call.
21 /// ### Why is this bad?
22 /// The recommended code is both shorter and avoids a temporary allocation.
26 /// # use std::panic::Location;
27 /// println!("error: {}", format!("something failed at {}", Location::caller()));
31 /// # use std::panic::Location;
32 /// println!("error: something failed at {}", Location::caller());
34 #[clippy::version = "1.58.0"]
35 pub FORMAT_IN_FORMAT_ARGS,
37 "`format!` used in a macro that does formatting"
40 declare_clippy_lint! {
42 /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
43 /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
44 /// in a macro that does formatting.
46 /// ### Why is this bad?
47 /// Since the type implements `Display`, the use of `to_string` is
52 /// # use std::panic::Location;
53 /// println!("error: something failed at {}", Location::caller().to_string());
57 /// # use std::panic::Location;
58 /// println!("error: something failed at {}", Location::caller());
60 #[clippy::version = "1.58.0"]
61 pub TO_STRING_IN_FORMAT_ARGS,
63 "`to_string` applied to a type that implements `Display` in format args"
66 declare_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
68 const FORMAT_MACRO_PATHS: &[&[&str]] = &[
69 &paths::FORMAT_ARGS_MACRO,
70 &paths::ASSERT_EQ_MACRO,
72 &paths::ASSERT_NE_MACRO,
74 &paths::EPRINTLN_MACRO,
76 &paths::PRINTLN_MACRO,
78 &paths::WRITELN_MACRO,
81 const FORMAT_MACRO_DIAG_ITEMS: &[Symbol] = &[sym::format_macro, sym::std_panic_macro];
83 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
84 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
86 if let Some(format_args) = FormatArgsExpn::parse(cx, expr);
87 let expr_expn_data = expr.span.ctxt().outer_expn_data();
88 let outermost_expn_data = outermost_expn_data(expr_expn_data);
89 if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
92 .any(|path| match_def_path(cx, macro_def_id, path))
93 || FORMAT_MACRO_DIAG_ITEMS
95 .any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, macro_def_id));
96 if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
97 if let Some(args) = format_args.args();
99 for (i, arg) in args.iter().enumerate() {
100 if arg.format_trait != sym::Display {
103 if arg.has_string_formatting() {
106 if is_aliased(&args, i) {
109 check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.value);
110 check_to_string_in_format_args(cx, name, arg.value);
117 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
118 if expn_data.call_site.from_expansion() {
119 outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
125 fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &Expr<'_>) {
126 let expn_data = arg.span.ctxt().outer_expn_data();
127 if expn_data.call_site.from_expansion() {
130 let Some(mac_id) = expn_data.macro_def_id else { return };
131 if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
136 FORMAT_IN_FORMAT_ARGS,
138 &format!("`format!` in `{}!` args", name),
141 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
144 diag.help("or consider changing `format!` to `format_args!`");
149 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
151 if !value.span.from_expansion();
152 if let ExprKind::MethodCall(_, _, [receiver], _) = value.kind;
153 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
154 if is_diag_trait_item(cx, method_def_id, sym::ToString);
155 let receiver_ty = cx.typeck_results().expr_ty(receiver);
156 if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
157 if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
159 let (n_needed_derefs, target) = count_needed_derefs(
161 cx.typeck_results().expr_adjustments(receiver).iter(),
163 if implements_trait(cx, target, display_trait_id, &[]) {
164 if n_needed_derefs == 0 {
167 TO_STRING_IN_FORMAT_ARGS,
168 value.span.with_lo(receiver.span.hi()),
169 &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
172 Applicability::MachineApplicable,
177 TO_STRING_IN_FORMAT_ARGS,
179 &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
181 format!("{:*>width$}{}", "", receiver_snippet, width = n_needed_derefs),
182 Applicability::MachineApplicable,
190 // Returns true if `args[i]` "refers to" or "is referred to by" another argument.
191 fn is_aliased(args: &[FormatArgsArg<'_>], i: usize) -> bool {
192 let value = args[i].value;
195 .any(|(j, arg)| i != j && std::ptr::eq(value, arg.value))
198 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
200 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
203 let mut n_needed = 0;
205 if let Some(Adjustment {
206 kind: Adjust::Deref(overloaded_deref),
211 if overloaded_deref.is_some() {
216 return (n_needed, ty);