Skip to content

Commit ebe6dc8

Browse files
committed
fix(ast): handle missing _fields in node repr
1 parent 77dd973 commit ebe6dc8

4 files changed

Lines changed: 26 additions & 0 deletions

File tree

Lib/test/test_ast/test_ast.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1165,6 +1165,20 @@ def test_repr_large_input_crash(self):
11651165
r"Exceeds the limit \(\d+ digits\)"):
11661166
repr(ast.Constant(value=eval(source)))
11671167

1168+
def test_repr_missing_fields_crash(self):
1169+
class FieldsMissingMeta(type):
1170+
def __getattribute__(self, name):
1171+
if name == "_fields":
1172+
raise AttributeError
1173+
return super().__getattribute__(name)
1174+
1175+
class FieldsMissing(ast.AST, metaclass=FieldsMissingMeta):
1176+
def __init__(self):
1177+
pass
1178+
1179+
node = FieldsMissing()
1180+
self.assertEqual(repr(node), "FieldsMissing()")
1181+
11681182
def test_tstring(self):
11691183
# Test AST structure for simple t-string
11701184
tree = ast.parse('t"Hello"')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in :func:`repr` of AST nodes when the AST node's type lacks the
2+
``_fields`` attribute. Patched by Shamil Abdulaev.

Parser/asdl_c.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1498,6 +1498,11 @@ def visitModule(self, mod):
14981498
return NULL;
14991499
}
15001500
1501+
if (fields == NULL) {
1502+
Py_ReprLeave((PyObject *)self);
1503+
return PyUnicode_FromFormat("%s()", Py_TYPE(self)->tp_name);
1504+
}
1505+
15011506
Py_ssize_t numfields = PySequence_Size(fields);
15021507
if (numfields < 0) {
15031508
Py_ReprLeave((PyObject *)self);

Python/Python-ast.c

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)