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

[refurb] Mark fix as unsafe when the right-hand side is a string (FURB171) #15273

Merged
merged 2 commits into from
Jan 5, 2025
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
@@ -1,4 +1,4 @@
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_python_ast::helpers::generate_comparison;
use ruff_python_ast::{self as ast, CmpOp, Expr, ExprStringLiteral};
Expand All @@ -25,6 +25,12 @@ use crate::fix::edits::pad;
/// 1 == 1
/// ```
///
/// ## Fix safety
///
/// When the right-hand side is a string, the fix is marked as unsafe.
/// This is because `c in "a"` is true both when `c` is `"a"` and when `c` is the empty string,
/// so the fix can change the behavior of your program in these cases.
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
/// - [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations)
Expand Down Expand Up @@ -74,9 +80,9 @@ pub(crate) fn single_item_membership_test(
return;
};

let mut diagnostic =
Diagnostic::new(SingleItemMembershipTest { membership_test }, expr.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
let diagnostic = Diagnostic::new(SingleItemMembershipTest { membership_test }, expr.range());

let edit = Edit::range_replacement(
pad(
generate_comparison(
left,
Expand All @@ -90,8 +96,17 @@ pub(crate) fn single_item_membership_test(
checker.locator(),
),
expr.range(),
)));
checker.diagnostics.push(diagnostic);
);

let applicability = if right.is_string_literal_expr() {
Applicability::Unsafe
} else {
Applicability::Safe
};

let fix = Fix::applicable_edit(edit, applicability);

checker.diagnostics.push(diagnostic.with_fix(fix));
}

/// Return the single item wrapped in `Some` if the expression contains a single
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ FURB171.py:12:4: FURB171 [*] Membership test against single-item container
|
= help: Convert to equality test

Safe fix
Unsafe fix
9 9 | if 1 in {1}:
10 10 | print("Single-element set")
11 11 |
Expand Down
Loading