1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::higher::{FormatArgsArg, FormatArgsExpn, FormatExpn};
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(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.is_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);
110 check_to_string_in_format_args(cx, name, arg);
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: &FormatArgsArg<'_>) {
127 if FormatExpn::parse(arg.value).is_some();
128 if !arg.value.span.ctxt().outer_expn_data().call_site.from_expansion();
132 FORMAT_IN_FORMAT_ARGS,
134 &format!("`format!` in `{}!` args", name),
137 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
140 diag.help("or consider changing `format!` to `format_args!`");
147 fn check_to_string_in_format_args<'tcx>(cx: &LateContext<'tcx>, name: Symbol, arg: &FormatArgsArg<'tcx>) {
148 let value = arg.value;
150 if !value.span.from_expansion();
151 if let ExprKind::MethodCall(_, _, [receiver], _) = value.kind;
152 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
153 if is_diag_trait_item(cx, method_def_id, sym::ToString);
154 let receiver_ty = cx.typeck_results().expr_ty(receiver);
155 if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
156 if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
158 let (n_needed_derefs, target) = count_needed_derefs(
160 cx.typeck_results().expr_adjustments(receiver).iter(),
162 if implements_trait(cx, target, display_trait_id, &[]) {
163 if n_needed_derefs == 0 {
166 TO_STRING_IN_FORMAT_ARGS,
167 value.span.with_lo(receiver.span.hi()),
168 &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
171 Applicability::MachineApplicable,
176 TO_STRING_IN_FORMAT_ARGS,
178 &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
180 format!("{:*>width$}{}", "", receiver_snippet, width = n_needed_derefs),
181 Applicability::MachineApplicable,
189 // Returns true if `args[i]` "refers to" or "is referred to by" another argument.
190 fn is_aliased(args: &[FormatArgsArg<'_>], i: usize) -> bool {
191 let value = args[i].value;
194 .any(|(j, arg)| i != j && std::ptr::eq(value, arg.value))
197 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
199 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
202 let mut n_needed = 0;
204 if let Some(Adjustment {
205 kind: Adjust::Deref(overloaded_deref),
210 if overloaded_deref.is_some() {
215 return (n_needed, ty);