diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 1bfbcb853c4ed1..c1d02cfaf0dcb6 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -2197,6 +2197,10 @@ def test_overlap_table(self): self.assertEqual(f("ababba"), [0, 0, 1, 2, 0, 1]) self.assertEqual(f("abcabdac"), [0, 0, 0, 1, 2, 0, 1, 0]) + def test_signedness(self): + self.assertGreaterEqual(sre_compile.MAXREPEAT, 0) + self.assertGreaterEqual(sre_compile.MAXGROUPS, 0) + class ExternalTests(unittest.TestCase): diff --git a/Modules/_sre.c b/Modules/_sre.c index fbabeb7c9f3054..3aa69752a997bb 100644 --- a/Modules/_sre.c +++ b/Modules/_sre.c @@ -2773,11 +2773,20 @@ static struct PyModuleDef sremodule = { NULL }; +#define ADD_ULONG_CONSTANT(module, name, value) \ + do { \ + PyObject *o = PyLong_FromUnsignedLong(value); \ + if (!o) \ + return NULL; \ + if (PyModule_AddObject(module, name, o) < 0) { \ + Py_DECREF(o); \ + return NULL; \ + } \ +} while (0) + PyMODINIT_FUNC PyInit__sre(void) { PyObject* m; - PyObject* d; - PyObject* x; /* Patch object types */ if (PyType_Ready(&Pattern_Type) || PyType_Ready(&Match_Type) || @@ -2787,37 +2796,22 @@ PyMODINIT_FUNC PyInit__sre(void) m = PyModule_Create(&sremodule); if (m == NULL) return NULL; - d = PyModule_GetDict(m); - x = PyLong_FromLong(SRE_MAGIC); - if (x) { - PyDict_SetItemString(d, "MAGIC", x); - Py_DECREF(x); + if (PyModule_AddIntConstant(m, "MAGIC", SRE_MAGIC) < 0) { + return NULL; } - x = PyLong_FromLong(sizeof(SRE_CODE)); - if (x) { - PyDict_SetItemString(d, "CODESIZE", x); - Py_DECREF(x); + if (PyModule_AddIntConstant(m, "CODESIZE", sizeof(SRE_CODE)) < 0) { + return NULL; } - x = PyLong_FromUnsignedLong(SRE_MAXREPEAT); - if (x) { - PyDict_SetItemString(d, "MAXREPEAT", x); - Py_DECREF(x); - } + ADD_ULONG_CONSTANT(m, "MAXREPEAT", SRE_MAXREPEAT); + ADD_ULONG_CONSTANT(m, "MAXGROUPS", SRE_MAXGROUPS); - x = PyLong_FromUnsignedLong(SRE_MAXGROUPS); - if (x) { - PyDict_SetItemString(d, "MAXGROUPS", x); - Py_DECREF(x); + if (PyModule_AddStringConstant(m, "copyright", copyright) < 0) { + return NULL; } - x = PyUnicode_FromString(copyright); - if (x) { - PyDict_SetItemString(d, "copyright", x); - Py_DECREF(x); - } return m; }