]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format_args.rs
Merge commit '91496c2ac6abf6454c413bb23e8becf6b6dc20ea' into clippyup
[rust.git] / clippy_lints / src / format_args.rs
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, BytePos, ExpnData, ExpnKind, Span, Symbol};
14
15 declare_clippy_lint! {
16     /// ### What it does
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.
20     ///
21     /// ### Why is this bad?
22     /// The recommended code is both shorter and avoids a temporary allocation.
23     ///
24     /// ### Example
25     /// ```rust
26     /// # use std::panic::Location;
27     /// println!("error: {}", format!("something failed at {}", Location::caller()));
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// # use std::panic::Location;
32     /// println!("error: something failed at {}", Location::caller());
33     /// ```
34     pub FORMAT_IN_FORMAT_ARGS,
35     perf,
36     "`format!` used in a macro that does formatting"
37 }
38
39 declare_clippy_lint! {
40     /// ### What it does
41     /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
42     /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
43     /// in a macro that does formatting.
44     ///
45     /// ### Why is this bad?
46     /// Since the type implements `Display`, the use of `to_string` is
47     /// unnecessary.
48     ///
49     /// ### Example
50     /// ```rust
51     /// # use std::panic::Location;
52     /// println!("error: something failed at {}", Location::caller().to_string());
53     /// ```
54     /// Use instead:
55     /// ```rust
56     /// # use std::panic::Location;
57     /// println!("error: something failed at {}", Location::caller());
58     /// ```
59     pub TO_STRING_IN_FORMAT_ARGS,
60     perf,
61     "`to_string` applied to a type that implements `Display` in format args"
62 }
63
64 declare_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
65
66 const FORMAT_MACRO_PATHS: &[&[&str]] = &[
67     &paths::FORMAT_ARGS_MACRO,
68     &paths::ASSERT_EQ_MACRO,
69     &paths::ASSERT_MACRO,
70     &paths::ASSERT_NE_MACRO,
71     &paths::EPRINT_MACRO,
72     &paths::EPRINTLN_MACRO,
73     &paths::PRINT_MACRO,
74     &paths::PRINTLN_MACRO,
75     &paths::WRITE_MACRO,
76     &paths::WRITELN_MACRO,
77 ];
78
79 const FORMAT_MACRO_DIAG_ITEMS: &[Symbol] = &[sym::format_macro, sym::std_panic_macro];
80
81 impl<'tcx> LateLintPass<'tcx> for FormatArgs {
82     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
83         if_chain! {
84             if let Some(format_args) = FormatArgsExpn::parse(expr);
85             let expr_expn_data = expr.span.ctxt().outer_expn_data();
86             let outermost_expn_data = outermost_expn_data(expr_expn_data);
87             if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
88             if FORMAT_MACRO_PATHS
89                 .iter()
90                 .any(|path| match_def_path(cx, macro_def_id, path))
91                 || FORMAT_MACRO_DIAG_ITEMS
92                     .iter()
93                     .any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, macro_def_id));
94             if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
95             if let Some(args) = format_args.args();
96             then {
97                 for (i, arg) in args.iter().enumerate() {
98                     if !arg.is_display() {
99                         continue;
100                     }
101                     if arg.has_string_formatting() {
102                         continue;
103                     }
104                     if is_aliased(&args, i) {
105                         continue;
106                     }
107                     check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg);
108                     check_to_string_in_format_args(cx, name, arg);
109                 }
110             }
111         }
112     }
113 }
114
115 fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
116     if expn_data.call_site.from_expansion() {
117         outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
118     } else {
119         expn_data
120     }
121 }
122
123 fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &FormatArgsArg<'_>) {
124     if_chain! {
125         if FormatExpn::parse(arg.value).is_some();
126         if !arg.value.span.ctxt().outer_expn_data().call_site.from_expansion();
127         then {
128             span_lint_and_then(
129                 cx,
130                 FORMAT_IN_FORMAT_ARGS,
131                 trim_semicolon(cx, call_site),
132                 &format!("`format!` in `{}!` args", name),
133                 |diag| {
134                     diag.help(&format!(
135                         "combine the `format!(..)` arguments with the outer `{}!(..)` call",
136                         name
137                     ));
138                     diag.help("or consider changing `format!` to `format_args!`");
139                 },
140             );
141         }
142     }
143 }
144
145 fn check_to_string_in_format_args<'tcx>(cx: &LateContext<'tcx>, name: Symbol, arg: &FormatArgsArg<'tcx>) {
146     let value = arg.value;
147     if_chain! {
148         if !value.span.from_expansion();
149         if let ExprKind::MethodCall(_, _, [receiver], _) = value.kind;
150         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
151         if is_diag_trait_item(cx, method_def_id, sym::ToString);
152         let receiver_ty = cx.typeck_results().expr_ty(receiver);
153         if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
154         if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
155         then {
156             let (n_needed_derefs, target) = count_needed_derefs(
157                 receiver_ty,
158                 cx.typeck_results().expr_adjustments(receiver).iter(),
159             );
160             if implements_trait(cx, target, display_trait_id, &[]) {
161                 if n_needed_derefs == 0 {
162                     span_lint_and_sugg(
163                         cx,
164                         TO_STRING_IN_FORMAT_ARGS,
165                         value.span.with_lo(receiver.span.hi()),
166                         &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
167                         "remove this",
168                         String::new(),
169                         Applicability::MachineApplicable,
170                     );
171                 } else {
172                     span_lint_and_sugg(
173                         cx,
174                         TO_STRING_IN_FORMAT_ARGS,
175                         value.span,
176                         &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name),
177                         "use this",
178                         format!("{:*>width$}{}", "", receiver_snippet, width = n_needed_derefs),
179                         Applicability::MachineApplicable,
180                     );
181                 }
182             }
183         }
184     }
185 }
186
187 // Returns true if `args[i]` "refers to" or "is referred to by" another argument.
188 fn is_aliased(args: &[FormatArgsArg<'_>], i: usize) -> bool {
189     let value = args[i].value;
190     args.iter()
191         .enumerate()
192         .any(|(j, arg)| i != j && std::ptr::eq(value, arg.value))
193 }
194
195 fn trim_semicolon(cx: &LateContext<'_>, span: Span) -> Span {
196     snippet_opt(cx, span).map_or(span, |snippet| {
197         let snippet = snippet.trim_end_matches(';');
198         span.with_hi(span.lo() + BytePos(u32::try_from(snippet.len()).unwrap()))
199     })
200 }
201
202 fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
203 where
204     I: Iterator<Item = &'tcx Adjustment<'tcx>>,
205 {
206     let mut n_total = 0;
207     let mut n_needed = 0;
208     loop {
209         if let Some(Adjustment {
210             kind: Adjust::Deref(overloaded_deref),
211             target,
212         }) = iter.next()
213         {
214             n_total += 1;
215             if overloaded_deref.is_some() {
216                 n_needed = n_total;
217             }
218             ty = target;
219         } else {
220             return (n_needed, ty);
221         }
222     }
223 }