#!/usr/bin/env python3 """Check PyType_Modified's ref/obj declarations and unchanged use order.""" import re from pathlib import Path source = Path("cpython/Objects/typeobject.c").read_text() match = re.search( r"\nvoid\nPyType_Modified\(PyTypeObject \*type\)\n\{(.*?)\n\}", source, re.S, ) assert match, "PyType_Modified definition missing" body = re.sub(r"/\*.*?\*/", "", match.group(1), flags=re.S) assert re.match( r"\s*PyObject \*subclasses;\s*Py_ssize_t i;\s*PyObject \*ref;", body, ), "PyType_Modified: PyObject *ref; must be in the opening declaration block" assert len(re.findall(r"\bPyObject\s*\*\s*ref\b", body)) == 1, ( "PyType_Modified: declare ref exactly once without initialization" ) assert re.match( r"\s*PyObject \*subclasses;\s*Py_ssize_t i;\s*PyObject \*ref;\s*" r"PyObject \*obj;", body, ), "PyType_Modified: PyObject *obj; must be in the opening declaration block" assert len(re.findall(r"\bPyObject\s*\*\s*obj\b", body)) == 1, ( "PyType_Modified: declare obj exactly once without initialization" ) assert re.fullmatch( r"\s*PyObject \*subclasses;\s*Py_ssize_t i;\s*PyObject \*ref;\s*" r"PyObject \*obj;\s*" r"if \(!_PyType_HasFeature\(type, Py_TPFLAGS_VALID_VERSION_TAG\)\) \{\s*" r"return;\s*\}\s*" r"subclasses = type->tp_subclasses;\s*" r"if \(subclasses != NULL\) \{\s*" r"assert\(PyDict_CheckExact\(subclasses\)\);\s*i = 0;\s*" r"while \(PyDict_Next\(subclasses, &i, NULL, &ref\)\) \{\s*" r"assert\(PyWeakref_CheckRef\(ref\)\);\s*" r"obj = PyWeakref_GET_OBJECT\(ref\);\s*" r"if \(obj == Py_None\) \{\s*continue;\s*\}\s*" r"PyType_Modified\(_PyType_CAST\(obj\)\);\s*\}\s*\}\s*" r"type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;\s*" r"type->tp_version_tag = 0;\s*", body, ), "PyType_Modified: preserve all assignments, uses and evaluation order" print("PyType_Modified ref/obj C89 declarations and unchanged use order: PASS")