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(
103 cx: &LateContext<'_>,
108 let expn_data = arg.span.ctxt().outer_expn_data();
109 if expn_data.call_site.from_expansion() {
112 let Some(mac_id) = expn_data.macro_def_id else { return };
113 if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
118 FORMAT_IN_FORMAT_ARGS,
120 &format!("`format!` in `{}!` args", name),
123 "combine the `format!(..)` arguments with the outer `{}!(..)` call",
126 diag.help("or consider changing `format!` to `format_args!`");
131 fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
133 if !value.span.from_expansion();
134 if let ExprKind::MethodCall(_, receiver, [], _) = value.kind;
135 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
136 if is_diag_trait_item(cx, method_def_id, sym::ToString);
137 let receiver_ty = cx.typeck_results().expr_ty(receiver);
138 if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
139 let (n_needed_derefs, target) =
140 count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
141 if implements_trait(cx, target, display_trait_id, &[]);
142 if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
143 if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
145 let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
146 if n_needed_derefs == 0 && !needs_ref {
149 TO_STRING_IN_FORMAT_ARGS,
150 value.span.with_lo(receiver.span.hi()),
152 "`to_string` applied to a type that implements `Display` in `{}!` args",
157 Applicability::MachineApplicable,
162 TO_STRING_IN_FORMAT_ARGS,
165 "`to_string` applied to a type that implements `Display` in `{}!` args",
171 if needs_ref { "&" } else { "" },
174 width = n_needed_derefs
176 Applicability::MachineApplicable,
183 // Returns true if `hir_id` is referred to by multiple format params
184 fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
185 args.params().filter(|param| param.value.hir_id == hir_id).at_most_one().is_err()
188 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
190 I: Iterator<Item = &'tcx Adjustment<'tcx>>,
193 let mut n_needed = 0;
195 if let Some(Adjustment { kind: Adjust::Deref(overloaded_deref), target }) = iter.next() {
197 if overloaded_deref.is_some() {
202 return (n_needed, ty);