#!/usr/bin/env python3 """Check PyStructSequence_New's C89 declaration and size lookup order.""" import re import sys from pathlib import Path source = Path(sys.argv[1] if len(sys.argv) > 1 else "cpython/Objects/structseq.c") match = re.search( r"PyStructSequence_New\(PyTypeObject \*type\)\s*\{(.*?)\n\}", source.read_text(), re.S, ) assert match, "PyStructSequence_New definition not found" body = match.group(1) assert re.match( r"\s*PyStructSequence \*obj;" r"\s*Py_ssize_t size = REAL_SIZE_TP\(type\), i;" r"\s*Py_ssize_t vsize;", body, ), "vsize must be declared without initializer before the size < 0 check" assert re.match( r"\s*PyStructSequence \*obj;" r"\s*Py_ssize_t size = REAL_SIZE_TP\(type\), i;" r"\s*Py_ssize_t vsize;" r"\s*if \(size < 0\) \{\s*return NULL;\s*\}" r"\s*vsize = VISIBLE_SIZE_TP\(type\);" r"\s*if \(vsize < 0\) \{\s*return NULL;\s*\}" r"\s*obj = PyObject_GC_NewVar\(PyStructSequence, type, size\);", body, ), "preserve size early return, visible-size lookup, and allocation order" assert body.count("VISIBLE_SIZE_TP(type)") == 1, "visible size must be read exactly once" assert body.count("Py_ssize_t vsize;") == 1, "vsize must be declared exactly once" print("PyStructSequence_New C89 declaration and size lookup order: PASS")