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, FormatArgsExpn};
4 use clippy_utils::source::snippet_opt;
5 use clippy_utils::ty::implements_trait;
6 use if_chain::if_chain;
7 use itertools::Itertools;
8 use rustc_errors::Applicability;
9 use rustc_hir::{Expr, ExprKind, HirId};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
12 use rustc_middle::ty::Ty;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
16 declare_clippy_lint! {
18 /// Detects `format!` within the arguments of another macro that does
19 /// formatting such as `format!` itself, `write!` or `println!`. Suggests
20 /// inlining the `format!` call.
22 /// ### Why is this bad?
23 /// The recommended code is both shorter and avoids a temporary allocation.
27 /// # use std::panic::Location;
28 /// println!("error: {}", format!("something failed at {}", Location::caller()));
32 /// # use std::panic::Location;
33 /// println!("error: something failed at {}", Location::caller());
35 #[clippy::version = "1.58.0"]
36 pub FORMAT_IN_FORMAT_ARGS,
38 "`format!` used in a macro that does formatting"
41 declare_clippy_lint! {
43 /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
44 /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
45 /// in a macro that does formatting.
47 /// ### Why is this bad?
48 /// Since the type implements `Display`, the use of `to_string` is
53 /// # use std::panic::Location;
54 /// println!("error: something failed at {}", Location::caller().to_string());
58 /// # use std::panic::Location;
59 /// println!("error: something failed at {}", Location::caller());
61 #[clippy::version = "1.58.0"]
62 pub TO_STRING_IN_FORMAT_ARGS,
64 "`to_string` applied to a type that implements `Display` in format args"
67 declare_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
69 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
70 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
72 if let Some(format_args) = FormatArgsExpn::parse(cx, expr);
73 let expr_expn_data = expr.span.ctxt().outer_expn_data();
74 let outermost_expn_data = outermost_expn_data(expr_expn_data);
75 if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
76 if is_format_macro(cx, macro_def_id);
77 if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
79 for arg in &format_args.args {
80 if arg.format.has_string_formatting() {
83 if is_aliased(&format_args, arg.param.value.hir_id) {
86 check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.param.value);
87 check_to_string_in_format_args(cx, name, arg.param.value);
94 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
95 if expn_data.call_site.from_expansion() {
96 outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
102 fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &Expr<'_>) {
103 let expn_data = arg.span.ctxt().outer_expn_data();
104 if expn_data.call_site.from_expansion() {
107 let Some(mac_id) = expn_data.macro_def_id else { return };
108 if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
113 FORMAT_IN_FORMAT_ARGS,
115 &format!("`format!` in `{}!` args", name),
118 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
121 diag.help("or consider changing `format!` to `format_args!`");
126 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
128 if !value.span.from_expansion();
129 if let ExprKind::MethodCall(_, [receiver], _) = value.kind;
130 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
131 if is_diag_trait_item(cx, method_def_id, sym::ToString);
132 let receiver_ty = cx.typeck_results().expr_ty(receiver);
133 if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
134 let (n_needed_derefs, target) =
135 count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
136 if implements_trait(cx, target, display_trait_id, &[]);
137 if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
138 if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
140 let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
141 if n_needed_derefs == 0 && !needs_ref {
144 TO_STRING_IN_FORMAT_ARGS,
145 value.span.with_lo(receiver.span.hi()),
147 "`to_string` applied to a type that implements `Display` in `{}!` args",
152 Applicability::MachineApplicable,
157 TO_STRING_IN_FORMAT_ARGS,
160 "`to_string` applied to a type that implements `Display` in `{}!` args",
166 if needs_ref { "&" } else { "" },
169 width = n_needed_derefs
171 Applicability::MachineApplicable,
178 // Returns true if `hir_id` is referred to by multiple format params
179 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
181 .filter(|param| param.value.hir_id == hir_id)
186 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
188 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
191 let mut n_needed = 0;
193 if let Some(Adjustment {
194 kind: Adjust::Deref(overloaded_deref),
199 if overloaded_deref.is_some() {
204 return (n_needed, ty);