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

[flake8-bugbear] Add fix for duplicate-value (B033) #9510

Merged
merged 6 commits into from
Jan 14, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Errors.
###
incorrect_set = {"value1", 23, 5, "value1"}
incorrect_set = {1, 1}
incorrect_set = {1, 1, 2, 1}

###
# Non-errors.
Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -980,9 +980,9 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
flake8_pie::rules::unnecessary_spread(checker, dict);
}
}
Expr::Set(ast::ExprSet { elts, range: _ }) => {
Expr::Set(ast::ExprSet { elts, range }) => {
if checker.enabled(Rule::DuplicateValue) {
flake8_bugbear::rules::duplicate_value(checker, elts);
flake8_bugbear::rules::duplicate_value(checker, elts, *range);
}
}
Expr::Yield(_) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use ruff_python_ast::Expr;
use ruff_python_ast::{Expr, ExprSet};
use rustc_hash::FxHashSet;

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_text_size::Ranged;
use ruff_text_size::{Ranged, TextRange};

use crate::checkers::ast::Checker;

Expand All @@ -30,29 +30,65 @@ pub struct DuplicateValue {
value: String,
}

impl Violation for DuplicateValue {
impl AlwaysFixableViolation for DuplicateValue {
#[derive_message_formats]
fn message(&self) -> String {
let DuplicateValue { value } = self;
format!("Sets should not contain duplicate item `{value}`")
}

fn fix_title(&self) -> String {
let DuplicateValue { value } = self;
format!("Remove duplicate item `{value}`")
}
}

/// B033
pub(crate) fn duplicate_value(checker: &mut Checker, elts: &Vec<Expr>) {
pub(crate) fn duplicate_value(checker: &mut Checker, elts: &[Expr], range: TextRange) {
let mut seen_values: FxHashSet<ComparableExpr> = FxHashSet::default();
for elt in elts {
let mut duplicate_indices: Vec<usize> = Vec::new();
let mut unique_indices: Vec<usize> = Vec::new();

for (index, elt) in elts.iter().enumerate() {
if elt.is_literal_expr() {
let comparable_value: ComparableExpr = elt.into();

if !seen_values.insert(comparable_value) {
checker.diagnostics.push(Diagnostic::new(
DuplicateValue {
value: checker.generator().expr(elt),
},
elt.range(),
));
if seen_values.insert(comparable_value) {
unique_indices.push(index);
} else {
duplicate_indices.push(index);
}
};
} else {
unique_indices.push(index);
}
}

if duplicate_indices.is_empty() {
return;
}

let fix = Fix::safe_edit(Edit::range_replacement(
checker.generator().expr(&Expr::Set(ExprSet {
elts: unique_indices
.into_iter()
.map(|index| elts[index].clone())
.collect(),
range: TextRange::default(),
})),
range,
));

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to do something similar to remove_argument, if possible, since the generator-based approach will lose comments. Are you open to trying that?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like remove_argument is strictly for ExprCalls and associated Arguments, unsure if it'd work to cast everything over.

All usages of remove_argument come from actual ExprCalls, and we're working with a vector of Expr here from a set.

Please advise! 🙏🏽

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh sorry, I meant, like, writing a new method that removes an element from a comma-separated collections, but based on the token stream, similar to remove_argument.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh. I'll see what I can do!

for index in duplicate_indices {
let elt = &elts[index];
let mut diagnostic = Diagnostic::new(
DuplicateValue {
value: checker.generator().expr(elt),
},
elt.range(),
);

diagnostic.set_fix(fix.clone());

checker.diagnostics.push(diagnostic);
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,66 @@
---
source: crates/ruff_linter/src/rules/flake8_bugbear/mod.rs
---
B033.py:4:35: B033 Sets should not contain duplicate item `"value1"`
B033.py:4:35: B033 [*] Sets should not contain duplicate item `"value1"`
|
2 | # Errors.
3 | ###
4 | incorrect_set = {"value1", 23, 5, "value1"}
| ^^^^^^^^ B033
5 | incorrect_set = {1, 1}
5 | incorrect_set = {1, 1, 2, 1}
|
= help: Remove duplicate item `"value1"`

B033.py:5:21: B033 Sets should not contain duplicate item `1`
ℹ Safe fix
1 1 | ###
2 2 | # Errors.
3 3 | ###
4 |-incorrect_set = {"value1", 23, 5, "value1"}
4 |+incorrect_set = {"value1", 23, 5}
5 5 | incorrect_set = {1, 1, 2, 1}
6 6 |
7 7 | ###

B033.py:5:21: B033 [*] Sets should not contain duplicate item `1`
|
3 | ###
4 | incorrect_set = {"value1", 23, 5, "value1"}
5 | incorrect_set = {1, 1}
5 | incorrect_set = {1, 1, 2, 1}
| ^ B033
6 |
7 | ###
|
= help: Remove duplicate item `1`

ℹ Safe fix
2 2 | # Errors.
3 3 | ###
4 4 | incorrect_set = {"value1", 23, 5, "value1"}
5 |-incorrect_set = {1, 1, 2, 1}
5 |+incorrect_set = {1, 2}
6 6 |
7 7 | ###
8 8 | # Non-errors.

B033.py:5:27: B033 [*] Sets should not contain duplicate item `1`
|
3 | ###
4 | incorrect_set = {"value1", 23, 5, "value1"}
5 | incorrect_set = {1, 1, 2, 1}
| ^ B033
6 |
7 | ###
|
= help: Remove duplicate item `1`

ℹ Safe fix
2 2 | # Errors.
3 3 | ###
4 4 | incorrect_set = {"value1", 23, 5, "value1"}
5 |-incorrect_set = {1, 1, 2, 1}
5 |+incorrect_set = {1, 2}
6 6 |
7 7 | ###
8 8 | # Non-errors.