Skip to content

Commit

Permalink
pythongh-109341: Fix crash on compiling invalid AST including TypeAlias
Browse files Browse the repository at this point in the history
  • Loading branch information
JelleZijlstra committed Sep 12, 2023
1 parent 5dcbbd8 commit 8a459c7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
20 changes: 20 additions & 0 deletions Lib/test/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,26 @@ def test_compile_ast(self):
ast.body = [_ast.BoolOp()]
self.assertRaises(TypeError, compile, ast, '<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.assertRaises(SyntaxError):
compile(ast.fix_missing_locations(m), "<file>", "exec")

def test_dict_evaluation_order(self):
i = 0

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix crash when compiling an invalid AST involving a :class:`ast.TypeAlias`.
7 changes: 6 additions & 1 deletion Python/symtable.c
Original file line number Diff line number Diff line change
Expand Up @@ -1581,7 +1581,12 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
}
case TypeAlias_kind: {
VISIT(st, expr, s->v.TypeAlias.name);
assert(s->v.TypeAlias.name->kind == Name_kind);
// This is only possible for a manually created AST
if (s->v.TypeAlias.name->kind != Name_kind) {
PyErr_SetString(PyExc_SyntaxError,
"Type alias name must be a simple name");
VISIT_QUIT(st, 0);
}
PyObject *name = s->v.TypeAlias.name->v.Name.id;
int is_in_class = st->st_cur->ste_type == ClassBlock;
int is_generic = asdl_seq_LEN(s->v.TypeAlias.type_params) > 0;
Expand Down

0 comments on commit 8a459c7

Please sign in to comment.