Skip to content

Commit 5c7e8c3

Browse files
[3.12] gh-109341: Fix crash on compiling invalid AST including TypeAlias (GH-109349) (#109381)
gh-109341: Fix crash on compiling invalid AST including TypeAlias (GH-109349) (cherry picked from commit 987b4bc) Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent 36d6ba0 commit 5c7e8c3

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

Lib/test/test_compile.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,26 @@ def test_compile_ast(self):
478478
ast.body = [_ast.BoolOp()]
479479
self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
480480

481+
def test_compile_invalid_typealias(self):
482+
# gh-109341
483+
m = ast.Module(
484+
body=[
485+
ast.TypeAlias(
486+
name=ast.Subscript(
487+
value=ast.Name(id="foo", ctx=ast.Load()),
488+
slice=ast.Constant(value="x"),
489+
ctx=ast.Store(),
490+
),
491+
type_params=[],
492+
value=ast.Name(id="Callable", ctx=ast.Load()),
493+
)
494+
],
495+
type_ignores=[],
496+
)
497+
498+
with self.assertRaisesRegex(TypeError, "TypeAlias with non-Name name"):
499+
compile(ast.fix_missing_locations(m), "<file>", "exec")
500+
481501
def test_dict_evaluation_order(self):
482502
i = 0
483503

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash when compiling an invalid AST involving a :class:`ast.TypeAlias`.

Python/ast.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -768,6 +768,11 @@ validate_stmt(struct validator *state, stmt_ty stmt)
768768
validate_expr(state, stmt->v.AnnAssign.annotation, Load);
769769
break;
770770
case TypeAlias_kind:
771+
if (stmt->v.TypeAlias.name->kind != Name_kind) {
772+
PyErr_SetString(PyExc_TypeError,
773+
"TypeAlias with non-Name name");
774+
return 0;
775+
}
771776
ret = validate_expr(state, stmt->v.TypeAlias.name, Store) &&
772777
validate_type_params(state, stmt->v.TypeAlias.type_params) &&
773778
validate_expr(state, stmt->v.TypeAlias.value, Load);

0 commit comments

Comments
 (0)