Skip to content

Commit 987b4bc

Browse files
gh-109341: Fix crash on compiling invalid AST including TypeAlias (#109349)
1 parent 79101ed commit 987b4bc

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

Lib/test/test_compile.py

+20
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,26 @@ def test_compile_ast(self):
505505
ast.body = [_ast.BoolOp()]
506506
self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
507507

508+
def test_compile_invalid_typealias(self):
509+
# gh-109341
510+
m = ast.Module(
511+
body=[
512+
ast.TypeAlias(
513+
name=ast.Subscript(
514+
value=ast.Name(id="foo", ctx=ast.Load()),
515+
slice=ast.Constant(value="x"),
516+
ctx=ast.Store(),
517+
),
518+
type_params=[],
519+
value=ast.Name(id="Callable", ctx=ast.Load()),
520+
)
521+
],
522+
type_ignores=[],
523+
)
524+
525+
with self.assertRaisesRegex(TypeError, "TypeAlias with non-Name name"):
526+
compile(ast.fix_missing_locations(m), "<file>", "exec")
527+
508528
def test_dict_evaluation_order(self):
509529
i = 0
510530

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

+5
Original file line numberDiff line numberDiff line change
@@ -773,6 +773,11 @@ validate_stmt(struct validator *state, stmt_ty stmt)
773773
validate_expr(state, stmt->v.AnnAssign.annotation, Load);
774774
break;
775775
case TypeAlias_kind:
776+
if (stmt->v.TypeAlias.name->kind != Name_kind) {
777+
PyErr_SetString(PyExc_TypeError,
778+
"TypeAlias with non-Name name");
779+
return 0;
780+
}
776781
ret = validate_expr(state, stmt->v.TypeAlias.name, Store) &&
777782
validate_type_params(state, stmt->v.TypeAlias.type_params) &&
778783
validate_expr(state, stmt->v.TypeAlias.value, Load);

0 commit comments

Comments
 (0)