#!/usr/bin/env python3 """Check only type_new_set_doc's doc_str declaration and conversion timing.""" import re from pathlib import Path source = Path("cpython/Objects/typeobject.c").read_text() match = re.search( r"\nstatic int\ntype_new_set_doc\(PyTypeObject \*type\)\n\{(.*?)\n\}", source, re.S, ) assert match, "type_new_set_doc definition missing" body = re.sub(r"/\*.*?\*/|//[^\n]*", "", match.group(1), flags=re.S) assert re.match( r"\s*const char \*doc_str;" r"\s*Py_ssize_t size;" r"\s*char \*tp_doc;" r"\s*PyObject \*doc = PyDict_GetItemWithError" r"\(type->tp_dict, &_Py_ID\(__doc__\)\);", body, ), "type_new_set_doc: doc_str and size must be in the opening declaration block (C89)" assert len(re.findall(r"\bconst\s+char\s*\*\s*doc_str\b", body)) == 1, ( "declare doc_str exactly once" ) assert len(re.findall(r"\bdoc_str\s*=(?!=)", body)) == 1, ( "assign doc_str exactly once" ) expected = """ const char *doc_str; Py_ssize_t size; char *tp_doc; PyObject *doc = PyDict_GetItemWithError(type->tp_dict, &_Py_ID(__doc__)); if (doc == NULL) { if (PyErr_Occurred()) { return -1; } return 0; } if (!PyUnicode_Check(doc)) { return 0; } doc_str = PyUnicode_AsUTF8(doc); if (doc_str == NULL) { return -1; } size = strlen(doc_str) + 1; tp_doc = (char *)PyObject_Malloc(size); if (tp_doc == NULL) { PyErr_NoMemory(); return -1; } memcpy(tp_doc, doc_str, size); type->tp_doc = tp_doc; return 0; """ assert body.split() == expected.split(), ( "type_new_set_doc: preserve conversion timing, early returns, allocation, " "and docstring copy; leave other declarations unchanged" ) print("type_new_set_doc doc_str C89 declaration and conversion timing: PASS")