Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid non-augmented-assignment for reversed, non-commutative operators #10909

Merged
merged 1 commit into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
a_list = a_list + ["to concat"]
some_set = some_set | {"to concat"}
to_multiply = to_multiply * 5
to_multiply = 5 * to_multiply
to_multiply = to_multiply * to_multiply
to_divide = to_divide / 5
to_divide = to_divide // 5
to_cube = to_cube**3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,11 @@ pub(crate) fn non_augmented_assignment(checker: &mut Checker, assign: &ast::Stmt
return;
};

let operator = AugmentedOperator::from(value.op);

// Match, e.g., `x = x + 1`.
if ComparableExpr::from(target) == ComparableExpr::from(&value.left) {
let mut diagnostic = Diagnostic::new(
NonAugmentedAssignment {
operator: AugmentedOperator::from(value.op),
},
assign.range(),
);
let mut diagnostic = Diagnostic::new(NonAugmentedAssignment { operator }, assign.range());
diagnostic.set_fix(Fix::unsafe_edit(augmented_assignment(
checker.generator(),
target,
Expand All @@ -104,14 +101,11 @@ pub(crate) fn non_augmented_assignment(checker: &mut Checker, assign: &ast::Stmt
return;
}

// Match, e.g., `x = 1 + x`.
if ComparableExpr::from(target) == ComparableExpr::from(&value.right) {
let mut diagnostic = Diagnostic::new(
NonAugmentedAssignment {
operator: AugmentedOperator::from(value.op),
},
assign.range(),
);
// If the operator is commutative, match, e.g., `x = 1 + x`.
if operator.is_commutative()
&& ComparableExpr::from(target) == ComparableExpr::from(&value.right)
{
let mut diagnostic = Diagnostic::new(NonAugmentedAssignment { operator }, assign.range());
diagnostic.set_fix(Fix::unsafe_edit(augmented_assignment(
checker.generator(),
target,
Expand Down Expand Up @@ -161,6 +155,16 @@ enum AugmentedOperator {
Sub,
}

impl AugmentedOperator {
/// Returns `true` if the operator is commutative.
fn is_commutative(self) -> bool {
matches!(
self,
Self::Add | Self::BitAnd | Self::BitOr | Self::BitXor | Self::Mult
)
}
}

impl From<Operator> for AugmentedOperator {
fn from(value: Operator) -> Self {
match value {
Expand Down
Loading
Loading