Skip to content

Commit f1f85a4

Browse files
[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 79101ed) Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent 66c0d0a commit f1f85a4

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

Lib/test/test_compile.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,33 @@ def f():
442442
self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
443443
self.assertIn("__package__", A.f.__code__.co_varnames)
444444

445+
def test_compile_invalid_namedexpr(self):
446+
# gh-109351
447+
m = ast.Module(
448+
body=[
449+
ast.Expr(
450+
value=ast.ListComp(
451+
elt=ast.NamedExpr(
452+
target=ast.Constant(value=1),
453+
value=ast.Constant(value=3),
454+
),
455+
generators=[
456+
ast.comprehension(
457+
target=ast.Name(id="x", ctx=ast.Store()),
458+
iter=ast.Name(id="y", ctx=ast.Load()),
459+
ifs=[],
460+
is_async=0,
461+
)
462+
],
463+
)
464+
)
465+
],
466+
type_ignores=[],
467+
)
468+
469+
with self.assertRaisesRegex(TypeError, "NamedExpr target must be a Name"):
470+
compile(ast.fix_missing_locations(m), "<file>", "exec")
471+
445472
def test_compile_ast(self):
446473
fname = __file__
447474
if fname.lower().endswith('pyc'):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix crash when compiling an invalid AST involving a named (walrus)
2+
expression.

Python/ast.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,11 @@ validate_expr(struct validator *state, expr_ty exp, expr_context_ty ctx)
379379
ret = validate_exprs(state, exp->v.Tuple.elts, ctx, 0);
380380
break;
381381
case NamedExpr_kind:
382+
if (exp->v.NamedExpr.target->kind != Name_kind) {
383+
PyErr_SetString(PyExc_TypeError,
384+
"NamedExpr target must be a Name");
385+
return 0;
386+
}
382387
ret = validate_expr(state, exp->v.NamedExpr.value, Load);
383388
break;
384389
/* This last case doesn't have any checking. */

0 commit comments

Comments
 (0)