[SIM115] Allow open followed by close (#7916)

This commit is contained in:
Harutaka Kawamura 2023-10-11 22:53:48 +09:00 committed by GitHub
parent 7a072cc2ea
commit f670f9b22c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View file

@ -127,12 +127,41 @@ fn is_open(checker: &mut Checker, func: &Expr) -> bool {
}
}
/// Return `true` if the current expression is followed by a `close` call.
fn is_closed(semantic: &SemanticModel) -> bool {
let Some(expr) = semantic.current_expression_grandparent() else {
return false;
};
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = expr
else {
return false;
};
if !arguments.is_empty() {
return false;
}
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
return false;
};
attr.as_str() == "close"
}
/// SIM115
pub(crate) fn open_file_with_context_handler(checker: &mut Checker, func: &Expr) {
if !is_open(checker, func) {
return;
}
// Ex) `open("foo.txt").close()`
if is_closed(checker.semantic()) {
return;
}
// Ex) `with open("foo.txt") as f: ...`
if checker.semantic().current_statement().is_with_stmt() {
return;