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

[ruff] Implement compound comparison rule (RUF029) #10028

Closed
Closed
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
20 changes: 20 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF029.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
a is b is c # OK
a == b == c # OK
a < b < c # OK
a <= b <= c # OK
a < b <= c # OK
a <= b < c # OK
a > b > c # OK
a >= b >= c # OK
a > b >= c # OK
a >= b > c # OK
a is not b # OK
a != b # OK
a is b is not c # RUF029
a is not b is c # RUF029
a is b == c # RUF029
a == b is c # RUF029
a is b < c # RUF029
a < b is c # RUF029
a > b < c # RUF029
a < b > c # RUF029
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1297,6 +1297,9 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
if checker.enabled(Rule::SingleItemMembershipTest) {
refurb::rules::single_item_membership_test(checker, expr, left, ops, comparators);
}
if checker.enabled(Rule::NonTransitiveCompoundComparison) {
ruff::rules::non_transitive_compound_comparison(checker, compare);
}
}
Expr::NumberLiteral(number_literal @ ast::ExprNumberLiteral { .. }) => {
if checker.source_type.is_stub() && checker.enabled(Rule::NumericLiteralTooLong) {
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Ruff, "025") => (RuleGroup::Preview, rules::ruff::rules::UnnecessaryDictComprehensionForIterable),
(Ruff, "026") => (RuleGroup::Preview, rules::ruff::rules::DefaultFactoryKwarg),
(Ruff, "027") => (RuleGroup::Preview, rules::ruff::rules::MissingFStringSyntax),
(Ruff, "029") => (RuleGroup::Preview, rules::ruff::rules::NonTransitiveCompoundComparison),
(Ruff, "100") => (RuleGroup::Stable, rules::ruff::rules::UnusedNOQA),
(Ruff, "200") => (RuleGroup::Stable, rules::ruff::rules::InvalidPyprojectToml),
#[cfg(feature = "test-rules")]
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/ruff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ mod tests {
#[test_case(Rule::MissingFStringSyntax, Path::new("RUF027_0.py"))]
#[test_case(Rule::MissingFStringSyntax, Path::new("RUF027_1.py"))]
#[test_case(Rule::MissingFStringSyntax, Path::new("RUF027_2.py"))]
#[test_case(Rule::NonTransitiveCompoundComparison, Path::new("RUF029.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Expand Down
2 changes: 2 additions & 0 deletions crates/ruff_linter/src/rules/ruff/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub(crate) use mutable_class_default::*;
pub(crate) use mutable_dataclass_default::*;
pub(crate) use mutable_fromkeys_value::*;
pub(crate) use never_union::*;
pub(crate) use non_transitive_compound_comparison::*;
pub(crate) use pairwise_over_zipped::*;
pub(crate) use parenthesize_logical_operators::*;
pub(crate) use quadratic_list_summation::*;
Expand Down Expand Up @@ -43,6 +44,7 @@ mod mutable_class_default;
mod mutable_dataclass_default;
mod mutable_fromkeys_value;
mod never_union;
mod non_transitive_compound_comparison;
mod pairwise_over_zipped;
mod parenthesize_logical_operators;
mod quadratic_list_summation;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast as ast;
use ruff_python_ast::CmpOp;
use ruff_text_size::Ranged;

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

/// ## What it does
/// Checks for non-transitive compound comparisons.
///
/// ## Why is this bad?
/// Compound comparisons chain comparisons arbitrarily. For example,
/// `a < b < c` is equivalent to `a < b and b < c` (with the exception that `b`
/// is only evaluated once). This can lead to unexpected behavior with some
/// combinations of comparisons.
///
/// ## Example
/// ```python
/// False == False in [False] # True
/// ```
///
/// Use instead:
/// ```python
/// (False == False) in [False] # False
/// ```
///
/// Or:
/// ```python
/// False == (False in [False]) # False
/// ```
///
/// Or, if the compound behavior is intended:
/// ```python
/// False == False and False in [False] # True
/// ```
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
#[violation]
pub struct NonTransitiveCompoundComparison;

impl Violation for NonTransitiveCompoundComparison {
#[derive_message_formats]
fn message(&self) -> String {
format!("Avoid non-transitive compound comparisons, which can be confusing")
}
}

/// RUF029
pub(crate) fn non_transitive_compound_comparison(
checker: &mut Checker,
compare: &ast::ExprCompare,
) {
// Make sure it's a compound comparison.
if compare.ops.len() < 2 {
return;
}
// A mix of `<` and `<=` is okay.
if compare
.ops
.iter()
.all(|op| *op == CmpOp::Lt || *op == CmpOp::LtE)
{
return;
}
// A mix of `>` and `>=` is okay.
if compare
.ops
.iter()
.all(|op| *op == CmpOp::Gt || *op == CmpOp::GtE)
{
return;
}
// All `is` is okay.
if compare.ops.iter().all(|op| *op == CmpOp::Is) {
return;
}
// All `==` is okay.
if compare.ops.iter().all(|op| *op == CmpOp::Eq) {
return;
}
checker.diagnostics.push(Diagnostic::new(
NonTransitiveCompoundComparison,
compare.range(),
));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
source: crates/ruff_linter/src/rules/ruff/mod.rs
---
RUF029.py:13:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
11 | a is not b # OK
12 | a != b # OK
13 | a is b is not c # RUF029
| ^^^^^^^^^^^^^^^ RUF029
14 | a is not b is c # RUF029
15 | a is b == c # RUF029
|

RUF029.py:14:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
12 | a != b # OK
13 | a is b is not c # RUF029
14 | a is not b is c # RUF029
| ^^^^^^^^^^^^^^^ RUF029
15 | a is b == c # RUF029
16 | a == b is c # RUF029
|

RUF029.py:15:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
13 | a is b is not c # RUF029
14 | a is not b is c # RUF029
15 | a is b == c # RUF029
| ^^^^^^^^^^^ RUF029
16 | a == b is c # RUF029
17 | a is b < c # RUF029
|

RUF029.py:16:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
14 | a is not b is c # RUF029
15 | a is b == c # RUF029
16 | a == b is c # RUF029
| ^^^^^^^^^^^ RUF029
17 | a is b < c # RUF029
18 | a < b is c # RUF029
|

RUF029.py:17:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
15 | a is b == c # RUF029
16 | a == b is c # RUF029
17 | a is b < c # RUF029
| ^^^^^^^^^^ RUF029
18 | a < b is c # RUF029
19 | a > b < c # RUF029
|

RUF029.py:18:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
16 | a == b is c # RUF029
17 | a is b < c # RUF029
18 | a < b is c # RUF029
| ^^^^^^^^^^ RUF029
19 | a > b < c # RUF029
20 | a < b > c # RUF029
|

RUF029.py:19:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
17 | a is b < c # RUF029
18 | a < b is c # RUF029
19 | a > b < c # RUF029
| ^^^^^^^^^ RUF029
20 | a < b > c # RUF029
|

RUF029.py:20:1: RUF029 Avoid non-transitive compound comparisons, which can be confusing
|
18 | a < b is c # RUF029
19 | a > b < c # RUF029
20 | a < b > c # RUF029
| ^^^^^^^^^ RUF029
|


1 change: 1 addition & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading