Deduplicate SIM116 errors (#3260)

This commit is contained in:
Charlie Marsh 2023-02-27 18:08:45 -05:00 committed by GitHub
parent 2261e194a0
commit ccfa9d5b20
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 59 additions and 1 deletions

View File

@ -74,3 +74,13 @@ elif b == b"two":
return 2
elif a == b"three":
return 3
# SIM116
if func_name == "create":
return "A"
elif func_name == "modify":
return "M"
elif func_name == "remove":
return "D"
elif func_name == "move":
return "MV"

View File

@ -1636,7 +1636,14 @@ where
flake8_simplify::rules::needless_bool(self, stmt);
}
if self.settings.rules.enabled(&Rule::ManualDictLookup) {
flake8_simplify::rules::manual_dict_lookup(self, stmt, test, body, orelse);
flake8_simplify::rules::manual_dict_lookup(
self,
stmt,
test,
body,
orelse,
self.current_stmt_parent().map(std::convert::Into::into),
);
}
if self.settings.rules.enabled(&Rule::UseTernaryOperator) {
flake8_simplify::rules::use_ternary_operator(

View File

@ -592,6 +592,7 @@ pub fn manual_dict_lookup(
test: &Expr,
body: &[Stmt],
orelse: &[Stmt],
parent: Option<&Stmt>,
) {
// Throughout this rule:
// * Each if-statement's test must consist of a constant equality check with the same variable.
@ -633,6 +634,36 @@ pub fn manual_dict_lookup(
return;
}
// It's part of a bigger if-elif block:
// https://github.com/MartinThoma/flake8-simplify/issues/115
if let Some(StmtKind::If {
orelse: parent_orelse,
..
}) = parent.map(|parent| &parent.node)
{
if parent_orelse.len() == 1 && stmt == &parent_orelse[0] {
// TODO(charlie): These two cases have the same AST:
//
// if True:
// pass
// elif a:
// b = 1
// else:
// b = 2
//
// if True:
// pass
// else:
// if a:
// b = 1
// else:
// b = 2
//
// We want to flag the latter, but not the former. Right now, we flag neither.
return;
}
}
let mut constants: FxHashSet<ComparableConstant> = FxHashSet::default();
constants.insert(constant.into());

View File

@ -62,4 +62,14 @@ expression: diagnostics
column: 23
fix: ~
parent: ~
- kind:
ManualDictLookup: ~
location:
row: 79
column: 0
end_location:
row: 86
column: 15
fix: ~
parent: ~