|
| 1 | +use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; |
| 2 | +use ruff_macros::{derive_message_formats, violation}; |
| 3 | +use ruff_python_ast::{ |
| 4 | + Expr, ExprCall, ExprContext, ExprList, ExprStringLiteral, StringLiteral, StringLiteralFlags, |
| 5 | + StringLiteralValue, |
| 6 | +}; |
| 7 | +use ruff_text_size::{Ranged, TextRange}; |
| 8 | + |
| 9 | +use crate::checkers::ast::Checker; |
| 10 | + |
| 11 | +/// ## What it does |
| 12 | +/// Checks for str.split calls that can be replaced with a `list` literal. |
| 13 | +/// |
| 14 | +/// ## Why is this bad? |
| 15 | +/// List literals are more readable and do not require the overhead of calling `str.split`. |
| 16 | +/// |
| 17 | +/// ## Example |
| 18 | +/// ```python |
| 19 | +/// "a,b,c,d".split(",") |
| 20 | +/// ``` |
| 21 | +/// |
| 22 | +/// Use instead: |
| 23 | +/// ```python |
| 24 | +/// ["a", "b", "c", "d"] |
| 25 | +/// |
| 26 | +/// ## References |
| 27 | +/// |
| 28 | +/// - [Python documentation: `str.split`](https://docs.python.org/3/library/stdtypes.html#str.split) |
| 29 | +/// |
| 30 | +/// ``` |
| 31 | +#[violation] |
| 32 | +pub struct SplitOfStaticString; |
| 33 | + |
| 34 | +impl Violation for SplitOfStaticString { |
| 35 | + const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; |
| 36 | + |
| 37 | + #[derive_message_formats] |
| 38 | + fn message(&self) -> String { |
| 39 | + format!("Consider using a list instead of string split") |
| 40 | + } |
| 41 | + |
| 42 | + fn fix_title(&self) -> Option<String> { |
| 43 | + Some(format!("Replace string split with list literal")) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +fn construct_replacement(list_items: &[&str]) -> Expr { |
| 48 | + Expr::List(ExprList { |
| 49 | + elts: list_items |
| 50 | + .iter() |
| 51 | + .map(|list_item| { |
| 52 | + Expr::StringLiteral(ExprStringLiteral { |
| 53 | + value: StringLiteralValue::single(StringLiteral { |
| 54 | + value: (*list_item).to_string().into_boxed_str(), |
| 55 | + range: TextRange::default(), |
| 56 | + flags: StringLiteralFlags::default(), |
| 57 | + }), |
| 58 | + range: TextRange::default(), |
| 59 | + }) |
| 60 | + }) |
| 61 | + .collect(), |
| 62 | + ctx: ExprContext::Load, |
| 63 | + range: TextRange::default(), |
| 64 | + }) |
| 65 | +} |
| 66 | + |
| 67 | +fn split_default(str_value: &str, max_split: usize) -> Option<Expr> { |
| 68 | + // From the Python documentation: |
| 69 | + // > If sep is not specified or is None, a different splitting algorithm is applied: runs of |
| 70 | + // > consecutive whitespace are regarded as a single separator, and the result will contain |
| 71 | + // > no empty strings at the start or end if the string has leading or trailing whitespace. |
| 72 | + // > Consequently, splitting an empty string or a string consisting of just whitespace with |
| 73 | + // > a None separator returns []. |
| 74 | + // https://docs.python.org/3/library/stdtypes.html#str.split |
| 75 | + if max_split == 0 { |
| 76 | + let list_items: Vec<&str> = str_value.split_whitespace().collect(); |
| 77 | + Some(construct_replacement(&list_items)) |
| 78 | + } else { |
| 79 | + // Autofix for maxsplit without separator not yet implemented |
| 80 | + None |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +fn split_sep(str_value: &str, sep_value: &str, max_split: usize, direction_left: bool) -> Expr { |
| 85 | + let list_items: Vec<&str> = if direction_left && max_split > 0 { |
| 86 | + str_value.splitn(max_split + 1, sep_value).collect() |
| 87 | + } else if !direction_left && max_split > 0 { |
| 88 | + str_value.rsplitn(max_split + 1, sep_value).collect() |
| 89 | + } else if direction_left && max_split == 0 { |
| 90 | + str_value.split(sep_value).collect() |
| 91 | + } else { |
| 92 | + str_value.rsplit(sep_value).collect() |
| 93 | + }; |
| 94 | + construct_replacement(&list_items) |
| 95 | +} |
| 96 | + |
| 97 | +/// RUF035 |
| 98 | +pub(crate) fn split_of_static_string( |
| 99 | + checker: &mut Checker, |
| 100 | + attr: &str, |
| 101 | + call: &ExprCall, |
| 102 | + str_value: &str, |
| 103 | +) { |
| 104 | + let ExprCall { arguments, .. } = call; |
| 105 | + |
| 106 | + let sep_arg = arguments.find_argument("sep", 0); |
| 107 | + let maxsplit_arg = arguments.find_argument("maxsplit", 1); |
| 108 | + |
| 109 | + // `split` vs `rsplit` |
| 110 | + let direction_left = attr == "split"; |
| 111 | + |
| 112 | + let maxsplit_value = if let Some(maxsplit) = maxsplit_arg { |
| 113 | + match maxsplit { |
| 114 | + Expr::NumberLiteral(maxsplit_val) => { |
| 115 | + if let Some(int_value) = maxsplit_val.value.as_int() { |
| 116 | + if let Some(usize_value) = int_value.as_usize() { |
| 117 | + usize_value |
| 118 | + } else { |
| 119 | + return; |
| 120 | + } |
| 121 | + } else { |
| 122 | + return; |
| 123 | + } |
| 124 | + } |
| 125 | + // Ignore when `maxsplit` is not a numeric value |
| 126 | + _ => { |
| 127 | + return; |
| 128 | + } |
| 129 | + } |
| 130 | + } else { |
| 131 | + 0 |
| 132 | + }; |
| 133 | + |
| 134 | + let split_replacement = if let Some(sep) = sep_arg { |
| 135 | + match sep { |
| 136 | + Expr::NoneLiteral(_) => split_default(str_value, maxsplit_value), |
| 137 | + Expr::StringLiteral(sep_value) => { |
| 138 | + let sep_value_str = sep_value.value.to_str(); |
| 139 | + Some(split_sep( |
| 140 | + str_value, |
| 141 | + sep_value_str, |
| 142 | + maxsplit_value, |
| 143 | + direction_left, |
| 144 | + )) |
| 145 | + } |
| 146 | + // Ignore names until type inference is available |
| 147 | + _ => { |
| 148 | + return; |
| 149 | + } |
| 150 | + } |
| 151 | + } else { |
| 152 | + split_default(str_value, maxsplit_value) |
| 153 | + }; |
| 154 | + |
| 155 | + let mut diagnostic = Diagnostic::new(SplitOfStaticString, call.range()); |
| 156 | + if let Some(ref replacement_expr) = split_replacement { |
| 157 | + // Construct replacement list |
| 158 | + let replacement = checker.generator().expr(replacement_expr); |
| 159 | + diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( |
| 160 | + replacement, |
| 161 | + call.range(), |
| 162 | + ))); |
| 163 | + } |
| 164 | + checker.diagnostics.push(diagnostic); |
| 165 | +} |
0 commit comments