From 56254109368c3e8bbaa13ac95b6a603f4187d473 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Mon, 3 Apr 2023 12:22:06 -0400 Subject: [PATCH] Remove `uses_magic_variable_access` dependence on `Checker` (#3864) --- .../rules/unused_loop_control_variable.rs | 4 +++- crates/ruff_python_ast/src/helpers.rs | 24 +++++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs index 7704a18312..4b338d6f59 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs @@ -140,7 +140,9 @@ pub fn unused_loop_control_variable( } // Avoid fixing any variables that _may_ be used, but undetectably so. - let certainty = Certainty::from(!helpers::uses_magic_variable_access(&checker.ctx, body)); + let certainty = Certainty::from(!helpers::uses_magic_variable_access(body, |id| { + checker.ctx.is_builtin(id) + })); // Attempt to rename the variable by prepending an underscore, but avoid // applying the fix if doing so wouldn't actually cause us to ignore the diff --git a/crates/ruff_python_ast/src/helpers.rs b/crates/ruff_python_ast/src/helpers.rs index 841c8764d5..005dca7051 100644 --- a/crates/ruff_python_ast/src/helpers.rs +++ b/crates/ruff_python_ast/src/helpers.rs @@ -651,19 +651,23 @@ pub fn has_comments_in(range: Range, locator: &Locator) -> bool { } /// Return `true` if the body uses `locals()`, `globals()`, `vars()`, `eval()`. -pub fn uses_magic_variable_access(ctx: &Context, body: &[Stmt]) -> bool { +/// +/// Accepts a closure that determines whether a given name (e.g., `"list"`) is a Python builtin. +pub fn uses_magic_variable_access(body: &[Stmt], is_builtin: F) -> bool +where + F: Fn(&str) -> bool, +{ any_over_body(body, &|expr| { if let ExprKind::Call { func, .. } = &expr.node { - ctx.resolve_call_path(func).map_or(false, |call_path| { - call_path.as_slice() == ["", "locals"] - || call_path.as_slice() == ["", "globals"] - || call_path.as_slice() == ["", "vars"] - || call_path.as_slice() == ["", "eval"] - || call_path.as_slice() == ["", "exec"] - }) - } else { - false + if let ExprKind::Name { id, .. } = &func.node { + if matches!(id.as_str(), "locals" | "globals" | "vars" | "exec" | "eval") { + if is_builtin(id.as_str()) { + return true; + } + } + } } + false }) }