Skip to content

Commit 4b2ba3d

Browse files
[3.12] gh-109351: Fix crash when compiling AST with invalid NamedExpr (GH-109352) (#109379)
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 2fb39f7 commit 4b2ba3d

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

Lib/test/test_compile.py

+27
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,33 @@ def f():
443443
self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
444444
self.assertIn("__package__", A.f.__code__.co_varnames)
445445

446+
def test_compile_invalid_namedexpr(self):
447+
# gh-109351
448+
m = ast.Module(
449+
body=[
450+
ast.Expr(
451+
value=ast.ListComp(
452+
elt=ast.NamedExpr(
453+
target=ast.Constant(value=1),
454+
value=ast.Constant(value=3),
455+
),
456+
generators=[
457+
ast.comprehension(
458+
target=ast.Name(id="x", ctx=ast.Store()),
459+
iter=ast.Name(id="y", ctx=ast.Load()),
460+
ifs=[],
461+
is_async=0,
462+
)
463+
],
464+
)
465+
)
466+
],
467+
type_ignores=[],
468+
)
469+
470+
with self.assertRaisesRegex(TypeError, "NamedExpr target must be a Name"):
471+
compile(ast.fix_missing_locations(m), "<file>", "exec")
472+
446473
def test_compile_ast(self):
447474
fname = __file__
448475
if fname.lower().endswith('pyc'):
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

+5
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,11 @@ validate_expr(struct validator *state, expr_ty exp, expr_context_ty ctx)
381381
ret = validate_exprs(state, exp->v.Tuple.elts, ctx, 0);
382382
break;
383383
case NamedExpr_kind:
384+
if (exp->v.NamedExpr.target->kind != Name_kind) {
385+
PyErr_SetString(PyExc_TypeError,
386+
"NamedExpr target must be a Name");
387+
return 0;
388+
}
384389
ret = validate_expr(state, exp->v.NamedExpr.value, Load);
385390
break;
386391
/* This last case doesn't have any checking. */

0 commit comments

Comments
 (0)