|
| 1 | +use rustc_ast::{LitKind, StrStyle}; |
| 2 | +use rustc_hir::{Expr, ExprKind}; |
| 3 | +use rustc_lexer::is_ident; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_parse_format::{ParseMode, Parser, Piece}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | +use rustc_span::{BytePos, Span}; |
| 8 | + |
| 9 | +use clippy_utils::diagnostics::span_lint; |
| 10 | +use clippy_utils::mir::enclosing_mir; |
| 11 | + |
| 12 | +declare_clippy_lint! { |
| 13 | + /// ### What it does |
| 14 | + /// Checks if string literals have formatting arguments outside of macros |
| 15 | + /// using them (like `format!`). |
| 16 | + /// |
| 17 | + /// ### Why is this bad? |
| 18 | + /// It will likely not generate the expected content. |
| 19 | + /// |
| 20 | + /// ### Example |
| 21 | + /// ```no_run |
| 22 | + /// let x: Option<usize> = None; |
| 23 | + /// let y = "hello"; |
| 24 | + /// x.expect("{y:?}"); |
| 25 | + /// ``` |
| 26 | + /// Use instead: |
| 27 | + /// ```no_run |
| 28 | + /// let x: Option<usize> = None; |
| 29 | + /// let y = "hello"; |
| 30 | + /// x.expect(&format!("{y:?}")); |
| 31 | + /// ``` |
| 32 | + #[clippy::version = "1.83.0"] |
| 33 | + pub LITERAL_STRING_WITH_FORMATTING_ARGS, |
| 34 | + suspicious, |
| 35 | + "Checks if string literals have formatting arguments" |
| 36 | +} |
| 37 | + |
| 38 | +declare_lint_pass!(LiteralStringWithFormattingArg => [LITERAL_STRING_WITH_FORMATTING_ARGS]); |
| 39 | + |
| 40 | +fn emit_lint(cx: &LateContext<'_>, expr: &Expr<'_>, spans: &[(Span, Option<String>)]) { |
| 41 | + if !spans.is_empty() |
| 42 | + && let Some(mir) = enclosing_mir(cx.tcx, expr.hir_id) |
| 43 | + { |
| 44 | + let spans = spans |
| 45 | + .iter() |
| 46 | + .filter_map(|(span, name)| { |
| 47 | + if let Some(name) = name { |
| 48 | + // We need to check that the name is a local. |
| 49 | + if !mir |
| 50 | + .var_debug_info |
| 51 | + .iter() |
| 52 | + .any(|local| !local.source_info.span.from_expansion() && local.name.as_str() == name) |
| 53 | + { |
| 54 | + return None; |
| 55 | + } |
| 56 | + } |
| 57 | + Some(*span) |
| 58 | + }) |
| 59 | + .collect::<Vec<_>>(); |
| 60 | + match spans.len() { |
| 61 | + 0 => {}, |
| 62 | + 1 => { |
| 63 | + span_lint( |
| 64 | + cx, |
| 65 | + LITERAL_STRING_WITH_FORMATTING_ARGS, |
| 66 | + spans, |
| 67 | + "this looks like a formatting argument but it is not part of a formatting macro", |
| 68 | + ); |
| 69 | + }, |
| 70 | + _ => { |
| 71 | + span_lint( |
| 72 | + cx, |
| 73 | + LITERAL_STRING_WITH_FORMATTING_ARGS, |
| 74 | + spans, |
| 75 | + "these look like formatting arguments but are not part of a formatting macro", |
| 76 | + ); |
| 77 | + }, |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +impl LateLintPass<'_> for LiteralStringWithFormattingArg { |
| 83 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 84 | + if expr.span.from_expansion() { |
| 85 | + return; |
| 86 | + } |
| 87 | + if let ExprKind::Lit(lit) = expr.kind { |
| 88 | + let (add, symbol) = match lit.node { |
| 89 | + LitKind::Str(symbol, style) => { |
| 90 | + let add = match style { |
| 91 | + StrStyle::Cooked => 1, |
| 92 | + StrStyle::Raw(nb) => nb as usize + 2, |
| 93 | + }; |
| 94 | + (add, symbol) |
| 95 | + }, |
| 96 | + _ => return, |
| 97 | + }; |
| 98 | + let fmt_str = symbol.as_str(); |
| 99 | + let lo = expr.span.lo(); |
| 100 | + let mut current = fmt_str; |
| 101 | + let mut diff_len = 0; |
| 102 | + |
| 103 | + let mut parser = Parser::new(current, None, None, false, ParseMode::Format); |
| 104 | + let mut spans = Vec::new(); |
| 105 | + while let Some(piece) = parser.next() { |
| 106 | + if let Some(error) = parser.errors.last() { |
| 107 | + // We simply ignore the errors and move after them. |
| 108 | + if error.span.end >= current.len() { |
| 109 | + break; |
| 110 | + } |
| 111 | + current = ¤t[error.span.end + 1..]; |
| 112 | + diff_len = fmt_str.len() - current.len(); |
| 113 | + parser = Parser::new(current, None, None, false, ParseMode::Format); |
| 114 | + } else if let Piece::NextArgument(arg) = piece { |
| 115 | + let mut pos = arg.position_span; |
| 116 | + pos.start += diff_len; |
| 117 | + pos.end += diff_len; |
| 118 | + |
| 119 | + let start = fmt_str[..pos.start].rfind('{').unwrap_or(pos.start); |
| 120 | + // If this is a unicode character escape, we don't want to lint. |
| 121 | + if start > 1 && fmt_str[..start].ends_with("\\u") { |
| 122 | + continue; |
| 123 | + } |
| 124 | + |
| 125 | + if fmt_str[start + 1..].trim_start().starts_with('}') { |
| 126 | + // We ignore `{}`. |
| 127 | + continue; |
| 128 | + } |
| 129 | + |
| 130 | + let end = fmt_str[start + 1..] |
| 131 | + .find('}') |
| 132 | + .map_or(pos.end, |found| start + 1 + found) |
| 133 | + + 1; |
| 134 | + let ident_start = start + 1; |
| 135 | + let colon_pos = fmt_str[ident_start..end].find(':'); |
| 136 | + let ident_end = colon_pos.unwrap_or(end - 1); |
| 137 | + let mut name = None; |
| 138 | + if ident_start < ident_end |
| 139 | + && let arg = &fmt_str[ident_start..ident_end] |
| 140 | + && !arg.is_empty() |
| 141 | + && is_ident(arg) |
| 142 | + { |
| 143 | + name = Some(arg.to_string()); |
| 144 | + } else if colon_pos.is_none() { |
| 145 | + // Not a `{:?}`. |
| 146 | + continue; |
| 147 | + } |
| 148 | + spans.push(( |
| 149 | + expr.span |
| 150 | + .with_hi(lo + BytePos((start + add).try_into().unwrap())) |
| 151 | + .with_lo(lo + BytePos((end + add).try_into().unwrap())), |
| 152 | + name, |
| 153 | + )); |
| 154 | + } |
| 155 | + } |
| 156 | + emit_lint(cx, expr, &spans); |
| 157 | + } |
| 158 | + } |
| 159 | +} |
0 commit comments