|
| 1 | +use std::cmp::Ordering; |
| 2 | + |
| 3 | +use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; |
| 4 | +use ruff_macros::{derive_message_formats, violation}; |
| 5 | +use ruff_python_ast::{ |
| 6 | + Expr, ExprCall, ExprContext, ExprList, ExprStringLiteral, ExprUnaryOp, StringLiteral, |
| 7 | + StringLiteralFlags, StringLiteralValue, UnaryOp, |
| 8 | +}; |
| 9 | +use ruff_text_size::{Ranged, TextRange}; |
| 10 | + |
| 11 | +use crate::checkers::ast::Checker; |
| 12 | + |
| 13 | +/// ## What it does |
| 14 | +/// Checks for static `str.split` calls that can be replaced with list literals. |
| 15 | +/// |
| 16 | +/// ## Why is this bad? |
| 17 | +/// List literals are more readable and do not require the overhead of calling `str.split`. |
| 18 | +/// |
| 19 | +/// ## Example |
| 20 | +/// ```python |
| 21 | +/// "a,b,c,d".split(",") |
| 22 | +/// ``` |
| 23 | +/// |
| 24 | +/// Use instead: |
| 25 | +/// ```python |
| 26 | +/// ["a", "b", "c", "d"] |
| 27 | +/// ``` |
| 28 | +/// |
| 29 | +/// ## Fix safety |
| 30 | +/// This rule's fix is marked as unsafe for implicit string concatenations with comments interleaved |
| 31 | +/// between segments, as comments may be removed. |
| 32 | +/// |
| 33 | +/// For example, the fix would be marked as unsafe in the following case: |
| 34 | +/// ```python |
| 35 | +/// ( |
| 36 | +/// "a" # comment |
| 37 | +/// "," # comment |
| 38 | +/// "b" # comment |
| 39 | +/// ).split(",") |
| 40 | +/// ``` |
| 41 | +/// |
| 42 | +/// ## References |
| 43 | +/// - [Python documentation: `str.split`](https://docs.python.org/3/library/stdtypes.html#str.split) |
| 44 | +/// ``` |
| 45 | +#[violation] |
| 46 | +pub struct SplitStaticString; |
| 47 | + |
| 48 | +impl Violation for SplitStaticString { |
| 49 | + const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; |
| 50 | + |
| 51 | + #[derive_message_formats] |
| 52 | + fn message(&self) -> String { |
| 53 | + format!("Consider using a list literal instead of `str.split`") |
| 54 | + } |
| 55 | + |
| 56 | + fn fix_title(&self) -> Option<String> { |
| 57 | + Some("Replace with list literal".to_string()) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/// SIM905 |
| 62 | +pub(crate) fn split_static_string( |
| 63 | + checker: &mut Checker, |
| 64 | + attr: &str, |
| 65 | + call: &ExprCall, |
| 66 | + str_value: &str, |
| 67 | +) { |
| 68 | + let ExprCall { arguments, .. } = call; |
| 69 | + |
| 70 | + let maxsplit_arg = arguments.find_argument("maxsplit", 1); |
| 71 | + let Some(maxsplit_value) = get_maxsplit_value(maxsplit_arg) else { |
| 72 | + return; |
| 73 | + }; |
| 74 | + |
| 75 | + // `split` vs `rsplit`. |
| 76 | + let direction = if attr == "split" { |
| 77 | + Direction::Left |
| 78 | + } else { |
| 79 | + Direction::Right |
| 80 | + }; |
| 81 | + |
| 82 | + let sep_arg = arguments.find_argument("sep", 0); |
| 83 | + let split_replacement = if let Some(sep) = sep_arg { |
| 84 | + match sep { |
| 85 | + Expr::NoneLiteral(_) => split_default(str_value, maxsplit_value), |
| 86 | + Expr::StringLiteral(sep_value) => { |
| 87 | + let sep_value_str = sep_value.value.to_str(); |
| 88 | + Some(split_sep( |
| 89 | + str_value, |
| 90 | + sep_value_str, |
| 91 | + maxsplit_value, |
| 92 | + direction, |
| 93 | + )) |
| 94 | + } |
| 95 | + // Ignore names until type inference is available. |
| 96 | + _ => { |
| 97 | + return; |
| 98 | + } |
| 99 | + } |
| 100 | + } else { |
| 101 | + split_default(str_value, maxsplit_value) |
| 102 | + }; |
| 103 | + |
| 104 | + let mut diagnostic = Diagnostic::new(SplitStaticString, call.range()); |
| 105 | + if let Some(ref replacement_expr) = split_replacement { |
| 106 | + diagnostic.set_fix(Fix::applicable_edit( |
| 107 | + Edit::range_replacement(checker.generator().expr(replacement_expr), call.range()), |
| 108 | + // The fix does not preserve comments within implicit string concatenations. |
| 109 | + if checker.comment_ranges().intersects(call.range()) { |
| 110 | + Applicability::Unsafe |
| 111 | + } else { |
| 112 | + Applicability::Safe |
| 113 | + }, |
| 114 | + )); |
| 115 | + } |
| 116 | + checker.diagnostics.push(diagnostic); |
| 117 | +} |
| 118 | + |
| 119 | +fn construct_replacement(elts: &[&str]) -> Expr { |
| 120 | + Expr::List(ExprList { |
| 121 | + elts: elts |
| 122 | + .iter() |
| 123 | + .map(|elt| { |
| 124 | + Expr::StringLiteral(ExprStringLiteral { |
| 125 | + value: StringLiteralValue::single(StringLiteral { |
| 126 | + value: (*elt).to_string().into_boxed_str(), |
| 127 | + range: TextRange::default(), |
| 128 | + flags: StringLiteralFlags::default(), |
| 129 | + }), |
| 130 | + range: TextRange::default(), |
| 131 | + }) |
| 132 | + }) |
| 133 | + .collect(), |
| 134 | + ctx: ExprContext::Load, |
| 135 | + range: TextRange::default(), |
| 136 | + }) |
| 137 | +} |
| 138 | + |
| 139 | +fn split_default(str_value: &str, max_split: i32) -> Option<Expr> { |
| 140 | + // From the Python documentation: |
| 141 | + // > If sep is not specified or is None, a different splitting algorithm is applied: runs of |
| 142 | + // > consecutive whitespace are regarded as a single separator, and the result will contain |
| 143 | + // > no empty strings at the start or end if the string has leading or trailing whitespace. |
| 144 | + // > Consequently, splitting an empty string or a string consisting of just whitespace with |
| 145 | + // > a None separator returns []. |
| 146 | + // https://docs.python.org/3/library/stdtypes.html#str.split |
| 147 | + match max_split.cmp(&0) { |
| 148 | + Ordering::Greater => { |
| 149 | + // Autofix for `maxsplit` without separator not yet implemented, as |
| 150 | + // `split_whitespace().remainder()` is not stable: |
| 151 | + // https://doc.rust-lang.org/std/str/struct.SplitWhitespace.html#method.remainder |
| 152 | + None |
| 153 | + } |
| 154 | + Ordering::Equal => { |
| 155 | + let list_items: Vec<&str> = vec![str_value]; |
| 156 | + Some(construct_replacement(&list_items)) |
| 157 | + } |
| 158 | + Ordering::Less => { |
| 159 | + let list_items: Vec<&str> = str_value.split_whitespace().collect(); |
| 160 | + Some(construct_replacement(&list_items)) |
| 161 | + } |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +fn split_sep(str_value: &str, sep_value: &str, max_split: i32, direction: Direction) -> Expr { |
| 166 | + let list_items: Vec<&str> = if let Ok(split_n) = usize::try_from(max_split) { |
| 167 | + match direction { |
| 168 | + Direction::Left => str_value.splitn(split_n + 1, sep_value).collect(), |
| 169 | + Direction::Right => str_value.rsplitn(split_n + 1, sep_value).collect(), |
| 170 | + } |
| 171 | + } else { |
| 172 | + match direction { |
| 173 | + Direction::Left => str_value.split(sep_value).collect(), |
| 174 | + Direction::Right => str_value.rsplit(sep_value).collect(), |
| 175 | + } |
| 176 | + }; |
| 177 | + |
| 178 | + construct_replacement(&list_items) |
| 179 | +} |
| 180 | + |
| 181 | +/// Returns the value of the `maxsplit` argument as an `i32`, if it is a numeric value. |
| 182 | +fn get_maxsplit_value(arg: Option<&Expr>) -> Option<i32> { |
| 183 | + if let Some(maxsplit) = arg { |
| 184 | + match maxsplit { |
| 185 | + // Negative number. |
| 186 | + Expr::UnaryOp(ExprUnaryOp { |
| 187 | + op: UnaryOp::USub, |
| 188 | + operand, |
| 189 | + .. |
| 190 | + }) => { |
| 191 | + match &**operand { |
| 192 | + Expr::NumberLiteral(maxsplit_val) => maxsplit_val |
| 193 | + .value |
| 194 | + .as_int() |
| 195 | + .and_then(ruff_python_ast::Int::as_i32) |
| 196 | + .map(|f| -f), |
| 197 | + // Ignore when `maxsplit` is not a numeric value. |
| 198 | + _ => None, |
| 199 | + } |
| 200 | + } |
| 201 | + // Positive number |
| 202 | + Expr::NumberLiteral(maxsplit_val) => maxsplit_val |
| 203 | + .value |
| 204 | + .as_int() |
| 205 | + .and_then(ruff_python_ast::Int::as_i32), |
| 206 | + // Ignore when `maxsplit` is not a numeric value. |
| 207 | + _ => None, |
| 208 | + } |
| 209 | + } else { |
| 210 | + // Default value is -1 (no splits). |
| 211 | + Some(-1) |
| 212 | + } |
| 213 | +} |
| 214 | + |
| 215 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 216 | +enum Direction { |
| 217 | + Left, |
| 218 | + Right, |
| 219 | +} |
0 commit comments