|
| 1 | +use ruff_diagnostics::{Applicability, Edit, Fix}; |
| 2 | +use ruff_python_ast::Stmt; |
| 3 | +use ruff_python_ast::name::Name; |
| 4 | +use ruff_text_size::{Ranged, TextRange, TextSize}; |
| 5 | + |
| 6 | +use ruff_macros::{ViolationMetadata, derive_message_formats}; |
| 7 | + |
| 8 | +use crate::checkers::ast::Checker; |
| 9 | +use crate::{FixAvailability, Violation}; |
| 10 | + |
| 11 | +/// ## What it does |
| 12 | +/// Checks for code that swaps two variables using a temporary variable. |
| 13 | +/// |
| 14 | +/// ## Why is this bad? |
| 15 | +/// Variables can be swapped by using "tuple unpacking" instead of using a temporary variable. That also makes the intention of the swapping logic more clear. |
| 16 | +/// |
| 17 | +/// ## Example |
| 18 | +/// ```python |
| 19 | +/// def function(x, y): |
| 20 | +/// if x > y: |
| 21 | +/// temp = x |
| 22 | +/// x = y |
| 23 | +/// y = temp |
| 24 | +/// assert x <= y |
| 25 | +/// ``` |
| 26 | +/// |
| 27 | +/// Use instead: |
| 28 | +/// ```python |
| 29 | +/// def function(x, y): |
| 30 | +/// if x > y: |
| 31 | +/// x, y = y, x |
| 32 | +/// assert x <= y |
| 33 | +/// ``` |
| 34 | +/// |
| 35 | +/// ## Fix safety |
| 36 | +/// The rule's fix is marked as safe, unless it contains comments. In this |
| 37 | +/// exception case, applying the quick fix would remove comments between the |
| 38 | +/// assignment statements. |
| 39 | +#[derive(ViolationMetadata)] |
| 40 | +#[violation_metadata(preview_since = "0.0.0")] |
| 41 | +pub(crate) struct ConsiderSwapVariables { |
| 42 | + var_a_name: Name, |
| 43 | + var_b_name: Name, |
| 44 | +} |
| 45 | + |
| 46 | +#[derive(Eq, PartialEq, Debug, Clone)] |
| 47 | +struct VarToVarAssignment { |
| 48 | + target_var_name: Name, |
| 49 | + value_var_name: Name, |
| 50 | + start: TextSize, |
| 51 | + end: TextSize, |
| 52 | +} |
| 53 | + |
| 54 | +impl Violation for ConsiderSwapVariables { |
| 55 | + const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always; |
| 56 | + |
| 57 | + #[derive_message_formats] |
| 58 | + fn message(&self) -> String { |
| 59 | + format!( |
| 60 | + r#"Consider swapping `{first_var}` and `{second_var}` using "tuple unpacking": `{first_var}, {second_var} = {second_var}, {first_var}`"#, |
| 61 | + first_var = self.var_a_name, |
| 62 | + second_var = self.var_b_name |
| 63 | + ) |
| 64 | + } |
| 65 | + |
| 66 | + fn fix_title(&self) -> Option<String> { |
| 67 | + Some("Swap variables via tuple unpacking".to_string()) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +pub(crate) fn consider_swap_variables(checker: &Checker, stmts: &[Stmt]) { |
| 72 | + for stmt_sequence in stmts.windows(3) { |
| 73 | + let stmt_sequence = stmt_sequence |
| 74 | + .iter() |
| 75 | + .filter_map(var_to_var_assignment) |
| 76 | + .collect::<Vec<_>>(); |
| 77 | + |
| 78 | + // if unwrapping fails, one of the statements hasn't been a var to var assignment |
| 79 | + let [stmt_a, stmt_b, stmt_c] = stmt_sequence.as_slice() else { |
| 80 | + continue; |
| 81 | + }; |
| 82 | + |
| 83 | + // Detect patterns like: |
| 84 | + // temp = x |
| 85 | + // x = y |
| 86 | + // y = temp |
| 87 | + if stmt_a.value_var_name == stmt_b.target_var_name |
| 88 | + && stmt_b.value_var_name == stmt_c.target_var_name |
| 89 | + && stmt_a.target_var_name == stmt_c.value_var_name |
| 90 | + { |
| 91 | + let diagnostic = ConsiderSwapVariables { |
| 92 | + var_a_name: stmt_b.target_var_name.clone(), |
| 93 | + var_b_name: stmt_c.target_var_name.clone(), |
| 94 | + }; |
| 95 | + let edit = Edit::replacement( |
| 96 | + format!( |
| 97 | + "{0}, {1} = {1}, {0}", |
| 98 | + &diagnostic.var_a_name, &diagnostic.var_b_name |
| 99 | + ), |
| 100 | + stmt_a.start, |
| 101 | + stmt_c.end, |
| 102 | + ); |
| 103 | + let mut diagnostic_guard = |
| 104 | + checker.report_diagnostic(diagnostic, TextRange::new(stmt_a.start, stmt_c.end)); |
| 105 | + |
| 106 | + // the quick fix would remove comments, hence it's unsafe |
| 107 | + let applicability = if checker.comment_ranges().intersects(edit.range()) { |
| 108 | + Applicability::Unsafe |
| 109 | + } else { |
| 110 | + Applicability::Safe |
| 111 | + }; |
| 112 | + diagnostic_guard.set_fix(Fix::applicable_edit(edit, applicability)); |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +fn var_to_var_assignment(stmt: &Stmt) -> Option<VarToVarAssignment> { |
| 118 | + let (target, value) = match stmt { |
| 119 | + Stmt::Assign(stmt_assign) => { |
| 120 | + // only one variable is expected for matching the pattern |
| 121 | + let [target_variable] = stmt_assign.targets.as_slice() else { |
| 122 | + return None; |
| 123 | + }; |
| 124 | + |
| 125 | + (target_variable.clone(), stmt_assign.value.clone()) |
| 126 | + } |
| 127 | + Stmt::AnnAssign(stmt_ann_assign) => { |
| 128 | + // only assignments that actually assign a value are relevant here |
| 129 | + let Some(value) = &stmt_ann_assign.value else { |
| 130 | + return None; |
| 131 | + }; |
| 132 | + |
| 133 | + ((*stmt_ann_assign.target).clone(), value.clone()) |
| 134 | + } |
| 135 | + // Stmt::AugAssign is not relevant because it modifies the content |
| 136 | + // of a variable based on its existing value, so it can't swap variables |
| 137 | + _ => return None, |
| 138 | + }; |
| 139 | + |
| 140 | + // assignment value is more complex than just a simple variable, skip such cases. |
| 141 | + if !target.is_name_expr() || !value.is_name_expr() { |
| 142 | + return None; |
| 143 | + } |
| 144 | + |
| 145 | + Some(VarToVarAssignment { |
| 146 | + target_var_name: target.expect_name_expr().id, |
| 147 | + value_var_name: value.expect_name_expr().id, |
| 148 | + start: stmt.start(), |
| 149 | + end: stmt.end(), |
| 150 | + }) |
| 151 | +} |
0 commit comments