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