#!/usr/bin/env python3 """Keep type_call's nargs declaration C89-safe and its evaluation after asserts.""" import re import sys from pathlib import Path source = Path(sys.argv[1] if len(sys.argv) > 1 else "cpython/Objects/typeobject.c").read_text() match = re.search( r"\nstatic PyObject \*\ntype_call\(PyTypeObject \*type, PyObject \*args, PyObject \*kwds\)\n\{(.*?)\n\}", source, re.S, ) assert match, "type_call definition missing" body = match.group(1) assert re.search(r"if \(type == &PyType_Type\) \{\s*Py_ssize_t nargs;", body), ( "type_call: nargs must be declared at block entry before assertions (C89)" ) assert len(re.findall(r"\bPy_ssize_t\s+nargs\b", body)) == 1, ( "type_call: declare nargs exactly once" ) expected = """ if (type == &PyType_Type) { Py_ssize_t nargs; assert(args != NULL && PyTuple_Check(args)); assert(kwds == NULL || PyDict_Check(kwds)); nargs = PyTuple_GET_SIZE(args); if (nargs == 1 && (kwds == NULL || !PyDict_GET_SIZE(kwds))) { obj = (PyObject *) Py_TYPE(PyTuple_GET_ITEM(args, 0)); Py_INCREF(obj); return obj; } /* SF bug 475327 -- if that didn't trigger, we need 3 arguments. But PyArg_ParseTuple in type_new may give a msg saying type() needs exactly 3. */ if (nargs != 3) { PyErr_SetString(PyExc_TypeError, "type() takes 1 or 3 arguments"); return NULL; } } """ special_case = body[body.index(" if (type == &PyType_Type)"):body.index(" if (type->tp_new == NULL)")] assert special_case.split() == expected.split(), ( "type_call: preserve nargs assignment after assertions and special-case control flow" ) assert re.findall(r"\bnargs\s*=(?!=)\s*([^;]+);", body) == ["PyTuple_GET_SIZE(args)"], ( "type_call: evaluate nargs exactly once" ) print("type_call nargs C89 declaration and unchanged evaluation/control flow: PASS")