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

Avoid false-positives for yields with non-identical references #1665

Merged
merged 1 commit into from Jan 5, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions resources/test/fixtures/pyupgrade/UP028_1.py
Expand Up @@ -111,3 +111,13 @@ def f():
class C:
def __init__(self):
print(x)


def f():
for x in y:
yield x, x + 1


def f():
for x, y in z:
yield x, y, x + y
21 changes: 17 additions & 4 deletions src/pyupgrade/plugins/rewrite_yield_from.rs
Expand Up @@ -8,11 +8,25 @@ use crate::autofix::Fix;
use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckKind};

/// Return `true` if the two expressions are equivalent, and consistent solely
/// of tuples and names.
fn is_same_expr(a: &Expr, b: &Expr) -> bool {
match (&a.node, &b.node) {
(ExprKind::Name { id: a, .. }, ExprKind::Name { id: b, .. }) => a == b,
(ExprKind::Tuple { elts: a, .. }, ExprKind::Tuple { elts: b, .. }) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| is_same_expr(a, b))
}
_ => false,
}
}

/// Collect all named variables in an expression consisting solely of tuples and
/// names.
fn collect_names(expr: &Expr) -> Vec<&str> {
match &expr.node {
ExprKind::Name { id, .. } => vec![id],
ExprKind::Tuple { elts, .. } => elts.iter().flat_map(collect_names).collect(),
_ => vec![],
_ => unreachable!("Expected: ExprKind::Name | ExprKind::Tuple"),
}
}

Expand Down Expand Up @@ -51,13 +65,12 @@ impl<'a> Visitor<'a> for YieldFromVisitor<'a> {
let body = &body[0];
if let StmtKind::Expr { value } = &body.node {
if let ExprKind::Yield { value: Some(value) } = &value.node {
let names = collect_names(target);
if names == collect_names(value) {
if is_same_expr(target, value) {
self.yields.push(YieldFrom {
stmt,
body,
iter,
names,
names: collect_names(target),
});
}
}
Expand Down