|
| 1 | +use rustc_hash::{FxBuildHasher, FxHashMap}; |
| 2 | + |
| 3 | +use ruff_diagnostics::{Applicability, Fix}; |
| 4 | +use ruff_macros::{ViolationMetadata, derive_message_formats}; |
| 5 | +use ruff_python_ast as ast; |
| 6 | +use ruff_text_size::Ranged; |
| 7 | + |
| 8 | +use crate::checkers::ast::Checker; |
| 9 | +use crate::fix::edits; |
| 10 | +use crate::{FixAvailability, Violation}; |
| 11 | + |
| 12 | +/// ## What it does |
| 13 | +/// Detects duplicate elements in `__all__` definitions. |
| 14 | +/// |
| 15 | +/// ## Why is this bad? |
| 16 | +/// Duplicate elements in `__all__` serve no purpose and can indicate copy-paste errors or |
| 17 | +/// incomplete refactoring. |
| 18 | +/// |
| 19 | +/// ## Example |
| 20 | +/// ```python |
| 21 | +/// __all__ = [ |
| 22 | +/// "DatabaseConnection", |
| 23 | +/// "Product", |
| 24 | +/// "User", |
| 25 | +/// "DatabaseConnection", # Duplicate |
| 26 | +/// ] |
| 27 | +/// ``` |
| 28 | +/// |
| 29 | +/// Use instead: |
| 30 | +/// ```python |
| 31 | +/// __all__ = [ |
| 32 | +/// "DatabaseConnection", |
| 33 | +/// "Product", |
| 34 | +/// "User", |
| 35 | +/// ] |
| 36 | +/// ``` |
| 37 | +/// |
| 38 | +/// ## Fix Safety |
| 39 | +/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the |
| 40 | +/// original expression, potentially losing important context or documentation. |
| 41 | +/// |
| 42 | +/// For example: |
| 43 | +/// ```python |
| 44 | +/// __all__ = [ |
| 45 | +/// "PublicAPI", |
| 46 | +/// # TODO: Remove this in v2.0 |
| 47 | +/// "PublicAPI", # Deprecated alias |
| 48 | +/// ] |
| 49 | +/// ``` |
| 50 | +#[derive(ViolationMetadata)] |
| 51 | +#[violation_metadata(preview_since = "0.14.14")] |
| 52 | +pub(crate) struct DuplicateEntryInDunderAll; |
| 53 | + |
| 54 | +impl Violation for DuplicateEntryInDunderAll { |
| 55 | + const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; |
| 56 | + |
| 57 | + #[derive_message_formats] |
| 58 | + fn message(&self) -> String { |
| 59 | + "`__all__` contains duplicate entries".to_string() |
| 60 | + } |
| 61 | + |
| 62 | + fn fix_title(&self) -> Option<String> { |
| 63 | + Some("Remove duplicate entries from `__all__`".to_string()) |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/// Apply RUF068 to `StmtAssign` AST node. For example: `__all__ = ["a", "b", "a"]`. |
| 68 | +pub(crate) fn duplicate_entry_in_dunder_all_assign( |
| 69 | + checker: &Checker, |
| 70 | + ast::StmtAssign { value, targets, .. }: &ast::StmtAssign, |
| 71 | +) { |
| 72 | + if let [expr] = targets.as_slice() { |
| 73 | + duplicate_entry_in_dunder_all(checker, expr, value); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/// Apply RUF068 to `StmtAugAssign` AST node. For example: `__all__ += ["a", "b", "a"]`. |
| 78 | +pub(crate) fn duplicate_entry_in_dunder_all_aug_assign( |
| 79 | + checker: &Checker, |
| 80 | + node: &ast::StmtAugAssign, |
| 81 | +) { |
| 82 | + if node.op.is_add() { |
| 83 | + duplicate_entry_in_dunder_all(checker, &node.target, &node.value); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +/// Apply RUF068 to `__all__.extend()`. |
| 88 | +pub(crate) fn duplicate_entry_in_dunder_all_extend_call( |
| 89 | + checker: &Checker, |
| 90 | + ast::ExprCall { |
| 91 | + func, |
| 92 | + arguments: ast::Arguments { args, keywords, .. }, |
| 93 | + .. |
| 94 | + }: &ast::ExprCall, |
| 95 | +) { |
| 96 | + let ([value_passed], []) = (&**args, &**keywords) else { |
| 97 | + return; |
| 98 | + }; |
| 99 | + let ast::Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = &**func else { |
| 100 | + return; |
| 101 | + }; |
| 102 | + if attr == "extend" { |
| 103 | + duplicate_entry_in_dunder_all(checker, value, value_passed); |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/// Apply RUF068 to a `StmtAnnAssign` AST node. |
| 108 | +/// For example: `__all__: list[str] = ["a", "b", "a"]`. |
| 109 | +pub(crate) fn duplicate_entry_in_dunder_all_ann_assign( |
| 110 | + checker: &Checker, |
| 111 | + node: &ast::StmtAnnAssign, |
| 112 | +) { |
| 113 | + if let Some(value) = &node.value { |
| 114 | + duplicate_entry_in_dunder_all(checker, &node.target, value); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +/// RUF068 |
| 119 | +/// This routine checks whether `__all__` contains duplicated entries, and emits |
| 120 | +/// a violation if it does. |
| 121 | +fn duplicate_entry_in_dunder_all(checker: &Checker, target: &ast::Expr, value: &ast::Expr) { |
| 122 | + let ast::Expr::Name(ast::ExprName { id, .. }) = target else { |
| 123 | + return; |
| 124 | + }; |
| 125 | + |
| 126 | + if id != "__all__" { |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + // We're only interested in `__all__` in the global scope |
| 131 | + if !checker.semantic().current_scope().kind.is_module() { |
| 132 | + return; |
| 133 | + } |
| 134 | + |
| 135 | + let elts = match value { |
| 136 | + ast::Expr::List(ast::ExprList { elts, .. }) => elts, |
| 137 | + ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => elts, |
| 138 | + _ => return, |
| 139 | + }; |
| 140 | + |
| 141 | + // It's impossible to have duplicates if there is one or no element |
| 142 | + if elts.len() <= 1 { |
| 143 | + return; |
| 144 | + } |
| 145 | + |
| 146 | + let mut deduplicated_elts = FxHashMap::with_capacity_and_hasher(elts.len(), FxBuildHasher); |
| 147 | + let source = checker.locator().contents(); |
| 148 | + |
| 149 | + for (index, expr) in elts.iter().enumerate() { |
| 150 | + let Some(string_value) = expr.as_string_literal_expr() else { |
| 151 | + // In the example below we're ignoring `foo`: |
| 152 | + // __all__ = [foo, "bar", "bar"] |
| 153 | + continue; |
| 154 | + }; |
| 155 | + |
| 156 | + let name = string_value.value.to_str(); |
| 157 | + |
| 158 | + if let Some(previous_expr) = deduplicated_elts.insert(name, expr) { |
| 159 | + let mut diagnostic = checker.report_diagnostic(DuplicateEntryInDunderAll, expr.range()); |
| 160 | + |
| 161 | + diagnostic.secondary_annotation( |
| 162 | + format_args!("previous occurrence of `{name}` here"), |
| 163 | + previous_expr, |
| 164 | + ); |
| 165 | + |
| 166 | + diagnostic.set_primary_message(format_args!("`{name}` duplicated here")); |
| 167 | + |
| 168 | + diagnostic.try_set_fix(|| { |
| 169 | + edits::remove_member(elts, index, source).map(|edit| { |
| 170 | + let applicability = if checker.comment_ranges().intersects(edit.range()) { |
| 171 | + Applicability::Unsafe |
| 172 | + } else { |
| 173 | + Applicability::Safe |
| 174 | + }; |
| 175 | + Fix::applicable_edit(edit, applicability) |
| 176 | + }) |
| 177 | + }); |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments