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

Fix B023 shadowed variables in nested functions #4111

Merged
merged 1 commit into from
Apr 26, 2023
Merged
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
11 changes: 11 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_bugbear/B023.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,14 @@ def iter_f(names):

if False:
return [lambda: i for i in range(3)] # error


for val in range(3):
def make_func(val=val):
def tmp():
return print(val)

return tmp


funcs.append(make_func())
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,8 @@ struct LoadedNamesVisitor<'a> {
}

/// `Visitor` to collect all used identifiers in a statement.
impl<'a, 'b> Visitor<'b> for LoadedNamesVisitor<'a>
where
'b: 'a,
{
fn visit_expr(&mut self, expr: &'b Expr) {
impl<'a> Visitor<'a> for LoadedNamesVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
match &expr.node {
ExprKind::Name { id, ctx } => match ctx {
ExprContext::Load => self.loaded.push((id, expr, Range::from(expr))),
Expand All @@ -56,11 +53,8 @@ struct SuspiciousVariablesVisitor<'a> {

/// `Visitor` to collect all suspicious variables (those referenced in
/// functions, but not bound as arguments).
impl<'a, 'b> Visitor<'b> for SuspiciousVariablesVisitor<'a>
where
'b: 'a,
{
fn visit_stmt(&mut self, stmt: &'b Stmt) {
impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match &stmt.node {
StmtKind::FunctionDef { args, body, .. }
| StmtKind::AsyncFunctionDef { args, body, .. } => {
Expand All @@ -76,9 +70,10 @@ where
self.names.extend(
visitor
.loaded
.iter()
.into_iter()
.filter(|(id, ..)| !arg_names.contains(id)),
);
return;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the real fix. We don't want to walk the function node again because that results in visiting the argument initializers (and a lot of unnecessary visiting)

}
StmtKind::Return { value: Some(value) } => {
// Mark `return lambda: x` as safe.
Expand All @@ -91,7 +86,7 @@ where
visitor::walk_stmt(self, stmt);
}

fn visit_expr(&mut self, expr: &'b Expr) {
fn visit_expr(&mut self, expr: &'a Expr) {
match &expr.node {
ExprKind::Call {
func,
Expand Down Expand Up @@ -145,6 +140,8 @@ where
.iter()
.filter(|(id, ..)| !arg_names.contains(id)),
);

return;
}
}
_ => {}
Expand All @@ -159,11 +156,8 @@ struct NamesFromAssignmentsVisitor<'a> {
}

/// `Visitor` to collect all names used in an assignment expression.
impl<'a, 'b> Visitor<'b> for NamesFromAssignmentsVisitor<'a>
where
'b: 'a,
{
fn visit_expr(&mut self, expr: &'b Expr) {
impl<'a> Visitor<'a> for NamesFromAssignmentsVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
match &expr.node {
ExprKind::Name { id, .. } => {
self.names.insert(id.as_str());
Expand All @@ -187,11 +181,8 @@ struct AssignedNamesVisitor<'a> {
}

/// `Visitor` to collect all used identifiers in a statement.
impl<'a, 'b> Visitor<'b> for AssignedNamesVisitor<'a>
where
'b: 'a,
{
fn visit_stmt(&mut self, stmt: &'b Stmt) {
impl<'a> Visitor<'a> for AssignedNamesVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
if matches!(
&stmt.node,
StmtKind::FunctionDef { .. } | StmtKind::AsyncFunctionDef { .. }
Expand Down Expand Up @@ -222,7 +213,7 @@ where
visitor::walk_stmt(self, stmt);
}

fn visit_expr(&mut self, expr: &'b Expr) {
fn visit_expr(&mut self, expr: &'a Expr) {
if matches!(&expr.node, ExprKind::Lambda { .. }) {
// Don't recurse.
return;
Expand All @@ -231,7 +222,7 @@ where
visitor::walk_expr(self, expr);
}

fn visit_comprehension(&mut self, comprehension: &'b Comprehension) {
fn visit_comprehension(&mut self, comprehension: &'a Comprehension) {
let mut visitor = NamesFromAssignmentsVisitor::default();
visitor.visit_expr(&comprehension.target);
self.names.extend(visitor.names);
Expand All @@ -241,14 +232,11 @@ where
}

/// B023
pub fn function_uses_loop_variable<'a, 'b>(checker: &'a mut Checker<'b>, node: &Node<'b>)
where
'b: 'a,
{
pub fn function_uses_loop_variable<'a>(checker: &mut Checker<'a>, node: &Node<'a>) {
// Identify any "suspicious" variables. These are defined as variables that are
// referenced in a function or lambda body, but aren't bound as arguments.
let suspicious_variables = {
let mut visitor = SuspiciousVariablesVisitor::<'b>::default();
let mut visitor = SuspiciousVariablesVisitor::default();
match node {
Node::Stmt(stmt) => visitor.visit_stmt(stmt),
Node::Expr(expr) => visitor.visit_expr(expr),
Expand All @@ -259,7 +247,7 @@ where
if !suspicious_variables.is_empty() {
// Identify any variables that are assigned in the loop (ignoring functions).
let reassigned_in_loop = {
let mut visitor = AssignedNamesVisitor::<'b>::default();
let mut visitor = AssignedNamesVisitor::default();
match node {
Node::Stmt(stmt) => visitor.visit_stmt(stmt),
Node::Expr(expr) => visitor.visit_expr(expr),
Expand Down