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::{is_format_macro, FormatArgsArg, FormatArgsExpn};
4 use clippy_utils::source::snippet_opt;
5 use clippy_utils::ty::implements_trait;
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 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
69 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
71 if let Some(format_args) = FormatArgsExpn::parse(cx, expr);
72 let expr_expn_data = expr.span.ctxt().outer_expn_data();
73 let outermost_expn_data = outermost_expn_data(expr_expn_data);
74 if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
75 if is_format_macro(cx, macro_def_id);
76 if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
77 if let Some(args) = format_args.args();
79 for (i, arg) in args.iter().enumerate() {
80 if arg.format_trait != sym::Display {
83 if arg.has_string_formatting() {
86 if is_aliased(&args, i) {
89 check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.value);
90 check_to_string_in_format_args(cx, name, arg.value);
97 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
98 if expn_data.call_site.from_expansion() {
99 outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
105 fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &Expr<'_>) {
106 let expn_data = arg.span.ctxt().outer_expn_data();
107 if expn_data.call_site.from_expansion() {
110 let Some(mac_id) = expn_data.macro_def_id else { return };
111 if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
116 FORMAT_IN_FORMAT_ARGS,
118 &format!("`format!` in `{}!` args", name),
121 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
124 diag.help("or consider changing `format!` to `format_args!`");
129 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
131 if !value.span.from_expansion();
132 if let ExprKind::MethodCall(_, [receiver], _) = value.kind;
133 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
134 if is_diag_trait_item(cx, method_def_id, sym::ToString);
135 let receiver_ty = cx.typeck_results().expr_ty(receiver);
136 if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
137 if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
139 let (n_needed_derefs, target) = count_needed_derefs(
141 cx.typeck_results().expr_adjustments(receiver).iter(),
143 if implements_trait(cx, target, display_trait_id, &[]) {
144 if n_needed_derefs == 0 {
147 TO_STRING_IN_FORMAT_ARGS,
148 value.span.with_lo(receiver.span.hi()),
149 &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
152 Applicability::MachineApplicable,
157 TO_STRING_IN_FORMAT_ARGS,
159 &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
161 format!("{:*>width$}{}", "", receiver_snippet, width = n_needed_derefs),
162 Applicability::MachineApplicable,
170 // Returns true if `args[i]` "refers to" or "is referred to by" another argument.
171 fn is_aliased(args: &[FormatArgsArg<'_>], i: usize) -> bool {
172 let value = args[i].value;
175 .any(|(j, arg)| i != j && std::ptr::eq(value, arg.value))
178 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
180 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
183 let mut n_needed = 0;
185 if let Some(Adjustment {
186 kind: Adjust::Deref(overloaded_deref),
191 if overloaded_deref.is_some() {
196 return (n_needed, ty);