|
| 1 | +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; |
| 2 | +use ruff_macros::{derive_message_formats, ViolationMetadata}; |
| 3 | +use ruff_python_ast::{ |
| 4 | + Arguments, CmpOp, Expr, ExprAttribute, ExprCall, ExprCompare, ExprContext, Identifier, |
| 5 | +}; |
| 6 | +use ruff_python_semantic::{Modules, SemanticModel}; |
| 7 | +use ruff_text_size::TextRange; |
| 8 | + |
| 9 | +use crate::checkers::ast::Checker; |
| 10 | + |
| 11 | +/// ## What it does |
| 12 | +/// |
| 13 | +/// Checks for uses of the `re` module that can be replaced with builtin `str` methods. |
| 14 | +/// |
| 15 | +/// ## Why is this bad? |
| 16 | +/// |
| 17 | +/// Performing checks on strings directly can make the code simpler, may require |
| 18 | +/// less escaping, and will often be faster. |
| 19 | +/// |
| 20 | +/// ## Example |
| 21 | +/// |
| 22 | +/// ```python |
| 23 | +/// re.sub("abc", "", s) |
| 24 | +/// ``` |
| 25 | +/// |
| 26 | +/// Use instead: |
| 27 | +/// |
| 28 | +/// ```python |
| 29 | +/// s.replace("abc", "") |
| 30 | +/// ``` |
| 31 | +/// |
| 32 | +/// ## Details |
| 33 | +/// |
| 34 | +/// The rule reports the following calls when the first argument to the call is |
| 35 | +/// a plain string literal, and no additional flags are passed: |
| 36 | +/// |
| 37 | +/// - `re.sub` |
| 38 | +/// - `re.match` |
| 39 | +/// - `re.search` |
| 40 | +/// - `re.fullmatch` |
| 41 | +/// - `re.split` |
| 42 | +/// |
| 43 | +/// For `re.sub`, the `repl` (replacement) argument must also be a string literal, |
| 44 | +/// not a function. For `re.match`, `re.search`, and `re.fullmatch`, the return |
| 45 | +/// value must also be used only for its truth value. |
| 46 | +/// |
| 47 | +/// ## Fix safety |
| 48 | +/// |
| 49 | +/// This rule's fix is marked as unsafe if the affected expression contains comments. Otherwise, |
| 50 | +/// the fix can be applied safely. |
| 51 | +/// |
| 52 | +/// ## References |
| 53 | +/// - [Python Regular Expression HOWTO: Common Problems - Use String Methods](https://docs.python.org/3/howto/regex.html#use-string-methods) |
| 54 | +#[derive(ViolationMetadata)] |
| 55 | +pub(crate) struct UnnecessaryRegularExpression { |
| 56 | + replacement: String, |
| 57 | +} |
| 58 | + |
| 59 | +impl AlwaysFixableViolation for UnnecessaryRegularExpression { |
| 60 | + #[derive_message_formats] |
| 61 | + fn message(&self) -> String { |
| 62 | + "Plain string pattern passed to `re` function".to_string() |
| 63 | + } |
| 64 | + |
| 65 | + fn fix_title(&self) -> String { |
| 66 | + format!("Replace with `{}`", self.replacement) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +/// RUF055 |
| 71 | +pub(crate) fn unnecessary_regular_expression(checker: &mut Checker, call: &ExprCall) { |
| 72 | + // adapted from unraw_re_pattern |
| 73 | + let semantic = checker.semantic(); |
| 74 | + |
| 75 | + if !semantic.seen_module(Modules::RE) { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + let Some(qualified_name) = semantic.resolve_qualified_name(&call.func) else { |
| 80 | + return; |
| 81 | + }; |
| 82 | + |
| 83 | + let ["re", func] = qualified_name.segments() else { |
| 84 | + return; |
| 85 | + }; |
| 86 | + |
| 87 | + // skip calls with more than `pattern` and `string` arguments (and `repl` |
| 88 | + // for `sub`) |
| 89 | + let Some(re_func) = ReFunc::from_call_expr(semantic, call, func) else { |
| 90 | + return; |
| 91 | + }; |
| 92 | + |
| 93 | + // For now, restrict this rule to string literals |
| 94 | + let Some(string_lit) = re_func.pattern.as_string_literal_expr() else { |
| 95 | + return; |
| 96 | + }; |
| 97 | + |
| 98 | + // For now, reject any regex metacharacters. Compare to the complete list |
| 99 | + // from https://docs.python.org/3/howto/regex.html#matching-characters |
| 100 | + let has_metacharacters = string_lit |
| 101 | + .value |
| 102 | + .to_str() |
| 103 | + .contains(['.', '^', '$', '*', '+', '?', '{', '[', '\\', '|', '(']); |
| 104 | + |
| 105 | + if has_metacharacters { |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + // Here we know the pattern is a string literal with no metacharacters, so |
| 110 | + // we can proceed with the str method replacement |
| 111 | + let new_expr = re_func.replacement(); |
| 112 | + |
| 113 | + let repl = checker.generator().expr(&new_expr); |
| 114 | + let diagnostic = Diagnostic::new( |
| 115 | + UnnecessaryRegularExpression { |
| 116 | + replacement: repl.clone(), |
| 117 | + }, |
| 118 | + call.range, |
| 119 | + ); |
| 120 | + |
| 121 | + let fix = Fix::applicable_edit( |
| 122 | + Edit::range_replacement(repl, call.range), |
| 123 | + if checker |
| 124 | + .comment_ranges() |
| 125 | + .has_comments(call, checker.source()) |
| 126 | + { |
| 127 | + Applicability::Unsafe |
| 128 | + } else { |
| 129 | + Applicability::Safe |
| 130 | + }, |
| 131 | + ); |
| 132 | + |
| 133 | + checker.diagnostics.push(diagnostic.with_fix(fix)); |
| 134 | +} |
| 135 | + |
| 136 | +/// The `re` functions supported by this rule. |
| 137 | +#[derive(Debug)] |
| 138 | +enum ReFuncKind<'a> { |
| 139 | + Sub { repl: &'a Expr }, |
| 140 | + Match, |
| 141 | + Search, |
| 142 | + Fullmatch, |
| 143 | + Split, |
| 144 | +} |
| 145 | + |
| 146 | +#[derive(Debug)] |
| 147 | +struct ReFunc<'a> { |
| 148 | + kind: ReFuncKind<'a>, |
| 149 | + pattern: &'a Expr, |
| 150 | + string: &'a Expr, |
| 151 | +} |
| 152 | + |
| 153 | +impl<'a> ReFunc<'a> { |
| 154 | + fn from_call_expr( |
| 155 | + semantic: &SemanticModel, |
| 156 | + call: &'a ExprCall, |
| 157 | + func_name: &str, |
| 158 | + ) -> Option<Self> { |
| 159 | + // the proposed fixes for match, search, and fullmatch rely on the |
| 160 | + // return value only being used for its truth value |
| 161 | + let in_if_context = semantic.in_boolean_test(); |
| 162 | + |
| 163 | + match (func_name, call.arguments.len()) { |
| 164 | + // `split` is the safest of these to fix, as long as metacharacters |
| 165 | + // have already been filtered out from the `pattern` |
| 166 | + ("split", 2) => Some(ReFunc { |
| 167 | + kind: ReFuncKind::Split, |
| 168 | + pattern: call.arguments.find_argument("pattern", 0)?, |
| 169 | + string: call.arguments.find_argument("string", 1)?, |
| 170 | + }), |
| 171 | + // `sub` is only safe to fix if `repl` is a string. `re.sub` also |
| 172 | + // allows it to be a function, which will *not* work in the str |
| 173 | + // version |
| 174 | + ("sub", 3) => { |
| 175 | + let repl = call.arguments.find_argument("repl", 1)?; |
| 176 | + if !repl.is_string_literal_expr() { |
| 177 | + return None; |
| 178 | + } |
| 179 | + Some(ReFunc { |
| 180 | + kind: ReFuncKind::Sub { repl }, |
| 181 | + pattern: call.arguments.find_argument("pattern", 0)?, |
| 182 | + string: call.arguments.find_argument("string", 2)?, |
| 183 | + }) |
| 184 | + } |
| 185 | + ("match", 2) if in_if_context => Some(ReFunc { |
| 186 | + kind: ReFuncKind::Match, |
| 187 | + pattern: call.arguments.find_argument("pattern", 0)?, |
| 188 | + string: call.arguments.find_argument("string", 1)?, |
| 189 | + }), |
| 190 | + ("search", 2) if in_if_context => Some(ReFunc { |
| 191 | + kind: ReFuncKind::Search, |
| 192 | + pattern: call.arguments.find_argument("pattern", 0)?, |
| 193 | + string: call.arguments.find_argument("string", 1)?, |
| 194 | + }), |
| 195 | + ("fullmatch", 2) if in_if_context => Some(ReFunc { |
| 196 | + kind: ReFuncKind::Fullmatch, |
| 197 | + pattern: call.arguments.find_argument("pattern", 0)?, |
| 198 | + string: call.arguments.find_argument("string", 1)?, |
| 199 | + }), |
| 200 | + _ => None, |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + fn replacement(&self) -> Expr { |
| 205 | + match self.kind { |
| 206 | + // string.replace(pattern, repl) |
| 207 | + ReFuncKind::Sub { repl } => { |
| 208 | + self.method_expr("replace", vec![self.pattern.clone(), repl.clone()]) |
| 209 | + } |
| 210 | + // string.startswith(pattern) |
| 211 | + ReFuncKind::Match => self.method_expr("startswith", vec![self.pattern.clone()]), |
| 212 | + // pattern in string |
| 213 | + ReFuncKind::Search => self.compare_expr(CmpOp::In), |
| 214 | + // string == pattern |
| 215 | + ReFuncKind::Fullmatch => self.compare_expr(CmpOp::Eq), |
| 216 | + // string.split(pattern) |
| 217 | + ReFuncKind::Split => self.method_expr("split", vec![self.pattern.clone()]), |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + /// Return a new compare expr of the form `self.pattern op self.string` |
| 222 | + fn compare_expr(&self, op: CmpOp) -> Expr { |
| 223 | + Expr::Compare(ExprCompare { |
| 224 | + left: Box::new(self.pattern.clone()), |
| 225 | + ops: Box::new([op]), |
| 226 | + comparators: Box::new([self.string.clone()]), |
| 227 | + range: TextRange::default(), |
| 228 | + }) |
| 229 | + } |
| 230 | + |
| 231 | + /// Return a new method call expression on `self.string` with `args` like |
| 232 | + /// `self.string.method(args...)` |
| 233 | + fn method_expr(&self, method: &str, args: Vec<Expr>) -> Expr { |
| 234 | + let method = Expr::Attribute(ExprAttribute { |
| 235 | + value: Box::new(self.string.clone()), |
| 236 | + attr: Identifier::new(method, TextRange::default()), |
| 237 | + ctx: ExprContext::Load, |
| 238 | + range: TextRange::default(), |
| 239 | + }); |
| 240 | + Expr::Call(ExprCall { |
| 241 | + func: Box::new(method), |
| 242 | + arguments: Arguments { |
| 243 | + args: args.into_boxed_slice(), |
| 244 | + keywords: Box::new([]), |
| 245 | + range: TextRange::default(), |
| 246 | + }, |
| 247 | + range: TextRange::default(), |
| 248 | + }) |
| 249 | + } |
| 250 | +} |
0 commit comments