#!/usr/bin/env python3 """Check only mro_implementation's first loop index and validation semantics.""" import re from pathlib import Path source = Path("cpython/Objects/typeobject.c").read_text() match = re.search( r"\nstatic PyObject \*\nmro_implementation\(PyTypeObject \*type\)\n\{(.*?)\n\}", source, re.S, ) assert match, "mro_implementation definition missing" body = re.sub(r"/\*.*?\*/", "", match.group(1), flags=re.S) validation = body.split("if (n == 1)", 1)[0] assert re.match( r"\s*PyObject \*bases;\s*Py_ssize_t n;\s*Py_ssize_t i;" r"\s*PyObject \*\*to_merge;\s*PyObject \*result;\s*if\b", validation, ), ( "mro_implementation: first loop index must be declared in the opening block" ) assert len(re.findall(r"\bPy_ssize_t\s+i\b", validation)) == 1, "declare first loop index exactly once" assert len(re.findall(r"\bi\s*=(?!=)", validation)) == 1, "initialize first loop index exactly once" expected = """ PyObject *bases; Py_ssize_t n; Py_ssize_t i; PyObject **to_merge; PyObject *result; if (!_PyType_IsReady(type)) { if (PyType_Ready(type) < 0) return NULL; } bases = type->tp_bases; n = PyTuple_GET_SIZE(bases); for (i = 0; i < n; i++) { PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, i)); if (base->tp_mro == NULL) { PyErr_Format(PyExc_TypeError, "Cannot extend an incomplete type '%.100s'", base->tp_name); return NULL; } assert(PyTuple_Check(base->tp_mro)); } """ assert validation.split() == expected.split(), ( "mro_implementation: preserve readiness, initialization timing, loop bounds, " "increment, and base validation" ) print("mro_implementation first loop index C89 declaration and unchanged validation: PASS")