[pylint] Implement boolean-chained-comparison (R1716) (#13435)

Co-authored-by: Micha Reiser <micha@reiser.io>
This commit is contained in:
Vince van Noort 2024-09-25 11:14:12 +02:00 committed by GitHub
parent be1d5e3368
commit ca0ae0a484
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 513 additions and 0 deletions

View file

@ -0,0 +1,120 @@
# ------------------
# less than examples
# ------------------
a = int(input())
b = int(input())
c = int(input())
if a < b and b < c: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
if a < b and b <= c: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
if a <= b and b < c: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
if a <= b and b <= c: # [boolean-chained-comparison]
pass
# ---------------------
# greater than examples
# ---------------------
a = int(input())
b = int(input())
c = int(input())
if a > b and b > c: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
if a >= b and b > c: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
if a > b and b >= c: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
if a >= b and b >= c: # [boolean-chained-comparison]
pass
# -----------------------
# multiple fixes examples
# -----------------------
a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a < b and b < c and c < d: # [boolean-chained-comparison]
pass
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
pass
# ------------
# bad examples
# ------------
a = int(input())
b = int(input())
c = int(input())
if a > b or b > c:
pass
a = int(input())
b = int(input())
c = int(input())
if a > b and b in (1, 2):
pass
a = int(input())
b = int(input())
c = int(input())
if a < b and b > c:
pass
a = int(input())
b = int(input())
c = int(input())
if a < b and b >= c:
pass
a = int(input())
b = int(input())
c = int(input())
if a <= b and b > c:
pass
a = int(input())
b = int(input())
c = int(input())
if a <= b and b >= c:
pass
a = int(input())
b = int(input())
c = int(input())
if a > b and b < c:
pass

View file

@ -1537,6 +1537,9 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
} }
} }
Expr::BoolOp(bool_op) => { Expr::BoolOp(bool_op) => {
if checker.enabled(Rule::BooleanChainedComparison) {
pylint::rules::boolean_chained_comparison(checker, bool_op);
}
if checker.enabled(Rule::MultipleStartsEndsWith) { if checker.enabled(Rule::MultipleStartsEndsWith) {
flake8_pie::rules::multiple_starts_ends_with(checker, expr); flake8_pie::rules::multiple_starts_ends_with(checker, expr);
} }

View file

@ -257,6 +257,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Pylint, "R1714") => (RuleGroup::Stable, rules::pylint::rules::RepeatedEqualityComparison), (Pylint, "R1714") => (RuleGroup::Stable, rules::pylint::rules::RepeatedEqualityComparison),
(Pylint, "R1722") => (RuleGroup::Stable, rules::pylint::rules::SysExitAlias), (Pylint, "R1722") => (RuleGroup::Stable, rules::pylint::rules::SysExitAlias),
(Pylint, "R1730") => (RuleGroup::Stable, rules::pylint::rules::IfStmtMinMax), (Pylint, "R1730") => (RuleGroup::Stable, rules::pylint::rules::IfStmtMinMax),
(Pylint, "R1716") => (RuleGroup::Preview, rules::pylint::rules::BooleanChainedComparison),
(Pylint, "R1733") => (RuleGroup::Preview, rules::pylint::rules::UnnecessaryDictIndexLookup), (Pylint, "R1733") => (RuleGroup::Preview, rules::pylint::rules::UnnecessaryDictIndexLookup),
(Pylint, "R1736") => (RuleGroup::Stable, rules::pylint::rules::UnnecessaryListIndexLookup), (Pylint, "R1736") => (RuleGroup::Stable, rules::pylint::rules::UnnecessaryListIndexLookup),
(Pylint, "R2004") => (RuleGroup::Stable, rules::pylint::rules::MagicValueComparison), (Pylint, "R2004") => (RuleGroup::Stable, rules::pylint::rules::MagicValueComparison),

View file

@ -36,6 +36,10 @@ mod tests {
#[test_case(Rule::BadStringFormatType, Path::new("bad_string_format_type.py"))] #[test_case(Rule::BadStringFormatType, Path::new("bad_string_format_type.py"))]
#[test_case(Rule::BidirectionalUnicode, Path::new("bidirectional_unicode.py"))] #[test_case(Rule::BidirectionalUnicode, Path::new("bidirectional_unicode.py"))]
#[test_case(Rule::BinaryOpException, Path::new("binary_op_exception.py"))] #[test_case(Rule::BinaryOpException, Path::new("binary_op_exception.py"))]
#[test_case(
Rule::BooleanChainedComparison,
Path::new("boolean_chained_comparison.py")
)]
#[test_case(Rule::CollapsibleElseIf, Path::new("collapsible_else_if.py"))] #[test_case(Rule::CollapsibleElseIf, Path::new("collapsible_else_if.py"))]
#[test_case(Rule::CompareToEmptyString, Path::new("compare_to_empty_string.py"))] #[test_case(Rule::CompareToEmptyString, Path::new("compare_to_empty_string.py"))]
#[test_case(Rule::ComparisonOfConstant, Path::new("comparison_of_constant.py"))] #[test_case(Rule::ComparisonOfConstant, Path::new("comparison_of_constant.py"))]

View file

@ -0,0 +1,120 @@
use itertools::Itertools;
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{name::Name, BoolOp, CmpOp, Expr, ExprBoolOp, ExprCompare};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
/// ## What it does
/// Check for chained boolean operations that can be simplified.
///
/// ## Why is this bad?
/// Refactoring the code will improve readability for these cases.
///
/// ## Example
///
/// ```python
/// a = int(input())
/// b = int(input())
/// c = int(input())
/// if a < b and b < c:
/// pass
/// ```
///
/// Use instead:
///
/// ```python
/// a = int(input())
/// b = int(input())
/// c = int(input())
/// if a < b < c:
/// pass
/// ```
#[violation]
pub struct BooleanChainedComparison {
variable: Name,
}
impl AlwaysFixableViolation for BooleanChainedComparison {
#[derive_message_formats]
fn message(&self) -> String {
format!("Contains chained boolean comparison that can be simplified")
}
fn fix_title(&self) -> String {
"Use a single compare expression".to_string()
}
}
/// PLR1716
pub(crate) fn boolean_chained_comparison(checker: &mut Checker, expr_bool_op: &ExprBoolOp) {
// early exit for non `and` boolean operations
if expr_bool_op.op != BoolOp::And {
return;
}
// early exit when not all expressions are compare expressions
if !expr_bool_op.values.iter().all(Expr::is_compare_expr) {
return;
}
// retrieve all compare statements from expression
let compare_expressions = expr_bool_op
.values
.iter()
.map(|stmt| stmt.as_compare_expr().unwrap());
let diagnostics = compare_expressions
.tuple_windows()
.filter(|(left_compare, right_compare)| {
are_compare_expr_simplifiable(left_compare, right_compare)
})
.filter_map(|(left_compare, right_compare)| {
let Expr::Name(left_compare_right) = left_compare.comparators.first()? else {
return None;
};
let Expr::Name(right_compare_left) = &*right_compare.left else {
return None;
};
if left_compare_right.id() != right_compare_left.id() {
return None;
}
let edit = Edit::range_replacement(
left_compare_right.id().to_string(),
TextRange::new(left_compare_right.start(), right_compare_left.end()),
);
Some(
Diagnostic::new(
BooleanChainedComparison {
variable: left_compare_right.id().clone(),
},
TextRange::new(left_compare.start(), right_compare.end()),
)
.with_fix(Fix::safe_edit(edit)),
)
});
checker.diagnostics.extend(diagnostics);
}
/// Checks whether two compare expressions are simplifiable
fn are_compare_expr_simplifiable(left: &ExprCompare, right: &ExprCompare) -> bool {
let [left_operator] = &*left.ops else {
return false;
};
let [right_operator] = &*right.ops else {
return false;
};
matches!(
(left_operator, right_operator),
(CmpOp::Lt | CmpOp::LtE, CmpOp::Lt | CmpOp::LtE)
| (CmpOp::Gt | CmpOp::GtE, CmpOp::Gt | CmpOp::GtE)
)
}

View file

@ -9,6 +9,7 @@ pub(crate) use bad_string_format_character::BadStringFormatCharacter;
pub(crate) use bad_string_format_type::*; pub(crate) use bad_string_format_type::*;
pub(crate) use bidirectional_unicode::*; pub(crate) use bidirectional_unicode::*;
pub(crate) use binary_op_exception::*; pub(crate) use binary_op_exception::*;
pub(crate) use boolean_chained_comparison::*;
pub(crate) use collapsible_else_if::*; pub(crate) use collapsible_else_if::*;
pub(crate) use compare_to_empty_string::*; pub(crate) use compare_to_empty_string::*;
pub(crate) use comparison_of_constant::*; pub(crate) use comparison_of_constant::*;
@ -112,6 +113,7 @@ pub(crate) mod bad_string_format_character;
mod bad_string_format_type; mod bad_string_format_type;
mod bidirectional_unicode; mod bidirectional_unicode;
mod binary_op_exception; mod binary_op_exception;
mod boolean_chained_comparison;
mod collapsible_else_if; mod collapsible_else_if;
mod compare_to_empty_string; mod compare_to_empty_string;
mod comparison_of_constant; mod comparison_of_constant;

View file

@ -0,0 +1,262 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
boolean_chained_comparison.py:8:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
6 | b = int(input())
7 | c = int(input())
8 | if a < b and b < c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
9 | pass
|
= help: Use a single compare expression
Safe fix
5 5 | a = int(input())
6 6 | b = int(input())
7 7 | c = int(input())
8 |-if a < b and b < c: # [boolean-chained-comparison]
8 |+if a < b < c: # [boolean-chained-comparison]
9 9 | pass
10 10 |
11 11 | a = int(input())
boolean_chained_comparison.py:14:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
12 | b = int(input())
13 | c = int(input())
14 | if a < b and b <= c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^^ PLR1716
15 | pass
|
= help: Use a single compare expression
Safe fix
11 11 | a = int(input())
12 12 | b = int(input())
13 13 | c = int(input())
14 |-if a < b and b <= c: # [boolean-chained-comparison]
14 |+if a < b <= c: # [boolean-chained-comparison]
15 15 | pass
16 16 |
17 17 | a = int(input())
boolean_chained_comparison.py:20:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
18 | b = int(input())
19 | c = int(input())
20 | if a <= b and b < c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^^ PLR1716
21 | pass
|
= help: Use a single compare expression
Safe fix
17 17 | a = int(input())
18 18 | b = int(input())
19 19 | c = int(input())
20 |-if a <= b and b < c: # [boolean-chained-comparison]
20 |+if a <= b < c: # [boolean-chained-comparison]
21 21 | pass
22 22 |
23 23 | a = int(input())
boolean_chained_comparison.py:26:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
24 | b = int(input())
25 | c = int(input())
26 | if a <= b and b <= c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^^^ PLR1716
27 | pass
|
= help: Use a single compare expression
Safe fix
23 23 | a = int(input())
24 24 | b = int(input())
25 25 | c = int(input())
26 |-if a <= b and b <= c: # [boolean-chained-comparison]
26 |+if a <= b <= c: # [boolean-chained-comparison]
27 27 | pass
28 28 |
29 29 | # ---------------------
boolean_chained_comparison.py:36:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
34 | b = int(input())
35 | c = int(input())
36 | if a > b and b > c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
37 | pass
|
= help: Use a single compare expression
Safe fix
33 33 | a = int(input())
34 34 | b = int(input())
35 35 | c = int(input())
36 |-if a > b and b > c: # [boolean-chained-comparison]
36 |+if a > b > c: # [boolean-chained-comparison]
37 37 | pass
38 38 |
39 39 | a = int(input())
boolean_chained_comparison.py:42:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
40 | b = int(input())
41 | c = int(input())
42 | if a >= b and b > c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^^ PLR1716
43 | pass
|
= help: Use a single compare expression
Safe fix
39 39 | a = int(input())
40 40 | b = int(input())
41 41 | c = int(input())
42 |-if a >= b and b > c: # [boolean-chained-comparison]
42 |+if a >= b > c: # [boolean-chained-comparison]
43 43 | pass
44 44 |
45 45 | a = int(input())
boolean_chained_comparison.py:48:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
46 | b = int(input())
47 | c = int(input())
48 | if a > b and b >= c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^^ PLR1716
49 | pass
|
= help: Use a single compare expression
Safe fix
45 45 | a = int(input())
46 46 | b = int(input())
47 47 | c = int(input())
48 |-if a > b and b >= c: # [boolean-chained-comparison]
48 |+if a > b >= c: # [boolean-chained-comparison]
49 49 | pass
50 50 |
51 51 | a = int(input())
boolean_chained_comparison.py:54:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
52 | b = int(input())
53 | c = int(input())
54 | if a >= b and b >= c: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^^^ PLR1716
55 | pass
|
= help: Use a single compare expression
Safe fix
51 51 | a = int(input())
52 52 | b = int(input())
53 53 | c = int(input())
54 |-if a >= b and b >= c: # [boolean-chained-comparison]
54 |+if a >= b >= c: # [boolean-chained-comparison]
55 55 | pass
56 56 |
57 57 | # -----------------------
boolean_chained_comparison.py:65:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
63 | c = int(input())
64 | d = int(input())
65 | if a < b and b < c and c < d: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
66 | pass
|
= help: Use a single compare expression
Safe fix
62 62 | b = int(input())
63 63 | c = int(input())
64 64 | d = int(input())
65 |-if a < b and b < c and c < d: # [boolean-chained-comparison]
65 |+if a < b < c and c < d: # [boolean-chained-comparison]
66 66 | pass
67 67 |
68 68 | a = int(input())
boolean_chained_comparison.py:65:14: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
63 | c = int(input())
64 | d = int(input())
65 | if a < b and b < c and c < d: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
66 | pass
|
= help: Use a single compare expression
Safe fix
62 62 | b = int(input())
63 63 | c = int(input())
64 64 | d = int(input())
65 |-if a < b and b < c and c < d: # [boolean-chained-comparison]
65 |+if a < b and b < c < d: # [boolean-chained-comparison]
66 66 | pass
67 67 |
68 68 | a = int(input())
boolean_chained_comparison.py:73:4: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
71 | d = int(input())
72 | e = int(input())
73 | if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
74 | pass
|
= help: Use a single compare expression
Safe fix
70 70 | c = int(input())
71 71 | d = int(input())
72 72 | e = int(input())
73 |-if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
73 |+if a < b < c and c < d and d < e: # [boolean-chained-comparison]
74 74 | pass
75 75 |
76 76 | # ------------
boolean_chained_comparison.py:73:14: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
71 | d = int(input())
72 | e = int(input())
73 | if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
74 | pass
|
= help: Use a single compare expression
Safe fix
70 70 | c = int(input())
71 71 | d = int(input())
72 72 | e = int(input())
73 |-if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
73 |+if a < b and b < c < d and d < e: # [boolean-chained-comparison]
74 74 | pass
75 75 |
76 76 | # ------------
boolean_chained_comparison.py:73:24: PLR1716 [*] Contains chained boolean comparison that can be simplified
|
71 | d = int(input())
72 | e = int(input())
73 | if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
| ^^^^^^^^^^^^^^^ PLR1716
74 | pass
|
= help: Use a single compare expression
Safe fix
70 70 | c = int(input())
71 71 | d = int(input())
72 72 | e = int(input())
73 |-if a < b and b < c and c < d and d < e: # [boolean-chained-comparison]
73 |+if a < b and b < c and c < d < e: # [boolean-chained-comparison]
74 74 | pass
75 75 |
76 76 | # ------------

1
ruff.schema.json generated
View file

@ -3548,6 +3548,7 @@
"PLR171", "PLR171",
"PLR1711", "PLR1711",
"PLR1714", "PLR1714",
"PLR1716",
"PLR172", "PLR172",
"PLR1722", "PLR1722",
"PLR173", "PLR173",