From 987b4bc0870e1e29a88275dc3fa39bf2c3dcc763 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 13 Sep 2023 09:00:39 -0700 Subject: gh-109341: Fix crash on compiling invalid AST including TypeAlias (#109349) --- Lib/test/test_compile.py | 20 ++++++++++++++++++++ .../2023-09-12-15-45-49.gh-issue-109341.4V5bkm.rst | 1 + Python/ast.c | 5 +++++ 3 files changed, 26 insertions(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2023-09-12-15-45-49.gh-issue-109341.4V5bkm.rst diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index fa74455..39d972c 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -505,6 +505,26 @@ class TestSpecifics(unittest.TestCase): ast.body = [_ast.BoolOp()] self.assertRaises(TypeError, compile, ast, '', 'exec') + def test_compile_invalid_typealias(self): + # gh-109341 + m = ast.Module( + body=[ + ast.TypeAlias( + name=ast.Subscript( + value=ast.Name(id="foo", ctx=ast.Load()), + slice=ast.Constant(value="x"), + ctx=ast.Store(), + ), + type_params=[], + value=ast.Name(id="Callable", ctx=ast.Load()), + ) + ], + type_ignores=[], + ) + + with self.assertRaisesRegex(TypeError, "TypeAlias with non-Name name"): + compile(ast.fix_missing_locations(m), "", "exec") + def test_dict_evaluation_order(self): i = 0 diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-09-12-15-45-49.gh-issue-109341.4V5bkm.rst b/Misc/NEWS.d/next/Core and Builtins/2023-09-12-15-45-49.gh-issue-109341.4V5bkm.rst new file mode 100644 index 0000000..9e99ef7 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-09-12-15-45-49.gh-issue-109341.4V5bkm.rst @@ -0,0 +1 @@ +Fix crash when compiling an invalid AST involving a :class:`ast.TypeAlias`. diff --git a/Python/ast.c b/Python/ast.c index a230c7e..5f46d41 100644 --- a/Python/ast.c +++ b/Python/ast.c @@ -773,6 +773,11 @@ validate_stmt(struct validator *state, stmt_ty stmt) validate_expr(state, stmt->v.AnnAssign.annotation, Load); break; case TypeAlias_kind: + if (stmt->v.TypeAlias.name->kind != Name_kind) { + PyErr_SetString(PyExc_TypeError, + "TypeAlias with non-Name name"); + return 0; + } ret = validate_expr(state, stmt->v.TypeAlias.name, Store) && validate_type_params(state, stmt->v.TypeAlias.type_params) && validate_expr(state, stmt->v.TypeAlias.value, Load); -- cgit v0.12