|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::format::{check_unformatted, is_display_arg}; |
| 3 | +use clippy_utils::higher::{FormatArgsExpn, FormatExpn}; |
| 4 | +use clippy_utils::source::snippet_opt; |
| 5 | +use clippy_utils::ty::implements_trait; |
| 6 | +use clippy_utils::{get_trait_def_id, match_def_path, paths}; |
| 7 | +use if_chain::if_chain; |
| 8 | +use rustc_errors::Applicability; |
| 9 | +use rustc_hir::{Expr, ExprKind}; |
| 10 | +use rustc_lint::{LateContext, LateLintPass}; |
| 11 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 12 | +use rustc_span::{BytePos, ExpnKind, Span, Symbol}; |
| 13 | + |
| 14 | +declare_clippy_lint! { |
| 15 | + /// ### What it does |
| 16 | + /// Warns on `format!` within the arguments of another macro that does |
| 17 | + /// formatting such as `format!` itself, `write!` or `println!`. Suggests |
| 18 | + /// inlining the `format!` call. |
| 19 | + /// |
| 20 | + /// ### Why is this bad? |
| 21 | + /// The recommended code is both shorter and avoids a temporary allocation. |
| 22 | + /// |
| 23 | + /// ### Example |
| 24 | + /// ```rust |
| 25 | + /// # use std::panic::Location; |
| 26 | + /// println!("error: {}", format!("something failed at {}", Location::caller())); |
| 27 | + /// ``` |
| 28 | + /// Use instead: |
| 29 | + /// ```rust |
| 30 | + /// # use std::panic::Location; |
| 31 | + /// println!("error: something failed at {}", Location::caller()); |
| 32 | + /// ``` |
| 33 | + pub FORMAT_IN_FORMAT_ARGS, |
| 34 | + perf, |
| 35 | + "`format!` used in a macro that does formatting" |
| 36 | +} |
| 37 | + |
| 38 | +declare_lint_pass!(FormatInFormatArgs => [FORMAT_IN_FORMAT_ARGS]); |
| 39 | + |
| 40 | +impl<'tcx> LateLintPass<'tcx> for FormatInFormatArgs { |
| 41 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 42 | + check_expr(cx, expr, format_in_format_args); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +declare_clippy_lint! { |
| 47 | + /// ### What it does |
| 48 | + /// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string) |
| 49 | + /// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html) |
| 50 | + /// in a macro that does formatting. |
| 51 | + /// |
| 52 | + /// ### Why is this bad? |
| 53 | + /// Since the type implements `Display`, the use of `to_string` is |
| 54 | + /// unnecessary. |
| 55 | + /// |
| 56 | + /// ### Example |
| 57 | + /// ```rust |
| 58 | + /// # use std::panic::Location; |
| 59 | + /// println!("error: something failed at {}", Location::caller().to_string()); |
| 60 | + /// ``` |
| 61 | + /// Use instead: |
| 62 | + /// ```rust |
| 63 | + /// # use std::panic::Location; |
| 64 | + /// println!("error: something failed at {}", Location::caller()); |
| 65 | + /// ``` |
| 66 | + pub TO_STRING_IN_FORMAT_ARGS, |
| 67 | + perf, |
| 68 | + "`to_string` applied to a type that implements `Display` in format args" |
| 69 | +} |
| 70 | + |
| 71 | +declare_lint_pass!(ToStringInFormatArgs => [TO_STRING_IN_FORMAT_ARGS]); |
| 72 | + |
| 73 | +impl<'tcx> LateLintPass<'tcx> for ToStringInFormatArgs { |
| 74 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 75 | + check_expr(cx, expr, to_string_in_format_args); |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +fn check_expr<'tcx, F>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, check_value: F) |
| 80 | +where |
| 81 | + F: Fn(&LateContext<'_>, &FormatArgsExpn<'_>, Span, Symbol, usize, &Expr<'_>) -> bool, |
| 82 | +{ |
| 83 | + if_chain! { |
| 84 | + if let Some(format_args) = FormatArgsExpn::parse(expr); |
| 85 | + let call_site = expr.span.ctxt().outer_expn_data().call_site; |
| 86 | + if call_site.from_expansion(); |
| 87 | + let expn_data = call_site.ctxt().outer_expn_data(); |
| 88 | + if let ExpnKind::Macro(_, name) = expn_data.kind; |
| 89 | + if format_args.fmt_expr.map_or(true, check_unformatted); |
| 90 | + then { |
| 91 | + assert_eq!(format_args.args.len(), format_args.value_args.len()); |
| 92 | + for (i, (arg, value)) in format_args.args.iter().zip(format_args.value_args.iter()).enumerate() { |
| 93 | + if !is_display_arg(arg) { |
| 94 | + continue; |
| 95 | + } |
| 96 | + if check_value(cx, &format_args, expn_data.call_site, name, i, value) { |
| 97 | + break; |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +fn format_in_format_args( |
| 105 | + cx: &LateContext<'_>, |
| 106 | + format_args: &FormatArgsExpn<'_>, |
| 107 | + call_site: Span, |
| 108 | + name: Symbol, |
| 109 | + i: usize, |
| 110 | + value: &Expr<'_>, |
| 111 | +) -> bool { |
| 112 | + if_chain! { |
| 113 | + if let Some(FormatExpn{ format_args: inner_format_args, .. }) = FormatExpn::parse(value); |
| 114 | + if let Some(format_string) = snippet_opt(cx, format_args.format_string_span); |
| 115 | + if let Some(inner_format_string) = snippet_opt(cx, inner_format_args.format_string_span); |
| 116 | + if let Some((sugg, applicability)) = format_in_format_args_sugg( |
| 117 | + cx, |
| 118 | + name, |
| 119 | + &format_string, |
| 120 | + &format_args.value_args, |
| 121 | + i, |
| 122 | + &inner_format_string, |
| 123 | + &inner_format_args.value_args |
| 124 | + ); |
| 125 | + then { |
| 126 | + span_lint_and_sugg( |
| 127 | + cx, |
| 128 | + FORMAT_IN_FORMAT_ARGS, |
| 129 | + trim_semicolon(cx, call_site), |
| 130 | + &format!("`format!` in `{}!` args", name), |
| 131 | + "inline the `format!` call", |
| 132 | + sugg, |
| 133 | + applicability, |
| 134 | + ); |
| 135 | + // Report only the first instance. |
| 136 | + return true; |
| 137 | + } |
| 138 | + } |
| 139 | + false |
| 140 | +} |
| 141 | + |
| 142 | +fn to_string_in_format_args( |
| 143 | + cx: &LateContext<'_>, |
| 144 | + _format_args: &FormatArgsExpn<'_>, |
| 145 | + _call_site: Span, |
| 146 | + name: Symbol, |
| 147 | + _i: usize, |
| 148 | + value: &Expr<'_>, |
| 149 | +) -> bool { |
| 150 | + if_chain! { |
| 151 | + if let ExprKind::MethodCall(_, _, args, _) = value.kind; |
| 152 | + if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id); |
| 153 | + if match_def_path(cx, method_def_id, &paths::TO_STRING_METHOD); |
| 154 | + if let Some(receiver) = args.get(0); |
| 155 | + let ty = cx.typeck_results().expr_ty(receiver); |
| 156 | + if let Some(display_trait_id) = get_trait_def_id(cx, &paths::DISPLAY_TRAIT); |
| 157 | + if implements_trait(cx, ty, display_trait_id, &[]); |
| 158 | + if let Some(snippet) = snippet_opt(cx, value.span); |
| 159 | + if let Some(dot) = snippet.rfind('.'); |
| 160 | + then { |
| 161 | + let span = value.span.with_lo( |
| 162 | + value.span.lo() + BytePos(u32::try_from(dot).unwrap()) |
| 163 | + ); |
| 164 | + span_lint_and_sugg( |
| 165 | + cx, |
| 166 | + TO_STRING_IN_FORMAT_ARGS, |
| 167 | + span, |
| 168 | + &format!("`to_string` applied to a type that implements `Display` in `{}!` args", name), |
| 169 | + "remove this", |
| 170 | + String::new(), |
| 171 | + Applicability::MachineApplicable, |
| 172 | + ); |
| 173 | + } |
| 174 | + } |
| 175 | + false |
| 176 | +} |
| 177 | + |
| 178 | +fn format_in_format_args_sugg( |
| 179 | + cx: &LateContext<'_>, |
| 180 | + name: Symbol, |
| 181 | + format_string: &str, |
| 182 | + values: &[&Expr<'_>], |
| 183 | + i: usize, |
| 184 | + inner_format_string: &str, |
| 185 | + inner_values: &[&Expr<'_>], |
| 186 | +) -> Option<(String, Applicability)> { |
| 187 | + let (left, right) = split_format_string(format_string, i); |
| 188 | + // If the inner format string is raw, the user is on their own. |
| 189 | + let (new_format_string, applicability) = if inner_format_string.starts_with('r') { |
| 190 | + (left + ".." + &right, Applicability::HasPlaceholders) |
| 191 | + } else { |
| 192 | + ( |
| 193 | + left + &trim_quotes(inner_format_string) + &right, |
| 194 | + Applicability::MachineApplicable, |
| 195 | + ) |
| 196 | + }; |
| 197 | + let values = values |
| 198 | + .iter() |
| 199 | + .map(|value| snippet_opt(cx, value.span)) |
| 200 | + .collect::<Option<Vec<_>>>()?; |
| 201 | + let inner_values = inner_values |
| 202 | + .iter() |
| 203 | + .map(|value| snippet_opt(cx, value.span)) |
| 204 | + .collect::<Option<Vec<_>>>()?; |
| 205 | + let new_values = itertools::join( |
| 206 | + values |
| 207 | + .iter() |
| 208 | + .take(i) |
| 209 | + .chain(inner_values.iter()) |
| 210 | + .chain(values.iter().skip(i + 1)), |
| 211 | + ", ", |
| 212 | + ); |
| 213 | + Some(( |
| 214 | + format!(r#"{}!({}, {})"#, name, new_format_string, new_values), |
| 215 | + applicability, |
| 216 | + )) |
| 217 | +} |
| 218 | + |
| 219 | +fn split_format_string(format_string: &str, i: usize) -> (String, String) { |
| 220 | + let mut iter = format_string.chars(); |
| 221 | + for j in 0..=i { |
| 222 | + assert!(advance(&mut iter) == '}' || j < i); |
| 223 | + } |
| 224 | + |
| 225 | + let right = iter.collect::<String>(); |
| 226 | + |
| 227 | + let size = format_string.len(); |
| 228 | + let right_size = right.len(); |
| 229 | + let left_size = size - right_size; |
| 230 | + assert!(left_size >= 2); |
| 231 | + let left = std::str::from_utf8(&format_string.as_bytes()[..left_size - 2]) |
| 232 | + .unwrap() |
| 233 | + .to_owned(); |
| 234 | + (left, right) |
| 235 | +} |
| 236 | + |
| 237 | +fn advance(iter: &mut std::str::Chars<'_>) -> char { |
| 238 | + loop { |
| 239 | + let first_char = iter.next().unwrap(); |
| 240 | + if first_char != '{' { |
| 241 | + continue; |
| 242 | + } |
| 243 | + let second_char = iter.next().unwrap(); |
| 244 | + if second_char == '{' { |
| 245 | + continue; |
| 246 | + } |
| 247 | + return second_char; |
| 248 | + } |
| 249 | +} |
| 250 | + |
| 251 | +fn trim_quotes(string_literal: &str) -> String { |
| 252 | + let len = string_literal.chars().count(); |
| 253 | + assert!(len >= 2); |
| 254 | + string_literal.chars().skip(1).take(len - 2).collect() |
| 255 | +} |
| 256 | + |
| 257 | +fn trim_semicolon(cx: &LateContext<'_>, span: Span) -> Span { |
| 258 | + snippet_opt(cx, span).map_or(span, |snippet| { |
| 259 | + let snippet = snippet.trim_end_matches(';'); |
| 260 | + span.with_hi(span.lo() + BytePos(u32::try_from(snippet.len()).unwrap())) |
| 261 | + }) |
| 262 | +} |
0 commit comments