[3.11] gh-109351: Fix crash when compiling AST with invalid NamedExpr (GH-109352) (#109380)

gh-109351: Fix crash when compiling AST with invalid NamedExpr (GH-109352)
(cherry picked from commit 79101edb03)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
Miss Islington (bot) 2023-09-13 09:32:08 -07:00 committed by GitHub
parent 66c0d0ac8c
commit f1f85a42ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 0 deletions

View file

@ -442,6 +442,33 @@ if 1:
self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
self.assertIn("__package__", A.f.__code__.co_varnames)
def test_compile_invalid_namedexpr(self):
# gh-109351
m = ast.Module(
body=[
ast.Expr(
value=ast.ListComp(
elt=ast.NamedExpr(
target=ast.Constant(value=1),
value=ast.Constant(value=3),
),
generators=[
ast.comprehension(
target=ast.Name(id="x", ctx=ast.Store()),
iter=ast.Name(id="y", ctx=ast.Load()),
ifs=[],
is_async=0,
)
],
)
)
],
type_ignores=[],
)
with self.assertRaisesRegex(TypeError, "NamedExpr target must be a Name"):
compile(ast.fix_missing_locations(m), "<file>", "exec")
def test_compile_ast(self):
fname = __file__
if fname.lower().endswith('pyc'):

View file

@ -0,0 +1,2 @@
Fix crash when compiling an invalid AST involving a named (walrus)
expression.

View file

@ -379,6 +379,11 @@ validate_expr(struct validator *state, expr_ty exp, expr_context_ty ctx)
ret = validate_exprs(state, exp->v.Tuple.elts, ctx, 0);
break;
case NamedExpr_kind:
if (exp->v.NamedExpr.target->kind != Name_kind) {
PyErr_SetString(PyExc_TypeError,
"NamedExpr target must be a Name");
return 0;
}
ret = validate_expr(state, exp->v.NamedExpr.value, Load);
break;
/* This last case doesn't have any checking. */