[Python-checkins] cpython: Issue #23501: Argumen Clinic now generates code into separate files by default.

serhiy.storchaka python-checkins at python.org
Fri Apr 3 22:54:14 CEST 2015


https://hg.python.org/cpython/rev/aa88a18a4aa1
changeset:   95423:aa88a18a4aa1
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Fri Apr 03 23:53:51 2015 +0300
summary:
  Issue #23501: Argumen Clinic now generates code into separate files by default.

files:
  Misc/NEWS                          |      2 +
  Modules/_bz2module.c               |      3 +-
  Modules/_codecsmodule.c            |     31 +-
  Modules/_cryptmodule.c             |     37 +-
  Modules/_cursesmodule.c            |     70 +-
  Modules/_datetimemodule.c          |     38 +-
  Modules/_dbmmodule.c               |     74 +-
  Modules/_lzmamodule.c              |      3 +-
  Modules/_opcode.c                  |     37 +-
  Modules/_pickle.c                  |      3 +-
  Modules/_weakref.c                 |     31 +-
  Modules/arraymodule.c              |      3 +-
  Modules/audioop.c                  |      3 +-
  Modules/binascii.c                 |      3 +-
  Modules/cjkcodecs/multibytecodec.c |      7 +-
  Modules/_codecsmodule.c            |   1229 +-
  Modules/_cryptmodule.c             |     64 +-
  Modules/_cursesmodule.c            |   3456 +---
  Modules/_datetimemodule.c          |   5556 +-----
  Modules/_dbmmodule.c               |    489 +-
  Modules/_opcode.c                  |     76 +-
  Modules/_weakref.c                 |    131 +-
  Modules/md5module.c                |    608 +-
  Modules/posixmodule.c              |  13317 +------------
  Modules/pyexpat.c                  |   1978 +-
  Modules/sha1module.c               |    580 +-
  Modules/sha256module.c             |    747 +-
  Modules/sha512module.c             |    852 +-
  Modules/unicodedata.c              |   1398 +-
  Modules/cmathmodule.c              |      3 +-
  Modules/fcntlmodule.c              |      3 +-
  Modules/grpmodule.c                |      3 +-
  Modules/md5module.c                |    103 +-
  Modules/posixmodule.c              |   5755 +-----
  Modules/pwdmodule.c                |      3 +-
  Modules/pyexpat.c                  |    307 +-
  Modules/sha1module.c               |    103 +-
  Modules/sha256module.c             |    135 +-
  Modules/sha512module.c             |    163 +-
  Modules/spwdmodule.c               |      3 +-
  Modules/unicodedata.c              |     37 +-
  Modules/zlibmodule.c               |      3 +-
  Objects/bytearrayobject.c          |    756 +-
  Objects/bytesobject.c              |    522 +-
  Objects/bytearrayobject.c          |   3271 +---
  Objects/bytesobject.c              |   3702 +---
  Objects/dictobject.c               |   3889 +---
  Objects/unicodeobject.c            |  15439 +--------------
  Objects/dictobject.c               |     44 +-
  Objects/unicodeobject.c            |     42 +-
  Python/bltinmodule.c               |    715 +-
  Python/bltinmodule.c               |   2694 +--
  Python/import.c                    |      3 +-
  Tools/clinic/clinic.py             |     14 +-
  54 files changed, 738 insertions(+), 67800 deletions(-)


diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -63,6 +63,8 @@
 Build
 -----
 
+- Issue #23501: Argumen Clinic now generates code into separate files by default.
+
 Tests
 -----
 
diff --git a/Modules/_bz2module.c b/Modules/_bz2module.c
--- a/Modules/_bz2module.c
+++ b/Modules/_bz2module.c
@@ -211,12 +211,11 @@
 }
 
 /*[clinic input]
-output preset file
 module _bz2
 class _bz2.BZ2Compressor "BZ2Compressor *" "&BZ2Compressor_Type"
 class _bz2.BZ2Decompressor "BZ2Decompressor *" "&BZ2Decompressor_Type"
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=e3b139924f5e18cc]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=dc7d7992a79f9cb7]*/
 
 #include "clinic/_bz2module.c.h"
 
diff --git a/Modules/_codecsmodule.c b/Modules/_codecsmodule.c
--- a/Modules/_codecsmodule.c
+++ b/Modules/_codecsmodule.c
@@ -47,6 +47,7 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=e1390e3da3cb9deb]*/
 
+#include "clinic/_codecsmodule.c.h"
 
 /* --- Registry ----------------------------------------------------------- */
 
@@ -153,37 +154,9 @@
 Purge the named codec from the internal codec lookup cache
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_codecs__forget_codec__doc__,
-"_forget_codec($module, encoding, /)\n"
-"--\n"
-"\n"
-"Purge the named codec from the internal codec lookup cache");
-
-#define _CODECS__FORGET_CODEC_METHODDEF    \
-    {"_forget_codec", (PyCFunction)_codecs__forget_codec, METH_VARARGS, _codecs__forget_codec__doc__},
-
-static PyObject *
-_codecs__forget_codec_impl(PyModuleDef *module, const char *encoding);
-
-static PyObject *
-_codecs__forget_codec(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    const char *encoding;
-
-    if (!PyArg_ParseTuple(args,
-        "s:_forget_codec",
-        &encoding))
-        goto exit;
-    return_value = _codecs__forget_codec_impl(module, encoding);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _codecs__forget_codec_impl(PyModuleDef *module, const char *encoding)
-/*[clinic end generated code: output=a75e631591702a5c input=18d5d92d0e386c38]*/
+/*[clinic end generated code: output=b56a9b99d2d28080 input=18d5d92d0e386c38]*/
 {
     if (_PyCodec_Forget(encoding) < 0) {
         return NULL;
diff --git a/Modules/_cryptmodule.c b/Modules/_cryptmodule.c
--- a/Modules/_cryptmodule.c
+++ b/Modules/_cryptmodule.c
@@ -12,6 +12,7 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c6252cf4f2f2ae81]*/
 
+#include "clinic/_cryptmodule.c.h"
 
 /*[clinic input]
 crypt.crypt
@@ -29,43 +30,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(crypt_crypt__doc__,
-"crypt($module, word, salt, /)\n"
-"--\n"
-"\n"
-"Hash a *word* with the given *salt* and return the hashed password.\n"
-"\n"
-"*word* will usually be a user\'s password.  *salt* (either a random 2 or 16\n"
-"character string, possibly prefixed with $digit$ to indicate the method)\n"
-"will be used to perturb the encryption algorithm and produce distinct\n"
-"results for a given *word*.");
-
-#define CRYPT_CRYPT_METHODDEF    \
-    {"crypt", (PyCFunction)crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
-
-static PyObject *
-crypt_crypt_impl(PyModuleDef *module, const char *word, const char *salt);
-
-static PyObject *
-crypt_crypt(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    const char *word;
-    const char *salt;
-
-    if (!PyArg_ParseTuple(args,
-        "ss:crypt",
-        &word, &salt))
-        goto exit;
-    return_value = crypt_crypt_impl(module, word, salt);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 crypt_crypt_impl(PyModuleDef *module, const char *word, const char *salt)
-/*[clinic end generated code: output=3eaacdf994a6ff23 input=4d93b6d0f41fbf58]*/
+/*[clinic end generated code: output=995ad1e854d83069 input=4d93b6d0f41fbf58]*/
 {
     /* On some platforms (AtheOS) crypt returns NULL for an invalid
        salt. Return None in that case. XXX Maybe raise an exception?  */
diff --git a/Modules/_cursesmodule.c b/Modules/_cursesmodule.c
--- a/Modules/_cursesmodule.c
+++ b/Modules/_cursesmodule.c
@@ -140,6 +140,8 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=88c860abdbb50e0c]*/
 
+#include "clinic/_cursesmodule.c.h"
+
 /* Definition of exception curses.error */
 
 static PyObject *PyCursesError;
@@ -583,75 +585,9 @@
 current settings for the window object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(curses_window_addch__doc__,
-"addch([y, x,] ch, [attr])\n"
-"Paint character ch at (y, x) with attributes attr.\n"
-"\n"
-"  y\n"
-"    Y-coordinate.\n"
-"  x\n"
-"    X-coordinate.\n"
-"  ch\n"
-"    Character to add.\n"
-"  attr\n"
-"    Attributes for the character.\n"
-"\n"
-"Paint character ch at (y, x) with attributes attr,\n"
-"overwriting any character previously painted at that location.\n"
-"By default, the character position and attributes are the\n"
-"current settings for the window object.");
-
-#define CURSES_WINDOW_ADDCH_METHODDEF    \
-    {"addch", (PyCFunction)curses_window_addch, METH_VARARGS, curses_window_addch__doc__},
-
-static PyObject *
-curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1, int y, int x, PyObject *ch, int group_right_1, long attr);
-
-static PyObject *
-curses_window_addch(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int group_left_1 = 0;
-    int y = 0;
-    int x = 0;
-    PyObject *ch;
-    int group_right_1 = 0;
-    long attr = 0;
-
-    switch (PyTuple_GET_SIZE(args)) {
-        case 1:
-            if (!PyArg_ParseTuple(args, "O:addch", &ch))
-                goto exit;
-            break;
-        case 2:
-            if (!PyArg_ParseTuple(args, "Ol:addch", &ch, &attr))
-                goto exit;
-            group_right_1 = 1;
-            break;
-        case 3:
-            if (!PyArg_ParseTuple(args, "iiO:addch", &y, &x, &ch))
-                goto exit;
-            group_left_1 = 1;
-            break;
-        case 4:
-            if (!PyArg_ParseTuple(args, "iiOl:addch", &y, &x, &ch, &attr))
-                goto exit;
-            group_right_1 = 1;
-            group_left_1 = 1;
-            break;
-        default:
-            PyErr_SetString(PyExc_TypeError, "curses.window.addch requires 1 to 4 arguments");
-            goto exit;
-    }
-    return_value = curses_window_addch_impl(self, group_left_1, y, x, ch, group_right_1, attr);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1, int y, int x, PyObject *ch, int group_right_1, long attr)
-/*[clinic end generated code: output=d4b97cc287010c54 input=5a41efb34a2de338]*/
+/*[clinic end generated code: output=9fa34a5d80151f1a input=5a41efb34a2de338]*/
 {
     PyCursesWindowObject *cwself = (PyCursesWindowObject *)self;
     int coordinates_group = group_left_1;
diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c
--- a/Modules/_datetimemodule.c
+++ b/Modules/_datetimemodule.c
@@ -26,6 +26,8 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
 
+#include "clinic/_datetimemodule.c.h"
+
 /* We require that C int be at least 32 bits, and use int virtually
  * everywhere.  In just a few cases we use a temp long, where a Python
  * API returns a C long.  In such cases, we have to ensure that the
@@ -4133,43 +4135,9 @@
 If no tz is specified, uses local timezone.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(datetime_datetime_now__doc__,
-"now($type, /, tz=None)\n"
-"--\n"
-"\n"
-"Returns new datetime object representing current time local to tz.\n"
-"\n"
-"  tz\n"
-"    Timezone object.\n"
-"\n"
-"If no tz is specified, uses local timezone.");
-
-#define DATETIME_DATETIME_NOW_METHODDEF    \
-    {"now", (PyCFunction)datetime_datetime_now, METH_VARARGS|METH_KEYWORDS|METH_CLASS, datetime_datetime_now__doc__},
-
-static PyObject *
-datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz);
-
-static PyObject *
-datetime_datetime_now(PyTypeObject *type, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"tz", NULL};
-    PyObject *tz = Py_None;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:now", _keywords,
-        &tz))
-        goto exit;
-    return_value = datetime_datetime_now_impl(type, tz);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
-/*[clinic end generated code: output=583c5637e3c843fa input=80d09869c5267d00]*/
+/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
 {
     PyObject *self;
 
diff --git a/Modules/_dbmmodule.c b/Modules/_dbmmodule.c
--- a/Modules/_dbmmodule.c
+++ b/Modules/_dbmmodule.c
@@ -40,6 +40,8 @@
     DBM *di_dbm;
 } dbmobject;
 
+#include "clinic/_dbmmodule.c.h"
+
 static PyTypeObject Dbmtype;
 
 #define is_dbmobject(v) (Py_TYPE(v) == &Dbmtype)
@@ -277,39 +279,9 @@
 Return the value for key if present, otherwise default.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(dbm_dbm_get__doc__,
-"get($self, key, default=None, /)\n"
-"--\n"
-"\n"
-"Return the value for key if present, otherwise default.");
-
-#define DBM_DBM_GET_METHODDEF    \
-    {"get", (PyCFunction)dbm_dbm_get, METH_VARARGS, dbm_dbm_get__doc__},
-
-static PyObject *
-dbm_dbm_get_impl(dbmobject *dp, const char *key, Py_ssize_clean_t key_length, PyObject *default_value);
-
-static PyObject *
-dbm_dbm_get(dbmobject *dp, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    const char *key;
-    Py_ssize_clean_t key_length;
-    PyObject *default_value = Py_None;
-
-    if (!PyArg_ParseTuple(args,
-        "s#|O:get",
-        &key, &key_length, &default_value))
-        goto exit;
-    return_value = dbm_dbm_get_impl(dp, key, key_length, default_value);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 dbm_dbm_get_impl(dbmobject *dp, const char *key, Py_ssize_clean_t key_length, PyObject *default_value)
-/*[clinic end generated code: output=452ea11394e7e92d input=aecf5efd2f2b1a3b]*/
+/*[clinic end generated code: output=c2bdccaa734ad349 input=aecf5efd2f2b1a3b]*/
 {
     datum dbm_key, val;
 
@@ -449,47 +421,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(dbmopen__doc__,
-"open($module, filename, flags=\'r\', mode=0o666, /)\n"
-"--\n"
-"\n"
-"Return a database object.\n"
-"\n"
-"  filename\n"
-"    The filename to open.\n"
-"  flags\n"
-"    How to open the file.  \"r\" for reading, \"w\" for writing, etc.\n"
-"  mode\n"
-"    If creating a new file, the mode bits for the new file\n"
-"    (e.g. os.O_RDWR).");
-
-#define DBMOPEN_METHODDEF    \
-    {"open", (PyCFunction)dbmopen, METH_VARARGS, dbmopen__doc__},
-
-static PyObject *
-dbmopen_impl(PyModuleDef *module, const char *filename, const char *flags, int mode);
-
-static PyObject *
-dbmopen(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    const char *filename;
-    const char *flags = "r";
-    int mode = 438;
-
-    if (!PyArg_ParseTuple(args,
-        "s|si:open",
-        &filename, &flags, &mode))
-        goto exit;
-    return_value = dbmopen_impl(module, filename, flags, mode);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 dbmopen_impl(PyModuleDef *module, const char *filename, const char *flags, int mode)
-/*[clinic end generated code: output=9a7b725f9c4dcec2 input=6499ab0fab1333ac]*/
+/*[clinic end generated code: output=8b618fe06b92bf86 input=6499ab0fab1333ac]*/
 {
     int iflags;
 
diff --git a/Modules/_lzmamodule.c b/Modules/_lzmamodule.c
--- a/Modules/_lzmamodule.c
+++ b/Modules/_lzmamodule.c
@@ -478,12 +478,11 @@
 
 
 /*[clinic input]
-output preset file
 module _lzma
 class _lzma.LZMACompressor "Compressor *" "&Compressor_type"
 class _lzma.LZMADecompressor "Decompressor *" "&Decompressor_type"
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f17afc786525d6c2]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2c14bbe05ff0c147]*/
 
 #include "clinic/_lzmamodule.c.h"
 
diff --git a/Modules/_opcode.c b/Modules/_opcode.c
--- a/Modules/_opcode.c
+++ b/Modules/_opcode.c
@@ -6,6 +6,8 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=117442e66eb376e6]*/
 
+#include "clinic/_opcode.c.h"
+
 /*[clinic input]
 
 _opcode.stack_effect -> int
@@ -17,42 +19,9 @@
 Compute the stack effect of the opcode.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_opcode_stack_effect__doc__,
-"stack_effect($module, opcode, oparg=None, /)\n"
-"--\n"
-"\n"
-"Compute the stack effect of the opcode.");
-
-#define _OPCODE_STACK_EFFECT_METHODDEF    \
-    {"stack_effect", (PyCFunction)_opcode_stack_effect, METH_VARARGS, _opcode_stack_effect__doc__},
-
-static int
-_opcode_stack_effect_impl(PyModuleDef *module, int opcode, PyObject *oparg);
-
-static PyObject *
-_opcode_stack_effect(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int opcode;
-    PyObject *oparg = Py_None;
-    int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "i|O:stack_effect",
-        &opcode, &oparg))
-        goto exit;
-    _return_value = _opcode_stack_effect_impl(module, opcode, oparg);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 _opcode_stack_effect_impl(PyModuleDef *module, int opcode, PyObject *oparg)
-/*[clinic end generated code: output=9e1133f8d587bc67 input=2d0a9ee53c0418f5]*/
+/*[clinic end generated code: output=1fcafd5596c6b050 input=2d0a9ee53c0418f5]*/
 {
     int effect;
     int oparg_int = 0;
diff --git a/Modules/_pickle.c b/Modules/_pickle.c
--- a/Modules/_pickle.c
+++ b/Modules/_pickle.c
@@ -5,14 +5,13 @@
 "Optimized C implementation for the Python pickle module.");
 
 /*[clinic input]
-output preset file
 module _pickle
 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
 class _pickle.PicklerMemoProxy "PicklerMemoProxyObject *" "&PicklerMemoProxyType"
 class _pickle.Unpickler "UnpicklerObject *" "&Unpickler_Type"
 class _pickle.UnpicklerMemoProxy "UnpicklerMemoProxyObject *" "&UnpicklerMemoProxyType"
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=11c45248a41dd3fc]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4b3e113468a58e6c]*/
 
 /* Bump this when new opcodes are added to the pickle protocol. */
 enum {
diff --git a/Modules/_weakref.c b/Modules/_weakref.c
--- a/Modules/_weakref.c
+++ b/Modules/_weakref.c
@@ -9,6 +9,8 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ffec73b85846596d]*/
 
+#include "clinic/_weakref.c.h"
+
 /*[clinic input]
 
 _weakref.getweakrefcount -> Py_ssize_t
@@ -19,36 +21,9 @@
 Return the number of weak references to 'object'.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_weakref_getweakrefcount__doc__,
-"getweakrefcount($module, object, /)\n"
-"--\n"
-"\n"
-"Return the number of weak references to \'object\'.");
-
-#define _WEAKREF_GETWEAKREFCOUNT_METHODDEF    \
-    {"getweakrefcount", (PyCFunction)_weakref_getweakrefcount, METH_O, _weakref_getweakrefcount__doc__},
-
-static Py_ssize_t
-_weakref_getweakrefcount_impl(PyModuleDef *module, PyObject *object);
-
-static PyObject *
-_weakref_getweakrefcount(PyModuleDef *module, PyObject *object)
-{
-    PyObject *return_value = NULL;
-    Py_ssize_t _return_value;
-
-    _return_value = _weakref_getweakrefcount_impl(module, object);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromSsize_t(_return_value);
-
-exit:
-    return return_value;
-}
-
 static Py_ssize_t
 _weakref_getweakrefcount_impl(PyModuleDef *module, PyObject *object)
-/*[clinic end generated code: output=032eedbfd7d69e10 input=cedb69711b6a2507]*/
+/*[clinic end generated code: output=6a6ad0b98285e468 input=cedb69711b6a2507]*/
 {
     PyWeakReference **list;
 
diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c
--- a/Modules/arraymodule.c
+++ b/Modules/arraymodule.c
@@ -16,10 +16,9 @@
 #endif /* !STDC_HEADERS */
 
 /*[clinic input]
-output preset file
 module array
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=0909c1a148c69931]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
 
 struct arrayobject; /* Forward */
 
diff --git a/Modules/audioop.c b/Modules/audioop.c
--- a/Modules/audioop.c
+++ b/Modules/audioop.c
@@ -391,10 +391,9 @@
 }
 
 /*[clinic input]
-output preset file
 module audioop
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5619f935f269199a]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8fa8f6611be3591a]*/
 
 /*[clinic input]
 audioop.getsample
diff --git a/Modules/binascii.c b/Modules/binascii.c
--- a/Modules/binascii.c
+++ b/Modules/binascii.c
@@ -184,10 +184,9 @@
 };
 
 /*[clinic input]
-output preset file
 module binascii
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=44c6f840ce708f0c]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=de89fb46bcaf3fec]*/
 
 /*[python input]
 
diff --git a/Modules/cjkcodecs/multibytecodec.c b/Modules/cjkcodecs/multibytecodec.c
--- a/Modules/cjkcodecs/multibytecodec.c
+++ b/Modules/cjkcodecs/multibytecodec.c
@@ -11,15 +11,10 @@
 #include "clinic/multibytecodec.c.h"
 
 /*[clinic input]
-output preset file
 module _multibytecodec
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=e0cf1b7f3c472d17]*/
-
-/*[clinic input]
 class _multibytecodec.MultibyteCodec "MultibyteCodecObject *" "&MultibyteCodec_Type"
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d5b1fc1fec8eb003]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=6ad689546cbb5450]*/
 
 typedef struct {
     PyObject            *inobj;
diff --git a/Modules/_codecsmodule.c b/Modules/clinic/_codecsmodule.c.h
copy from Modules/_codecsmodule.c
copy to Modules/clinic/_codecsmodule.c.h
--- a/Modules/_codecsmodule.c
+++ b/Modules/clinic/_codecsmodule.c.h
@@ -1,156 +1,5 @@
-/* ------------------------------------------------------------------------
-
-   _codecs -- Provides access to the codec registry and the builtin
-              codecs.
-
-   This module should never be imported directly. The standard library
-   module "codecs" wraps this builtin module for use within Python.
-
-   The codec registry is accessible via:
-
-     register(search_function) -> None
-
-     lookup(encoding) -> CodecInfo object
-
-   The builtin Unicode codecs use the following interface:
-
-     <encoding>_encode(Unicode_object[,errors='strict']) ->
-        (string object, bytes consumed)
-
-     <encoding>_decode(char_buffer_obj[,errors='strict']) ->
-        (Unicode object, bytes consumed)
-
-   <encoding>_encode() interfaces also accept non-Unicode object as
-   input. The objects are then converted to Unicode using
-   PyUnicode_FromObject() prior to applying the conversion.
-
-   These <encoding>s are available: utf_8, unicode_escape,
-   raw_unicode_escape, unicode_internal, latin_1, ascii (7-bit),
-   mbcs (on win32).
-
-
-Written by Marc-Andre Lemburg (mal at lemburg.com).
-
-Copyright (c) Corporation for National Research Initiatives.
-
-   ------------------------------------------------------------------------ */
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-
-#ifdef MS_WINDOWS
-#include <windows.h>
-#endif
-
 /*[clinic input]
-module _codecs
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=e1390e3da3cb9deb]*/
-
-
-/* --- Registry ----------------------------------------------------------- */
-
-PyDoc_STRVAR(register__doc__,
-"register(search_function)\n\
-\n\
-Register a codec search function. Search functions are expected to take\n\
-one argument, the encoding name in all lower case letters, and either\n\
-return None, or a tuple of functions (encoder, decoder, stream_reader,\n\
-stream_writer) (or a CodecInfo object).");
-
-static
-PyObject *codec_register(PyObject *self, PyObject *search_function)
-{
-    if (PyCodec_Register(search_function))
-        return NULL;
-
-    Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(lookup__doc__,
-"lookup(encoding) -> CodecInfo\n\
-\n\
-Looks up a codec tuple in the Python codec registry and returns\n\
-a CodecInfo object.");
-
-static
-PyObject *codec_lookup(PyObject *self, PyObject *args)
-{
-    char *encoding;
-
-    if (!PyArg_ParseTuple(args, "s:lookup", &encoding))
-        return NULL;
-
-    return _PyCodec_Lookup(encoding);
-}
-
-PyDoc_STRVAR(encode__doc__,
-"encode(obj, [encoding[,errors]]) -> object\n\
-\n\
-Encodes obj using the codec registered for encoding. encoding defaults\n\
-to the default encoding. errors may be given to set a different error\n\
-handling scheme. Default is 'strict' meaning that encoding errors raise\n\
-a ValueError. Other possible values are 'ignore', 'replace' and\n\
-'xmlcharrefreplace' as well as any other name registered with\n\
-codecs.register_error that can handle ValueErrors.");
-
-static PyObject *
-codec_encode(PyObject *self, PyObject *args, PyObject *kwargs)
-{
-    static char *kwlist[] = {"obj", "encoding", "errors", NULL};
-    const char *encoding = NULL;
-    const char *errors = NULL;
-    PyObject *v;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|ss:encode", kwlist,
-                                     &v, &encoding, &errors))
-        return NULL;
-
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-
-    /* Encode via the codec registry */
-    return PyCodec_Encode(v, encoding, errors);
-}
-
-PyDoc_STRVAR(decode__doc__,
-"decode(obj, [encoding[,errors]]) -> object\n\
-\n\
-Decodes obj using the codec registered for encoding. encoding defaults\n\
-to the default encoding. errors may be given to set a different error\n\
-handling scheme. Default is 'strict' meaning that encoding errors raise\n\
-a ValueError. Other possible values are 'ignore' and 'replace'\n\
-as well as any other name registered with codecs.register_error that is\n\
-able to handle ValueErrors.");
-
-static PyObject *
-codec_decode(PyObject *self, PyObject *args, PyObject *kwargs)
-{
-    static char *kwlist[] = {"obj", "encoding", "errors", NULL};
-    const char *encoding = NULL;
-    const char *errors = NULL;
-    PyObject *v;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|ss:decode", kwlist,
-                                     &v, &encoding, &errors))
-        return NULL;
-
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-
-    /* Decode via the codec registry */
-    return PyCodec_Decode(v, encoding, errors);
-}
-
-/* --- Helpers ------------------------------------------------------------ */
-
-/*[clinic input]
-_codecs._forget_codec
-
-    encoding: str
-    /
-
-Purge the named codec from the internal codec lookup cache
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(_codecs__forget_codec__doc__,
@@ -180,1078 +29,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-_codecs__forget_codec_impl(PyModuleDef *module, const char *encoding)
-/*[clinic end generated code: output=a75e631591702a5c input=18d5d92d0e386c38]*/
-{
-    if (_PyCodec_Forget(encoding) < 0) {
-        return NULL;
-    };
-    Py_RETURN_NONE;
-}
-
-static
-PyObject *codec_tuple(PyObject *unicode,
-                      Py_ssize_t len)
-{
-    PyObject *v;
-    if (unicode == NULL)
-        return NULL;
-    v = Py_BuildValue("On", unicode, len);
-    Py_DECREF(unicode);
-    return v;
-}
-
-/* --- String codecs ------------------------------------------------------ */
-static PyObject *
-escape_decode(PyObject *self,
-              PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    PyObject *result;
-
-    if (!PyArg_ParseTuple(args, "s*|z:escape_decode",
-                          &pbuf, &errors))
-        return NULL;
-    result = codec_tuple(
-            PyBytes_DecodeEscape(pbuf.buf, pbuf.len, errors, 0, NULL),
-            pbuf.len);
-    PyBuffer_Release(&pbuf);
-    return result;
-}
-
-static PyObject *
-escape_encode(PyObject *self,
-              PyObject *args)
-{
-    PyObject *str;
-    Py_ssize_t size;
-    Py_ssize_t newsize;
-    const char *errors = NULL;
-    PyObject *v;
-
-    if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
-                          &PyBytes_Type, &str, &errors))
-        return NULL;
-
-    size = PyBytes_GET_SIZE(str);
-    if (size > PY_SSIZE_T_MAX / 4) {
-        PyErr_SetString(PyExc_OverflowError,
-            "string is too large to encode");
-            return NULL;
-    }
-    newsize = 4*size;
-    v = PyBytes_FromStringAndSize(NULL, newsize);
-
-    if (v == NULL) {
-        return NULL;
-    }
-    else {
-        Py_ssize_t i;
-        char c;
-        char *p = PyBytes_AS_STRING(v);
-
-        for (i = 0; i < size; i++) {
-            /* There's at least enough room for a hex escape */
-            assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4);
-            c = PyBytes_AS_STRING(str)[i];
-            if (c == '\'' || c == '\\')
-                *p++ = '\\', *p++ = c;
-            else if (c == '\t')
-                *p++ = '\\', *p++ = 't';
-            else if (c == '\n')
-                *p++ = '\\', *p++ = 'n';
-            else if (c == '\r')
-                *p++ = '\\', *p++ = 'r';
-            else if (c < ' ' || c >= 0x7f) {
-                *p++ = '\\';
-                *p++ = 'x';
-                *p++ = Py_hexdigits[(c & 0xf0) >> 4];
-                *p++ = Py_hexdigits[c & 0xf];
-            }
-            else
-                *p++ = c;
-        }
-        *p = '\0';
-        if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) {
-            return NULL;
-        }
-    }
-
-    return codec_tuple(v, size);
-}
-
-/* --- Decoder ------------------------------------------------------------ */
-
-static PyObject *
-unicode_internal_decode(PyObject *self,
-                        PyObject *args)
-{
-    PyObject *obj;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:unicode_internal_decode",
-                          &obj, &errors))
-        return NULL;
-
-    if (PyUnicode_Check(obj)) {
-        if (PyUnicode_READY(obj) < 0)
-            return NULL;
-        Py_INCREF(obj);
-        return codec_tuple(obj, PyUnicode_GET_LENGTH(obj));
-    }
-    else {
-        Py_buffer view;
-        PyObject *result;
-        if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
-            return NULL;
-
-        result = codec_tuple(
-                _PyUnicode_DecodeUnicodeInternal(view.buf, view.len, errors),
-                view.len);
-        PyBuffer_Release(&view);
-        return result;
-    }
-}
-
-static PyObject *
-utf_7_decode(PyObject *self,
-             PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_7_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len;
-
-    decoded = PyUnicode_DecodeUTF7Stateful(pbuf.buf, pbuf.len, errors,
-                                           final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-utf_8_decode(PyObject *self,
-            PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_8_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len;
-
-    decoded = PyUnicode_DecodeUTF8Stateful(pbuf.buf, pbuf.len, errors,
-                                           final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-utf_16_decode(PyObject *self,
-            PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = 0;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_16_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
-                                        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-utf_16_le_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = -1;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_16_le_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
-        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-utf_16_be_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = 1;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_16_be_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
-        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-/* This non-standard version also provides access to the byteorder
-   parameter of the builtin UTF-16 codec.
-
-   It returns a tuple (unicode, bytesread, byteorder) with byteorder
-   being the value in effect at the end of data.
-
-*/
-
-static PyObject *
-utf_16_ex_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = 0;
-    PyObject *unicode, *tuple;
-    int final = 0;
-    Py_ssize_t consumed;
-
-    if (!PyArg_ParseTuple(args, "y*|zii:utf_16_ex_decode",
-                          &pbuf, &errors, &byteorder, &final))
-        return NULL;
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    unicode = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
-                                        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (unicode == NULL)
-        return NULL;
-    tuple = Py_BuildValue("Oni", unicode, consumed, byteorder);
-    Py_DECREF(unicode);
-    return tuple;
-}
-
-static PyObject *
-utf_32_decode(PyObject *self,
-            PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = 0;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_32_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
-                                        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-utf_32_le_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = -1;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_32_le_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
-                                        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-utf_32_be_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = 1;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:utf_32_be_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
-                                        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-/* This non-standard version also provides access to the byteorder
-   parameter of the builtin UTF-32 codec.
-
-   It returns a tuple (unicode, bytesread, byteorder) with byteorder
-   being the value in effect at the end of data.
-
-*/
-
-static PyObject *
-utf_32_ex_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int byteorder = 0;
-    PyObject *unicode, *tuple;
-    int final = 0;
-    Py_ssize_t consumed;
-
-    if (!PyArg_ParseTuple(args, "y*|zii:utf_32_ex_decode",
-                          &pbuf, &errors, &byteorder, &final))
-        return NULL;
-    consumed = pbuf.len; /* This is overwritten unless final is true. */
-    unicode = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
-                                        &byteorder, final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (unicode == NULL)
-        return NULL;
-    tuple = Py_BuildValue("Oni", unicode, consumed, byteorder);
-    Py_DECREF(unicode);
-    return tuple;
-}
-
-static PyObject *
-unicode_escape_decode(PyObject *self,
-                     PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-        PyObject *unicode;
-
-    if (!PyArg_ParseTuple(args, "s*|z:unicode_escape_decode",
-                          &pbuf, &errors))
-        return NULL;
-
-    unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors);
-    PyBuffer_Release(&pbuf);
-    return codec_tuple(unicode, pbuf.len);
-}
-
-static PyObject *
-raw_unicode_escape_decode(PyObject *self,
-                        PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    PyObject *unicode;
-
-    if (!PyArg_ParseTuple(args, "s*|z:raw_unicode_escape_decode",
-                          &pbuf, &errors))
-        return NULL;
-
-    unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors);
-    PyBuffer_Release(&pbuf);
-    return codec_tuple(unicode, pbuf.len);
-}
-
-static PyObject *
-latin_1_decode(PyObject *self,
-               PyObject *args)
-{
-    Py_buffer pbuf;
-    PyObject *unicode;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|z:latin_1_decode",
-                          &pbuf, &errors))
-        return NULL;
-
-    unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors);
-    PyBuffer_Release(&pbuf);
-    return codec_tuple(unicode, pbuf.len);
-}
-
-static PyObject *
-ascii_decode(PyObject *self,
-             PyObject *args)
-{
-    Py_buffer pbuf;
-    PyObject *unicode;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|z:ascii_decode",
-                          &pbuf, &errors))
-        return NULL;
-
-    unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors);
-    PyBuffer_Release(&pbuf);
-    return codec_tuple(unicode, pbuf.len);
-}
-
-static PyObject *
-charmap_decode(PyObject *self,
-               PyObject *args)
-{
-    Py_buffer pbuf;
-    PyObject *unicode;
-    const char *errors = NULL;
-    PyObject *mapping = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|zO:charmap_decode",
-                          &pbuf, &errors, &mapping))
-        return NULL;
-    if (mapping == Py_None)
-        mapping = NULL;
-
-    unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors);
-    PyBuffer_Release(&pbuf);
-    return codec_tuple(unicode, pbuf.len);
-}
-
-#ifdef HAVE_MBCS
-
-static PyObject *
-mbcs_decode(PyObject *self,
-            PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded = NULL;
-
-    if (!PyArg_ParseTuple(args, "y*|zi:mbcs_decode",
-                          &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len;
-
-    decoded = PyUnicode_DecodeMBCSStateful(pbuf.buf, pbuf.len, errors,
-                                           final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-static PyObject *
-code_page_decode(PyObject *self,
-                 PyObject *args)
-{
-    Py_buffer pbuf;
-    const char *errors = NULL;
-    int final = 0;
-    Py_ssize_t consumed;
-    PyObject *decoded = NULL;
-    int code_page;
-
-    if (!PyArg_ParseTuple(args, "iy*|zi:code_page_decode",
-                          &code_page, &pbuf, &errors, &final))
-        return NULL;
-    consumed = pbuf.len;
-
-    decoded = PyUnicode_DecodeCodePageStateful(code_page,
-                                               pbuf.buf, pbuf.len, errors,
-                                               final ? NULL : &consumed);
-    PyBuffer_Release(&pbuf);
-    if (decoded == NULL)
-        return NULL;
-    return codec_tuple(decoded, consumed);
-}
-
-#endif /* HAVE_MBCS */
-
-/* --- Encoder ------------------------------------------------------------ */
-
-static PyObject *
-readbuffer_encode(PyObject *self,
-                  PyObject *args)
-{
-    Py_buffer pdata;
-    const char *data;
-    Py_ssize_t size;
-    const char *errors = NULL;
-    PyObject *result;
-
-    if (!PyArg_ParseTuple(args, "s*|z:readbuffer_encode",
-                          &pdata, &errors))
-        return NULL;
-    data = pdata.buf;
-    size = pdata.len;
-
-    result = PyBytes_FromStringAndSize(data, size);
-    PyBuffer_Release(&pdata);
-    return codec_tuple(result, size);
-}
-
-static PyObject *
-unicode_internal_encode(PyObject *self,
-                        PyObject *args)
-{
-    PyObject *obj;
-    const char *errors = NULL;
-
-    if (PyErr_WarnEx(PyExc_DeprecationWarning,
-                     "unicode_internal codec has been deprecated",
-                     1))
-        return NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:unicode_internal_encode",
-                          &obj, &errors))
-        return NULL;
-
-    if (PyUnicode_Check(obj)) {
-        Py_UNICODE *u;
-        Py_ssize_t len, size;
-
-        if (PyUnicode_READY(obj) < 0)
-            return NULL;
-
-        u = PyUnicode_AsUnicodeAndSize(obj, &len);
-        if (u == NULL)
-            return NULL;
-        if ((size_t)len > (size_t)PY_SSIZE_T_MAX / sizeof(Py_UNICODE))
-            return PyErr_NoMemory();
-        size = len * sizeof(Py_UNICODE);
-        return codec_tuple(PyBytes_FromStringAndSize((const char*)u, size),
-                           PyUnicode_GET_LENGTH(obj));
-    }
-    else {
-        Py_buffer view;
-        PyObject *result;
-        if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
-            return NULL;
-        result = codec_tuple(PyBytes_FromStringAndSize(view.buf, view.len), view.len);
-        PyBuffer_Release(&view);
-        return result;
-    }
-}
-
-static PyObject *
-utf_7_encode(PyObject *self,
-            PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:utf_7_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF7(str, 0, 0, errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-utf_8_encode(PyObject *self,
-            PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:utf_8_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(PyUnicode_AsEncodedString(str, "utf-8", errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-/* This version provides access to the byteorder parameter of the
-   builtin UTF-16 codecs as optional third argument. It defaults to 0
-   which means: use the native byte order and prepend the data with a
-   BOM mark.
-
-*/
-
-static PyObject *
-utf_16_encode(PyObject *self,
-            PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-    int byteorder = 0;
-
-    if (!PyArg_ParseTuple(args, "O|zi:utf_16_encode",
-                          &str, &errors, &byteorder))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF16(str, errors, byteorder),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-utf_16_le_encode(PyObject *self,
-                 PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:utf_16_le_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF16(str, errors, -1),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-utf_16_be_encode(PyObject *self,
-                 PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:utf_16_be_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF16(str, errors, +1),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-/* This version provides access to the byteorder parameter of the
-   builtin UTF-32 codecs as optional third argument. It defaults to 0
-   which means: use the native byte order and prepend the data with a
-   BOM mark.
-
-*/
-
-static PyObject *
-utf_32_encode(PyObject *self,
-            PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-    int byteorder = 0;
-
-    if (!PyArg_ParseTuple(args, "O|zi:utf_32_encode",
-                          &str, &errors, &byteorder))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF32(str, errors, byteorder),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-utf_32_le_encode(PyObject *self,
-                 PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:utf_32_le_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF32(str, errors, -1),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-utf_32_be_encode(PyObject *self,
-                 PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:utf_32_be_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeUTF32(str, errors, +1),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-unicode_escape_encode(PyObject *self,
-                     PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:unicode_escape_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(PyUnicode_AsUnicodeEscapeString(str),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-raw_unicode_escape_encode(PyObject *self,
-                        PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:raw_unicode_escape_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(PyUnicode_AsRawUnicodeEscapeString(str),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-latin_1_encode(PyObject *self,
-               PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:latin_1_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_AsLatin1String(str, errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-ascii_encode(PyObject *self,
-             PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:ascii_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_AsASCIIString(str, errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-charmap_encode(PyObject *self,
-             PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-    PyObject *mapping = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|zO:charmap_encode",
-                          &str, &errors, &mapping))
-        return NULL;
-    if (mapping == Py_None)
-        mapping = NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(_PyUnicode_EncodeCharmap(str, mapping, errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject*
-charmap_build(PyObject *self, PyObject *args)
-{
-    PyObject *map;
-    if (!PyArg_ParseTuple(args, "U:charmap_build", &map))
-        return NULL;
-    return PyUnicode_BuildEncodingMap(map);
-}
-
-#ifdef HAVE_MBCS
-
-static PyObject *
-mbcs_encode(PyObject *self,
-            PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTuple(args, "O|z:mbcs_encode",
-                          &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(PyUnicode_EncodeCodePage(CP_ACP, str, errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-static PyObject *
-code_page_encode(PyObject *self,
-                 PyObject *args)
-{
-    PyObject *str, *v;
-    const char *errors = NULL;
-    int code_page;
-
-    if (!PyArg_ParseTuple(args, "iO|z:code_page_encode",
-                          &code_page, &str, &errors))
-        return NULL;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL || PyUnicode_READY(str) < 0) {
-        Py_XDECREF(str);
-        return NULL;
-    }
-    v = codec_tuple(PyUnicode_EncodeCodePage(code_page,
-                                             str,
-                                             errors),
-                    PyUnicode_GET_LENGTH(str));
-    Py_DECREF(str);
-    return v;
-}
-
-#endif /* HAVE_MBCS */
-
-/* --- Error handler registry --------------------------------------------- */
-
-PyDoc_STRVAR(register_error__doc__,
-"register_error(errors, handler)\n\
-\n\
-Register the specified error handler under the name\n\
-errors. handler must be a callable object, that\n\
-will be called with an exception instance containing\n\
-information about the location of the encoding/decoding\n\
-error and must return a (replacement, new position) tuple.");
-
-static PyObject *register_error(PyObject *self, PyObject *args)
-{
-    const char *name;
-    PyObject *handler;
-
-    if (!PyArg_ParseTuple(args, "sO:register_error",
-                          &name, &handler))
-        return NULL;
-    if (PyCodec_RegisterError(name, handler))
-        return NULL;
-    Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(lookup_error__doc__,
-"lookup_error(errors) -> handler\n\
-\n\
-Return the error handler for the specified error handling name\n\
-or raise a LookupError, if no handler exists under this name.");
-
-static PyObject *lookup_error(PyObject *self, PyObject *args)
-{
-    const char *name;
-
-    if (!PyArg_ParseTuple(args, "s:lookup_error",
-                          &name))
-        return NULL;
-    return PyCodec_LookupError(name);
-}
-
-/* --- Module API --------------------------------------------------------- */
-
-static PyMethodDef _codecs_functions[] = {
-    {"register",                codec_register,                 METH_O,
-        register__doc__},
-    {"lookup",                  codec_lookup,                   METH_VARARGS,
-        lookup__doc__},
-    {"encode",     (PyCFunction)codec_encode,     METH_VARARGS|METH_KEYWORDS,
-        encode__doc__},
-    {"decode",     (PyCFunction)codec_decode,     METH_VARARGS|METH_KEYWORDS,
-        decode__doc__},
-    {"escape_encode",           escape_encode,                  METH_VARARGS},
-    {"escape_decode",           escape_decode,                  METH_VARARGS},
-    {"utf_8_encode",            utf_8_encode,                   METH_VARARGS},
-    {"utf_8_decode",            utf_8_decode,                   METH_VARARGS},
-    {"utf_7_encode",            utf_7_encode,                   METH_VARARGS},
-    {"utf_7_decode",            utf_7_decode,                   METH_VARARGS},
-    {"utf_16_encode",           utf_16_encode,                  METH_VARARGS},
-    {"utf_16_le_encode",        utf_16_le_encode,               METH_VARARGS},
-    {"utf_16_be_encode",        utf_16_be_encode,               METH_VARARGS},
-    {"utf_16_decode",           utf_16_decode,                  METH_VARARGS},
-    {"utf_16_le_decode",        utf_16_le_decode,               METH_VARARGS},
-    {"utf_16_be_decode",        utf_16_be_decode,               METH_VARARGS},
-    {"utf_16_ex_decode",        utf_16_ex_decode,               METH_VARARGS},
-    {"utf_32_encode",           utf_32_encode,                  METH_VARARGS},
-    {"utf_32_le_encode",        utf_32_le_encode,               METH_VARARGS},
-    {"utf_32_be_encode",        utf_32_be_encode,               METH_VARARGS},
-    {"utf_32_decode",           utf_32_decode,                  METH_VARARGS},
-    {"utf_32_le_decode",        utf_32_le_decode,               METH_VARARGS},
-    {"utf_32_be_decode",        utf_32_be_decode,               METH_VARARGS},
-    {"utf_32_ex_decode",        utf_32_ex_decode,               METH_VARARGS},
-    {"unicode_escape_encode",   unicode_escape_encode,          METH_VARARGS},
-    {"unicode_escape_decode",   unicode_escape_decode,          METH_VARARGS},
-    {"unicode_internal_encode", unicode_internal_encode,        METH_VARARGS},
-    {"unicode_internal_decode", unicode_internal_decode,        METH_VARARGS},
-    {"raw_unicode_escape_encode", raw_unicode_escape_encode,    METH_VARARGS},
-    {"raw_unicode_escape_decode", raw_unicode_escape_decode,    METH_VARARGS},
-    {"latin_1_encode",          latin_1_encode,                 METH_VARARGS},
-    {"latin_1_decode",          latin_1_decode,                 METH_VARARGS},
-    {"ascii_encode",            ascii_encode,                   METH_VARARGS},
-    {"ascii_decode",            ascii_decode,                   METH_VARARGS},
-    {"charmap_encode",          charmap_encode,                 METH_VARARGS},
-    {"charmap_decode",          charmap_decode,                 METH_VARARGS},
-    {"charmap_build",           charmap_build,                  METH_VARARGS},
-    {"readbuffer_encode",       readbuffer_encode,              METH_VARARGS},
-#ifdef HAVE_MBCS
-    {"mbcs_encode",             mbcs_encode,                    METH_VARARGS},
-    {"mbcs_decode",             mbcs_decode,                    METH_VARARGS},
-    {"code_page_encode",        code_page_encode,               METH_VARARGS},
-    {"code_page_decode",        code_page_decode,               METH_VARARGS},
-#endif
-    {"register_error",          register_error,                 METH_VARARGS,
-        register_error__doc__},
-    {"lookup_error",            lookup_error,                   METH_VARARGS,
-        lookup_error__doc__},
-    _CODECS__FORGET_CODEC_METHODDEF
-    {NULL, NULL}                /* sentinel */
-};
-
-static struct PyModuleDef codecsmodule = {
-        PyModuleDef_HEAD_INIT,
-        "_codecs",
-        NULL,
-        -1,
-        _codecs_functions,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-PyInit__codecs(void)
-{
-        return PyModule_Create(&codecsmodule);
-}
+/*[clinic end generated code: output=cdea83e21d76a900 input=a9049054013a1b77]*/
diff --git a/Modules/_cryptmodule.c b/Modules/clinic/_cryptmodule.c.h
copy from Modules/_cryptmodule.c
copy to Modules/clinic/_cryptmodule.c.h
--- a/Modules/_cryptmodule.c
+++ b/Modules/clinic/_cryptmodule.c.h
@@ -1,32 +1,5 @@
-/* cryptmodule.c - by Steve Majewski
- */
-
-#include "Python.h"
-
-#include <sys/types.h>
-
-/* Module crypt */
-
 /*[clinic input]
-module crypt
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c6252cf4f2f2ae81]*/
-
-
-/*[clinic input]
-crypt.crypt
-
-    word: 's'
-    salt: 's'
-    /
-
-Hash a *word* with the given *salt* and return the hashed password.
-
-*word* will usually be a user's password.  *salt* (either a random 2 or 16
-character string, possibly prefixed with $digit$ to indicate the method)
-will be used to perturb the encryption algorithm and produce distinct
-results for a given *word*.
-
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(crypt_crypt__doc__,
@@ -62,37 +35,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-crypt_crypt_impl(PyModuleDef *module, const char *word, const char *salt)
-/*[clinic end generated code: output=3eaacdf994a6ff23 input=4d93b6d0f41fbf58]*/
-{
-    /* On some platforms (AtheOS) crypt returns NULL for an invalid
-       salt. Return None in that case. XXX Maybe raise an exception?  */
-    return Py_BuildValue("s", crypt(word, salt));
-}
-
-
-static PyMethodDef crypt_methods[] = {
-    CRYPT_CRYPT_METHODDEF
-    {NULL,              NULL}           /* sentinel */
-};
-
-
-static struct PyModuleDef cryptmodule = {
-    PyModuleDef_HEAD_INIT,
-    "_crypt",
-    NULL,
-    -1,
-    crypt_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit__crypt(void)
-{
-    return PyModule_Create(&cryptmodule);
-}
+/*[clinic end generated code: output=b5b8d977189d19ea input=a9049054013a1b77]*/
diff --git a/Modules/_cursesmodule.c b/Modules/clinic/_cursesmodule.c.h
copy from Modules/_cursesmodule.c
copy to Modules/clinic/_cursesmodule.c.h
--- a/Modules/_cursesmodule.c
+++ b/Modules/clinic/_cursesmodule.c.h
@@ -1,586 +1,5 @@
-/*
- *   This is a curses module for Python.
- *
- *   Based on prior work by Lance Ellinghaus and Oliver Andrich
- *   Version 1.2 of this module: Copyright 1994 by Lance Ellinghouse,
- *    Cathedral City, California Republic, United States of America.
- *
- *   Version 1.5b1, heavily extended for ncurses by Oliver Andrich:
- *   Copyright 1996,1997 by Oliver Andrich, Koblenz, Germany.
- *
- *   Tidied for Python 1.6, and currently maintained by <amk at amk.ca>.
- *
- *   Permission is hereby granted, free of charge, to any person obtaining
- *   a copy of this source file to use, copy, modify, merge, or publish it
- *   subject to the following conditions:
- *
- *   The above copyright notice and this permission notice shall be included
- *   in all copies or in any new file that contains a substantial portion of
- *   this file.
- *
- *   THE  AUTHOR  MAKES  NO  REPRESENTATIONS ABOUT  THE  SUITABILITY  OF
- *   THE  SOFTWARE FOR  ANY  PURPOSE.  IT IS  PROVIDED  "AS IS"  WITHOUT
- *   EXPRESS OR  IMPLIED WARRANTY.  THE AUTHOR DISCLAIMS  ALL WARRANTIES
- *   WITH  REGARD TO  THIS  SOFTWARE, INCLUDING  ALL IMPLIED  WARRANTIES
- *   OF   MERCHANTABILITY,  FITNESS   FOR  A   PARTICULAR  PURPOSE   AND
- *   NON-INFRINGEMENT  OF THIRD  PARTY  RIGHTS. IN  NO  EVENT SHALL  THE
- *   AUTHOR  BE LIABLE  TO  YOU  OR ANY  OTHER  PARTY  FOR ANY  SPECIAL,
- *   INDIRECT,  OR  CONSEQUENTIAL  DAMAGES  OR  ANY  DAMAGES  WHATSOEVER
- *   WHETHER IN AN  ACTION OF CONTRACT, NEGLIGENCE,  STRICT LIABILITY OR
- *   ANY OTHER  ACTION ARISING OUT OF  OR IN CONNECTION WITH  THE USE OR
- *   PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
-
-  A number of SysV or ncurses functions don't have wrappers yet; if you
-  need a given function, add it and send a patch.  See
-  http://www.python.org/dev/patches/ for instructions on how to submit
-  patches to Python.
-
-  Here's a list of currently unsupported functions:
-
-  addchnstr addchstr color_set define_key
-  del_curterm delscreen dupwin inchnstr inchstr innstr keyok
-  mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr
-  mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr
-  mvwinchnstr mvwinchstr mvwinnstr newterm
-  restartterm ripoffline scr_dump
-  scr_init scr_restore scr_set scrl set_curterm set_term setterm
-  tgetent tgetflag tgetnum tgetstr tgoto timeout tputs
-  vidattr vidputs waddchnstr waddchstr
-  wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl
-
-  Low-priority:
-  slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff
-  slk_attron slk_attrset slk_clear slk_color slk_init slk_label
-  slk_noutrefresh slk_refresh slk_restore slk_set slk_touch
-
-  Menu extension (ncurses and probably SYSV):
-  current_item free_item free_menu item_count item_description
-  item_index item_init item_name item_opts item_opts_off
-  item_opts_on item_term item_userptr item_value item_visible
-  menu_back menu_driver menu_fore menu_format menu_grey
-  menu_init menu_items menu_mark menu_opts menu_opts_off
-  menu_opts_on menu_pad menu_pattern menu_request_by_name
-  menu_request_name menu_spacing menu_sub menu_term menu_userptr
-  menu_win new_item new_menu pos_menu_cursor post_menu
-  scale_menu set_current_item set_item_init set_item_opts
-  set_item_term set_item_userptr set_item_value set_menu_back
-  set_menu_fore set_menu_format set_menu_grey set_menu_init
-  set_menu_items set_menu_mark set_menu_opts set_menu_pad
-  set_menu_pattern set_menu_spacing set_menu_sub set_menu_term
-  set_menu_userptr set_menu_win set_top_row top_row unpost_menu
-
-  Form extension (ncurses and probably SYSV):
-  current_field data_ahead data_behind dup_field
-  dynamic_fieldinfo field_arg field_back field_buffer
-  field_count field_fore field_index field_info field_init
-  field_just field_opts field_opts_off field_opts_on field_pad
-  field_status field_term field_type field_userptr form_driver
-  form_fields form_init form_opts form_opts_off form_opts_on
-  form_page form_request_by_name form_request_name form_sub
-  form_term form_userptr form_win free_field free_form
-  link_field link_fieldtype move_field new_field new_form
-  new_page pos_form_cursor post_form scale_form
-  set_current_field set_field_back set_field_buffer
-  set_field_fore set_field_init set_field_just set_field_opts
-  set_field_pad set_field_status set_field_term set_field_type
-  set_field_userptr set_fieldtype_arg set_fieldtype_choice
-  set_form_fields set_form_init set_form_opts set_form_page
-  set_form_sub set_form_term set_form_userptr set_form_win
-  set_max_field set_new_page unpost_form
-
-
-*/
-
-/* Release Number */
-
-char *PyCursesVersion = "2.2";
-
-/* Includes */
-
-#define PY_SSIZE_T_CLEAN
-
-#include "Python.h"
-
-
-#ifdef __hpux
-#define STRICT_SYSV_CURSES
-#endif
-
-#define CURSES_MODULE
-#include "py_curses.h"
-
-/*  These prototypes are in <term.h>, but including this header
-    #defines many common symbols (such as "lines") which breaks the
-    curses module in other ways.  So the code will just specify
-    explicit prototypes here. */
-extern int setupterm(char *,int,int *);
-#ifdef __sgi
-#include <term.h>
-#endif
-
-#ifdef HAVE_LANGINFO_H
-#include <langinfo.h>
-#endif
-
-#if !defined(HAVE_NCURSES_H) && (defined(sgi) || defined(__sun) || defined(SCO5))
-#define STRICT_SYSV_CURSES       /* Don't use ncurses extensions */
-typedef chtype attr_t;           /* No attr_t type is available */
-#endif
-
-#if defined(_AIX)
-#define STRICT_SYSV_CURSES
-#endif
-
 /*[clinic input]
-module curses
-class curses.window "PyCursesWindowObject *" "&PyCursesWindow_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=88c860abdbb50e0c]*/
-
-/* Definition of exception curses.error */
-
-static PyObject *PyCursesError;
-
-/* Tells whether setupterm() has been called to initialise terminfo.  */
-static int initialised_setupterm = FALSE;
-
-/* Tells whether initscr() has been called to initialise curses.  */
-static int initialised = FALSE;
-
-/* Tells whether start_color() has been called to initialise color usage. */
-static int initialisedcolors = FALSE;
-
-static char *screen_encoding = NULL;
-
-/* Utility Macros */
-#define PyCursesSetupTermCalled                                         \
-    if (initialised_setupterm != TRUE) {                                \
-        PyErr_SetString(PyCursesError,                                  \
-                        "must call (at least) setupterm() first");      \
-        return 0; }
-
-#define PyCursesInitialised                             \
-    if (initialised != TRUE) {                          \
-        PyErr_SetString(PyCursesError,                  \
-                        "must call initscr() first");   \
-        return 0; }
-
-#define PyCursesInitialisedColor                                \
-    if (initialisedcolors != TRUE) {                            \
-        PyErr_SetString(PyCursesError,                          \
-                        "must call start_color() first");       \
-        return 0; }
-
-/* Utility Functions */
-
-/*
- * Check the return code from a curses function and return None
- * or raise an exception as appropriate.  These are exported using the
- * capsule API.
- */
-
-static PyObject *
-PyCursesCheckERR(int code, const char *fname)
-{
-    if (code != ERR) {
-        Py_INCREF(Py_None);
-        return Py_None;
-    } else {
-        if (fname == NULL) {
-            PyErr_SetString(PyCursesError, catchall_ERR);
-        } else {
-            PyErr_Format(PyCursesError, "%s() returned ERR", fname);
-        }
-        return NULL;
-    }
-}
-
-/* Convert an object to a byte (an integer of type chtype):
-
-   - int
-   - bytes of length 1
-   - str of length 1
-
-   Return 1 on success, 0 on error (invalid type or integer overflow). */
-static int
-PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
-{
-    long value;
-    if(PyBytes_Check(obj) && PyBytes_Size(obj) == 1) {
-        value = (unsigned char)PyBytes_AsString(obj)[0];
-    }
-    else if (PyUnicode_Check(obj)) {
-        if (PyUnicode_GetLength(obj) != 1) {
-            PyErr_Format(PyExc_TypeError,
-                         "expect bytes or str of length 1, or int, "
-                         "got a str of length %zi",
-                         PyUnicode_GET_LENGTH(obj));
-            return 0;
-        }
-        value = PyUnicode_READ_CHAR(obj, 0);
-        if (128 < value) {
-            PyObject *bytes;
-            const char *encoding;
-            if (win)
-                encoding = win->encoding;
-            else
-                encoding = screen_encoding;
-            bytes = PyUnicode_AsEncodedObject(obj, encoding, NULL);
-            if (bytes == NULL)
-                return 0;
-            if (PyBytes_GET_SIZE(bytes) == 1)
-                value = (unsigned char)PyBytes_AS_STRING(bytes)[0];
-            else
-                value = -1;
-            Py_DECREF(bytes);
-            if (value < 0)
-                goto overflow;
-        }
-    }
-    else if (PyLong_CheckExact(obj)) {
-        int long_overflow;
-        value = PyLong_AsLongAndOverflow(obj, &long_overflow);
-        if (long_overflow)
-            goto overflow;
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "expect bytes or str of length 1, or int, got %s",
-                     Py_TYPE(obj)->tp_name);
-        return 0;
-    }
-    *ch = (chtype)value;
-    if ((long)*ch != value)
-        goto overflow;
-    return 1;
-
-overflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "byte doesn't fit in chtype");
-    return 0;
-}
-
-/* Convert an object to a byte (chtype) or a character (cchar_t):
-
-    - int
-    - bytes of length 1
-    - str of length 1
-
-   Return:
-
-    - 2 if obj is a character (written into *wch)
-    - 1 if obj is a byte (written into *ch)
-    - 0 on error: raise an exception */
-static int
-PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
-                          chtype *ch
-#ifdef HAVE_NCURSESW
-                          , cchar_t *wch
-#endif
-                          )
-{
-    long value;
-#ifdef HAVE_NCURSESW
-    wchar_t buffer[2];
-#endif
-
-    if (PyUnicode_Check(obj)) {
-#ifdef HAVE_NCURSESW
-        if (PyUnicode_AsWideChar(obj, buffer, 2) != 1) {
-            PyErr_Format(PyExc_TypeError,
-                         "expect bytes or str of length 1, or int, "
-                         "got a str of length %zi",
-                         PyUnicode_GET_LENGTH(obj));
-            return 0;
-        }
-        memset(wch->chars, 0, sizeof(wch->chars));
-        wch->chars[0] = buffer[0];
-        return 2;
-#else
-        return PyCurses_ConvertToChtype(win, obj, ch);
-#endif
-    }
-    else if(PyBytes_Check(obj) && PyBytes_Size(obj) == 1) {
-        value = (unsigned char)PyBytes_AsString(obj)[0];
-    }
-    else if (PyLong_CheckExact(obj)) {
-        int overflow;
-        value = PyLong_AsLongAndOverflow(obj, &overflow);
-        if (overflow) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "int doesn't fit in long");
-            return 0;
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "expect bytes or str of length 1, or int, got %s",
-                     Py_TYPE(obj)->tp_name);
-        return 0;
-    }
-
-    *ch = (chtype)value;
-    if ((long)*ch != value) {
-        PyErr_Format(PyExc_OverflowError,
-                     "byte doesn't fit in chtype");
-        return 0;
-    }
-    return 1;
-}
-
-/* Convert an object to a byte string (char*) or a wide character string
-   (wchar_t*). Return:
-
-    - 2 if obj is a character string (written into *wch)
-    - 1 if obj is a byte string (written into *bytes)
-    - 0 on error: raise an exception */
-static int
-PyCurses_ConvertToString(PyCursesWindowObject *win, PyObject *obj,
-                         PyObject **bytes, wchar_t **wstr)
-{
-    if (PyUnicode_Check(obj)) {
-#ifdef HAVE_NCURSESW
-        assert (wstr != NULL);
-        *wstr = PyUnicode_AsWideCharString(obj, NULL);
-        if (*wstr == NULL)
-            return 0;
-        return 2;
-#else
-        assert (wstr == NULL);
-        *bytes = PyUnicode_AsEncodedObject(obj, win->encoding, NULL);
-        if (*bytes == NULL)
-            return 0;
-        return 1;
-#endif
-    }
-    else if (PyBytes_Check(obj)) {
-        Py_INCREF(obj);
-        *bytes = obj;
-        return 1;
-    }
-
-    PyErr_Format(PyExc_TypeError, "expect bytes or str, got %s",
-                 Py_TYPE(obj)->tp_name);
-    return 0;
-}
-
-/* Function versions of the 3 functions for testing whether curses has been
-   initialised or not. */
-
-static int func_PyCursesSetupTermCalled(void)
-{
-    PyCursesSetupTermCalled;
-    return 1;
-}
-
-static int func_PyCursesInitialised(void)
-{
-    PyCursesInitialised;
-    return 1;
-}
-
-static int func_PyCursesInitialisedColor(void)
-{
-    PyCursesInitialisedColor;
-    return 1;
-}
-
-/*****************************************************************************
- The Window Object
-******************************************************************************/
-
-/* Definition of the window type */
-
-PyTypeObject PyCursesWindow_Type;
-
-/* Function prototype macros for Window object
-
-   X - function name
-   TYPE - parameter Type
-   ERGSTR - format string for construction of the return value
-   PARSESTR - format string for argument parsing
-*/
-
-#define Window_NoArgNoReturnFunction(X)                 \
-    static PyObject *PyCursesWindow_ ## X               \
-    (PyCursesWindowObject *self, PyObject *args)        \
-    { return PyCursesCheckERR(X(self->win), # X); }
-
-#define Window_NoArgTrueFalseFunction(X)                                \
-    static PyObject * PyCursesWindow_ ## X                              \
-    (PyCursesWindowObject *self)                                        \
-    {                                                                   \
-        if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \
-        else { Py_INCREF(Py_True); return Py_True; } }
-
-#define Window_NoArgNoReturnVoidFunction(X)                     \
-    static PyObject * PyCursesWindow_ ## X                      \
-    (PyCursesWindowObject *self)                                \
-    {                                                           \
-        X(self->win); Py_INCREF(Py_None); return Py_None; }
-
-#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR)               \
-    static PyObject * PyCursesWindow_ ## X                              \
-    (PyCursesWindowObject *self)                                        \
-    {                                                                   \
-        TYPE arg1, arg2;                                                \
-        X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); }
-
-#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR)            \
-    static PyObject * PyCursesWindow_ ## X                              \
-    (PyCursesWindowObject *self, PyObject *args)                        \
-    {                                                                   \
-        TYPE arg1;                                                      \
-        if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL;      \
-        X(self->win,arg1); Py_INCREF(Py_None); return Py_None; }
-
-#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR)                \
-    static PyObject * PyCursesWindow_ ## X                              \
-    (PyCursesWindowObject *self, PyObject *args)                        \
-    {                                                                   \
-        TYPE arg1;                                                      \
-        if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL;       \
-        return PyCursesCheckERR(X(self->win, arg1), # X); }
-
-#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR)                \
-    static PyObject * PyCursesWindow_ ## X                              \
-    (PyCursesWindowObject *self, PyObject *args)                        \
-    {                                                                   \
-        TYPE arg1, arg2;                                                \
-        if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \
-        return PyCursesCheckERR(X(self->win, arg1, arg2), # X); }
-
-/* ------------- WINDOW routines --------------- */
-
-Window_NoArgNoReturnFunction(untouchwin)
-Window_NoArgNoReturnFunction(touchwin)
-Window_NoArgNoReturnFunction(redrawwin)
-Window_NoArgNoReturnFunction(winsertln)
-Window_NoArgNoReturnFunction(werase)
-Window_NoArgNoReturnFunction(wdeleteln)
-
-Window_NoArgTrueFalseFunction(is_wintouched)
-
-Window_NoArgNoReturnVoidFunction(wsyncup)
-Window_NoArgNoReturnVoidFunction(wsyncdown)
-Window_NoArgNoReturnVoidFunction(wstandend)
-Window_NoArgNoReturnVoidFunction(wstandout)
-Window_NoArgNoReturnVoidFunction(wcursyncup)
-Window_NoArgNoReturnVoidFunction(wclrtoeol)
-Window_NoArgNoReturnVoidFunction(wclrtobot)
-Window_NoArgNoReturnVoidFunction(wclear)
-
-Window_OneArgNoReturnVoidFunction(idcok, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnVoidFunction(immedok, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnVoidFunction(wtimeout, int, "i;delay")
-
-Window_NoArg2TupleReturnFunction(getyx, int, "ii")
-Window_NoArg2TupleReturnFunction(getbegyx, int, "ii")
-Window_NoArg2TupleReturnFunction(getmaxyx, int, "ii")
-Window_NoArg2TupleReturnFunction(getparyx, int, "ii")
-
-Window_OneArgNoReturnFunction(clearok, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnFunction(idlok, int, "i;True(1) or False(0)")
-#if defined(__NetBSD__)
-Window_OneArgNoReturnVoidFunction(keypad, int, "i;True(1) or False(0)")
-#else
-Window_OneArgNoReturnFunction(keypad, int, "i;True(1) or False(0)")
-#endif
-Window_OneArgNoReturnFunction(leaveok, int, "i;True(1) or False(0)")
-#if defined(__NetBSD__)
-Window_OneArgNoReturnVoidFunction(nodelay, int, "i;True(1) or False(0)")
-#else
-Window_OneArgNoReturnFunction(nodelay, int, "i;True(1) or False(0)")
-#endif
-Window_OneArgNoReturnFunction(notimeout, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnFunction(scrollok, int, "i;True(1) or False(0)")
-Window_OneArgNoReturnFunction(winsdelln, int, "i;nlines")
-Window_OneArgNoReturnFunction(syncok, int, "i;True(1) or False(0)")
-
-Window_TwoArgNoReturnFunction(mvwin, int, "ii;y,x")
-Window_TwoArgNoReturnFunction(mvderwin, int, "ii;y,x")
-Window_TwoArgNoReturnFunction(wmove, int, "ii;y,x")
-#ifndef STRICT_SYSV_CURSES
-Window_TwoArgNoReturnFunction(wresize, int, "ii;lines,columns")
-#endif
-
-/* Allocation and deallocation of Window Objects */
-
-static PyObject *
-PyCursesWindow_New(WINDOW *win, const char *encoding)
-{
-    PyCursesWindowObject *wo;
-
-    if (encoding == NULL) {
-#if defined(MS_WINDOWS)
-        char *buffer[100];
-        UINT cp;
-        cp = GetConsoleOutputCP();
-        if (cp != 0) {
-            PyOS_snprintf(buffer, sizeof(buffer), "cp%u", cp);
-            encoding = buffer;
-        }
-#elif defined(CODESET)
-        const char *codeset = nl_langinfo(CODESET);
-        if (codeset != NULL && codeset[0] != 0)
-            encoding = codeset;
-#endif
-        if (encoding == NULL)
-            encoding = "utf-8";
-    }
-
-    wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type);
-    if (wo == NULL) return NULL;
-    wo->win = win;
-    wo->encoding = _PyMem_Strdup(encoding);
-    if (wo->encoding == NULL) {
-        Py_DECREF(wo);
-        PyErr_NoMemory();
-        return NULL;
-    }
-    return (PyObject *)wo;
-}
-
-static void
-PyCursesWindow_Dealloc(PyCursesWindowObject *wo)
-{
-    if (wo->win != stdscr) delwin(wo->win);
-    if (wo->encoding != NULL)
-        PyMem_Free(wo->encoding);
-    PyObject_DEL(wo);
-}
-
-/* Addch, Addstr, Addnstr */
-
-/*[clinic input]
-
-curses.window.addch
-
-    [
-    y: int
-      Y-coordinate.
-    x: int
-      X-coordinate.
-    ]
-
-    ch: object
-      Character to add.
-
-    [
-    attr: long
-      Attributes for the character.
-    ]
-    /
-
-Paint character ch at (y, x) with attributes attr.
-
-Paint character ch at (y, x) with attributes attr,
-overwriting any character previously painted at that location.
-By default, the character position and attributes are the
-current settings for the window object.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(curses_window_addch__doc__,
@@ -648,2875 +67,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1, int y, int x, PyObject *ch, int group_right_1, long attr)
-/*[clinic end generated code: output=d4b97cc287010c54 input=5a41efb34a2de338]*/
-{
-    PyCursesWindowObject *cwself = (PyCursesWindowObject *)self;
-    int coordinates_group = group_left_1;
-    int attr_group = group_right_1;
-    int rtn;
-    int type;
-    chtype cch;
-#ifdef HAVE_NCURSESW
-    cchar_t wch;
-#endif
-    const char *funcname;
-
-    if (!attr_group)
-      attr = A_NORMAL;
-
-#ifdef HAVE_NCURSESW
-    type = PyCurses_ConvertToCchar_t(cwself, ch, &cch, &wch);
-    if (type == 2) {
-        funcname = "add_wch";
-        wch.attr = attr;
-        if (coordinates_group)
-            rtn = mvwadd_wch(cwself->win,y,x, &wch);
-        else {
-            rtn = wadd_wch(cwself->win, &wch);
-        }
-    }
-    else
-#else
-    type = PyCurses_ConvertToCchar_t(cwself, ch, &cch);
-#endif
-    if (type == 1) {
-        funcname = "addch";
-        if (coordinates_group)
-            rtn = mvwaddch(cwself->win,y,x, cch | attr);
-        else {
-            rtn = waddch(cwself->win, cch | attr);
-        }
-    }
-    else {
-        return NULL;
-    }
-    return PyCursesCheckERR(rtn, funcname);
-}
-
-static PyObject *
-PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn;
-    int x, y;
-    int strtype;
-    PyObject *strobj, *bytesobj = NULL;
-#ifdef HAVE_NCURSESW
-    wchar_t *wstr = NULL;
-#endif
-    attr_t attr = A_NORMAL , attr_old = A_NORMAL;
-    long lattr;
-    int use_xy = FALSE, use_attr = FALSE;
-    const char *funcname;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"O;str", &strobj))
-            return NULL;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"Ol;str,attr", &strobj, &lattr))
-            return NULL;
-        attr = lattr;
-        use_attr = TRUE;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"iiO;int,int,str", &y, &x, &strobj))
-            return NULL;
-        use_xy = TRUE;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args,"iiOl;int,int,str,attr", &y, &x, &strobj, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = use_attr = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments");
-        return NULL;
-    }
-#ifdef HAVE_NCURSESW
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, &wstr);
-#else
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, NULL);
-#endif
-    if (strtype == 0)
-        return NULL;
-    if (use_attr == TRUE) {
-        attr_old = getattrs(self->win);
-        (void)wattrset(self->win,attr);
-    }
-#ifdef HAVE_NCURSESW
-    if (strtype == 2) {
-        funcname = "addwstr";
-        if (use_xy == TRUE)
-            rtn = mvwaddwstr(self->win,y,x,wstr);
-        else
-            rtn = waddwstr(self->win,wstr);
-        PyMem_Free(wstr);
-    }
-    else
-#endif
-    {
-        char *str = PyBytes_AS_STRING(bytesobj);
-        funcname = "addstr";
-        if (use_xy == TRUE)
-            rtn = mvwaddstr(self->win,y,x,str);
-        else
-            rtn = waddstr(self->win,str);
-        Py_DECREF(bytesobj);
-    }
-    if (use_attr == TRUE)
-        (void)wattrset(self->win,attr_old);
-    return PyCursesCheckERR(rtn, funcname);
-}
-
-static PyObject *
-PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn, x, y, n;
-    int strtype;
-    PyObject *strobj, *bytesobj = NULL;
-#ifdef HAVE_NCURSESW
-    wchar_t *wstr = NULL;
-#endif
-    attr_t attr = A_NORMAL , attr_old = A_NORMAL;
-    long lattr;
-    int use_xy = FALSE, use_attr = FALSE;
-    const char *funcname;
-
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args,"Oi;str,n", &strobj, &n))
-            return NULL;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"Oil;str,n,attr", &strobj, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        use_attr = TRUE;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args,"iiOi;y,x,str,n", &y, &x, &strobj, &n))
-            return NULL;
-        use_xy = TRUE;
-        break;
-    case 5:
-        if (!PyArg_ParseTuple(args,"iiOil;y,x,str,n,attr", &y, &x, &strobj, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = use_attr = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments");
-        return NULL;
-    }
-#ifdef HAVE_NCURSESW
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, &wstr);
-#else
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, NULL);
-#endif
-    if (strtype == 0)
-        return NULL;
-
-    if (use_attr == TRUE) {
-        attr_old = getattrs(self->win);
-        (void)wattrset(self->win,attr);
-    }
-#ifdef HAVE_NCURSESW
-    if (strtype == 2) {
-        funcname = "addnwstr";
-        if (use_xy == TRUE)
-            rtn = mvwaddnwstr(self->win,y,x,wstr,n);
-        else
-            rtn = waddnwstr(self->win,wstr,n);
-        PyMem_Free(wstr);
-    }
-    else
-#endif
-    {
-        char *str = PyBytes_AS_STRING(bytesobj);
-        funcname = "addnstr";
-        if (use_xy == TRUE)
-            rtn = mvwaddnstr(self->win,y,x,str,n);
-        else
-            rtn = waddnstr(self->win,str,n);
-        Py_DECREF(bytesobj);
-    }
-    if (use_attr == TRUE)
-        (void)wattrset(self->win,attr_old);
-    return PyCursesCheckERR(rtn, funcname);
-}
-
-static PyObject *
-PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype bkgd;
-    attr_t attr = A_NORMAL;
-    long lattr;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "O;ch or int", &temp))
-            return NULL;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments");
-        return NULL;
-    }
-
-    if (!PyCurses_ConvertToChtype(self, temp, &bkgd))
-        return NULL;
-
-    return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd");
-}
-
-static PyObject *
-PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args)
-{
-    long lattr;
-    if (!PyArg_ParseTuple(args,"l;attr", &lattr))
-        return NULL;
-    return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff");
-}
-
-static PyObject *
-PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args)
-{
-    long lattr;
-    if (!PyArg_ParseTuple(args,"l;attr", &lattr))
-        return NULL;
-    return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron");
-}
-
-static PyObject *
-PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args)
-{
-    long lattr;
-    if (!PyArg_ParseTuple(args,"l;attr", &lattr))
-        return NULL;
-    return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset");
-}
-
-static PyObject *
-PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype bkgd;
-    attr_t attr = A_NORMAL;
-    long lattr;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "O;ch or int", &temp))
-            return NULL;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments");
-        return NULL;
-    }
-
-    if (!PyCurses_ConvertToChtype(self, temp, &bkgd))
-        return NULL;
-
-    wbkgdset(self->win, bkgd | attr);
-    return PyCursesCheckERR(0, "bkgdset");
-}
-
-static PyObject *
-PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *temp[8];
-    chtype ch[8];
-    int i;
-
-    /* Clear the array of parameters */
-    for(i=0; i<8; i++) {
-        temp[i] = NULL;
-        ch[i] = 0;
-    }
-
-    if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br",
-                          &temp[0], &temp[1], &temp[2], &temp[3],
-                          &temp[4], &temp[5], &temp[6], &temp[7]))
-        return NULL;
-
-    for(i=0; i<8; i++) {
-        if (temp[i] != NULL && !PyCurses_ConvertToChtype(self, temp[i], &ch[i]))
-            return NULL;
-    }
-
-    wborder(self->win,
-            ch[0], ch[1], ch[2], ch[3],
-            ch[4], ch[5], ch[6], ch[7]);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *
-PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args)
-{
-    chtype ch1=0,ch2=0;
-    switch(PyTuple_Size(args)){
-    case 0: break;
-    default:
-        if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2))
-            return NULL;
-    }
-    box(self->win,ch1,ch2);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-#if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION)
-#define py_mvwdelch mvwdelch
-#else
-int py_mvwdelch(WINDOW *w, int y, int x)
-{
-    mvwdelch(w,y,x);
-    /* On HP/UX, mvwdelch already returns. On other systems,
-       we may well run into this return statement. */
-    return 0;
-}
-#endif
-
-/* chgat, added by Fabian Kreutz <fabian.kreutz at gmx.net> */
-
-static PyObject *
-PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn;
-    int x, y;
-    int num = -1;
-    short color;
-    attr_t attr = A_NORMAL;
-    long lattr;
-    int use_xy = FALSE;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"l;attr", &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = TRUE;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments");
-        return NULL;
-    }
-
-    color = (short)((attr >> 8) & 0xff);
-    attr = attr - (color << 8);
-
-    if (use_xy == TRUE) {
-        rtn = mvwchgat(self->win,y,x,num,attr,color,NULL);
-        touchline(self->win,y,1);
-    } else {
-        getyx(self->win,y,x);
-        rtn = wchgat(self->win,num,attr,color,NULL);
-        touchline(self->win,y,1);
-    }
-    return PyCursesCheckERR(rtn, "chgat");
-}
-
-
-static PyObject *
-PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn;
-    int x, y;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        rtn = wdelch(self->win);
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x))
-            return NULL;
-        rtn = py_mvwdelch(self->win,y,x);
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments");
-        return NULL;
-    }
-    return PyCursesCheckERR(rtn, "[mv]wdelch");
-}
-
-static PyObject *
-PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args)
-{
-    WINDOW *win;
-    int nlines, ncols, begin_y, begin_x;
-
-    nlines = 0;
-    ncols  = 0;
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x))
-            return NULL;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x",
-                              &nlines,&ncols,&begin_y,&begin_x))
-            return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments");
-        return NULL;
-    }
-
-    win = derwin(self->win,nlines,ncols,begin_y,begin_x);
-
-    if (win == NULL) {
-        PyErr_SetString(PyCursesError, catchall_NULL);
-        return NULL;
-    }
-
-    return (PyObject *)PyCursesWindow_New(win, NULL);
-}
-
-static PyObject *
-PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype ch;
-    attr_t attr = A_NORMAL;
-    long lattr;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"O;ch or int", &temp))
-            return NULL;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments");
-
-
-        return NULL;
-    }
-
-    if (!PyCurses_ConvertToChtype(self, temp, &ch))
-        return NULL;
-
-#ifdef WINDOW_HAS_FLAGS
-    if (self->win->_flags & _ISPAD)
-        return PyCursesCheckERR(pechochar(self->win, ch | attr),
-                                "echochar");
-    else
-#endif
-        return PyCursesCheckERR(wechochar(self->win, ch | attr),
-                                "echochar");
-}
-
-#ifdef NCURSES_MOUSE_VERSION
-static PyObject *
-PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y;
-    if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x))
-        return NULL;
-
-    return PyLong_FromLong( wenclose(self->win,y,x) );
-}
-#endif
-
-static PyObject *
-PyCursesWindow_GetBkgd(PyCursesWindowObject *self)
-{
-    return PyLong_FromLong((long) getbkgd(self->win));
-}
-
-static PyObject *
-PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y;
-    int rtn;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        Py_BEGIN_ALLOW_THREADS
-        rtn = wgetch(self->win);
-        Py_END_ALLOW_THREADS
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x))
-            return NULL;
-        Py_BEGIN_ALLOW_THREADS
-        rtn = mvwgetch(self->win,y,x);
-        Py_END_ALLOW_THREADS
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments");
-        return NULL;
-    }
-    return PyLong_FromLong((long)rtn);
-}
-
-static PyObject *
-PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y;
-    int rtn;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        Py_BEGIN_ALLOW_THREADS
-        rtn = wgetch(self->win);
-        Py_END_ALLOW_THREADS
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x))
-            return NULL;
-        Py_BEGIN_ALLOW_THREADS
-        rtn = mvwgetch(self->win,y,x);
-        Py_END_ALLOW_THREADS
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments");
-        return NULL;
-    }
-    if (rtn == ERR) {
-        /* getch() returns ERR in nodelay mode */
-        PyErr_CheckSignals();
-        if (!PyErr_Occurred())
-            PyErr_SetString(PyCursesError, "no input");
-        return NULL;
-    } else if (rtn<=255) {
-        return Py_BuildValue("C", rtn);
-    } else {
-        const char *knp;
-#if defined(__NetBSD__)
-        knp = unctrl(rtn);
-#else
-        knp = keyname(rtn);
-#endif
-        return PyUnicode_FromString((knp == NULL) ? "" : knp);
-    }
-}
-
-#ifdef HAVE_NCURSESW
-static PyObject *
-PyCursesWindow_Get_WCh(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y;
-    int ct;
-    wint_t rtn;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        Py_BEGIN_ALLOW_THREADS
-        ct = wget_wch(self->win,&rtn);
-        Py_END_ALLOW_THREADS
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x))
-            return NULL;
-        Py_BEGIN_ALLOW_THREADS
-        ct = mvwget_wch(self->win,y,x,&rtn);
-        Py_END_ALLOW_THREADS
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "get_wch requires 0 or 2 arguments");
-        return NULL;
-    }
-    if (ct == ERR) {
-        if (PyErr_CheckSignals())
-            return NULL;
-
-        /* get_wch() returns ERR in nodelay mode */
-        PyErr_SetString(PyCursesError, "no input");
-        return NULL;
-    }
-    if (ct == KEY_CODE_YES)
-        return PyLong_FromLong(rtn);
-    else
-        return PyUnicode_FromOrdinal(rtn);
-}
-#endif
-
-static PyObject *
-PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y, n;
-    char rtn[1024]; /* This should be big enough.. I hope */
-    int rtn2;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        Py_BEGIN_ALLOW_THREADS
-        rtn2 = wgetnstr(self->win,rtn, 1023);
-        Py_END_ALLOW_THREADS
-        break;
-    case 1:
-        if (!PyArg_ParseTuple(args,"i;n", &n))
-            return NULL;
-        Py_BEGIN_ALLOW_THREADS
-        rtn2 = wgetnstr(self->win, rtn, Py_MIN(n, 1023));
-        Py_END_ALLOW_THREADS
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x))
-            return NULL;
-        Py_BEGIN_ALLOW_THREADS
-#ifdef STRICT_SYSV_CURSES
-        rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023);
-#else
-        rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023);
-#endif
-        Py_END_ALLOW_THREADS
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n))
-            return NULL;
-#ifdef STRICT_SYSV_CURSES
-        Py_BEGIN_ALLOW_THREADS
-        rtn2 = wmove(self->win,y,x)==ERR ? ERR :
-        wgetnstr(self->win, rtn, Py_MIN(n, 1023));
-        Py_END_ALLOW_THREADS
-#else
-        Py_BEGIN_ALLOW_THREADS
-        rtn2 = mvwgetnstr(self->win, y, x, rtn, Py_MIN(n, 1023));
-        Py_END_ALLOW_THREADS
-#endif
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments");
-        return NULL;
-    }
-    if (rtn2 == ERR)
-        rtn[0] = 0;
-    return PyBytes_FromString(rtn);
-}
-
-static PyObject *
-PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype ch;
-    int n, x, y, code = OK;
-    attr_t attr = A_NORMAL;
-    long lattr;
-
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n))
-            return NULL;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n))
-            return NULL;
-        code = wmove(self->win, y, x);
-        break;
-    case 5:
-        if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr",
-                              &y, &x, &temp, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        code = wmove(self->win, y, x);
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments");
-        return NULL;
-    }
-
-    if (code != ERR) {
-        if (!PyCurses_ConvertToChtype(self, temp, &ch))
-            return NULL;
-        return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline");
-    } else
-        return PyCursesCheckERR(code, "wmove");
-}
-
-static PyObject *
-PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn, x, y, use_xy = FALSE;
-    PyObject *temp;
-    chtype ch = 0;
-    attr_t attr = A_NORMAL;
-    long lattr;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "O;ch or int", &temp))
-            return NULL;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp))
-            return NULL;
-        use_xy = TRUE;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments");
-        return NULL;
-    }
-
-    if (!PyCurses_ConvertToChtype(self, temp, &ch))
-        return NULL;
-
-    if (use_xy == TRUE)
-        rtn = mvwinsch(self->win,y,x, ch | attr);
-    else {
-        rtn = winsch(self->win, ch | attr);
-    }
-    return PyCursesCheckERR(rtn, "insch");
-}
-
-static PyObject *
-PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y;
-    unsigned long rtn;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        rtn = winch(self->win);
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x))
-            return NULL;
-        rtn = mvwinch(self->win,y,x);
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments");
-        return NULL;
-    }
-    return PyLong_FromUnsignedLong(rtn);
-}
-
-static PyObject *
-PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y, n;
-    char rtn[1024]; /* This should be big enough.. I hope */
-    int rtn2;
-
-    switch (PyTuple_Size(args)) {
-    case 0:
-        rtn2 = winnstr(self->win,rtn, 1023);
-        break;
-    case 1:
-        if (!PyArg_ParseTuple(args,"i;n", &n))
-            return NULL;
-        rtn2 = winnstr(self->win, rtn, Py_MIN(n, 1023));
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x))
-            return NULL;
-        rtn2 = mvwinnstr(self->win,y,x,rtn,1023);
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n))
-            return NULL;
-        rtn2 = mvwinnstr(self->win, y, x, rtn, Py_MIN(n,1023));
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments");
-        return NULL;
-    }
-    if (rtn2 == ERR)
-        rtn[0] = 0;
-    return PyBytes_FromString(rtn);
-}
-
-static PyObject *
-PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn;
-    int x, y;
-    int strtype;
-    PyObject *strobj, *bytesobj = NULL;
-#ifdef HAVE_NCURSESW
-    wchar_t *wstr = NULL;
-#endif
-    attr_t attr = A_NORMAL , attr_old = A_NORMAL;
-    long lattr;
-    int use_xy = FALSE, use_attr = FALSE;
-    const char *funcname;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"O;str", &strobj))
-            return NULL;
-        break;
-    case 2:
-        if (!PyArg_ParseTuple(args,"Ol;str,attr", &strobj, &lattr))
-            return NULL;
-        attr = lattr;
-        use_attr = TRUE;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"iiO;y,x,str", &y, &x, &strobj))
-            return NULL;
-        use_xy = TRUE;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args,"iiOl;y,x,str,attr", &y, &x, &strobj, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = use_attr = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments");
-        return NULL;
-    }
-
-#ifdef HAVE_NCURSESW
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, &wstr);
-#else
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, NULL);
-#endif
-    if (strtype == 0)
-        return NULL;
-
-    if (use_attr == TRUE) {
-        attr_old = getattrs(self->win);
-        (void)wattrset(self->win,attr);
-    }
-#ifdef HAVE_NCURSESW
-    if (strtype == 2) {
-        funcname = "inswstr";
-        if (use_xy == TRUE)
-            rtn = mvwins_wstr(self->win,y,x,wstr);
-        else
-            rtn = wins_wstr(self->win,wstr);
-        PyMem_Free(wstr);
-    }
-    else
-#endif
-    {
-        char *str = PyBytes_AS_STRING(bytesobj);
-        funcname = "insstr";
-        if (use_xy == TRUE)
-            rtn = mvwinsstr(self->win,y,x,str);
-        else
-            rtn = winsstr(self->win,str);
-        Py_DECREF(bytesobj);
-    }
-    if (use_attr == TRUE)
-        (void)wattrset(self->win,attr_old);
-    return PyCursesCheckERR(rtn, funcname);
-}
-
-static PyObject *
-PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args)
-{
-    int rtn, x, y, n;
-    int strtype;
-    PyObject *strobj, *bytesobj = NULL;
-#ifdef HAVE_NCURSESW
-    wchar_t *wstr = NULL;
-#endif
-    attr_t attr = A_NORMAL , attr_old = A_NORMAL;
-    long lattr;
-    int use_xy = FALSE, use_attr = FALSE;
-    const char *funcname;
-
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args,"Oi;str,n", &strobj, &n))
-            return NULL;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args,"Oil;str,n,attr", &strobj, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        use_attr = TRUE;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args,"iiOi;y,x,str,n", &y, &x, &strobj, &n))
-            return NULL;
-        use_xy = TRUE;
-        break;
-    case 5:
-        if (!PyArg_ParseTuple(args,"iiOil;y,x,str,n,attr", &y, &x, &strobj, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        use_xy = use_attr = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments");
-        return NULL;
-    }
-
-#ifdef HAVE_NCURSESW
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, &wstr);
-#else
-    strtype = PyCurses_ConvertToString(self, strobj, &bytesobj, NULL);
-#endif
-    if (strtype == 0)
-        return NULL;
-
-    if (use_attr == TRUE) {
-        attr_old = getattrs(self->win);
-        (void)wattrset(self->win,attr);
-    }
-#ifdef HAVE_NCURSESW
-    if (strtype == 2) {
-        funcname = "insn_wstr";
-        if (use_xy == TRUE)
-            rtn = mvwins_nwstr(self->win,y,x,wstr,n);
-        else
-            rtn = wins_nwstr(self->win,wstr,n);
-        PyMem_Free(wstr);
-    }
-    else
-#endif
-    {
-        char *str = PyBytes_AS_STRING(bytesobj);
-        funcname = "insnstr";
-        if (use_xy == TRUE)
-            rtn = mvwinsnstr(self->win,y,x,str,n);
-        else
-            rtn = winsnstr(self->win,str,n);
-        Py_DECREF(bytesobj);
-    }
-    if (use_attr == TRUE)
-        (void)wattrset(self->win,attr_old);
-    return PyCursesCheckERR(rtn, funcname);
-}
-
-static PyObject *
-PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args)
-{
-    int line, erg;
-    if (!PyArg_ParseTuple(args,"i;line", &line))
-        return NULL;
-    erg = is_linetouched(self->win, line);
-    if (erg == ERR) {
-        PyErr_SetString(PyExc_TypeError,
-                        "is_linetouched: line number outside of boundaries");
-        return NULL;
-    } else
-        if (erg == FALSE) {
-            Py_INCREF(Py_False);
-            return Py_False;
-        } else {
-            Py_INCREF(Py_True);
-            return Py_True;
-        }
-}
-
-static PyObject *
-PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args)
-{
-    int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol;
-    int rtn;
-
-#ifndef WINDOW_HAS_FLAGS
-    if (0)
-#else
-        if (self->win->_flags & _ISPAD)
-#endif
-        {
-            switch(PyTuple_Size(args)) {
-            case 6:
-                if (!PyArg_ParseTuple(args,
-                                      "iiiiii;" \
-                                      "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol",
-                                      &pminrow, &pmincol, &sminrow,
-                                      &smincol, &smaxrow, &smaxcol))
-                    return NULL;
-                Py_BEGIN_ALLOW_THREADS
-                rtn = pnoutrefresh(self->win,
-                                   pminrow, pmincol, sminrow,
-                                   smincol, smaxrow, smaxcol);
-                Py_END_ALLOW_THREADS
-                return PyCursesCheckERR(rtn, "pnoutrefresh");
-            default:
-                PyErr_SetString(PyCursesError,
-                                "noutrefresh() called for a pad "
-                                "requires 6 arguments");
-                return NULL;
-            }
-        } else {
-            if (!PyArg_ParseTuple(args, ":noutrefresh"))
-                return NULL;
-
-            Py_BEGIN_ALLOW_THREADS
-            rtn = wnoutrefresh(self->win);
-            Py_END_ALLOW_THREADS
-            return PyCursesCheckERR(rtn, "wnoutrefresh");
-        }
-}
-
-static PyObject *
-PyCursesWindow_Overlay(PyCursesWindowObject *self, PyObject *args)
-{
-    PyCursesWindowObject *temp;
-    int use_copywin = FALSE;
-    int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol;
-    int rtn;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "O!;window object",
-                              &PyCursesWindow_Type, &temp))
-            return NULL;
-        break;
-    case 7:
-        if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int",
-                              &PyCursesWindow_Type, &temp, &sminrow, &smincol,
-                              &dminrow, &dmincol, &dmaxrow, &dmaxcol))
-            return NULL;
-        use_copywin = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError,
-                        "overlay requires one or seven arguments");
-        return NULL;
-    }
-
-    if (use_copywin == TRUE) {
-        rtn = copywin(self->win, temp->win, sminrow, smincol,
-                      dminrow, dmincol, dmaxrow, dmaxcol, TRUE);
-        return PyCursesCheckERR(rtn, "copywin");
-    }
-    else {
-        rtn = overlay(self->win, temp->win);
-        return PyCursesCheckERR(rtn, "overlay");
-    }
-}
-
-static PyObject *
-PyCursesWindow_Overwrite(PyCursesWindowObject *self, PyObject *args)
-{
-    PyCursesWindowObject *temp;
-    int use_copywin = FALSE;
-    int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol;
-    int rtn;
-
-    switch (PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "O!;window object",
-                              &PyCursesWindow_Type, &temp))
-            return NULL;
-        break;
-    case 7:
-        if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int",
-                              &PyCursesWindow_Type, &temp, &sminrow, &smincol,
-                              &dminrow, &dmincol, &dmaxrow, &dmaxcol))
-            return NULL;
-        use_copywin = TRUE;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError,
-                        "overwrite requires one or seven arguments");
-        return NULL;
-    }
-
-    if (use_copywin == TRUE) {
-        rtn = copywin(self->win, temp->win, sminrow, smincol,
-                      dminrow, dmincol, dmaxrow, dmaxcol, FALSE);
-        return PyCursesCheckERR(rtn, "copywin");
-    }
-    else {
-        rtn = overwrite(self->win, temp->win);
-        return PyCursesCheckERR(rtn, "overwrite");
-    }
-}
-
-static PyObject *
-PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *stream)
-{
-    /* We have to simulate this by writing to a temporary FILE*,
-       then reading back, then writing to the argument stream. */
-    char fn[100];
-    int fd = -1;
-    FILE *fp = NULL;
-    PyObject *res = NULL;
-
-    strcpy(fn, "/tmp/py.curses.putwin.XXXXXX");
-    fd = mkstemp(fn);
-    if (fd < 0)
-        return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn);
-    if (_Py_set_inheritable(fd, 0, NULL) < 0)
-        goto exit;
-    fp = fdopen(fd, "wb+");
-    if (fp == NULL) {
-        PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn);
-        goto exit;
-    }
-    res = PyCursesCheckERR(putwin(self->win, fp), "putwin");
-    if (res == NULL)
-        goto exit;
-    fseek(fp, 0, 0);
-    while (1) {
-        char buf[BUFSIZ];
-        Py_ssize_t n = fread(buf, 1, BUFSIZ, fp);
-        _Py_IDENTIFIER(write);
-
-        if (n <= 0)
-            break;
-        Py_DECREF(res);
-        res = _PyObject_CallMethodId(stream, &PyId_write, "y#", buf, n);
-        if (res == NULL)
-            break;
-    }
-
-exit:
-    if (fp != NULL)
-        fclose(fp);
-    else if (fd != -1)
-        close(fd);
-    remove(fn);
-    return res;
-}
-
-static PyObject *
-PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args)
-{
-    int beg, num;
-    if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num))
-        return NULL;
-    return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln");
-}
-
-static PyObject *
-PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args)
-{
-    int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol;
-    int rtn;
-
-#ifndef WINDOW_HAS_FLAGS
-    if (0)
-#else
-        if (self->win->_flags & _ISPAD)
-#endif
-        {
-            switch(PyTuple_Size(args)) {
-            case 6:
-                if (!PyArg_ParseTuple(args,
-                                      "iiiiii;" \
-                                      "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol",
-                                      &pminrow, &pmincol, &sminrow,
-                                      &smincol, &smaxrow, &smaxcol))
-                    return NULL;
-
-                Py_BEGIN_ALLOW_THREADS
-                rtn = prefresh(self->win,
-                               pminrow, pmincol, sminrow,
-                               smincol, smaxrow, smaxcol);
-                Py_END_ALLOW_THREADS
-                return PyCursesCheckERR(rtn, "prefresh");
-            default:
-                PyErr_SetString(PyCursesError,
-                                "refresh() for a pad requires 6 arguments");
-                return NULL;
-            }
-        } else {
-            if (!PyArg_ParseTuple(args, ":refresh"))
-                return NULL;
-            Py_BEGIN_ALLOW_THREADS
-            rtn = wrefresh(self->win);
-            Py_END_ALLOW_THREADS
-            return PyCursesCheckERR(rtn, "prefresh");
-        }
-}
-
-static PyObject *
-PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args)
-{
-    int x, y;
-    if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x))
-        return NULL;
-    return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg");
-}
-
-static PyObject *
-PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args)
-{
-    WINDOW *win;
-    int nlines, ncols, begin_y, begin_x;
-
-    nlines = 0;
-    ncols  = 0;
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x))
-            return NULL;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x",
-                              &nlines,&ncols,&begin_y,&begin_x))
-            return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments");
-        return NULL;
-    }
-
-    /* printf("Subwin: %i %i %i %i   \n", nlines, ncols, begin_y, begin_x); */
-#ifdef WINDOW_HAS_FLAGS
-    if (self->win->_flags & _ISPAD)
-        win = subpad(self->win, nlines, ncols, begin_y, begin_x);
-    else
-#endif
-        win = subwin(self->win, nlines, ncols, begin_y, begin_x);
-
-    if (win == NULL) {
-        PyErr_SetString(PyCursesError, catchall_NULL);
-        return NULL;
-    }
-
-    return (PyObject *)PyCursesWindow_New(win, self->encoding);
-}
-
-static PyObject *
-PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args)
-{
-    int nlines;
-    switch(PyTuple_Size(args)) {
-    case 0:
-        return PyCursesCheckERR(scroll(self->win), "scroll");
-    case 1:
-        if (!PyArg_ParseTuple(args, "i;nlines", &nlines))
-            return NULL;
-        return PyCursesCheckERR(wscrl(self->win, nlines), "scroll");
-    default:
-        PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments");
-        return NULL;
-    }
-}
-
-static PyObject *
-PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args)
-{
-    int st, cnt, val;
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt))
-            return NULL;
-        return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline");
-    case 3:
-        if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val))
-            return NULL;
-        return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline");
-    default:
-        PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments");
-        return NULL;
-    }
-}
-
-static PyObject *
-PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype ch;
-    int n, x, y, code = OK;
-    attr_t attr = A_NORMAL;
-    long lattr;
-
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n))
-            return NULL;
-        break;
-    case 3:
-        if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n))
-            return NULL;
-        code = wmove(self->win, y, x);
-        break;
-    case 5:
-        if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr",
-                              &y, &x, &temp, &n, &lattr))
-            return NULL;
-        attr = lattr;
-        code = wmove(self->win, y, x);
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments");
-        return NULL;
-    }
-
-    if (code != ERR) {
-        if (!PyCurses_ConvertToChtype(self, temp, &ch))
-            return NULL;
-        return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline");
-    } else
-        return PyCursesCheckERR(code, "wmove");
-}
-
-static PyObject *
-PyCursesWindow_get_encoding(PyCursesWindowObject *self, void *closure)
-{
-    return PyUnicode_FromString(self->encoding);
-}
-
-static int
-PyCursesWindow_set_encoding(PyCursesWindowObject *self, PyObject *value)
-{
-    PyObject *ascii;
-    char *encoding;
-
-    /* It is illegal to del win.encoding */
-    if (value == NULL) {
-        PyErr_SetString(PyExc_TypeError,
-                        "encoding may not be deleted");
-        return -1;
-    }
-
-    if (!PyUnicode_Check(value)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "setting encoding to a non-string");
-        return -1;
-    }
-    ascii = PyUnicode_AsASCIIString(value);
-    if (ascii == NULL)
-        return -1;
-    encoding = _PyMem_Strdup(PyBytes_AS_STRING(ascii));
-    Py_DECREF(ascii);
-    if (encoding == NULL) {
-        PyErr_NoMemory();
-        return -1;
-    }
-    PyMem_Free(self->encoding);
-    self->encoding = encoding;
-    return 0;
-}
-
-
-static PyMethodDef PyCursesWindow_Methods[] = {
-    CURSES_WINDOW_ADDCH_METHODDEF
-    {"addnstr",         (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS},
-    {"addstr",          (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS},
-    {"attroff",         (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS},
-    {"attron",          (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS},
-    {"attrset",         (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS},
-    {"bkgd",            (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS},
-    {"chgat",           (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS},
-    {"bkgdset",         (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS},
-    {"border",          (PyCFunction)PyCursesWindow_Border, METH_VARARGS},
-    {"box",             (PyCFunction)PyCursesWindow_Box, METH_VARARGS},
-    {"clear",           (PyCFunction)PyCursesWindow_wclear, METH_NOARGS},
-    {"clearok",         (PyCFunction)PyCursesWindow_clearok, METH_VARARGS},
-    {"clrtobot",        (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS},
-    {"clrtoeol",        (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS},
-    {"cursyncup",       (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS},
-    {"delch",           (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS},
-    {"deleteln",        (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS},
-    {"derwin",          (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS},
-    {"echochar",        (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS},
-#ifdef NCURSES_MOUSE_VERSION
-    {"enclose",         (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS},
-#endif
-    {"erase",           (PyCFunction)PyCursesWindow_werase, METH_NOARGS},
-    {"getbegyx",        (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS},
-    {"getbkgd",         (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS},
-    {"getch",           (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS},
-    {"getkey",          (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS},
-#ifdef HAVE_NCURSESW
-    {"get_wch",         (PyCFunction)PyCursesWindow_Get_WCh, METH_VARARGS},
-#endif
-    {"getmaxyx",        (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS},
-    {"getparyx",        (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS},
-    {"getstr",          (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS},
-    {"getyx",           (PyCFunction)PyCursesWindow_getyx, METH_NOARGS},
-    {"hline",           (PyCFunction)PyCursesWindow_Hline, METH_VARARGS},
-    {"idcok",           (PyCFunction)PyCursesWindow_idcok, METH_VARARGS},
-    {"idlok",           (PyCFunction)PyCursesWindow_idlok, METH_VARARGS},
-    {"immedok",         (PyCFunction)PyCursesWindow_immedok, METH_VARARGS},
-    {"inch",            (PyCFunction)PyCursesWindow_InCh, METH_VARARGS},
-    {"insch",           (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS},
-    {"insdelln",        (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS},
-    {"insertln",        (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS},
-    {"insnstr",         (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS},
-    {"insstr",          (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS},
-    {"instr",           (PyCFunction)PyCursesWindow_InStr, METH_VARARGS},
-    {"is_linetouched",  (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS},
-    {"is_wintouched",   (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS},
-    {"keypad",          (PyCFunction)PyCursesWindow_keypad, METH_VARARGS},
-    {"leaveok",         (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS},
-    {"move",            (PyCFunction)PyCursesWindow_wmove, METH_VARARGS},
-    {"mvderwin",        (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS},
-    {"mvwin",           (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS},
-    {"nodelay",         (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS},
-    {"notimeout",       (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS},
-    {"noutrefresh",     (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS},
-    {"overlay",         (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS},
-    {"overwrite",       (PyCFunction)PyCursesWindow_Overwrite,
-     METH_VARARGS},
-    {"putwin",          (PyCFunction)PyCursesWindow_PutWin, METH_O},
-    {"redrawln",        (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS},
-    {"redrawwin",       (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS},
-    {"refresh",         (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS},
-#ifndef STRICT_SYSV_CURSES
-    {"resize",          (PyCFunction)PyCursesWindow_wresize, METH_VARARGS},
-#endif
-    {"scroll",          (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS},
-    {"scrollok",        (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS},
-    {"setscrreg",       (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS},
-    {"standend",        (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS},
-    {"standout",        (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS},
-    {"subpad",          (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS},
-    {"subwin",          (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS},
-    {"syncdown",        (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS},
-    {"syncok",          (PyCFunction)PyCursesWindow_syncok, METH_VARARGS},
-    {"syncup",          (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS},
-    {"timeout",         (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS},
-    {"touchline",       (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS},
-    {"touchwin",        (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS},
-    {"untouchwin",      (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS},
-    {"vline",           (PyCFunction)PyCursesWindow_Vline, METH_VARARGS},
-    {NULL,                  NULL}   /* sentinel */
-};
-
-static PyGetSetDef PyCursesWindow_getsets[] = {
-    {"encoding",
-     (getter)PyCursesWindow_get_encoding,
-     (setter)PyCursesWindow_set_encoding,
-     "the typecode character used to create the array"},
-    {NULL, NULL, NULL, NULL }  /* sentinel */
-};
-
-/* -------------------------------------------------------*/
-
-PyTypeObject PyCursesWindow_Type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_curses.curses window",            /*tp_name*/
-    sizeof(PyCursesWindowObject),       /*tp_basicsize*/
-    0,                          /*tp_itemsize*/
-    /* methods */
-    (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/
-    0,                          /*tp_print*/
-    (getattrfunc)0,             /*tp_getattr*/
-    (setattrfunc)0,             /*tp_setattr*/
-    0,                          /*tp_reserved*/
-    0,                          /*tp_repr*/
-    0,                          /*tp_as_number*/
-    0,                          /*tp_as_sequence*/
-    0,                          /*tp_as_mapping*/
-    0,                          /*tp_hash*/
-    0,                          /*tp_call*/
-    0,                          /*tp_str*/
-    0,                          /*tp_getattro*/
-    0,                          /*tp_setattro*/
-    0,                          /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT,         /*tp_flags*/
-    0,                          /*tp_doc*/
-    0,                          /*tp_traverse*/
-    0,                          /*tp_clear*/
-    0,                          /*tp_richcompare*/
-    0,                          /*tp_weaklistoffset*/
-    0,                          /*tp_iter*/
-    0,                          /*tp_iternext*/
-    PyCursesWindow_Methods,     /*tp_methods*/
-    0,                          /* tp_members */
-    PyCursesWindow_getsets,     /* tp_getset */
-};
-
-/*********************************************************************
- Global Functions
-**********************************************************************/
-
-NoArgNoReturnFunction(beep)
-NoArgNoReturnFunction(def_prog_mode)
-NoArgNoReturnFunction(def_shell_mode)
-NoArgNoReturnFunction(doupdate)
-NoArgNoReturnFunction(endwin)
-NoArgNoReturnFunction(flash)
-NoArgNoReturnFunction(nocbreak)
-NoArgNoReturnFunction(noecho)
-NoArgNoReturnFunction(nonl)
-NoArgNoReturnFunction(noraw)
-NoArgNoReturnFunction(reset_prog_mode)
-NoArgNoReturnFunction(reset_shell_mode)
-NoArgNoReturnFunction(resetty)
-NoArgNoReturnFunction(savetty)
-
-NoArgOrFlagNoReturnFunction(cbreak)
-NoArgOrFlagNoReturnFunction(echo)
-NoArgOrFlagNoReturnFunction(nl)
-NoArgOrFlagNoReturnFunction(raw)
-
-NoArgReturnIntFunction(baudrate)
-NoArgReturnIntFunction(termattrs)
-
-NoArgReturnStringFunction(termname)
-NoArgReturnStringFunction(longname)
-
-NoArgTrueFalseFunction(can_change_color)
-NoArgTrueFalseFunction(has_colors)
-NoArgTrueFalseFunction(has_ic)
-NoArgTrueFalseFunction(has_il)
-NoArgTrueFalseFunction(isendwin)
-NoArgNoReturnVoidFunction(flushinp)
-NoArgNoReturnVoidFunction(noqiflush)
-
-static PyObject *
-PyCurses_filter(PyObject *self)
-{
-    /* not checking for PyCursesInitialised here since filter() must
-       be called before initscr() */
-    filter();
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *
-PyCurses_Color_Content(PyObject *self, PyObject *args)
-{
-    short color,r,g,b;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL;
-
-    if (color_content(color, &r, &g, &b) != ERR)
-        return Py_BuildValue("(iii)", r, g, b);
-    else {
-        PyErr_SetString(PyCursesError,
-                        "Argument 1 was out of range. Check value of COLORS.");
-        return NULL;
-    }
-}
-
-static PyObject *
-PyCurses_color_pair(PyObject *self, PyObject *args)
-{
-    int n;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL;
-    return PyLong_FromLong((long) (n << 8));
-}
-
-static PyObject *
-PyCurses_Curs_Set(PyObject *self, PyObject *args)
-{
-    int vis,erg;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL;
-
-    erg = curs_set(vis);
-    if (erg == ERR) return PyCursesCheckERR(erg, "curs_set");
-
-    return PyLong_FromLong((long) erg);
-}
-
-static PyObject *
-PyCurses_Delay_Output(PyObject *self, PyObject *args)
-{
-    int ms;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL;
-
-    return PyCursesCheckERR(delay_output(ms), "delay_output");
-}
-
-static PyObject *
-PyCurses_EraseChar(PyObject *self)
-{
-    char ch;
-
-    PyCursesInitialised;
-
-    ch = erasechar();
-
-    return PyBytes_FromStringAndSize(&ch, 1);
-}
-
-static PyObject *
-PyCurses_getsyx(PyObject *self)
-{
-    int x = 0;
-    int y = 0;
-
-    PyCursesInitialised;
-
-    getsyx(y, x);
-
-    return Py_BuildValue("(ii)", y, x);
-}
-
-#ifdef NCURSES_MOUSE_VERSION
-static PyObject *
-PyCurses_GetMouse(PyObject *self)
-{
-    int rtn;
-    MEVENT event;
-
-    PyCursesInitialised;
-
-    rtn = getmouse( &event );
-    if (rtn == ERR) {
-        PyErr_SetString(PyCursesError, "getmouse() returned ERR");
-        return NULL;
-    }
-    return Py_BuildValue("(hiiil)",
-                         (short)event.id,
-                         event.x, event.y, event.z,
-                         (long) event.bstate);
-}
-
-static PyObject *
-PyCurses_UngetMouse(PyObject *self, PyObject *args)
-{
-    MEVENT event;
-
-    PyCursesInitialised;
-    if (!PyArg_ParseTuple(args, "hiiil",
-                          &event.id,
-                          &event.x, &event.y, &event.z,
-                          (int *) &event.bstate))
-        return NULL;
-
-    return PyCursesCheckERR(ungetmouse(&event), "ungetmouse");
-}
-#endif
-
-static PyObject *
-PyCurses_GetWin(PyCursesWindowObject *self, PyObject *stream)
-{
-    char fn[100];
-    int fd = -1;
-    FILE *fp = NULL;
-    PyObject *data;
-    size_t datalen;
-    WINDOW *win;
-    _Py_IDENTIFIER(read);
-    PyObject *res = NULL;
-
-    PyCursesInitialised;
-
-    strcpy(fn, "/tmp/py.curses.getwin.XXXXXX");
-    fd = mkstemp(fn);
-    if (fd < 0)
-        return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn);
-    if (_Py_set_inheritable(fd, 0, NULL) < 0)
-        goto error;
-    fp = fdopen(fd, "wb+");
-    if (fp == NULL) {
-        PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn);
-        goto error;
-    }
-
-    data = _PyObject_CallMethodId(stream, &PyId_read, "");
-    if (data == NULL)
-        goto error;
-    if (!PyBytes_Check(data)) {
-        PyErr_Format(PyExc_TypeError,
-                     "f.read() returned %.100s instead of bytes",
-                     data->ob_type->tp_name);
-        Py_DECREF(data);
-        goto error;
-    }
-    datalen = PyBytes_GET_SIZE(data);
-    if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) {
-        Py_DECREF(data);
-        PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn);
-        goto error;
-    }
-    Py_DECREF(data);
-
-    fseek(fp, 0, 0);
-    win = getwin(fp);
-    if (win == NULL) {
-        PyErr_SetString(PyCursesError, catchall_NULL);
-        goto error;
-    }
-    res = PyCursesWindow_New(win, NULL);
-
-error:
-    if (fp != NULL)
-        fclose(fp);
-    else if (fd != -1)
-        close(fd);
-    remove(fn);
-    return res;
-}
-
-static PyObject *
-PyCurses_HalfDelay(PyObject *self, PyObject *args)
-{
-    unsigned char tenths;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL;
-
-    return PyCursesCheckERR(halfdelay(tenths), "halfdelay");
-}
-
-#ifndef STRICT_SYSV_CURSES
-/* No has_key! */
-static PyObject * PyCurses_has_key(PyObject *self, PyObject *args)
-{
-    int ch;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"i",&ch)) return NULL;
-
-    if (has_key(ch) == FALSE) {
-        Py_INCREF(Py_False);
-        return Py_False;
-    }
-    Py_INCREF(Py_True);
-    return Py_True;
-}
-#endif /* STRICT_SYSV_CURSES */
-
-static PyObject *
-PyCurses_Init_Color(PyObject *self, PyObject *args)
-{
-    short color, r, g, b;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    switch(PyTuple_Size(args)) {
-    case 4:
-        if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments");
-        return NULL;
-    }
-
-    return PyCursesCheckERR(init_color(color, r, g, b), "init_color");
-}
-
-static PyObject *
-PyCurses_Init_Pair(PyObject *self, PyObject *args)
-{
-    short pair, f, b;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    if (PyTuple_Size(args) != 3) {
-        PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments");
-        return NULL;
-    }
-
-    if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL;
-
-    return PyCursesCheckERR(init_pair(pair, f, b), "init_pair");
-}
-
-static PyObject *ModDict;
-
-static PyObject *
-PyCurses_InitScr(PyObject *self)
-{
-    WINDOW *win;
-    PyCursesWindowObject *winobj;
-
-    if (initialised == TRUE) {
-        wrefresh(stdscr);
-        return (PyObject *)PyCursesWindow_New(stdscr, NULL);
-    }
-
-    win = initscr();
-
-    if (win == NULL) {
-        PyErr_SetString(PyCursesError, catchall_NULL);
-        return NULL;
-    }
-
-    initialised = initialised_setupterm = TRUE;
-
-/* This was moved from initcurses() because it core dumped on SGI,
-   where they're not defined until you've called initscr() */
-#define SetDictInt(string,ch)                                           \
-    do {                                                                \
-        PyObject *o = PyLong_FromLong((long) (ch));                     \
-        if (o && PyDict_SetItemString(ModDict, string, o) == 0)     {   \
-            Py_DECREF(o);                                               \
-        }                                                               \
-    } while (0)
-
-    /* Here are some graphic symbols you can use */
-    SetDictInt("ACS_ULCORNER",      (ACS_ULCORNER));
-    SetDictInt("ACS_LLCORNER",      (ACS_LLCORNER));
-    SetDictInt("ACS_URCORNER",      (ACS_URCORNER));
-    SetDictInt("ACS_LRCORNER",      (ACS_LRCORNER));
-    SetDictInt("ACS_LTEE",          (ACS_LTEE));
-    SetDictInt("ACS_RTEE",          (ACS_RTEE));
-    SetDictInt("ACS_BTEE",          (ACS_BTEE));
-    SetDictInt("ACS_TTEE",          (ACS_TTEE));
-    SetDictInt("ACS_HLINE",         (ACS_HLINE));
-    SetDictInt("ACS_VLINE",         (ACS_VLINE));
-    SetDictInt("ACS_PLUS",          (ACS_PLUS));
-#if !defined(__hpux) || defined(HAVE_NCURSES_H)
-    /* On HP/UX 11, these are of type cchar_t, which is not an
-       integral type. If this is a problem on more platforms, a
-       configure test should be added to determine whether ACS_S1
-       is of integral type. */
-    SetDictInt("ACS_S1",            (ACS_S1));
-    SetDictInt("ACS_S9",            (ACS_S9));
-    SetDictInt("ACS_DIAMOND",       (ACS_DIAMOND));
-    SetDictInt("ACS_CKBOARD",       (ACS_CKBOARD));
-    SetDictInt("ACS_DEGREE",        (ACS_DEGREE));
-    SetDictInt("ACS_PLMINUS",       (ACS_PLMINUS));
-    SetDictInt("ACS_BULLET",        (ACS_BULLET));
-    SetDictInt("ACS_LARROW",        (ACS_LARROW));
-    SetDictInt("ACS_RARROW",        (ACS_RARROW));
-    SetDictInt("ACS_DARROW",        (ACS_DARROW));
-    SetDictInt("ACS_UARROW",        (ACS_UARROW));
-    SetDictInt("ACS_BOARD",         (ACS_BOARD));
-    SetDictInt("ACS_LANTERN",       (ACS_LANTERN));
-    SetDictInt("ACS_BLOCK",         (ACS_BLOCK));
-#endif
-    SetDictInt("ACS_BSSB",          (ACS_ULCORNER));
-    SetDictInt("ACS_SSBB",          (ACS_LLCORNER));
-    SetDictInt("ACS_BBSS",          (ACS_URCORNER));
-    SetDictInt("ACS_SBBS",          (ACS_LRCORNER));
-    SetDictInt("ACS_SBSS",          (ACS_RTEE));
-    SetDictInt("ACS_SSSB",          (ACS_LTEE));
-    SetDictInt("ACS_SSBS",          (ACS_BTEE));
-    SetDictInt("ACS_BSSS",          (ACS_TTEE));
-    SetDictInt("ACS_BSBS",          (ACS_HLINE));
-    SetDictInt("ACS_SBSB",          (ACS_VLINE));
-    SetDictInt("ACS_SSSS",          (ACS_PLUS));
-
-    /* The following are never available with strict SYSV curses */
-#ifdef ACS_S3
-    SetDictInt("ACS_S3",            (ACS_S3));
-#endif
-#ifdef ACS_S7
-    SetDictInt("ACS_S7",            (ACS_S7));
-#endif
-#ifdef ACS_LEQUAL
-    SetDictInt("ACS_LEQUAL",        (ACS_LEQUAL));
-#endif
-#ifdef ACS_GEQUAL
-    SetDictInt("ACS_GEQUAL",        (ACS_GEQUAL));
-#endif
-#ifdef ACS_PI
-    SetDictInt("ACS_PI",            (ACS_PI));
-#endif
-#ifdef ACS_NEQUAL
-    SetDictInt("ACS_NEQUAL",        (ACS_NEQUAL));
-#endif
-#ifdef ACS_STERLING
-    SetDictInt("ACS_STERLING",      (ACS_STERLING));
-#endif
-
-    SetDictInt("LINES", LINES);
-    SetDictInt("COLS", COLS);
-
-    winobj = (PyCursesWindowObject *)PyCursesWindow_New(win, NULL);
-    screen_encoding = winobj->encoding;
-    return (PyObject *)winobj;
-}
-
-static PyObject *
-PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds)
-{
-    int fd = -1;
-    int err;
-    char* termstr = NULL;
-
-    static char *kwlist[] = {"term", "fd", NULL};
-
-    if (!PyArg_ParseTupleAndKeywords(
-            args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) {
-        return NULL;
-    }
-
-    if (fd == -1) {
-        PyObject* sys_stdout;
-
-        sys_stdout = PySys_GetObject("stdout");
-
-        if (sys_stdout == NULL || sys_stdout == Py_None) {
-            PyErr_SetString(
-                PyCursesError,
-                "lost sys.stdout");
-            return NULL;
-        }
-
-        fd = PyObject_AsFileDescriptor(sys_stdout);
-
-        if (fd == -1) {
-            return NULL;
-        }
-    }
-
-    if (!initialised_setupterm && setupterm(termstr,fd,&err) == ERR) {
-        char* s = "setupterm: unknown error";
-
-        if (err == 0) {
-            s = "setupterm: could not find terminal";
-        } else if (err == -1) {
-            s = "setupterm: could not find terminfo database";
-        }
-
-        PyErr_SetString(PyCursesError,s);
-        return NULL;
-    }
-
-    initialised_setupterm = TRUE;
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *
-PyCurses_IntrFlush(PyObject *self, PyObject *args)
-{
-    int ch;
-
-    PyCursesInitialised;
-
-    switch(PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument");
-        return NULL;
-    }
-
-    return PyCursesCheckERR(intrflush(NULL,ch), "intrflush");
-}
-
-#ifdef HAVE_CURSES_IS_TERM_RESIZED
-static PyObject *
-PyCurses_Is_Term_Resized(PyObject *self, PyObject *args)
-{
-    int lines;
-    int columns;
-    int result;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns))
-        return NULL;
-    result = is_term_resized(lines, columns);
-    if (result == TRUE) {
-        Py_INCREF(Py_True);
-        return Py_True;
-    } else {
-        Py_INCREF(Py_False);
-        return Py_False;
-    }
-}
-#endif /* HAVE_CURSES_IS_TERM_RESIZED */
-
-#if !defined(__NetBSD__)
-static PyObject *
-PyCurses_KeyName(PyObject *self, PyObject *args)
-{
-    const char *knp;
-    int ch;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"i",&ch)) return NULL;
-
-    if (ch < 0) {
-        PyErr_SetString(PyExc_ValueError, "invalid key number");
-        return NULL;
-    }
-    knp = keyname(ch);
-
-    return PyBytes_FromString((knp == NULL) ? "" : knp);
-}
-#endif
-
-static PyObject *
-PyCurses_KillChar(PyObject *self)
-{
-    char ch;
-
-    ch = killchar();
-
-    return PyBytes_FromStringAndSize(&ch, 1);
-}
-
-static PyObject *
-PyCurses_Meta(PyObject *self, PyObject *args)
-{
-    int ch;
-
-    PyCursesInitialised;
-
-    switch(PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "meta requires 1 argument");
-        return NULL;
-    }
-
-    return PyCursesCheckERR(meta(stdscr, ch), "meta");
-}
-
-#ifdef NCURSES_MOUSE_VERSION
-static PyObject *
-PyCurses_MouseInterval(PyObject *self, PyObject *args)
-{
-    int interval;
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"i;interval",&interval))
-        return NULL;
-    return PyCursesCheckERR(mouseinterval(interval), "mouseinterval");
-}
-
-static PyObject *
-PyCurses_MouseMask(PyObject *self, PyObject *args)
-{
-    int newmask;
-    mmask_t oldmask, availmask;
-
-    PyCursesInitialised;
-    if (!PyArg_ParseTuple(args,"i;mousemask",&newmask))
-        return NULL;
-    availmask = mousemask(newmask, &oldmask);
-    return Py_BuildValue("(ll)", (long)availmask, (long)oldmask);
-}
-#endif
-
-static PyObject *
-PyCurses_Napms(PyObject *self, PyObject *args)
-{
-    int ms;
-
-    PyCursesInitialised;
-    if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL;
-
-    return Py_BuildValue("i", napms(ms));
-}
-
-
-static PyObject *
-PyCurses_NewPad(PyObject *self, PyObject *args)
-{
-    WINDOW *win;
-    int nlines, ncols;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL;
-
-    win = newpad(nlines, ncols);
-
-    if (win == NULL) {
-        PyErr_SetString(PyCursesError, catchall_NULL);
-        return NULL;
-    }
-
-    return (PyObject *)PyCursesWindow_New(win, NULL);
-}
-
-static PyObject *
-PyCurses_NewWindow(PyObject *self, PyObject *args)
-{
-    WINDOW *win;
-    int nlines, ncols, begin_y=0, begin_x=0;
-
-    PyCursesInitialised;
-
-    switch (PyTuple_Size(args)) {
-    case 2:
-        if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols))
-            return NULL;
-        break;
-    case 4:
-        if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x",
-                              &nlines,&ncols,&begin_y,&begin_x))
-            return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments");
-        return NULL;
-    }
-
-    win = newwin(nlines,ncols,begin_y,begin_x);
-    if (win == NULL) {
-        PyErr_SetString(PyCursesError, catchall_NULL);
-        return NULL;
-    }
-
-    return (PyObject *)PyCursesWindow_New(win, NULL);
-}
-
-static PyObject *
-PyCurses_Pair_Content(PyObject *self, PyObject *args)
-{
-    short pair,f,b;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    switch(PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument");
-        return NULL;
-    }
-
-    if (pair_content(pair, &f, &b)==ERR) {
-        PyErr_SetString(PyCursesError,
-                        "Argument 1 was out of range. (1..COLOR_PAIRS-1)");
-        return NULL;
-    }
-
-    return Py_BuildValue("(ii)", f, b);
-}
-
-static PyObject *
-PyCurses_pair_number(PyObject *self, PyObject *args)
-{
-    int n;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    switch(PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError,
-                        "pair_number requires 1 argument");
-        return NULL;
-    }
-
-    return PyLong_FromLong((long) ((n & A_COLOR) >> 8));
-}
-
-static PyObject *
-PyCurses_Putp(PyObject *self, PyObject *args)
-{
-    char *str;
-
-    if (!PyArg_ParseTuple(args,"y;str", &str))
-        return NULL;
-    return PyCursesCheckERR(putp(str), "putp");
-}
-
-static PyObject *
-PyCurses_QiFlush(PyObject *self, PyObject *args)
-{
-    int flag = 0;
-
-    PyCursesInitialised;
-
-    switch(PyTuple_Size(args)) {
-    case 0:
-        qiflush();
-        Py_INCREF(Py_None);
-        return Py_None;
-    case 1:
-        if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL;
-        if (flag) qiflush();
-        else noqiflush();
-        Py_INCREF(Py_None);
-        return Py_None;
-    default:
-        PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments");
-        return NULL;
-    }
-}
-
-/* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES
- * and _curses.COLS */
-#if defined(HAVE_CURSES_RESIZETERM) || defined(HAVE_CURSES_RESIZE_TERM)
-static int
-update_lines_cols(void)
-{
-    PyObject *o;
-    PyObject *m = PyImport_ImportModuleNoBlock("curses");
-    _Py_IDENTIFIER(LINES);
-    _Py_IDENTIFIER(COLS);
-
-    if (!m)
-        return 0;
-
-    o = PyLong_FromLong(LINES);
-    if (!o) {
-        Py_DECREF(m);
-        return 0;
-    }
-    if (_PyObject_SetAttrId(m, &PyId_LINES, o)) {
-        Py_DECREF(m);
-        Py_DECREF(o);
-        return 0;
-    }
-    /* PyId_LINES.object will be initialized here. */
-    if (PyDict_SetItem(ModDict, PyId_LINES.object, o)) {
-        Py_DECREF(m);
-        Py_DECREF(o);
-        return 0;
-    }
-    Py_DECREF(o);
-    o = PyLong_FromLong(COLS);
-    if (!o) {
-        Py_DECREF(m);
-        return 0;
-    }
-    if (_PyObject_SetAttrId(m, &PyId_COLS, o)) {
-        Py_DECREF(m);
-        Py_DECREF(o);
-        return 0;
-    }
-    if (PyDict_SetItem(ModDict, PyId_COLS.object, o)) {
-        Py_DECREF(m);
-        Py_DECREF(o);
-        return 0;
-    }
-    Py_DECREF(o);
-    Py_DECREF(m);
-    return 1;
-}
-#endif
-
-#ifdef HAVE_CURSES_RESIZETERM
-static PyObject *
-PyCurses_ResizeTerm(PyObject *self, PyObject *args)
-{
-    int lines;
-    int columns;
-    PyObject *result;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns))
-        return NULL;
-
-    result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm");
-    if (!result)
-        return NULL;
-    if (!update_lines_cols())
-        return NULL;
-    return result;
-}
-
-#endif
-
-#ifdef HAVE_CURSES_RESIZE_TERM
-static PyObject *
-PyCurses_Resize_Term(PyObject *self, PyObject *args)
-{
-    int lines;
-    int columns;
-
-    PyObject *result;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns))
-        return NULL;
-
-    result = PyCursesCheckERR(resize_term(lines, columns), "resize_term");
-    if (!result)
-        return NULL;
-    if (!update_lines_cols())
-        return NULL;
-    return result;
-}
-#endif /* HAVE_CURSES_RESIZE_TERM */
-
-static PyObject *
-PyCurses_setsyx(PyObject *self, PyObject *args)
-{
-    int y,x;
-
-    PyCursesInitialised;
-
-    if (PyTuple_Size(args)!=2) {
-        PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments");
-        return NULL;
-    }
-
-    if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL;
-
-    setsyx(y,x);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *
-PyCurses_Start_Color(PyObject *self)
-{
-    int code;
-    PyObject *c, *cp;
-
-    PyCursesInitialised;
-
-    code = start_color();
-    if (code != ERR) {
-        initialisedcolors = TRUE;
-        c = PyLong_FromLong((long) COLORS);
-        if (c == NULL)
-            return NULL;
-        PyDict_SetItemString(ModDict, "COLORS", c);
-        Py_DECREF(c);
-        cp = PyLong_FromLong((long) COLOR_PAIRS);
-        if (cp == NULL)
-            return NULL;
-        PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp);
-        Py_DECREF(cp);
-        Py_INCREF(Py_None);
-        return Py_None;
-    } else {
-        PyErr_SetString(PyCursesError, "start_color() returned ERR");
-        return NULL;
-    }
-}
-
-static PyObject *
-PyCurses_tigetflag(PyObject *self, PyObject *args)
-{
-    char *capname;
-
-    PyCursesSetupTermCalled;
-
-    if (!PyArg_ParseTuple(args, "s", &capname))
-        return NULL;
-
-    return PyLong_FromLong( (long) tigetflag( capname ) );
-}
-
-static PyObject *
-PyCurses_tigetnum(PyObject *self, PyObject *args)
-{
-    char *capname;
-
-    PyCursesSetupTermCalled;
-
-    if (!PyArg_ParseTuple(args, "s", &capname))
-        return NULL;
-
-    return PyLong_FromLong( (long) tigetnum( capname ) );
-}
-
-static PyObject *
-PyCurses_tigetstr(PyObject *self, PyObject *args)
-{
-    char *capname;
-
-    PyCursesSetupTermCalled;
-
-    if (!PyArg_ParseTuple(args, "s", &capname))
-        return NULL;
-
-    capname = tigetstr( capname );
-    if (capname == 0 || capname == (char*) -1) {
-        Py_INCREF(Py_None);
-        return Py_None;
-    }
-    return PyBytes_FromString( capname );
-}
-
-static PyObject *
-PyCurses_tparm(PyObject *self, PyObject *args)
-{
-    char* fmt;
-    char* result = NULL;
-    int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;
-
-    PyCursesSetupTermCalled;
-
-    if (!PyArg_ParseTuple(args, "y|iiiiiiiii:tparm",
-                          &fmt, &i1, &i2, &i3, &i4,
-                          &i5, &i6, &i7, &i8, &i9)) {
-        return NULL;
-    }
-
-    result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9);
-    if (!result) {
-        PyErr_SetString(PyCursesError, "tparm() returned NULL");
-        return NULL;
-    }
-
-    return PyBytes_FromString(result);
-}
-
-static PyObject *
-PyCurses_TypeAhead(PyObject *self, PyObject *args)
-{
-    int fd;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL;
-
-    return PyCursesCheckERR(typeahead( fd ), "typeahead");
-}
-
-static PyObject *
-PyCurses_UnCtrl(PyObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype ch;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL;
-
-    if (!PyCurses_ConvertToChtype(NULL, temp, &ch))
-        return NULL;
-
-    return PyBytes_FromString(unctrl(ch));
-}
-
-static PyObject *
-PyCurses_UngetCh(PyObject *self, PyObject *args)
-{
-    PyObject *temp;
-    chtype ch;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"O;ch or int",&temp))
-        return NULL;
-
-    if (!PyCurses_ConvertToChtype(NULL, temp, &ch))
-        return NULL;
-
-    return PyCursesCheckERR(ungetch(ch), "ungetch");
-}
-
-#ifdef HAVE_NCURSESW
-/* Convert an object to a character (wchar_t):
-
-    - int
-    - str of length 1
-
-   Return 1 on success, 0 on error. */
-static int
-PyCurses_ConvertToWchar_t(PyObject *obj,
-                          wchar_t *wch)
-{
-    if (PyUnicode_Check(obj)) {
-        wchar_t buffer[2];
-        if (PyUnicode_AsWideChar(obj, buffer, 2) != 1) {
-            PyErr_Format(PyExc_TypeError,
-                         "expect bytes or str of length 1, or int, "
-                         "got a str of length %zi",
-                         PyUnicode_GET_LENGTH(obj));
-            return 0;
-        }
-        *wch = buffer[0];
-        return 2;
-    }
-    else if (PyLong_CheckExact(obj)) {
-        long value;
-        int overflow;
-        value = PyLong_AsLongAndOverflow(obj, &overflow);
-        if (overflow) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "int doesn't fit in long");
-            return 0;
-        }
-        *wch = (wchar_t)value;
-        if ((long)*wch != value) {
-            PyErr_Format(PyExc_OverflowError,
-                         "character doesn't fit in wchar_t");
-            return 0;
-        }
-        return 1;
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "expect bytes or str of length 1, or int, got %s",
-                     Py_TYPE(obj)->tp_name);
-        return 0;
-    }
-}
-
-static PyObject *
-PyCurses_Unget_Wch(PyObject *self, PyObject *args)
-{
-    PyObject *obj;
-    wchar_t wch;
-
-    PyCursesInitialised;
-
-    if (!PyArg_ParseTuple(args,"O", &obj))
-        return NULL;
-
-    if (!PyCurses_ConvertToWchar_t(obj, &wch))
-        return NULL;
-    return PyCursesCheckERR(unget_wch(wch), "unget_wch");
-}
-#endif
-
-static PyObject *
-PyCurses_Use_Env(PyObject *self, PyObject *args)
-{
-    int flag;
-
-    switch(PyTuple_Size(args)) {
-    case 1:
-        if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag))
-            return NULL;
-        break;
-    default:
-        PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument");
-        return NULL;
-    }
-    use_env(flag);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-#ifndef STRICT_SYSV_CURSES
-static PyObject *
-PyCurses_Use_Default_Colors(PyObject *self)
-{
-    int code;
-
-    PyCursesInitialised;
-    PyCursesInitialisedColor;
-
-    code = use_default_colors();
-    if (code != ERR) {
-        Py_INCREF(Py_None);
-        return Py_None;
-    } else {
-        PyErr_SetString(PyCursesError, "use_default_colors() returned ERR");
-        return NULL;
-    }
-}
-#endif /* STRICT_SYSV_CURSES */
-
-/* List of functions defined in the module */
-
-static PyMethodDef PyCurses_methods[] = {
-    {"baudrate",            (PyCFunction)PyCurses_baudrate, METH_NOARGS},
-    {"beep",                (PyCFunction)PyCurses_beep, METH_NOARGS},
-    {"can_change_color",    (PyCFunction)PyCurses_can_change_color, METH_NOARGS},
-    {"cbreak",              (PyCFunction)PyCurses_cbreak, METH_VARARGS},
-    {"color_content",       (PyCFunction)PyCurses_Color_Content, METH_VARARGS},
-    {"color_pair",          (PyCFunction)PyCurses_color_pair, METH_VARARGS},
-    {"curs_set",            (PyCFunction)PyCurses_Curs_Set, METH_VARARGS},
-    {"def_prog_mode",       (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS},
-    {"def_shell_mode",      (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS},
-    {"delay_output",        (PyCFunction)PyCurses_Delay_Output, METH_VARARGS},
-    {"doupdate",            (PyCFunction)PyCurses_doupdate, METH_NOARGS},
-    {"echo",                (PyCFunction)PyCurses_echo, METH_VARARGS},
-    {"endwin",              (PyCFunction)PyCurses_endwin, METH_NOARGS},
-    {"erasechar",           (PyCFunction)PyCurses_EraseChar, METH_NOARGS},
-    {"filter",              (PyCFunction)PyCurses_filter, METH_NOARGS},
-    {"flash",               (PyCFunction)PyCurses_flash, METH_NOARGS},
-    {"flushinp",            (PyCFunction)PyCurses_flushinp, METH_NOARGS},
-#ifdef NCURSES_MOUSE_VERSION
-    {"getmouse",            (PyCFunction)PyCurses_GetMouse, METH_NOARGS},
-    {"ungetmouse",          (PyCFunction)PyCurses_UngetMouse, METH_VARARGS},
-#endif
-    {"getsyx",              (PyCFunction)PyCurses_getsyx, METH_NOARGS},
-    {"getwin",              (PyCFunction)PyCurses_GetWin, METH_O},
-    {"has_colors",          (PyCFunction)PyCurses_has_colors, METH_NOARGS},
-    {"has_ic",              (PyCFunction)PyCurses_has_ic, METH_NOARGS},
-    {"has_il",              (PyCFunction)PyCurses_has_il, METH_NOARGS},
-#ifndef STRICT_SYSV_CURSES
-    {"has_key",             (PyCFunction)PyCurses_has_key, METH_VARARGS},
-#endif
-    {"halfdelay",           (PyCFunction)PyCurses_HalfDelay, METH_VARARGS},
-    {"init_color",          (PyCFunction)PyCurses_Init_Color, METH_VARARGS},
-    {"init_pair",           (PyCFunction)PyCurses_Init_Pair, METH_VARARGS},
-    {"initscr",             (PyCFunction)PyCurses_InitScr, METH_NOARGS},
-    {"intrflush",           (PyCFunction)PyCurses_IntrFlush, METH_VARARGS},
-    {"isendwin",            (PyCFunction)PyCurses_isendwin, METH_NOARGS},
-#ifdef HAVE_CURSES_IS_TERM_RESIZED
-    {"is_term_resized",     (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS},
-#endif
-#if !defined(__NetBSD__)
-    {"keyname",             (PyCFunction)PyCurses_KeyName, METH_VARARGS},
-#endif
-    {"killchar",            (PyCFunction)PyCurses_KillChar, METH_NOARGS},
-    {"longname",            (PyCFunction)PyCurses_longname, METH_NOARGS},
-    {"meta",                (PyCFunction)PyCurses_Meta, METH_VARARGS},
-#ifdef NCURSES_MOUSE_VERSION
-    {"mouseinterval",       (PyCFunction)PyCurses_MouseInterval, METH_VARARGS},
-    {"mousemask",           (PyCFunction)PyCurses_MouseMask, METH_VARARGS},
-#endif
-    {"napms",               (PyCFunction)PyCurses_Napms, METH_VARARGS},
-    {"newpad",              (PyCFunction)PyCurses_NewPad, METH_VARARGS},
-    {"newwin",              (PyCFunction)PyCurses_NewWindow, METH_VARARGS},
-    {"nl",                  (PyCFunction)PyCurses_nl, METH_VARARGS},
-    {"nocbreak",            (PyCFunction)PyCurses_nocbreak, METH_NOARGS},
-    {"noecho",              (PyCFunction)PyCurses_noecho, METH_NOARGS},
-    {"nonl",                (PyCFunction)PyCurses_nonl, METH_NOARGS},
-    {"noqiflush",           (PyCFunction)PyCurses_noqiflush, METH_NOARGS},
-    {"noraw",               (PyCFunction)PyCurses_noraw, METH_NOARGS},
-    {"pair_content",        (PyCFunction)PyCurses_Pair_Content, METH_VARARGS},
-    {"pair_number",         (PyCFunction)PyCurses_pair_number, METH_VARARGS},
-    {"putp",                (PyCFunction)PyCurses_Putp, METH_VARARGS},
-    {"qiflush",             (PyCFunction)PyCurses_QiFlush, METH_VARARGS},
-    {"raw",                 (PyCFunction)PyCurses_raw, METH_VARARGS},
-    {"reset_prog_mode",     (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS},
-    {"reset_shell_mode",    (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS},
-    {"resetty",             (PyCFunction)PyCurses_resetty, METH_NOARGS},
-#ifdef HAVE_CURSES_RESIZETERM
-    {"resizeterm",          (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS},
-#endif
-#ifdef HAVE_CURSES_RESIZE_TERM
-    {"resize_term",         (PyCFunction)PyCurses_Resize_Term, METH_VARARGS},
-#endif
-    {"savetty",             (PyCFunction)PyCurses_savetty, METH_NOARGS},
-    {"setsyx",              (PyCFunction)PyCurses_setsyx, METH_VARARGS},
-    {"setupterm",           (PyCFunction)PyCurses_setupterm,
-     METH_VARARGS|METH_KEYWORDS},
-    {"start_color",         (PyCFunction)PyCurses_Start_Color, METH_NOARGS},
-    {"termattrs",           (PyCFunction)PyCurses_termattrs, METH_NOARGS},
-    {"termname",            (PyCFunction)PyCurses_termname, METH_NOARGS},
-    {"tigetflag",           (PyCFunction)PyCurses_tigetflag, METH_VARARGS},
-    {"tigetnum",            (PyCFunction)PyCurses_tigetnum, METH_VARARGS},
-    {"tigetstr",            (PyCFunction)PyCurses_tigetstr, METH_VARARGS},
-    {"tparm",               (PyCFunction)PyCurses_tparm, METH_VARARGS},
-    {"typeahead",           (PyCFunction)PyCurses_TypeAhead, METH_VARARGS},
-    {"unctrl",              (PyCFunction)PyCurses_UnCtrl, METH_VARARGS},
-    {"ungetch",             (PyCFunction)PyCurses_UngetCh, METH_VARARGS},
-#ifdef HAVE_NCURSESW
-    {"unget_wch",           (PyCFunction)PyCurses_Unget_Wch, METH_VARARGS},
-#endif
-    {"use_env",             (PyCFunction)PyCurses_Use_Env, METH_VARARGS},
-#ifndef STRICT_SYSV_CURSES
-    {"use_default_colors",  (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS},
-#endif
-    {NULL,                  NULL}         /* sentinel */
-};
-
-/* Initialization function for the module */
-
-
-static struct PyModuleDef _cursesmodule = {
-    PyModuleDef_HEAD_INIT,
-    "_curses",
-    NULL,
-    -1,
-    PyCurses_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit__curses(void)
-{
-    PyObject *m, *d, *v, *c_api_object;
-    static void *PyCurses_API[PyCurses_API_pointers];
-
-    /* Initialize object type */
-    if (PyType_Ready(&PyCursesWindow_Type) < 0)
-        return NULL;
-
-    /* Initialize the C API pointer array */
-    PyCurses_API[0] = (void *)&PyCursesWindow_Type;
-    PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled;
-    PyCurses_API[2] = (void *)func_PyCursesInitialised;
-    PyCurses_API[3] = (void *)func_PyCursesInitialisedColor;
-
-    /* Create the module and add the functions */
-    m = PyModule_Create(&_cursesmodule);
-    if (m == NULL)
-        return NULL;
-
-    /* Add some symbolic constants to the module */
-    d = PyModule_GetDict(m);
-    if (d == NULL)
-        return NULL;
-    ModDict = d; /* For PyCurses_InitScr to use later */
-
-    /* Add a capsule for the C API */
-    c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL);
-    PyDict_SetItemString(d, "_C_API", c_api_object);
-    Py_DECREF(c_api_object);
-
-    /* For exception curses.error */
-    PyCursesError = PyErr_NewException("_curses.error", NULL, NULL);
-    PyDict_SetItemString(d, "error", PyCursesError);
-
-    /* Make the version available */
-    v = PyBytes_FromString(PyCursesVersion);
-    PyDict_SetItemString(d, "version", v);
-    PyDict_SetItemString(d, "__version__", v);
-    Py_DECREF(v);
-
-    SetDictInt("ERR", ERR);
-    SetDictInt("OK", OK);
-
-    /* Here are some attributes you can add to chars to print */
-
-    SetDictInt("A_ATTRIBUTES",      A_ATTRIBUTES);
-    SetDictInt("A_NORMAL",              A_NORMAL);
-    SetDictInt("A_STANDOUT",            A_STANDOUT);
-    SetDictInt("A_UNDERLINE",           A_UNDERLINE);
-    SetDictInt("A_REVERSE",             A_REVERSE);
-    SetDictInt("A_BLINK",               A_BLINK);
-    SetDictInt("A_DIM",                 A_DIM);
-    SetDictInt("A_BOLD",                A_BOLD);
-    SetDictInt("A_ALTCHARSET",          A_ALTCHARSET);
-#if !defined(__NetBSD__)
-    SetDictInt("A_INVIS",           A_INVIS);
-#endif
-    SetDictInt("A_PROTECT",         A_PROTECT);
-    SetDictInt("A_CHARTEXT",        A_CHARTEXT);
-    SetDictInt("A_COLOR",           A_COLOR);
-
-    /* The following are never available with strict SYSV curses */
-#ifdef A_HORIZONTAL
-    SetDictInt("A_HORIZONTAL",      A_HORIZONTAL);
-#endif
-#ifdef A_LEFT
-    SetDictInt("A_LEFT",            A_LEFT);
-#endif
-#ifdef A_LOW
-    SetDictInt("A_LOW",             A_LOW);
-#endif
-#ifdef A_RIGHT
-    SetDictInt("A_RIGHT",           A_RIGHT);
-#endif
-#ifdef A_TOP
-    SetDictInt("A_TOP",             A_TOP);
-#endif
-#ifdef A_VERTICAL
-    SetDictInt("A_VERTICAL",        A_VERTICAL);
-#endif
-
-    SetDictInt("COLOR_BLACK",       COLOR_BLACK);
-    SetDictInt("COLOR_RED",         COLOR_RED);
-    SetDictInt("COLOR_GREEN",       COLOR_GREEN);
-    SetDictInt("COLOR_YELLOW",      COLOR_YELLOW);
-    SetDictInt("COLOR_BLUE",        COLOR_BLUE);
-    SetDictInt("COLOR_MAGENTA",     COLOR_MAGENTA);
-    SetDictInt("COLOR_CYAN",        COLOR_CYAN);
-    SetDictInt("COLOR_WHITE",       COLOR_WHITE);
-
-#ifdef NCURSES_MOUSE_VERSION
-    /* Mouse-related constants */
-    SetDictInt("BUTTON1_PRESSED",          BUTTON1_PRESSED);
-    SetDictInt("BUTTON1_RELEASED",         BUTTON1_RELEASED);
-    SetDictInt("BUTTON1_CLICKED",          BUTTON1_CLICKED);
-    SetDictInt("BUTTON1_DOUBLE_CLICKED",   BUTTON1_DOUBLE_CLICKED);
-    SetDictInt("BUTTON1_TRIPLE_CLICKED",   BUTTON1_TRIPLE_CLICKED);
-
-    SetDictInt("BUTTON2_PRESSED",          BUTTON2_PRESSED);
-    SetDictInt("BUTTON2_RELEASED",         BUTTON2_RELEASED);
-    SetDictInt("BUTTON2_CLICKED",          BUTTON2_CLICKED);
-    SetDictInt("BUTTON2_DOUBLE_CLICKED",   BUTTON2_DOUBLE_CLICKED);
-    SetDictInt("BUTTON2_TRIPLE_CLICKED",   BUTTON2_TRIPLE_CLICKED);
-
-    SetDictInt("BUTTON3_PRESSED",          BUTTON3_PRESSED);
-    SetDictInt("BUTTON3_RELEASED",         BUTTON3_RELEASED);
-    SetDictInt("BUTTON3_CLICKED",          BUTTON3_CLICKED);
-    SetDictInt("BUTTON3_DOUBLE_CLICKED",   BUTTON3_DOUBLE_CLICKED);
-    SetDictInt("BUTTON3_TRIPLE_CLICKED",   BUTTON3_TRIPLE_CLICKED);
-
-    SetDictInt("BUTTON4_PRESSED",          BUTTON4_PRESSED);
-    SetDictInt("BUTTON4_RELEASED",         BUTTON4_RELEASED);
-    SetDictInt("BUTTON4_CLICKED",          BUTTON4_CLICKED);
-    SetDictInt("BUTTON4_DOUBLE_CLICKED",   BUTTON4_DOUBLE_CLICKED);
-    SetDictInt("BUTTON4_TRIPLE_CLICKED",   BUTTON4_TRIPLE_CLICKED);
-
-    SetDictInt("BUTTON_SHIFT",             BUTTON_SHIFT);
-    SetDictInt("BUTTON_CTRL",              BUTTON_CTRL);
-    SetDictInt("BUTTON_ALT",               BUTTON_ALT);
-
-    SetDictInt("ALL_MOUSE_EVENTS",         ALL_MOUSE_EVENTS);
-    SetDictInt("REPORT_MOUSE_POSITION",    REPORT_MOUSE_POSITION);
-#endif
-    /* Now set everything up for KEY_ variables */
-    {
-        int key;
-        char *key_n;
-        char *key_n2;
-#if !defined(__NetBSD__)
-        for (key=KEY_MIN;key < KEY_MAX; key++) {
-            key_n = (char *)keyname(key);
-            if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0)
-                continue;
-            if (strncmp(key_n,"KEY_F(",6)==0) {
-                char *p1, *p2;
-                key_n2 = PyMem_Malloc(strlen(key_n)+1);
-                if (!key_n2) {
-                    PyErr_NoMemory();
-                    break;
-                }
-                p1 = key_n;
-                p2 = key_n2;
-                while (*p1) {
-                    if (*p1 != '(' && *p1 != ')') {
-                        *p2 = *p1;
-                        p2++;
-                    }
-                    p1++;
-                }
-                *p2 = (char)0;
-            } else
-                key_n2 = key_n;
-            SetDictInt(key_n2,key);
-            if (key_n2 != key_n)
-                PyMem_Free(key_n2);
-        }
-#endif
-        SetDictInt("KEY_MIN", KEY_MIN);
-        SetDictInt("KEY_MAX", KEY_MAX);
-    }
-    return m;
-}
+/*[clinic end generated code: output=660ab0ae6d8fbdda input=a9049054013a1b77]*/
diff --git a/Modules/_datetimemodule.c b/Modules/clinic/_datetimemodule.c.h
copy from Modules/_datetimemodule.c
copy to Modules/clinic/_datetimemodule.c.h
--- a/Modules/_datetimemodule.c
+++ b/Modules/clinic/_datetimemodule.c.h
@@ -1,4136 +1,5 @@
-/*  C implementation for the date/time type documented at
- *  http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
- */
-
-#include "Python.h"
-#include "structmember.h"
-
-#include <time.h>
-
-#ifdef MS_WINDOWS
-#  include <winsock2.h>         /* struct timeval */
-#endif
-
-/* Differentiate between building the core module and building extension
- * modules.
- */
-#ifndef Py_BUILD_CORE
-#define Py_BUILD_CORE
-#endif
-#include "datetime.h"
-#undef Py_BUILD_CORE
-
 /*[clinic input]
-module datetime
-class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
-
-/* We require that C int be at least 32 bits, and use int virtually
- * everywhere.  In just a few cases we use a temp long, where a Python
- * API returns a C long.  In such cases, we have to ensure that the
- * final result fits in a C int (this can be an issue on 64-bit boxes).
- */
-#if SIZEOF_INT < 4
-#       error "_datetime.c requires that C int have at least 32 bits"
-#endif
-
-#define MINYEAR 1
-#define MAXYEAR 9999
-#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
-
-/* Nine decimal digits is easy to communicate, and leaves enough room
- * so that two delta days can be added w/o fear of overflowing a signed
- * 32-bit int, and with plenty of room left over to absorb any possible
- * carries from adding seconds.
- */
-#define MAX_DELTA_DAYS 999999999
-
-/* Rename the long macros in datetime.h to more reasonable short names. */
-#define GET_YEAR                PyDateTime_GET_YEAR
-#define GET_MONTH               PyDateTime_GET_MONTH
-#define GET_DAY                 PyDateTime_GET_DAY
-#define DATE_GET_HOUR           PyDateTime_DATE_GET_HOUR
-#define DATE_GET_MINUTE         PyDateTime_DATE_GET_MINUTE
-#define DATE_GET_SECOND         PyDateTime_DATE_GET_SECOND
-#define DATE_GET_MICROSECOND    PyDateTime_DATE_GET_MICROSECOND
-
-/* Date accessors for date and datetime. */
-#define SET_YEAR(o, v)          (((o)->data[0] = ((v) & 0xff00) >> 8), \
-                 ((o)->data[1] = ((v) & 0x00ff)))
-#define SET_MONTH(o, v)         (PyDateTime_GET_MONTH(o) = (v))
-#define SET_DAY(o, v)           (PyDateTime_GET_DAY(o) = (v))
-
-/* Date/Time accessors for datetime. */
-#define DATE_SET_HOUR(o, v)     (PyDateTime_DATE_GET_HOUR(o) = (v))
-#define DATE_SET_MINUTE(o, v)   (PyDateTime_DATE_GET_MINUTE(o) = (v))
-#define DATE_SET_SECOND(o, v)   (PyDateTime_DATE_GET_SECOND(o) = (v))
-#define DATE_SET_MICROSECOND(o, v)      \
-    (((o)->data[7] = ((v) & 0xff0000) >> 16), \
-     ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
-     ((o)->data[9] = ((v) & 0x0000ff)))
-
-/* Time accessors for time. */
-#define TIME_GET_HOUR           PyDateTime_TIME_GET_HOUR
-#define TIME_GET_MINUTE         PyDateTime_TIME_GET_MINUTE
-#define TIME_GET_SECOND         PyDateTime_TIME_GET_SECOND
-#define TIME_GET_MICROSECOND    PyDateTime_TIME_GET_MICROSECOND
-#define TIME_SET_HOUR(o, v)     (PyDateTime_TIME_GET_HOUR(o) = (v))
-#define TIME_SET_MINUTE(o, v)   (PyDateTime_TIME_GET_MINUTE(o) = (v))
-#define TIME_SET_SECOND(o, v)   (PyDateTime_TIME_GET_SECOND(o) = (v))
-#define TIME_SET_MICROSECOND(o, v)      \
-    (((o)->data[3] = ((v) & 0xff0000) >> 16), \
-     ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
-     ((o)->data[5] = ((v) & 0x0000ff)))
-
-/* Delta accessors for timedelta. */
-#define GET_TD_DAYS(o)          (((PyDateTime_Delta *)(o))->days)
-#define GET_TD_SECONDS(o)       (((PyDateTime_Delta *)(o))->seconds)
-#define GET_TD_MICROSECONDS(o)  (((PyDateTime_Delta *)(o))->microseconds)
-
-#define SET_TD_DAYS(o, v)       ((o)->days = (v))
-#define SET_TD_SECONDS(o, v)    ((o)->seconds = (v))
-#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
-
-/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
- * p->hastzinfo.
- */
-#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
-#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
-                            ((PyDateTime_Time *)(p))->tzinfo : Py_None)
-#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
-                          ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
-/* M is a char or int claiming to be a valid month.  The macro is equivalent
- * to the two-sided Python test
- *      1 <= M <= 12
- */
-#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
-
-/* Forward declarations. */
-static PyTypeObject PyDateTime_DateType;
-static PyTypeObject PyDateTime_DateTimeType;
-static PyTypeObject PyDateTime_DeltaType;
-static PyTypeObject PyDateTime_TimeType;
-static PyTypeObject PyDateTime_TZInfoType;
-static PyTypeObject PyDateTime_TimeZoneType;
-
-_Py_IDENTIFIER(as_integer_ratio);
-_Py_IDENTIFIER(fromutc);
-_Py_IDENTIFIER(isoformat);
-_Py_IDENTIFIER(strftime);
-
-/* ---------------------------------------------------------------------------
- * Math utilities.
- */
-
-/* k = i+j overflows iff k differs in sign from both inputs,
- * iff k^i has sign bit set and k^j has sign bit set,
- * iff (k^i)&(k^j) has sign bit set.
- */
-#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
-    ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
-
-/* Compute Python divmod(x, y), returning the quotient and storing the
- * remainder into *r.  The quotient is the floor of x/y, and that's
- * the real point of this.  C will probably truncate instead (C99
- * requires truncation; C89 left it implementation-defined).
- * Simplification:  we *require* that y > 0 here.  That's appropriate
- * for all the uses made of it.  This simplifies the code and makes
- * the overflow case impossible (divmod(LONG_MIN, -1) is the only
- * overflow case).
- */
-static int
-divmod(int x, int y, int *r)
-{
-    int quo;
-
-    assert(y > 0);
-    quo = x / y;
-    *r = x - quo * y;
-    if (*r < 0) {
-        --quo;
-        *r += y;
-    }
-    assert(0 <= *r && *r < y);
-    return quo;
-}
-
-/* Nearest integer to m / n for integers m and n. Half-integer results
- * are rounded to even.
- */
-static PyObject *
-divide_nearest(PyObject *m, PyObject *n)
-{
-    PyObject *result;
-    PyObject *temp;
-
-    temp = _PyLong_DivmodNear(m, n);
-    if (temp == NULL)
-        return NULL;
-    result = PyTuple_GET_ITEM(temp, 0);
-    Py_INCREF(result);
-    Py_DECREF(temp);
-
-    return result;
-}
-
-/* ---------------------------------------------------------------------------
- * General calendrical helper functions
- */
-
-/* For each month ordinal in 1..12, the number of days in that month,
- * and the number of days before that month in the same year.  These
- * are correct for non-leap years only.
- */
-static int _days_in_month[] = {
-    0, /* unused; this vector uses 1-based indexing */
-    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
-};
-
-static int _days_before_month[] = {
-    0, /* unused; this vector uses 1-based indexing */
-    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
-};
-
-/* year -> 1 if leap year, else 0. */
-static int
-is_leap(int year)
-{
-    /* Cast year to unsigned.  The result is the same either way, but
-     * C can generate faster code for unsigned mod than for signed
-     * mod (especially for % 4 -- a good compiler should just grab
-     * the last 2 bits when the LHS is unsigned).
-     */
-    const unsigned int ayear = (unsigned int)year;
-    return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
-}
-
-/* year, month -> number of days in that month in that year */
-static int
-days_in_month(int year, int month)
-{
-    assert(month >= 1);
-    assert(month <= 12);
-    if (month == 2 && is_leap(year))
-        return 29;
-    else
-        return _days_in_month[month];
-}
-
-/* year, month -> number of days in year preceeding first day of month */
-static int
-days_before_month(int year, int month)
-{
-    int days;
-
-    assert(month >= 1);
-    assert(month <= 12);
-    days = _days_before_month[month];
-    if (month > 2 && is_leap(year))
-        ++days;
-    return days;
-}
-
-/* year -> number of days before January 1st of year.  Remember that we
- * start with year 1, so days_before_year(1) == 0.
- */
-static int
-days_before_year(int year)
-{
-    int y = year - 1;
-    /* This is incorrect if year <= 0; we really want the floor
-     * here.  But so long as MINYEAR is 1, the smallest year this
-     * can see is 1.
-     */
-    assert (year >= 1);
-    return y*365 + y/4 - y/100 + y/400;
-}
-
-/* Number of days in 4, 100, and 400 year cycles.  That these have
- * the correct values is asserted in the module init function.
- */
-#define DI4Y    1461    /* days_before_year(5); days in 4 years */
-#define DI100Y  36524   /* days_before_year(101); days in 100 years */
-#define DI400Y  146097  /* days_before_year(401); days in 400 years  */
-
-/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
-static void
-ord_to_ymd(int ordinal, int *year, int *month, int *day)
-{
-    int n, n1, n4, n100, n400, leapyear, preceding;
-
-    /* ordinal is a 1-based index, starting at 1-Jan-1.  The pattern of
-     * leap years repeats exactly every 400 years.  The basic strategy is
-     * to find the closest 400-year boundary at or before ordinal, then
-     * work with the offset from that boundary to ordinal.  Life is much
-     * clearer if we subtract 1 from ordinal first -- then the values
-     * of ordinal at 400-year boundaries are exactly those divisible
-     * by DI400Y:
-     *
-     *    D  M   Y            n              n-1
-     *    -- --- ----        ----------     ----------------
-     *    31 Dec -400        -DI400Y       -DI400Y -1
-     *     1 Jan -399         -DI400Y +1   -DI400Y      400-year boundary
-     *    ...
-     *    30 Dec  000        -1             -2
-     *    31 Dec  000         0             -1
-     *     1 Jan  001         1              0          400-year boundary
-     *     2 Jan  001         2              1
-     *     3 Jan  001         3              2
-     *    ...
-     *    31 Dec  400         DI400Y        DI400Y -1
-     *     1 Jan  401         DI400Y +1     DI400Y      400-year boundary
-     */
-    assert(ordinal >= 1);
-    --ordinal;
-    n400 = ordinal / DI400Y;
-    n = ordinal % DI400Y;
-    *year = n400 * 400 + 1;
-
-    /* Now n is the (non-negative) offset, in days, from January 1 of
-     * year, to the desired date.  Now compute how many 100-year cycles
-     * precede n.
-     * Note that it's possible for n100 to equal 4!  In that case 4 full
-     * 100-year cycles precede the desired day, which implies the
-     * desired day is December 31 at the end of a 400-year cycle.
-     */
-    n100 = n / DI100Y;
-    n = n % DI100Y;
-
-    /* Now compute how many 4-year cycles precede it. */
-    n4 = n / DI4Y;
-    n = n % DI4Y;
-
-    /* And now how many single years.  Again n1 can be 4, and again
-     * meaning that the desired day is December 31 at the end of the
-     * 4-year cycle.
-     */
-    n1 = n / 365;
-    n = n % 365;
-
-    *year += n100 * 100 + n4 * 4 + n1;
-    if (n1 == 4 || n100 == 4) {
-        assert(n == 0);
-        *year -= 1;
-        *month = 12;
-        *day = 31;
-        return;
-    }
-
-    /* Now the year is correct, and n is the offset from January 1.  We
-     * find the month via an estimate that's either exact or one too
-     * large.
-     */
-    leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
-    assert(leapyear == is_leap(*year));
-    *month = (n + 50) >> 5;
-    preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
-    if (preceding > n) {
-        /* estimate is too large */
-        *month -= 1;
-        preceding -= days_in_month(*year, *month);
-    }
-    n -= preceding;
-    assert(0 <= n);
-    assert(n < days_in_month(*year, *month));
-
-    *day = n + 1;
-}
-
-/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
-static int
-ymd_to_ord(int year, int month, int day)
-{
-    return days_before_year(year) + days_before_month(year, month) + day;
-}
-
-/* Day of week, where Monday==0, ..., Sunday==6.  1/1/1 was a Monday. */
-static int
-weekday(int year, int month, int day)
-{
-    return (ymd_to_ord(year, month, day) + 6) % 7;
-}
-
-/* Ordinal of the Monday starting week 1 of the ISO year.  Week 1 is the
- * first calendar week containing a Thursday.
- */
-static int
-iso_week1_monday(int year)
-{
-    int first_day = ymd_to_ord(year, 1, 1);     /* ord of 1/1 */
-    /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
-    int first_weekday = (first_day + 6) % 7;
-    /* ordinal of closest Monday at or before 1/1 */
-    int week1_monday  = first_day - first_weekday;
-
-    if (first_weekday > 3)      /* if 1/1 was Fri, Sat, Sun */
-        week1_monday += 7;
-    return week1_monday;
-}
-
-/* ---------------------------------------------------------------------------
- * Range checkers.
- */
-
-/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS.  If so, return 0.
- * If not, raise OverflowError and return -1.
- */
-static int
-check_delta_day_range(int days)
-{
-    if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
-        return 0;
-    PyErr_Format(PyExc_OverflowError,
-                 "days=%d; must have magnitude <= %d",
-                 days, MAX_DELTA_DAYS);
-    return -1;
-}
-
-/* Check that date arguments are in range.  Return 0 if they are.  If they
- * aren't, raise ValueError and return -1.
- */
-static int
-check_date_args(int year, int month, int day)
-{
-
-    if (year < MINYEAR || year > MAXYEAR) {
-        PyErr_SetString(PyExc_ValueError,
-                        "year is out of range");
-        return -1;
-    }
-    if (month < 1 || month > 12) {
-        PyErr_SetString(PyExc_ValueError,
-                        "month must be in 1..12");
-        return -1;
-    }
-    if (day < 1 || day > days_in_month(year, month)) {
-        PyErr_SetString(PyExc_ValueError,
-                        "day is out of range for month");
-        return -1;
-    }
-    return 0;
-}
-
-/* Check that time arguments are in range.  Return 0 if they are.  If they
- * aren't, raise ValueError and return -1.
- */
-static int
-check_time_args(int h, int m, int s, int us)
-{
-    if (h < 0 || h > 23) {
-        PyErr_SetString(PyExc_ValueError,
-                        "hour must be in 0..23");
-        return -1;
-    }
-    if (m < 0 || m > 59) {
-        PyErr_SetString(PyExc_ValueError,
-                        "minute must be in 0..59");
-        return -1;
-    }
-    if (s < 0 || s > 59) {
-        PyErr_SetString(PyExc_ValueError,
-                        "second must be in 0..59");
-        return -1;
-    }
-    if (us < 0 || us > 999999) {
-        PyErr_SetString(PyExc_ValueError,
-                        "microsecond must be in 0..999999");
-        return -1;
-    }
-    return 0;
-}
-
-/* ---------------------------------------------------------------------------
- * Normalization utilities.
- */
-
-/* One step of a mixed-radix conversion.  A "hi" unit is equivalent to
- * factor "lo" units.  factor must be > 0.  If *lo is less than 0, or
- * at least factor, enough of *lo is converted into "hi" units so that
- * 0 <= *lo < factor.  The input values must be such that int overflow
- * is impossible.
- */
-static void
-normalize_pair(int *hi, int *lo, int factor)
-{
-    assert(factor > 0);
-    assert(lo != hi);
-    if (*lo < 0 || *lo >= factor) {
-        const int num_hi = divmod(*lo, factor, lo);
-        const int new_hi = *hi + num_hi;
-        assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
-        *hi = new_hi;
-    }
-    assert(0 <= *lo && *lo < factor);
-}
-
-/* Fiddle days (d), seconds (s), and microseconds (us) so that
- *      0 <= *s < 24*3600
- *      0 <= *us < 1000000
- * The input values must be such that the internals don't overflow.
- * The way this routine is used, we don't get close.
- */
-static void
-normalize_d_s_us(int *d, int *s, int *us)
-{
-    if (*us < 0 || *us >= 1000000) {
-        normalize_pair(s, us, 1000000);
-        /* |s| can't be bigger than about
-         * |original s| + |original us|/1000000 now.
-         */
-
-    }
-    if (*s < 0 || *s >= 24*3600) {
-        normalize_pair(d, s, 24*3600);
-        /* |d| can't be bigger than about
-         * |original d| +
-         * (|original s| + |original us|/1000000) / (24*3600) now.
-         */
-    }
-    assert(0 <= *s && *s < 24*3600);
-    assert(0 <= *us && *us < 1000000);
-}
-
-/* Fiddle years (y), months (m), and days (d) so that
- *      1 <= *m <= 12
- *      1 <= *d <= days_in_month(*y, *m)
- * The input values must be such that the internals don't overflow.
- * The way this routine is used, we don't get close.
- */
-static int
-normalize_y_m_d(int *y, int *m, int *d)
-{
-    int dim;            /* # of days in month */
-
-    /* In actual use, m is always the month component extracted from a
-     * date/datetime object.  Therefore it is always in [1, 12] range.
-     */
-
-    assert(1 <= *m && *m <= 12);
-
-    /* Now only day can be out of bounds (year may also be out of bounds
-     * for a datetime object, but we don't care about that here).
-     * If day is out of bounds, what to do is arguable, but at least the
-     * method here is principled and explainable.
-     */
-    dim = days_in_month(*y, *m);
-    if (*d < 1 || *d > dim) {
-        /* Move day-1 days from the first of the month.  First try to
-         * get off cheap if we're only one day out of range
-         * (adjustments for timezone alone can't be worse than that).
-         */
-        if (*d == 0) {
-            --*m;
-            if (*m > 0)
-                *d = days_in_month(*y, *m);
-            else {
-                --*y;
-                *m = 12;
-                *d = 31;
-            }
-        }
-        else if (*d == dim + 1) {
-            /* move forward a day */
-            ++*m;
-            *d = 1;
-            if (*m > 12) {
-                *m = 1;
-                ++*y;
-            }
-        }
-        else {
-            int ordinal = ymd_to_ord(*y, *m, 1) +
-                                      *d - 1;
-            if (ordinal < 1 || ordinal > MAXORDINAL) {
-                goto error;
-            } else {
-                ord_to_ymd(ordinal, y, m, d);
-                return 0;
-            }
-        }
-    }
-    assert(*m > 0);
-    assert(*d > 0);
-    if (MINYEAR <= *y && *y <= MAXYEAR)
-        return 0;
- error:
-    PyErr_SetString(PyExc_OverflowError,
-            "date value out of range");
-    return -1;
-
-}
-
-/* Fiddle out-of-bounds months and days so that the result makes some kind
- * of sense.  The parameters are both inputs and outputs.  Returns < 0 on
- * failure, where failure means the adjusted year is out of bounds.
- */
-static int
-normalize_date(int *year, int *month, int *day)
-{
-    return normalize_y_m_d(year, month, day);
-}
-
-/* Force all the datetime fields into range.  The parameters are both
- * inputs and outputs.  Returns < 0 on error.
- */
-static int
-normalize_datetime(int *year, int *month, int *day,
-                   int *hour, int *minute, int *second,
-                   int *microsecond)
-{
-    normalize_pair(second, microsecond, 1000000);
-    normalize_pair(minute, second, 60);
-    normalize_pair(hour, minute, 60);
-    normalize_pair(day, hour, 24);
-    return normalize_date(year, month, day);
-}
-
-/* ---------------------------------------------------------------------------
- * Basic object allocation:  tp_alloc implementations.  These allocate
- * Python objects of the right size and type, and do the Python object-
- * initialization bit.  If there's not enough memory, they return NULL after
- * setting MemoryError.  All data members remain uninitialized trash.
- *
- * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
- * member is needed.  This is ugly, imprecise, and possibly insecure.
- * tp_basicsize for the time and datetime types is set to the size of the
- * struct that has room for the tzinfo member, so subclasses in Python will
- * allocate enough space for a tzinfo member whether or not one is actually
- * needed.  That's the "ugly and imprecise" parts.  The "possibly insecure"
- * part is that PyType_GenericAlloc() (which subclasses in Python end up
- * using) just happens today to effectively ignore the nitems argument
- * when tp_itemsize is 0, which it is for these type objects.  If that
- * changes, perhaps the callers of tp_alloc slots in this file should
- * be changed to force a 0 nitems argument unless the type being allocated
- * is a base type implemented in this file (so that tp_alloc is time_alloc
- * or datetime_alloc below, which know about the nitems abuse).
- */
-
-static PyObject *
-time_alloc(PyTypeObject *type, Py_ssize_t aware)
-{
-    PyObject *self;
-
-    self = (PyObject *)
-        PyObject_MALLOC(aware ?
-                        sizeof(PyDateTime_Time) :
-                sizeof(_PyDateTime_BaseTime));
-    if (self == NULL)
-        return (PyObject *)PyErr_NoMemory();
-    (void)PyObject_INIT(self, type);
-    return self;
-}
-
-static PyObject *
-datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
-{
-    PyObject *self;
-
-    self = (PyObject *)
-        PyObject_MALLOC(aware ?
-                        sizeof(PyDateTime_DateTime) :
-                sizeof(_PyDateTime_BaseDateTime));
-    if (self == NULL)
-        return (PyObject *)PyErr_NoMemory();
-    (void)PyObject_INIT(self, type);
-    return self;
-}
-
-/* ---------------------------------------------------------------------------
- * Helpers for setting object fields.  These work on pointers to the
- * appropriate base class.
- */
-
-/* For date and datetime. */
-static void
-set_date_fields(PyDateTime_Date *self, int y, int m, int d)
-{
-    self->hashcode = -1;
-    SET_YEAR(self, y);
-    SET_MONTH(self, m);
-    SET_DAY(self, d);
-}
-
-/* ---------------------------------------------------------------------------
- * Create various objects, mostly without range checking.
- */
-
-/* Create a date instance with no range checking. */
-static PyObject *
-new_date_ex(int year, int month, int day, PyTypeObject *type)
-{
-    PyDateTime_Date *self;
-
-    self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
-    if (self != NULL)
-        set_date_fields(self, year, month, day);
-    return (PyObject *) self;
-}
-
-#define new_date(year, month, day) \
-    new_date_ex(year, month, day, &PyDateTime_DateType)
-
-/* Create a datetime instance with no range checking. */
-static PyObject *
-new_datetime_ex(int year, int month, int day, int hour, int minute,
-             int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
-{
-    PyDateTime_DateTime *self;
-    char aware = tzinfo != Py_None;
-
-    self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
-    if (self != NULL) {
-        self->hastzinfo = aware;
-        set_date_fields((PyDateTime_Date *)self, year, month, day);
-        DATE_SET_HOUR(self, hour);
-        DATE_SET_MINUTE(self, minute);
-        DATE_SET_SECOND(self, second);
-        DATE_SET_MICROSECOND(self, usecond);
-        if (aware) {
-            Py_INCREF(tzinfo);
-            self->tzinfo = tzinfo;
-        }
-    }
-    return (PyObject *)self;
-}
-
-#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo)           \
-    new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo,            \
-                    &PyDateTime_DateTimeType)
-
-/* Create a time instance with no range checking. */
-static PyObject *
-new_time_ex(int hour, int minute, int second, int usecond,
-            PyObject *tzinfo, PyTypeObject *type)
-{
-    PyDateTime_Time *self;
-    char aware = tzinfo != Py_None;
-
-    self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
-    if (self != NULL) {
-        self->hastzinfo = aware;
-        self->hashcode = -1;
-        TIME_SET_HOUR(self, hour);
-        TIME_SET_MINUTE(self, minute);
-        TIME_SET_SECOND(self, second);
-        TIME_SET_MICROSECOND(self, usecond);
-        if (aware) {
-            Py_INCREF(tzinfo);
-            self->tzinfo = tzinfo;
-        }
-    }
-    return (PyObject *)self;
-}
-
-#define new_time(hh, mm, ss, us, tzinfo)                \
-    new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
-
-/* Create a timedelta instance.  Normalize the members iff normalize is
- * true.  Passing false is a speed optimization, if you know for sure
- * that seconds and microseconds are already in their proper ranges.  In any
- * case, raises OverflowError and returns NULL if the normalized days is out
- * of range).
- */
-static PyObject *
-new_delta_ex(int days, int seconds, int microseconds, int normalize,
-             PyTypeObject *type)
-{
-    PyDateTime_Delta *self;
-
-    if (normalize)
-        normalize_d_s_us(&days, &seconds, &microseconds);
-    assert(0 <= seconds && seconds < 24*3600);
-    assert(0 <= microseconds && microseconds < 1000000);
-
-    if (check_delta_day_range(days) < 0)
-        return NULL;
-
-    self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
-    if (self != NULL) {
-        self->hashcode = -1;
-        SET_TD_DAYS(self, days);
-        SET_TD_SECONDS(self, seconds);
-        SET_TD_MICROSECONDS(self, microseconds);
-    }
-    return (PyObject *) self;
-}
-
-#define new_delta(d, s, us, normalize)  \
-    new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
-
-
-typedef struct
-{
-    PyObject_HEAD
-    PyObject *offset;
-    PyObject *name;
-} PyDateTime_TimeZone;
-
-/* The interned UTC timezone instance */
-static PyObject *PyDateTime_TimeZone_UTC;
-/* The interned Epoch datetime instance */
-static PyObject *PyDateTime_Epoch;
-
-/* Create new timezone instance checking offset range.  This
-   function does not check the name argument.  Caller must assure
-   that offset is a timedelta instance and name is either NULL
-   or a unicode object. */
-static PyObject *
-create_timezone(PyObject *offset, PyObject *name)
-{
-    PyDateTime_TimeZone *self;
-    PyTypeObject *type = &PyDateTime_TimeZoneType;
-
-    assert(offset != NULL);
-    assert(PyDelta_Check(offset));
-    assert(name == NULL || PyUnicode_Check(name));
-
-    self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
-    if (self == NULL) {
-        return NULL;
-    }
-    Py_INCREF(offset);
-    self->offset = offset;
-    Py_XINCREF(name);
-    self->name = name;
-    return (PyObject *)self;
-}
-
-static int delta_bool(PyDateTime_Delta *self);
-
-static PyObject *
-new_timezone(PyObject *offset, PyObject *name)
-{
-    assert(offset != NULL);
-    assert(PyDelta_Check(offset));
-    assert(name == NULL || PyUnicode_Check(name));
-
-    if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
-        Py_INCREF(PyDateTime_TimeZone_UTC);
-        return PyDateTime_TimeZone_UTC;
-    }
-    if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
-        PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                     " representing a whole number of minutes,"
-                     " not %R.", offset);
-        return NULL;
-    }
-    if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
-        GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
-        PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                     " strictly between -timedelta(hours=24) and"
-                     " timedelta(hours=24),"
-                     " not %R.", offset);
-        return NULL;
-    }
-
-    return create_timezone(offset, name);
-}
-
-/* ---------------------------------------------------------------------------
- * tzinfo helpers.
- */
-
-/* Ensure that p is None or of a tzinfo subclass.  Return 0 if OK; if not
- * raise TypeError and return -1.
- */
-static int
-check_tzinfo_subclass(PyObject *p)
-{
-    if (p == Py_None || PyTZInfo_Check(p))
-        return 0;
-    PyErr_Format(PyExc_TypeError,
-                 "tzinfo argument must be None or of a tzinfo subclass, "
-                 "not type '%s'",
-                 Py_TYPE(p)->tp_name);
-    return -1;
-}
-
-/* If self has a tzinfo member, return a BORROWED reference to it.  Else
- * return NULL, which is NOT AN ERROR.  There are no error returns here,
- * and the caller must not decref the result.
- */
-static PyObject *
-get_tzinfo_member(PyObject *self)
-{
-    PyObject *tzinfo = NULL;
-
-    if (PyDateTime_Check(self) && HASTZINFO(self))
-        tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
-    else if (PyTime_Check(self) && HASTZINFO(self))
-        tzinfo = ((PyDateTime_Time *)self)->tzinfo;
-
-    return tzinfo;
-}
-
-/* Call getattr(tzinfo, name)(tzinfoarg), and check the result.  tzinfo must
- * be an instance of the tzinfo class.  If the method returns None, this
- * returns None.  If the method doesn't return None or timedelta, TypeError is
- * raised and this returns NULL.  If it returns a timedelta and the value is
- * out of range or isn't a whole number of minutes, ValueError is raised and
- * this returns NULL.  Else result is returned.
- */
-static PyObject *
-call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
-{
-    PyObject *offset;
-
-    assert(tzinfo != NULL);
-    assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
-    assert(tzinfoarg != NULL);
-
-    if (tzinfo == Py_None)
-        Py_RETURN_NONE;
-    offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
-    if (offset == Py_None || offset == NULL)
-        return offset;
-    if (PyDelta_Check(offset)) {
-        if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
-            Py_DECREF(offset);
-            PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                         " representing a whole number of minutes");
-            return NULL;
-        }
-        if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
-            GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
-            Py_DECREF(offset);
-            PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                         " strictly between -timedelta(hours=24) and"
-                         " timedelta(hours=24).");
-            return NULL;
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "tzinfo.%s() must return None or "
-                     "timedelta, not '%.200s'",
-                     name, Py_TYPE(offset)->tp_name);
-        Py_DECREF(offset);
-        return NULL;
-    }
-
-    return offset;
-}
-
-/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
- * result.  tzinfo must be an instance of the tzinfo class.  If utcoffset()
- * returns None, call_utcoffset returns 0 and sets *none to 1.  If uctoffset()
- * doesn't return None or timedelta, TypeError is raised and this returns -1.
- * If utcoffset() returns an invalid timedelta (out of range, or not a whole
- * # of minutes), ValueError is raised and this returns -1.  Else *none is
- * set to 0 and the offset is returned (as int # of minutes east of UTC).
- */
-static PyObject *
-call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
-}
-
-/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
- * result.  tzinfo must be an instance of the tzinfo class.  If dst()
- * returns None, call_dst returns 0 and sets *none to 1.  If dst()
- & doesn't return None or timedelta, TypeError is raised and this
- * returns -1.  If dst() returns an invalid timedelta for a UTC offset,
- * ValueError is raised and this returns -1.  Else *none is set to 0 and
- * the offset is returned (as an int # of minutes east of UTC).
- */
-static PyObject *
-call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
-}
-
-/* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be
- * an instance of the tzinfo class or None.  If tzinfo isn't None, and
- * tzname() doesn't return None or a string, TypeError is raised and this
- * returns NULL.  If the result is a string, we ensure it is a Unicode
- * string.
- */
-static PyObject *
-call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    PyObject *result;
-    _Py_IDENTIFIER(tzname);
-
-    assert(tzinfo != NULL);
-    assert(check_tzinfo_subclass(tzinfo) >= 0);
-    assert(tzinfoarg != NULL);
-
-    if (tzinfo == Py_None)
-        Py_RETURN_NONE;
-
-    result = _PyObject_CallMethodId(tzinfo, &PyId_tzname, "O", tzinfoarg);
-
-    if (result == NULL || result == Py_None)
-        return result;
-
-    if (!PyUnicode_Check(result)) {
-        PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
-                     "return None or a string, not '%s'",
-                     Py_TYPE(result)->tp_name);
-        Py_DECREF(result);
-        result = NULL;
-    }
-
-    return result;
-}
-
-/* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,
- * stuff
- *     ", tzinfo=" + repr(tzinfo)
- * before the closing ")".
- */
-static PyObject *
-append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
-{
-    PyObject *temp;
-
-    assert(PyUnicode_Check(repr));
-    assert(tzinfo);
-    if (tzinfo == Py_None)
-        return repr;
-    /* Get rid of the trailing ')'. */
-    assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
-    temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
-    Py_DECREF(repr);
-    if (temp == NULL)
-        return NULL;
-    repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
-    Py_DECREF(temp);
-    return repr;
-}
-
-/* ---------------------------------------------------------------------------
- * String format helpers.
- */
-
-static PyObject *
-format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
-{
-    static const char *DayNames[] = {
-        "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
-    };
-    static const char *MonthNames[] = {
-        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-    };
-
-    int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
-
-    return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
-                                DayNames[wday], MonthNames[GET_MONTH(date)-1],
-                                GET_DAY(date), hours, minutes, seconds,
-                                GET_YEAR(date));
-}
-
-static PyObject *delta_negative(PyDateTime_Delta *self);
-
-/* Add an hours & minutes UTC offset string to buf.  buf has no more than
- * buflen bytes remaining.  The UTC offset is gotten by calling
- * tzinfo.uctoffset(tzinfoarg).  If that returns None, \0 is stored into
- * *buf, and that's all.  Else the returned value is checked for sanity (an
- * integer in range), and if that's OK it's converted to an hours & minutes
- * string of the form
- *   sign HH sep MM
- * Returns 0 if everything is OK.  If the return value from utcoffset() is
- * bogus, an appropriate exception is set and -1 is returned.
- */
-static int
-format_utcoffset(char *buf, size_t buflen, const char *sep,
-                PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    PyObject *offset;
-    int hours, minutes, seconds;
-    char sign;
-
-    assert(buflen >= 1);
-
-    offset = call_utcoffset(tzinfo, tzinfoarg);
-    if (offset == NULL)
-        return -1;
-    if (offset == Py_None) {
-        Py_DECREF(offset);
-        *buf = '\0';
-        return 0;
-    }
-    /* Offset is normalized, so it is negative if days < 0 */
-    if (GET_TD_DAYS(offset) < 0) {
-        PyObject *temp = offset;
-        sign = '-';
-        offset = delta_negative((PyDateTime_Delta *)offset);
-        Py_DECREF(temp);
-        if (offset == NULL)
-            return -1;
-    }
-    else {
-        sign = '+';
-    }
-    /* Offset is not negative here. */
-    seconds = GET_TD_SECONDS(offset);
-    Py_DECREF(offset);
-    minutes = divmod(seconds, 60, &seconds);
-    hours = divmod(minutes, 60, &minutes);
-    assert(seconds == 0);
-    /* XXX ignore sub-minute data, curently not allowed. */
-    PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
-
-    return 0;
-}
-
-static PyObject *
-make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
-{
-    PyObject *temp;
-    PyObject *tzinfo = get_tzinfo_member(object);
-    PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
-    _Py_IDENTIFIER(replace);
-
-    if (Zreplacement == NULL)
-        return NULL;
-    if (tzinfo == Py_None || tzinfo == NULL)
-        return Zreplacement;
-
-    assert(tzinfoarg != NULL);
-    temp = call_tzname(tzinfo, tzinfoarg);
-    if (temp == NULL)
-        goto Error;
-    if (temp == Py_None) {
-        Py_DECREF(temp);
-        return Zreplacement;
-    }
-
-    assert(PyUnicode_Check(temp));
-    /* Since the tzname is getting stuffed into the
-     * format, we have to double any % signs so that
-     * strftime doesn't treat them as format codes.
-     */
-    Py_DECREF(Zreplacement);
-    Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
-    Py_DECREF(temp);
-    if (Zreplacement == NULL)
-        return NULL;
-    if (!PyUnicode_Check(Zreplacement)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "tzname.replace() did not return a string");
-        goto Error;
-    }
-    return Zreplacement;
-
-  Error:
-    Py_DECREF(Zreplacement);
-    return NULL;
-}
-
-static PyObject *
-make_freplacement(PyObject *object)
-{
-    char freplacement[64];
-    if (PyTime_Check(object))
-        sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
-    else if (PyDateTime_Check(object))
-        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
-    else
-        sprintf(freplacement, "%06d", 0);
-
-    return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
-}
-
-/* I sure don't want to reproduce the strftime code from the time module,
- * so this imports the module and calls it.  All the hair is due to
- * giving special meanings to the %z, %Z and %f format codes via a
- * preprocessing step on the format string.
- * tzinfoarg is the argument to pass to the object's tzinfo method, if
- * needed.
- */
-static PyObject *
-wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
-              PyObject *tzinfoarg)
-{
-    PyObject *result = NULL;            /* guilty until proved innocent */
-
-    PyObject *zreplacement = NULL;      /* py string, replacement for %z */
-    PyObject *Zreplacement = NULL;      /* py string, replacement for %Z */
-    PyObject *freplacement = NULL;      /* py string, replacement for %f */
-
-    const char *pin;            /* pointer to next char in input format */
-    Py_ssize_t flen;            /* length of input format */
-    char ch;                    /* next char in input format */
-
-    PyObject *newfmt = NULL;            /* py string, the output format */
-    char *pnew;         /* pointer to available byte in output format */
-    size_t totalnew;            /* number bytes total in output format buffer,
-                               exclusive of trailing \0 */
-    size_t usednew;     /* number bytes used so far in output format buffer */
-
-    const char *ptoappend;      /* ptr to string to append to output buffer */
-    Py_ssize_t ntoappend;       /* # of bytes to append to output buffer */
-
-    assert(object && format && timetuple);
-    assert(PyUnicode_Check(format));
-    /* Convert the input format to a C string and size */
-    pin = _PyUnicode_AsStringAndSize(format, &flen);
-    if (!pin)
-        return NULL;
-
-    /* Scan the input format, looking for %z/%Z/%f escapes, building
-     * a new format.  Since computing the replacements for those codes
-     * is expensive, don't unless they're actually used.
-     */
-    if (flen > INT_MAX - 1) {
-        PyErr_NoMemory();
-        goto Done;
-    }
-
-    totalnew = flen + 1;        /* realistic if no %z/%Z */
-    newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
-    if (newfmt == NULL) goto Done;
-    pnew = PyBytes_AsString(newfmt);
-    usednew = 0;
-
-    while ((ch = *pin++) != '\0') {
-        if (ch != '%') {
-            ptoappend = pin - 1;
-            ntoappend = 1;
-        }
-        else if ((ch = *pin++) == '\0') {
-            /* There's a lone trailing %; doesn't make sense. */
-            PyErr_SetString(PyExc_ValueError, "strftime format "
-                            "ends with raw %");
-            goto Done;
-        }
-        /* A % has been seen and ch is the character after it. */
-        else if (ch == 'z') {
-            if (zreplacement == NULL) {
-                /* format utcoffset */
-                char buf[100];
-                PyObject *tzinfo = get_tzinfo_member(object);
-                zreplacement = PyBytes_FromStringAndSize("", 0);
-                if (zreplacement == NULL) goto Done;
-                if (tzinfo != Py_None && tzinfo != NULL) {
-                    assert(tzinfoarg != NULL);
-                    if (format_utcoffset(buf,
-                                         sizeof(buf),
-                                         "",
-                                         tzinfo,
-                                         tzinfoarg) < 0)
-                        goto Done;
-                    Py_DECREF(zreplacement);
-                    zreplacement =
-                      PyBytes_FromStringAndSize(buf,
-                                               strlen(buf));
-                    if (zreplacement == NULL)
-                        goto Done;
-                }
-            }
-            assert(zreplacement != NULL);
-            ptoappend = PyBytes_AS_STRING(zreplacement);
-            ntoappend = PyBytes_GET_SIZE(zreplacement);
-        }
-        else if (ch == 'Z') {
-            /* format tzname */
-            if (Zreplacement == NULL) {
-                Zreplacement = make_Zreplacement(object,
-                                                 tzinfoarg);
-                if (Zreplacement == NULL)
-                    goto Done;
-            }
-            assert(Zreplacement != NULL);
-            assert(PyUnicode_Check(Zreplacement));
-            ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
-                                                  &ntoappend);
-            if (ptoappend == NULL)
-                goto Done;
-        }
-        else if (ch == 'f') {
-            /* format microseconds */
-            if (freplacement == NULL) {
-                freplacement = make_freplacement(object);
-                if (freplacement == NULL)
-                    goto Done;
-            }
-            assert(freplacement != NULL);
-            assert(PyBytes_Check(freplacement));
-            ptoappend = PyBytes_AS_STRING(freplacement);
-            ntoappend = PyBytes_GET_SIZE(freplacement);
-        }
-        else {
-            /* percent followed by neither z nor Z */
-            ptoappend = pin - 2;
-            ntoappend = 2;
-        }
-
-        /* Append the ntoappend chars starting at ptoappend to
-         * the new format.
-         */
-        if (ntoappend == 0)
-            continue;
-        assert(ptoappend != NULL);
-        assert(ntoappend > 0);
-        while (usednew + ntoappend > totalnew) {
-            if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
-                PyErr_NoMemory();
-                goto Done;
-            }
-            totalnew <<= 1;
-            if (_PyBytes_Resize(&newfmt, totalnew) < 0)
-                goto Done;
-            pnew = PyBytes_AsString(newfmt) + usednew;
-        }
-        memcpy(pnew, ptoappend, ntoappend);
-        pnew += ntoappend;
-        usednew += ntoappend;
-        assert(usednew <= totalnew);
-    }  /* end while() */
-
-    if (_PyBytes_Resize(&newfmt, usednew) < 0)
-        goto Done;
-    {
-        PyObject *format;
-        PyObject *time = PyImport_ImportModuleNoBlock("time");
-
-        if (time == NULL)
-            goto Done;
-        format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
-        if (format != NULL) {
-            result = _PyObject_CallMethodId(time, &PyId_strftime, "OO",
-                                            format, timetuple, NULL);
-            Py_DECREF(format);
-        }
-        Py_DECREF(time);
-    }
- Done:
-    Py_XDECREF(freplacement);
-    Py_XDECREF(zreplacement);
-    Py_XDECREF(Zreplacement);
-    Py_XDECREF(newfmt);
-    return result;
-}
-
-/* ---------------------------------------------------------------------------
- * Wrap functions from the time module.  These aren't directly available
- * from C.  Perhaps they should be.
- */
-
-/* Call time.time() and return its result (a Python float). */
-static PyObject *
-time_time(void)
-{
-    PyObject *result = NULL;
-    PyObject *time = PyImport_ImportModuleNoBlock("time");
-
-    if (time != NULL) {
-        _Py_IDENTIFIER(time);
-
-        result = _PyObject_CallMethodId(time, &PyId_time, "()");
-        Py_DECREF(time);
-    }
-    return result;
-}
-
-/* Build a time.struct_time.  The weekday and day number are automatically
- * computed from the y,m,d args.
- */
-static PyObject *
-build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
-{
-    PyObject *time;
-    PyObject *result = NULL;
-
-    time = PyImport_ImportModuleNoBlock("time");
-    if (time != NULL) {
-        _Py_IDENTIFIER(struct_time);
-
-        result = _PyObject_CallMethodId(time, &PyId_struct_time,
-                                        "((iiiiiiiii))",
-                                        y, m, d,
-                                        hh, mm, ss,
-                                        weekday(y, m, d),
-                                        days_before_month(y, m) + d,
-                                        dstflag);
-        Py_DECREF(time);
-    }
-    return result;
-}
-
-/* ---------------------------------------------------------------------------
- * Miscellaneous helpers.
- */
-
-/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
- * The comparisons here all most naturally compute a cmp()-like result.
- * This little helper turns that into a bool result for rich comparisons.
- */
-static PyObject *
-diff_to_bool(int diff, int op)
-{
-    PyObject *result;
-    int istrue;
-
-    switch (op) {
-        case Py_EQ: istrue = diff == 0; break;
-        case Py_NE: istrue = diff != 0; break;
-        case Py_LE: istrue = diff <= 0; break;
-        case Py_GE: istrue = diff >= 0; break;
-        case Py_LT: istrue = diff < 0; break;
-        case Py_GT: istrue = diff > 0; break;
-        default:
-            assert(! "op unknown");
-            istrue = 0; /* To shut up compiler */
-    }
-    result = istrue ? Py_True : Py_False;
-    Py_INCREF(result);
-    return result;
-}
-
-/* Raises a "can't compare" TypeError and returns NULL. */
-static PyObject *
-cmperror(PyObject *a, PyObject *b)
-{
-    PyErr_Format(PyExc_TypeError,
-                 "can't compare %s to %s",
-                 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
-    return NULL;
-}
-
-/* ---------------------------------------------------------------------------
- * Cached Python objects; these are set by the module init function.
- */
-
-/* Conversion factors. */
-static PyObject *one = NULL;      /* 1 */
-static PyObject *us_per_ms = NULL;      /* 1000 */
-static PyObject *us_per_second = NULL;  /* 1000000 */
-static PyObject *us_per_minute = NULL;  /* 1e6 * 60 as Python int */
-static PyObject *us_per_hour = NULL;    /* 1e6 * 3600 as Python int */
-static PyObject *us_per_day = NULL;     /* 1e6 * 3600 * 24 as Python int */
-static PyObject *us_per_week = NULL;    /* 1e6*3600*24*7 as Python int */
-static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
-
-/* ---------------------------------------------------------------------------
- * Class implementations.
- */
-
-/*
- * PyDateTime_Delta implementation.
- */
-
-/* Convert a timedelta to a number of us,
- *      (24*3600*self.days + self.seconds)*1000000 + self.microseconds
- * as a Python int.
- * Doing mixed-radix arithmetic by hand instead is excruciating in C,
- * due to ubiquitous overflow possibilities.
- */
-static PyObject *
-delta_to_microseconds(PyDateTime_Delta *self)
-{
-    PyObject *x1 = NULL;
-    PyObject *x2 = NULL;
-    PyObject *x3 = NULL;
-    PyObject *result = NULL;
-
-    x1 = PyLong_FromLong(GET_TD_DAYS(self));
-    if (x1 == NULL)
-        goto Done;
-    x2 = PyNumber_Multiply(x1, seconds_per_day);        /* days in seconds */
-    if (x2 == NULL)
-        goto Done;
-    Py_DECREF(x1);
-    x1 = NULL;
-
-    /* x2 has days in seconds */
-    x1 = PyLong_FromLong(GET_TD_SECONDS(self));         /* seconds */
-    if (x1 == NULL)
-        goto Done;
-    x3 = PyNumber_Add(x1, x2);          /* days and seconds in seconds */
-    if (x3 == NULL)
-        goto Done;
-    Py_DECREF(x1);
-    Py_DECREF(x2);
-    /* x1 = */ x2 = NULL;
-
-    /* x3 has days+seconds in seconds */
-    x1 = PyNumber_Multiply(x3, us_per_second);          /* us */
-    if (x1 == NULL)
-        goto Done;
-    Py_DECREF(x3);
-    x3 = NULL;
-
-    /* x1 has days+seconds in us */
-    x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
-    if (x2 == NULL)
-        goto Done;
-    result = PyNumber_Add(x1, x2);
-
-Done:
-    Py_XDECREF(x1);
-    Py_XDECREF(x2);
-    Py_XDECREF(x3);
-    return result;
-}
-
-/* Convert a number of us (as a Python int) to a timedelta.
- */
-static PyObject *
-microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
-{
-    int us;
-    int s;
-    int d;
-    long temp;
-
-    PyObject *tuple = NULL;
-    PyObject *num = NULL;
-    PyObject *result = NULL;
-
-    tuple = PyNumber_Divmod(pyus, us_per_second);
-    if (tuple == NULL)
-        goto Done;
-
-    num = PyTuple_GetItem(tuple, 1);            /* us */
-    if (num == NULL)
-        goto Done;
-    temp = PyLong_AsLong(num);
-    num = NULL;
-    if (temp == -1 && PyErr_Occurred())
-        goto Done;
-    assert(0 <= temp && temp < 1000000);
-    us = (int)temp;
-    if (us < 0) {
-        /* The divisor was positive, so this must be an error. */
-        assert(PyErr_Occurred());
-        goto Done;
-    }
-
-    num = PyTuple_GetItem(tuple, 0);            /* leftover seconds */
-    if (num == NULL)
-        goto Done;
-    Py_INCREF(num);
-    Py_DECREF(tuple);
-
-    tuple = PyNumber_Divmod(num, seconds_per_day);
-    if (tuple == NULL)
-        goto Done;
-    Py_DECREF(num);
-
-    num = PyTuple_GetItem(tuple, 1);            /* seconds */
-    if (num == NULL)
-        goto Done;
-    temp = PyLong_AsLong(num);
-    num = NULL;
-    if (temp == -1 && PyErr_Occurred())
-        goto Done;
-    assert(0 <= temp && temp < 24*3600);
-    s = (int)temp;
-
-    if (s < 0) {
-        /* The divisor was positive, so this must be an error. */
-        assert(PyErr_Occurred());
-        goto Done;
-    }
-
-    num = PyTuple_GetItem(tuple, 0);            /* leftover days */
-    if (num == NULL)
-        goto Done;
-    Py_INCREF(num);
-    temp = PyLong_AsLong(num);
-    if (temp == -1 && PyErr_Occurred())
-        goto Done;
-    d = (int)temp;
-    if ((long)d != temp) {
-        PyErr_SetString(PyExc_OverflowError, "normalized days too "
-                        "large to fit in a C int");
-        goto Done;
-    }
-    result = new_delta_ex(d, s, us, 0, type);
-
-Done:
-    Py_XDECREF(tuple);
-    Py_XDECREF(num);
-    return result;
-}
-
-#define microseconds_to_delta(pymicros) \
-    microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
-
-static PyObject *
-multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
-{
-    PyObject *pyus_in;
-    PyObject *pyus_out;
-    PyObject *result;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-
-    pyus_out = PyNumber_Multiply(pyus_in, intobj);
-    Py_DECREF(pyus_in);
-    if (pyus_out == NULL)
-        return NULL;
-
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
-    return result;
-}
-
-static PyObject *
-multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
-{
-    PyObject *result = NULL;
-    PyObject *pyus_in = NULL, *temp, *pyus_out;
-    PyObject *ratio = NULL;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-    ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
-    if (ratio == NULL)
-        goto error;
-    temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
-    Py_DECREF(pyus_in);
-    pyus_in = NULL;
-    if (temp == NULL)
-        goto error;
-    pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
-    Py_DECREF(temp);
-    if (pyus_out == NULL)
-        goto error;
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
- error:
-    Py_XDECREF(pyus_in);
-    Py_XDECREF(ratio);
-
-    return result;
-}
-
-static PyObject *
-divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
-{
-    PyObject *pyus_in;
-    PyObject *pyus_out;
-    PyObject *result;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-
-    pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
-    Py_DECREF(pyus_in);
-    if (pyus_out == NULL)
-        return NULL;
-
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
-    return result;
-}
-
-static PyObject *
-divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *result;
-
-    pyus_left = delta_to_microseconds(left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds(right);
-    if (pyus_right == NULL)     {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    result = PyNumber_FloorDivide(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    return result;
-}
-
-static PyObject *
-truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *result;
-
-    pyus_left = delta_to_microseconds(left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds(right);
-    if (pyus_right == NULL)     {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    result = PyNumber_TrueDivide(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    return result;
-}
-
-static PyObject *
-truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
-{
-    PyObject *result = NULL;
-    PyObject *pyus_in = NULL, *temp, *pyus_out;
-    PyObject *ratio = NULL;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-    ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
-    if (ratio == NULL)
-        goto error;
-    temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
-    Py_DECREF(pyus_in);
-    pyus_in = NULL;
-    if (temp == NULL)
-        goto error;
-    pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
-    Py_DECREF(temp);
-    if (pyus_out == NULL)
-        goto error;
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
- error:
-    Py_XDECREF(pyus_in);
-    Py_XDECREF(ratio);
-
-    return result;
-}
-
-static PyObject *
-truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
-{
-    PyObject *result;
-    PyObject *pyus_in, *pyus_out;
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-    pyus_out = divide_nearest(pyus_in, i);
-    Py_DECREF(pyus_in);
-    if (pyus_out == NULL)
-        return NULL;
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
-
-    return result;
-}
-
-static PyObject *
-delta_add(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left) && PyDelta_Check(right)) {
-        /* delta + delta */
-        /* The C-level additions can't overflow because of the
-         * invariant bounds.
-         */
-        int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
-        int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
-        int microseconds = GET_TD_MICROSECONDS(left) +
-                           GET_TD_MICROSECONDS(right);
-        result = new_delta(days, seconds, microseconds, 1);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_negative(PyDateTime_Delta *self)
-{
-    return new_delta(-GET_TD_DAYS(self),
-                     -GET_TD_SECONDS(self),
-                     -GET_TD_MICROSECONDS(self),
-                     1);
-}
-
-static PyObject *
-delta_positive(PyDateTime_Delta *self)
-{
-    /* Could optimize this (by returning self) if this isn't a
-     * subclass -- but who uses unary + ?  Approximately nobody.
-     */
-    return new_delta(GET_TD_DAYS(self),
-                     GET_TD_SECONDS(self),
-                     GET_TD_MICROSECONDS(self),
-                     0);
-}
-
-static PyObject *
-delta_abs(PyDateTime_Delta *self)
-{
-    PyObject *result;
-
-    assert(GET_TD_MICROSECONDS(self) >= 0);
-    assert(GET_TD_SECONDS(self) >= 0);
-
-    if (GET_TD_DAYS(self) < 0)
-        result = delta_negative(self);
-    else
-        result = delta_positive(self);
-
-    return result;
-}
-
-static PyObject *
-delta_subtract(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left) && PyDelta_Check(right)) {
-        /* delta - delta */
-        /* The C-level additions can't overflow because of the
-         * invariant bounds.
-         */
-        int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
-        int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
-        int microseconds = GET_TD_MICROSECONDS(left) -
-                           GET_TD_MICROSECONDS(right);
-        result = new_delta(days, seconds, microseconds, 1);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static int
-delta_cmp(PyObject *self, PyObject *other)
-{
-    int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
-    if (diff == 0) {
-        diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
-        if (diff == 0)
-            diff = GET_TD_MICROSECONDS(self) -
-                GET_TD_MICROSECONDS(other);
-    }
-    return diff;
-}
-
-static PyObject *
-delta_richcompare(PyObject *self, PyObject *other, int op)
-{
-    if (PyDelta_Check(other)) {
-        int diff = delta_cmp(self, other);
-        return diff_to_bool(diff, op);
-    }
-    else {
-        Py_RETURN_NOTIMPLEMENTED;
-    }
-}
-
-static PyObject *delta_getstate(PyDateTime_Delta *self);
-
-static Py_hash_t
-delta_hash(PyDateTime_Delta *self)
-{
-    if (self->hashcode == -1) {
-        PyObject *temp = delta_getstate(self);
-        if (temp != NULL) {
-            self->hashcode = PyObject_Hash(temp);
-            Py_DECREF(temp);
-        }
-    }
-    return self->hashcode;
-}
-
-static PyObject *
-delta_multiply(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left)) {
-        /* delta * ??? */
-        if (PyLong_Check(right))
-            result = multiply_int_timedelta(right,
-                            (PyDateTime_Delta *) left);
-        else if (PyFloat_Check(right))
-            result = multiply_float_timedelta(right,
-                            (PyDateTime_Delta *) left);
-    }
-    else if (PyLong_Check(left))
-        result = multiply_int_timedelta(left,
-                        (PyDateTime_Delta *) right);
-    else if (PyFloat_Check(left))
-        result = multiply_float_timedelta(left,
-                        (PyDateTime_Delta *) right);
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_divide(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left)) {
-        /* delta * ??? */
-        if (PyLong_Check(right))
-            result = divide_timedelta_int(
-                            (PyDateTime_Delta *)left,
-                            right);
-        else if (PyDelta_Check(right))
-            result = divide_timedelta_timedelta(
-                            (PyDateTime_Delta *)left,
-                            (PyDateTime_Delta *)right);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_truedivide(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left)) {
-        if (PyDelta_Check(right))
-            result = truedivide_timedelta_timedelta(
-                            (PyDateTime_Delta *)left,
-                            (PyDateTime_Delta *)right);
-        else if (PyFloat_Check(right))
-            result = truedivide_timedelta_float(
-                            (PyDateTime_Delta *)left, right);
-        else if (PyLong_Check(right))
-            result = truedivide_timedelta_int(
-                            (PyDateTime_Delta *)left, right);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_remainder(PyObject *left, PyObject *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *pyus_remainder;
-    PyObject *remainder;
-
-    if (!PyDelta_Check(left) || !PyDelta_Check(right))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
-    if (pyus_right == NULL) {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    if (pyus_remainder == NULL)
-        return NULL;
-
-    remainder = microseconds_to_delta(pyus_remainder);
-    Py_DECREF(pyus_remainder);
-    if (remainder == NULL)
-        return NULL;
-
-    return remainder;
-}
-
-static PyObject *
-delta_divmod(PyObject *left, PyObject *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *divmod;
-    PyObject *delta;
-    PyObject *result;
-
-    if (!PyDelta_Check(left) || !PyDelta_Check(right))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
-    if (pyus_right == NULL) {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    divmod = PyNumber_Divmod(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    if (divmod == NULL)
-        return NULL;
-
-    assert(PyTuple_Size(divmod) == 2);
-    delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
-    if (delta == NULL) {
-        Py_DECREF(divmod);
-        return NULL;
-    }
-    result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
-    Py_DECREF(delta);
-    Py_DECREF(divmod);
-    return result;
-}
-
-/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
- * timedelta constructor.  sofar is the # of microseconds accounted for
- * so far, and there are factor microseconds per current unit, the number
- * of which is given by num.  num * factor is added to sofar in a
- * numerically careful way, and that's the result.  Any fractional
- * microseconds left over (this can happen if num is a float type) are
- * added into *leftover.
- * Note that there are many ways this can give an error (NULL) return.
- */
-static PyObject *
-accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
-      double *leftover)
-{
-    PyObject *prod;
-    PyObject *sum;
-
-    assert(num != NULL);
-
-    if (PyLong_Check(num)) {
-        prod = PyNumber_Multiply(num, factor);
-        if (prod == NULL)
-            return NULL;
-        sum = PyNumber_Add(sofar, prod);
-        Py_DECREF(prod);
-        return sum;
-    }
-
-    if (PyFloat_Check(num)) {
-        double dnum;
-        double fracpart;
-        double intpart;
-        PyObject *x;
-        PyObject *y;
-
-        /* The Plan:  decompose num into an integer part and a
-         * fractional part, num = intpart + fracpart.
-         * Then num * factor ==
-         *      intpart * factor + fracpart * factor
-         * and the LHS can be computed exactly in long arithmetic.
-         * The RHS is again broken into an int part and frac part.
-         * and the frac part is added into *leftover.
-         */
-        dnum = PyFloat_AsDouble(num);
-        if (dnum == -1.0 && PyErr_Occurred())
-            return NULL;
-        fracpart = modf(dnum, &intpart);
-        x = PyLong_FromDouble(intpart);
-        if (x == NULL)
-            return NULL;
-
-        prod = PyNumber_Multiply(x, factor);
-        Py_DECREF(x);
-        if (prod == NULL)
-            return NULL;
-
-        sum = PyNumber_Add(sofar, prod);
-        Py_DECREF(prod);
-        if (sum == NULL)
-            return NULL;
-
-        if (fracpart == 0.0)
-            return sum;
-        /* So far we've lost no information.  Dealing with the
-         * fractional part requires float arithmetic, and may
-         * lose a little info.
-         */
-        assert(PyLong_Check(factor));
-        dnum = PyLong_AsDouble(factor);
-
-        dnum *= fracpart;
-        fracpart = modf(dnum, &intpart);
-        x = PyLong_FromDouble(intpart);
-        if (x == NULL) {
-            Py_DECREF(sum);
-            return NULL;
-        }
-
-        y = PyNumber_Add(sum, x);
-        Py_DECREF(sum);
-        Py_DECREF(x);
-        *leftover += fracpart;
-        return y;
-    }
-
-    PyErr_Format(PyExc_TypeError,
-                 "unsupported type for timedelta %s component: %s",
-                 tag, Py_TYPE(num)->tp_name);
-    return NULL;
-}
-
-static PyObject *
-delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-
-    /* Argument objects. */
-    PyObject *day = NULL;
-    PyObject *second = NULL;
-    PyObject *us = NULL;
-    PyObject *ms = NULL;
-    PyObject *minute = NULL;
-    PyObject *hour = NULL;
-    PyObject *week = NULL;
-
-    PyObject *x = NULL;         /* running sum of microseconds */
-    PyObject *y = NULL;         /* temp sum of microseconds */
-    double leftover_us = 0.0;
-
-    static char *keywords[] = {
-        "days", "seconds", "microseconds", "milliseconds",
-        "minutes", "hours", "weeks", NULL
-    };
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
-                                    keywords,
-                                    &day, &second, &us,
-                                    &ms, &minute, &hour, &week) == 0)
-        goto Done;
-
-    x = PyLong_FromLong(0);
-    if (x == NULL)
-        goto Done;
-
-#define CLEANUP         \
-    Py_DECREF(x);       \
-    x = y;              \
-    if (x == NULL)      \
-        goto Done
-
-    if (us) {
-        y = accum("microseconds", x, us, one, &leftover_us);
-        CLEANUP;
-    }
-    if (ms) {
-        y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
-        CLEANUP;
-    }
-    if (second) {
-        y = accum("seconds", x, second, us_per_second, &leftover_us);
-        CLEANUP;
-    }
-    if (minute) {
-        y = accum("minutes", x, minute, us_per_minute, &leftover_us);
-        CLEANUP;
-    }
-    if (hour) {
-        y = accum("hours", x, hour, us_per_hour, &leftover_us);
-        CLEANUP;
-    }
-    if (day) {
-        y = accum("days", x, day, us_per_day, &leftover_us);
-        CLEANUP;
-    }
-    if (week) {
-        y = accum("weeks", x, week, us_per_week, &leftover_us);
-        CLEANUP;
-    }
-    if (leftover_us) {
-        /* Round to nearest whole # of us, and add into x. */
-        double whole_us = round(leftover_us);
-        int x_is_odd;
-        PyObject *temp;
-
-        whole_us = round(leftover_us);
-        if (fabs(whole_us - leftover_us) == 0.5) {
-            /* We're exactly halfway between two integers.  In order
-             * to do round-half-to-even, we must determine whether x
-             * is odd. Note that x is odd when it's last bit is 1. The
-             * code below uses bitwise and operation to check the last
-             * bit. */
-            temp = PyNumber_And(x, one);  /* temp <- x & 1 */
-            if (temp == NULL) {
-                Py_DECREF(x);
-                goto Done;
-            }
-            x_is_odd = PyObject_IsTrue(temp);
-            Py_DECREF(temp);
-            if (x_is_odd == -1) {
-                Py_DECREF(x);
-                goto Done;
-            }
-            whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
-        }
-
-        temp = PyLong_FromLong((long)whole_us);
-
-        if (temp == NULL) {
-            Py_DECREF(x);
-            goto Done;
-        }
-        y = PyNumber_Add(x, temp);
-        Py_DECREF(temp);
-        CLEANUP;
-    }
-
-    self = microseconds_to_delta_ex(x, type);
-    Py_DECREF(x);
-Done:
-    return self;
-
-#undef CLEANUP
-}
-
-static int
-delta_bool(PyDateTime_Delta *self)
-{
-    return (GET_TD_DAYS(self) != 0
-        || GET_TD_SECONDS(self) != 0
-        || GET_TD_MICROSECONDS(self) != 0);
-}
-
-static PyObject *
-delta_repr(PyDateTime_Delta *self)
-{
-    if (GET_TD_MICROSECONDS(self) != 0)
-        return PyUnicode_FromFormat("%s(%d, %d, %d)",
-                                    Py_TYPE(self)->tp_name,
-                                    GET_TD_DAYS(self),
-                                    GET_TD_SECONDS(self),
-                                    GET_TD_MICROSECONDS(self));
-    if (GET_TD_SECONDS(self) != 0)
-        return PyUnicode_FromFormat("%s(%d, %d)",
-                                    Py_TYPE(self)->tp_name,
-                                    GET_TD_DAYS(self),
-                                    GET_TD_SECONDS(self));
-
-    return PyUnicode_FromFormat("%s(%d)",
-                                Py_TYPE(self)->tp_name,
-                                GET_TD_DAYS(self));
-}
-
-static PyObject *
-delta_str(PyDateTime_Delta *self)
-{
-    int us = GET_TD_MICROSECONDS(self);
-    int seconds = GET_TD_SECONDS(self);
-    int minutes = divmod(seconds, 60, &seconds);
-    int hours = divmod(minutes, 60, &minutes);
-    int days = GET_TD_DAYS(self);
-
-    if (days) {
-        if (us)
-            return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
-                                        days, (days == 1 || days == -1) ? "" : "s",
-                                        hours, minutes, seconds, us);
-        else
-            return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
-                                        days, (days == 1 || days == -1) ? "" : "s",
-                                        hours, minutes, seconds);
-    } else {
-        if (us)
-            return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
-                                        hours, minutes, seconds, us);
-        else
-            return PyUnicode_FromFormat("%d:%02d:%02d",
-                                        hours, minutes, seconds);
-    }
-
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* __getstate__ isn't exposed */
-static PyObject *
-delta_getstate(PyDateTime_Delta *self)
-{
-    return Py_BuildValue("iii", GET_TD_DAYS(self),
-                                GET_TD_SECONDS(self),
-                                GET_TD_MICROSECONDS(self));
-}
-
-static PyObject *
-delta_total_seconds(PyObject *self)
-{
-    PyObject *total_seconds;
-    PyObject *total_microseconds;
-
-    total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
-    if (total_microseconds == NULL)
-        return NULL;
-
-    total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
-
-    Py_DECREF(total_microseconds);
-    return total_seconds;
-}
-
-static PyObject *
-delta_reduce(PyDateTime_Delta* self)
-{
-    return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
-}
-
-#define OFFSET(field)  offsetof(PyDateTime_Delta, field)
-
-static PyMemberDef delta_members[] = {
-
-    {"days",         T_INT, OFFSET(days),         READONLY,
-     PyDoc_STR("Number of days.")},
-
-    {"seconds",      T_INT, OFFSET(seconds),      READONLY,
-     PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
-
-    {"microseconds", T_INT, OFFSET(microseconds), READONLY,
-     PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
-    {NULL}
-};
-
-static PyMethodDef delta_methods[] = {
-    {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
-     PyDoc_STR("Total seconds in the duration.")},
-
-    {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL},
-};
-
-static char delta_doc[] =
-PyDoc_STR("Difference between two datetime values.");
-
-static PyNumberMethods delta_as_number = {
-    delta_add,                                  /* nb_add */
-    delta_subtract,                             /* nb_subtract */
-    delta_multiply,                             /* nb_multiply */
-    delta_remainder,                            /* nb_remainder */
-    delta_divmod,                               /* nb_divmod */
-    0,                                          /* nb_power */
-    (unaryfunc)delta_negative,                  /* nb_negative */
-    (unaryfunc)delta_positive,                  /* nb_positive */
-    (unaryfunc)delta_abs,                       /* nb_absolute */
-    (inquiry)delta_bool,                        /* nb_bool */
-    0,                                          /*nb_invert*/
-    0,                                          /*nb_lshift*/
-    0,                                          /*nb_rshift*/
-    0,                                          /*nb_and*/
-    0,                                          /*nb_xor*/
-    0,                                          /*nb_or*/
-    0,                                          /*nb_int*/
-    0,                                          /*nb_reserved*/
-    0,                                          /*nb_float*/
-    0,                                          /*nb_inplace_add*/
-    0,                                          /*nb_inplace_subtract*/
-    0,                                          /*nb_inplace_multiply*/
-    0,                                          /*nb_inplace_remainder*/
-    0,                                          /*nb_inplace_power*/
-    0,                                          /*nb_inplace_lshift*/
-    0,                                          /*nb_inplace_rshift*/
-    0,                                          /*nb_inplace_and*/
-    0,                                          /*nb_inplace_xor*/
-    0,                                          /*nb_inplace_or*/
-    delta_divide,                               /* nb_floor_divide */
-    delta_truedivide,                           /* nb_true_divide */
-    0,                                          /* nb_inplace_floor_divide */
-    0,                                          /* nb_inplace_true_divide */
-};
-
-static PyTypeObject PyDateTime_DeltaType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.timedelta",                               /* tp_name */
-    sizeof(PyDateTime_Delta),                           /* tp_basicsize */
-    0,                                                  /* tp_itemsize */
-    0,                                                  /* tp_dealloc */
-    0,                                                  /* tp_print */
-    0,                                                  /* tp_getattr */
-    0,                                                  /* tp_setattr */
-    0,                                                  /* tp_reserved */
-    (reprfunc)delta_repr,                               /* tp_repr */
-    &delta_as_number,                                   /* tp_as_number */
-    0,                                                  /* tp_as_sequence */
-    0,                                                  /* tp_as_mapping */
-    (hashfunc)delta_hash,                               /* tp_hash */
-    0,                                                  /* tp_call */
-    (reprfunc)delta_str,                                /* tp_str */
-    PyObject_GenericGetAttr,                            /* tp_getattro */
-    0,                                                  /* tp_setattro */
-    0,                                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,           /* tp_flags */
-    delta_doc,                                          /* tp_doc */
-    0,                                                  /* tp_traverse */
-    0,                                                  /* tp_clear */
-    delta_richcompare,                                  /* tp_richcompare */
-    0,                                                  /* tp_weaklistoffset */
-    0,                                                  /* tp_iter */
-    0,                                                  /* tp_iternext */
-    delta_methods,                                      /* tp_methods */
-    delta_members,                                      /* tp_members */
-    0,                                                  /* tp_getset */
-    0,                                                  /* tp_base */
-    0,                                                  /* tp_dict */
-    0,                                                  /* tp_descr_get */
-    0,                                                  /* tp_descr_set */
-    0,                                                  /* tp_dictoffset */
-    0,                                                  /* tp_init */
-    0,                                                  /* tp_alloc */
-    delta_new,                                          /* tp_new */
-    0,                                                  /* tp_free */
-};
-
-/*
- * PyDateTime_Date implementation.
- */
-
-/* Accessor properties. */
-
-static PyObject *
-date_year(PyDateTime_Date *self, void *unused)
-{
-    return PyLong_FromLong(GET_YEAR(self));
-}
-
-static PyObject *
-date_month(PyDateTime_Date *self, void *unused)
-{
-    return PyLong_FromLong(GET_MONTH(self));
-}
-
-static PyObject *
-date_day(PyDateTime_Date *self, void *unused)
-{
-    return PyLong_FromLong(GET_DAY(self));
-}
-
-static PyGetSetDef date_getset[] = {
-    {"year",        (getter)date_year},
-    {"month",       (getter)date_month},
-    {"day",         (getter)date_day},
-    {NULL}
-};
-
-/* Constructors. */
-
-static char *date_kws[] = {"year", "month", "day", NULL};
-
-static PyObject *
-date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-    PyObject *state;
-    int year;
-    int month;
-    int day;
-
-    /* Check for invocation from pickle with __getstate__ state */
-    if (PyTuple_GET_SIZE(args) == 1 &&
-        PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-        PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
-        MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
-    {
-        PyDateTime_Date *me;
-
-        me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
-        if (me != NULL) {
-            char *pdata = PyBytes_AS_STRING(state);
-            memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
-            me->hashcode = -1;
-        }
-        return (PyObject *)me;
-    }
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
-                                    &year, &month, &day)) {
-        if (check_date_args(year, month, day) < 0)
-            return NULL;
-        self = new_date_ex(year, month, day, type);
-    }
-    return self;
-}
-
-/* Return new date from localtime(t). */
-static PyObject *
-date_local_from_object(PyObject *cls, PyObject *obj)
-{
-    struct tm *tm;
-    time_t t;
-
-    if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
-        return NULL;
-
-    tm = localtime(&t);
-    if (tm == NULL) {
-        /* unconvertible time */
-#ifdef EINVAL
-        if (errno == 0)
-            errno = EINVAL;
-#endif
-        PyErr_SetFromErrno(PyExc_OSError);
-        return NULL;
-    }
-
-    return PyObject_CallFunction(cls, "iii",
-                                 tm->tm_year + 1900,
-                                 tm->tm_mon + 1,
-                                 tm->tm_mday);
-}
-
-/* Return new date from current time.
- * We say this is equivalent to fromtimestamp(time.time()), and the
- * only way to be sure of that is to *call* time.time().  That's not
- * generally the same as calling C's time.
- */
-static PyObject *
-date_today(PyObject *cls, PyObject *dummy)
-{
-    PyObject *time;
-    PyObject *result;
-    _Py_IDENTIFIER(fromtimestamp);
-
-    time = time_time();
-    if (time == NULL)
-        return NULL;
-
-    /* Note well:  today() is a class method, so this may not call
-     * date.fromtimestamp.  For example, it may call
-     * datetime.fromtimestamp.  That's why we need all the accuracy
-     * time.time() delivers; if someone were gonzo about optimization,
-     * date.today() could get away with plain C time().
-     */
-    result = _PyObject_CallMethodId(cls, &PyId_fromtimestamp, "O", time);
-    Py_DECREF(time);
-    return result;
-}
-
-/* Return new date from given timestamp (Python timestamp -- a double). */
-static PyObject *
-date_fromtimestamp(PyObject *cls, PyObject *args)
-{
-    PyObject *timestamp;
-    PyObject *result = NULL;
-
-    if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
-        result = date_local_from_object(cls, timestamp);
-    return result;
-}
-
-/* Return new date from proleptic Gregorian ordinal.  Raises ValueError if
- * the ordinal is out of range.
- */
-static PyObject *
-date_fromordinal(PyObject *cls, PyObject *args)
-{
-    PyObject *result = NULL;
-    int ordinal;
-
-    if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
-        int year;
-        int month;
-        int day;
-
-        if (ordinal < 1)
-            PyErr_SetString(PyExc_ValueError, "ordinal must be "
-                                              ">= 1");
-        else {
-            ord_to_ymd(ordinal, &year, &month, &day);
-            result = PyObject_CallFunction(cls, "iii",
-                                           year, month, day);
-        }
-    }
-    return result;
-}
-
-/*
- * Date arithmetic.
- */
-
-/* date + timedelta -> date.  If arg negate is true, subtract the timedelta
- * instead.
- */
-static PyObject *
-add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
-{
-    PyObject *result = NULL;
-    int year = GET_YEAR(date);
-    int month = GET_MONTH(date);
-    int deltadays = GET_TD_DAYS(delta);
-    /* C-level overflow is impossible because |deltadays| < 1e9. */
-    int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
-
-    if (normalize_date(&year, &month, &day) >= 0)
-        result = new_date(year, month, day);
-    return result;
-}
-
-static PyObject *
-date_add(PyObject *left, PyObject *right)
-{
-    if (PyDateTime_Check(left) || PyDateTime_Check(right))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    if (PyDate_Check(left)) {
-        /* date + ??? */
-        if (PyDelta_Check(right))
-            /* date + delta */
-            return add_date_timedelta((PyDateTime_Date *) left,
-                                      (PyDateTime_Delta *) right,
-                                      0);
-    }
-    else {
-        /* ??? + date
-         * 'right' must be one of us, or we wouldn't have been called
-         */
-        if (PyDelta_Check(left))
-            /* delta + date */
-            return add_date_timedelta((PyDateTime_Date *) right,
-                                      (PyDateTime_Delta *) left,
-                                      0);
-    }
-    Py_RETURN_NOTIMPLEMENTED;
-}
-
-static PyObject *
-date_subtract(PyObject *left, PyObject *right)
-{
-    if (PyDateTime_Check(left) || PyDateTime_Check(right))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    if (PyDate_Check(left)) {
-        if (PyDate_Check(right)) {
-            /* date - date */
-            int left_ord = ymd_to_ord(GET_YEAR(left),
-                                      GET_MONTH(left),
-                                      GET_DAY(left));
-            int right_ord = ymd_to_ord(GET_YEAR(right),
-                                       GET_MONTH(right),
-                                       GET_DAY(right));
-            return new_delta(left_ord - right_ord, 0, 0, 0);
-        }
-        if (PyDelta_Check(right)) {
-            /* date - delta */
-            return add_date_timedelta((PyDateTime_Date *) left,
-                                      (PyDateTime_Delta *) right,
-                                      1);
-        }
-    }
-    Py_RETURN_NOTIMPLEMENTED;
-}
-
-
-/* Various ways to turn a date into a string. */
-
-static PyObject *
-date_repr(PyDateTime_Date *self)
-{
-    return PyUnicode_FromFormat("%s(%d, %d, %d)",
-                                Py_TYPE(self)->tp_name,
-                                GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-}
-
-static PyObject *
-date_isoformat(PyDateTime_Date *self)
-{
-    return PyUnicode_FromFormat("%04d-%02d-%02d",
-                                GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-}
-
-/* str() calls the appropriate isoformat() method. */
-static PyObject *
-date_str(PyDateTime_Date *self)
-{
-    return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
-}
-
-
-static PyObject *
-date_ctime(PyDateTime_Date *self)
-{
-    return format_ctime(self, 0, 0, 0);
-}
-
-static PyObject *
-date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
-{
-    /* This method can be inherited, and needs to call the
-     * timetuple() method appropriate to self's class.
-     */
-    PyObject *result;
-    PyObject *tuple;
-    PyObject *format;
-    _Py_IDENTIFIER(timetuple);
-    static char *keywords[] = {"format", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
-                                      &format))
-        return NULL;
-
-    tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, "()");
-    if (tuple == NULL)
-        return NULL;
-    result = wrap_strftime((PyObject *)self, format, tuple,
-                           (PyObject *)self);
-    Py_DECREF(tuple);
-    return result;
-}
-
-static PyObject *
-date_format(PyDateTime_Date *self, PyObject *args)
-{
-    PyObject *format;
-
-    if (!PyArg_ParseTuple(args, "U:__format__", &format))
-        return NULL;
-
-    /* if the format is zero length, return str(self) */
-    if (PyUnicode_GetLength(format) == 0)
-        return PyObject_Str((PyObject *)self);
-
-    return _PyObject_CallMethodId((PyObject *)self, &PyId_strftime, "O", format);
-}
-
-/* ISO methods. */
-
-static PyObject *
-date_isoweekday(PyDateTime_Date *self)
-{
-    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-
-    return PyLong_FromLong(dow + 1);
-}
-
-static PyObject *
-date_isocalendar(PyDateTime_Date *self)
-{
-    int  year         = GET_YEAR(self);
-    int  week1_monday = iso_week1_monday(year);
-    int today         = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
-    int  week;
-    int  day;
-
-    week = divmod(today - week1_monday, 7, &day);
-    if (week < 0) {
-        --year;
-        week1_monday = iso_week1_monday(year);
-        week = divmod(today - week1_monday, 7, &day);
-    }
-    else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
-        ++year;
-        week = 0;
-    }
-    return Py_BuildValue("iii", year, week + 1, day + 1);
-}
-
-/* Miscellaneous methods. */
-
-static PyObject *
-date_richcompare(PyObject *self, PyObject *other, int op)
-{
-    if (PyDate_Check(other)) {
-        int diff = memcmp(((PyDateTime_Date *)self)->data,
-                          ((PyDateTime_Date *)other)->data,
-                          _PyDateTime_DATE_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-    else
-        Py_RETURN_NOTIMPLEMENTED;
-}
-
-static PyObject *
-date_timetuple(PyDateTime_Date *self)
-{
-    return build_struct_time(GET_YEAR(self),
-                             GET_MONTH(self),
-                             GET_DAY(self),
-                             0, 0, 0, -1);
-}
-
-static PyObject *
-date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
-{
-    PyObject *clone;
-    PyObject *tuple;
-    int year = GET_YEAR(self);
-    int month = GET_MONTH(self);
-    int day = GET_DAY(self);
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
-                                      &year, &month, &day))
-        return NULL;
-    tuple = Py_BuildValue("iii", year, month, day);
-    if (tuple == NULL)
-        return NULL;
-    clone = date_new(Py_TYPE(self), tuple, NULL);
-    Py_DECREF(tuple);
-    return clone;
-}
-
-static Py_hash_t
-generic_hash(unsigned char *data, int len)
-{
-    return _Py_HashBytes(data, len);
-}
-
-
-static PyObject *date_getstate(PyDateTime_Date *self);
-
-static Py_hash_t
-date_hash(PyDateTime_Date *self)
-{
-    if (self->hashcode == -1)
-        self->hashcode = generic_hash(
-            (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
-
-    return self->hashcode;
-}
-
-static PyObject *
-date_toordinal(PyDateTime_Date *self)
-{
-    return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
-                                     GET_DAY(self)));
-}
-
-static PyObject *
-date_weekday(PyDateTime_Date *self)
-{
-    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-
-    return PyLong_FromLong(dow);
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* __getstate__ isn't exposed */
-static PyObject *
-date_getstate(PyDateTime_Date *self)
-{
-    PyObject* field;
-    field = PyBytes_FromStringAndSize((char*)self->data,
-                                       _PyDateTime_DATE_DATASIZE);
-    return Py_BuildValue("(N)", field);
-}
-
-static PyObject *
-date_reduce(PyDateTime_Date *self, PyObject *arg)
-{
-    return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
-}
-
-static PyMethodDef date_methods[] = {
-
-    /* Class methods: */
-
-    {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
-                                                       METH_CLASS,
-     PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
-               "time.time()).")},
-
-    {"fromordinal", (PyCFunction)date_fromordinal,      METH_VARARGS |
-                                                    METH_CLASS,
-     PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
-               "ordinal.")},
-
-    {"today",         (PyCFunction)date_today,   METH_NOARGS | METH_CLASS,
-     PyDoc_STR("Current date or datetime:  same as "
-               "self.__class__.fromtimestamp(time.time()).")},
-
-    /* Instance methods: */
-
-    {"ctime",       (PyCFunction)date_ctime,        METH_NOARGS,
-     PyDoc_STR("Return ctime() style string.")},
-
-    {"strftime",        (PyCFunction)date_strftime,     METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("format -> strftime() style string.")},
-
-    {"__format__",      (PyCFunction)date_format,       METH_VARARGS,
-     PyDoc_STR("Formats self with strftime.")},
-
-    {"timetuple",   (PyCFunction)date_timetuple,    METH_NOARGS,
-     PyDoc_STR("Return time tuple, compatible with time.localtime().")},
-
-    {"isocalendar", (PyCFunction)date_isocalendar,  METH_NOARGS,
-     PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
-               "weekday.")},
-
-    {"isoformat",   (PyCFunction)date_isoformat,        METH_NOARGS,
-     PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
-
-    {"isoweekday",  (PyCFunction)date_isoweekday,   METH_NOARGS,
-     PyDoc_STR("Return the day of the week represented by the date.\n"
-               "Monday == 1 ... Sunday == 7")},
-
-    {"toordinal",   (PyCFunction)date_toordinal,    METH_NOARGS,
-     PyDoc_STR("Return proleptic Gregorian ordinal.  January 1 of year "
-               "1 is day 1.")},
-
-    {"weekday",     (PyCFunction)date_weekday,      METH_NOARGS,
-     PyDoc_STR("Return the day of the week represented by the date.\n"
-               "Monday == 0 ... Sunday == 6")},
-
-    {"replace",     (PyCFunction)date_replace,      METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("Return date with new specified fields.")},
-
-    {"__reduce__", (PyCFunction)date_reduce,        METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL}
-};
-
-static char date_doc[] =
-PyDoc_STR("date(year, month, day) --> date object");
-
-static PyNumberMethods date_as_number = {
-    date_add,                                           /* nb_add */
-    date_subtract,                                      /* nb_subtract */
-    0,                                                  /* nb_multiply */
-    0,                                                  /* nb_remainder */
-    0,                                                  /* nb_divmod */
-    0,                                                  /* nb_power */
-    0,                                                  /* nb_negative */
-    0,                                                  /* nb_positive */
-    0,                                                  /* nb_absolute */
-    0,                                                  /* nb_bool */
-};
-
-static PyTypeObject PyDateTime_DateType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.date",                                    /* tp_name */
-    sizeof(PyDateTime_Date),                            /* tp_basicsize */
-    0,                                                  /* tp_itemsize */
-    0,                                                  /* tp_dealloc */
-    0,                                                  /* tp_print */
-    0,                                                  /* tp_getattr */
-    0,                                                  /* tp_setattr */
-    0,                                                  /* tp_reserved */
-    (reprfunc)date_repr,                                /* tp_repr */
-    &date_as_number,                                    /* tp_as_number */
-    0,                                                  /* tp_as_sequence */
-    0,                                                  /* tp_as_mapping */
-    (hashfunc)date_hash,                                /* tp_hash */
-    0,                                                  /* tp_call */
-    (reprfunc)date_str,                                 /* tp_str */
-    PyObject_GenericGetAttr,                            /* tp_getattro */
-    0,                                                  /* tp_setattro */
-    0,                                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,           /* tp_flags */
-    date_doc,                                           /* tp_doc */
-    0,                                                  /* tp_traverse */
-    0,                                                  /* tp_clear */
-    date_richcompare,                                   /* tp_richcompare */
-    0,                                                  /* tp_weaklistoffset */
-    0,                                                  /* tp_iter */
-    0,                                                  /* tp_iternext */
-    date_methods,                                       /* tp_methods */
-    0,                                                  /* tp_members */
-    date_getset,                                        /* tp_getset */
-    0,                                                  /* tp_base */
-    0,                                                  /* tp_dict */
-    0,                                                  /* tp_descr_get */
-    0,                                                  /* tp_descr_set */
-    0,                                                  /* tp_dictoffset */
-    0,                                                  /* tp_init */
-    0,                                                  /* tp_alloc */
-    date_new,                                           /* tp_new */
-    0,                                                  /* tp_free */
-};
-
-/*
- * PyDateTime_TZInfo implementation.
- */
-
-/* This is a pure abstract base class, so doesn't do anything beyond
- * raising NotImplemented exceptions.  Real tzinfo classes need
- * to derive from this.  This is mostly for clarity, and for efficiency in
- * datetime and time constructors (their tzinfo arguments need to
- * be subclasses of this tzinfo class, which is easy and quick to check).
- *
- * Note:  For reasons having to do with pickling of subclasses, we have
- * to allow tzinfo objects to be instantiated.  This wasn't an issue
- * in the Python implementation (__init__() could raise NotImplementedError
- * there without ill effect), but doing so in the C implementation hit a
- * brick wall.
- */
-
-static PyObject *
-tzinfo_nogo(const char* methodname)
-{
-    PyErr_Format(PyExc_NotImplementedError,
-                 "a tzinfo subclass must implement %s()",
-                 methodname);
-    return NULL;
-}
-
-/* Methods.  A subclass must implement these. */
-
-static PyObject *
-tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    return tzinfo_nogo("tzname");
-}
-
-static PyObject *
-tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    return tzinfo_nogo("utcoffset");
-}
-
-static PyObject *
-tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    return tzinfo_nogo("dst");
-}
-
-
-static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
-                                        PyDateTime_Delta *delta,
-                                        int factor);
-static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
-static PyObject *datetime_dst(PyObject *self, PyObject *);
-
-static PyObject *
-tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    PyObject *result = NULL;
-    PyObject *off = NULL, *dst = NULL;
-    PyDateTime_Delta *delta = NULL;
-
-    if (!PyDateTime_Check(dt)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "fromutc: argument must be a datetime");
-        return NULL;
-    }
-    if (GET_DT_TZINFO(dt) != (PyObject *)self) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
-                        "is not self");
-        return NULL;
-    }
-
-    off = datetime_utcoffset(dt, NULL);
-    if (off == NULL)
-        return NULL;
-    if (off == Py_None) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
-                        "utcoffset() result required");
-        goto Fail;
-    }
-
-    dst = datetime_dst(dt, NULL);
-    if (dst == NULL)
-        goto Fail;
-    if (dst == Py_None) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
-                        "dst() result required");
-        goto Fail;
-    }
-
-    delta = (PyDateTime_Delta *)delta_subtract(off, dst);
-    if (delta == NULL)
-        goto Fail;
-    result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
-    if (result == NULL)
-        goto Fail;
-
-    Py_DECREF(dst);
-    dst = call_dst(GET_DT_TZINFO(dt), result);
-    if (dst == NULL)
-        goto Fail;
-    if (dst == Py_None)
-        goto Inconsistent;
-    if (delta_bool(delta) != 0) {
-        PyObject *temp = result;
-        result = add_datetime_timedelta((PyDateTime_DateTime *)result,
-                                        (PyDateTime_Delta *)dst, 1);
-        Py_DECREF(temp);
-        if (result == NULL)
-            goto Fail;
-    }
-    Py_DECREF(delta);
-    Py_DECREF(dst);
-    Py_DECREF(off);
-    return result;
-
-Inconsistent:
-    PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
-                    "inconsistent results; cannot convert");
-
-    /* fall thru to failure */
-Fail:
-    Py_XDECREF(off);
-    Py_XDECREF(dst);
-    Py_XDECREF(delta);
-    Py_XDECREF(result);
-    return NULL;
-}
-
-/*
- * Pickle support.  This is solely so that tzinfo subclasses can use
- * pickling -- tzinfo itself is supposed to be uninstantiable.
- */
-
-static PyObject *
-tzinfo_reduce(PyObject *self)
-{
-    PyObject *args, *state, *tmp;
-    PyObject *getinitargs, *getstate;
-    _Py_IDENTIFIER(__getinitargs__);
-    _Py_IDENTIFIER(__getstate__);
-
-    tmp = PyTuple_New(0);
-    if (tmp == NULL)
-        return NULL;
-
-    getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
-    if (getinitargs != NULL) {
-        args = PyObject_CallObject(getinitargs, tmp);
-        Py_DECREF(getinitargs);
-        if (args == NULL) {
-            Py_DECREF(tmp);
-            return NULL;
-        }
-    }
-    else {
-        PyErr_Clear();
-        args = tmp;
-        Py_INCREF(args);
-    }
-
-    getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
-    if (getstate != NULL) {
-        state = PyObject_CallObject(getstate, tmp);
-        Py_DECREF(getstate);
-        if (state == NULL) {
-            Py_DECREF(args);
-            Py_DECREF(tmp);
-            return NULL;
-        }
-    }
-    else {
-        PyObject **dictptr;
-        PyErr_Clear();
-        state = Py_None;
-        dictptr = _PyObject_GetDictPtr(self);
-        if (dictptr && *dictptr && PyDict_Size(*dictptr))
-            state = *dictptr;
-        Py_INCREF(state);
-    }
-
-    Py_DECREF(tmp);
-
-    if (state == Py_None) {
-        Py_DECREF(state);
-        return Py_BuildValue("(ON)", Py_TYPE(self), args);
-    }
-    else
-        return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
-}
-
-static PyMethodDef tzinfo_methods[] = {
-
-    {"tzname",          (PyCFunction)tzinfo_tzname,             METH_O,
-     PyDoc_STR("datetime -> string name of time zone.")},
-
-    {"utcoffset",       (PyCFunction)tzinfo_utcoffset,          METH_O,
-     PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
-           "values indicating West of UTC")},
-
-    {"dst",             (PyCFunction)tzinfo_dst,                METH_O,
-     PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
-
-    {"fromutc",         (PyCFunction)tzinfo_fromutc,            METH_O,
-     PyDoc_STR("datetime in UTC -> datetime in local time.")},
-
-    {"__reduce__",  (PyCFunction)tzinfo_reduce,             METH_NOARGS,
-     PyDoc_STR("-> (cls, state)")},
-
-    {NULL, NULL}
-};
-
-static char tzinfo_doc[] =
-PyDoc_STR("Abstract base class for time zone info objects.");
-
-static PyTypeObject PyDateTime_TZInfoType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.tzinfo",                          /* tp_name */
-    sizeof(PyDateTime_TZInfo),                  /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    0,                                          /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
-    tzinfo_doc,                                 /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    0,                                          /* tp_iter */
-    0,                                          /* tp_iternext */
-    tzinfo_methods,                             /* tp_methods */
-    0,                                          /* tp_members */
-    0,                                          /* tp_getset */
-    0,                                          /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    0,                                          /* tp_alloc */
-    PyType_GenericNew,                          /* tp_new */
-    0,                                          /* tp_free */
-};
-
-static char *timezone_kws[] = {"offset", "name", NULL};
-
-static PyObject *
-timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *offset;
-    PyObject *name = NULL;
-    if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
-                                    &PyDateTime_DeltaType, &offset,
-                                    &PyUnicode_Type, &name))
-        return new_timezone(offset, name);
-
-    return NULL;
-}
-
-static void
-timezone_dealloc(PyDateTime_TimeZone *self)
-{
-    Py_CLEAR(self->offset);
-    Py_CLEAR(self->name);
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-static PyObject *
-timezone_richcompare(PyDateTime_TimeZone *self,
-                     PyDateTime_TimeZone *other, int op)
-{
-    if (op != Py_EQ && op != Py_NE)
-        Py_RETURN_NOTIMPLEMENTED;
-    if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
-        if (op == Py_EQ)
-            Py_RETURN_FALSE;
-        else
-            Py_RETURN_TRUE;
-    }
-    return delta_richcompare(self->offset, other->offset, op);
-}
-
-static Py_hash_t
-timezone_hash(PyDateTime_TimeZone *self)
-{
-    return delta_hash((PyDateTime_Delta *)self->offset);
-}
-
-/* Check argument type passed to tzname, utcoffset, or dst methods.
-   Returns 0 for good argument.  Returns -1 and sets exception info
-   otherwise.
- */
-static int
-_timezone_check_argument(PyObject *dt, const char *meth)
-{
-    if (dt == Py_None || PyDateTime_Check(dt))
-        return 0;
-    PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
-                 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
-    return -1;
-}
-
-static PyObject *
-timezone_repr(PyDateTime_TimeZone *self)
-{
-    /* Note that although timezone is not subclassable, it is convenient
-       to use Py_TYPE(self)->tp_name here. */
-    const char *type_name = Py_TYPE(self)->tp_name;
-
-    if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
-        return PyUnicode_FromFormat("%s.utc", type_name);
-
-    if (self->name == NULL)
-        return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
-
-    return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
-                                self->name);
-}
-
-
-static PyObject *
-timezone_str(PyDateTime_TimeZone *self)
-{
-    int hours, minutes, seconds;
-    PyObject *offset;
-    char sign;
-
-    if (self->name != NULL) {
-        Py_INCREF(self->name);
-        return self->name;
-    }
-    /* Offset is normalized, so it is negative if days < 0 */
-    if (GET_TD_DAYS(self->offset) < 0) {
-        sign = '-';
-        offset = delta_negative((PyDateTime_Delta *)self->offset);
-        if (offset == NULL)
-            return NULL;
-    }
-    else {
-        sign = '+';
-        offset = self->offset;
-        Py_INCREF(offset);
-    }
-    /* Offset is not negative here. */
-    seconds = GET_TD_SECONDS(offset);
-    Py_DECREF(offset);
-    minutes = divmod(seconds, 60, &seconds);
-    hours = divmod(minutes, 60, &minutes);
-    /* XXX ignore sub-minute data, curently not allowed. */
-    assert(seconds == 0);
-    return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
-}
-
-static PyObject *
-timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
-{
-    if (_timezone_check_argument(dt, "tzname") == -1)
-        return NULL;
-
-    return timezone_str(self);
-}
-
-static PyObject *
-timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
-{
-    if (_timezone_check_argument(dt, "utcoffset") == -1)
-        return NULL;
-
-    Py_INCREF(self->offset);
-    return self->offset;
-}
-
-static PyObject *
-timezone_dst(PyObject *self, PyObject *dt)
-{
-    if (_timezone_check_argument(dt, "dst") == -1)
-        return NULL;
-
-    Py_RETURN_NONE;
-}
-
-static PyObject *
-timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
-{
-    if (!PyDateTime_Check(dt)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "fromutc: argument must be a datetime");
-        return NULL;
-    }
-    if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
-                        "is not self");
-        return NULL;
-    }
-
-    return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
-}
-
-static PyObject *
-timezone_getinitargs(PyDateTime_TimeZone *self)
-{
-    if (self->name == NULL)
-        return Py_BuildValue("(O)", self->offset);
-    return Py_BuildValue("(OO)", self->offset, self->name);
-}
-
-static PyMethodDef timezone_methods[] = {
-    {"tzname", (PyCFunction)timezone_tzname, METH_O,
-     PyDoc_STR("If name is specified when timezone is created, returns the name."
-               "  Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
-
-    {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
-     PyDoc_STR("Return fixed offset.")},
-
-    {"dst", (PyCFunction)timezone_dst, METH_O,
-     PyDoc_STR("Return None.")},
-
-    {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
-     PyDoc_STR("datetime in UTC -> datetime in local time.")},
-
-    {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
-     PyDoc_STR("pickle support")},
-
-    {NULL, NULL}
-};
-
-static char timezone_doc[] =
-PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
-
-static PyTypeObject PyDateTime_TimeZoneType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.timezone",              /* tp_name */
-    sizeof(PyDateTime_TimeZone),      /* tp_basicsize */
-    0,                                /* tp_itemsize */
-    (destructor)timezone_dealloc,     /* tp_dealloc */
-    0,                                /* tp_print */
-    0,                                /* tp_getattr */
-    0,                                /* tp_setattr */
-    0,                                /* tp_reserved */
-    (reprfunc)timezone_repr,          /* tp_repr */
-    0,                                /* tp_as_number */
-    0,                                /* tp_as_sequence */
-    0,                                /* tp_as_mapping */
-    (hashfunc)timezone_hash,          /* tp_hash */
-    0,                                /* tp_call */
-    (reprfunc)timezone_str,           /* tp_str */
-    0,                                /* tp_getattro */
-    0,                                /* tp_setattro */
-    0,                                /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,               /* tp_flags */
-    timezone_doc,                     /* tp_doc */
-    0,                                /* tp_traverse */
-    0,                                /* tp_clear */
-    (richcmpfunc)timezone_richcompare,/* tp_richcompare */
-    0,                                /* tp_weaklistoffset */
-    0,                                /* tp_iter */
-    0,                                /* tp_iternext */
-    timezone_methods,                 /* tp_methods */
-    0,                                /* tp_members */
-    0,                                /* tp_getset */
-    &PyDateTime_TZInfoType,           /* tp_base */
-    0,                                /* tp_dict */
-    0,                                /* tp_descr_get */
-    0,                                /* tp_descr_set */
-    0,                                /* tp_dictoffset */
-    0,                                /* tp_init */
-    0,                                /* tp_alloc */
-    timezone_new,                     /* tp_new */
-};
-
-/*
- * PyDateTime_Time implementation.
- */
-
-/* Accessor properties.
- */
-
-static PyObject *
-time_hour(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_HOUR(self));
-}
-
-static PyObject *
-time_minute(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_MINUTE(self));
-}
-
-/* The name time_second conflicted with some platform header file. */
-static PyObject *
-py_time_second(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_SECOND(self));
-}
-
-static PyObject *
-time_microsecond(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_MICROSECOND(self));
-}
-
-static PyObject *
-time_tzinfo(PyDateTime_Time *self, void *unused)
-{
-    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
-    Py_INCREF(result);
-    return result;
-}
-
-static PyGetSetDef time_getset[] = {
-    {"hour",        (getter)time_hour},
-    {"minute",      (getter)time_minute},
-    {"second",      (getter)py_time_second},
-    {"microsecond", (getter)time_microsecond},
-    {"tzinfo",          (getter)time_tzinfo},
-    {NULL}
-};
-
-/*
- * Constructors.
- */
-
-static char *time_kws[] = {"hour", "minute", "second", "microsecond",
-                           "tzinfo", NULL};
-
-static PyObject *
-time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-    PyObject *state;
-    int hour = 0;
-    int minute = 0;
-    int second = 0;
-    int usecond = 0;
-    PyObject *tzinfo = Py_None;
-
-    /* Check for invocation from pickle with __getstate__ state */
-    if (PyTuple_GET_SIZE(args) >= 1 &&
-        PyTuple_GET_SIZE(args) <= 2 &&
-        PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-        PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
-        ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
-    {
-        PyDateTime_Time *me;
-        char aware;
-
-        if (PyTuple_GET_SIZE(args) == 2) {
-            tzinfo = PyTuple_GET_ITEM(args, 1);
-            if (check_tzinfo_subclass(tzinfo) < 0) {
-                PyErr_SetString(PyExc_TypeError, "bad "
-                    "tzinfo state arg");
-                return NULL;
-            }
-        }
-        aware = (char)(tzinfo != Py_None);
-        me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
-        if (me != NULL) {
-            char *pdata = PyBytes_AS_STRING(state);
-
-            memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
-            me->hashcode = -1;
-            me->hastzinfo = aware;
-            if (aware) {
-                Py_INCREF(tzinfo);
-                me->tzinfo = tzinfo;
-            }
-        }
-        return (PyObject *)me;
-    }
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
-                                    &hour, &minute, &second, &usecond,
-                                    &tzinfo)) {
-        if (check_time_args(hour, minute, second, usecond) < 0)
-            return NULL;
-        if (check_tzinfo_subclass(tzinfo) < 0)
-            return NULL;
-        self = new_time_ex(hour, minute, second, usecond, tzinfo,
-                           type);
-    }
-    return self;
-}
-
-/*
- * Destructor.
- */
-
-static void
-time_dealloc(PyDateTime_Time *self)
-{
-    if (HASTZINFO(self)) {
-        Py_XDECREF(self->tzinfo);
-    }
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-/*
- * Indirect access to tzinfo methods.
- */
-
-/* These are all METH_NOARGS, so don't need to check the arglist. */
-static PyObject *
-time_utcoffset(PyObject *self, PyObject *unused) {
-    return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
-}
-
-static PyObject *
-time_dst(PyObject *self, PyObject *unused) {
-    return call_dst(GET_TIME_TZINFO(self), Py_None);
-}
-
-static PyObject *
-time_tzname(PyDateTime_Time *self, PyObject *unused) {
-    return call_tzname(GET_TIME_TZINFO(self), Py_None);
-}
-
-/*
- * Various ways to turn a time into a string.
- */
-
-static PyObject *
-time_repr(PyDateTime_Time *self)
-{
-    const char *type_name = Py_TYPE(self)->tp_name;
-    int h = TIME_GET_HOUR(self);
-    int m = TIME_GET_MINUTE(self);
-    int s = TIME_GET_SECOND(self);
-    int us = TIME_GET_MICROSECOND(self);
-    PyObject *result = NULL;
-
-    if (us)
-        result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
-                                      type_name, h, m, s, us);
-    else if (s)
-        result = PyUnicode_FromFormat("%s(%d, %d, %d)",
-                                      type_name, h, m, s);
-    else
-        result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
-    if (result != NULL && HASTZINFO(self))
-        result = append_keyword_tzinfo(result, self->tzinfo);
-    return result;
-}
-
-static PyObject *
-time_str(PyDateTime_Time *self)
-{
-    return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
-}
-
-static PyObject *
-time_isoformat(PyDateTime_Time *self, PyObject *unused)
-{
-    char buf[100];
-    PyObject *result;
-    int us = TIME_GET_MICROSECOND(self);
-
-    if (us)
-        result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
-                                      TIME_GET_HOUR(self),
-                                      TIME_GET_MINUTE(self),
-                                      TIME_GET_SECOND(self),
-                                      us);
-    else
-        result = PyUnicode_FromFormat("%02d:%02d:%02d",
-                                      TIME_GET_HOUR(self),
-                                      TIME_GET_MINUTE(self),
-                                      TIME_GET_SECOND(self));
-
-    if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
-        return result;
-
-    /* We need to append the UTC offset. */
-    if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
-                         Py_None) < 0) {
-        Py_DECREF(result);
-        return NULL;
-    }
-    PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
-    return result;
-}
-
-static PyObject *
-time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
-{
-    PyObject *result;
-    PyObject *tuple;
-    PyObject *format;
-    static char *keywords[] = {"format", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
-                                      &format))
-        return NULL;
-
-    /* Python's strftime does insane things with the year part of the
-     * timetuple.  The year is forced to (the otherwise nonsensical)
-     * 1900 to work around that.
-     */
-    tuple = Py_BuildValue("iiiiiiiii",
-                          1900, 1, 1, /* year, month, day */
-                  TIME_GET_HOUR(self),
-                  TIME_GET_MINUTE(self),
-                  TIME_GET_SECOND(self),
-                  0, 1, -1); /* weekday, daynum, dst */
-    if (tuple == NULL)
-        return NULL;
-    assert(PyTuple_Size(tuple) == 9);
-    result = wrap_strftime((PyObject *)self, format, tuple,
-                           Py_None);
-    Py_DECREF(tuple);
-    return result;
-}
-
-/*
- * Miscellaneous methods.
- */
-
-static PyObject *
-time_richcompare(PyObject *self, PyObject *other, int op)
-{
-    PyObject *result = NULL;
-    PyObject *offset1, *offset2;
-    int diff;
-
-    if (! PyTime_Check(other))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
-        diff = memcmp(((PyDateTime_Time *)self)->data,
-                      ((PyDateTime_Time *)other)->data,
-                      _PyDateTime_TIME_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-    offset1 = time_utcoffset(self, NULL);
-    if (offset1 == NULL)
-        return NULL;
-    offset2 = time_utcoffset(other, NULL);
-    if (offset2 == NULL)
-        goto done;
-    /* If they're both naive, or both aware and have the same offsets,
-     * we get off cheap.  Note that if they're both naive, offset1 ==
-     * offset2 == Py_None at this point.
-     */
-    if ((offset1 == offset2) ||
-        (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
-         delta_cmp(offset1, offset2) == 0)) {
-        diff = memcmp(((PyDateTime_Time *)self)->data,
-                      ((PyDateTime_Time *)other)->data,
-                      _PyDateTime_TIME_DATASIZE);
-        result = diff_to_bool(diff, op);
-    }
-    /* The hard case: both aware with different UTC offsets */
-    else if (offset1 != Py_None && offset2 != Py_None) {
-        int offsecs1, offsecs2;
-        assert(offset1 != offset2); /* else last "if" handled it */
-        offsecs1 = TIME_GET_HOUR(self) * 3600 +
-                   TIME_GET_MINUTE(self) * 60 +
-                   TIME_GET_SECOND(self) -
-                   GET_TD_DAYS(offset1) * 86400 -
-                   GET_TD_SECONDS(offset1);
-        offsecs2 = TIME_GET_HOUR(other) * 3600 +
-                   TIME_GET_MINUTE(other) * 60 +
-                   TIME_GET_SECOND(other) -
-                   GET_TD_DAYS(offset2) * 86400 -
-                   GET_TD_SECONDS(offset2);
-        diff = offsecs1 - offsecs2;
-        if (diff == 0)
-            diff = TIME_GET_MICROSECOND(self) -
-                   TIME_GET_MICROSECOND(other);
-        result = diff_to_bool(diff, op);
-    }
-    else if (op == Py_EQ) {
-        result = Py_False;
-        Py_INCREF(result);
-    }
-    else if (op == Py_NE) {
-        result = Py_True;
-        Py_INCREF(result);
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "can't compare offset-naive and "
-                        "offset-aware times");
-    }
- done:
-    Py_DECREF(offset1);
-    Py_XDECREF(offset2);
-    return result;
-}
-
-static Py_hash_t
-time_hash(PyDateTime_Time *self)
-{
-    if (self->hashcode == -1) {
-        PyObject *offset;
-
-        offset = time_utcoffset((PyObject *)self, NULL);
-
-        if (offset == NULL)
-            return -1;
-
-        /* Reduce this to a hash of another object. */
-        if (offset == Py_None)
-            self->hashcode = generic_hash(
-                (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
-        else {
-            PyObject *temp1, *temp2;
-            int seconds, microseconds;
-            assert(HASTZINFO(self));
-            seconds = TIME_GET_HOUR(self) * 3600 +
-                      TIME_GET_MINUTE(self) * 60 +
-                      TIME_GET_SECOND(self);
-            microseconds = TIME_GET_MICROSECOND(self);
-            temp1 = new_delta(0, seconds, microseconds, 1);
-            if (temp1 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            temp2 = delta_subtract(temp1, offset);
-            Py_DECREF(temp1);
-            if (temp2 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            self->hashcode = PyObject_Hash(temp2);
-            Py_DECREF(temp2);
-        }
-        Py_DECREF(offset);
-    }
-    return self->hashcode;
-}
-
-static PyObject *
-time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
-{
-    PyObject *clone;
-    PyObject *tuple;
-    int hh = TIME_GET_HOUR(self);
-    int mm = TIME_GET_MINUTE(self);
-    int ss = TIME_GET_SECOND(self);
-    int us = TIME_GET_MICROSECOND(self);
-    PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
-                                      time_kws,
-                                      &hh, &mm, &ss, &us, &tzinfo))
-        return NULL;
-    tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
-    if (tuple == NULL)
-        return NULL;
-    clone = time_new(Py_TYPE(self), tuple, NULL);
-    Py_DECREF(tuple);
-    return clone;
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* Let basestate be the non-tzinfo data string.
- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
- * So it's a tuple in any (non-error) case.
- * __getstate__ isn't exposed.
- */
-static PyObject *
-time_getstate(PyDateTime_Time *self)
-{
-    PyObject *basestate;
-    PyObject *result = NULL;
-
-    basestate =  PyBytes_FromStringAndSize((char *)self->data,
-                                            _PyDateTime_TIME_DATASIZE);
-    if (basestate != NULL) {
-        if (! HASTZINFO(self) || self->tzinfo == Py_None)
-            result = PyTuple_Pack(1, basestate);
-        else
-            result = PyTuple_Pack(2, basestate, self->tzinfo);
-        Py_DECREF(basestate);
-    }
-    return result;
-}
-
-static PyObject *
-time_reduce(PyDateTime_Time *self, PyObject *arg)
-{
-    return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
-}
-
-static PyMethodDef time_methods[] = {
-
-    {"isoformat",   (PyCFunction)time_isoformat,        METH_NOARGS,
-     PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
-               "[+HH:MM].")},
-
-    {"strftime",        (PyCFunction)time_strftime,     METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("format -> strftime() style string.")},
-
-    {"__format__",      (PyCFunction)date_format,       METH_VARARGS,
-     PyDoc_STR("Formats self with strftime.")},
-
-    {"utcoffset",       (PyCFunction)time_utcoffset,    METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
-
-    {"tzname",          (PyCFunction)time_tzname,       METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.tzname(self).")},
-
-    {"dst",             (PyCFunction)time_dst,          METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.dst(self).")},
-
-    {"replace",     (PyCFunction)time_replace,          METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("Return time with new specified fields.")},
-
-    {"__reduce__", (PyCFunction)time_reduce,        METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL}
-};
-
-static char time_doc[] =
-PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
-\n\
-All arguments are optional. tzinfo may be None, or an instance of\n\
-a tzinfo subclass. The remaining arguments may be ints.\n");
-
-static PyTypeObject PyDateTime_TimeType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.time",                            /* tp_name */
-    sizeof(PyDateTime_Time),                    /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    (destructor)time_dealloc,                   /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)time_repr,                        /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    (hashfunc)time_hash,                        /* tp_hash */
-    0,                                          /* tp_call */
-    (reprfunc)time_str,                         /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
-    time_doc,                                   /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    time_richcompare,                           /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    0,                                          /* tp_iter */
-    0,                                          /* tp_iternext */
-    time_methods,                               /* tp_methods */
-    0,                                          /* tp_members */
-    time_getset,                                /* tp_getset */
-    0,                                          /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    time_alloc,                                 /* tp_alloc */
-    time_new,                                   /* tp_new */
-    0,                                          /* tp_free */
-};
-
-/*
- * PyDateTime_DateTime implementation.
- */
-
-/* Accessor properties.  Properties for day, month, and year are inherited
- * from date.
- */
-
-static PyObject *
-datetime_hour(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_HOUR(self));
-}
-
-static PyObject *
-datetime_minute(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_MINUTE(self));
-}
-
-static PyObject *
-datetime_second(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_SECOND(self));
-}
-
-static PyObject *
-datetime_microsecond(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_MICROSECOND(self));
-}
-
-static PyObject *
-datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
-{
-    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
-    Py_INCREF(result);
-    return result;
-}
-
-static PyGetSetDef datetime_getset[] = {
-    {"hour",        (getter)datetime_hour},
-    {"minute",      (getter)datetime_minute},
-    {"second",      (getter)datetime_second},
-    {"microsecond", (getter)datetime_microsecond},
-    {"tzinfo",          (getter)datetime_tzinfo},
-    {NULL}
-};
-
-/*
- * Constructors.
- */
-
-static char *datetime_kws[] = {
-    "year", "month", "day", "hour", "minute", "second",
-    "microsecond", "tzinfo", NULL
-};
-
-static PyObject *
-datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-    PyObject *state;
-    int year;
-    int month;
-    int day;
-    int hour = 0;
-    int minute = 0;
-    int second = 0;
-    int usecond = 0;
-    PyObject *tzinfo = Py_None;
-
-    /* Check for invocation from pickle with __getstate__ state */
-    if (PyTuple_GET_SIZE(args) >= 1 &&
-        PyTuple_GET_SIZE(args) <= 2 &&
-        PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-        PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
-        MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
-    {
-        PyDateTime_DateTime *me;
-        char aware;
-
-        if (PyTuple_GET_SIZE(args) == 2) {
-            tzinfo = PyTuple_GET_ITEM(args, 1);
-            if (check_tzinfo_subclass(tzinfo) < 0) {
-                PyErr_SetString(PyExc_TypeError, "bad "
-                    "tzinfo state arg");
-                return NULL;
-            }
-        }
-        aware = (char)(tzinfo != Py_None);
-        me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
-        if (me != NULL) {
-            char *pdata = PyBytes_AS_STRING(state);
-
-            memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
-            me->hashcode = -1;
-            me->hastzinfo = aware;
-            if (aware) {
-                Py_INCREF(tzinfo);
-                me->tzinfo = tzinfo;
-            }
-        }
-        return (PyObject *)me;
-    }
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
-                                    &year, &month, &day, &hour, &minute,
-                                    &second, &usecond, &tzinfo)) {
-        if (check_date_args(year, month, day) < 0)
-            return NULL;
-        if (check_time_args(hour, minute, second, usecond) < 0)
-            return NULL;
-        if (check_tzinfo_subclass(tzinfo) < 0)
-            return NULL;
-        self = new_datetime_ex(year, month, day,
-                                hour, minute, second, usecond,
-                                tzinfo, type);
-    }
-    return self;
-}
-
-/* TM_FUNC is the shared type of localtime() and gmtime(). */
-typedef struct tm *(*TM_FUNC)(const time_t *timer);
-
-/* Internal helper.
- * Build datetime from a time_t and a distinct count of microseconds.
- * Pass localtime or gmtime for f, to control the interpretation of timet.
- */
-static PyObject *
-datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
-                           PyObject *tzinfo)
-{
-    struct tm *tm;
-
-    tm = f(&timet);
-    if (tm == NULL) {
-#ifdef EINVAL
-        if (errno == 0)
-            errno = EINVAL;
-#endif
-        return PyErr_SetFromErrno(PyExc_OSError);
-    }
-
-    /* The platform localtime/gmtime may insert leap seconds,
-     * indicated by tm->tm_sec > 59.  We don't care about them,
-     * except to the extent that passing them on to the datetime
-     * constructor would raise ValueError for a reason that
-     * made no sense to the user.
-     */
-    if (tm->tm_sec > 59)
-        tm->tm_sec = 59;
-    return PyObject_CallFunction(cls, "iiiiiiiO",
-                                 tm->tm_year + 1900,
-                                 tm->tm_mon + 1,
-                                 tm->tm_mday,
-                                 tm->tm_hour,
-                                 tm->tm_min,
-                                 tm->tm_sec,
-                                 us,
-                                 tzinfo);
-}
-
-/* Internal helper.
- * Build datetime from a Python timestamp.  Pass localtime or gmtime for f,
- * to control the interpretation of the timestamp.  Since a double doesn't
- * have enough bits to cover a datetime's full range of precision, it's
- * better to call datetime_from_timet_and_us provided you have a way
- * to get that much precision (e.g., C time() isn't good enough).
- */
-static PyObject *
-datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
-                        PyObject *tzinfo)
-{
-    time_t timet;
-    long us;
-
-    if (_PyTime_ObjectToTimeval(timestamp,
-                                &timet, &us, _PyTime_ROUND_FLOOR) == -1)
-        return NULL;
-    assert(0 <= us && us <= 999999);
-
-    return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
-}
-
-/* Internal helper.
- * Build most accurate possible datetime for current time.  Pass localtime or
- * gmtime for f as appropriate.
- */
-static PyObject *
-datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
-{
-    _PyTime_t ts = _PyTime_GetSystemClock();
-    struct timeval tv;
-
-    if (_PyTime_AsTimeval(ts, &tv, _PyTime_ROUND_FLOOR) < 0)
-        return NULL;
-    assert(0 <= tv.tv_usec && tv.tv_usec <= 999999);
-
-    return datetime_from_timet_and_us(cls, f, tv.tv_sec, tv.tv_usec, tzinfo);
-}
-
-/*[clinic input]
-
- at classmethod
-datetime.datetime.now
-
-    tz: object = None
-        Timezone object.
-
-Returns new datetime object representing current time local to tz.
-
-If no tz is specified, uses local timezone.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(datetime_datetime_now__doc__,
@@ -4166,1425 +35,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
-/*[clinic end generated code: output=583c5637e3c843fa input=80d09869c5267d00]*/
-{
-    PyObject *self;
-
-    /* Return best possible local time -- this isn't constrained by the
-     * precision of a timestamp.
-     */
-    if (check_tzinfo_subclass(tz) < 0)
-        return NULL;
-
-    self = datetime_best_possible((PyObject *)type,
-                                  tz == Py_None ? localtime : gmtime,
-                                  tz);
-    if (self != NULL && tz != Py_None) {
-        /* Convert UTC to tzinfo's zone. */
-        PyObject *temp = self;
-
-        self = _PyObject_CallMethodId(tz, &PyId_fromutc, "O", self);
-        Py_DECREF(temp);
-    }
-    return self;
-}
-
-/* Return best possible UTC time -- this isn't constrained by the
- * precision of a timestamp.
- */
-static PyObject *
-datetime_utcnow(PyObject *cls, PyObject *dummy)
-{
-    return datetime_best_possible(cls, gmtime, Py_None);
-}
-
-/* Return new local datetime from timestamp (Python timestamp -- a double). */
-static PyObject *
-datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
-{
-    PyObject *self;
-    PyObject *timestamp;
-    PyObject *tzinfo = Py_None;
-    static char *keywords[] = {"timestamp", "tz", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
-                                      keywords, &timestamp, &tzinfo))
-        return NULL;
-    if (check_tzinfo_subclass(tzinfo) < 0)
-        return NULL;
-
-    self = datetime_from_timestamp(cls,
-                                   tzinfo == Py_None ? localtime : gmtime,
-                                   timestamp,
-                                   tzinfo);
-    if (self != NULL && tzinfo != Py_None) {
-        /* Convert UTC to tzinfo's zone. */
-        PyObject *temp = self;
-
-        self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
-        Py_DECREF(temp);
-    }
-    return self;
-}
-
-/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
-static PyObject *
-datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
-{
-    PyObject *timestamp;
-    PyObject *result = NULL;
-
-    if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
-        result = datetime_from_timestamp(cls, gmtime, timestamp,
-                                         Py_None);
-    return result;
-}
-
-/* Return new datetime from _strptime.strptime_datetime(). */
-static PyObject *
-datetime_strptime(PyObject *cls, PyObject *args)
-{
-    static PyObject *module = NULL;
-    PyObject *string, *format;
-    _Py_IDENTIFIER(_strptime_datetime);
-
-    if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
-        return NULL;
-
-    if (module == NULL) {
-        module = PyImport_ImportModuleNoBlock("_strptime");
-        if (module == NULL)
-            return NULL;
-    }
-    return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
-                                 cls, string, format);
-}
-
-/* Return new datetime from date/datetime and time arguments. */
-static PyObject *
-datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
-{
-    static char *keywords[] = {"date", "time", NULL};
-    PyObject *date;
-    PyObject *time;
-    PyObject *result = NULL;
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
-                                    &PyDateTime_DateType, &date,
-                                    &PyDateTime_TimeType, &time)) {
-        PyObject *tzinfo = Py_None;
-
-        if (HASTZINFO(time))
-            tzinfo = ((PyDateTime_Time *)time)->tzinfo;
-        result = PyObject_CallFunction(cls, "iiiiiiiO",
-                                        GET_YEAR(date),
-                                        GET_MONTH(date),
-                                        GET_DAY(date),
-                                        TIME_GET_HOUR(time),
-                                        TIME_GET_MINUTE(time),
-                                        TIME_GET_SECOND(time),
-                                        TIME_GET_MICROSECOND(time),
-                                        tzinfo);
-    }
-    return result;
-}
-
-/*
- * Destructor.
- */
-
-static void
-datetime_dealloc(PyDateTime_DateTime *self)
-{
-    if (HASTZINFO(self)) {
-        Py_XDECREF(self->tzinfo);
-    }
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-/*
- * Indirect access to tzinfo methods.
- */
-
-/* These are all METH_NOARGS, so don't need to check the arglist. */
-static PyObject *
-datetime_utcoffset(PyObject *self, PyObject *unused) {
-    return call_utcoffset(GET_DT_TZINFO(self), self);
-}
-
-static PyObject *
-datetime_dst(PyObject *self, PyObject *unused) {
-    return call_dst(GET_DT_TZINFO(self), self);
-}
-
-static PyObject *
-datetime_tzname(PyObject *self, PyObject *unused) {
-    return call_tzname(GET_DT_TZINFO(self), self);
-}
-
-/*
- * datetime arithmetic.
- */
-
-/* factor must be 1 (to add) or -1 (to subtract).  The result inherits
- * the tzinfo state of date.
- */
-static PyObject *
-add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
-                       int factor)
-{
-    /* Note that the C-level additions can't overflow, because of
-     * invariant bounds on the member values.
-     */
-    int year = GET_YEAR(date);
-    int month = GET_MONTH(date);
-    int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
-    int hour = DATE_GET_HOUR(date);
-    int minute = DATE_GET_MINUTE(date);
-    int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
-    int microsecond = DATE_GET_MICROSECOND(date) +
-                      GET_TD_MICROSECONDS(delta) * factor;
-
-    assert(factor == 1 || factor == -1);
-    if (normalize_datetime(&year, &month, &day,
-                           &hour, &minute, &second, &microsecond) < 0)
-        return NULL;
-    else
-        return new_datetime(year, month, day,
-                            hour, minute, second, microsecond,
-                            HASTZINFO(date) ? date->tzinfo : Py_None);
-}
-
-static PyObject *
-datetime_add(PyObject *left, PyObject *right)
-{
-    if (PyDateTime_Check(left)) {
-        /* datetime + ??? */
-        if (PyDelta_Check(right))
-            /* datetime + delta */
-            return add_datetime_timedelta(
-                            (PyDateTime_DateTime *)left,
-                            (PyDateTime_Delta *)right,
-                            1);
-    }
-    else if (PyDelta_Check(left)) {
-        /* delta + datetime */
-        return add_datetime_timedelta((PyDateTime_DateTime *) right,
-                                      (PyDateTime_Delta *) left,
-                                      1);
-    }
-    Py_RETURN_NOTIMPLEMENTED;
-}
-
-static PyObject *
-datetime_subtract(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDateTime_Check(left)) {
-        /* datetime - ??? */
-        if (PyDateTime_Check(right)) {
-            /* datetime - datetime */
-            PyObject *offset1, *offset2, *offdiff = NULL;
-            int delta_d, delta_s, delta_us;
-
-            if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
-                offset2 = offset1 = Py_None;
-                Py_INCREF(offset1);
-                Py_INCREF(offset2);
-            }
-            else {
-                offset1 = datetime_utcoffset(left, NULL);
-                if (offset1 == NULL)
-                    return NULL;
-                offset2 = datetime_utcoffset(right, NULL);
-                if (offset2 == NULL) {
-                    Py_DECREF(offset1);
-                    return NULL;
-                }
-                if ((offset1 != Py_None) != (offset2 != Py_None)) {
-                    PyErr_SetString(PyExc_TypeError,
-                                    "can't subtract offset-naive and "
-                                    "offset-aware datetimes");
-                    Py_DECREF(offset1);
-                    Py_DECREF(offset2);
-                    return NULL;
-                }
-            }
-            if ((offset1 != offset2) &&
-                delta_cmp(offset1, offset2) != 0) {
-                offdiff = delta_subtract(offset1, offset2);
-                if (offdiff == NULL) {
-                    Py_DECREF(offset1);
-                    Py_DECREF(offset2);
-                    return NULL;
-                }
-            }
-            Py_DECREF(offset1);
-            Py_DECREF(offset2);
-            delta_d = ymd_to_ord(GET_YEAR(left),
-                                 GET_MONTH(left),
-                                 GET_DAY(left)) -
-                      ymd_to_ord(GET_YEAR(right),
-                                 GET_MONTH(right),
-                                 GET_DAY(right));
-            /* These can't overflow, since the values are
-             * normalized.  At most this gives the number of
-             * seconds in one day.
-             */
-            delta_s = (DATE_GET_HOUR(left) -
-                       DATE_GET_HOUR(right)) * 3600 +
-                      (DATE_GET_MINUTE(left) -
-                       DATE_GET_MINUTE(right)) * 60 +
-                      (DATE_GET_SECOND(left) -
-                       DATE_GET_SECOND(right));
-            delta_us = DATE_GET_MICROSECOND(left) -
-                       DATE_GET_MICROSECOND(right);
-            result = new_delta(delta_d, delta_s, delta_us, 1);
-            if (result == NULL)
-                return NULL;
-
-            if (offdiff != NULL) {
-                PyObject *temp = result;
-                result = delta_subtract(result, offdiff);
-                Py_DECREF(temp);
-                Py_DECREF(offdiff);
-            }
-        }
-        else if (PyDelta_Check(right)) {
-            /* datetime - delta */
-            result = add_datetime_timedelta(
-                            (PyDateTime_DateTime *)left,
-                            (PyDateTime_Delta *)right,
-                            -1);
-        }
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-/* Various ways to turn a datetime into a string. */
-
-static PyObject *
-datetime_repr(PyDateTime_DateTime *self)
-{
-    const char *type_name = Py_TYPE(self)->tp_name;
-    PyObject *baserepr;
-
-    if (DATE_GET_MICROSECOND(self)) {
-        baserepr = PyUnicode_FromFormat(
-                      "%s(%d, %d, %d, %d, %d, %d, %d)",
-                      type_name,
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                      DATE_GET_SECOND(self),
-                      DATE_GET_MICROSECOND(self));
-    }
-    else if (DATE_GET_SECOND(self)) {
-        baserepr = PyUnicode_FromFormat(
-                      "%s(%d, %d, %d, %d, %d, %d)",
-                      type_name,
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                      DATE_GET_SECOND(self));
-    }
-    else {
-        baserepr = PyUnicode_FromFormat(
-                      "%s(%d, %d, %d, %d, %d)",
-                      type_name,
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
-    }
-    if (baserepr == NULL || ! HASTZINFO(self))
-        return baserepr;
-    return append_keyword_tzinfo(baserepr, self->tzinfo);
-}
-
-static PyObject *
-datetime_str(PyDateTime_DateTime *self)
-{
-    return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
-}
-
-static PyObject *
-datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
-{
-    int sep = 'T';
-    static char *keywords[] = {"sep", NULL};
-    char buffer[100];
-    PyObject *result;
-    int us = DATE_GET_MICROSECOND(self);
-
-    if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
-        return NULL;
-    if (us)
-        result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
-                                      GET_YEAR(self), GET_MONTH(self),
-                                      GET_DAY(self), (int)sep,
-                                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                                      DATE_GET_SECOND(self), us);
-    else
-        result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
-                                      GET_YEAR(self), GET_MONTH(self),
-                                      GET_DAY(self), (int)sep,
-                                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                                      DATE_GET_SECOND(self));
-
-    if (!result || !HASTZINFO(self))
-        return result;
-
-    /* We need to append the UTC offset. */
-    if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
-                         (PyObject *)self) < 0) {
-        Py_DECREF(result);
-        return NULL;
-    }
-    PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
-    return result;
-}
-
-static PyObject *
-datetime_ctime(PyDateTime_DateTime *self)
-{
-    return format_ctime((PyDateTime_Date *)self,
-                        DATE_GET_HOUR(self),
-                        DATE_GET_MINUTE(self),
-                        DATE_GET_SECOND(self));
-}
-
-/* Miscellaneous methods. */
-
-static PyObject *
-datetime_richcompare(PyObject *self, PyObject *other, int op)
-{
-    PyObject *result = NULL;
-    PyObject *offset1, *offset2;
-    int diff;
-
-    if (! PyDateTime_Check(other)) {
-        if (PyDate_Check(other)) {
-            /* Prevent invocation of date_richcompare.  We want to
-               return NotImplemented here to give the other object
-               a chance.  But since DateTime is a subclass of
-               Date, if the other object is a Date, it would
-               compute an ordering based on the date part alone,
-               and we don't want that.  So force unequal or
-               uncomparable here in that case. */
-            if (op == Py_EQ)
-                Py_RETURN_FALSE;
-            if (op == Py_NE)
-                Py_RETURN_TRUE;
-            return cmperror(self, other);
-        }
-        Py_RETURN_NOTIMPLEMENTED;
-    }
-
-    if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
-        diff = memcmp(((PyDateTime_DateTime *)self)->data,
-                      ((PyDateTime_DateTime *)other)->data,
-                      _PyDateTime_DATETIME_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-    offset1 = datetime_utcoffset(self, NULL);
-    if (offset1 == NULL)
-        return NULL;
-    offset2 = datetime_utcoffset(other, NULL);
-    if (offset2 == NULL)
-        goto done;
-    /* If they're both naive, or both aware and have the same offsets,
-     * we get off cheap.  Note that if they're both naive, offset1 ==
-     * offset2 == Py_None at this point.
-     */
-    if ((offset1 == offset2) ||
-        (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
-         delta_cmp(offset1, offset2) == 0)) {
-        diff = memcmp(((PyDateTime_DateTime *)self)->data,
-                      ((PyDateTime_DateTime *)other)->data,
-                      _PyDateTime_DATETIME_DATASIZE);
-        result = diff_to_bool(diff, op);
-    }
-    else if (offset1 != Py_None && offset2 != Py_None) {
-        PyDateTime_Delta *delta;
-
-        assert(offset1 != offset2); /* else last "if" handled it */
-        delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
-                                                       other);
-        if (delta == NULL)
-            goto done;
-        diff = GET_TD_DAYS(delta);
-        if (diff == 0)
-            diff = GET_TD_SECONDS(delta) |
-                   GET_TD_MICROSECONDS(delta);
-        Py_DECREF(delta);
-        result = diff_to_bool(diff, op);
-    }
-    else if (op == Py_EQ) {
-        result = Py_False;
-        Py_INCREF(result);
-    }
-    else if (op == Py_NE) {
-        result = Py_True;
-        Py_INCREF(result);
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "can't compare offset-naive and "
-                        "offset-aware datetimes");
-    }
- done:
-    Py_DECREF(offset1);
-    Py_XDECREF(offset2);
-    return result;
-}
-
-static Py_hash_t
-datetime_hash(PyDateTime_DateTime *self)
-{
-    if (self->hashcode == -1) {
-        PyObject *offset;
-
-        offset = datetime_utcoffset((PyObject *)self, NULL);
-
-        if (offset == NULL)
-            return -1;
-
-        /* Reduce this to a hash of another object. */
-        if (offset == Py_None)
-            self->hashcode = generic_hash(
-                (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
-        else {
-            PyObject *temp1, *temp2;
-            int days, seconds;
-
-            assert(HASTZINFO(self));
-            days = ymd_to_ord(GET_YEAR(self),
-                              GET_MONTH(self),
-                              GET_DAY(self));
-            seconds = DATE_GET_HOUR(self) * 3600 +
-                      DATE_GET_MINUTE(self) * 60 +
-                      DATE_GET_SECOND(self);
-            temp1 = new_delta(days, seconds,
-                              DATE_GET_MICROSECOND(self),
-                              1);
-            if (temp1 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            temp2 = delta_subtract(temp1, offset);
-            Py_DECREF(temp1);
-            if (temp2 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            self->hashcode = PyObject_Hash(temp2);
-            Py_DECREF(temp2);
-        }
-        Py_DECREF(offset);
-    }
-    return self->hashcode;
-}
-
-static PyObject *
-datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
-{
-    PyObject *clone;
-    PyObject *tuple;
-    int y = GET_YEAR(self);
-    int m = GET_MONTH(self);
-    int d = GET_DAY(self);
-    int hh = DATE_GET_HOUR(self);
-    int mm = DATE_GET_MINUTE(self);
-    int ss = DATE_GET_SECOND(self);
-    int us = DATE_GET_MICROSECOND(self);
-    PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
-                                      datetime_kws,
-                                      &y, &m, &d, &hh, &mm, &ss, &us,
-                                      &tzinfo))
-        return NULL;
-    tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
-    if (tuple == NULL)
-        return NULL;
-    clone = datetime_new(Py_TYPE(self), tuple, NULL);
-    Py_DECREF(tuple);
-    return clone;
-}
-
-static PyObject *
-local_timezone(PyDateTime_DateTime *utc_time)
-{
-    PyObject *result = NULL;
-    struct tm *timep;
-    time_t timestamp;
-    PyObject *delta;
-    PyObject *one_second;
-    PyObject *seconds;
-    PyObject *nameo = NULL;
-    const char *zone = NULL;
-
-    delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
-    if (delta == NULL)
-        return NULL;
-    one_second = new_delta(0, 1, 0, 0);
-    if (one_second == NULL)
-        goto error;
-    seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
-                                         (PyDateTime_Delta *)one_second);
-    Py_DECREF(one_second);
-    if (seconds == NULL)
-        goto error;
-    Py_DECREF(delta);
-    timestamp = PyLong_AsLong(seconds);
-    Py_DECREF(seconds);
-    if (timestamp == -1 && PyErr_Occurred())
-        return NULL;
-    timep = localtime(&timestamp);
-#ifdef HAVE_STRUCT_TM_TM_ZONE
-    zone = timep->tm_zone;
-    delta = new_delta(0, timep->tm_gmtoff, 0, 1);
-#else /* HAVE_STRUCT_TM_TM_ZONE */
-    {
-        PyObject *local_time;
-        local_time = new_datetime(timep->tm_year + 1900, timep->tm_mon + 1,
-                                  timep->tm_mday, timep->tm_hour, timep->tm_min,
-                                  timep->tm_sec, DATE_GET_MICROSECOND(utc_time),
-                                  utc_time->tzinfo);
-        if (local_time == NULL)
-            goto error;
-        delta = datetime_subtract(local_time, (PyObject*)utc_time);
-        /* XXX: before relying on tzname, we should compare delta
-           to the offset implied by timezone/altzone */
-        if (daylight && timep->tm_isdst >= 0)
-            zone = tzname[timep->tm_isdst % 2];
-        else
-            zone = tzname[0];
-        Py_DECREF(local_time);
-    }
-#endif /* HAVE_STRUCT_TM_TM_ZONE */
-    if (zone != NULL) {
-        nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
-        if (nameo == NULL)
-            goto error;
-    }
-    result = new_timezone(delta, nameo);
-    Py_XDECREF(nameo);
-  error:
-    Py_DECREF(delta);
-    return result;
-}
-
-static PyDateTime_DateTime *
-datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
-{
-    PyDateTime_DateTime *result;
-    PyObject *offset;
-    PyObject *temp;
-    PyObject *tzinfo = Py_None;
-    static char *keywords[] = {"tz", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
-                                      &tzinfo))
-        return NULL;
-
-    if (check_tzinfo_subclass(tzinfo) == -1)
-        return NULL;
-
-    if (!HASTZINFO(self) || self->tzinfo == Py_None)
-        goto NeedAware;
-
-    /* Conversion to self's own time zone is a NOP. */
-    if (self->tzinfo == tzinfo) {
-        Py_INCREF(self);
-        return self;
-    }
-
-    /* Convert self to UTC. */
-    offset = datetime_utcoffset((PyObject *)self, NULL);
-    if (offset == NULL)
-        return NULL;
-    if (offset == Py_None) {
-        Py_DECREF(offset);
-      NeedAware:
-        PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
-                        "a naive datetime");
-        return NULL;
-    }
-
-    /* result = self - offset */
-    result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
-                                       (PyDateTime_Delta *)offset, -1);
-    Py_DECREF(offset);
-    if (result == NULL)
-        return NULL;
-
-    /* Attach new tzinfo and let fromutc() do the rest. */
-    temp = result->tzinfo;
-    if (tzinfo == Py_None) {
-        tzinfo = local_timezone(result);
-        if (tzinfo == NULL) {
-            Py_DECREF(result);
-            return NULL;
-        }
-    }
-    else
-      Py_INCREF(tzinfo);
-    result->tzinfo = tzinfo;
-    Py_DECREF(temp);
-
-    temp = (PyObject *)result;
-    result = (PyDateTime_DateTime *)
-        _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
-    Py_DECREF(temp);
-
-    return result;
-}
-
-static PyObject *
-datetime_timetuple(PyDateTime_DateTime *self)
-{
-    int dstflag = -1;
-
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        PyObject * dst;
-
-        dst = call_dst(self->tzinfo, (PyObject *)self);
-        if (dst == NULL)
-            return NULL;
-
-        if (dst != Py_None)
-            dstflag = delta_bool((PyDateTime_Delta *)dst);
-        Py_DECREF(dst);
-    }
-    return build_struct_time(GET_YEAR(self),
-                             GET_MONTH(self),
-                             GET_DAY(self),
-                             DATE_GET_HOUR(self),
-                             DATE_GET_MINUTE(self),
-                             DATE_GET_SECOND(self),
-                             dstflag);
-}
-
-static PyObject *
-datetime_timestamp(PyDateTime_DateTime *self)
-{
-    PyObject *result;
-
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        PyObject *delta;
-        delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
-        if (delta == NULL)
-            return NULL;
-        result = delta_total_seconds(delta);
-        Py_DECREF(delta);
-    }
-    else {
-        struct tm time;
-        time_t timestamp;
-        memset((void *) &time, '\0', sizeof(struct tm));
-        time.tm_year = GET_YEAR(self) - 1900;
-        time.tm_mon = GET_MONTH(self) - 1;
-        time.tm_mday = GET_DAY(self);
-        time.tm_hour = DATE_GET_HOUR(self);
-        time.tm_min = DATE_GET_MINUTE(self);
-        time.tm_sec = DATE_GET_SECOND(self);
-        time.tm_wday = -1;
-        time.tm_isdst = -1;
-        timestamp = mktime(&time);
-        if (timestamp == (time_t)(-1)
-#ifndef _AIX
-            /* Return value of -1 does not necessarily mean an error,
-             * but tm_wday cannot remain set to -1 if mktime succeeded. */
-            && time.tm_wday == -1
-#else
-            /* on AIX, tm_wday is always sets, even on error */
-#endif
-          )
-        {
-            PyErr_SetString(PyExc_OverflowError,
-                            "timestamp out of range");
-            return NULL;
-        }
-        result = PyFloat_FromDouble(timestamp + DATE_GET_MICROSECOND(self) / 1e6);
-    }
-    return result;
-}
-
-static PyObject *
-datetime_getdate(PyDateTime_DateTime *self)
-{
-    return new_date(GET_YEAR(self),
-                    GET_MONTH(self),
-                    GET_DAY(self));
-}
-
-static PyObject *
-datetime_gettime(PyDateTime_DateTime *self)
-{
-    return new_time(DATE_GET_HOUR(self),
-                    DATE_GET_MINUTE(self),
-                    DATE_GET_SECOND(self),
-                    DATE_GET_MICROSECOND(self),
-                    Py_None);
-}
-
-static PyObject *
-datetime_gettimetz(PyDateTime_DateTime *self)
-{
-    return new_time(DATE_GET_HOUR(self),
-                    DATE_GET_MINUTE(self),
-                    DATE_GET_SECOND(self),
-                    DATE_GET_MICROSECOND(self),
-                    GET_DT_TZINFO(self));
-}
-
-static PyObject *
-datetime_utctimetuple(PyDateTime_DateTime *self)
-{
-    int y, m, d, hh, mm, ss;
-    PyObject *tzinfo;
-    PyDateTime_DateTime *utcself;
-
-    tzinfo = GET_DT_TZINFO(self);
-    if (tzinfo == Py_None) {
-        utcself = self;
-        Py_INCREF(utcself);
-    }
-    else {
-        PyObject *offset;
-        offset = call_utcoffset(tzinfo, (PyObject *)self);
-        if (offset == NULL)
-            return NULL;
-        if (offset == Py_None) {
-            Py_DECREF(offset);
-            utcself = self;
-            Py_INCREF(utcself);
-        }
-        else {
-            utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
-                                                (PyDateTime_Delta *)offset, -1);
-            Py_DECREF(offset);
-            if (utcself == NULL)
-                return NULL;
-        }
-    }
-    y = GET_YEAR(utcself);
-    m = GET_MONTH(utcself);
-    d = GET_DAY(utcself);
-    hh = DATE_GET_HOUR(utcself);
-    mm = DATE_GET_MINUTE(utcself);
-    ss = DATE_GET_SECOND(utcself);
-
-    Py_DECREF(utcself);
-    return build_struct_time(y, m, d, hh, mm, ss, 0);
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* Let basestate be the non-tzinfo data string.
- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
- * So it's a tuple in any (non-error) case.
- * __getstate__ isn't exposed.
- */
-static PyObject *
-datetime_getstate(PyDateTime_DateTime *self)
-{
-    PyObject *basestate;
-    PyObject *result = NULL;
-
-    basestate = PyBytes_FromStringAndSize((char *)self->data,
-                                           _PyDateTime_DATETIME_DATASIZE);
-    if (basestate != NULL) {
-        if (! HASTZINFO(self) || self->tzinfo == Py_None)
-            result = PyTuple_Pack(1, basestate);
-        else
-            result = PyTuple_Pack(2, basestate, self->tzinfo);
-        Py_DECREF(basestate);
-    }
-    return result;
-}
-
-static PyObject *
-datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
-{
-    return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
-}
-
-static PyMethodDef datetime_methods[] = {
-
-    /* Class methods: */
-
-    DATETIME_DATETIME_NOW_METHODDEF
-
-    {"utcnow",         (PyCFunction)datetime_utcnow,
-     METH_NOARGS | METH_CLASS,
-     PyDoc_STR("Return a new datetime representing UTC day and time.")},
-
-    {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,
-     PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
-
-    {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
-     METH_VARARGS | METH_CLASS,
-     PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
-
-    {"strptime", (PyCFunction)datetime_strptime,
-     METH_VARARGS | METH_CLASS,
-     PyDoc_STR("string, format -> new datetime parsed from a string "
-               "(like time.strptime()).")},
-
-    {"combine", (PyCFunction)datetime_combine,
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,
-     PyDoc_STR("date, time -> datetime with same date and time fields")},
-
-    /* Instance methods: */
-
-    {"date",   (PyCFunction)datetime_getdate, METH_NOARGS,
-     PyDoc_STR("Return date object with same year, month and day.")},
-
-    {"time",   (PyCFunction)datetime_gettime, METH_NOARGS,
-     PyDoc_STR("Return time object with same time but with tzinfo=None.")},
-
-    {"timetz",   (PyCFunction)datetime_gettimetz, METH_NOARGS,
-     PyDoc_STR("Return time object with same time and tzinfo.")},
-
-    {"ctime",       (PyCFunction)datetime_ctime,        METH_NOARGS,
-     PyDoc_STR("Return ctime() style string.")},
-
-    {"timetuple",   (PyCFunction)datetime_timetuple, METH_NOARGS,
-     PyDoc_STR("Return time tuple, compatible with time.localtime().")},
-
-    {"timestamp",   (PyCFunction)datetime_timestamp, METH_NOARGS,
-     PyDoc_STR("Return POSIX timestamp as float.")},
-
-    {"utctimetuple",   (PyCFunction)datetime_utctimetuple, METH_NOARGS,
-     PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
-
-    {"isoformat",   (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("[sep] -> string in ISO 8601 format, "
-               "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
-               "sep is used to separate the year from the time, and "
-               "defaults to 'T'.")},
-
-    {"utcoffset",       (PyCFunction)datetime_utcoffset, METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
-
-    {"tzname",          (PyCFunction)datetime_tzname,   METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.tzname(self).")},
-
-    {"dst",             (PyCFunction)datetime_dst, METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.dst(self).")},
-
-    {"replace",     (PyCFunction)datetime_replace,      METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("Return datetime with new specified fields.")},
-
-    {"astimezone",  (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
-
-    {"__reduce__", (PyCFunction)datetime_reduce,     METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL}
-};
-
-static char datetime_doc[] =
-PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
-\n\
-The year, month and day arguments are required. tzinfo may be None, or an\n\
-instance of a tzinfo subclass. The remaining arguments may be ints.\n");
-
-static PyNumberMethods datetime_as_number = {
-    datetime_add,                               /* nb_add */
-    datetime_subtract,                          /* nb_subtract */
-    0,                                          /* nb_multiply */
-    0,                                          /* nb_remainder */
-    0,                                          /* nb_divmod */
-    0,                                          /* nb_power */
-    0,                                          /* nb_negative */
-    0,                                          /* nb_positive */
-    0,                                          /* nb_absolute */
-    0,                                          /* nb_bool */
-};
-
-static PyTypeObject PyDateTime_DateTimeType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.datetime",                        /* tp_name */
-    sizeof(PyDateTime_DateTime),                /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    (destructor)datetime_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)datetime_repr,                    /* tp_repr */
-    &datetime_as_number,                        /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    (hashfunc)datetime_hash,                    /* tp_hash */
-    0,                                          /* tp_call */
-    (reprfunc)datetime_str,                     /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
-    datetime_doc,                               /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    datetime_richcompare,                       /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    0,                                          /* tp_iter */
-    0,                                          /* tp_iternext */
-    datetime_methods,                           /* tp_methods */
-    0,                                          /* tp_members */
-    datetime_getset,                            /* tp_getset */
-    &PyDateTime_DateType,                       /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    datetime_alloc,                             /* tp_alloc */
-    datetime_new,                               /* tp_new */
-    0,                                          /* tp_free */
-};
-
-/* ---------------------------------------------------------------------------
- * Module methods and initialization.
- */
-
-static PyMethodDef module_methods[] = {
-    {NULL, NULL}
-};
-
-/* C API.  Clients get at this via PyDateTime_IMPORT, defined in
- * datetime.h.
- */
-static PyDateTime_CAPI CAPI = {
-    &PyDateTime_DateType,
-    &PyDateTime_DateTimeType,
-    &PyDateTime_TimeType,
-    &PyDateTime_DeltaType,
-    &PyDateTime_TZInfoType,
-    new_date_ex,
-    new_datetime_ex,
-    new_time_ex,
-    new_delta_ex,
-    datetime_fromtimestamp,
-    date_fromtimestamp
-};
-
-
-
-static struct PyModuleDef datetimemodule = {
-    PyModuleDef_HEAD_INIT,
-    "_datetime",
-    "Fast implementation of the datetime type.",
-    -1,
-    module_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit__datetime(void)
-{
-    PyObject *m;        /* a module object */
-    PyObject *d;        /* its dict */
-    PyObject *x;
-    PyObject *delta;
-
-    m = PyModule_Create(&datetimemodule);
-    if (m == NULL)
-        return NULL;
-
-    if (PyType_Ready(&PyDateTime_DateType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_DeltaType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_TimeType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
-        return NULL;
-
-    /* timedelta values */
-    d = PyDateTime_DeltaType.tp_dict;
-
-    x = new_delta(0, 0, 1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* date values */
-    d = PyDateTime_DateType.tp_dict;
-
-    x = new_date(1, 1, 1);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_date(MAXYEAR, 12, 31);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(1, 0, 0, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* time values */
-    d = PyDateTime_TimeType.tp_dict;
-
-    x = new_time(0, 0, 0, 0, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_time(23, 59, 59, 999999, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(0, 0, 1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* datetime values */
-    d = PyDateTime_DateTimeType.tp_dict;
-
-    x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(0, 0, 1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* timezone values */
-    d = PyDateTime_TimeZoneType.tp_dict;
-
-    delta = new_delta(0, 0, 0, 0);
-    if (delta == NULL)
-        return NULL;
-    x = create_timezone(delta, NULL);
-    Py_DECREF(delta);
-    if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
-        return NULL;
-    PyDateTime_TimeZone_UTC = x;
-
-    delta = new_delta(-1, 60, 0, 1); /* -23:59 */
-    if (delta == NULL)
-        return NULL;
-    x = create_timezone(delta, NULL);
-    Py_DECREF(delta);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
-    if (delta == NULL)
-        return NULL;
-    x = create_timezone(delta, NULL);
-    Py_DECREF(delta);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* Epoch */
-    PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
-                                    PyDateTime_TimeZone_UTC);
-    if (PyDateTime_Epoch == NULL)
-      return NULL;
-
-    /* module initialization */
-    PyModule_AddIntMacro(m, MINYEAR);
-    PyModule_AddIntMacro(m, MAXYEAR);
-
-    Py_INCREF(&PyDateTime_DateType);
-    PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
-
-    Py_INCREF(&PyDateTime_DateTimeType);
-    PyModule_AddObject(m, "datetime",
-                       (PyObject *)&PyDateTime_DateTimeType);
-
-    Py_INCREF(&PyDateTime_TimeType);
-    PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
-
-    Py_INCREF(&PyDateTime_DeltaType);
-    PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
-
-    Py_INCREF(&PyDateTime_TZInfoType);
-    PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
-
-    Py_INCREF(&PyDateTime_TimeZoneType);
-    PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
-
-    x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
-    if (x == NULL)
-        return NULL;
-    PyModule_AddObject(m, "datetime_CAPI", x);
-
-    /* A 4-year cycle has an extra leap day over what we'd get from
-     * pasting together 4 single years.
-     */
-    assert(DI4Y == 4 * 365 + 1);
-    assert(DI4Y == days_before_year(4+1));
-
-    /* Similarly, a 400-year cycle has an extra leap day over what we'd
-     * get from pasting together 4 100-year cycles.
-     */
-    assert(DI400Y == 4 * DI100Y + 1);
-    assert(DI400Y == days_before_year(400+1));
-
-    /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
-     * pasting together 25 4-year cycles.
-     */
-    assert(DI100Y == 25 * DI4Y - 1);
-    assert(DI100Y == days_before_year(100+1));
-
-    one = PyLong_FromLong(1);
-    us_per_ms = PyLong_FromLong(1000);
-    us_per_second = PyLong_FromLong(1000000);
-    us_per_minute = PyLong_FromLong(60000000);
-    seconds_per_day = PyLong_FromLong(24 * 3600);
-    if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
-        us_per_minute == NULL || seconds_per_day == NULL)
-        return NULL;
-
-    /* The rest are too big for 32-bit ints, but even
-     * us_per_week fits in 40 bits, so doubles should be exact.
-     */
-    us_per_hour = PyLong_FromDouble(3600000000.0);
-    us_per_day = PyLong_FromDouble(86400000000.0);
-    us_per_week = PyLong_FromDouble(604800000000.0);
-    if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
-        return NULL;
-    return m;
-}
-
-/* ---------------------------------------------------------------------------
-Some time zone algebra.  For a datetime x, let
-    x.n = x stripped of its timezone -- its naive time.
-    x.o = x.utcoffset(), and assuming that doesn't raise an exception or
-      return None
-    x.d = x.dst(), and assuming that doesn't raise an exception or
-      return None
-    x.s = x's standard offset, x.o - x.d
-
-Now some derived rules, where k is a duration (timedelta).
-
-1. x.o = x.s + x.d
-   This follows from the definition of x.s.
-
-2. If x and y have the same tzinfo member, x.s = y.s.
-   This is actually a requirement, an assumption we need to make about
-   sane tzinfo classes.
-
-3. The naive UTC time corresponding to x is x.n - x.o.
-   This is again a requirement for a sane tzinfo class.
-
-4. (x+k).s = x.s
-   This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
-
-5. (x+k).n = x.n + k
-   Again follows from how arithmetic is defined.
-
-Now we can explain tz.fromutc(x).  Let's assume it's an interesting case
-(meaning that the various tzinfo methods exist, and don't blow up or return
-None when called).
-
-The function wants to return a datetime y with timezone tz, equivalent to x.
-x is already in UTC.
-
-By #3, we want
-
-    y.n - y.o = x.n                             [1]
-
-The algorithm starts by attaching tz to x.n, and calling that y.  So
-x.n = y.n at the start.  Then it wants to add a duration k to y, so that [1]
-becomes true; in effect, we want to solve [2] for k:
-
-   (y+k).n - (y+k).o = x.n                      [2]
-
-By #1, this is the same as
-
-   (y+k).n - ((y+k).s + (y+k).d) = x.n          [3]
-
-By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
-Substituting that into [3],
-
-   x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
-   k - (y+k).s - (y+k).d = 0; rearranging,
-   k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
-   k = y.s - (y+k).d
-
-On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
-approximate k by ignoring the (y+k).d term at first.  Note that k can't be
-very large, since all offset-returning methods return a duration of magnitude
-less than 24 hours.  For that reason, if y is firmly in std time, (y+k).d must
-be 0, so ignoring it has no consequence then.
-
-In any case, the new value is
-
-    z = y + y.s                                 [4]
-
-It's helpful to step back at look at [4] from a higher level:  it's simply
-mapping from UTC to tz's standard time.
-
-At this point, if
-
-    z.n - z.o = x.n                             [5]
-
-we have an equivalent time, and are almost done.  The insecurity here is
-at the start of daylight time.  Picture US Eastern for concreteness.  The wall
-time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
-sense then.  The docs ask that an Eastern tzinfo class consider such a time to
-be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
-on the day DST starts.  We want to return the 1:MM EST spelling because that's
-the only spelling that makes sense on the local wall clock.
-
-In fact, if [5] holds at this point, we do have the standard-time spelling,
-but that takes a bit of proof.  We first prove a stronger result.  What's the
-difference between the LHS and RHS of [5]?  Let
-
-    diff = x.n - (z.n - z.o)                    [6]
-
-Now
-    z.n =                       by [4]
-    (y + y.s).n =               by #5
-    y.n + y.s =                 since y.n = x.n
-    x.n + y.s =                 since z and y are have the same tzinfo member,
-                                    y.s = z.s by #2
-    x.n + z.s
-
-Plugging that back into [6] gives
-
-    diff =
-    x.n - ((x.n + z.s) - z.o) =     expanding
-    x.n - x.n - z.s + z.o =         cancelling
-    - z.s + z.o =                   by #2
-    z.d
-
-So diff = z.d.
-
-If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
-spelling we wanted in the endcase described above.  We're done.  Contrarily,
-if z.d = 0, then we have a UTC equivalent, and are also done.
-
-If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
-add to z (in effect, z is in tz's standard time, and we need to shift the
-local clock into tz's daylight time).
-
-Let
-
-    z' = z + z.d = z + diff                     [7]
-
-and we can again ask whether
-
-    z'.n - z'.o = x.n                           [8]
-
-If so, we're done.  If not, the tzinfo class is insane, according to the
-assumptions we've made.  This also requires a bit of proof.  As before, let's
-compute the difference between the LHS and RHS of [8] (and skipping some of
-the justifications for the kinds of substitutions we've done several times
-already):
-
-    diff' = x.n - (z'.n - z'.o) =           replacing z'.n via [7]
-        x.n  - (z.n + diff - z'.o) =    replacing diff via [6]
-        x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
-        x.n - z.n - x.n + z.n - z.o + z'.o =    cancel x.n
-        - z.n + z.n - z.o + z'.o =              cancel z.n
-        - z.o + z'.o =                      #1 twice
-        -z.s - z.d + z'.s + z'.d =          z and z' have same tzinfo
-        z'.d - z.d
-
-So z' is UTC-equivalent to x iff z'.d = z.d at this point.  If they are equal,
-we've found the UTC-equivalent so are done.  In fact, we stop with [7] and
-return z', not bothering to compute z'.d.
-
-How could z.d and z'd differ?  z' = z + z.d [7], so merely moving z' by
-a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
-would have to change the result dst() returns:  we start in DST, and moving
-a little further into it takes us out of DST.
-
-There isn't a sane case where this can happen.  The closest it gets is at
-the end of DST, where there's an hour in UTC with no spelling in a hybrid
-tzinfo class.  In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT.  During
-that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
-UTC) because the docs insist on that, but 0:MM is taken as being in daylight
-time (4:MM UTC).  There is no local time mapping to 5:MM UTC.  The local
-clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
-standard time.  Since that's what the local clock *does*, we want to map both
-UTC hours 5:MM and 6:MM to 1:MM Eastern.  The result is ambiguous
-in local time, but so it goes -- it's the way the local clock works.
-
-When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
-so z=0:MM.  z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
-z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
-(correctly) concludes that z' is not UTC-equivalent to x.
-
-Because we know z.d said z was in daylight time (else [5] would have held and
-we would have stopped then), and we know z.d != z'.d (else [8] would have held
-and we would have stopped then), and there are only 2 possible values dst() can
-return in Eastern, it follows that z'.d must be 0 (which it is in the example,
-but the reasoning doesn't depend on the example -- it depends on there being
-two possible dst() outcomes, one zero and the other non-zero).  Therefore
-z' must be in standard time, and is the spelling we want in this case.
-
-Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
-concerned (because it takes z' as being in standard time rather than the
-daylight time we intend here), but returning it gives the real-life "local
-clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
-tz.
-
-When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
-the 1:MM standard time spelling we want.
-
-So how can this break?  One of the assumptions must be violated.  Two
-possibilities:
-
-1) [2] effectively says that y.s is invariant across all y belong to a given
-   time zone.  This isn't true if, for political reasons or continental drift,
-   a region decides to change its base offset from UTC.
-
-2) There may be versions of "double daylight" time where the tail end of
-   the analysis gives up a step too early.  I haven't thought about that
-   enough to say.
-
-In any case, it's clear that the default fromutc() is strong enough to handle
-"almost all" time zones:  so long as the standard offset is invariant, it
-doesn't matter if daylight time transition points change from year to year, or
-if daylight time is skipped in some years; it doesn't matter how large or
-small dst() may get within its bounds; and it doesn't even matter if some
-perverse time zone returns a negative dst()).  So a breaking case must be
-pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
---------------------------------------------------------------------------- */
+/*[clinic end generated code: output=a5c51b96f10c462c input=a9049054013a1b77]*/
diff --git a/Modules/_dbmmodule.c b/Modules/clinic/_dbmmodule.c.h
copy from Modules/_dbmmodule.c
copy to Modules/clinic/_dbmmodule.c.h
--- a/Modules/_dbmmodule.c
+++ b/Modules/clinic/_dbmmodule.c.h
@@ -1,280 +1,5 @@
-
-/* DBM module using dictionary interface */
-
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-/* Some Linux systems install gdbm/ndbm.h, but not ndbm.h.  This supports
- * whichever configure was able to locate.
- */
-#if defined(HAVE_NDBM_H)
-#include <ndbm.h>
-static char *which_dbm = "GNU gdbm";  /* EMX port of GDBM */
-#elif defined(HAVE_GDBM_NDBM_H)
-#include <gdbm/ndbm.h>
-static char *which_dbm = "GNU gdbm";
-#elif defined(HAVE_GDBM_DASH_NDBM_H)
-#include <gdbm-ndbm.h>
-static char *which_dbm = "GNU gdbm";
-#elif defined(HAVE_BERKDB_H)
-#include <db.h>
-static char *which_dbm = "Berkeley DB";
-#else
-#error "No ndbm.h available!"
-#endif
-
 /*[clinic input]
-module dbm
-class dbm.dbm "dbmobject *" "&Dbmtype"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=92450564684a69a3]*/
-
-typedef struct {
-    PyObject_HEAD
-    int di_size;        /* -1 means recompute */
-    DBM *di_dbm;
-} dbmobject;
-
-static PyTypeObject Dbmtype;
-
-#define is_dbmobject(v) (Py_TYPE(v) == &Dbmtype)
-#define check_dbmobject_open(v) if ((v)->di_dbm == NULL) \
-               { PyErr_SetString(DbmError, "DBM object has already been closed"); \
-                 return NULL; }
-
-static PyObject *DbmError;
-
-/*[python input]
-class dbmobject_converter(self_converter):
-    type = "dbmobject *"
-    def pre_render(self):
-        super().pre_render()
-        self.name = 'dp'
-[python start generated code]*/
-/*[python end generated code: output=da39a3ee5e6b4b0d input=6ad536357913879a]*/
-
-static PyObject *
-newdbmobject(const char *file, int flags, int mode)
-{
-    dbmobject *dp;
-
-    dp = PyObject_New(dbmobject, &Dbmtype);
-    if (dp == NULL)
-        return NULL;
-    dp->di_size = -1;
-    /* See issue #19296 */
-    if ( (dp->di_dbm = dbm_open((char *)file, flags, mode)) == 0 ) {
-        PyErr_SetFromErrno(DbmError);
-        Py_DECREF(dp);
-        return NULL;
-    }
-    return (PyObject *)dp;
-}
-
-/* Methods */
-
-static void
-dbm_dealloc(dbmobject *dp)
-{
-    if ( dp->di_dbm )
-        dbm_close(dp->di_dbm);
-    PyObject_Del(dp);
-}
-
-static Py_ssize_t
-dbm_length(dbmobject *dp)
-{
-    if (dp->di_dbm == NULL) {
-             PyErr_SetString(DbmError, "DBM object has already been closed");
-             return -1;
-    }
-    if ( dp->di_size < 0 ) {
-        datum key;
-        int size;
-
-        size = 0;
-        for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
-              key = dbm_nextkey(dp->di_dbm))
-            size++;
-        dp->di_size = size;
-    }
-    return dp->di_size;
-}
-
-static PyObject *
-dbm_subscript(dbmobject *dp, PyObject *key)
-{
-    datum drec, krec;
-    Py_ssize_t tmp_size;
-
-    if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
-        return NULL;
-
-    krec.dsize = tmp_size;
-    check_dbmobject_open(dp);
-    drec = dbm_fetch(dp->di_dbm, krec);
-    if ( drec.dptr == 0 ) {
-        PyErr_SetObject(PyExc_KeyError, key);
-        return NULL;
-    }
-    if ( dbm_error(dp->di_dbm) ) {
-        dbm_clearerr(dp->di_dbm);
-        PyErr_SetString(DbmError, "");
-        return NULL;
-    }
-    return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
-}
-
-static int
-dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
-{
-    datum krec, drec;
-    Py_ssize_t tmp_size;
-
-    if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
-        PyErr_SetString(PyExc_TypeError,
-                        "dbm mappings have bytes or string keys only");
-        return -1;
-    }
-    krec.dsize = tmp_size;
-    if (dp->di_dbm == NULL) {
-             PyErr_SetString(DbmError, "DBM object has already been closed");
-             return -1;
-    }
-    dp->di_size = -1;
-    if (w == NULL) {
-        if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
-            dbm_clearerr(dp->di_dbm);
-            PyErr_SetObject(PyExc_KeyError, v);
-            return -1;
-        }
-    } else {
-        if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
-            PyErr_SetString(PyExc_TypeError,
-                 "dbm mappings have byte or string elements only");
-            return -1;
-        }
-        drec.dsize = tmp_size;
-        if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
-            dbm_clearerr(dp->di_dbm);
-            PyErr_SetString(DbmError,
-                            "cannot add item to database");
-            return -1;
-        }
-    }
-    if ( dbm_error(dp->di_dbm) ) {
-        dbm_clearerr(dp->di_dbm);
-        PyErr_SetString(DbmError, "");
-        return -1;
-    }
-    return 0;
-}
-
-static PyMappingMethods dbm_as_mapping = {
-    (lenfunc)dbm_length,                /*mp_length*/
-    (binaryfunc)dbm_subscript,          /*mp_subscript*/
-    (objobjargproc)dbm_ass_sub,         /*mp_ass_subscript*/
-};
-
-static PyObject *
-dbm__close(dbmobject *dp, PyObject *unused)
-{
-    if (dp->di_dbm)
-        dbm_close(dp->di_dbm);
-    dp->di_dbm = NULL;
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *
-dbm_keys(dbmobject *dp, PyObject *unused)
-{
-    PyObject *v, *item;
-    datum key;
-    int err;
-
-    check_dbmobject_open(dp);
-    v = PyList_New(0);
-    if (v == NULL)
-        return NULL;
-    for (key = dbm_firstkey(dp->di_dbm); key.dptr;
-         key = dbm_nextkey(dp->di_dbm)) {
-        item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
-        if (item == NULL) {
-            Py_DECREF(v);
-            return NULL;
-        }
-        err = PyList_Append(v, item);
-        Py_DECREF(item);
-        if (err != 0) {
-            Py_DECREF(v);
-            return NULL;
-        }
-    }
-    return v;
-}
-
-static int
-dbm_contains(PyObject *self, PyObject *arg)
-{
-    dbmobject *dp = (dbmobject *)self;
-    datum key, val;
-    Py_ssize_t size;
-
-    if ((dp)->di_dbm == NULL) {
-        PyErr_SetString(DbmError,
-                        "DBM object has already been closed");
-         return -1;
-    }
-    if (PyUnicode_Check(arg)) {
-        key.dptr = PyUnicode_AsUTF8AndSize(arg, &size);
-        key.dsize = size;
-        if (key.dptr == NULL)
-            return -1;
-    }
-    else if (!PyBytes_Check(arg)) {
-        PyErr_Format(PyExc_TypeError,
-                     "dbm key must be bytes or string, not %.100s",
-                     arg->ob_type->tp_name);
-        return -1;
-    }
-    else {
-        key.dptr = PyBytes_AS_STRING(arg);
-        key.dsize = PyBytes_GET_SIZE(arg);
-    }
-    val = dbm_fetch(dp->di_dbm, key);
-    return val.dptr != NULL;
-}
-
-static PySequenceMethods dbm_as_sequence = {
-    0,                          /* sq_length */
-    0,                          /* sq_concat */
-    0,                          /* sq_repeat */
-    0,                          /* sq_item */
-    0,                          /* sq_slice */
-    0,                          /* sq_ass_item */
-    0,                          /* sq_ass_slice */
-    dbm_contains,               /* sq_contains */
-    0,                          /* sq_inplace_concat */
-    0,                          /* sq_inplace_repeat */
-};
-
-/*[clinic input]
-
-dbm.dbm.get
-
-    self: dbmobject
-
-    key: str(length=True)
-    default: object = None
-    /
-
-Return the value for key if present, otherwise default.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(dbm_dbm_get__doc__,
@@ -307,148 +32,6 @@
     return return_value;
 }
 
-static PyObject *
-dbm_dbm_get_impl(dbmobject *dp, const char *key, Py_ssize_clean_t key_length, PyObject *default_value)
-/*[clinic end generated code: output=452ea11394e7e92d input=aecf5efd2f2b1a3b]*/
-{
-    datum dbm_key, val;
-
-    dbm_key.dptr = (char *)key;
-    dbm_key.dsize = key_length;
-    check_dbmobject_open(dp);
-    val = dbm_fetch(dp->di_dbm, dbm_key);
-    if (val.dptr != NULL)
-        return PyBytes_FromStringAndSize(val.dptr, val.dsize);
-
-    Py_INCREF(default_value);
-    return default_value;
-}
-
-static PyObject *
-dbm_setdefault(dbmobject *dp, PyObject *args)
-{
-    datum key, val;
-    PyObject *defvalue = NULL;
-    char *tmp_ptr;
-    Py_ssize_t tmp_size;
-
-    if (!PyArg_ParseTuple(args, "s#|O:setdefault",
-                          &tmp_ptr, &tmp_size, &defvalue))
-        return NULL;
-    key.dptr = tmp_ptr;
-    key.dsize = tmp_size;
-    check_dbmobject_open(dp);
-    val = dbm_fetch(dp->di_dbm, key);
-    if (val.dptr != NULL)
-        return PyBytes_FromStringAndSize(val.dptr, val.dsize);
-    if (defvalue == NULL) {
-        defvalue = PyBytes_FromStringAndSize(NULL, 0);
-        if (defvalue == NULL)
-            return NULL;
-        val.dptr = NULL;
-        val.dsize = 0;
-    }
-    else {
-        if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) {
-            PyErr_SetString(PyExc_TypeError,
-                "dbm mappings have byte string elements only");
-            return NULL;
-        }
-        val.dsize = tmp_size;
-        Py_INCREF(defvalue);
-    }
-    if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
-        dbm_clearerr(dp->di_dbm);
-        PyErr_SetString(DbmError, "cannot add item to database");
-        Py_DECREF(defvalue);
-        return NULL;
-    }
-    return defvalue;
-}
-
-static PyObject *
-dbm__enter__(PyObject *self, PyObject *args)
-{
-    Py_INCREF(self);
-    return self;
-}
-
-static PyObject *
-dbm__exit__(PyObject *self, PyObject *args)
-{
-    _Py_IDENTIFIER(close);
-    return _PyObject_CallMethodId(self, &PyId_close, NULL);
-}
-
-
-static PyMethodDef dbm_methods[] = {
-    {"close",           (PyCFunction)dbm__close,        METH_NOARGS,
-     "close()\nClose the database."},
-    {"keys",            (PyCFunction)dbm_keys,          METH_NOARGS,
-     "keys() -> list\nReturn a list of all keys in the database."},
-    DBM_DBM_GET_METHODDEF
-    {"setdefault",      (PyCFunction)dbm_setdefault,    METH_VARARGS,
-     "setdefault(key[, default]) -> value\n"
-     "Return the value for key if present, otherwise default.  If key\n"
-     "is not in the database, it is inserted with default as the value."},
-    {"__enter__", dbm__enter__, METH_NOARGS, NULL},
-    {"__exit__",  dbm__exit__, METH_VARARGS, NULL},
-    {NULL,              NULL}           /* sentinel */
-};
-
-static PyTypeObject Dbmtype = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_dbm.dbm",
-    sizeof(dbmobject),
-    0,
-    (destructor)dbm_dealloc,  /*tp_dealloc*/
-    0,                            /*tp_print*/
-    0,                        /*tp_getattr*/
-    0,                            /*tp_setattr*/
-    0,                            /*tp_reserved*/
-    0,                            /*tp_repr*/
-    0,                            /*tp_as_number*/
-    &dbm_as_sequence,             /*tp_as_sequence*/
-    &dbm_as_mapping,              /*tp_as_mapping*/
-    0,                    /*tp_hash*/
-    0,                    /*tp_call*/
-    0,                    /*tp_str*/
-    0,                    /*tp_getattro*/
-    0,                    /*tp_setattro*/
-    0,                    /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT,   /*tp_flags*/
-    0,                        /*tp_doc*/
-    0,                        /*tp_traverse*/
-    0,                        /*tp_clear*/
-    0,                        /*tp_richcompare*/
-    0,                        /*tp_weaklistoffset*/
-    0,                        /*tp_iter*/
-    0,                        /*tp_iternext*/
-    dbm_methods,          /*tp_methods*/
-};
-
-/* ----------------------------------------------------------------- */
-
-/*[clinic input]
-
-dbm.open as dbmopen
-
-    filename: str
-        The filename to open.
-
-    flags: str="r"
-        How to open the file.  "r" for reading, "w" for writing, etc.
-
-    mode: int(py_default="0o666") = 0o666
-        If creating a new file, the mode bits for the new file
-        (e.g. os.O_RDWR).
-
-    /
-
-Return a database object.
-
-[clinic start generated code]*/
-
 PyDoc_STRVAR(dbmopen__doc__,
 "open($module, filename, flags=\'r\', mode=0o666, /)\n"
 "--\n"
@@ -486,72 +69,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-dbmopen_impl(PyModuleDef *module, const char *filename, const char *flags, int mode)
-/*[clinic end generated code: output=9a7b725f9c4dcec2 input=6499ab0fab1333ac]*/
-{
-    int iflags;
-
-    if ( strcmp(flags, "r") == 0 )
-        iflags = O_RDONLY;
-    else if ( strcmp(flags, "w") == 0 )
-        iflags = O_RDWR;
-    else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
-        iflags = O_RDWR|O_CREAT;
-    else if ( strcmp(flags, "c") == 0 )
-        iflags = O_RDWR|O_CREAT;
-    else if ( strcmp(flags, "n") == 0 )
-        iflags = O_RDWR|O_CREAT|O_TRUNC;
-    else {
-        PyErr_SetString(DbmError,
-                        "arg 2 to open should be 'r', 'w', 'c', or 'n'");
-        return NULL;
-    }
-    return newdbmobject(filename, iflags, mode);
-}
-
-static PyMethodDef dbmmodule_methods[] = {
-    DBMOPEN_METHODDEF
-    { 0, 0 },
-};
-
-
-static struct PyModuleDef _dbmmodule = {
-    PyModuleDef_HEAD_INIT,
-    "_dbm",
-    NULL,
-    -1,
-    dbmmodule_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit__dbm(void) {
-    PyObject *m, *d, *s;
-
-    if (PyType_Ready(&Dbmtype) < 0)
-        return NULL;
-    m = PyModule_Create(&_dbmmodule);
-    if (m == NULL)
-        return NULL;
-    d = PyModule_GetDict(m);
-    if (DbmError == NULL)
-        DbmError = PyErr_NewException("_dbm.error",
-                                      PyExc_IOError, NULL);
-    s = PyUnicode_FromString(which_dbm);
-    if (s != NULL) {
-        PyDict_SetItemString(d, "library", s);
-        Py_DECREF(s);
-    }
-    if (DbmError != NULL)
-        PyDict_SetItemString(d, "error", DbmError);
-    if (PyErr_Occurred()) {
-        Py_DECREF(m);
-        m = NULL;
-    }
-    return m;
-}
+/*[clinic end generated code: output=78d62d1aa3ddd13c input=a9049054013a1b77]*/
diff --git a/Modules/_opcode.c b/Modules/clinic/_opcode.c.h
copy from Modules/_opcode.c
copy to Modules/clinic/_opcode.c.h
--- a/Modules/_opcode.c
+++ b/Modules/clinic/_opcode.c.h
@@ -1,20 +1,5 @@
-#include "Python.h"
-#include "opcode.h"
-
 /*[clinic input]
-module _opcode
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=117442e66eb376e6]*/
-
-/*[clinic input]
-
-_opcode.stack_effect -> int
-
-  opcode: int
-  oparg: object = None
-  /
-
-Compute the stack effect of the opcode.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(_opcode_stack_effect__doc__,
@@ -49,61 +34,4 @@
 exit:
     return return_value;
 }
-
-static int
-_opcode_stack_effect_impl(PyModuleDef *module, int opcode, PyObject *oparg)
-/*[clinic end generated code: output=9e1133f8d587bc67 input=2d0a9ee53c0418f5]*/
-{
-    int effect;
-    int oparg_int = 0;
-    if (HAS_ARG(opcode)) {
-        if (oparg == Py_None) {
-            PyErr_SetString(PyExc_ValueError,
-                    "stack_effect: opcode requires oparg but oparg was not specified");
-            return -1;
-        }
-        oparg_int = (int)PyLong_AsLong(oparg);
-        if ((oparg_int == -1) && PyErr_Occurred())
-            return -1;
-    }
-    else if (oparg != Py_None) {
-        PyErr_SetString(PyExc_ValueError,
-                "stack_effect: opcode does not permit oparg but oparg was specified");
-        return -1;
-    }
-    effect = PyCompile_OpcodeStackEffect(opcode, oparg_int);
-    if (effect == PY_INVALID_STACK_EFFECT) {
-            PyErr_SetString(PyExc_ValueError,
-                    "invalid opcode or oparg");
-            return -1;
-    }
-    return effect;
-}
-
-
-
-
-static PyMethodDef
-opcode_functions[] =  {
-    _OPCODE_STACK_EFFECT_METHODDEF
-    {NULL, NULL, 0, NULL}
-};
-
-
-static struct PyModuleDef opcodemodule = {
-    PyModuleDef_HEAD_INIT,
-    "_opcode",
-    "Opcode support module.",
-    -1,
-    opcode_functions,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit__opcode(void)
-{
-    return PyModule_Create(&opcodemodule);
-}
+/*[clinic end generated code: output=dbe45148bc21ecdf input=a9049054013a1b77]*/
diff --git a/Modules/_weakref.c b/Modules/clinic/_weakref.c.h
copy from Modules/_weakref.c
copy to Modules/clinic/_weakref.c.h
--- a/Modules/_weakref.c
+++ b/Modules/clinic/_weakref.c.h
@@ -1,22 +1,5 @@
-#include "Python.h"
-
-
-#define GET_WEAKREFS_LISTPTR(o) \
-        ((PyWeakReference **) PyObject_GET_WEAKREFS_LISTPTR(o))
-
 /*[clinic input]
-module _weakref
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ffec73b85846596d]*/
-
-/*[clinic input]
-
-_weakref.getweakrefcount -> Py_ssize_t
-
-  object: object
-  /
-
-Return the number of weak references to 'object'.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(_weakref_getweakrefcount__doc__,
@@ -45,114 +28,4 @@
 exit:
     return return_value;
 }
-
-static Py_ssize_t
-_weakref_getweakrefcount_impl(PyModuleDef *module, PyObject *object)
-/*[clinic end generated code: output=032eedbfd7d69e10 input=cedb69711b6a2507]*/
-{
-    PyWeakReference **list;
-
-    if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(object)))
-        return 0;
-
-    list = GET_WEAKREFS_LISTPTR(object);
-    return _PyWeakref_GetWeakrefCount(*list);
-}
-
-
-PyDoc_STRVAR(weakref_getweakrefs__doc__,
-"getweakrefs(object) -- return a list of all weak reference objects\n"
-"that point to 'object'.");
-
-static PyObject *
-weakref_getweakrefs(PyObject *self, PyObject *object)
-{
-    PyObject *result = NULL;
-
-    if (PyType_SUPPORTS_WEAKREFS(Py_TYPE(object))) {
-        PyWeakReference **list = GET_WEAKREFS_LISTPTR(object);
-        Py_ssize_t count = _PyWeakref_GetWeakrefCount(*list);
-
-        result = PyList_New(count);
-        if (result != NULL) {
-            PyWeakReference *current = *list;
-            Py_ssize_t i;
-            for (i = 0; i < count; ++i) {
-                PyList_SET_ITEM(result, i, (PyObject *) current);
-                Py_INCREF(current);
-                current = current->wr_next;
-            }
-        }
-    }
-    else {
-        result = PyList_New(0);
-    }
-    return result;
-}
-
-
-PyDoc_STRVAR(weakref_proxy__doc__,
-"proxy(object[, callback]) -- create a proxy object that weakly\n"
-"references 'object'.  'callback', if given, is called with a\n"
-"reference to the proxy when 'object' is about to be finalized.");
-
-static PyObject *
-weakref_proxy(PyObject *self, PyObject *args)
-{
-    PyObject *object;
-    PyObject *callback = NULL;
-    PyObject *result = NULL;
-
-    if (PyArg_UnpackTuple(args, "proxy", 1, 2, &object, &callback)) {
-        result = PyWeakref_NewProxy(object, callback);
-    }
-    return result;
-}
-
-
-static PyMethodDef
-weakref_functions[] =  {
-    _WEAKREF_GETWEAKREFCOUNT_METHODDEF
-    {"getweakrefs",     weakref_getweakrefs,            METH_O,
-     weakref_getweakrefs__doc__},
-    {"proxy",           weakref_proxy,                  METH_VARARGS,
-     weakref_proxy__doc__},
-    {NULL, NULL, 0, NULL}
-};
-
-
-static struct PyModuleDef weakrefmodule = {
-	PyModuleDef_HEAD_INIT,
-	"_weakref",
-	"Weak-reference support module.",
-	-1,
-	weakref_functions,
-	NULL,
-	NULL,
-	NULL,
-	NULL
-};
-
-PyMODINIT_FUNC
-PyInit__weakref(void)
-{
-    PyObject *m;
-
-    m = PyModule_Create(&weakrefmodule);
-
-    if (m != NULL) {
-        Py_INCREF(&_PyWeakref_RefType);
-        PyModule_AddObject(m, "ref",
-                           (PyObject *) &_PyWeakref_RefType);
-        Py_INCREF(&_PyWeakref_RefType);
-        PyModule_AddObject(m, "ReferenceType",
-                           (PyObject *) &_PyWeakref_RefType);
-        Py_INCREF(&_PyWeakref_ProxyType);
-        PyModule_AddObject(m, "ProxyType",
-                           (PyObject *) &_PyWeakref_ProxyType);
-        Py_INCREF(&_PyWeakref_CallableProxyType);
-        PyModule_AddObject(m, "CallableProxyType",
-                           (PyObject *) &_PyWeakref_CallableProxyType);
-    }
-    return m;
-}
+/*[clinic end generated code: output=4da9aade63eed77f input=a9049054013a1b77]*/
diff --git a/Modules/md5module.c b/Modules/clinic/md5module.c.h
copy from Modules/md5module.c
copy to Modules/clinic/md5module.c.h
--- a/Modules/md5module.c
+++ b/Modules/clinic/md5module.c.h
@@ -1,346 +1,5 @@
-/* MD5 module */
-
-/* This module provides an interface to the MD5 algorithm */
-
-/* See below for information about the original code this module was
-   based upon. Additional work performed by:
-
-   Andrew Kuchling (amk at amk.ca)
-   Greg Stein (gstein at lyra.org)
-   Trevor Perrin (trevp at trevp.net)
-
-   Copyright (C) 2005-2007   Gregory P. Smith (greg at krypto.org)
-   Licensed to PSF under a Contributor Agreement.
-
-*/
-
-/* MD5 objects */
-
-#include "Python.h"
-#include "hashlib.h"
-
 /*[clinic input]
-module _md5
-class MD5Type "MD5object *" "&PyType_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=6e5261719957a912]*/
-
-/* Some useful types */
-
-#if SIZEOF_INT == 4
-typedef unsigned int MD5_INT32; /* 32-bit integer */
-typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
-#else
-/* not defined. compilation will die. */
-#endif
-
-/* The MD5 block size and message digest sizes, in bytes */
-
-#define MD5_BLOCKSIZE    64
-#define MD5_DIGESTSIZE   16
-
-/* The structure for storing MD5 info */
-
-struct md5_state {
-    MD5_INT64 length;
-    MD5_INT32 state[4], curlen;
-    unsigned char buf[MD5_BLOCKSIZE];
-};
-
-typedef struct {
-    PyObject_HEAD
-
-    struct md5_state hash_state;
-} MD5object;
-
-
-/* ------------------------------------------------------------------------
- *
- * This code for the MD5 algorithm was noted as public domain. The
- * original headers are pasted below.
- *
- * Several changes have been made to make it more compatible with the
- * Python environment and desired interface.
- *
- */
-
-/* LibTomCrypt, modular cryptographic library -- Tom St Denis
- *
- * LibTomCrypt is a library that provides various cryptographic
- * algorithms in a highly modular and flexible manner.
- *
- * The library is free for all purposes without any express
- * guarantee it works.
- *
- * Tom St Denis, tomstdenis at gmail.com, http://libtom.org
- */
-
-/* rotate the hard way (platform optimizations could be done) */
-#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
-
-/* Endian Neutral macros that work on all platforms */
-
-#define STORE32L(x, y)                                                                     \
-     { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);   \
-       (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
-
-#define LOAD32L(x, y)                            \
-     { x = ((unsigned long)((y)[3] & 255)<<24) | \
-           ((unsigned long)((y)[2] & 255)<<16) | \
-           ((unsigned long)((y)[1] & 255)<<8)  | \
-           ((unsigned long)((y)[0] & 255)); }
-
-#define STORE64L(x, y)                                                                     \
-     { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255);   \
-       (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255);   \
-       (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);   \
-       (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
-
-
-/* MD5 macros */
-
-#define F(x,y,z)  (z ^ (x & (y ^ z)))
-#define G(x,y,z)  (y ^ (z & (y ^ x)))
-#define H(x,y,z)  (x^y^z)
-#define I(x,y,z)  (y^(x|(~z)))
-
-#define FF(a,b,c,d,M,s,t) \
-    a = (a + F(b,c,d) + M + t); a = ROLc(a, s) + b;
-
-#define GG(a,b,c,d,M,s,t) \
-    a = (a + G(b,c,d) + M + t); a = ROLc(a, s) + b;
-
-#define HH(a,b,c,d,M,s,t) \
-    a = (a + H(b,c,d) + M + t); a = ROLc(a, s) + b;
-
-#define II(a,b,c,d,M,s,t) \
-    a = (a + I(b,c,d) + M + t); a = ROLc(a, s) + b;
-
-
-static void md5_compress(struct md5_state *md5, unsigned char *buf)
-{
-    MD5_INT32 i, W[16], a, b, c, d;
-
-    assert(md5 != NULL);
-    assert(buf != NULL);
-
-    /* copy the state into 512-bits into W[0..15] */
-    for (i = 0; i < 16; i++) {
-        LOAD32L(W[i], buf + (4*i));
-    }
-
-    /* copy state */
-    a = md5->state[0];
-    b = md5->state[1];
-    c = md5->state[2];
-    d = md5->state[3];
-
-    FF(a,b,c,d,W[0],7,0xd76aa478UL)
-    FF(d,a,b,c,W[1],12,0xe8c7b756UL)
-    FF(c,d,a,b,W[2],17,0x242070dbUL)
-    FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
-    FF(a,b,c,d,W[4],7,0xf57c0fafUL)
-    FF(d,a,b,c,W[5],12,0x4787c62aUL)
-    FF(c,d,a,b,W[6],17,0xa8304613UL)
-    FF(b,c,d,a,W[7],22,0xfd469501UL)
-    FF(a,b,c,d,W[8],7,0x698098d8UL)
-    FF(d,a,b,c,W[9],12,0x8b44f7afUL)
-    FF(c,d,a,b,W[10],17,0xffff5bb1UL)
-    FF(b,c,d,a,W[11],22,0x895cd7beUL)
-    FF(a,b,c,d,W[12],7,0x6b901122UL)
-    FF(d,a,b,c,W[13],12,0xfd987193UL)
-    FF(c,d,a,b,W[14],17,0xa679438eUL)
-    FF(b,c,d,a,W[15],22,0x49b40821UL)
-    GG(a,b,c,d,W[1],5,0xf61e2562UL)
-    GG(d,a,b,c,W[6],9,0xc040b340UL)
-    GG(c,d,a,b,W[11],14,0x265e5a51UL)
-    GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
-    GG(a,b,c,d,W[5],5,0xd62f105dUL)
-    GG(d,a,b,c,W[10],9,0x02441453UL)
-    GG(c,d,a,b,W[15],14,0xd8a1e681UL)
-    GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
-    GG(a,b,c,d,W[9],5,0x21e1cde6UL)
-    GG(d,a,b,c,W[14],9,0xc33707d6UL)
-    GG(c,d,a,b,W[3],14,0xf4d50d87UL)
-    GG(b,c,d,a,W[8],20,0x455a14edUL)
-    GG(a,b,c,d,W[13],5,0xa9e3e905UL)
-    GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
-    GG(c,d,a,b,W[7],14,0x676f02d9UL)
-    GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
-    HH(a,b,c,d,W[5],4,0xfffa3942UL)
-    HH(d,a,b,c,W[8],11,0x8771f681UL)
-    HH(c,d,a,b,W[11],16,0x6d9d6122UL)
-    HH(b,c,d,a,W[14],23,0xfde5380cUL)
-    HH(a,b,c,d,W[1],4,0xa4beea44UL)
-    HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
-    HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
-    HH(b,c,d,a,W[10],23,0xbebfbc70UL)
-    HH(a,b,c,d,W[13],4,0x289b7ec6UL)
-    HH(d,a,b,c,W[0],11,0xeaa127faUL)
-    HH(c,d,a,b,W[3],16,0xd4ef3085UL)
-    HH(b,c,d,a,W[6],23,0x04881d05UL)
-    HH(a,b,c,d,W[9],4,0xd9d4d039UL)
-    HH(d,a,b,c,W[12],11,0xe6db99e5UL)
-    HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
-    HH(b,c,d,a,W[2],23,0xc4ac5665UL)
-    II(a,b,c,d,W[0],6,0xf4292244UL)
-    II(d,a,b,c,W[7],10,0x432aff97UL)
-    II(c,d,a,b,W[14],15,0xab9423a7UL)
-    II(b,c,d,a,W[5],21,0xfc93a039UL)
-    II(a,b,c,d,W[12],6,0x655b59c3UL)
-    II(d,a,b,c,W[3],10,0x8f0ccc92UL)
-    II(c,d,a,b,W[10],15,0xffeff47dUL)
-    II(b,c,d,a,W[1],21,0x85845dd1UL)
-    II(a,b,c,d,W[8],6,0x6fa87e4fUL)
-    II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
-    II(c,d,a,b,W[6],15,0xa3014314UL)
-    II(b,c,d,a,W[13],21,0x4e0811a1UL)
-    II(a,b,c,d,W[4],6,0xf7537e82UL)
-    II(d,a,b,c,W[11],10,0xbd3af235UL)
-    II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
-    II(b,c,d,a,W[9],21,0xeb86d391UL)
-
-    md5->state[0] = md5->state[0] + a;
-    md5->state[1] = md5->state[1] + b;
-    md5->state[2] = md5->state[2] + c;
-    md5->state[3] = md5->state[3] + d;
-}
-
-
-/**
-   Initialize the hash state
-   @param sha1   The hash state you wish to initialize
-*/
-static void
-md5_init(struct md5_state *md5)
-{
-    assert(md5 != NULL);
-    md5->state[0] = 0x67452301UL;
-    md5->state[1] = 0xefcdab89UL;
-    md5->state[2] = 0x98badcfeUL;
-    md5->state[3] = 0x10325476UL;
-    md5->curlen = 0;
-    md5->length = 0;
-}
-
-/**
-   Process a block of memory though the hash
-   @param sha1   The hash state
-   @param in     The data to hash
-   @param inlen  The length of the data (octets)
-*/
-static void
-md5_process(struct md5_state *md5, const unsigned char *in, Py_ssize_t inlen)
-{
-    Py_ssize_t n;
-
-    assert(md5 != NULL);
-    assert(in != NULL);
-    assert(md5->curlen <= sizeof(md5->buf));
-
-    while (inlen > 0) {
-        if (md5->curlen == 0 && inlen >= MD5_BLOCKSIZE) {
-           md5_compress(md5, (unsigned char *)in);
-           md5->length    += MD5_BLOCKSIZE * 8;
-           in             += MD5_BLOCKSIZE;
-           inlen          -= MD5_BLOCKSIZE;
-        } else {
-           n = Py_MIN(inlen, (Py_ssize_t)(MD5_BLOCKSIZE - md5->curlen));
-           memcpy(md5->buf + md5->curlen, in, (size_t)n);
-           md5->curlen    += (MD5_INT32)n;
-           in             += n;
-           inlen          -= n;
-           if (md5->curlen == MD5_BLOCKSIZE) {
-              md5_compress(md5, md5->buf);
-              md5->length += 8*MD5_BLOCKSIZE;
-              md5->curlen = 0;
-           }
-       }
-    }
-}
-
-/**
-   Terminate the hash to get the digest
-   @param sha1  The hash state
-   @param out [out] The destination of the hash (16 bytes)
-*/
-static void
-md5_done(struct md5_state *md5, unsigned char *out)
-{
-    int i;
-
-    assert(md5 != NULL);
-    assert(out != NULL);
-    assert(md5->curlen < sizeof(md5->buf));
-
-    /* increase the length of the message */
-    md5->length += md5->curlen * 8;
-
-    /* append the '1' bit */
-    md5->buf[md5->curlen++] = (unsigned char)0x80;
-
-    /* if the length is currently above 56 bytes we append zeros
-     * then compress.  Then we can fall back to padding zeros and length
-     * encoding like normal.
-     */
-    if (md5->curlen > 56) {
-        while (md5->curlen < 64) {
-            md5->buf[md5->curlen++] = (unsigned char)0;
-        }
-        md5_compress(md5, md5->buf);
-        md5->curlen = 0;
-    }
-
-    /* pad upto 56 bytes of zeroes */
-    while (md5->curlen < 56) {
-        md5->buf[md5->curlen++] = (unsigned char)0;
-    }
-
-    /* store length */
-    STORE64L(md5->length, md5->buf+56);
-    md5_compress(md5, md5->buf);
-
-    /* copy output */
-    for (i = 0; i < 4; i++) {
-        STORE32L(md5->state[i], out+(4*i));
-    }
-}
-
-/* .Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */
-/* .Revision: 1.10 $ */
-/* .Date: 2007/05/12 14:25:28 $ */
-
-/*
- * End of copied MD5 code.
- *
- * ------------------------------------------------------------------------
- */
-
-static PyTypeObject MD5type;
-
-
-static MD5object *
-newMD5object(void)
-{
-    return (MD5object *)PyObject_New(MD5object, &MD5type);
-}
-
-
-/* Internal methods for a hash object */
-
-static void
-MD5_dealloc(PyObject *ptr)
-{
-    PyObject_Del(ptr);
-}
-
-
-/* External methods for a hash object */
-
-/*[clinic input]
-MD5Type.copy
-
-Return a copy of the hash object.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(MD5Type_copy__doc__,
@@ -361,30 +20,6 @@
     return MD5Type_copy_impl(self);
 }
 
-static PyObject *
-MD5Type_copy_impl(MD5object *self)
-/*[clinic end generated code: output=3b3a88920b3dc7f4 input=2c09e6d2493f3079]*/
-{
-    MD5object *newobj;
-
-    if (Py_TYPE(self) == &MD5type) {
-        if ( (newobj = newMD5object())==NULL)
-            return NULL;
-    } else {
-        if ( (newobj = newMD5object())==NULL)
-            return NULL;
-    }
-
-    newobj->hash_state = self->hash_state;
-    return (PyObject *)newobj;
-}
-
-/*[clinic input]
-MD5Type.digest
-
-Return the digest value as a string of binary data.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(MD5Type_digest__doc__,
 "digest($self, /)\n"
 "--\n"
@@ -403,24 +38,6 @@
     return MD5Type_digest_impl(self);
 }
 
-static PyObject *
-MD5Type_digest_impl(MD5object *self)
-/*[clinic end generated code: output=7a796b28fa89485f input=7b96e65389412a34]*/
-{
-    unsigned char digest[MD5_DIGESTSIZE];
-    struct md5_state temp;
-
-    temp = self->hash_state;
-    md5_done(&temp, digest);
-    return PyBytes_FromStringAndSize((const char *)digest, MD5_DIGESTSIZE);
-}
-
-/*[clinic input]
-MD5Type.hexdigest
-
-Return the digest value as a string of hexadecimal digits.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(MD5Type_hexdigest__doc__,
 "hexdigest($self, /)\n"
 "--\n"
@@ -439,49 +56,6 @@
     return MD5Type_hexdigest_impl(self);
 }
 
-static PyObject *
-MD5Type_hexdigest_impl(MD5object *self)
-/*[clinic end generated code: output=daa73609f94f92e1 input=b60b19de644798dd]*/
-{
-    unsigned char digest[MD5_DIGESTSIZE];
-    struct md5_state temp;
-    PyObject *retval;
-    Py_UCS1 *hex_digest;
-    int i, j;
-
-    /* Get the raw (binary) digest value */
-    temp = self->hash_state;
-    md5_done(&temp, digest);
-
-    /* Create a new string */
-    retval = PyUnicode_New(MD5_DIGESTSIZE * 2, 127);
-    if (!retval)
-            return NULL;
-    hex_digest = PyUnicode_1BYTE_DATA(retval);
-
-    /* Make hex version of the digest */
-    for(i=j=0; i<MD5_DIGESTSIZE; i++) {
-        unsigned char c;
-        c = (digest[i] >> 4) & 0xf;
-        hex_digest[j++] = Py_hexdigits[c];
-        c = (digest[i] & 0xf);
-        hex_digest[j++] = Py_hexdigits[c];
-    }
-#ifdef Py_DEBUG
-    assert(_PyUnicode_CheckConsistency(retval, 1));
-#endif
-    return retval;
-}
-
-/*[clinic input]
-MD5Type.update
-
-    obj: object
-    /
-
-Update this hash object's state with the provided string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(MD5Type_update__doc__,
 "update($self, obj, /)\n"
 "--\n"
@@ -491,109 +65,6 @@
 #define MD5TYPE_UPDATE_METHODDEF    \
     {"update", (PyCFunction)MD5Type_update, METH_O, MD5Type_update__doc__},
 
-static PyObject *
-MD5Type_update(MD5object *self, PyObject *obj)
-/*[clinic end generated code: output=9d09b6c6cdc6cac3 input=6e1efcd9ecf17032]*/
-{
-    Py_buffer buf;
-
-    GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
-
-    md5_process(&self->hash_state, buf.buf, buf.len);
-
-    PyBuffer_Release(&buf);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyMethodDef MD5_methods[] = {
-    MD5TYPE_COPY_METHODDEF
-    MD5TYPE_DIGEST_METHODDEF
-    MD5TYPE_HEXDIGEST_METHODDEF
-    MD5TYPE_UPDATE_METHODDEF
-    {NULL,        NULL}         /* sentinel */
-};
-
-static PyObject *
-MD5_get_block_size(PyObject *self, void *closure)
-{
-    return PyLong_FromLong(MD5_BLOCKSIZE);
-}
-
-static PyObject *
-MD5_get_name(PyObject *self, void *closure)
-{
-    return PyUnicode_FromStringAndSize("md5", 3);
-}
-
-static PyObject *
-md5_get_digest_size(PyObject *self, void *closure)
-{
-    return PyLong_FromLong(MD5_DIGESTSIZE);
-}
-
-
-static PyGetSetDef MD5_getseters[] = {
-    {"block_size",
-     (getter)MD5_get_block_size, NULL,
-     NULL,
-     NULL},
-    {"name",
-     (getter)MD5_get_name, NULL,
-     NULL,
-     NULL},
-    {"digest_size",
-     (getter)md5_get_digest_size, NULL,
-     NULL,
-     NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyTypeObject MD5type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_md5.md5",         /*tp_name*/
-    sizeof(MD5object),  /*tp_size*/
-    0,                  /*tp_itemsize*/
-    /* methods */
-    MD5_dealloc,        /*tp_dealloc*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,                  /*tp_clear*/
-    0,                  /*tp_richcompare*/
-    0,                  /*tp_weaklistoffset*/
-    0,                  /*tp_iter*/
-    0,                  /*tp_iternext*/
-    MD5_methods,        /* tp_methods */
-    NULL,               /* tp_members */
-    MD5_getseters,      /* tp_getset */
-};
-
-
-/* The single module-level function: new() */
-
-/*[clinic input]
-_md5.md5
-
-    string: object(c_default="NULL") = b''
-
-Return a new MD5 hash object; optionally initialized with a string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(_md5_md5__doc__,
 "md5($module, /, string=b\'\')\n"
 "--\n"
@@ -622,79 +93,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-_md5_md5_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=1039e912d919880e input=d12ef8f72d684f7b]*/
-{
-    MD5object *new;
-    Py_buffer buf;
-
-    if (string)
-        GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
-
-    if ((new = newMD5object()) == NULL) {
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-
-    md5_init(&new->hash_state);
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-    if (string) {
-        md5_process(&new->hash_state, buf.buf, buf.len);
-        PyBuffer_Release(&buf);
-    }
-
-    return (PyObject *)new;
-}
-
-
-/* List of functions exported by this module */
-
-static struct PyMethodDef MD5_functions[] = {
-    _MD5_MD5_METHODDEF
-    {NULL,      NULL}            /* Sentinel */
-};
-
-
-/* Initialize this module. */
-
-#define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
-
-
-static struct PyModuleDef _md5module = {
-        PyModuleDef_HEAD_INIT,
-        "_md5",
-        NULL,
-        -1,
-        MD5_functions,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-PyInit__md5(void)
-{
-    PyObject *m;
-
-    Py_TYPE(&MD5type) = &PyType_Type;
-    if (PyType_Ready(&MD5type) < 0)
-        return NULL;
-
-    m = PyModule_Create(&_md5module);
-    if (m == NULL)
-        return NULL;
-
-    Py_INCREF((PyObject *)&MD5type);
-    PyModule_AddObject(m, "MD5Type", (PyObject *)&MD5type);
-    return m;
-}
+/*[clinic end generated code: output=f72618edfd35d984 input=a9049054013a1b77]*/
diff --git a/Modules/posixmodule.c b/Modules/clinic/posixmodule.c.h
copy from Modules/posixmodule.c
copy to Modules/clinic/posixmodule.c.h
--- a/Modules/posixmodule.c
+++ b/Modules/clinic/posixmodule.c.h
@@ -1,2473 +1,5 @@
-
-/* POSIX module implementation */
-
-/* This file is also used for Windows NT/MS-Win.  In that case the
-   module actually calls itself 'nt', not 'posix', and a few
-   functions are either unimplemented or implemented differently.  The source
-   assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
-   of the compiler used.  Different compilers define their own feature
-   test macro, e.g. '_MSC_VER'. */
-
-
-
-#ifdef __APPLE__
-   /*
-    * Step 1 of support for weak-linking a number of symbols existing on
-    * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
-    * at the end of this file for more information.
-    */
-#  pragma weak lchown
-#  pragma weak statvfs
-#  pragma weak fstatvfs
-
-#endif /* __APPLE__ */
-
-#define PY_SSIZE_T_CLEAN
-
-#include "Python.h"
-#include "structmember.h"
-#ifndef MS_WINDOWS
-#include "posixmodule.h"
-#else
-#include "winreparse.h"
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyDoc_STRVAR(posix__doc__,
-"This module provides access to operating system functionality that is\n\
-standardized by the C Standard and the POSIX standard (a thinly\n\
-disguised Unix interface).  Refer to the library manual and\n\
-corresponding Unix manual entries for more information on calls.");
-
-
-#ifdef HAVE_SYS_UIO_H
-#include <sys/uio.h>
-#endif
-
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif /* HAVE_SYS_TYPES_H */
-
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif /* HAVE_SYS_STAT_H */
-
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>           /* For WNOHANG */
-#endif
-
-#ifdef HAVE_SIGNAL_H
-#include <signal.h>
-#endif
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-
-#ifdef HAVE_GRP_H
-#include <grp.h>
-#endif
-
-#ifdef HAVE_SYSEXITS_H
-#include <sysexits.h>
-#endif /* HAVE_SYSEXITS_H */
-
-#ifdef HAVE_SYS_LOADAVG_H
-#include <sys/loadavg.h>
-#endif
-
-#ifdef HAVE_LANGINFO_H
-#include <langinfo.h>
-#endif
-
-#ifdef HAVE_SYS_SENDFILE_H
-#include <sys/sendfile.h>
-#endif
-
-#ifdef HAVE_SCHED_H
-#include <sched.h>
-#endif
-
-#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
-#undef HAVE_SCHED_SETAFFINITY
-#endif
-
-#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
-#define USE_XATTRS
-#endif
-
-#ifdef USE_XATTRS
-#include <sys/xattr.h>
-#endif
-
-#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#endif
-
-#ifdef HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#ifdef __hpux
-#include <sys/mpctl.h>
-#endif
-
-#if defined(__DragonFly__) || \
-    defined(__OpenBSD__)   || \
-    defined(__FreeBSD__)   || \
-    defined(__NetBSD__)    || \
-    defined(__APPLE__)
-#include <sys/sysctl.h>
-#endif
-
-#if defined(MS_WINDOWS)
-#  define TERMSIZE_USE_CONIO
-#elif defined(HAVE_SYS_IOCTL_H)
-#  include <sys/ioctl.h>
-#  if defined(HAVE_TERMIOS_H)
-#    include <termios.h>
-#  endif
-#  if defined(TIOCGWINSZ)
-#    define TERMSIZE_USE_IOCTL
-#  endif
-#endif /* MS_WINDOWS */
-
-/* Various compilers have only certain posix functions */
-/* XXX Gosh I wish these were all moved into pyconfig.h */
-#if defined(__WATCOMC__) && !defined(__QNX__)           /* Watcom compiler */
-#define HAVE_OPENDIR    1
-#define HAVE_SYSTEM     1
-#include <process.h>
-#else
-#ifdef _MSC_VER         /* Microsoft compiler */
-#define HAVE_GETPPID    1
-#define HAVE_GETLOGIN   1
-#define HAVE_SPAWNV     1
-#define HAVE_EXECV      1
-#define HAVE_PIPE       1
-#define HAVE_SYSTEM     1
-#define HAVE_CWAIT      1
-#define HAVE_FSYNC      1
-#define fsync _commit
-#else
-/* Unix functions that the configure script doesn't check for */
-#define HAVE_EXECV      1
-#define HAVE_FORK       1
-#if defined(__USLC__) && defined(__SCO_VERSION__)       /* SCO UDK Compiler */
-#define HAVE_FORK1      1
-#endif
-#define HAVE_GETEGID    1
-#define HAVE_GETEUID    1
-#define HAVE_GETGID     1
-#define HAVE_GETPPID    1
-#define HAVE_GETUID     1
-#define HAVE_KILL       1
-#define HAVE_OPENDIR    1
-#define HAVE_PIPE       1
-#define HAVE_SYSTEM     1
-#define HAVE_WAIT       1
-#define HAVE_TTYNAME    1
-#endif  /* _MSC_VER */
-#endif  /* ! __WATCOMC__ || __QNX__ */
-
-
 /*[clinic input]
-# one of the few times we lie about this name!
-module os
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
-
-#ifndef _MSC_VER
-
-#if defined(__sgi)&&_COMPILER_VERSION>=700
-/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
-   (default) */
-extern char        *ctermid_r(char *);
-#endif
-
-#ifndef HAVE_UNISTD_H
-#if defined(PYCC_VACPP)
-extern int mkdir(char *);
-#else
-#if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
-extern int mkdir(const char *);
-#else
-extern int mkdir(const char *, mode_t);
-#endif
-#endif
-#if defined(__IBMC__) || defined(__IBMCPP__)
-extern int chdir(char *);
-extern int rmdir(char *);
-#else
-extern int chdir(const char *);
-extern int rmdir(const char *);
-#endif
-extern int chmod(const char *, mode_t);
-/*#ifdef HAVE_FCHMOD
-extern int fchmod(int, mode_t);
-#endif*/
-/*#ifdef HAVE_LCHMOD
-extern int lchmod(const char *, mode_t);
-#endif*/
-extern int chown(const char *, uid_t, gid_t);
-extern char *getcwd(char *, int);
-extern char *strerror(int);
-extern int link(const char *, const char *);
-extern int rename(const char *, const char *);
-extern int stat(const char *, struct stat *);
-extern int unlink(const char *);
-#ifdef HAVE_SYMLINK
-extern int symlink(const char *, const char *);
-#endif /* HAVE_SYMLINK */
-#ifdef HAVE_LSTAT
-extern int lstat(const char *, struct stat *);
-#endif /* HAVE_LSTAT */
-#endif /* !HAVE_UNISTD_H */
-
-#endif /* !_MSC_VER */
-
-#ifdef HAVE_UTIME_H
-#include <utime.h>
-#endif /* HAVE_UTIME_H */
-
-#ifdef HAVE_SYS_UTIME_H
-#include <sys/utime.h>
-#define HAVE_UTIME_H /* pretend we do for the rest of this file */
-#endif /* HAVE_SYS_UTIME_H */
-
-#ifdef HAVE_SYS_TIMES_H
-#include <sys/times.h>
-#endif /* HAVE_SYS_TIMES_H */
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif /* HAVE_SYS_PARAM_H */
-
-#ifdef HAVE_SYS_UTSNAME_H
-#include <sys/utsname.h>
-#endif /* HAVE_SYS_UTSNAME_H */
-
-#ifdef HAVE_DIRENT_H
-#include <dirent.h>
-#define NAMLEN(dirent) strlen((dirent)->d_name)
-#else
-#if defined(__WATCOMC__) && !defined(__QNX__)
-#include <direct.h>
-#define NAMLEN(dirent) strlen((dirent)->d_name)
-#else
-#define dirent direct
-#define NAMLEN(dirent) (dirent)->d_namlen
-#endif
-#ifdef HAVE_SYS_NDIR_H
-#include <sys/ndir.h>
-#endif
-#ifdef HAVE_SYS_DIR_H
-#include <sys/dir.h>
-#endif
-#ifdef HAVE_NDIR_H
-#include <ndir.h>
-#endif
-#endif
-
-#ifdef _MSC_VER
-#ifdef HAVE_DIRECT_H
-#include <direct.h>
-#endif
-#ifdef HAVE_IO_H
-#include <io.h>
-#endif
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-#ifndef VOLUME_NAME_DOS
-#define VOLUME_NAME_DOS 0x0
-#endif
-#ifndef VOLUME_NAME_NT
-#define VOLUME_NAME_NT  0x2
-#endif
-#ifndef IO_REPARSE_TAG_SYMLINK
-#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
-#endif
-#ifndef IO_REPARSE_TAG_MOUNT_POINT
-#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
-#endif
-#include "osdefs.h"
-#include <malloc.h>
-#include <windows.h>
-#include <shellapi.h>   /* for ShellExecute() */
-#include <lmcons.h>     /* for UNLEN */
-#ifdef SE_CREATE_SYMBOLIC_LINK_NAME /* Available starting with Vista */
-#define HAVE_SYMLINK
-static int win32_can_symlink = 0;
-#endif
-#endif /* _MSC_VER */
-
-#ifndef MAXPATHLEN
-#if defined(PATH_MAX) && PATH_MAX > 1024
-#define MAXPATHLEN PATH_MAX
-#else
-#define MAXPATHLEN 1024
-#endif
-#endif /* MAXPATHLEN */
-
-#ifdef UNION_WAIT
-/* Emulate some macros on systems that have a union instead of macros */
-
-#ifndef WIFEXITED
-#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
-#endif
-
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
-#endif
-
-#ifndef WTERMSIG
-#define WTERMSIG(u_wait) ((u_wait).w_termsig)
-#endif
-
-#define WAIT_TYPE union wait
-#define WAIT_STATUS_INT(s) (s.w_status)
-
-#else /* !UNION_WAIT */
-#define WAIT_TYPE int
-#define WAIT_STATUS_INT(s) (s)
-#endif /* UNION_WAIT */
-
-/* Don't use the "_r" form if we don't need it (also, won't have a
-   prototype for it, at least on Solaris -- maybe others as well?). */
-#if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
-#define USE_CTERMID_R
-#endif
-
-/* choose the appropriate stat and fstat functions and return structs */
-#undef STAT
-#undef FSTAT
-#undef STRUCT_STAT
-#ifdef MS_WINDOWS
-#       define STAT win32_stat
-#       define LSTAT win32_lstat
-#       define FSTAT _Py_fstat_noraise
-#       define STRUCT_STAT struct _Py_stat_struct
-#else
-#       define STAT stat
-#       define LSTAT lstat
-#       define FSTAT fstat
-#       define STRUCT_STAT struct stat
-#endif
-
-#if defined(MAJOR_IN_MKDEV)
-#include <sys/mkdev.h>
-#else
-#if defined(MAJOR_IN_SYSMACROS)
-#include <sys/sysmacros.h>
-#endif
-#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
-#include <sys/mkdev.h>
-#endif
-#endif
-
-#define DWORD_MAX 4294967295U
-
-#ifdef MS_WINDOWS
-#define INITFUNC PyInit_nt
-#define MODNAME "nt"
-#else
-#define INITFUNC PyInit_posix
-#define MODNAME "posix"
-#endif
-
-#ifdef MS_WINDOWS
-/* defined in fileutils.c */
-PyAPI_FUNC(void) _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
-PyAPI_FUNC(void) _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
-                                            ULONG, struct _Py_stat_struct *);
-#endif
-
-#ifdef MS_WINDOWS
-static int
-win32_warn_bytes_api()
-{
-    return PyErr_WarnEx(PyExc_DeprecationWarning,
-        "The Windows bytes API has been deprecated, "
-        "use Unicode filenames instead",
-        1);
-}
-#endif
-
-
-#ifndef MS_WINDOWS
-PyObject *
-_PyLong_FromUid(uid_t uid)
-{
-    if (uid == (uid_t)-1)
-        return PyLong_FromLong(-1);
-    return PyLong_FromUnsignedLong(uid);
-}
-
-PyObject *
-_PyLong_FromGid(gid_t gid)
-{
-    if (gid == (gid_t)-1)
-        return PyLong_FromLong(-1);
-    return PyLong_FromUnsignedLong(gid);
-}
-
-int
-_Py_Uid_Converter(PyObject *obj, void *p)
-{
-    uid_t uid;
-    PyObject *index;
-    int overflow;
-    long result;
-    unsigned long uresult;
-
-    index = PyNumber_Index(obj);
-    if (index == NULL) {
-        PyErr_Format(PyExc_TypeError,
-                     "uid should be integer, not %.200s",
-                     Py_TYPE(obj)->tp_name);
-        return 0;
-    }
-
-    /*
-     * Handling uid_t is complicated for two reasons:
-     *  * Although uid_t is (always?) unsigned, it still
-     *    accepts -1.
-     *  * We don't know its size in advance--it may be
-     *    bigger than an int, or it may be smaller than
-     *    a long.
-     *
-     * So a bit of defensive programming is in order.
-     * Start with interpreting the value passed
-     * in as a signed long and see if it works.
-     */
-
-    result = PyLong_AsLongAndOverflow(index, &overflow);
-
-    if (!overflow) {
-        uid = (uid_t)result;
-
-        if (result == -1) {
-            if (PyErr_Occurred())
-                goto fail;
-            /* It's a legitimate -1, we're done. */
-            goto success;
-        }
-
-        /* Any other negative number is disallowed. */
-        if (result < 0)
-            goto underflow;
-
-        /* Ensure the value wasn't truncated. */
-        if (sizeof(uid_t) < sizeof(long) &&
-            (long)uid != result)
-            goto underflow;
-        goto success;
-    }
-
-    if (overflow < 0)
-        goto underflow;
-
-    /*
-     * Okay, the value overflowed a signed long.  If it
-     * fits in an *unsigned* long, it may still be okay,
-     * as uid_t may be unsigned long on this platform.
-     */
-    uresult = PyLong_AsUnsignedLong(index);
-    if (PyErr_Occurred()) {
-        if (PyErr_ExceptionMatches(PyExc_OverflowError))
-            goto overflow;
-        goto fail;
-    }
-
-    uid = (uid_t)uresult;
-
-    /*
-     * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
-     * but this value would get interpreted as (uid_t)-1  by chown
-     * and its siblings.   That's not what the user meant!  So we
-     * throw an overflow exception instead.   (We already
-     * handled a real -1 with PyLong_AsLongAndOverflow() above.)
-     */
-    if (uid == (uid_t)-1)
-        goto overflow;
-
-    /* Ensure the value wasn't truncated. */
-    if (sizeof(uid_t) < sizeof(long) &&
-        (unsigned long)uid != uresult)
-        goto overflow;
-    /* fallthrough */
-
-success:
-    Py_DECREF(index);
-    *(uid_t *)p = uid;
-    return 1;
-
-underflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "uid is less than minimum");
-    goto fail;
-
-overflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "uid is greater than maximum");
-    /* fallthrough */
-
-fail:
-    Py_DECREF(index);
-    return 0;
-}
-
-int
-_Py_Gid_Converter(PyObject *obj, void *p)
-{
-    gid_t gid;
-    PyObject *index;
-    int overflow;
-    long result;
-    unsigned long uresult;
-
-    index = PyNumber_Index(obj);
-    if (index == NULL) {
-        PyErr_Format(PyExc_TypeError,
-                     "gid should be integer, not %.200s",
-                     Py_TYPE(obj)->tp_name);
-        return 0;
-    }
-
-    /*
-     * Handling gid_t is complicated for two reasons:
-     *  * Although gid_t is (always?) unsigned, it still
-     *    accepts -1.
-     *  * We don't know its size in advance--it may be
-     *    bigger than an int, or it may be smaller than
-     *    a long.
-     *
-     * So a bit of defensive programming is in order.
-     * Start with interpreting the value passed
-     * in as a signed long and see if it works.
-     */
-
-    result = PyLong_AsLongAndOverflow(index, &overflow);
-
-    if (!overflow) {
-        gid = (gid_t)result;
-
-        if (result == -1) {
-            if (PyErr_Occurred())
-                goto fail;
-            /* It's a legitimate -1, we're done. */
-            goto success;
-        }
-
-        /* Any other negative number is disallowed. */
-        if (result < 0) {
-            goto underflow;
-        }
-
-        /* Ensure the value wasn't truncated. */
-        if (sizeof(gid_t) < sizeof(long) &&
-            (long)gid != result)
-            goto underflow;
-        goto success;
-    }
-
-    if (overflow < 0)
-        goto underflow;
-
-    /*
-     * Okay, the value overflowed a signed long.  If it
-     * fits in an *unsigned* long, it may still be okay,
-     * as gid_t may be unsigned long on this platform.
-     */
-    uresult = PyLong_AsUnsignedLong(index);
-    if (PyErr_Occurred()) {
-        if (PyErr_ExceptionMatches(PyExc_OverflowError))
-            goto overflow;
-        goto fail;
-    }
-
-    gid = (gid_t)uresult;
-
-    /*
-     * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
-     * but this value would get interpreted as (gid_t)-1  by chown
-     * and its siblings.   That's not what the user meant!  So we
-     * throw an overflow exception instead.   (We already
-     * handled a real -1 with PyLong_AsLongAndOverflow() above.)
-     */
-    if (gid == (gid_t)-1)
-        goto overflow;
-
-    /* Ensure the value wasn't truncated. */
-    if (sizeof(gid_t) < sizeof(long) &&
-        (unsigned long)gid != uresult)
-        goto overflow;
-    /* fallthrough */
-
-success:
-    Py_DECREF(index);
-    *(gid_t *)p = gid;
-    return 1;
-
-underflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "gid is less than minimum");
-    goto fail;
-
-overflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "gid is greater than maximum");
-    /* fallthrough */
-
-fail:
-    Py_DECREF(index);
-    return 0;
-}
-#endif /* MS_WINDOWS */
-
-
-#ifdef HAVE_LONG_LONG
-#  define _PyLong_FromDev PyLong_FromLongLong
-#else
-#  define _PyLong_FromDev PyLong_FromLong
-#endif
-
-
-#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
-static int
-_Py_Dev_Converter(PyObject *obj, void *p)
-{
-#ifdef HAVE_LONG_LONG
-    *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
-#else
-    *((dev_t *)p) = PyLong_AsUnsignedLong(obj);
-#endif
-    if (PyErr_Occurred())
-        return 0;
-    return 1;
-}
-#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
-
-
-#ifdef AT_FDCWD
-/*
- * Why the (int) cast?  Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
- * without the int cast, the value gets interpreted as uint (4291925331),
- * which doesn't play nicely with all the initializer lines in this file that
- * look like this:
- *      int dir_fd = DEFAULT_DIR_FD;
- */
-#define DEFAULT_DIR_FD (int)AT_FDCWD
-#else
-#define DEFAULT_DIR_FD (-100)
-#endif
-
-static int
-_fd_converter(PyObject *o, int *p, const char *allowed)
-{
-    int overflow;
-    long long_value;
-
-    PyObject *index = PyNumber_Index(o);
-    if (index == NULL) {
-        PyErr_Format(PyExc_TypeError,
-                     "argument should be %s, not %.200s",
-                     allowed, Py_TYPE(o)->tp_name);
-        return 0;
-    }
-
-    long_value = PyLong_AsLongAndOverflow(index, &overflow);
-    Py_DECREF(index);
-    if (overflow > 0 || long_value > INT_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "fd is greater than maximum");
-        return 0;
-    }
-    if (overflow < 0 || long_value < INT_MIN) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "fd is less than minimum");
-        return 0;
-    }
-
-    *p = (int)long_value;
-    return 1;
-}
-
-static int
-dir_fd_converter(PyObject *o, void *p)
-{
-    if (o == Py_None) {
-        *(int *)p = DEFAULT_DIR_FD;
-        return 1;
-    }
-    return _fd_converter(o, (int *)p, "integer");
-}
-
-
-/*
- * A PyArg_ParseTuple "converter" function
- * that handles filesystem paths in the manner
- * preferred by the os module.
- *
- * path_converter accepts (Unicode) strings and their
- * subclasses, and bytes and their subclasses.  What
- * it does with the argument depends on the platform:
- *
- *   * On Windows, if we get a (Unicode) string we
- *     extract the wchar_t * and return it; if we get
- *     bytes we extract the char * and return that.
- *
- *   * On all other platforms, strings are encoded
- *     to bytes using PyUnicode_FSConverter, then we
- *     extract the char * from the bytes object and
- *     return that.
- *
- * path_converter also optionally accepts signed
- * integers (representing open file descriptors) instead
- * of path strings.
- *
- * Input fields:
- *   path.nullable
- *     If nonzero, the path is permitted to be None.
- *   path.allow_fd
- *     If nonzero, the path is permitted to be a file handle
- *     (a signed int) instead of a string.
- *   path.function_name
- *     If non-NULL, path_converter will use that as the name
- *     of the function in error messages.
- *     (If path.function_name is NULL it omits the function name.)
- *   path.argument_name
- *     If non-NULL, path_converter will use that as the name
- *     of the parameter in error messages.
- *     (If path.argument_name is NULL it uses "path".)
- *
- * Output fields:
- *   path.wide
- *     Points to the path if it was expressed as Unicode
- *     and was not encoded.  (Only used on Windows.)
- *   path.narrow
- *     Points to the path if it was expressed as bytes,
- *     or it was Unicode and was encoded to bytes.
- *   path.fd
- *     Contains a file descriptor if path.accept_fd was true
- *     and the caller provided a signed integer instead of any
- *     sort of string.
- *
- *     WARNING: if your "path" parameter is optional, and is
- *     unspecified, path_converter will never get called.
- *     So if you set allow_fd, you *MUST* initialize path.fd = -1
- *     yourself!
- *   path.length
- *     The length of the path in characters, if specified as
- *     a string.
- *   path.object
- *     The original object passed in.
- *   path.cleanup
- *     For internal use only.  May point to a temporary object.
- *     (Pay no attention to the man behind the curtain.)
- *
- *   At most one of path.wide or path.narrow will be non-NULL.
- *   If path was None and path.nullable was set,
- *     or if path was an integer and path.allow_fd was set,
- *     both path.wide and path.narrow will be NULL
- *     and path.length will be 0.
- *
- *   path_converter takes care to not write to the path_t
- *   unless it's successful.  However it must reset the
- *   "cleanup" field each time it's called.
- *
- * Use as follows:
- *      path_t path;
- *      memset(&path, 0, sizeof(path));
- *      PyArg_ParseTuple(args, "O&", path_converter, &path);
- *      // ... use values from path ...
- *      path_cleanup(&path);
- *
- * (Note that if PyArg_Parse fails you don't need to call
- * path_cleanup().  However it is safe to do so.)
- */
-typedef struct {
-    const char *function_name;
-    const char *argument_name;
-    int nullable;
-    int allow_fd;
-    wchar_t *wide;
-    char *narrow;
-    int fd;
-    Py_ssize_t length;
-    PyObject *object;
-    PyObject *cleanup;
-} path_t;
-
-#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
-    {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
-
-static void
-path_cleanup(path_t *path) {
-    if (path->cleanup) {
-        Py_CLEAR(path->cleanup);
-    }
-}
-
-static int
-path_converter(PyObject *o, void *p) {
-    path_t *path = (path_t *)p;
-    PyObject *unicode, *bytes;
-    Py_ssize_t length;
-    char *narrow;
-
-#define FORMAT_EXCEPTION(exc, fmt) \
-    PyErr_Format(exc, "%s%s" fmt, \
-        path->function_name ? path->function_name : "", \
-        path->function_name ? ": "                : "", \
-        path->argument_name ? path->argument_name : "path")
-
-    /* Py_CLEANUP_SUPPORTED support */
-    if (o == NULL) {
-        path_cleanup(path);
-        return 1;
-    }
-
-    /* ensure it's always safe to call path_cleanup() */
-    path->cleanup = NULL;
-
-    if (o == Py_None) {
-        if (!path->nullable) {
-            FORMAT_EXCEPTION(PyExc_TypeError,
-                             "can't specify None for %s argument");
-            return 0;
-        }
-        path->wide = NULL;
-        path->narrow = NULL;
-        path->length = 0;
-        path->object = o;
-        path->fd = -1;
-        return 1;
-    }
-
-    unicode = PyUnicode_FromObject(o);
-    if (unicode) {
-#ifdef MS_WINDOWS
-        wchar_t *wide;
-
-        wide = PyUnicode_AsUnicodeAndSize(unicode, &length);
-        if (!wide) {
-            Py_DECREF(unicode);
-            return 0;
-        }
-        if (length > 32767) {
-            FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
-            Py_DECREF(unicode);
-            return 0;
-        }
-
-        path->wide = wide;
-        path->narrow = NULL;
-        path->length = length;
-        path->object = o;
-        path->fd = -1;
-        path->cleanup = unicode;
-        return Py_CLEANUP_SUPPORTED;
-#else
-        int converted = PyUnicode_FSConverter(unicode, &bytes);
-        Py_DECREF(unicode);
-        if (!converted)
-            bytes = NULL;
-#endif
-    }
-    else {
-        PyErr_Clear();
-        if (PyObject_CheckBuffer(o))
-            bytes = PyBytes_FromObject(o);
-        else
-            bytes = NULL;
-        if (!bytes) {
-            PyErr_Clear();
-            if (path->allow_fd) {
-                int fd;
-                int result = _fd_converter(o, &fd,
-                        "string, bytes or integer");
-                if (result) {
-                    path->wide = NULL;
-                    path->narrow = NULL;
-                    path->length = 0;
-                    path->object = o;
-                    path->fd = fd;
-                    return result;
-                }
-            }
-        }
-    }
-
-    if (!bytes) {
-        if (!PyErr_Occurred())
-            FORMAT_EXCEPTION(PyExc_TypeError, "illegal type for %s parameter");
-        return 0;
-    }
-
-#ifdef MS_WINDOWS
-    if (win32_warn_bytes_api()) {
-        Py_DECREF(bytes);
-        return 0;
-    }
-#endif
-
-    length = PyBytes_GET_SIZE(bytes);
-#ifdef MS_WINDOWS
-    if (length > MAX_PATH-1) {
-        FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
-        Py_DECREF(bytes);
-        return 0;
-    }
-#endif
-
-    narrow = PyBytes_AS_STRING(bytes);
-    if ((size_t)length != strlen(narrow)) {
-        FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
-        Py_DECREF(bytes);
-        return 0;
-    }
-
-    path->wide = NULL;
-    path->narrow = narrow;
-    path->length = length;
-    path->object = o;
-    path->fd = -1;
-    path->cleanup = bytes;
-    return Py_CLEANUP_SUPPORTED;
-}
-
-static void
-argument_unavailable_error(char *function_name, char *argument_name) {
-    PyErr_Format(PyExc_NotImplementedError,
-        "%s%s%s unavailable on this platform",
-        (function_name != NULL) ? function_name : "",
-        (function_name != NULL) ? ": ": "",
-        argument_name);
-}
-
-static int
-dir_fd_unavailable(PyObject *o, void *p)
-{
-    int dir_fd;
-    if (!dir_fd_converter(o, &dir_fd))
-        return 0;
-    if (dir_fd != DEFAULT_DIR_FD) {
-        argument_unavailable_error(NULL, "dir_fd");
-        return 0;
-    }
-    *(int *)p = dir_fd;
-    return 1;
-}
-
-static int
-fd_specified(char *function_name, int fd) {
-    if (fd == -1)
-        return 0;
-
-    argument_unavailable_error(function_name, "fd");
-    return 1;
-}
-
-static int
-follow_symlinks_specified(char *function_name, int follow_symlinks) {
-    if (follow_symlinks)
-        return 0;
-
-    argument_unavailable_error(function_name, "follow_symlinks");
-    return 1;
-}
-
-static int
-path_and_dir_fd_invalid(char *function_name, path_t *path, int dir_fd) {
-    if (!path->narrow && !path->wide && (dir_fd != DEFAULT_DIR_FD)) {
-        PyErr_Format(PyExc_ValueError,
-                     "%s: can't specify dir_fd without matching path",
-                     function_name);
-        return 1;
-    }
-    return 0;
-}
-
-static int
-dir_fd_and_fd_invalid(char *function_name, int dir_fd, int fd) {
-    if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
-        PyErr_Format(PyExc_ValueError,
-                     "%s: can't specify both dir_fd and fd",
-                     function_name);
-        return 1;
-    }
-    return 0;
-}
-
-static int
-fd_and_follow_symlinks_invalid(char *function_name, int fd,
-                               int follow_symlinks) {
-    if ((fd > 0) && (!follow_symlinks)) {
-        PyErr_Format(PyExc_ValueError,
-                     "%s: cannot use fd and follow_symlinks together",
-                     function_name);
-        return 1;
-    }
-    return 0;
-}
-
-static int
-dir_fd_and_follow_symlinks_invalid(char *function_name, int dir_fd,
-                                   int follow_symlinks) {
-    if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
-        PyErr_Format(PyExc_ValueError,
-                     "%s: cannot use dir_fd and follow_symlinks together",
-                     function_name);
-        return 1;
-    }
-    return 0;
-}
-
-#ifdef MS_WINDOWS
-    typedef PY_LONG_LONG Py_off_t;
-#else
-    typedef off_t Py_off_t;
-#endif
-
-static int
-Py_off_t_converter(PyObject *arg, void *addr)
-{
-#ifdef HAVE_LARGEFILE_SUPPORT
-    *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
-#else
-    *((Py_off_t *)addr) = PyLong_AsLong(arg);
-#endif
-    if (PyErr_Occurred())
-        return 0;
-    return 1;
-}
-
-static PyObject *
-PyLong_FromPy_off_t(Py_off_t offset)
-{
-#ifdef HAVE_LARGEFILE_SUPPORT
-    return PyLong_FromLongLong(offset);
-#else
-    return PyLong_FromLong(offset);
-#endif
-}
-
-
-#if defined _MSC_VER && _MSC_VER >= 1400 && _MSC_VER < 1900
-/* Legacy implementation of _PyVerify_fd_dup2 while transitioning to
- * MSVC 14.0. This should eventually be removed. (issue23524)
- */
-#define IOINFO_L2E 5
-#define IOINFO_ARRAYS 64
-#define IOINFO_ARRAY_ELTS   (1 << IOINFO_L2E)
-#define _NHANDLE_           (IOINFO_ARRAYS * IOINFO_ARRAY_ELTS)
-#define _NO_CONSOLE_FILENO (intptr_t)-2
-
-/* the special case of checking dup2.  The target fd must be in a sensible range */
-static int
-_PyVerify_fd_dup2(int fd1, int fd2)
-{
-    if (!_PyVerify_fd(fd1))
-        return 0;
-    if (fd2 == _NO_CONSOLE_FILENO)
-        return 0;
-    if ((unsigned)fd2 < _NHANDLE_)
-        return 1;
-    else
-        return 0;
-}
-#else
-#define _PyVerify_fd_dup2(fd1, fd2) (_PyVerify_fd(fd1) && (fd2) >= 0)
-#endif
-
-#ifdef MS_WINDOWS
-
-static int
-win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
-{
-    char target_buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
-    REPARSE_DATA_BUFFER *rdb = (REPARSE_DATA_BUFFER *)target_buffer;
-    DWORD n_bytes_returned;
-
-    if (0 == DeviceIoControl(
-        reparse_point_handle,
-        FSCTL_GET_REPARSE_POINT,
-        NULL, 0, /* in buffer */
-        target_buffer, sizeof(target_buffer),
-        &n_bytes_returned,
-        NULL)) /* we're not using OVERLAPPED_IO */
-        return FALSE;
-
-    if (reparse_tag)
-        *reparse_tag = rdb->ReparseTag;
-
-    return TRUE;
-}
-
-#endif /* MS_WINDOWS */
-
-/* Return a dictionary corresponding to the POSIX environment table */
-#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
-/* On Darwin/MacOSX a shared library or framework has no access to
-** environ directly, we must obtain it with _NSGetEnviron(). See also
-** man environ(7).
-*/
-#include <crt_externs.h>
-static char **environ;
-#elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
-extern char **environ;
-#endif /* !_MSC_VER */
-
-static PyObject *
-convertenviron(void)
-{
-    PyObject *d;
-#ifdef MS_WINDOWS
-    wchar_t **e;
-#else
-    char **e;
-#endif
-
-    d = PyDict_New();
-    if (d == NULL)
-        return NULL;
-#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
-    if (environ == NULL)
-        environ = *_NSGetEnviron();
-#endif
-#ifdef MS_WINDOWS
-    /* _wenviron must be initialized in this way if the program is started
-       through main() instead of wmain(). */
-    _wgetenv(L"");
-    if (_wenviron == NULL)
-        return d;
-    /* This part ignores errors */
-    for (e = _wenviron; *e != NULL; e++) {
-        PyObject *k;
-        PyObject *v;
-        wchar_t *p = wcschr(*e, L'=');
-        if (p == NULL)
-            continue;
-        k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
-        if (k == NULL) {
-            PyErr_Clear();
-            continue;
-        }
-        v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
-        if (v == NULL) {
-            PyErr_Clear();
-            Py_DECREF(k);
-            continue;
-        }
-        if (PyDict_GetItem(d, k) == NULL) {
-            if (PyDict_SetItem(d, k, v) != 0)
-                PyErr_Clear();
-        }
-        Py_DECREF(k);
-        Py_DECREF(v);
-    }
-#else
-    if (environ == NULL)
-        return d;
-    /* This part ignores errors */
-    for (e = environ; *e != NULL; e++) {
-        PyObject *k;
-        PyObject *v;
-        char *p = strchr(*e, '=');
-        if (p == NULL)
-            continue;
-        k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
-        if (k == NULL) {
-            PyErr_Clear();
-            continue;
-        }
-        v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
-        if (v == NULL) {
-            PyErr_Clear();
-            Py_DECREF(k);
-            continue;
-        }
-        if (PyDict_GetItem(d, k) == NULL) {
-            if (PyDict_SetItem(d, k, v) != 0)
-                PyErr_Clear();
-        }
-        Py_DECREF(k);
-        Py_DECREF(v);
-    }
-#endif
-    return d;
-}
-
-/* Set a POSIX-specific error from errno, and return NULL */
-
-static PyObject *
-posix_error(void)
-{
-    return PyErr_SetFromErrno(PyExc_OSError);
-}
-
-#ifdef MS_WINDOWS
-static PyObject *
-win32_error(char* function, const char* filename)
-{
-    /* XXX We should pass the function name along in the future.
-       (winreg.c also wants to pass the function name.)
-       This would however require an additional param to the
-       Windows error object, which is non-trivial.
-    */
-    errno = GetLastError();
-    if (filename)
-        return PyErr_SetFromWindowsErrWithFilename(errno, filename);
-    else
-        return PyErr_SetFromWindowsErr(errno);
-}
-
-static PyObject *
-win32_error_object(char* function, PyObject* filename)
-{
-    /* XXX - see win32_error for comments on 'function' */
-    errno = GetLastError();
-    if (filename)
-        return PyErr_SetExcFromWindowsErrWithFilenameObject(
-                    PyExc_OSError,
-                    errno,
-                    filename);
-    else
-        return PyErr_SetFromWindowsErr(errno);
-}
-
-#endif /* MS_WINDOWS */
-
-static PyObject *
-path_error(path_t *path)
-{
-#ifdef MS_WINDOWS
-    return PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError,
-                                                        0, path->object);
-#else
-    return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
-#endif
-}
-
-
-static PyObject *
-path_error2(path_t *path, path_t *path2)
-{
-#ifdef MS_WINDOWS
-    return PyErr_SetExcFromWindowsErrWithFilenameObjects(PyExc_OSError,
-            0, path->object, path2->object);
-#else
-    return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError,
-        path->object, path2->object);
-#endif
-}
-
-
-/* POSIX generic methods */
-
-static int
-fildes_converter(PyObject *o, void *p)
-{
-    int fd;
-    int *pointer = (int *)p;
-    fd = PyObject_AsFileDescriptor(o);
-    if (fd < 0)
-        return 0;
-    if (!_PyVerify_fd(fd)) {
-        posix_error();
-        return 0;
-    }
-    *pointer = fd;
-    return 1;
-}
-
-static PyObject *
-posix_fildes_fd(int fd, int (*func)(int))
-{
-    int res;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = (*func)(fd);
-        Py_END_ALLOW_THREADS
-    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res != 0)
-        return (!async_err) ? posix_error() : NULL;
-    Py_RETURN_NONE;
-}
-
-
-#ifdef MS_WINDOWS
-/* This is a reimplementation of the C library's chdir function,
-   but one that produces Win32 errors instead of DOS error codes.
-   chdir is essentially a wrapper around SetCurrentDirectory; however,
-   it also needs to set "magic" environment variables indicating
-   the per-drive current directory, which are of the form =<drive>: */
-static BOOL __stdcall
-win32_chdir(LPCSTR path)
-{
-    char new_path[MAX_PATH];
-    int result;
-    char env[4] = "=x:";
-
-    if(!SetCurrentDirectoryA(path))
-        return FALSE;
-    result = GetCurrentDirectoryA(Py_ARRAY_LENGTH(new_path), new_path);
-    if (!result)
-        return FALSE;
-    /* In the ANSI API, there should not be any paths longer
-       than MAX_PATH-1 (not including the final null character). */
-    assert(result < Py_ARRAY_LENGTH(new_path));
-    if (strncmp(new_path, "\\\\", 2) == 0 ||
-        strncmp(new_path, "//", 2) == 0)
-        /* UNC path, nothing to do. */
-        return TRUE;
-    env[1] = new_path[0];
-    return SetEnvironmentVariableA(env, new_path);
-}
-
-/* The Unicode version differs from the ANSI version
-   since the current directory might exceed MAX_PATH characters */
-static BOOL __stdcall
-win32_wchdir(LPCWSTR path)
-{
-    wchar_t _new_path[MAX_PATH], *new_path = _new_path;
-    int result;
-    wchar_t env[4] = L"=x:";
-
-    if(!SetCurrentDirectoryW(path))
-        return FALSE;
-    result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(new_path), new_path);
-    if (!result)
-        return FALSE;
-    if (result > Py_ARRAY_LENGTH(new_path)) {
-        new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
-        if (!new_path) {
-            SetLastError(ERROR_OUTOFMEMORY);
-            return FALSE;
-        }
-        result = GetCurrentDirectoryW(result, new_path);
-        if (!result) {
-            PyMem_RawFree(new_path);
-            return FALSE;
-        }
-    }
-    if (wcsncmp(new_path, L"\\\\", 2) == 0 ||
-        wcsncmp(new_path, L"//", 2) == 0)
-        /* UNC path, nothing to do. */
-        return TRUE;
-    env[1] = new_path[0];
-    result = SetEnvironmentVariableW(env, new_path);
-    if (new_path != _new_path)
-        PyMem_RawFree(new_path);
-    return result;
-}
-#endif
-
-#ifdef MS_WINDOWS
-/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
-   - time stamps are restricted to second resolution
-   - file modification times suffer from forth-and-back conversions between
-     UTC and local time
-   Therefore, we implement our own stat, based on the Win32 API directly.
-*/
-#define HAVE_STAT_NSEC 1
-#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
-
-static BOOL
-attributes_from_dir(LPCSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
-{
-    HANDLE hFindFile;
-    WIN32_FIND_DATAA FileData;
-    hFindFile = FindFirstFileA(pszFile, &FileData);
-    if (hFindFile == INVALID_HANDLE_VALUE)
-        return FALSE;
-    FindClose(hFindFile);
-    memset(info, 0, sizeof(*info));
-    *reparse_tag = 0;
-    info->dwFileAttributes = FileData.dwFileAttributes;
-    info->ftCreationTime   = FileData.ftCreationTime;
-    info->ftLastAccessTime = FileData.ftLastAccessTime;
-    info->ftLastWriteTime  = FileData.ftLastWriteTime;
-    info->nFileSizeHigh    = FileData.nFileSizeHigh;
-    info->nFileSizeLow     = FileData.nFileSizeLow;
-/*  info->nNumberOfLinks   = 1; */
-    if (FileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
-        *reparse_tag = FileData.dwReserved0;
-    return TRUE;
-}
-
-static void
-find_data_to_file_info_w(WIN32_FIND_DATAW *pFileData,
-                         BY_HANDLE_FILE_INFORMATION *info,
-                         ULONG *reparse_tag)
-{
-    memset(info, 0, sizeof(*info));
-    info->dwFileAttributes = pFileData->dwFileAttributes;
-    info->ftCreationTime   = pFileData->ftCreationTime;
-    info->ftLastAccessTime = pFileData->ftLastAccessTime;
-    info->ftLastWriteTime  = pFileData->ftLastWriteTime;
-    info->nFileSizeHigh    = pFileData->nFileSizeHigh;
-    info->nFileSizeLow     = pFileData->nFileSizeLow;
-/*  info->nNumberOfLinks   = 1; */
-    if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
-        *reparse_tag = pFileData->dwReserved0;
-    else
-        *reparse_tag = 0;
-}
-
-static BOOL
-attributes_from_dir_w(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
-{
-    HANDLE hFindFile;
-    WIN32_FIND_DATAW FileData;
-    hFindFile = FindFirstFileW(pszFile, &FileData);
-    if (hFindFile == INVALID_HANDLE_VALUE)
-        return FALSE;
-    FindClose(hFindFile);
-    find_data_to_file_info_w(&FileData, info, reparse_tag);
-    return TRUE;
-}
-
-static BOOL
-get_target_path(HANDLE hdl, wchar_t **target_path)
-{
-    int buf_size, result_length;
-    wchar_t *buf;
-
-    /* We have a good handle to the target, use it to determine
-       the target path name (then we'll call lstat on it). */
-    buf_size = GetFinalPathNameByHandleW(hdl, 0, 0,
-                                         VOLUME_NAME_DOS);
-    if(!buf_size)
-        return FALSE;
-
-    buf = PyMem_New(wchar_t, buf_size+1);
-    if (!buf) {
-        SetLastError(ERROR_OUTOFMEMORY);
-        return FALSE;
-    }
-
-    result_length = GetFinalPathNameByHandleW(hdl,
-                       buf, buf_size, VOLUME_NAME_DOS);
-
-    if(!result_length) {
-        PyMem_Free(buf);
-        return FALSE;
-    }
-
-    if(!CloseHandle(hdl)) {
-        PyMem_Free(buf);
-        return FALSE;
-    }
-
-    buf[result_length] = 0;
-
-    *target_path = buf;
-    return TRUE;
-}
-
-static int
-win32_xstat_impl_w(const wchar_t *path, struct _Py_stat_struct *result,
-                   BOOL traverse);
-static int
-win32_xstat_impl(const char *path, struct _Py_stat_struct *result,
-                 BOOL traverse)
-{
-    int code;
-    HANDLE hFile, hFile2;
-    BY_HANDLE_FILE_INFORMATION info;
-    ULONG reparse_tag = 0;
-    wchar_t *target_path;
-    const char *dot;
-
-    hFile = CreateFileA(
-        path,
-        FILE_READ_ATTRIBUTES, /* desired access */
-        0, /* share mode */
-        NULL, /* security attributes */
-        OPEN_EXISTING,
-        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
-        /* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
-           Because of this, calls like GetFinalPathNameByHandle will return
-           the symlink path again and not the actual final path. */
-        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
-            FILE_FLAG_OPEN_REPARSE_POINT,
-        NULL);
-
-    if (hFile == INVALID_HANDLE_VALUE) {
-        /* Either the target doesn't exist, or we don't have access to
-           get a handle to it. If the former, we need to return an error.
-           If the latter, we can use attributes_from_dir. */
-        if (GetLastError() != ERROR_SHARING_VIOLATION)
-            return -1;
-        /* Could not get attributes on open file. Fall back to
-           reading the directory. */
-        if (!attributes_from_dir(path, &info, &reparse_tag))
-            /* Very strange. This should not fail now */
-            return -1;
-        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-            if (traverse) {
-                /* Should traverse, but could not open reparse point handle */
-                SetLastError(ERROR_SHARING_VIOLATION);
-                return -1;
-            }
-        }
-    } else {
-        if (!GetFileInformationByHandle(hFile, &info)) {
-            CloseHandle(hFile);
-            return -1;
-        }
-        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-            if (!win32_get_reparse_tag(hFile, &reparse_tag))
-                return -1;
-
-            /* Close the outer open file handle now that we're about to
-               reopen it with different flags. */
-            if (!CloseHandle(hFile))
-                return -1;
-
-            if (traverse) {
-                /* In order to call GetFinalPathNameByHandle we need to open
-                   the file without the reparse handling flag set. */
-                hFile2 = CreateFileA(
-                           path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
-                           NULL, OPEN_EXISTING,
-                           FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
-                           NULL);
-                if (hFile2 == INVALID_HANDLE_VALUE)
-                    return -1;
-
-                if (!get_target_path(hFile2, &target_path))
-                    return -1;
-
-                code = win32_xstat_impl_w(target_path, result, FALSE);
-                PyMem_Free(target_path);
-                return code;
-            }
-        } else
-            CloseHandle(hFile);
-    }
-    _Py_attribute_data_to_stat(&info, reparse_tag, result);
-
-    /* Set S_IEXEC if it is an .exe, .bat, ... */
-    dot = strrchr(path, '.');
-    if (dot) {
-        if (stricmp(dot, ".bat") == 0 || stricmp(dot, ".cmd") == 0 ||
-            stricmp(dot, ".exe") == 0 || stricmp(dot, ".com") == 0)
-            result->st_mode |= 0111;
-    }
-    return 0;
-}
-
-static int
-win32_xstat_impl_w(const wchar_t *path, struct _Py_stat_struct *result,
-                   BOOL traverse)
-{
-    int code;
-    HANDLE hFile, hFile2;
-    BY_HANDLE_FILE_INFORMATION info;
-    ULONG reparse_tag = 0;
-    wchar_t *target_path;
-    const wchar_t *dot;
-
-    hFile = CreateFileW(
-        path,
-        FILE_READ_ATTRIBUTES, /* desired access */
-        0, /* share mode */
-        NULL, /* security attributes */
-        OPEN_EXISTING,
-        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
-        /* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
-           Because of this, calls like GetFinalPathNameByHandle will return
-           the symlink path again and not the actual final path. */
-        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
-            FILE_FLAG_OPEN_REPARSE_POINT,
-        NULL);
-
-    if (hFile == INVALID_HANDLE_VALUE) {
-        /* Either the target doesn't exist, or we don't have access to
-           get a handle to it. If the former, we need to return an error.
-           If the latter, we can use attributes_from_dir. */
-        if (GetLastError() != ERROR_SHARING_VIOLATION)
-            return -1;
-        /* Could not get attributes on open file. Fall back to
-           reading the directory. */
-        if (!attributes_from_dir_w(path, &info, &reparse_tag))
-            /* Very strange. This should not fail now */
-            return -1;
-        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-            if (traverse) {
-                /* Should traverse, but could not open reparse point handle */
-                SetLastError(ERROR_SHARING_VIOLATION);
-                return -1;
-            }
-        }
-    } else {
-        if (!GetFileInformationByHandle(hFile, &info)) {
-            CloseHandle(hFile);
-            return -1;
-        }
-        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-            if (!win32_get_reparse_tag(hFile, &reparse_tag))
-                return -1;
-
-            /* Close the outer open file handle now that we're about to
-               reopen it with different flags. */
-            if (!CloseHandle(hFile))
-                return -1;
-
-            if (traverse) {
-                /* In order to call GetFinalPathNameByHandle we need to open
-                   the file without the reparse handling flag set. */
-                hFile2 = CreateFileW(
-                           path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
-                           NULL, OPEN_EXISTING,
-                           FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
-                           NULL);
-                if (hFile2 == INVALID_HANDLE_VALUE)
-                    return -1;
-
-                if (!get_target_path(hFile2, &target_path))
-                    return -1;
-
-                code = win32_xstat_impl_w(target_path, result, FALSE);
-                PyMem_Free(target_path);
-                return code;
-            }
-        } else
-            CloseHandle(hFile);
-    }
-    _Py_attribute_data_to_stat(&info, reparse_tag, result);
-
-    /* Set S_IEXEC if it is an .exe, .bat, ... */
-    dot = wcsrchr(path, '.');
-    if (dot) {
-        if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
-            _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
-            result->st_mode |= 0111;
-    }
-    return 0;
-}
-
-static int
-win32_xstat(const char *path, struct _Py_stat_struct *result, BOOL traverse)
-{
-    /* Protocol violation: we explicitly clear errno, instead of
-       setting it to a POSIX error. Callers should use GetLastError. */
-    int code = win32_xstat_impl(path, result, traverse);
-    errno = 0;
-    return code;
-}
-
-static int
-win32_xstat_w(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
-{
-    /* Protocol violation: we explicitly clear errno, instead of
-       setting it to a POSIX error. Callers should use GetLastError. */
-    int code = win32_xstat_impl_w(path, result, traverse);
-    errno = 0;
-    return code;
-}
-/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
-
-   In Posix, stat automatically traverses symlinks and returns the stat
-   structure for the target.  In Windows, the equivalent GetFileAttributes by
-   default does not traverse symlinks and instead returns attributes for
-   the symlink.
-
-   Therefore, win32_lstat will get the attributes traditionally, and
-   win32_stat will first explicitly resolve the symlink target and then will
-   call win32_lstat on that result.
-
-   The _w represent Unicode equivalents of the aforementioned ANSI functions. */
-
-static int
-win32_lstat(const char* path, struct _Py_stat_struct *result)
-{
-    return win32_xstat(path, result, FALSE);
-}
-
-static int
-win32_lstat_w(const wchar_t* path, struct _Py_stat_struct *result)
-{
-    return win32_xstat_w(path, result, FALSE);
-}
-
-static int
-win32_stat(const char* path, struct _Py_stat_struct *result)
-{
-    return win32_xstat(path, result, TRUE);
-}
-
-static int
-win32_stat_w(const wchar_t* path, struct _Py_stat_struct *result)
-{
-    return win32_xstat_w(path, result, TRUE);
-}
-
-#endif /* MS_WINDOWS */
-
-PyDoc_STRVAR(stat_result__doc__,
-"stat_result: Result from stat, fstat, or lstat.\n\n\
-This object may be accessed either as a tuple of\n\
-  (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
-or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
-\n\
-Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
-or st_flags, they are available as attributes only.\n\
-\n\
-See os.stat for more information.");
-
-static PyStructSequence_Field stat_result_fields[] = {
-    {"st_mode",    "protection bits"},
-    {"st_ino",     "inode"},
-    {"st_dev",     "device"},
-    {"st_nlink",   "number of hard links"},
-    {"st_uid",     "user ID of owner"},
-    {"st_gid",     "group ID of owner"},
-    {"st_size",    "total size, in bytes"},
-    /* The NULL is replaced with PyStructSequence_UnnamedField later. */
-    {NULL,   "integer time of last access"},
-    {NULL,   "integer time of last modification"},
-    {NULL,   "integer time of last change"},
-    {"st_atime",   "time of last access"},
-    {"st_mtime",   "time of last modification"},
-    {"st_ctime",   "time of last change"},
-    {"st_atime_ns",   "time of last access in nanoseconds"},
-    {"st_mtime_ns",   "time of last modification in nanoseconds"},
-    {"st_ctime_ns",   "time of last change in nanoseconds"},
-#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
-    {"st_blksize", "blocksize for filesystem I/O"},
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
-    {"st_blocks",  "number of blocks allocated"},
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_RDEV
-    {"st_rdev",    "device type (if inode device)"},
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_FLAGS
-    {"st_flags",   "user defined flags for file"},
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_GEN
-    {"st_gen",    "generation number"},
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
-    {"st_birthtime",   "time of creation"},
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
-    {"st_file_attributes", "Windows file attribute bits"},
-#endif
-    {0}
-};
-
-#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
-#define ST_BLKSIZE_IDX 16
-#else
-#define ST_BLKSIZE_IDX 15
-#endif
-
-#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
-#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
-#else
-#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
-#endif
-
-#ifdef HAVE_STRUCT_STAT_ST_RDEV
-#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
-#else
-#define ST_RDEV_IDX ST_BLOCKS_IDX
-#endif
-
-#ifdef HAVE_STRUCT_STAT_ST_FLAGS
-#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
-#else
-#define ST_FLAGS_IDX ST_RDEV_IDX
-#endif
-
-#ifdef HAVE_STRUCT_STAT_ST_GEN
-#define ST_GEN_IDX (ST_FLAGS_IDX+1)
-#else
-#define ST_GEN_IDX ST_FLAGS_IDX
-#endif
-
-#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
-#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
-#else
-#define ST_BIRTHTIME_IDX ST_GEN_IDX
-#endif
-
-#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
-#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
-#else
-#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
-#endif
-
-static PyStructSequence_Desc stat_result_desc = {
-    "stat_result", /* name */
-    stat_result__doc__, /* doc */
-    stat_result_fields,
-    10
-};
-
-PyDoc_STRVAR(statvfs_result__doc__,
-"statvfs_result: Result from statvfs or fstatvfs.\n\n\
-This object may be accessed either as a tuple of\n\
-  (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
-or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
-\n\
-See os.statvfs for more information.");
-
-static PyStructSequence_Field statvfs_result_fields[] = {
-    {"f_bsize",  },
-    {"f_frsize", },
-    {"f_blocks", },
-    {"f_bfree",  },
-    {"f_bavail", },
-    {"f_files",  },
-    {"f_ffree",  },
-    {"f_favail", },
-    {"f_flag",   },
-    {"f_namemax",},
-    {0}
-};
-
-static PyStructSequence_Desc statvfs_result_desc = {
-    "statvfs_result", /* name */
-    statvfs_result__doc__, /* doc */
-    statvfs_result_fields,
-    10
-};
-
-#if defined(HAVE_WAITID) && !defined(__APPLE__)
-PyDoc_STRVAR(waitid_result__doc__,
-"waitid_result: Result from waitid.\n\n\
-This object may be accessed either as a tuple of\n\
-  (si_pid, si_uid, si_signo, si_status, si_code),\n\
-or via the attributes si_pid, si_uid, and so on.\n\
-\n\
-See os.waitid for more information.");
-
-static PyStructSequence_Field waitid_result_fields[] = {
-    {"si_pid",  },
-    {"si_uid", },
-    {"si_signo", },
-    {"si_status",  },
-    {"si_code", },
-    {0}
-};
-
-static PyStructSequence_Desc waitid_result_desc = {
-    "waitid_result", /* name */
-    waitid_result__doc__, /* doc */
-    waitid_result_fields,
-    5
-};
-static PyTypeObject WaitidResultType;
-#endif
-
-static int initialized;
-static PyTypeObject StatResultType;
-static PyTypeObject StatVFSResultType;
-#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
-static PyTypeObject SchedParamType;
-#endif
-static newfunc structseq_new;
-
-static PyObject *
-statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyStructSequence *result;
-    int i;
-
-    result = (PyStructSequence*)structseq_new(type, args, kwds);
-    if (!result)
-        return NULL;
-    /* If we have been initialized from a tuple,
-       st_?time might be set to None. Initialize it
-       from the int slots.  */
-    for (i = 7; i <= 9; i++) {
-        if (result->ob_item[i+3] == Py_None) {
-            Py_DECREF(Py_None);
-            Py_INCREF(result->ob_item[i]);
-            result->ob_item[i+3] = result->ob_item[i];
-        }
-    }
-    return (PyObject*)result;
-}
-
-
-
-/* If true, st_?time is float. */
-static int _stat_float_times = 1;
-
-PyDoc_STRVAR(stat_float_times__doc__,
-"stat_float_times([newval]) -> oldval\n\n\
-Determine whether os.[lf]stat represents time stamps as float objects.\n\
-\n\
-If value is True, future calls to stat() return floats; if it is False,\n\
-future calls return ints.\n\
-If value is omitted, return the current setting.\n");
-
-/* AC 3.5: the public default value should be None, not ready for that yet */
-static PyObject*
-stat_float_times(PyObject* self, PyObject *args)
-{
-    int newval = -1;
-    if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
-        return NULL;
-    if (PyErr_WarnEx(PyExc_DeprecationWarning,
-                     "stat_float_times() is deprecated",
-                     1))
-        return NULL;
-    if (newval == -1)
-        /* Return old value */
-        return PyBool_FromLong(_stat_float_times);
-    _stat_float_times = newval;
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *billion = NULL;
-
-static void
-fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
-{
-    PyObject *s = _PyLong_FromTime_t(sec);
-    PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
-    PyObject *s_in_ns = NULL;
-    PyObject *ns_total = NULL;
-    PyObject *float_s = NULL;
-
-    if (!(s && ns_fractional))
-        goto exit;
-
-    s_in_ns = PyNumber_Multiply(s, billion);
-    if (!s_in_ns)
-        goto exit;
-
-    ns_total = PyNumber_Add(s_in_ns, ns_fractional);
-    if (!ns_total)
-        goto exit;
-
-    if (_stat_float_times) {
-        float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
-        if (!float_s)
-            goto exit;
-    }
-    else {
-        float_s = s;
-        Py_INCREF(float_s);
-    }
-
-    PyStructSequence_SET_ITEM(v, index, s);
-    PyStructSequence_SET_ITEM(v, index+3, float_s);
-    PyStructSequence_SET_ITEM(v, index+6, ns_total);
-    s = NULL;
-    float_s = NULL;
-    ns_total = NULL;
-exit:
-    Py_XDECREF(s);
-    Py_XDECREF(ns_fractional);
-    Py_XDECREF(s_in_ns);
-    Py_XDECREF(ns_total);
-    Py_XDECREF(float_s);
-}
-
-/* pack a system stat C structure into the Python stat tuple
-   (used by posix_stat() and posix_fstat()) */
-static PyObject*
-_pystat_fromstructstat(STRUCT_STAT *st)
-{
-    unsigned long ansec, mnsec, cnsec;
-    PyObject *v = PyStructSequence_New(&StatResultType);
-    if (v == NULL)
-        return NULL;
-
-    PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
-#ifdef HAVE_LARGEFILE_SUPPORT
-    PyStructSequence_SET_ITEM(v, 1,
-                              PyLong_FromLongLong((PY_LONG_LONG)st->st_ino));
-#else
-    PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino));
-#endif
-#ifdef MS_WINDOWS
-    PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
-#else
-    PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
-#endif
-    PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
-#if defined(MS_WINDOWS)
-    PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
-    PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
-#else
-    PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
-    PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
-#endif
-#ifdef HAVE_LARGEFILE_SUPPORT
-    PyStructSequence_SET_ITEM(v, 6,
-                              PyLong_FromLongLong((PY_LONG_LONG)st->st_size));
-#else
-    PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size));
-#endif
-
-#if defined(HAVE_STAT_TV_NSEC)
-    ansec = st->st_atim.tv_nsec;
-    mnsec = st->st_mtim.tv_nsec;
-    cnsec = st->st_ctim.tv_nsec;
-#elif defined(HAVE_STAT_TV_NSEC2)
-    ansec = st->st_atimespec.tv_nsec;
-    mnsec = st->st_mtimespec.tv_nsec;
-    cnsec = st->st_ctimespec.tv_nsec;
-#elif defined(HAVE_STAT_NSEC)
-    ansec = st->st_atime_nsec;
-    mnsec = st->st_mtime_nsec;
-    cnsec = st->st_ctime_nsec;
-#else
-    ansec = mnsec = cnsec = 0;
-#endif
-    fill_time(v, 7, st->st_atime, ansec);
-    fill_time(v, 8, st->st_mtime, mnsec);
-    fill_time(v, 9, st->st_ctime, cnsec);
-
-#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
-    PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
-                              PyLong_FromLong((long)st->st_blksize));
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
-    PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
-                              PyLong_FromLong((long)st->st_blocks));
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_RDEV
-    PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
-                              PyLong_FromLong((long)st->st_rdev));
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_GEN
-    PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
-                              PyLong_FromLong((long)st->st_gen));
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
-    {
-      PyObject *val;
-      unsigned long bsec,bnsec;
-      bsec = (long)st->st_birthtime;
-#ifdef HAVE_STAT_TV_NSEC2
-      bnsec = st->st_birthtimespec.tv_nsec;
-#else
-      bnsec = 0;
-#endif
-      if (_stat_float_times) {
-        val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
-      } else {
-        val = PyLong_FromLong((long)bsec);
-      }
-      PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
-                                val);
-    }
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_FLAGS
-    PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
-                              PyLong_FromLong((long)st->st_flags));
-#endif
-#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
-    PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
-                              PyLong_FromUnsignedLong(st->st_file_attributes));
-#endif
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(v);
-        return NULL;
-    }
-
-    return v;
-}
-
-/* POSIX methods */
-
-
-static PyObject *
-posix_do_stat(char *function_name, path_t *path,
-              int dir_fd, int follow_symlinks)
-{
-    STRUCT_STAT st;
-    int result;
-
-#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
-    if (follow_symlinks_specified(function_name, follow_symlinks))
-        return NULL;
-#endif
-
-    if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
-        dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
-        fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
-        return NULL;
-
-    Py_BEGIN_ALLOW_THREADS
-    if (path->fd != -1)
-        result = FSTAT(path->fd, &st);
-    else
-#ifdef MS_WINDOWS
-    if (path->wide) {
-        if (follow_symlinks)
-            result = win32_stat_w(path->wide, &st);
-        else
-            result = win32_lstat_w(path->wide, &st);
-    }
-    else
-#endif
-#if defined(HAVE_LSTAT) || defined(MS_WINDOWS)
-    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
-        result = LSTAT(path->narrow, &st);
-    else
-#endif
-#ifdef HAVE_FSTATAT
-    if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
-        result = fstatat(dir_fd, path->narrow, &st,
-                         follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
-    else
-#endif
-        result = STAT(path->narrow, &st);
-    Py_END_ALLOW_THREADS
-
-    if (result != 0) {
-        return path_error(path);
-    }
-
-    return _pystat_fromstructstat(&st);
-}
-
-/*[python input]
-
-for s in """
-
-FACCESSAT
-FCHMODAT
-FCHOWNAT
-FSTATAT
-LINKAT
-MKDIRAT
-MKFIFOAT
-MKNODAT
-OPENAT
-READLINKAT
-SYMLINKAT
-UNLINKAT
-
-""".strip().split():
-    s = s.strip()
-    print("""
-#ifdef HAVE_{s}
-    #define {s}_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-""".rstrip().format(s=s))
-
-for s in """
-
-FCHDIR
-FCHMOD
-FCHOWN
-FDOPENDIR
-FEXECVE
-FPATHCONF
-FSTATVFS
-FTRUNCATE
-
-""".strip().split():
-    s = s.strip()
-    print("""
-#ifdef HAVE_{s}
-    #define PATH_HAVE_{s} 1
-#else
-    #define PATH_HAVE_{s} 0
-#endif
-
-""".rstrip().format(s=s))
-[python start generated code]*/
-
-#ifdef HAVE_FACCESSAT
-    #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_FCHMODAT
-    #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_FCHOWNAT
-    #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_FSTATAT
-    #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_LINKAT
-    #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_MKDIRAT
-    #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_MKFIFOAT
-    #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_MKNODAT
-    #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_OPENAT
-    #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_READLINKAT
-    #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_SYMLINKAT
-    #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_UNLINKAT
-    #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#ifdef HAVE_FCHDIR
-    #define PATH_HAVE_FCHDIR 1
-#else
-    #define PATH_HAVE_FCHDIR 0
-#endif
-
-#ifdef HAVE_FCHMOD
-    #define PATH_HAVE_FCHMOD 1
-#else
-    #define PATH_HAVE_FCHMOD 0
-#endif
-
-#ifdef HAVE_FCHOWN
-    #define PATH_HAVE_FCHOWN 1
-#else
-    #define PATH_HAVE_FCHOWN 0
-#endif
-
-#ifdef HAVE_FDOPENDIR
-    #define PATH_HAVE_FDOPENDIR 1
-#else
-    #define PATH_HAVE_FDOPENDIR 0
-#endif
-
-#ifdef HAVE_FEXECVE
-    #define PATH_HAVE_FEXECVE 1
-#else
-    #define PATH_HAVE_FEXECVE 0
-#endif
-
-#ifdef HAVE_FPATHCONF
-    #define PATH_HAVE_FPATHCONF 1
-#else
-    #define PATH_HAVE_FPATHCONF 0
-#endif
-
-#ifdef HAVE_FSTATVFS
-    #define PATH_HAVE_FSTATVFS 1
-#else
-    #define PATH_HAVE_FSTATVFS 0
-#endif
-
-#ifdef HAVE_FTRUNCATE
-    #define PATH_HAVE_FTRUNCATE 1
-#else
-    #define PATH_HAVE_FTRUNCATE 0
-#endif
-/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
-
-
-/*[python input]
-
-class path_t_converter(CConverter):
-
-    type = "path_t"
-    impl_by_reference = True
-    parse_by_reference = True
-
-    converter = 'path_converter'
-
-    def converter_init(self, *, allow_fd=False, nullable=False):
-        # right now path_t doesn't support default values.
-        # to support a default value, you'll need to override initialize().
-        if self.default not in (unspecified, None):
-            fail("Can't specify a default to the path_t converter!")
-
-        if self.c_default not in (None, 'Py_None'):
-            raise RuntimeError("Can't specify a c_default to the path_t converter!")
-
-        self.nullable = nullable
-        self.allow_fd = allow_fd
-
-    def pre_render(self):
-        def strify(value):
-            if isinstance(value, str):
-                return value
-            return str(int(bool(value)))
-
-        # add self.py_name here when merging with posixmodule conversion
-        self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
-            self.function.name,
-            self.name,
-            strify(self.nullable),
-            strify(self.allow_fd),
-            )
-
-    def cleanup(self):
-        return "path_cleanup(&" + self.name + ");\n"
-
-
-class dir_fd_converter(CConverter):
-    type = 'int'
-
-    def converter_init(self, requires=None):
-        if self.default in (unspecified, None):
-            self.c_default = 'DEFAULT_DIR_FD'
-        if isinstance(requires, str):
-            self.converter = requires.upper() + '_DIR_FD_CONVERTER'
-        else:
-            self.converter = 'dir_fd_converter'
-
-class fildes_converter(CConverter):
-    type = 'int'
-    converter = 'fildes_converter'
-
-class uid_t_converter(CConverter):
-    type = "uid_t"
-    converter = '_Py_Uid_Converter'
-
-class gid_t_converter(CConverter):
-    type = "gid_t"
-    converter = '_Py_Gid_Converter'
-
-class dev_t_converter(CConverter):
-    type = 'dev_t'
-    converter = '_Py_Dev_Converter'
-
-class dev_t_return_converter(unsigned_long_return_converter):
-    type = 'dev_t'
-    conversion_fn = '_PyLong_FromDev'
-    unsigned_cast = '(dev_t)'
-
-class FSConverter_converter(CConverter):
-    type = 'PyObject *'
-    converter = 'PyUnicode_FSConverter'
-    def converter_init(self):
-        if self.default is not unspecified:
-            fail("FSConverter_converter does not support default values")
-        self.c_default = 'NULL'
-
-    def cleanup(self):
-        return "Py_XDECREF(" + self.name + ");\n"
-
-class pid_t_converter(CConverter):
-    type = 'pid_t'
-    format_unit = '" _Py_PARSE_PID "'
-
-class idtype_t_converter(int_converter):
-    type = 'idtype_t'
-
-class id_t_converter(CConverter):
-    type = 'id_t'
-    format_unit = '" _Py_PARSE_PID "'
-
-class Py_intptr_t_converter(CConverter):
-    type = 'Py_intptr_t'
-    format_unit = '" _Py_PARSE_INTPTR "'
-
-class Py_off_t_converter(CConverter):
-    type = 'Py_off_t'
-    converter = 'Py_off_t_converter'
-
-class Py_off_t_return_converter(long_return_converter):
-    type = 'Py_off_t'
-    conversion_fn = 'PyLong_FromPy_off_t'
-
-class path_confname_converter(CConverter):
-    type="int"
-    converter="conv_path_confname"
-
-class confstr_confname_converter(path_confname_converter):
-    converter='conv_confstr_confname'
-
-class sysconf_confname_converter(path_confname_converter):
-    converter="conv_sysconf_confname"
-
-class sched_param_converter(CConverter):
-    type = 'struct sched_param'
-    converter = 'convert_sched_param'
-    impl_by_reference = True;
-
-[python start generated code]*/
-/*[python end generated code: output=da39a3ee5e6b4b0d input=affe68316f160401]*/
-
-/*[clinic input]
-
-os.stat
-
-    path : path_t(allow_fd=True)
-        Path to be examined; can be string, bytes, or open-file-descriptor int.
-
-    *
-
-    dir_fd : dir_fd(requires='fstatat') = None
-        If not None, it should be a file descriptor open to a directory,
-        and path should be a relative string; path will then be relative to
-        that directory.
-
-    follow_symlinks: bool = True
-        If False, and the last element of the path is a symbolic link,
-        stat will examine the symbolic link itself instead of the file
-        the link points to.
-
-Perform a stat system call on the given path.
-
-dir_fd and follow_symlinks may not be implemented
-  on your platform.  If they are unavailable, using them will raise a
-  NotImplementedError.
-
-It's an error to use dir_fd or follow_symlinks when specifying path as
-  an open file descriptor.
-
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(os_stat__doc__,
@@ -2522,29 +54,6 @@
     return return_value;
 }
 
-static PyObject *
-os_stat_impl(PyModuleDef *module, path_t *path, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=0e9f9508fa0c0607 input=099d356c306fa24a]*/
-{
-    return posix_do_stat("stat", path, dir_fd, follow_symlinks);
-}
-
-
-/*[clinic input]
-os.lstat
-
-    path : path_t
-
-    *
-
-    dir_fd : dir_fd(requires='fstatat') = None
-
-Perform a stat system call on the given path, without following symbolic links.
-
-Like stat(), but do not follow symbolic links.
-Equivalent to stat(path, follow_symlinks=False).
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_lstat__doc__,
 "lstat($module, /, path, *, dir_fd=None)\n"
 "--\n"
@@ -2581,54 +90,6 @@
     return return_value;
 }
 
-static PyObject *
-os_lstat_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=85702247224a2b1c input=0b7474765927b925]*/
-{
-    int follow_symlinks = 0;
-    return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
-}
-
-
-/*[clinic input]
-os.access -> bool
-
-    path: path_t(allow_fd=True)
-        Path to be tested; can be string, bytes, or open-file-descriptor int.
-
-    mode: int
-        Operating-system mode bitfield.  Can be F_OK to test existence,
-        or the inclusive-OR of R_OK, W_OK, and X_OK.
-
-    *
-
-    dir_fd : dir_fd(requires='faccessat') = None
-        If not None, it should be a file descriptor open to a directory,
-        and path should be relative; path will then be relative to that
-        directory.
-
-    effective_ids: bool = False
-        If True, access will use the effective uid/gid instead of
-        the real uid/gid.
-
-    follow_symlinks: bool = True
-        If False, and the last element of the path is a symbolic link,
-        access will examine the symbolic link itself instead of the file
-        the link points to.
-
-Use the real uid/gid to test for access to a path.
-
-{parameters}
-dir_fd, effective_ids, and follow_symlinks may not be implemented
-  on your platform.  If they are unavailable, using them will raise a
-  NotImplementedError.
-
-Note that most operations will use the effective uid/gid, therefore this
-  routine can be used in a suid/sgid environment to test if the invoking user
-  has the specified access to the path.
-
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_access__doc__,
 "access($module, /, path, mode, *, dir_fd=None, effective_ids=False,\n"
 "       follow_symlinks=True)\n"
@@ -2695,97 +156,7 @@
     return return_value;
 }
 
-static int
-os_access_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd, int effective_ids, int follow_symlinks)
-/*[clinic end generated code: output=dfd404666906f012 input=b75a756797af45ec]*/
-{
-    int return_value;
-
-#ifdef MS_WINDOWS
-    DWORD attr;
-#else
-    int result;
-#endif
-
-#ifndef HAVE_FACCESSAT
-    if (follow_symlinks_specified("access", follow_symlinks))
-        return -1;
-
-    if (effective_ids) {
-        argument_unavailable_error("access", "effective_ids");
-        return -1;
-    }
-#endif
-
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    if (path->wide != NULL)
-        attr = GetFileAttributesW(path->wide);
-    else
-        attr = GetFileAttributesA(path->narrow);
-    Py_END_ALLOW_THREADS
-
-    /*
-     * Access is possible if
-     *   * we didn't get a -1, and
-     *     * write access wasn't requested,
-     *     * or the file isn't read-only,
-     *     * or it's a directory.
-     * (Directories cannot be read-only on Windows.)
-    */
-    return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
-            (!(mode & 2) ||
-            !(attr & FILE_ATTRIBUTE_READONLY) ||
-            (attr & FILE_ATTRIBUTE_DIRECTORY));
-#else
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_FACCESSAT
-    if ((dir_fd != DEFAULT_DIR_FD) ||
-        effective_ids ||
-        !follow_symlinks) {
-        int flags = 0;
-        if (!follow_symlinks)
-            flags |= AT_SYMLINK_NOFOLLOW;
-        if (effective_ids)
-            flags |= AT_EACCESS;
-        result = faccessat(dir_fd, path->narrow, mode, flags);
-    }
-    else
-#endif
-        result = access(path->narrow, mode);
-    Py_END_ALLOW_THREADS
-    return_value = !result;
-#endif
-
-    return return_value;
-}
-
-#ifndef F_OK
-#define F_OK 0
-#endif
-#ifndef R_OK
-#define R_OK 4
-#endif
-#ifndef W_OK
-#define W_OK 2
-#endif
-#ifndef X_OK
-#define X_OK 1
-#endif
-
-
-#ifdef HAVE_TTYNAME
-/*[clinic input]
-os.ttyname -> DecodeFSDefault
-
-    fd: int
-        Integer file descriptor handle.
-
-    /
-
-Return the name of the terminal device connected to 'fd'.
-[clinic start generated code]*/
+#if defined(HAVE_TTYNAME)
 
 PyDoc_STRVAR(os_ttyname__doc__,
 "ttyname($module, fd, /)\n"
@@ -2822,25 +193,9 @@
     return return_value;
 }
 
-static char *
-os_ttyname_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=cee7bc4cffec01a2 input=5f72ca83e76b3b45]*/
-{
-    char *ret;
-
-    ret = ttyname(fd);
-    if (ret == NULL)
-        posix_error();
-    return ret;
-}
-#endif
-
-#ifdef HAVE_CTERMID
-/*[clinic input]
-os.ctermid
-
-Return the name of the controlling terminal for this process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_TTYNAME) */
+
+#if defined(HAVE_CTERMID)
 
 PyDoc_STRVAR(os_ctermid__doc__,
 "ctermid($module, /)\n"
@@ -2860,36 +215,7 @@
     return os_ctermid_impl(module);
 }
 
-static PyObject *
-os_ctermid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=277bf7964ec2d782 input=3b87fdd52556382d]*/
-{
-    char *ret;
-    char buffer[L_ctermid];
-
-#ifdef USE_CTERMID_R
-    ret = ctermid_r(buffer);
-#else
-    ret = ctermid(buffer);
-#endif
-    if (ret == NULL)
-        return posix_error();
-    return PyUnicode_DecodeFSDefault(buffer);
-}
-#endif /* HAVE_CTERMID */
-
-
-/*[clinic input]
-os.chdir
-
-    path: path_t(allow_fd='PATH_HAVE_FCHDIR')
-
-Change the current working directory to the specified path.
-
-path may always be specified as a string.
-On some platforms, path may also be specified as an open file descriptor.
-  If this functionality is unavailable, using it raises an exception.
-[clinic start generated code]*/
+#endif /* defined(HAVE_CTERMID) */
 
 PyDoc_STRVAR(os_chdir__doc__,
 "chdir($module, /, path)\n"
@@ -2927,49 +253,7 @@
     return return_value;
 }
 
-static PyObject *
-os_chdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=cc07592dd23ca9e0 input=1a4a15b4d12cb15d]*/
-{
-    int result;
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef MS_WINDOWS
-    if (path->wide)
-        result = win32_wchdir(path->wide);
-    else
-        result = win32_chdir(path->narrow);
-    result = !result; /* on unix, success = 0, on windows, success = !0 */
-#else
-#ifdef HAVE_FCHDIR
-    if (path->fd != -1)
-        result = fchdir(path->fd);
-    else
-#endif
-        result = chdir(path->narrow);
-#endif
-    Py_END_ALLOW_THREADS
-
-    if (result) {
-        return path_error(path);
-    }
-
-    Py_RETURN_NONE;
-}
-
-
-#ifdef HAVE_FCHDIR
-/*[clinic input]
-os.fchdir
-
-    fd: fildes
-
-Change to the directory of the given file descriptor.
-
-fd must be opened on a directory, not a file.
-Equivalent to os.chdir(fd).
-
-[clinic start generated code]*/
+#if defined(HAVE_FCHDIR)
 
 PyDoc_STRVAR(os_fchdir__doc__,
 "fchdir($module, /, fd)\n"
@@ -3003,46 +287,7 @@
     return return_value;
 }
 
-static PyObject *
-os_fchdir_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=9f6dbc89b2778834 input=18e816479a2fa985]*/
-{
-    return posix_fildes_fd(fd, fchdir);
-}
-#endif /* HAVE_FCHDIR */
-
-
-/*[clinic input]
-os.chmod
-
-    path: path_t(allow_fd='PATH_HAVE_FCHMOD')
-        Path to be modified.  May always be specified as a str or bytes.
-        On some platforms, path may also be specified as an open file descriptor.
-        If this functionality is unavailable, using it raises an exception.
-
-    mode: int
-        Operating-system mode bitfield.
-
-    *
-
-    dir_fd : dir_fd(requires='fchmodat') = None
-        If not None, it should be a file descriptor open to a directory,
-        and path should be relative; path will then be relative to that
-        directory.
-
-    follow_symlinks: bool = True
-        If False, and the last element of the path is a symbolic link,
-        chmod will modify the symbolic link itself instead of the file
-        the link points to.
-
-Change the access permissions of a file.
-
-It is an error to use dir_fd or follow_symlinks when specifying path as
-  an open file descriptor.
-dir_fd and follow_symlinks may not be implemented on your platform.
-  If they are unavailable, using them will raise a NotImplementedError.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_FCHDIR) */
 
 PyDoc_STRVAR(os_chmod__doc__,
 "chmod($module, /, path, mode, *, dir_fd=None, follow_symlinks=True)\n"
@@ -3099,118 +344,7 @@
     return return_value;
 }
 
-static PyObject *
-os_chmod_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=1e9db031aea46422 input=7f1618e5e15cc196]*/
-{
-    int result;
-
-#ifdef MS_WINDOWS
-    DWORD attr;
-#endif
-
-#ifdef HAVE_FCHMODAT
-    int fchmodat_nofollow_unsupported = 0;
-#endif
-
-#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
-    if (follow_symlinks_specified("chmod", follow_symlinks))
-        return NULL;
-#endif
-
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    if (path->wide)
-        attr = GetFileAttributesW(path->wide);
-    else
-        attr = GetFileAttributesA(path->narrow);
-    if (attr == INVALID_FILE_ATTRIBUTES)
-        result = 0;
-    else {
-        if (mode & _S_IWRITE)
-            attr &= ~FILE_ATTRIBUTE_READONLY;
-        else
-            attr |= FILE_ATTRIBUTE_READONLY;
-        if (path->wide)
-            result = SetFileAttributesW(path->wide, attr);
-        else
-            result = SetFileAttributesA(path->narrow, attr);
-    }
-    Py_END_ALLOW_THREADS
-
-    if (!result) {
-        return path_error(path);
-    }
-#else /* MS_WINDOWS */
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_FCHMOD
-    if (path->fd != -1)
-        result = fchmod(path->fd, mode);
-    else
-#endif
-#ifdef HAVE_LCHMOD
-    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
-        result = lchmod(path->narrow, mode);
-    else
-#endif
-#ifdef HAVE_FCHMODAT
-    if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
-        /*
-         * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
-         * The documentation specifically shows how to use it,
-         * and then says it isn't implemented yet.
-         * (true on linux with glibc 2.15, and openindiana 3.x)
-         *
-         * Once it is supported, os.chmod will automatically
-         * support dir_fd and follow_symlinks=False.  (Hopefully.)
-         * Until then, we need to be careful what exception we raise.
-         */
-        result = fchmodat(dir_fd, path->narrow, mode,
-                          follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
-        /*
-         * But wait!  We can't throw the exception without allowing threads,
-         * and we can't do that in this nested scope.  (Macro trickery, sigh.)
-         */
-        fchmodat_nofollow_unsupported =
-                         result &&
-                         ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
-                         !follow_symlinks;
-    }
-    else
-#endif
-        result = chmod(path->narrow, mode);
-    Py_END_ALLOW_THREADS
-
-    if (result) {
-#ifdef HAVE_FCHMODAT
-        if (fchmodat_nofollow_unsupported) {
-            if (dir_fd != DEFAULT_DIR_FD)
-                dir_fd_and_follow_symlinks_invalid("chmod",
-                                                   dir_fd, follow_symlinks);
-            else
-                follow_symlinks_specified("chmod", follow_symlinks);
-        }
-        else
-#endif
-        return path_error(path);
-    }
-#endif
-
-    Py_RETURN_NONE;
-}
-
-
-#ifdef HAVE_FCHMOD
-/*[clinic input]
-os.fchmod
-
-    fd: int
-    mode: int
-
-Change the access permissions of the file given by file descriptor fd.
-
-Equivalent to os.chmod(fd, mode).
-[clinic start generated code]*/
+#if defined(HAVE_FCHMOD)
 
 PyDoc_STRVAR(os_fchmod__doc__,
 "fchmod($module, /, fd, mode)\n"
@@ -3244,38 +378,9 @@
     return return_value;
 }
 
-static PyObject *
-os_fchmod_impl(PyModuleDef *module, int fd, int mode)
-/*[clinic end generated code: output=3c19fbfd724a8e0f input=8ab11975ca01ee5b]*/
-{
-    int res;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = fchmod(fd, mode);
-        Py_END_ALLOW_THREADS
-    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res != 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_FCHMOD */
-
-
-#ifdef HAVE_LCHMOD
-/*[clinic input]
-os.lchmod
-
-    path: path_t
-    mode: int
-
-Change the access permissions of a file, without following symbolic links.
-
-If path is a symlink, this affects the link itself rather than the target.
-Equivalent to chmod(path, mode, follow_symlinks=False)."
-[clinic start generated code]*/
+#endif /* defined(HAVE_FCHMOD) */
+
+#if defined(HAVE_LCHMOD)
 
 PyDoc_STRVAR(os_lchmod__doc__,
 "lchmod($module, /, path, mode)\n"
@@ -3313,40 +418,9 @@
     return return_value;
 }
 
-static PyObject *
-os_lchmod_impl(PyModuleDef *module, path_t *path, int mode)
-/*[clinic end generated code: output=2849977d65f8c68c input=90c5663c7465d24f]*/
-{
-    int res;
-    Py_BEGIN_ALLOW_THREADS
-    res = lchmod(path->narrow, mode);
-    Py_END_ALLOW_THREADS
-    if (res < 0) {
-        path_error(path);
-        return NULL;
-    }
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_LCHMOD */
-
-
-#ifdef HAVE_CHFLAGS
-/*[clinic input]
-os.chflags
-
-    path: path_t
-    flags: unsigned_long(bitwise=True)
-    follow_symlinks: bool=True
-
-Set file flags.
-
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, chflags will change flags on the symbolic link itself instead of the
-  file the link points to.
-follow_symlinks may not be implemented on your platform.  If it is
-unavailable, using it will raise a NotImplementedError.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_LCHMOD) */
+
+#if defined(HAVE_CHFLAGS)
 
 PyDoc_STRVAR(os_chflags__doc__,
 "chflags($module, /, path, flags, follow_symlinks=True)\n"
@@ -3388,46 +462,9 @@
     return return_value;
 }
 
-static PyObject *
-os_chflags_impl(PyModuleDef *module, path_t *path, unsigned long flags, int follow_symlinks)
-/*[clinic end generated code: output=2767927bf071e3cf input=0327e29feb876236]*/
-{
-    int result;
-
-#ifndef HAVE_LCHFLAGS
-    if (follow_symlinks_specified("chflags", follow_symlinks))
-        return NULL;
-#endif
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_LCHFLAGS
-    if (!follow_symlinks)
-        result = lchflags(path->narrow, flags);
-    else
-#endif
-        result = chflags(path->narrow, flags);
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error(path);
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_CHFLAGS */
-
-
-#ifdef HAVE_LCHFLAGS
-/*[clinic input]
-os.lchflags
-
-    path: path_t
-    flags: unsigned_long(bitwise=True)
-
-Set file flags.
-
-This function will not follow symbolic links.
-Equivalent to chflags(path, flags, follow_symlinks=False).
-[clinic start generated code]*/
+#endif /* defined(HAVE_CHFLAGS) */
+
+#if defined(HAVE_LCHFLAGS)
 
 PyDoc_STRVAR(os_lchflags__doc__,
 "lchflags($module, /, path, flags)\n"
@@ -3465,30 +502,9 @@
     return return_value;
 }
 
-static PyObject *
-os_lchflags_impl(PyModuleDef *module, path_t *path, unsigned long flags)
-/*[clinic end generated code: output=bb93b6b8a5e45aa7 input=f9f82ea8b585ca9d]*/
-{
-    int res;
-    Py_BEGIN_ALLOW_THREADS
-    res = lchflags(path->narrow, flags);
-    Py_END_ALLOW_THREADS
-    if (res < 0) {
-        return path_error(path);
-    }
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_LCHFLAGS */
-
-
-#ifdef HAVE_CHROOT
-/*[clinic input]
-os.chroot
-    path: path_t
-
-Change root directory to path.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_LCHFLAGS) */
+
+#if defined(HAVE_CHROOT)
 
 PyDoc_STRVAR(os_chroot__doc__,
 "chroot($module, /, path)\n"
@@ -3522,29 +538,9 @@
     return return_value;
 }
 
-static PyObject *
-os_chroot_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=15b1256cbe4f24a1 input=14822965652c3dc3]*/
-{
-    int res;
-    Py_BEGIN_ALLOW_THREADS
-    res = chroot(path->narrow);
-    Py_END_ALLOW_THREADS
-    if (res < 0)
-        return path_error(path);
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_CHROOT */
-
-
-#ifdef HAVE_FSYNC
-/*[clinic input]
-os.fsync
-
-    fd: fildes
-
-Force write of fd to disk.
-[clinic start generated code]*/
+#endif /* defined(HAVE_CHROOT) */
+
+#if defined(HAVE_FSYNC)
 
 PyDoc_STRVAR(os_fsync__doc__,
 "fsync($module, /, fd)\n"
@@ -3575,21 +571,9 @@
     return return_value;
 }
 
-static PyObject *
-os_fsync_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=59f32d3a0b360133 input=21c3645c056967f2]*/
-{
-    return posix_fildes_fd(fd, fsync);
-}
-#endif /* HAVE_FSYNC */
-
-
-#ifdef HAVE_SYNC
-/*[clinic input]
-os.sync
-
-Force write of everything to disk.
-[clinic start generated code]*/
+#endif /* defined(HAVE_FSYNC) */
+
+#if defined(HAVE_SYNC)
 
 PyDoc_STRVAR(os_sync__doc__,
 "sync($module, /)\n"
@@ -3609,30 +593,9 @@
     return os_sync_impl(module);
 }
 
-static PyObject *
-os_sync_impl(PyModuleDef *module)
-/*[clinic end generated code: output=526c495683d0bb38 input=84749fe5e9b404ff]*/
-{
-    Py_BEGIN_ALLOW_THREADS
-    sync();
-    Py_END_ALLOW_THREADS
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SYNC */
-
-
-#ifdef HAVE_FDATASYNC
-#ifdef __hpux
-extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
-#endif
-
-/*[clinic input]
-os.fdatasync
-
-    fd: fildes
-
-Force write of fd to disk without forcing update of metadata.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYNC) */
+
+#if defined(HAVE_FDATASYNC)
 
 PyDoc_STRVAR(os_fdatasync__doc__,
 "fdatasync($module, /, fd)\n"
@@ -3663,54 +626,9 @@
     return return_value;
 }
 
-static PyObject *
-os_fdatasync_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=2335fdfd37c92180 input=bc74791ee54dd291]*/
-{
-    return posix_fildes_fd(fd, fdatasync);
-}
-#endif /* HAVE_FDATASYNC */
-
-
-#ifdef HAVE_CHOWN
-/*[clinic input]
-os.chown
-
-    path : path_t(allow_fd='PATH_HAVE_FCHOWN')
-        Path to be examined; can be string, bytes, or open-file-descriptor int.
-
-    uid: uid_t
-
-    gid: gid_t
-
-    *
-
-    dir_fd : dir_fd(requires='fchownat') = None
-        If not None, it should be a file descriptor open to a directory,
-        and path should be relative; path will then be relative to that
-        directory.
-
-    follow_symlinks: bool = True
-        If False, and the last element of the path is a symbolic link,
-        stat will examine the symbolic link itself instead of the file
-        the link points to.
-
-Change the owner and group id of path to the numeric uid and gid.\
-
-path may always be specified as a string.
-On some platforms, path may also be specified as an open file descriptor.
-  If this functionality is unavailable, using it raises an exception.
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, chown will modify the symbolic link itself instead of the file the
-  link points to.
-It is an error to use dir_fd or follow_symlinks when specifying path as
-  an open file descriptor.
-dir_fd and follow_symlinks may not be implemented on your platform.
-  If they are unavailable, using them will raise a NotImplementedError.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_FDATASYNC) */
+
+#if defined(HAVE_CHOWN)
 
 PyDoc_STRVAR(os_chown__doc__,
 "chown($module, /, path, uid, gid, *, dir_fd=None, follow_symlinks=True)\n"
@@ -3772,74 +690,9 @@
     return return_value;
 }
 
-static PyObject *
-os_chown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=22f011e3b4f9ff49 input=a61cc35574814d5d]*/
-{
-    int result;
-
-#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
-    if (follow_symlinks_specified("chown", follow_symlinks))
-        return NULL;
-#endif
-    if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
-        fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
-        return NULL;
-
-#ifdef __APPLE__
-    /*
-     * This is for Mac OS X 10.3, which doesn't have lchown.
-     * (But we still have an lchown symbol because of weak-linking.)
-     * It doesn't have fchownat either.  So there's no possibility
-     * of a graceful failover.
-     */
-    if ((!follow_symlinks) && (lchown == NULL)) {
-        follow_symlinks_specified("chown", follow_symlinks);
-        return NULL;
-    }
-#endif
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_FCHOWN
-    if (path->fd != -1)
-        result = fchown(path->fd, uid, gid);
-    else
-#endif
-#ifdef HAVE_LCHOWN
-    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
-        result = lchown(path->narrow, uid, gid);
-    else
-#endif
-#ifdef HAVE_FCHOWNAT
-    if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
-        result = fchownat(dir_fd, path->narrow, uid, gid,
-                          follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
-    else
-#endif
-        result = chown(path->narrow, uid, gid);
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error(path);
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_CHOWN */
-
-
-#ifdef HAVE_FCHOWN
-/*[clinic input]
-os.fchown
-
-    fd: int
-    uid: uid_t
-    gid: gid_t
-
-Change the owner and group id of the file specified by file descriptor.
-
-Equivalent to os.chown(fd, uid, gid).
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_CHOWN) */
+
+#if defined(HAVE_FCHOWN)
 
 PyDoc_STRVAR(os_fchown__doc__,
 "fchown($module, /, fd, uid, gid)\n"
@@ -3874,39 +727,9 @@
     return return_value;
 }
 
-static PyObject *
-os_fchown_impl(PyModuleDef *module, int fd, uid_t uid, gid_t gid)
-/*[clinic end generated code: output=687781cb7d8974d6 input=3af544ba1b13a0d7]*/
-{
-    int res;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = fchown(fd, uid, gid);
-        Py_END_ALLOW_THREADS
-    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res != 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_FCHOWN */
-
-
-#ifdef HAVE_LCHOWN
-/*[clinic input]
-os.lchown
-
-    path : path_t
-    uid: uid_t
-    gid: gid_t
-
-Change the owner and group id of path to the numeric uid and gid.
-
-This function will not follow symbolic links.
-Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
-[clinic start generated code]*/
+#endif /* defined(HAVE_FCHOWN) */
+
+#if defined(HAVE_LCHOWN)
 
 PyDoc_STRVAR(os_lchown__doc__,
 "lchown($module, /, path, uid, gid)\n"
@@ -3945,80 +768,7 @@
     return return_value;
 }
 
-static PyObject *
-os_lchown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid)
-/*[clinic end generated code: output=bf25fdb0d25130e2 input=b1c6014d563a7161]*/
-{
-    int res;
-    Py_BEGIN_ALLOW_THREADS
-    res = lchown(path->narrow, uid, gid);
-    Py_END_ALLOW_THREADS
-    if (res < 0) {
-        return path_error(path);
-    }
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_LCHOWN */
-
-
-static PyObject *
-posix_getcwd(int use_bytes)
-{
-    char buf[1026];
-    char *res;
-
-#ifdef MS_WINDOWS
-    if (!use_bytes) {
-        wchar_t wbuf[1026];
-        wchar_t *wbuf2 = wbuf;
-        PyObject *resobj;
-        DWORD len;
-        Py_BEGIN_ALLOW_THREADS
-        len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
-        /* If the buffer is large enough, len does not include the
-           terminating \0. If the buffer is too small, len includes
-           the space needed for the terminator. */
-        if (len >= Py_ARRAY_LENGTH(wbuf)) {
-            wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
-            if (wbuf2)
-                len = GetCurrentDirectoryW(len, wbuf2);
-        }
-        Py_END_ALLOW_THREADS
-        if (!wbuf2) {
-            PyErr_NoMemory();
-            return NULL;
-        }
-        if (!len) {
-            if (wbuf2 != wbuf)
-                PyMem_RawFree(wbuf2);
-            return PyErr_SetFromWindowsErr(0);
-        }
-        resobj = PyUnicode_FromWideChar(wbuf2, len);
-        if (wbuf2 != wbuf)
-            PyMem_RawFree(wbuf2);
-        return resobj;
-    }
-
-    if (win32_warn_bytes_api())
-        return NULL;
-#endif
-
-    Py_BEGIN_ALLOW_THREADS
-    res = getcwd(buf, sizeof buf);
-    Py_END_ALLOW_THREADS
-    if (res == NULL)
-        return posix_error();
-    if (use_bytes)
-        return PyBytes_FromStringAndSize(buf, strlen(buf));
-    return PyUnicode_DecodeFSDefault(buf);
-}
-
-
-/*[clinic input]
-os.getcwd
-
-Return a unicode string representing the current working directory.
-[clinic start generated code]*/
+#endif /* defined(HAVE_LCHOWN) */
 
 PyDoc_STRVAR(os_getcwd__doc__,
 "getcwd($module, /)\n"
@@ -4038,20 +788,6 @@
     return os_getcwd_impl(module);
 }
 
-static PyObject *
-os_getcwd_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d70b281db5c78ff7 input=f069211bb70e3d39]*/
-{
-    return posix_getcwd(0);
-}
-
-
-/*[clinic input]
-os.getcwdb
-
-Return a bytes string representing the current working directory.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_getcwdb__doc__,
 "getcwdb($module, /)\n"
 "--\n"
@@ -4070,42 +806,7 @@
     return os_getcwdb_impl(module);
 }
 
-static PyObject *
-os_getcwdb_impl(PyModuleDef *module)
-/*[clinic end generated code: output=75da47f2d75f9166 input=f6f6a378dad3d9cb]*/
-{
-    return posix_getcwd(1);
-}
-
-
-#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
-#define HAVE_LINK 1
-#endif
-
-#ifdef HAVE_LINK
-/*[clinic input]
-
-os.link
-
-    src : path_t
-    dst : path_t
-    *
-    src_dir_fd : dir_fd = None
-    dst_dir_fd : dir_fd = None
-    follow_symlinks: bool = True
-
-Create a hard link to a file.
-
-If either src_dir_fd or dst_dir_fd is not None, it should be a file
-  descriptor open to a directory, and the respective path string (src or dst)
-  should be relative; the path will then be relative to that directory.
-If follow_symlinks is False, and the last element of src is a symbolic
-  link, link will create a link to the symbolic link itself instead of the
-  file the link points to.
-src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
-  platform.  If they are unavailable, using them will raise a
-  NotImplementedError.
-[clinic start generated code]*/
+#if defined(HAVE_LINK)
 
 PyDoc_STRVAR(os_link__doc__,
 "link($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None,\n"
@@ -4156,345 +857,7 @@
     return return_value;
 }
 
-static PyObject *
-os_link_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=53477662fe02e183 input=b0095ebbcbaa7e04]*/
-{
-#ifdef MS_WINDOWS
-    BOOL result;
-#else
-    int result;
-#endif
-
-#ifndef HAVE_LINKAT
-    if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
-        argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
-        return NULL;
-    }
-#endif
-
-    if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
-        PyErr_SetString(PyExc_NotImplementedError,
-                        "link: src and dst must be the same type");
-        return NULL;
-    }
-
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    if (src->wide)
-        result = CreateHardLinkW(dst->wide, src->wide, NULL);
-    else
-        result = CreateHardLinkA(dst->narrow, src->narrow, NULL);
-    Py_END_ALLOW_THREADS
-
-    if (!result)
-        return path_error2(src, dst);
-#else
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_LINKAT
-    if ((src_dir_fd != DEFAULT_DIR_FD) ||
-        (dst_dir_fd != DEFAULT_DIR_FD) ||
-        (!follow_symlinks))
-        result = linkat(src_dir_fd, src->narrow,
-            dst_dir_fd, dst->narrow,
-            follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
-    else
-#endif
-        result = link(src->narrow, dst->narrow);
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error2(src, dst);
-#endif
-
-    Py_RETURN_NONE;
-}
-#endif
-
-
-#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
-static PyObject *
-_listdir_windows_no_opendir(path_t *path, PyObject *list)
-{
-    PyObject *v;
-    HANDLE hFindFile = INVALID_HANDLE_VALUE;
-    BOOL result;
-    WIN32_FIND_DATA FileData;
-    char namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
-    char *bufptr = namebuf;
-    /* only claim to have space for MAX_PATH */
-    Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
-    PyObject *po = NULL;
-    wchar_t *wnamebuf = NULL;
-
-    if (!path->narrow) {
-        WIN32_FIND_DATAW wFileData;
-        wchar_t *po_wchars;
-
-        if (!path->wide) { /* Default arg: "." */
-            po_wchars = L".";
-            len = 1;
-        } else {
-            po_wchars = path->wide;
-            len = wcslen(path->wide);
-        }
-        /* The +5 is so we can append "\\*.*\0" */
-        wnamebuf = PyMem_New(wchar_t, len + 5);
-        if (!wnamebuf) {
-            PyErr_NoMemory();
-            goto exit;
-        }
-        wcscpy(wnamebuf, po_wchars);
-        if (len > 0) {
-            wchar_t wch = wnamebuf[len-1];
-            if (wch != SEP && wch != ALTSEP && wch != L':')
-                wnamebuf[len++] = SEP;
-            wcscpy(wnamebuf + len, L"*.*");
-        }
-        if ((list = PyList_New(0)) == NULL) {
-            goto exit;
-        }
-        Py_BEGIN_ALLOW_THREADS
-        hFindFile = FindFirstFileW(wnamebuf, &wFileData);
-        Py_END_ALLOW_THREADS
-        if (hFindFile == INVALID_HANDLE_VALUE) {
-            int error = GetLastError();
-            if (error == ERROR_FILE_NOT_FOUND)
-                goto exit;
-            Py_DECREF(list);
-            list = path_error(path);
-            goto exit;
-        }
-        do {
-            /* Skip over . and .. */
-            if (wcscmp(wFileData.cFileName, L".") != 0 &&
-                wcscmp(wFileData.cFileName, L"..") != 0) {
-                v = PyUnicode_FromWideChar(wFileData.cFileName,
-                                           wcslen(wFileData.cFileName));
-                if (v == NULL) {
-                    Py_DECREF(list);
-                    list = NULL;
-                    break;
-                }
-                if (PyList_Append(list, v) != 0) {
-                    Py_DECREF(v);
-                    Py_DECREF(list);
-                    list = NULL;
-                    break;
-                }
-                Py_DECREF(v);
-            }
-            Py_BEGIN_ALLOW_THREADS
-            result = FindNextFileW(hFindFile, &wFileData);
-            Py_END_ALLOW_THREADS
-            /* FindNextFile sets error to ERROR_NO_MORE_FILES if
-               it got to the end of the directory. */
-            if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
-                Py_DECREF(list);
-                list = path_error(path);
-                goto exit;
-            }
-        } while (result == TRUE);
-
-        goto exit;
-    }
-    strcpy(namebuf, path->narrow);
-    len = path->length;
-    if (len > 0) {
-        char ch = namebuf[len-1];
-        if (ch != '\\' && ch != '/' && ch != ':')
-            namebuf[len++] = '\\';
-        strcpy(namebuf + len, "*.*");
-    }
-
-    if ((list = PyList_New(0)) == NULL)
-        return NULL;
-
-    Py_BEGIN_ALLOW_THREADS
-    hFindFile = FindFirstFile(namebuf, &FileData);
-    Py_END_ALLOW_THREADS
-    if (hFindFile == INVALID_HANDLE_VALUE) {
-        int error = GetLastError();
-        if (error == ERROR_FILE_NOT_FOUND)
-            goto exit;
-        Py_DECREF(list);
-        list = path_error(path);
-        goto exit;
-    }
-    do {
-        /* Skip over . and .. */
-        if (strcmp(FileData.cFileName, ".") != 0 &&
-            strcmp(FileData.cFileName, "..") != 0) {
-            v = PyBytes_FromString(FileData.cFileName);
-            if (v == NULL) {
-                Py_DECREF(list);
-                list = NULL;
-                break;
-            }
-            if (PyList_Append(list, v) != 0) {
-                Py_DECREF(v);
-                Py_DECREF(list);
-                list = NULL;
-                break;
-            }
-            Py_DECREF(v);
-        }
-        Py_BEGIN_ALLOW_THREADS
-        result = FindNextFile(hFindFile, &FileData);
-        Py_END_ALLOW_THREADS
-        /* FindNextFile sets error to ERROR_NO_MORE_FILES if
-           it got to the end of the directory. */
-        if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
-            Py_DECREF(list);
-            list = path_error(path);
-            goto exit;
-        }
-    } while (result == TRUE);
-
-exit:
-    if (hFindFile != INVALID_HANDLE_VALUE) {
-        if (FindClose(hFindFile) == FALSE) {
-            if (list != NULL) {
-                Py_DECREF(list);
-                list = path_error(path);
-            }
-        }
-    }
-    PyMem_Free(wnamebuf);
-
-    return list;
-}  /* end of _listdir_windows_no_opendir */
-
-#else  /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
-
-static PyObject *
-_posix_listdir(path_t *path, PyObject *list)
-{
-    PyObject *v;
-    DIR *dirp = NULL;
-    struct dirent *ep;
-    int return_str; /* if false, return bytes */
-#ifdef HAVE_FDOPENDIR
-    int fd = -1;
-#endif
-
-    errno = 0;
-#ifdef HAVE_FDOPENDIR
-    if (path->fd != -1) {
-        /* closedir() closes the FD, so we duplicate it */
-        fd = _Py_dup(path->fd);
-        if (fd == -1)
-            return NULL;
-
-        return_str = 1;
-
-        Py_BEGIN_ALLOW_THREADS
-        dirp = fdopendir(fd);
-        Py_END_ALLOW_THREADS
-    }
-    else
-#endif
-    {
-        char *name;
-        if (path->narrow) {
-            name = path->narrow;
-            /* only return bytes if they specified a bytes object */
-            return_str = !(PyBytes_Check(path->object));
-        }
-        else {
-            name = ".";
-            return_str = 1;
-        }
-
-        Py_BEGIN_ALLOW_THREADS
-        dirp = opendir(name);
-        Py_END_ALLOW_THREADS
-    }
-
-    if (dirp == NULL) {
-        list = path_error(path);
-#ifdef HAVE_FDOPENDIR
-        if (fd != -1) {
-            Py_BEGIN_ALLOW_THREADS
-            close(fd);
-            Py_END_ALLOW_THREADS
-        }
-#endif
-        goto exit;
-    }
-    if ((list = PyList_New(0)) == NULL) {
-        goto exit;
-    }
-    for (;;) {
-        errno = 0;
-        Py_BEGIN_ALLOW_THREADS
-        ep = readdir(dirp);
-        Py_END_ALLOW_THREADS
-        if (ep == NULL) {
-            if (errno == 0) {
-                break;
-            } else {
-                Py_DECREF(list);
-                list = path_error(path);
-                goto exit;
-            }
-        }
-        if (ep->d_name[0] == '.' &&
-            (NAMLEN(ep) == 1 ||
-             (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
-            continue;
-        if (return_str)
-            v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
-        else
-            v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
-        if (v == NULL) {
-            Py_CLEAR(list);
-            break;
-        }
-        if (PyList_Append(list, v) != 0) {
-            Py_DECREF(v);
-            Py_CLEAR(list);
-            break;
-        }
-        Py_DECREF(v);
-    }
-
-exit:
-    if (dirp != NULL) {
-        Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_FDOPENDIR
-        if (fd > -1)
-            rewinddir(dirp);
-#endif
-        closedir(dirp);
-        Py_END_ALLOW_THREADS
-    }
-
-    return list;
-}  /* end of _posix_listdir */
-#endif  /* which OS */
-
-
-/*[clinic input]
-os.listdir
-
-    path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
-
-Return a list containing the names of the files in the directory.
-
-path can be specified as either str or bytes.  If path is bytes,
-  the filenames returned will also be bytes; in all other circumstances
-  the filenames returned will be str.
-If path is None, uses the path='.'.
-On some platforms, path may also be specified as an open file descriptor;\
-  the file descriptor must refer to a directory.
-  If this functionality is unavailable, using it raises NotImplementedError.
-
-The list is in arbitrary order.  It does not include the special
-entries '.' and '..' even if they are present in the directory.
-
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_LINK) */
 
 PyDoc_STRVAR(os_listdir__doc__,
 "listdir($module, /, path=None)\n"
@@ -4539,86 +902,7 @@
     return return_value;
 }
 
-static PyObject *
-os_listdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=e159bd9be6909018 input=09e300416e3cd729]*/
-{
-#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
-    return _listdir_windows_no_opendir(path, NULL);
-#else
-    return _posix_listdir(path, NULL);
-#endif
-}
-
-#ifdef MS_WINDOWS
-/* A helper function for abspath on win32 */
-/* AC 3.5: probably just convert to using path converter */
-static PyObject *
-posix__getfullpathname(PyObject *self, PyObject *args)
-{
-    const char *path;
-    char outbuf[MAX_PATH];
-    char *temp;
-    PyObject *po;
-
-    if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po))
-    {
-        wchar_t *wpath;
-        wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
-        wchar_t *wtemp;
-        DWORD result;
-        PyObject *v;
-
-        wpath = PyUnicode_AsUnicode(po);
-        if (wpath == NULL)
-            return NULL;
-        result = GetFullPathNameW(wpath,
-                                  Py_ARRAY_LENGTH(woutbuf),
-                                  woutbuf, &wtemp);
-        if (result > Py_ARRAY_LENGTH(woutbuf)) {
-            woutbufp = PyMem_New(wchar_t, result);
-            if (!woutbufp)
-                return PyErr_NoMemory();
-            result = GetFullPathNameW(wpath, result, woutbufp, &wtemp);
-        }
-        if (result)
-            v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
-        else
-            v = win32_error_object("GetFullPathNameW", po);
-        if (woutbufp != woutbuf)
-            PyMem_Free(woutbufp);
-        return v;
-    }
-    /* Drop the argument parsing error as narrow strings
-       are also valid. */
-    PyErr_Clear();
-
-    if (!PyArg_ParseTuple (args, "y:_getfullpathname",
-                           &path))
-        return NULL;
-    if (win32_warn_bytes_api())
-        return NULL;
-    if (!GetFullPathName(path, Py_ARRAY_LENGTH(outbuf),
-                         outbuf, &temp)) {
-        win32_error("GetFullPathName", path);
-        return NULL;
-    }
-    if (PyUnicode_Check(PyTuple_GetItem(args, 0))) {
-        return PyUnicode_Decode(outbuf, strlen(outbuf),
-                                Py_FileSystemDefaultEncoding, NULL);
-    }
-    return PyBytes_FromString(outbuf);
-}
-
-
-/*[clinic input]
-os._getfinalpathname
-
-    path: unicode
-    /
-
-A helper function for samepath on windows.
-[clinic start generated code]*/
+#if defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os__getfinalpathname__doc__,
 "_getfinalpathname($module, path, /)\n"
@@ -4648,107 +932,9 @@
     return return_value;
 }
 
-static PyObject *
-os__getfinalpathname_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=4563c6eacf1b0881 input=71d5e89334891bf4]*/
-{
-    HANDLE hFile;
-    int buf_size;
-    wchar_t *target_path;
-    int result_length;
-    PyObject *result;
-    wchar_t *path_wchar;
-
-    path_wchar = PyUnicode_AsUnicode(path);
-    if (path_wchar == NULL)
-        return NULL;
-
-    hFile = CreateFileW(
-        path_wchar,
-        0, /* desired access */
-        0, /* share mode */
-        NULL, /* security attributes */
-        OPEN_EXISTING,
-        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
-        FILE_FLAG_BACKUP_SEMANTICS,
-        NULL);
-
-    if(hFile == INVALID_HANDLE_VALUE)
-        return win32_error_object("CreateFileW", path);
-
-    /* We have a good handle to the target, use it to determine the
-       target path name. */
-    buf_size = GetFinalPathNameByHandleW(hFile, 0, 0, VOLUME_NAME_NT);
-
-    if(!buf_size)
-        return win32_error_object("GetFinalPathNameByHandle", path);
-
-    target_path = PyMem_New(wchar_t, buf_size+1);
-    if(!target_path)
-        return PyErr_NoMemory();
-
-    result_length = GetFinalPathNameByHandleW(hFile, target_path,
-                                              buf_size, VOLUME_NAME_DOS);
-    if(!result_length)
-        return win32_error_object("GetFinalPathNamyByHandle", path);
-
-    if(!CloseHandle(hFile))
-        return win32_error_object("CloseHandle", path);
-
-    target_path[result_length] = 0;
-    result = PyUnicode_FromWideChar(target_path, result_length);
-    PyMem_Free(target_path);
-    return result;
-}
-
-PyDoc_STRVAR(posix__isdir__doc__,
-"Return true if the pathname refers to an existing directory.");
-
-/* AC 3.5: convert using path converter */
-static PyObject *
-posix__isdir(PyObject *self, PyObject *args)
-{
-    const char *path;
-    PyObject *po;
-    DWORD attributes;
-
-    if (PyArg_ParseTuple(args, "U|:_isdir", &po)) {
-        wchar_t *wpath = PyUnicode_AsUnicode(po);
-        if (wpath == NULL)
-            return NULL;
-
-        attributes = GetFileAttributesW(wpath);
-        if (attributes == INVALID_FILE_ATTRIBUTES)
-            Py_RETURN_FALSE;
-        goto check;
-    }
-    /* Drop the argument parsing error as narrow strings
-       are also valid. */
-    PyErr_Clear();
-
-    if (!PyArg_ParseTuple(args, "y:_isdir", &path))
-        return NULL;
-    if (win32_warn_bytes_api())
-        return NULL;
-    attributes = GetFileAttributesA(path);
-    if (attributes == INVALID_FILE_ATTRIBUTES)
-        Py_RETURN_FALSE;
-
-check:
-    if (attributes & FILE_ATTRIBUTE_DIRECTORY)
-        Py_RETURN_TRUE;
-    else
-        Py_RETURN_FALSE;
-}
-
-
-/*[clinic input]
-os._getvolumepathname
-
-    path: unicode
-
-A helper function for ismount on Win32.
-[clinic start generated code]*/
+#endif /* defined(MS_WINDOWS) */
+
+#if defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os__getvolumepathname__doc__,
 "_getvolumepathname($module, /, path)\n"
@@ -4779,73 +965,7 @@
     return return_value;
 }
 
-static PyObject *
-os__getvolumepathname_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=ac0833b6d6da7657 input=7eacadc40acbda6b]*/
-{
-    PyObject *result;
-    wchar_t *path_wchar, *mountpath=NULL;
-    size_t buflen;
-    BOOL ret;
-
-    path_wchar = PyUnicode_AsUnicodeAndSize(path, &buflen);
-    if (path_wchar == NULL)
-        return NULL;
-    buflen += 1;
-
-    /* Volume path should be shorter than entire path */
-    buflen = Py_MAX(buflen, MAX_PATH);
-
-    if (buflen > DWORD_MAX) {
-        PyErr_SetString(PyExc_OverflowError, "path too long");
-        return NULL;
-    }
-
-    mountpath = PyMem_New(wchar_t, buflen);
-    if (mountpath == NULL)
-        return PyErr_NoMemory();
-
-    Py_BEGIN_ALLOW_THREADS
-    ret = GetVolumePathNameW(path_wchar, mountpath,
-                             Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
-    Py_END_ALLOW_THREADS
-
-    if (!ret) {
-        result = win32_error_object("_getvolumepathname", path);
-        goto exit;
-    }
-    result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
-
-exit:
-    PyMem_Free(mountpath);
-    return result;
-}
-
-#endif /* MS_WINDOWS */
-
-
-/*[clinic input]
-os.mkdir
-
-    path : path_t
-
-    mode: int = 0o777
-
-    *
-
-    dir_fd : dir_fd(requires='mkdirat') = None
-
-# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
-
-Create a directory.
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-
-The mode argument is ignored on Windows.
-[clinic start generated code]*/
+#endif /* defined(MS_WINDOWS) */
 
 PyDoc_STRVAR(os_mkdir__doc__,
 "mkdir($module, /, path, mode=511, *, dir_fd=None)\n"
@@ -4888,57 +1008,7 @@
     return return_value;
 }
 
-static PyObject *
-os_mkdir_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd)
-/*[clinic end generated code: output=55c6ef2bc1b207e6 input=e965f68377e9b1ce]*/
-{
-    int result;
-
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    if (path->wide)
-        result = CreateDirectoryW(path->wide, NULL);
-    else
-        result = CreateDirectoryA(path->narrow, NULL);
-    Py_END_ALLOW_THREADS
-
-    if (!result)
-        return path_error(path);
-#else
-    Py_BEGIN_ALLOW_THREADS
-#if HAVE_MKDIRAT
-    if (dir_fd != DEFAULT_DIR_FD)
-        result = mkdirat(dir_fd, path->narrow, mode);
-    else
-#endif
-#if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
-        result = mkdir(path->narrow);
-#else
-        result = mkdir(path->narrow, mode);
-#endif
-    Py_END_ALLOW_THREADS
-    if (result < 0)
-        return path_error(path);
-#endif
-    Py_RETURN_NONE;
-}
-
-
-/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
-#if defined(HAVE_SYS_RESOURCE_H)
-#include <sys/resource.h>
-#endif
-
-
-#ifdef HAVE_NICE
-/*[clinic input]
-os.nice
-
-    increment: int
-    /
-
-Add increment to the priority of process and return the new priority.
-[clinic start generated code]*/
+#if defined(HAVE_NICE)
 
 PyDoc_STRVAR(os_nice__doc__,
 "nice($module, increment, /)\n"
@@ -4968,45 +1038,9 @@
     return return_value;
 }
 
-static PyObject *
-os_nice_impl(PyModuleDef *module, int increment)
-/*[clinic end generated code: output=c360dc2a3bd8e3d0 input=864be2d402a21da2]*/
-{
-    int value;
-
-    /* There are two flavours of 'nice': one that returns the new
-       priority (as required by almost all standards out there) and the
-       Linux/FreeBSD/BSDI one, which returns '0' on success and advices
-       the use of getpriority() to get the new priority.
-
-       If we are of the nice family that returns the new priority, we
-       need to clear errno before the call, and check if errno is filled
-       before calling posix_error() on a returnvalue of -1, because the
-       -1 may be the actual new priority! */
-
-    errno = 0;
-    value = nice(increment);
-#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
-    if (value == 0)
-        value = getpriority(PRIO_PROCESS, 0);
-#endif
-    if (value == -1 && errno != 0)
-        /* either nice() or getpriority() returned an error */
-        return posix_error();
-    return PyLong_FromLong((long) value);
-}
-#endif /* HAVE_NICE */
-
-
-#ifdef HAVE_GETPRIORITY
-/*[clinic input]
-os.getpriority
-
-    which: int
-    who: int
-
-Return program scheduling priority.
-[clinic start generated code]*/
+#endif /* defined(HAVE_NICE) */
+
+#if defined(HAVE_GETPRIORITY)
 
 PyDoc_STRVAR(os_getpriority__doc__,
 "getpriority($module, /, which, who)\n"
@@ -5038,31 +1072,9 @@
     return return_value;
 }
 
-static PyObject *
-os_getpriority_impl(PyModuleDef *module, int which, int who)
-/*[clinic end generated code: output=81639cf765f05dae input=9be615d40e2544ef]*/
-{
-    int retval;
-
-    errno = 0;
-    retval = getpriority(which, who);
-    if (errno != 0)
-        return posix_error();
-    return PyLong_FromLong((long)retval);
-}
-#endif /* HAVE_GETPRIORITY */
-
-
-#ifdef HAVE_SETPRIORITY
-/*[clinic input]
-os.setpriority
-
-    which: int
-    who: int
-    priority: int
-
-Set program scheduling priority.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETPRIORITY) */
+
+#if defined(HAVE_SETPRIORITY)
 
 PyDoc_STRVAR(os_setpriority__doc__,
 "setpriority($module, /, which, who, priority)\n"
@@ -5095,93 +1107,7 @@
     return return_value;
 }
 
-static PyObject *
-os_setpriority_impl(PyModuleDef *module, int which, int who, int priority)
-/*[clinic end generated code: output=ddad62651fb2120c input=710ccbf65b9dc513]*/
-{
-    int retval;
-
-    retval = setpriority(which, who, priority);
-    if (retval == -1)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETPRIORITY */
-
-
-static PyObject *
-internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
-{
-    char *function_name = is_replace ? "replace" : "rename";
-    int dir_fd_specified;
-
-#ifdef MS_WINDOWS
-    BOOL result;
-    int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
-#else
-    int result;
-#endif
-
-    dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
-                       (dst_dir_fd != DEFAULT_DIR_FD);
-#ifndef HAVE_RENAMEAT
-    if (dir_fd_specified) {
-        argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
-        return NULL;
-    }
-#endif
-
-    if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
-        PyErr_Format(PyExc_ValueError,
-                     "%s: src and dst must be the same type", function_name);
-        return NULL;
-    }
-
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    if (src->wide)
-        result = MoveFileExW(src->wide, dst->wide, flags);
-    else
-        result = MoveFileExA(src->narrow, dst->narrow, flags);
-    Py_END_ALLOW_THREADS
-
-    if (!result)
-        return path_error2(src, dst);
-
-#else
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_RENAMEAT
-    if (dir_fd_specified)
-        result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
-    else
-#endif
-        result = rename(src->narrow, dst->narrow);
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error2(src, dst);
-#endif
-    Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.rename
-
-    src : path_t
-    dst : path_t
-    *
-    src_dir_fd : dir_fd = None
-    dst_dir_fd : dir_fd = None
-
-Rename a file or directory.
-
-If either src_dir_fd or dst_dir_fd is not None, it should be a file
-  descriptor open to a directory, and the respective path string (src or dst)
-  should be relative; the path will then be relative to that directory.
-src_dir_fd and dst_dir_fd, may not be implemented on your platform.
-  If they are unavailable, using them will raise a NotImplementedError.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETPRIORITY) */
 
 PyDoc_STRVAR(os_rename__doc__,
 "rename($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None)\n"
@@ -5226,26 +1152,6 @@
     return return_value;
 }
 
-static PyObject *
-os_rename_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd)
-/*[clinic end generated code: output=c936bdc81f460a1e input=faa61c847912c850]*/
-{
-    return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
-}
-
-
-/*[clinic input]
-os.replace = os.rename
-
-Rename a file or directory, overwriting the destination.
-
-If either src_dir_fd or dst_dir_fd is not None, it should be a file
-  descriptor open to a directory, and the respective path string (src or dst)
-  should be relative; the path will then be relative to that directory.
-src_dir_fd and dst_dir_fd, may not be implemented on your platform.
-  If they are unavailable, using them will raise a NotImplementedError."
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_replace__doc__,
 "replace($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None)\n"
 "--\n"
@@ -5289,29 +1195,6 @@
     return return_value;
 }
 
-static PyObject *
-os_replace_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd)
-/*[clinic end generated code: output=224e4710d290d171 input=25515dfb107c8421]*/
-{
-    return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
-}
-
-
-/*[clinic input]
-os.rmdir
-
-    path: path_t
-    *
-    dir_fd: dir_fd(requires='unlinkat') = None
-
-Remove a directory.
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_rmdir__doc__,
 "rmdir($module, /, path, *, dir_fd=None)\n"
 "--\n"
@@ -5350,45 +1233,7 @@
     return return_value;
 }
 
-static PyObject *
-os_rmdir_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=70b9fdbe3bee0591 input=38c8b375ca34a7e2]*/
-{
-    int result;
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef MS_WINDOWS
-    if (path->wide)
-        result = RemoveDirectoryW(path->wide);
-    else
-        result = RemoveDirectoryA(path->narrow);
-    result = !result; /* Windows, success=1, UNIX, success=0 */
-#else
-#ifdef HAVE_UNLINKAT
-    if (dir_fd != DEFAULT_DIR_FD)
-        result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
-    else
-#endif
-        result = rmdir(path->narrow);
-#endif
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error(path);
-
-    Py_RETURN_NONE;
-}
-
-
-#ifdef HAVE_SYSTEM
-#ifdef MS_WINDOWS
-/*[clinic input]
-os.system -> long
-
-    command: Py_UNICODE
-
-Execute the command in a subshell.
-[clinic start generated code]*/
+#if defined(HAVE_SYSTEM) && defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os_system__doc__,
 "system($module, /, command)\n"
@@ -5423,24 +1268,9 @@
     return return_value;
 }
 
-static long
-os_system_impl(PyModuleDef *module, Py_UNICODE *command)
-/*[clinic end generated code: output=29fe699c0b2e9d38 input=303f5ce97df606b0]*/
-{
-    long result;
-    Py_BEGIN_ALLOW_THREADS
-    result = _wsystem(command);
-    Py_END_ALLOW_THREADS
-    return result;
-}
-#else /* MS_WINDOWS */
-/*[clinic input]
-os.system -> long
-
-    command: FSConverter
-
-Execute the command in a subshell.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYSTEM) && defined(MS_WINDOWS) */
+
+#if defined(HAVE_SYSTEM) && !defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os_system__doc__,
 "system($module, /, command)\n"
@@ -5478,29 +1308,7 @@
     return return_value;
 }
 
-static long
-os_system_impl(PyModuleDef *module, PyObject *command)
-/*[clinic end generated code: output=5be9f3c40ead3bad input=86a58554ba6094af]*/
-{
-    long result;
-    char *bytes = PyBytes_AsString(command);
-    Py_BEGIN_ALLOW_THREADS
-    result = system(bytes);
-    Py_END_ALLOW_THREADS
-    return result;
-}
-#endif
-#endif /* HAVE_SYSTEM */
-
-
-/*[clinic input]
-os.umask
-
-    mask: int
-    /
-
-Set the current numeric umask and return the previous umask.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYSTEM) && !defined(MS_WINDOWS) */
 
 PyDoc_STRVAR(os_umask__doc__,
 "umask($module, mask, /)\n"
@@ -5530,72 +1338,6 @@
     return return_value;
 }
 
-static PyObject *
-os_umask_impl(PyModuleDef *module, int mask)
-/*[clinic end generated code: output=90048b39d2d4a961 input=ab6bfd9b24d8a7e8]*/
-{
-    int i = (int)umask(mask);
-    if (i < 0)
-        return posix_error();
-    return PyLong_FromLong((long)i);
-}
-
-#ifdef MS_WINDOWS
-
-/* override the default DeleteFileW behavior so that directory
-symlinks can be removed with this function, the same as with
-Unix symlinks */
-BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
-{
-    WIN32_FILE_ATTRIBUTE_DATA info;
-    WIN32_FIND_DATAW find_data;
-    HANDLE find_data_handle;
-    int is_directory = 0;
-    int is_link = 0;
-
-    if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
-        is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
-
-        /* Get WIN32_FIND_DATA structure for the path to determine if
-           it is a symlink */
-        if(is_directory &&
-           info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-            find_data_handle = FindFirstFileW(lpFileName, &find_data);
-
-            if(find_data_handle != INVALID_HANDLE_VALUE) {
-                /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
-                   IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
-                is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
-                          find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
-                FindClose(find_data_handle);
-            }
-        }
-    }
-
-    if (is_directory && is_link)
-        return RemoveDirectoryW(lpFileName);
-
-    return DeleteFileW(lpFileName);
-}
-#endif /* MS_WINDOWS */
-
-
-/*[clinic input]
-os.unlink
-
-    path: path_t
-    *
-    dir_fd: dir_fd(requires='unlinkat')=None
-
-Remove a file (same as remove()).
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_unlink__doc__,
 "unlink($module, /, path, *, dir_fd=None)\n"
 "--\n"
@@ -5634,47 +1376,6 @@
     return return_value;
 }
 
-static PyObject *
-os_unlink_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=59a6e66d67ff2e75 input=d7bcde2b1b2a2552]*/
-{
-    int result;
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef MS_WINDOWS
-    if (path->wide)
-        result = Py_DeleteFileW(path->wide);
-    else
-        result = DeleteFileA(path->narrow);
-    result = !result; /* Windows, success=1, UNIX, success=0 */
-#else
-#ifdef HAVE_UNLINKAT
-    if (dir_fd != DEFAULT_DIR_FD)
-        result = unlinkat(dir_fd, path->narrow, 0);
-    else
-#endif /* HAVE_UNLINKAT */
-        result = unlink(path->narrow);
-#endif
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error(path);
-
-    Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.remove = os.unlink
-
-Remove a file (same as unlink()).
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_remove__doc__,
 "remove($module, /, path, *, dir_fd=None)\n"
 "--\n"
@@ -5713,51 +1414,7 @@
     return return_value;
 }
 
-static PyObject *
-os_remove_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=cb170cf1e195b8ed input=e05c5ab55cd30983]*/
-{
-    return os_unlink_impl(module, path, dir_fd);
-}
-
-
-static PyStructSequence_Field uname_result_fields[] = {
-    {"sysname",    "operating system name"},
-    {"nodename",   "name of machine on network (implementation-defined)"},
-    {"release",    "operating system release"},
-    {"version",    "operating system version"},
-    {"machine",    "hardware identifier"},
-    {NULL}
-};
-
-PyDoc_STRVAR(uname_result__doc__,
-"uname_result: Result from os.uname().\n\n\
-This object may be accessed either as a tuple of\n\
-  (sysname, nodename, release, version, machine),\n\
-or via the attributes sysname, nodename, release, version, and machine.\n\
-\n\
-See os.uname for more information.");
-
-static PyStructSequence_Desc uname_result_desc = {
-    "uname_result", /* name */
-    uname_result__doc__, /* doc */
-    uname_result_fields,
-    5
-};
-
-static PyTypeObject UnameResultType;
-
-
-#ifdef HAVE_UNAME
-/*[clinic input]
-os.uname
-
-Return an object identifying the current operating system.
-
-The object behaves like a named tuple with the following fields:
-  (sysname, nodename, release, version, machine)
-
-[clinic start generated code]*/
+#if defined(HAVE_UNAME)
 
 PyDoc_STRVAR(os_uname__doc__,
 "uname($module, /)\n"
@@ -5780,259 +1437,7 @@
     return os_uname_impl(module);
 }
 
-static PyObject *
-os_uname_impl(PyModuleDef *module)
-/*[clinic end generated code: output=459a86521ff5041c input=e68bd246db3043ed]*/
-{
-    struct utsname u;
-    int res;
-    PyObject *value;
-
-    Py_BEGIN_ALLOW_THREADS
-    res = uname(&u);
-    Py_END_ALLOW_THREADS
-    if (res < 0)
-        return posix_error();
-
-    value = PyStructSequence_New(&UnameResultType);
-    if (value == NULL)
-        return NULL;
-
-#define SET(i, field) \
-    { \
-    PyObject *o = PyUnicode_DecodeFSDefault(field); \
-    if (!o) { \
-        Py_DECREF(value); \
-        return NULL; \
-    } \
-    PyStructSequence_SET_ITEM(value, i, o); \
-    } \
-
-    SET(0, u.sysname);
-    SET(1, u.nodename);
-    SET(2, u.release);
-    SET(3, u.version);
-    SET(4, u.machine);
-
-#undef SET
-
-    return value;
-}
-#endif /* HAVE_UNAME */
-
-
-
-typedef struct {
-    int    now;
-    time_t atime_s;
-    long   atime_ns;
-    time_t mtime_s;
-    long   mtime_ns;
-} utime_t;
-
-/*
- * these macros assume that "ut" is a pointer to a utime_t
- * they also intentionally leak the declaration of a pointer named "time"
- */
-#define UTIME_TO_TIMESPEC \
-    struct timespec ts[2]; \
-    struct timespec *time; \
-    if (ut->now) \
-        time = NULL; \
-    else { \
-        ts[0].tv_sec = ut->atime_s; \
-        ts[0].tv_nsec = ut->atime_ns; \
-        ts[1].tv_sec = ut->mtime_s; \
-        ts[1].tv_nsec = ut->mtime_ns; \
-        time = ts; \
-    } \
-
-#define UTIME_TO_TIMEVAL \
-    struct timeval tv[2]; \
-    struct timeval *time; \
-    if (ut->now) \
-        time = NULL; \
-    else { \
-        tv[0].tv_sec = ut->atime_s; \
-        tv[0].tv_usec = ut->atime_ns / 1000; \
-        tv[1].tv_sec = ut->mtime_s; \
-        tv[1].tv_usec = ut->mtime_ns / 1000; \
-        time = tv; \
-    } \
-
-#define UTIME_TO_UTIMBUF \
-    struct utimbuf u; \
-    struct utimbuf *time; \
-    if (ut->now) \
-        time = NULL; \
-    else { \
-        u.actime = ut->atime_s; \
-        u.modtime = ut->mtime_s; \
-        time = &u; \
-    }
-
-#define UTIME_TO_TIME_T \
-    time_t timet[2]; \
-    time_t *time; \
-    if (ut->now) \
-        time = NULL; \
-    else { \
-        timet[0] = ut->atime_s; \
-        timet[1] = ut->mtime_s; \
-        time = timet; \
-    } \
-
-
-#define UTIME_HAVE_DIR_FD (defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT))
-
-#if UTIME_HAVE_DIR_FD
-
-static int
-utime_dir_fd(utime_t *ut, int dir_fd, char *path, int follow_symlinks)
-{
-#ifdef HAVE_UTIMENSAT
-    int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
-    UTIME_TO_TIMESPEC;
-    return utimensat(dir_fd, path, time, flags);
-#elif defined(HAVE_FUTIMESAT)
-    UTIME_TO_TIMEVAL;
-    /*
-     * follow_symlinks will never be false here;
-     * we only allow !follow_symlinks and dir_fd together
-     * if we have utimensat()
-     */
-    assert(follow_symlinks);
-    return futimesat(dir_fd, path, time);
-#endif
-}
-
-    #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
-#else
-    #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
-#endif
-
-#define UTIME_HAVE_FD (defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS))
-
-#if UTIME_HAVE_FD
-
-static int
-utime_fd(utime_t *ut, int fd)
-{
-#ifdef HAVE_FUTIMENS
-    UTIME_TO_TIMESPEC;
-    return futimens(fd, time);
-#else
-    UTIME_TO_TIMEVAL;
-    return futimes(fd, time);
-#endif
-}
-
-    #define PATH_UTIME_HAVE_FD 1
-#else
-    #define PATH_UTIME_HAVE_FD 0
-#endif
-
-
-#define UTIME_HAVE_NOFOLLOW_SYMLINKS \
-        (defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES))
-
-#if UTIME_HAVE_NOFOLLOW_SYMLINKS
-
-static int
-utime_nofollow_symlinks(utime_t *ut, char *path)
-{
-#ifdef HAVE_UTIMENSAT
-    UTIME_TO_TIMESPEC;
-    return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
-#else
-    UTIME_TO_TIMEVAL;
-    return lutimes(path, time);
-#endif
-}
-
-#endif
-
-#ifndef MS_WINDOWS
-
-static int
-utime_default(utime_t *ut, char *path)
-{
-#ifdef HAVE_UTIMENSAT
-    UTIME_TO_TIMESPEC;
-    return utimensat(DEFAULT_DIR_FD, path, time, 0);
-#elif defined(HAVE_UTIMES)
-    UTIME_TO_TIMEVAL;
-    return utimes(path, time);
-#elif defined(HAVE_UTIME_H)
-    UTIME_TO_UTIMBUF;
-    return utime(path, time);
-#else
-    UTIME_TO_TIME_T;
-    return utime(path, time);
-#endif
-}
-
-#endif
-
-static int
-split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
-{
-    int result = 0;
-    PyObject *divmod;
-    divmod = PyNumber_Divmod(py_long, billion);
-    if (!divmod)
-        goto exit;
-    *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
-    if ((*s == -1) && PyErr_Occurred())
-        goto exit;
-    *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
-    if ((*ns == -1) && PyErr_Occurred())
-        goto exit;
-
-    result = 1;
-exit:
-    Py_XDECREF(divmod);
-    return result;
-}
-
-
-/*[clinic input]
-os.utime
-
-    path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
-    times: object = NULL
-    *
-    ns: object = NULL
-    dir_fd: dir_fd(requires='futimensat') = None
-    follow_symlinks: bool=True
-
-# "utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True)\n\
-
-Set the access and modified time of path.
-
-path may always be specified as a string.
-On some platforms, path may also be specified as an open file descriptor.
-  If this functionality is unavailable, using it raises an exception.
-
-If times is not None, it must be a tuple (atime, mtime);
-    atime and mtime should be expressed as float seconds since the epoch.
-If ns is not None, it must be a tuple (atime_ns, mtime_ns);
-    atime_ns and mtime_ns should be expressed as integer nanoseconds
-    since the epoch.
-If both times and ns are None, utime uses the current time.
-Specifying tuples for both times and ns is an error.
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, utime will modify the symbolic link itself instead of the file the
-  link points to.
-It is an error to use dir_fd or follow_symlinks when specifying path
-  as an open file descriptor.
-dir_fd and follow_symlinks may not be available on your platform.
-  If they are unavailable, using them will raise a NotImplementedError.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_UNAME) */
 
 PyDoc_STRVAR(os_utime__doc__,
 "utime($module, /, path, times=None, *, ns=None, dir_fd=None,\n"
@@ -6093,175 +1498,6 @@
     return return_value;
 }
 
-static PyObject *
-os_utime_impl(PyModuleDef *module, path_t *path, PyObject *times, PyObject *ns, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=891489c35cc68c5d input=1f18c17d5941aa82]*/
-{
-#ifdef MS_WINDOWS
-    HANDLE hFile;
-    FILETIME atime, mtime;
-#else
-    int result;
-#endif
-
-    PyObject *return_value = NULL;
-    utime_t utime;
-
-    memset(&utime, 0, sizeof(utime_t));
-
-    if (times && (times != Py_None) && ns) {
-        PyErr_SetString(PyExc_ValueError,
-                     "utime: you may specify either 'times'"
-                     " or 'ns' but not both");
-        goto exit;
-    }
-
-    if (times && (times != Py_None)) {
-        time_t a_sec, m_sec;
-        long a_nsec, m_nsec;
-        if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
-            PyErr_SetString(PyExc_TypeError,
-                         "utime: 'times' must be either"
-                         " a tuple of two ints or None");
-            goto exit;
-        }
-        utime.now = 0;
-        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
-                                     &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
-            _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
-                                     &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
-            goto exit;
-        }
-        utime.atime_s = a_sec;
-        utime.atime_ns = a_nsec;
-        utime.mtime_s = m_sec;
-        utime.mtime_ns = m_nsec;
-    }
-    else if (ns) {
-        if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
-            PyErr_SetString(PyExc_TypeError,
-                         "utime: 'ns' must be a tuple of two ints");
-            goto exit;
-        }
-        utime.now = 0;
-        if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
-                                      &utime.atime_s, &utime.atime_ns) ||
-            !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
-                                       &utime.mtime_s, &utime.mtime_ns)) {
-            goto exit;
-        }
-    }
-    else {
-        /* times and ns are both None/unspecified. use "now". */
-        utime.now = 1;
-    }
-
-#if !UTIME_HAVE_NOFOLLOW_SYMLINKS
-    if (follow_symlinks_specified("utime", follow_symlinks))
-        goto exit;
-#endif
-
-    if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
-        dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
-        fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
-        goto exit;
-
-#if !defined(HAVE_UTIMENSAT)
-    if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
-        PyErr_SetString(PyExc_ValueError,
-                     "utime: cannot use dir_fd and follow_symlinks "
-                     "together on this platform");
-        goto exit;
-    }
-#endif
-
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    if (path->wide)
-        hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
-                            NULL, OPEN_EXISTING,
-                            FILE_FLAG_BACKUP_SEMANTICS, NULL);
-    else
-        hFile = CreateFileA(path->narrow, FILE_WRITE_ATTRIBUTES, 0,
-                            NULL, OPEN_EXISTING,
-                            FILE_FLAG_BACKUP_SEMANTICS, NULL);
-    Py_END_ALLOW_THREADS
-    if (hFile == INVALID_HANDLE_VALUE) {
-        path_error(path);
-        goto exit;
-    }
-
-    if (utime.now) {
-        GetSystemTimeAsFileTime(&mtime);
-        atime = mtime;
-    }
-    else {
-        _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
-        _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
-    }
-    if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
-        /* Avoid putting the file name into the error here,
-           as that may confuse the user into believing that
-           something is wrong with the file, when it also
-           could be the time stamp that gives a problem. */
-        PyErr_SetFromWindowsErr(0);
-        goto exit;
-    }
-#else /* MS_WINDOWS */
-    Py_BEGIN_ALLOW_THREADS
-
-#if UTIME_HAVE_NOFOLLOW_SYMLINKS
-    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
-        result = utime_nofollow_symlinks(&utime, path->narrow);
-    else
-#endif
-
-#if UTIME_HAVE_DIR_FD
-    if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
-        result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
-    else
-#endif
-
-#if UTIME_HAVE_FD
-    if (path->fd != -1)
-        result = utime_fd(&utime, path->fd);
-    else
-#endif
-
-    result = utime_default(&utime, path->narrow);
-
-    Py_END_ALLOW_THREADS
-
-    if (result < 0) {
-        /* see previous comment about not putting filename in error here */
-        return_value = posix_error();
-        goto exit;
-    }
-
-#endif /* MS_WINDOWS */
-
-    Py_INCREF(Py_None);
-    return_value = Py_None;
-
-exit:
-#ifdef MS_WINDOWS
-    if (hFile != INVALID_HANDLE_VALUE)
-        CloseHandle(hFile);
-#endif
-    return return_value;
-}
-
-/* Process operations */
-
-
-/*[clinic input]
-os._exit
-
-    status: int
-
-Exit to the system with specified status, without normal exit processing.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os__exit__doc__,
 "_exit($module, /, status)\n"
 "--\n"
@@ -6291,161 +1527,7 @@
     return return_value;
 }
 
-static PyObject *
-os__exit_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=4f9858c4cc2dcb89 input=5e6d57556b0c4a62]*/
-{
-    _exit(status);
-    return NULL; /* Make gcc -Wall happy */
-}
-
-#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
-static void
-free_string_array(char **array, Py_ssize_t count)
-{
-    Py_ssize_t i;
-    for (i = 0; i < count; i++)
-        PyMem_Free(array[i]);
-    PyMem_DEL(array);
-}
-
-static
-int fsconvert_strdup(PyObject *o, char**out)
-{
-    PyObject *bytes;
-    Py_ssize_t size;
-    if (!PyUnicode_FSConverter(o, &bytes))
-        return 0;
-    size = PyBytes_GET_SIZE(bytes);
-    *out = PyMem_Malloc(size+1);
-    if (!*out) {
-        PyErr_NoMemory();
-        return 0;
-    }
-    memcpy(*out, PyBytes_AsString(bytes), size+1);
-    Py_DECREF(bytes);
-    return 1;
-}
-#endif
-
-#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE)
-static char**
-parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
-{
-    char **envlist;
-    Py_ssize_t i, pos, envc;
-    PyObject *keys=NULL, *vals=NULL;
-    PyObject *key, *val, *key2, *val2;
-    char *p, *k, *v;
-    size_t len;
-
-    i = PyMapping_Size(env);
-    if (i < 0)
-        return NULL;
-    envlist = PyMem_NEW(char *, i + 1);
-    if (envlist == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    envc = 0;
-    keys = PyMapping_Keys(env);
-    if (!keys)
-        goto error;
-    vals = PyMapping_Values(env);
-    if (!vals)
-        goto error;
-    if (!PyList_Check(keys) || !PyList_Check(vals)) {
-        PyErr_Format(PyExc_TypeError,
-                     "env.keys() or env.values() is not a list");
-        goto error;
-    }
-
-    for (pos = 0; pos < i; pos++) {
-        key = PyList_GetItem(keys, pos);
-        val = PyList_GetItem(vals, pos);
-        if (!key || !val)
-            goto error;
-
-        if (PyUnicode_FSConverter(key, &key2) == 0)
-            goto error;
-        if (PyUnicode_FSConverter(val, &val2) == 0) {
-            Py_DECREF(key2);
-            goto error;
-        }
-
-        k = PyBytes_AsString(key2);
-        v = PyBytes_AsString(val2);
-        len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2;
-
-        p = PyMem_NEW(char, len);
-        if (p == NULL) {
-            PyErr_NoMemory();
-            Py_DECREF(key2);
-            Py_DECREF(val2);
-            goto error;
-        }
-        PyOS_snprintf(p, len, "%s=%s", k, v);
-        envlist[envc++] = p;
-        Py_DECREF(key2);
-        Py_DECREF(val2);
-    }
-    Py_DECREF(vals);
-    Py_DECREF(keys);
-
-    envlist[envc] = 0;
-    *envc_ptr = envc;
-    return envlist;
-
-error:
-    Py_XDECREF(keys);
-    Py_XDECREF(vals);
-    while (--envc >= 0)
-        PyMem_DEL(envlist[envc]);
-    PyMem_DEL(envlist);
-    return NULL;
-}
-
-static char**
-parse_arglist(PyObject* argv, Py_ssize_t *argc)
-{
-    int i;
-    char **argvlist = PyMem_NEW(char *, *argc+1);
-    if (argvlist == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    for (i = 0; i < *argc; i++) {
-        PyObject* item = PySequence_ITEM(argv, i);
-        if (item == NULL)
-            goto fail;
-        if (!fsconvert_strdup(item, &argvlist[i])) {
-            Py_DECREF(item);
-            goto fail;
-        }
-        Py_DECREF(item);
-    }
-    argvlist[*argc] = NULL;
-    return argvlist;
-fail:
-    *argc = i;
-    free_string_array(argvlist, *argc);
-    return NULL;
-}
-#endif
-
-
-#ifdef HAVE_EXECV
-/*[clinic input]
-os.execv
-
-    path: FSConverter
-        Path of executable file.
-    argv: object
-        Tuple or list of strings.
-    /
-
-Execute an executable path with arguments, replacing current process.
-[clinic start generated code]*/
+#if defined(HAVE_EXECV)
 
 PyDoc_STRVAR(os_execv__doc__,
 "execv($module, path, argv, /)\n"
@@ -6484,55 +1566,9 @@
     return return_value;
 }
 
-static PyObject *
-os_execv_impl(PyModuleDef *module, PyObject *path, PyObject *argv)
-/*[clinic end generated code: output=b0f5f2caa6097edc input=96041559925e5229]*/
-{
-    char *path_char;
-    char **argvlist;
-    Py_ssize_t argc;
-
-    /* execv has two arguments: (path, argv), where
-       argv is a list or tuple of strings. */
-
-    path_char = PyBytes_AsString(path);
-    if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "execv() arg 2 must be a tuple or list");
-        return NULL;
-    }
-    argc = PySequence_Size(argv);
-    if (argc < 1) {
-        PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
-        return NULL;
-    }
-
-    argvlist = parse_arglist(argv, &argc);
-    if (argvlist == NULL) {
-        return NULL;
-    }
-
-    execv(path_char, argvlist);
-
-    /* If we get here it's definitely an error */
-
-    free_string_array(argvlist, argc);
-    return posix_error();
-}
-
-
-/*[clinic input]
-os.execve
-
-    path: path_t(allow_fd='PATH_HAVE_FEXECVE')
-        Path of executable file.
-    argv: object
-        Tuple or list of strings.
-    env: object
-        Dictionary of strings mapping to strings.
-
-Execute an executable path with arguments, replacing current process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_EXECV) */
+
+#if defined(HAVE_EXECV)
 
 PyDoc_STRVAR(os_execve__doc__,
 "execve($module, /, path, argv, env)\n"
@@ -6575,75 +1611,9 @@
     return return_value;
 }
 
-static PyObject *
-os_execve_impl(PyModuleDef *module, path_t *path, PyObject *argv, PyObject *env)
-/*[clinic end generated code: output=fb283760f5d15ab7 input=626804fa092606d9]*/
-{
-    char **argvlist = NULL;
-    char **envlist;
-    Py_ssize_t argc, envc;
-
-    /* execve has three arguments: (path, argv, env), where
-       argv is a list or tuple of strings and env is a dictionary
-       like posix.environ. */
-
-    if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "execve: argv must be a tuple or list");
-        goto fail;
-    }
-    argc = PySequence_Size(argv);
-    if (!PyMapping_Check(env)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "execve: environment must be a mapping object");
-        goto fail;
-    }
-
-    argvlist = parse_arglist(argv, &argc);
-    if (argvlist == NULL) {
-        goto fail;
-    }
-
-    envlist = parse_envlist(env, &envc);
-    if (envlist == NULL)
-        goto fail;
-
-#ifdef HAVE_FEXECVE
-    if (path->fd > -1)
-        fexecve(path->fd, argvlist, envlist);
-    else
-#endif
-        execve(path->narrow, argvlist, envlist);
-
-    /* If we get here it's definitely an error */
-
-    path_error(path);
-
-    while (--envc >= 0)
-        PyMem_DEL(envlist[envc]);
-    PyMem_DEL(envlist);
-  fail:
-    if (argvlist)
-        free_string_array(argvlist, argc);
-    return NULL;
-}
-#endif /* HAVE_EXECV */
-
-
-#ifdef HAVE_SPAWNV
-/*[clinic input]
-os.spawnv
-
-    mode: int
-        Mode of process creation.
-    path: FSConverter
-        Path of executable file.
-    argv: object
-        Tuple or list of strings.
-    /
-
-Execute the program specified by path in a new process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_EXECV) */
+
+#if defined(HAVE_SPAWNV)
 
 PyDoc_STRVAR(os_spawnv__doc__,
 "spawnv($module, mode, path, argv, /)\n"
@@ -6685,82 +1655,9 @@
     return return_value;
 }
 
-static PyObject *
-os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv)
-/*[clinic end generated code: output=dfee6be062e780e3 input=042c91dfc1e6debc]*/
-{
-    char *path_char;
-    char **argvlist;
-    int i;
-    Py_ssize_t argc;
-    Py_intptr_t spawnval;
-    PyObject *(*getitem)(PyObject *, Py_ssize_t);
-
-    /* spawnv has three arguments: (mode, path, argv), where
-       argv is a list or tuple of strings. */
-
-    path_char = PyBytes_AsString(path);
-    if (PyList_Check(argv)) {
-        argc = PyList_Size(argv);
-        getitem = PyList_GetItem;
-    }
-    else if (PyTuple_Check(argv)) {
-        argc = PyTuple_Size(argv);
-        getitem = PyTuple_GetItem;
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "spawnv() arg 2 must be a tuple or list");
-        return NULL;
-    }
-
-    argvlist = PyMem_NEW(char *, argc+1);
-    if (argvlist == NULL) {
-        return PyErr_NoMemory();
-    }
-    for (i = 0; i < argc; i++) {
-        if (!fsconvert_strdup((*getitem)(argv, i),
-                              &argvlist[i])) {
-            free_string_array(argvlist, i);
-            PyErr_SetString(
-                PyExc_TypeError,
-                "spawnv() arg 2 must contain only strings");
-            return NULL;
-        }
-    }
-    argvlist[argc] = NULL;
-
-    if (mode == _OLD_P_OVERLAY)
-        mode = _P_OVERLAY;
-
-    Py_BEGIN_ALLOW_THREADS
-    spawnval = _spawnv(mode, path_char, argvlist);
-    Py_END_ALLOW_THREADS
-
-    free_string_array(argvlist, argc);
-
-    if (spawnval == -1)
-        return posix_error();
-    else
-        return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
-}
-
-
-/*[clinic input]
-os.spawnve
-
-    mode: int
-        Mode of process creation.
-    path: FSConverter
-        Path of executable file.
-    argv: object
-        Tuple or list of strings.
-    env: object
-        Dictionary of strings mapping to strings.
-    /
-
-Execute the program specified by path in a new process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SPAWNV) */
+
+#if defined(HAVE_SPAWNV)
 
 PyDoc_STRVAR(os_spawnve__doc__,
 "spawnve($module, mode, path, argv, env, /)\n"
@@ -6805,95 +1702,9 @@
     return return_value;
 }
 
-static PyObject *
-os_spawnve_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv, PyObject *env)
-/*[clinic end generated code: output=6f7df38473f63c7c input=02362fd937963f8f]*/
-{
-    char *path_char;
-    char **argvlist;
-    char **envlist;
-    PyObject *res = NULL;
-    Py_ssize_t argc, i, envc;
-    Py_intptr_t spawnval;
-    PyObject *(*getitem)(PyObject *, Py_ssize_t);
-    Py_ssize_t lastarg = 0;
-
-    /* spawnve has four arguments: (mode, path, argv, env), where
-       argv is a list or tuple of strings and env is a dictionary
-       like posix.environ. */
-
-    path_char = PyBytes_AsString(path);
-    if (PyList_Check(argv)) {
-        argc = PyList_Size(argv);
-        getitem = PyList_GetItem;
-    }
-    else if (PyTuple_Check(argv)) {
-        argc = PyTuple_Size(argv);
-        getitem = PyTuple_GetItem;
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "spawnve() arg 2 must be a tuple or list");
-        goto fail_0;
-    }
-    if (!PyMapping_Check(env)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "spawnve() arg 3 must be a mapping object");
-        goto fail_0;
-    }
-
-    argvlist = PyMem_NEW(char *, argc+1);
-    if (argvlist == NULL) {
-        PyErr_NoMemory();
-        goto fail_0;
-    }
-    for (i = 0; i < argc; i++) {
-        if (!fsconvert_strdup((*getitem)(argv, i),
-                              &argvlist[i]))
-        {
-            lastarg = i;
-            goto fail_1;
-        }
-    }
-    lastarg = argc;
-    argvlist[argc] = NULL;
-
-    envlist = parse_envlist(env, &envc);
-    if (envlist == NULL)
-        goto fail_1;
-
-    if (mode == _OLD_P_OVERLAY)
-        mode = _P_OVERLAY;
-
-    Py_BEGIN_ALLOW_THREADS
-    spawnval = _spawnve(mode, path_char, argvlist, envlist);
-    Py_END_ALLOW_THREADS
-
-    if (spawnval == -1)
-        (void) posix_error();
-    else
-        res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
-
-    while (--envc >= 0)
-        PyMem_DEL(envlist[envc]);
-    PyMem_DEL(envlist);
-  fail_1:
-    free_string_array(argvlist, lastarg);
-  fail_0:
-    return res;
-}
-
-#endif /* HAVE_SPAWNV */
-
-
-#ifdef HAVE_FORK1
-/*[clinic input]
-os.fork1
-
-Fork a child process with a single multiplexed (i.e., not bound) thread.
-
-Return 0 to child process and PID of child to parent process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SPAWNV) */
+
+#if defined(HAVE_FORK1)
 
 PyDoc_STRVAR(os_fork1__doc__,
 "fork1($module, /)\n"
@@ -6915,42 +1726,9 @@
     return os_fork1_impl(module);
 }
 
-static PyObject *
-os_fork1_impl(PyModuleDef *module)
-/*[clinic end generated code: output=fa04088d6bc02efa input=12db02167893926e]*/
-{
-    pid_t pid;
-    int result = 0;
-    _PyImport_AcquireLock();
-    pid = fork1();
-    if (pid == 0) {
-        /* child: this clobbers and resets the import lock. */
-        PyOS_AfterFork();
-    } else {
-        /* parent: release the import lock. */
-        result = _PyImport_ReleaseLock();
-    }
-    if (pid == -1)
-        return posix_error();
-    if (result < 0) {
-        /* Don't clobber the OSError if the fork failed. */
-        PyErr_SetString(PyExc_RuntimeError,
-                        "not holding the import lock");
-        return NULL;
-    }
-    return PyLong_FromPid(pid);
-}
-#endif /* HAVE_FORK1 */
-
-
-#ifdef HAVE_FORK
-/*[clinic input]
-os.fork
-
-Fork a child process.
-
-Return 0 to child process and PID of child to parent process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_FORK1) */
+
+#if defined(HAVE_FORK)
 
 PyDoc_STRVAR(os_fork__doc__,
 "fork($module, /)\n"
@@ -6972,43 +1750,9 @@
     return os_fork_impl(module);
 }
 
-static PyObject *
-os_fork_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b3c8e6bdc11eedc6 input=13c956413110eeaa]*/
-{
-    pid_t pid;
-    int result = 0;
-    _PyImport_AcquireLock();
-    pid = fork();
-    if (pid == 0) {
-        /* child: this clobbers and resets the import lock. */
-        PyOS_AfterFork();
-    } else {
-        /* parent: release the import lock. */
-        result = _PyImport_ReleaseLock();
-    }
-    if (pid == -1)
-        return posix_error();
-    if (result < 0) {
-        /* Don't clobber the OSError if the fork failed. */
-        PyErr_SetString(PyExc_RuntimeError,
-                        "not holding the import lock");
-        return NULL;
-    }
-    return PyLong_FromPid(pid);
-}
-#endif /* HAVE_FORK */
-
-
-#ifdef HAVE_SCHED_H
-#ifdef HAVE_SCHED_GET_PRIORITY_MAX
-/*[clinic input]
-os.sched_get_priority_max
-
-    policy: int
-
-Get the maximum scheduling priority for policy.
-[clinic start generated code]*/
+#endif /* defined(HAVE_FORK) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_GET_PRIORITY_MAX)
 
 PyDoc_STRVAR(os_sched_get_priority_max__doc__,
 "sched_get_priority_max($module, /, policy)\n"
@@ -7039,26 +1783,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_get_priority_max_impl(PyModuleDef *module, int policy)
-/*[clinic end generated code: output=a580a52f25238c1f input=2097b7998eca6874]*/
-{
-    int max;
-
-    max = sched_get_priority_max(policy);
-    if (max < 0)
-        return posix_error();
-    return PyLong_FromLong(max);
-}
-
-
-/*[clinic input]
-os.sched_get_priority_min
-
-    policy: int
-
-Get the minimum scheduling priority for policy.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_GET_PRIORITY_MAX) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_GET_PRIORITY_MAX)
 
 PyDoc_STRVAR(os_sched_get_priority_min__doc__,
 "sched_get_priority_min($module, /, policy)\n"
@@ -7089,28 +1816,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_get_priority_min_impl(PyModuleDef *module, int policy)
-/*[clinic end generated code: output=bad8ba10e7d0e977 input=21bc8fa0d70983bf]*/
-{
-    int min = sched_get_priority_min(policy);
-    if (min < 0)
-        return posix_error();
-    return PyLong_FromLong(min);
-}
-#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
-
-
-#ifdef HAVE_SCHED_SETSCHEDULER
-/*[clinic input]
-os.sched_getscheduler
-    pid: pid_t
-    /
-
-Get the scheduling policy for the process identifiedy by pid.
-
-Passing 0 for pid returns the scheduling policy for the calling process.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_GET_PRIORITY_MAX) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETSCHEDULER)
 
 PyDoc_STRVAR(os_sched_getscheduler__doc__,
 "sched_getscheduler($module, pid, /)\n"
@@ -7142,32 +1850,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_getscheduler_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=e0d6244207b1d828 input=5f14cfd1f189e1a0]*/
-{
-    int policy;
-
-    policy = sched_getscheduler(pid);
-    if (policy < 0)
-        return posix_error();
-    return PyLong_FromLong(policy);
-}
-#endif /* HAVE_SCHED_SETSCHEDULER */
-
-
-#if defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM)
-/*[clinic input]
-class os.sched_param "PyObject *" "&SchedParamType"
-
- at classmethod
-os.sched_param.__new__
-
-    sched_priority: object
-        A scheduling parameter.
-
-Current has only one field: sched_priority");
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETSCHEDULER) */
+
+#if defined(HAVE_SCHED_H) && (defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM))
 
 PyDoc_STRVAR(os_sched_param__doc__,
 "sched_param(sched_priority)\n"
@@ -7198,69 +1883,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
-/*[clinic end generated code: output=d3791e345f7fe573 input=73a4c22f7071fc62]*/
-{
-    PyObject *res;
-
-    res = PyStructSequence_New(type);
-    if (!res)
-        return NULL;
-    Py_INCREF(sched_priority);
-    PyStructSequence_SET_ITEM(res, 0, sched_priority);
-    return res;
-}
-
-
-static PyStructSequence_Field sched_param_fields[] = {
-    {"sched_priority", "the scheduling priority"},
-    {0}
-};
-
-static PyStructSequence_Desc sched_param_desc = {
-    "sched_param", /* name */
-    os_sched_param__doc__, /* doc */
-    sched_param_fields,
-    1
-};
-
-static int
-convert_sched_param(PyObject *param, struct sched_param *res)
-{
-    long priority;
-
-    if (Py_TYPE(param) != &SchedParamType) {
-        PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
-        return 0;
-    }
-    priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
-    if (priority == -1 && PyErr_Occurred())
-        return 0;
-    if (priority > INT_MAX || priority < INT_MIN) {
-        PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
-        return 0;
-    }
-    res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
-    return 1;
-}
-#endif /* defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM) */
-
-
-#ifdef HAVE_SCHED_SETSCHEDULER
-/*[clinic input]
-os.sched_setscheduler
-
-    pid: pid_t
-    policy: int
-    param: sched_param
-    /
-
-Set the scheduling policy for the process identified by pid.
-
-If pid is 0, the calling process is changed.
-param is an instance of sched_param.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && (defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM)) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETSCHEDULER)
 
 PyDoc_STRVAR(os_sched_setscheduler__doc__,
 "sched_setscheduler($module, pid, policy, param, /)\n"
@@ -7295,33 +1920,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_setscheduler_impl(PyModuleDef *module, pid_t pid, int policy, struct sched_param *param)
-/*[clinic end generated code: output=36abdb73f81c224f input=c581f9469a5327dd]*/
-{
-    /*
-    ** sched_setscheduler() returns 0 in Linux, but the previous
-    ** scheduling policy under Solaris/Illumos, and others.
-    ** On error, -1 is returned in all Operating Systems.
-    */
-    if (sched_setscheduler(pid, policy, param) == -1)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif  /* HAVE_SCHED_SETSCHEDULER*/
-
-
-#ifdef HAVE_SCHED_SETPARAM
-/*[clinic input]
-os.sched_getparam
-    pid: pid_t
-    /
-
-Returns scheduling parameters for the process identified by pid.
-
-If pid is 0, returns parameters for the calling process.
-Return value is an instance of sched_param.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETSCHEDULER) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETPARAM)
 
 PyDoc_STRVAR(os_sched_getparam__doc__,
 "sched_getparam($module, pid, /)\n"
@@ -7354,40 +1955,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_getparam_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=b33acc8db004a8c9 input=18a1ef9c2efae296]*/
-{
-    struct sched_param param;
-    PyObject *result;
-    PyObject *priority;
-
-    if (sched_getparam(pid, &param))
-        return posix_error();
-    result = PyStructSequence_New(&SchedParamType);
-    if (!result)
-        return NULL;
-    priority = PyLong_FromLong(param.sched_priority);
-    if (!priority) {
-        Py_DECREF(result);
-        return NULL;
-    }
-    PyStructSequence_SET_ITEM(result, 0, priority);
-    return result;
-}
-
-
-/*[clinic input]
-os.sched_setparam
-    pid: pid_t
-    param: sched_param
-    /
-
-Set scheduling parameters for the process identified by pid.
-
-If pid is 0, sets parameters for the calling process.
-param should be an instance of sched_param.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETPARAM) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETPARAM)
 
 PyDoc_STRVAR(os_sched_setparam__doc__,
 "sched_setparam($module, pid, param, /)\n"
@@ -7421,27 +1991,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_setparam_impl(PyModuleDef *module, pid_t pid, struct sched_param *param)
-/*[clinic end generated code: output=488bdf5bcbe0d4e8 input=6b8d6dfcecdc21bd]*/
-{
-    if (sched_setparam(pid, param))
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SCHED_SETPARAM */
-
-
-#ifdef HAVE_SCHED_RR_GET_INTERVAL
-/*[clinic input]
-os.sched_rr_get_interval -> double
-    pid: pid_t
-    /
-
-Return the round-robin quantum for the process identified by pid, in seconds.
-
-Value returned is a float.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETPARAM) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_RR_GET_INTERVAL)
 
 PyDoc_STRVAR(os_sched_rr_get_interval__doc__,
 "sched_rr_get_interval($module, pid, /)\n"
@@ -7477,25 +2029,9 @@
     return return_value;
 }
 
-static double
-os_sched_rr_get_interval_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=5b3b8d1f27fb2c0a input=2a973da15cca6fae]*/
-{
-    struct timespec interval;
-    if (sched_rr_get_interval(pid, &interval)) {
-        posix_error();
-        return -1.0;
-    }
-    return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
-}
-#endif /* HAVE_SCHED_RR_GET_INTERVAL */
-
-
-/*[clinic input]
-os.sched_yield
-
-Voluntarily relinquish the CPU.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_RR_GET_INTERVAL) */
+
+#if defined(HAVE_SCHED_H)
 
 PyDoc_STRVAR(os_sched_yield__doc__,
 "sched_yield($module, /)\n"
@@ -7515,29 +2051,9 @@
     return os_sched_yield_impl(module);
 }
 
-static PyObject *
-os_sched_yield_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9d2e5f29f1370324 input=e54d6f98189391d4]*/
-{
-    if (sched_yield())
-        return posix_error();
-    Py_RETURN_NONE;
-}
-
-#ifdef HAVE_SCHED_SETAFFINITY
-/* The minimum number of CPUs allocated in a cpu_set_t */
-static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
-
-/*[clinic input]
-os.sched_setaffinity
-    pid: pid_t
-    mask : object
-    /
-
-Set the CPU affinity of the process identified by pid to mask.
-
-mask should be an iterable of integers identifying CPUs.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETAFFINITY)
 
 PyDoc_STRVAR(os_sched_setaffinity__doc__,
 "sched_setaffinity($module, pid, mask, /)\n"
@@ -7570,101 +2086,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_setaffinity_impl(PyModuleDef *module, pid_t pid, PyObject *mask)
-/*[clinic end generated code: output=5199929738130196 input=a0791a597c7085ba]*/
-{
-    int ncpus;
-    size_t setsize;
-    cpu_set_t *cpu_set = NULL;
-    PyObject *iterator = NULL, *item;
-
-    iterator = PyObject_GetIter(mask);
-    if (iterator == NULL)
-        return NULL;
-
-    ncpus = NCPUS_START;
-    setsize = CPU_ALLOC_SIZE(ncpus);
-    cpu_set = CPU_ALLOC(ncpus);
-    if (cpu_set == NULL) {
-        PyErr_NoMemory();
-        goto error;
-    }
-    CPU_ZERO_S(setsize, cpu_set);
-
-    while ((item = PyIter_Next(iterator))) {
-        long cpu;
-        if (!PyLong_Check(item)) {
-            PyErr_Format(PyExc_TypeError,
-                        "expected an iterator of ints, "
-                        "but iterator yielded %R",
-                        Py_TYPE(item));
-            Py_DECREF(item);
-            goto error;
-        }
-        cpu = PyLong_AsLong(item);
-        Py_DECREF(item);
-        if (cpu < 0) {
-            if (!PyErr_Occurred())
-                PyErr_SetString(PyExc_ValueError, "negative CPU number");
-            goto error;
-        }
-        if (cpu > INT_MAX - 1) {
-            PyErr_SetString(PyExc_OverflowError, "CPU number too large");
-            goto error;
-        }
-        if (cpu >= ncpus) {
-            /* Grow CPU mask to fit the CPU number */
-            int newncpus = ncpus;
-            cpu_set_t *newmask;
-            size_t newsetsize;
-            while (newncpus <= cpu) {
-                if (newncpus > INT_MAX / 2)
-                    newncpus = cpu + 1;
-                else
-                    newncpus = newncpus * 2;
-            }
-            newmask = CPU_ALLOC(newncpus);
-            if (newmask == NULL) {
-                PyErr_NoMemory();
-                goto error;
-            }
-            newsetsize = CPU_ALLOC_SIZE(newncpus);
-            CPU_ZERO_S(newsetsize, newmask);
-            memcpy(newmask, cpu_set, setsize);
-            CPU_FREE(cpu_set);
-            setsize = newsetsize;
-            cpu_set = newmask;
-            ncpus = newncpus;
-        }
-        CPU_SET_S(cpu, setsize, cpu_set);
-    }
-    Py_CLEAR(iterator);
-
-    if (sched_setaffinity(pid, setsize, cpu_set)) {
-        posix_error();
-        goto error;
-    }
-    CPU_FREE(cpu_set);
-    Py_RETURN_NONE;
-
-error:
-    if (cpu_set)
-        CPU_FREE(cpu_set);
-    Py_XDECREF(iterator);
-    return NULL;
-}
-
-
-/*[clinic input]
-os.sched_getaffinity
-    pid: pid_t
-    /
-
-Return the affinity of the process identified by pid.
-
-The affinity is returned as a set of CPU identifiers.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETAFFINITY) */
+
+#if defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETAFFINITY)
 
 PyDoc_STRVAR(os_sched_getaffinity__doc__,
 "sched_getaffinity($module, pid, /)\n"
@@ -7696,141 +2120,9 @@
     return return_value;
 }
 
-static PyObject *
-os_sched_getaffinity_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=7b273b0fca9830f0 input=eaf161936874b8a1]*/
-{
-    int cpu, ncpus, count;
-    size_t setsize;
-    cpu_set_t *mask = NULL;
-    PyObject *res = NULL;
-
-    ncpus = NCPUS_START;
-    while (1) {
-        setsize = CPU_ALLOC_SIZE(ncpus);
-        mask = CPU_ALLOC(ncpus);
-        if (mask == NULL)
-            return PyErr_NoMemory();
-        if (sched_getaffinity(pid, setsize, mask) == 0)
-            break;
-        CPU_FREE(mask);
-        if (errno != EINVAL)
-            return posix_error();
-        if (ncpus > INT_MAX / 2) {
-            PyErr_SetString(PyExc_OverflowError, "could not allocate "
-                            "a large enough CPU set");
-            return NULL;
-        }
-        ncpus = ncpus * 2;
-    }
-
-    res = PySet_New(NULL);
-    if (res == NULL)
-        goto error;
-    for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
-        if (CPU_ISSET_S(cpu, setsize, mask)) {
-            PyObject *cpu_num = PyLong_FromLong(cpu);
-            --count;
-            if (cpu_num == NULL)
-                goto error;
-            if (PySet_Add(res, cpu_num)) {
-                Py_DECREF(cpu_num);
-                goto error;
-            }
-            Py_DECREF(cpu_num);
-        }
-    }
-    CPU_FREE(mask);
-    return res;
-
-error:
-    if (mask)
-        CPU_FREE(mask);
-    Py_XDECREF(res);
-    return NULL;
-}
-
-#endif /* HAVE_SCHED_SETAFFINITY */
-
-#endif /* HAVE_SCHED_H */
-
-#ifndef OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-#define OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-#endif  /* OS_SCHED_GET_PRIORITY_MAX_METHODDEF */
-
-#ifndef OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-#define OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-#endif  /* OS_SCHED_GET_PRIORITY_MIN_METHODDEF */
-
-#ifndef OS_SCHED_GETSCHEDULER_METHODDEF
-#define OS_SCHED_GETSCHEDULER_METHODDEF
-#endif  /* OS_SCHED_GETSCHEDULER_METHODDEF */
-
-#ifndef OS_SCHED_SETSCHEDULER_METHODDEF
-#define OS_SCHED_SETSCHEDULER_METHODDEF
-#endif  /* OS_SCHED_SETSCHEDULER_METHODDEF */
-
-#ifndef OS_SCHED_GETPARAM_METHODDEF
-#define OS_SCHED_GETPARAM_METHODDEF
-#endif  /* OS_SCHED_GETPARAM_METHODDEF */
-
-#ifndef OS_SCHED_SETPARAM_METHODDEF
-#define OS_SCHED_SETPARAM_METHODDEF
-#endif  /* OS_SCHED_SETPARAM_METHODDEF */
-
-#ifndef OS_SCHED_RR_GET_INTERVAL_METHODDEF
-#define OS_SCHED_RR_GET_INTERVAL_METHODDEF
-#endif  /* OS_SCHED_RR_GET_INTERVAL_METHODDEF */
-
-#ifndef OS_SCHED_YIELD_METHODDEF
-#define OS_SCHED_YIELD_METHODDEF
-#endif  /* OS_SCHED_YIELD_METHODDEF */
-
-#ifndef OS_SCHED_SETAFFINITY_METHODDEF
-#define OS_SCHED_SETAFFINITY_METHODDEF
-#endif  /* OS_SCHED_SETAFFINITY_METHODDEF */
-
-#ifndef OS_SCHED_GETAFFINITY_METHODDEF
-#define OS_SCHED_GETAFFINITY_METHODDEF
-#endif  /* OS_SCHED_GETAFFINITY_METHODDEF */
-
-
-/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
-/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
-#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
-#define DEV_PTY_FILE "/dev/ptc"
-#define HAVE_DEV_PTMX
-#else
-#define DEV_PTY_FILE "/dev/ptmx"
-#endif
-
-#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
-#ifdef HAVE_PTY_H
-#include <pty.h>
-#else
-#ifdef HAVE_LIBUTIL_H
-#include <libutil.h>
-#else
-#ifdef HAVE_UTIL_H
-#include <util.h>
-#endif /* HAVE_UTIL_H */
-#endif /* HAVE_LIBUTIL_H */
-#endif /* HAVE_PTY_H */
-#ifdef HAVE_STROPTS_H
-#include <stropts.h>
-#endif
-#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */
-
-
-#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
-/*[clinic input]
-os.openpty
-
-Open a pseudo-terminal.
-
-Return a tuple of (master_fd, slave_fd) containing open file descriptors
-for both the master and slave ends.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SCHED_H) && defined(HAVE_SCHED_SETAFFINITY) */
+
+#if (defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX))
 
 PyDoc_STRVAR(os_openpty__doc__,
 "openpty($module, /)\n"
@@ -7853,107 +2145,9 @@
     return os_openpty_impl(module);
 }
 
-static PyObject *
-os_openpty_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b12d3c1735468464 input=f3d99fd99e762907]*/
-{
-    int master_fd = -1, slave_fd = -1;
-#ifndef HAVE_OPENPTY
-    char * slave_name;
-#endif
-#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
-    PyOS_sighandler_t sig_saved;
-#ifdef sun
-    extern char *ptsname(int fildes);
-#endif
-#endif
-
-#ifdef HAVE_OPENPTY
-    if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
-        goto posix_error;
-
-    if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
-        goto error;
-    if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
-        goto error;
-
-#elif defined(HAVE__GETPTY)
-    slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
-    if (slave_name == NULL)
-        goto posix_error;
-    if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
-        goto error;
-
-    slave_fd = _Py_open(slave_name, O_RDWR);
-    if (slave_fd < 0)
-        goto error;
-
-#else
-    master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
-    if (master_fd < 0)
-        goto posix_error;
-
-    sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
-
-    /* change permission of slave */
-    if (grantpt(master_fd) < 0) {
-        PyOS_setsig(SIGCHLD, sig_saved);
-        goto posix_error;
-    }
-
-    /* unlock slave */
-    if (unlockpt(master_fd) < 0) {
-        PyOS_setsig(SIGCHLD, sig_saved);
-        goto posix_error;
-    }
-
-    PyOS_setsig(SIGCHLD, sig_saved);
-
-    slave_name = ptsname(master_fd); /* get name of slave */
-    if (slave_name == NULL)
-        goto posix_error;
-
-    slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
-    if (slave_fd == -1)
-        goto error;
-
-    if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
-        goto posix_error;
-
-#if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)
-    ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
-    ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
-#ifndef __hpux
-    ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
-#endif /* __hpux */
-#endif /* HAVE_CYGWIN */
-#endif /* HAVE_OPENPTY */
-
-    return Py_BuildValue("(ii)", master_fd, slave_fd);
-
-posix_error:
-    posix_error();
-error:
-    if (master_fd != -1)
-        close(master_fd);
-    if (slave_fd != -1)
-        close(slave_fd);
-    return NULL;
-}
-#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
-
-
-#ifdef HAVE_FORKPTY
-/*[clinic input]
-os.forkpty
-
-Fork a new process with a new pseudo-terminal as controlling tty.
-
-Returns a tuple of (pid, master_fd).
-Like fork(), return pid of 0 to the child process,
-and pid of child to the parent process.
-To both, return fd of newly opened pseudo-terminal.
-[clinic start generated code]*/
+#endif /* (defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)) */
+
+#if defined(HAVE_FORKPTY)
 
 PyDoc_STRVAR(os_forkpty__doc__,
 "forkpty($module, /)\n"
@@ -7978,41 +2172,9 @@
     return os_forkpty_impl(module);
 }
 
-static PyObject *
-os_forkpty_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d4f82958d2ed5cad input=f1f7f4bae3966010]*/
-{
-    int master_fd = -1, result = 0;
-    pid_t pid;
-
-    _PyImport_AcquireLock();
-    pid = forkpty(&master_fd, NULL, NULL, NULL);
-    if (pid == 0) {
-        /* child: this clobbers and resets the import lock. */
-        PyOS_AfterFork();
-    } else {
-        /* parent: release the import lock. */
-        result = _PyImport_ReleaseLock();
-    }
-    if (pid == -1)
-        return posix_error();
-    if (result < 0) {
-        /* Don't clobber the OSError if the fork failed. */
-        PyErr_SetString(PyExc_RuntimeError,
-                        "not holding the import lock");
-        return NULL;
-    }
-    return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
-}
-#endif /* HAVE_FORKPTY */
-
-
-#ifdef HAVE_GETEGID
-/*[clinic input]
-os.getegid
-
-Return the current process's effective group id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_FORKPTY) */
+
+#if defined(HAVE_GETEGID)
 
 PyDoc_STRVAR(os_getegid__doc__,
 "getegid($module, /)\n"
@@ -8032,21 +2194,9 @@
     return os_getegid_impl(module);
 }
 
-static PyObject *
-os_getegid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=fd12c346fa41cccb input=1596f79ad1107d5d]*/
-{
-    return _PyLong_FromGid(getegid());
-}
-#endif /* HAVE_GETEGID */
-
-
-#ifdef HAVE_GETEUID
-/*[clinic input]
-os.geteuid
-
-Return the current process's effective user id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETEGID) */
+
+#if defined(HAVE_GETEUID)
 
 PyDoc_STRVAR(os_geteuid__doc__,
 "geteuid($module, /)\n"
@@ -8066,21 +2216,9 @@
     return os_geteuid_impl(module);
 }
 
-static PyObject *
-os_geteuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=03d98e07f4bc03d4 input=4644c662d3bd9f19]*/
-{
-    return _PyLong_FromUid(geteuid());
-}
-#endif /* HAVE_GETEUID */
-
-
-#ifdef HAVE_GETGID
-/*[clinic input]
-os.getgid
-
-Return the current process's group id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETEUID) */
+
+#if defined(HAVE_GETGID)
 
 PyDoc_STRVAR(os_getgid__doc__,
 "getgid($module, /)\n"
@@ -8100,20 +2238,7 @@
     return os_getgid_impl(module);
 }
 
-static PyObject *
-os_getgid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=07b0356121b8098d input=58796344cd87c0f6]*/
-{
-    return _PyLong_FromGid(getgid());
-}
-#endif /* HAVE_GETGID */
-
-
-/*[clinic input]
-os.getpid
-
-Return the current process id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETGID) */
 
 PyDoc_STRVAR(os_getpid__doc__,
 "getpid($module, /)\n"
@@ -8133,97 +2258,7 @@
     return os_getpid_impl(module);
 }
 
-static PyObject *
-os_getpid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d63a01a3cebc573d input=5a9a00f0ab68aa00]*/
-{
-    return PyLong_FromPid(getpid());
-}
-
-#ifdef HAVE_GETGROUPLIST
-
-/* AC 3.5: funny apple logic below */
-PyDoc_STRVAR(posix_getgrouplist__doc__,
-"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
-Returns a list of groups to which a user belongs.\n\n\
-    user: username to lookup\n\
-    group: base group id of the user");
-
-static PyObject *
-posix_getgrouplist(PyObject *self, PyObject *args)
-{
-#ifdef NGROUPS_MAX
-#define MAX_GROUPS NGROUPS_MAX
-#else
-    /* defined to be 16 on Solaris7, so this should be a small number */
-#define MAX_GROUPS 64
-#endif
-
-    const char *user;
-    int i, ngroups;
-    PyObject *list;
-#ifdef __APPLE__
-    int *groups, basegid;
-#else
-    gid_t *groups, basegid;
-#endif
-    ngroups = MAX_GROUPS;
-
-#ifdef __APPLE__
-    if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
-        return NULL;
-#else
-    if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
-                          _Py_Gid_Converter, &basegid))
-        return NULL;
-#endif
-
-#ifdef __APPLE__
-    groups = PyMem_New(int, ngroups);
-#else
-    groups = PyMem_New(gid_t, ngroups);
-#endif
-    if (groups == NULL)
-        return PyErr_NoMemory();
-
-    if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
-        PyMem_Del(groups);
-        return posix_error();
-    }
-
-    list = PyList_New(ngroups);
-    if (list == NULL) {
-        PyMem_Del(groups);
-        return NULL;
-    }
-
-    for (i = 0; i < ngroups; i++) {
-#ifdef __APPLE__
-        PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
-#else
-        PyObject *o = _PyLong_FromGid(groups[i]);
-#endif
-        if (o == NULL) {
-            Py_DECREF(list);
-            PyMem_Del(groups);
-            return NULL;
-        }
-        PyList_SET_ITEM(list, i, o);
-    }
-
-    PyMem_Del(groups);
-
-    return list;
-}
-#endif /* HAVE_GETGROUPLIST */
-
-
-#ifdef HAVE_GETGROUPS
-/*[clinic input]
-os.getgroups
-
-Return list of supplemental group IDs for the process.
-[clinic start generated code]*/
+#if defined(HAVE_GETGROUPS)
 
 PyDoc_STRVAR(os_getgroups__doc__,
 "getgroups($module, /)\n"
@@ -8243,160 +2278,9 @@
     return os_getgroups_impl(module);
 }
 
-static PyObject *
-os_getgroups_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d9a3559b2e6f4ab8 input=d3f109412e6a155c]*/
-{
-    PyObject *result = NULL;
-
-#ifdef NGROUPS_MAX
-#define MAX_GROUPS NGROUPS_MAX
-#else
-    /* defined to be 16 on Solaris7, so this should be a small number */
-#define MAX_GROUPS 64
-#endif
-    gid_t grouplist[MAX_GROUPS];
-
-    /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
-     * This is a helper variable to store the intermediate result when
-     * that happens.
-     *
-     * To keep the code readable the OSX behaviour is unconditional,
-     * according to the POSIX spec this should be safe on all unix-y
-     * systems.
-     */
-    gid_t* alt_grouplist = grouplist;
-    int n;
-
-#ifdef __APPLE__
-    /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
-     * there are more groups than can fit in grouplist.  Therefore, on OS X
-     * always first call getgroups with length 0 to get the actual number
-     * of groups.
-     */
-    n = getgroups(0, NULL);
-    if (n < 0) {
-        return posix_error();
-    } else if (n <= MAX_GROUPS) {
-        /* groups will fit in existing array */
-        alt_grouplist = grouplist;
-    } else {
-        alt_grouplist = PyMem_New(gid_t, n);
-        if (alt_grouplist == NULL) {
-            errno = EINVAL;
-            return posix_error();
-        }
-    }
-
-    n = getgroups(n, alt_grouplist);
-    if (n == -1) {
-        if (alt_grouplist != grouplist) {
-            PyMem_Free(alt_grouplist);
-        }
-        return posix_error();
-    }
-#else
-    n = getgroups(MAX_GROUPS, grouplist);
-    if (n < 0) {
-        if (errno == EINVAL) {
-            n = getgroups(0, NULL);
-            if (n == -1) {
-                return posix_error();
-            }
-            if (n == 0) {
-                /* Avoid malloc(0) */
-                alt_grouplist = grouplist;
-            } else {
-                alt_grouplist = PyMem_New(gid_t, n);
-                if (alt_grouplist == NULL) {
-                    errno = EINVAL;
-                    return posix_error();
-                }
-                n = getgroups(n, alt_grouplist);
-                if (n == -1) {
-                    PyMem_Free(alt_grouplist);
-                    return posix_error();
-                }
-            }
-        } else {
-            return posix_error();
-        }
-    }
-#endif
-
-    result = PyList_New(n);
-    if (result != NULL) {
-        int i;
-        for (i = 0; i < n; ++i) {
-            PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
-            if (o == NULL) {
-                Py_DECREF(result);
-                result = NULL;
-                break;
-            }
-            PyList_SET_ITEM(result, i, o);
-        }
-    }
-
-    if (alt_grouplist != grouplist) {
-        PyMem_Free(alt_grouplist);
-    }
-
-    return result;
-}
-#endif /* HAVE_GETGROUPS */
-
-#ifdef HAVE_INITGROUPS
-PyDoc_STRVAR(posix_initgroups__doc__,
-"initgroups(username, gid) -> None\n\n\
-Call the system initgroups() to initialize the group access list with all of\n\
-the groups of which the specified username is a member, plus the specified\n\
-group id.");
-
-/* AC 3.5: funny apple logic */
-static PyObject *
-posix_initgroups(PyObject *self, PyObject *args)
-{
-    PyObject *oname;
-    char *username;
-    int res;
-#ifdef __APPLE__
-    int gid;
-#else
-    gid_t gid;
-#endif
-
-#ifdef __APPLE__
-    if (!PyArg_ParseTuple(args, "O&i:initgroups",
-                          PyUnicode_FSConverter, &oname,
-                          &gid))
-#else
-    if (!PyArg_ParseTuple(args, "O&O&:initgroups",
-                          PyUnicode_FSConverter, &oname,
-                          _Py_Gid_Converter, &gid))
-#endif
-        return NULL;
-    username = PyBytes_AS_STRING(oname);
-
-    res = initgroups(username, gid);
-    Py_DECREF(oname);
-    if (res == -1)
-        return PyErr_SetFromErrno(PyExc_OSError);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-#endif /* HAVE_INITGROUPS */
-
-
-#ifdef HAVE_GETPGID
-/*[clinic input]
-os.getpgid
-
-    pid: pid_t
-
-Call the system call getpgid(), and return the result.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETGROUPS) */
+
+#if defined(HAVE_GETPGID)
 
 PyDoc_STRVAR(os_getpgid__doc__,
 "getpgid($module, /, pid)\n"
@@ -8427,24 +2311,9 @@
     return return_value;
 }
 
-static PyObject *
-os_getpgid_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=3db4ed686179160d input=39d710ae3baaf1c7]*/
-{
-    pid_t pgid = getpgid(pid);
-    if (pgid < 0)
-        return posix_error();
-    return PyLong_FromPid(pgid);
-}
-#endif /* HAVE_GETPGID */
-
-
-#ifdef HAVE_GETPGRP
-/*[clinic input]
-os.getpgrp
-
-Return the current process group id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETPGID) */
+
+#if defined(HAVE_GETPGRP)
 
 PyDoc_STRVAR(os_getpgrp__doc__,
 "getpgrp($module, /)\n"
@@ -8464,25 +2333,9 @@
     return os_getpgrp_impl(module);
 }
 
-static PyObject *
-os_getpgrp_impl(PyModuleDef *module)
-/*[clinic end generated code: output=3b0d3663ea054277 input=6846fb2bb9a3705e]*/
-{
-#ifdef GETPGRP_HAVE_ARG
-    return PyLong_FromPid(getpgrp(0));
-#else /* GETPGRP_HAVE_ARG */
-    return PyLong_FromPid(getpgrp());
-#endif /* GETPGRP_HAVE_ARG */
-}
-#endif /* HAVE_GETPGRP */
-
-
-#ifdef HAVE_SETPGRP
-/*[clinic input]
-os.setpgrp
-
-Make the current process the leader of its process group.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETPGRP) */
+
+#if defined(HAVE_SETPGRP)
 
 PyDoc_STRVAR(os_setpgrp__doc__,
 "setpgrp($module, /)\n"
@@ -8502,74 +2355,9 @@
     return os_setpgrp_impl(module);
 }
 
-static PyObject *
-os_setpgrp_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8fbb0ee29ef6fb2d input=1f0619fcb5731e7e]*/
-{
-#ifdef SETPGRP_HAVE_ARG
-    if (setpgrp(0, 0) < 0)
-#else /* SETPGRP_HAVE_ARG */
-    if (setpgrp() < 0)
-#endif /* SETPGRP_HAVE_ARG */
-        return posix_error();
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-#endif /* HAVE_SETPGRP */
-
-#ifdef HAVE_GETPPID
-
-#ifdef MS_WINDOWS
-#include <tlhelp32.h>
-
-static PyObject*
-win32_getppid()
-{
-    HANDLE snapshot;
-    pid_t mypid;
-    PyObject* result = NULL;
-    BOOL have_record;
-    PROCESSENTRY32 pe;
-
-    mypid = getpid(); /* This function never fails */
-
-    snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
-    if (snapshot == INVALID_HANDLE_VALUE)
-        return PyErr_SetFromWindowsErr(GetLastError());
-
-    pe.dwSize = sizeof(pe);
-    have_record = Process32First(snapshot, &pe);
-    while (have_record) {
-        if (mypid == (pid_t)pe.th32ProcessID) {
-            /* We could cache the ulong value in a static variable. */
-            result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
-            break;
-        }
-
-        have_record = Process32Next(snapshot, &pe);
-    }
-
-    /* If our loop exits and our pid was not found (result will be NULL)
-     * then GetLastError will return ERROR_NO_MORE_FILES. This is an
-     * error anyway, so let's raise it. */
-    if (!result)
-        result = PyErr_SetFromWindowsErr(GetLastError());
-
-    CloseHandle(snapshot);
-
-    return result;
-}
-#endif /*MS_WINDOWS*/
-
-
-/*[clinic input]
-os.getppid
-
-Return the parent's process id.
-
-If the parent process has already exited, Windows machines will still
-return its id; others systems will return the id of the 'init' process (1).
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETPGRP) */
+
+#if defined(HAVE_GETPPID)
 
 PyDoc_STRVAR(os_getppid__doc__,
 "getppid($module, /)\n"
@@ -8592,25 +2380,9 @@
     return os_getppid_impl(module);
 }
 
-static PyObject *
-os_getppid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9ff3b387781edf3a input=e637cb87539c030e]*/
-{
-#ifdef MS_WINDOWS
-    return win32_getppid();
-#else
-    return PyLong_FromPid(getppid());
-#endif
-}
-#endif /* HAVE_GETPPID */
-
-
-#ifdef HAVE_GETLOGIN
-/*[clinic input]
-os.getlogin
-
-Return the actual login name.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETPPID) */
+
+#if defined(HAVE_GETLOGIN)
 
 PyDoc_STRVAR(os_getlogin__doc__,
 "getlogin($module, /)\n"
@@ -8630,48 +2402,9 @@
     return os_getlogin_impl(module);
 }
 
-static PyObject *
-os_getlogin_impl(PyModuleDef *module)
-/*[clinic end generated code: output=ab6211dab104cbb2 input=2a21ab1e917163df]*/
-{
-    PyObject *result = NULL;
-#ifdef MS_WINDOWS
-    wchar_t user_name[UNLEN + 1];
-    DWORD num_chars = Py_ARRAY_LENGTH(user_name);
-
-    if (GetUserNameW(user_name, &num_chars)) {
-        /* num_chars is the number of unicode chars plus null terminator */
-        result = PyUnicode_FromWideChar(user_name, num_chars - 1);
-    }
-    else
-        result = PyErr_SetFromWindowsErr(GetLastError());
-#else
-    char *name;
-    int old_errno = errno;
-
-    errno = 0;
-    name = getlogin();
-    if (name == NULL) {
-        if (errno)
-            posix_error();
-        else
-            PyErr_SetString(PyExc_OSError, "unable to determine login name");
-    }
-    else
-        result = PyUnicode_DecodeFSDefault(name);
-    errno = old_errno;
-#endif
-    return result;
-}
-#endif /* HAVE_GETLOGIN */
-
-
-#ifdef HAVE_GETUID
-/*[clinic input]
-os.getuid
-
-Return the current process's user id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETLOGIN) */
+
+#if defined(HAVE_GETUID)
 
 PyDoc_STRVAR(os_getuid__doc__,
 "getuid($module, /)\n"
@@ -8691,29 +2424,9 @@
     return os_getuid_impl(module);
 }
 
-static PyObject *
-os_getuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=77e0dcf2e37d1e89 input=b53c8b35f110a516]*/
-{
-    return _PyLong_FromUid(getuid());
-}
-#endif /* HAVE_GETUID */
-
-
-#ifdef MS_WINDOWS
-#define HAVE_KILL
-#endif /* MS_WINDOWS */
-
-#ifdef HAVE_KILL
-/*[clinic input]
-os.kill
-
-    pid: pid_t
-    signal: Py_ssize_t
-    /
-
-Kill a process with a signal.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETUID) */
+
+#if defined(HAVE_KILL)
 
 PyDoc_STRVAR(os_kill__doc__,
 "kill($module, pid, signal, /)\n"
@@ -8744,66 +2457,9 @@
     return return_value;
 }
 
-static PyObject *
-os_kill_impl(PyModuleDef *module, pid_t pid, Py_ssize_t signal)
-/*[clinic end generated code: output=2f5c77920ed575e6 input=61a36b86ca275ab9]*/
-#ifndef MS_WINDOWS
-{
-    if (kill(pid, (int)signal) == -1)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#else /* !MS_WINDOWS */
-{
-    PyObject *result;
-    DWORD sig = (DWORD)signal;
-    DWORD err;
-    HANDLE handle;
-
-    /* Console processes which share a common console can be sent CTRL+C or
-       CTRL+BREAK events, provided they handle said events. */
-    if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
-        if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
-            err = GetLastError();
-            PyErr_SetFromWindowsErr(err);
-        }
-        else
-            Py_RETURN_NONE;
-    }
-
-    /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
-       attempt to open and terminate the process. */
-    handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
-    if (handle == NULL) {
-        err = GetLastError();
-        return PyErr_SetFromWindowsErr(err);
-    }
-
-    if (TerminateProcess(handle, sig) == 0) {
-        err = GetLastError();
-        result = PyErr_SetFromWindowsErr(err);
-    } else {
-        Py_INCREF(Py_None);
-        result = Py_None;
-    }
-
-    CloseHandle(handle);
-    return result;
-}
-#endif /* !MS_WINDOWS */
-#endif /* HAVE_KILL */
-
-
-#ifdef HAVE_KILLPG
-/*[clinic input]
-os.killpg
-
-    pgid: pid_t
-    signal: int
-    /
-
-Kill a process group with a signal.
-[clinic start generated code]*/
+#endif /* defined(HAVE_KILL) */
+
+#if defined(HAVE_KILLPG)
 
 PyDoc_STRVAR(os_killpg__doc__,
 "killpg($module, pgid, signal, /)\n"
@@ -8834,33 +2490,9 @@
     return return_value;
 }
 
-static PyObject *
-os_killpg_impl(PyModuleDef *module, pid_t pgid, int signal)
-/*[clinic end generated code: output=0e05215d1c007e01 input=38b5449eb8faec19]*/
-{
-    /* XXX some man pages make the `pgid` parameter an int, others
-       a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
-       take the same type. Moreover, pid_t is always at least as wide as
-       int (else compilation of this module fails), which is safe. */
-    if (killpg(pgid, signal) == -1)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_KILLPG */
-
-
-#ifdef HAVE_PLOCK
-#ifdef HAVE_SYS_LOCK_H
-#include <sys/lock.h>
-#endif
-
-/*[clinic input]
-os.plock
-    op: int
-    /
-
-Lock program segments into memory.");
-[clinic start generated code]*/
+#endif /* defined(HAVE_KILLPG) */
+
+#if defined(HAVE_PLOCK)
 
 PyDoc_STRVAR(os_plock__doc__,
 "plock($module, op, /)\n"
@@ -8890,26 +2522,9 @@
     return return_value;
 }
 
-static PyObject *
-os_plock_impl(PyModuleDef *module, int op)
-/*[clinic end generated code: output=2744fe4b6e5f4dbc input=e6e5e348e1525f60]*/
-{
-    if (plock(op) == -1)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_PLOCK */
-
-
-#ifdef HAVE_SETUID
-/*[clinic input]
-os.setuid
-
-    uid: uid_t
-    /
-
-Set the current process's user id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PLOCK) */
+
+#if defined(HAVE_SETUID)
 
 PyDoc_STRVAR(os_setuid__doc__,
 "setuid($module, uid, /)\n"
@@ -8939,26 +2554,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setuid_impl(PyModuleDef *module, uid_t uid)
-/*[clinic end generated code: output=aea344bc22ccf400 input=c921a3285aa22256]*/
-{
-    if (setuid(uid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETUID */
-
-
-#ifdef HAVE_SETEUID
-/*[clinic input]
-os.seteuid
-
-    euid: uid_t
-    /
-
-Set the current process's effective user id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETUID) */
+
+#if defined(HAVE_SETEUID)
 
 PyDoc_STRVAR(os_seteuid__doc__,
 "seteuid($module, euid, /)\n"
@@ -8988,26 +2586,9 @@
     return return_value;
 }
 
-static PyObject *
-os_seteuid_impl(PyModuleDef *module, uid_t euid)
-/*[clinic end generated code: output=6e824cce4f3b8a5d input=ba93d927e4781aa9]*/
-{
-    if (seteuid(euid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETEUID */
-
-
-#ifdef HAVE_SETEGID
-/*[clinic input]
-os.setegid
-
-    egid: gid_t
-    /
-
-Set the current process's effective group id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETEUID) */
+
+#if defined(HAVE_SETEGID)
 
 PyDoc_STRVAR(os_setegid__doc__,
 "setegid($module, egid, /)\n"
@@ -9037,27 +2618,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setegid_impl(PyModuleDef *module, gid_t egid)
-/*[clinic end generated code: output=80a32263a4d56a9c input=4080526d0ccd6ce3]*/
-{
-    if (setegid(egid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETEGID */
-
-
-#ifdef HAVE_SETREUID
-/*[clinic input]
-os.setreuid
-
-    ruid: uid_t
-    euid: uid_t
-    /
-
-Set the current process's real and effective user ids.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETEGID) */
+
+#if defined(HAVE_SETREUID)
 
 PyDoc_STRVAR(os_setreuid__doc__,
 "setreuid($module, ruid, euid, /)\n"
@@ -9088,30 +2651,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setreuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid)
-/*[clinic end generated code: output=d7f226f943dad739 input=0ca8978de663880c]*/
-{
-    if (setreuid(ruid, euid) < 0) {
-        return posix_error();
-    } else {
-        Py_INCREF(Py_None);
-        return Py_None;
-    }
-}
-#endif /* HAVE_SETREUID */
-
-
-#ifdef HAVE_SETREGID
-/*[clinic input]
-os.setregid
-
-    rgid: gid_t
-    egid: gid_t
-    /
-
-Set the current process's real and effective group ids.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETREUID) */
+
+#if defined(HAVE_SETREGID)
 
 PyDoc_STRVAR(os_setregid__doc__,
 "setregid($module, rgid, egid, /)\n"
@@ -9142,25 +2684,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setregid_impl(PyModuleDef *module, gid_t rgid, gid_t egid)
-/*[clinic end generated code: output=a82d9ab70f8e6562 input=c59499f72846db78]*/
-{
-    if (setregid(rgid, egid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETREGID */
-
-
-#ifdef HAVE_SETGID
-/*[clinic input]
-os.setgid
-    gid: gid_t
-    /
-
-Set the current process's group id.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETREGID) */
+
+#if defined(HAVE_SETGID)
 
 PyDoc_STRVAR(os_setgid__doc__,
 "setgid($module, gid, /)\n"
@@ -9190,26 +2716,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setgid_impl(PyModuleDef *module, gid_t gid)
-/*[clinic end generated code: output=08287886db435f23 input=27d30c4059045dc6]*/
-{
-    if (setgid(gid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETGID */
-
-
-#ifdef HAVE_SETGROUPS
-/*[clinic input]
-os.setgroups
-
-    groups: object
-    /
-
-Set the groups of the current process to list.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETGID) */
+
+#if defined(HAVE_SETGROUPS)
 
 PyDoc_STRVAR(os_setgroups__doc__,
 "setgroups($module, groups, /)\n"
@@ -9220,120 +2729,9 @@
 #define OS_SETGROUPS_METHODDEF    \
     {"setgroups", (PyCFunction)os_setgroups, METH_O, os_setgroups__doc__},
 
-static PyObject *
-os_setgroups(PyModuleDef *module, PyObject *groups)
-/*[clinic end generated code: output=0b8de65d5b3cda94 input=fa742ca3daf85a7e]*/
-{
-    int i, len;
-    gid_t grouplist[MAX_GROUPS];
-
-    if (!PySequence_Check(groups)) {
-        PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
-        return NULL;
-    }
-    len = PySequence_Size(groups);
-    if (len > MAX_GROUPS) {
-        PyErr_SetString(PyExc_ValueError, "too many groups");
-        return NULL;
-    }
-    for(i = 0; i < len; i++) {
-        PyObject *elem;
-        elem = PySequence_GetItem(groups, i);
-        if (!elem)
-            return NULL;
-        if (!PyLong_Check(elem)) {
-            PyErr_SetString(PyExc_TypeError,
-                            "groups must be integers");
-            Py_DECREF(elem);
-            return NULL;
-        } else {
-            if (!_Py_Gid_Converter(elem, &grouplist[i])) {
-                Py_DECREF(elem);
-                return NULL;
-            }
-        }
-        Py_DECREF(elem);
-    }
-
-    if (setgroups(len, grouplist) < 0)
-        return posix_error();
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-#endif /* HAVE_SETGROUPS */
-
-#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
-static PyObject *
-wait_helper(pid_t pid, int status, struct rusage *ru)
-{
-    PyObject *result;
-    static PyObject *struct_rusage;
-    _Py_IDENTIFIER(struct_rusage);
-
-    if (pid == -1)
-        return posix_error();
-
-    if (struct_rusage == NULL) {
-        PyObject *m = PyImport_ImportModuleNoBlock("resource");
-        if (m == NULL)
-            return NULL;
-        struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
-        Py_DECREF(m);
-        if (struct_rusage == NULL)
-            return NULL;
-    }
-
-    /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
-    result = PyStructSequence_New((PyTypeObject*) struct_rusage);
-    if (!result)
-        return NULL;
-
-#ifndef doubletime
-#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
-#endif
-
-    PyStructSequence_SET_ITEM(result, 0,
-                              PyFloat_FromDouble(doubletime(ru->ru_utime)));
-    PyStructSequence_SET_ITEM(result, 1,
-                              PyFloat_FromDouble(doubletime(ru->ru_stime)));
-#define SET_INT(result, index, value)\
-        PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
-    SET_INT(result, 2, ru->ru_maxrss);
-    SET_INT(result, 3, ru->ru_ixrss);
-    SET_INT(result, 4, ru->ru_idrss);
-    SET_INT(result, 5, ru->ru_isrss);
-    SET_INT(result, 6, ru->ru_minflt);
-    SET_INT(result, 7, ru->ru_majflt);
-    SET_INT(result, 8, ru->ru_nswap);
-    SET_INT(result, 9, ru->ru_inblock);
-    SET_INT(result, 10, ru->ru_oublock);
-    SET_INT(result, 11, ru->ru_msgsnd);
-    SET_INT(result, 12, ru->ru_msgrcv);
-    SET_INT(result, 13, ru->ru_nsignals);
-    SET_INT(result, 14, ru->ru_nvcsw);
-    SET_INT(result, 15, ru->ru_nivcsw);
-#undef SET_INT
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
-}
-#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
-
-
-#ifdef HAVE_WAIT3
-/*[clinic input]
-os.wait3
-
-    options: int
-Wait for completion of a child process.
-
-Returns a tuple of information about the child process:
-  (pid, status, rusage)
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETGROUPS) */
+
+#if defined(HAVE_WAIT3)
 
 PyDoc_STRVAR(os_wait3__doc__,
 "wait3($module, /, options)\n"
@@ -9367,42 +2765,9 @@
     return return_value;
 }
 
-static PyObject *
-os_wait3_impl(PyModuleDef *module, int options)
-/*[clinic end generated code: output=1f2a63b6a93cbb57 input=8ac4c56956b61710]*/
-{
-    pid_t pid;
-    struct rusage ru;
-    int async_err = 0;
-    WAIT_TYPE status;
-    WAIT_STATUS_INT(status) = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        pid = wait3(&status, options, &ru);
-        Py_END_ALLOW_THREADS
-    } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (pid < 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
-}
-#endif /* HAVE_WAIT3 */
-
-
-#ifdef HAVE_WAIT4
-/*[clinic input]
-
-os.wait4
-
-    pid: pid_t
-    options: int
-
-Wait for completion of a specific child process.
-
-Returns a tuple of information about the child process:
-  (pid, status, rusage)
-[clinic start generated code]*/
+#endif /* defined(HAVE_WAIT3) */
+
+#if defined(HAVE_WAIT4)
 
 PyDoc_STRVAR(os_wait4__doc__,
 "wait4($module, /, pid, options)\n"
@@ -9437,47 +2802,9 @@
     return return_value;
 }
 
-static PyObject *
-os_wait4_impl(PyModuleDef *module, pid_t pid, int options)
-/*[clinic end generated code: output=20dfb05289d37dc6 input=d11deed0750600ba]*/
-{
-    pid_t res;
-    struct rusage ru;
-    int async_err = 0;
-    WAIT_TYPE status;
-    WAIT_STATUS_INT(status) = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = wait4(pid, &status, options, &ru);
-        Py_END_ALLOW_THREADS
-    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res < 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    return wait_helper(res, WAIT_STATUS_INT(status), &ru);
-}
-#endif /* HAVE_WAIT4 */
-
-
-#if defined(HAVE_WAITID) && !defined(__APPLE__)
-/*[clinic input]
-os.waitid
-
-    idtype: idtype_t
-        Must be one of be P_PID, P_PGID or P_ALL.
-    id: id_t
-        The id to wait on.
-    options: int
-        Constructed from the ORing of one or more of WEXITED, WSTOPPED
-        or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
-    /
-
-Returns the result of waiting for a process or processes.
-
-Returns either waitid_result or None if WNOHANG is specified and there are
-no children in a waitable state.
-[clinic start generated code]*/
+#endif /* defined(HAVE_WAIT4) */
+
+#if (defined(HAVE_WAITID) && !defined(__APPLE__))
 
 PyDoc_STRVAR(os_waitid__doc__,
 "waitid($module, idtype, id, options, /)\n"
@@ -9520,60 +2847,9 @@
     return return_value;
 }
 
-static PyObject *
-os_waitid_impl(PyModuleDef *module, idtype_t idtype, id_t id, int options)
-/*[clinic end generated code: output=fb44bf97f01021b2 input=d8e7f76e052b7920]*/
-{
-    PyObject *result;
-    int res;
-    int async_err = 0;
-    siginfo_t si;
-    si.si_pid = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = waitid(idtype, id, &si, options);
-        Py_END_ALLOW_THREADS
-    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res < 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    if (si.si_pid == 0)
-        Py_RETURN_NONE;
-
-    result = PyStructSequence_New(&WaitidResultType);
-    if (!result)
-        return NULL;
-
-    PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
-    PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
-    PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
-    PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
-    PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
-    if (PyErr_Occurred()) {
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    return result;
-}
-#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
-
+#endif /* (defined(HAVE_WAITID) && !defined(__APPLE__)) */
 
 #if defined(HAVE_WAITPID)
-/*[clinic input]
-os.waitpid
-    pid: pid_t
-    options: int
-    /
-
-Wait for completion of a given child process.
-
-Returns a tuple of information regarding the child process:
-    (pid, status)
-
-The options argument is ignored on Windows.
-[clinic start generated code]*/
 
 PyDoc_STRVAR(os_waitpid__doc__,
 "waitpid($module, pid, options, /)\n"
@@ -9609,40 +2885,9 @@
     return return_value;
 }
 
-static PyObject *
-os_waitpid_impl(PyModuleDef *module, pid_t pid, int options)
-/*[clinic end generated code: output=095a6b00af70b7ac input=0bf1666b8758fda3]*/
-{
-    pid_t res;
-    int async_err = 0;
-    WAIT_TYPE status;
-    WAIT_STATUS_INT(status) = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = waitpid(pid, &status, options);
-        Py_END_ALLOW_THREADS
-    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res < 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
-}
-#elif defined(HAVE_CWAIT)
-/* MS C has a variant of waitpid() that's usable for most purposes. */
-/*[clinic input]
-os.waitpid
-    pid: Py_intptr_t
-    options: int
-    /
-
-Wait for completion of a given process.
-
-Returns a tuple of information regarding the process:
-    (pid, status << 8)
-
-The options argument is ignored on Windows.
-[clinic start generated code]*/
+#endif /* defined(HAVE_WAITPID) */
+
+#if defined(HAVE_CWAIT)
 
 PyDoc_STRVAR(os_waitpid__doc__,
 "waitpid($module, pid, options, /)\n"
@@ -9678,37 +2923,9 @@
     return return_value;
 }
 
-static PyObject *
-os_waitpid_impl(PyModuleDef *module, Py_intptr_t pid, int options)
-/*[clinic end generated code: output=c20b95b15ad44a3a input=444c8f51cca5b862]*/
-{
-    int status;
-    Py_intptr_t res;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = _cwait(&status, pid, options);
-        Py_END_ALLOW_THREADS
-    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res != 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    /* shift the status left a byte so this is more like the POSIX waitpid */
-    return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
-}
-#endif
-
-
-#ifdef HAVE_WAIT
-/*[clinic input]
-os.wait
-
-Wait for completion of a child process.
-
-Returns a tuple of information about the child process:
-    (pid, status)
-[clinic start generated code]*/
+#endif /* defined(HAVE_CWAIT) */
+
+#if defined(HAVE_WAIT)
 
 PyDoc_STRVAR(os_wait__doc__,
 "wait($module, /)\n"
@@ -9731,333 +2948,9 @@
     return os_wait_impl(module);
 }
 
-static PyObject *
-os_wait_impl(PyModuleDef *module)
-/*[clinic end generated code: output=2a83a9d164e7e6a8 input=03b0182d4a4700ce]*/
-{
-    pid_t pid;
-    int async_err = 0;
-    WAIT_TYPE status;
-    WAIT_STATUS_INT(status) = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        pid = wait(&status);
-        Py_END_ALLOW_THREADS
-    } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (pid < 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
-}
-#endif /* HAVE_WAIT */
-
-
-#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
-PyDoc_STRVAR(readlink__doc__,
-"readlink(path, *, dir_fd=None) -> path\n\n\
-Return a string representing the path to which the symbolic link points.\n\
-\n\
-If dir_fd is not None, it should be a file descriptor open to a directory,\n\
-  and path should be relative; path will then be relative to that directory.\n\
-dir_fd may not be implemented on your platform.\n\
-  If it is unavailable, using it will raise a NotImplementedError.");
-#endif
-
-#ifdef HAVE_READLINK
-
-/* AC 3.5: merge win32 and not together */
-static PyObject *
-posix_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
-{
-    path_t path;
-    int dir_fd = DEFAULT_DIR_FD;
-    char buffer[MAXPATHLEN];
-    ssize_t length;
-    PyObject *return_value = NULL;
-    static char *keywords[] = {"path", "dir_fd", NULL};
-
-    memset(&path, 0, sizeof(path));
-    path.function_name = "readlink";
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|$O&:readlink", keywords,
-                          path_converter, &path,
-                          READLINKAT_DIR_FD_CONVERTER, &dir_fd))
-        return NULL;
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_READLINKAT
-    if (dir_fd != DEFAULT_DIR_FD)
-        length = readlinkat(dir_fd, path.narrow, buffer, sizeof(buffer));
-    else
-#endif
-        length = readlink(path.narrow, buffer, sizeof(buffer));
-    Py_END_ALLOW_THREADS
-
-    if (length < 0) {
-        return_value = path_error(&path);
-        goto exit;
-    }
-
-    if (PyUnicode_Check(path.object))
-        return_value = PyUnicode_DecodeFSDefaultAndSize(buffer, length);
-    else
-        return_value = PyBytes_FromStringAndSize(buffer, length);
-exit:
-    path_cleanup(&path);
-    return return_value;
-}
-
-#endif /* HAVE_READLINK */
-
-#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
-
-static PyObject *
-win_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
-{
-    wchar_t *path;
-    DWORD n_bytes_returned;
-    DWORD io_result;
-    PyObject *po, *result;
-        int dir_fd;
-    HANDLE reparse_point_handle;
-
-    char target_buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
-    REPARSE_DATA_BUFFER *rdb = (REPARSE_DATA_BUFFER *)target_buffer;
-    wchar_t *print_name;
-
-    static char *keywords[] = {"path", "dir_fd", NULL};
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "U|$O&:readlink", keywords,
-                          &po,
-                          dir_fd_unavailable, &dir_fd
-                          ))
-        return NULL;
-
-    path = PyUnicode_AsUnicode(po);
-    if (path == NULL)
-        return NULL;
-
-    /* First get a handle to the reparse point */
-    Py_BEGIN_ALLOW_THREADS
-    reparse_point_handle = CreateFileW(
-        path,
-        0,
-        0,
-        0,
-        OPEN_EXISTING,
-        FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
-        0);
-    Py_END_ALLOW_THREADS
-
-    if (reparse_point_handle==INVALID_HANDLE_VALUE)
-        return win32_error_object("readlink", po);
-
-    Py_BEGIN_ALLOW_THREADS
-    /* New call DeviceIoControl to read the reparse point */
-    io_result = DeviceIoControl(
-        reparse_point_handle,
-        FSCTL_GET_REPARSE_POINT,
-        0, 0, /* in buffer */
-        target_buffer, sizeof(target_buffer),
-        &n_bytes_returned,
-        0 /* we're not using OVERLAPPED_IO */
-        );
-    CloseHandle(reparse_point_handle);
-    Py_END_ALLOW_THREADS
-
-    if (io_result==0)
-        return win32_error_object("readlink", po);
-
-    if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
-    {
-        PyErr_SetString(PyExc_ValueError,
-                "not a symbolic link");
-        return NULL;
-    }
-    print_name = rdb->SymbolicLinkReparseBuffer.PathBuffer +
-                 rdb->SymbolicLinkReparseBuffer.PrintNameOffset;
-
-    result = PyUnicode_FromWideChar(print_name,
-                    rdb->SymbolicLinkReparseBuffer.PrintNameLength/2);
-    return result;
-}
-
-#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
-
-
-
-#ifdef HAVE_SYMLINK
-
-#if defined(MS_WINDOWS)
-
-/* Grab CreateSymbolicLinkW dynamically from kernel32 */
-static DWORD (CALLBACK *Py_CreateSymbolicLinkW)(LPWSTR, LPWSTR, DWORD) = NULL;
-static DWORD (CALLBACK *Py_CreateSymbolicLinkA)(LPSTR, LPSTR, DWORD) = NULL;
-
-static int
-check_CreateSymbolicLink(void)
-{
-    HINSTANCE hKernel32;
-    /* only recheck */
-    if (Py_CreateSymbolicLinkW && Py_CreateSymbolicLinkA)
-        return 1;
-    hKernel32 = GetModuleHandleW(L"KERNEL32");
-    *(FARPROC*)&Py_CreateSymbolicLinkW = GetProcAddress(hKernel32,
-                                                        "CreateSymbolicLinkW");
-    *(FARPROC*)&Py_CreateSymbolicLinkA = GetProcAddress(hKernel32,
-                                                        "CreateSymbolicLinkA");
-    return (Py_CreateSymbolicLinkW && Py_CreateSymbolicLinkA);
-}
-
-/* Remove the last portion of the path */
-static void
-_dirnameW(WCHAR *path)
-{
-    WCHAR *ptr;
-
-    /* walk the path from the end until a backslash is encountered */
-    for(ptr = path + wcslen(path); ptr != path; ptr--) {
-        if (*ptr == L'\\' || *ptr == L'/')
-            break;
-    }
-    *ptr = 0;
-}
-
-/* Remove the last portion of the path */
-static void
-_dirnameA(char *path)
-{
-    char *ptr;
-
-    /* walk the path from the end until a backslash is encountered */
-    for(ptr = path + strlen(path); ptr != path; ptr--) {
-        if (*ptr == '\\' || *ptr == '/')
-            break;
-    }
-    *ptr = 0;
-}
-
-/* Is this path absolute? */
-static int
-_is_absW(const WCHAR *path)
-{
-    return path[0] == L'\\' || path[0] == L'/' || path[1] == L':';
-
-}
-
-/* Is this path absolute? */
-static int
-_is_absA(const char *path)
-{
-    return path[0] == '\\' || path[0] == '/' || path[1] == ':';
-
-}
-
-/* join root and rest with a backslash */
-static void
-_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
-{
-    size_t root_len;
-
-    if (_is_absW(rest)) {
-        wcscpy(dest_path, rest);
-        return;
-    }
-
-    root_len = wcslen(root);
-
-    wcscpy(dest_path, root);
-    if(root_len) {
-        dest_path[root_len] = L'\\';
-        root_len++;
-    }
-    wcscpy(dest_path+root_len, rest);
-}
-
-/* join root and rest with a backslash */
-static void
-_joinA(char *dest_path, const char *root, const char *rest)
-{
-    size_t root_len;
-
-    if (_is_absA(rest)) {
-        strcpy(dest_path, rest);
-        return;
-    }
-
-    root_len = strlen(root);
-
-    strcpy(dest_path, root);
-    if(root_len) {
-        dest_path[root_len] = '\\';
-        root_len++;
-    }
-    strcpy(dest_path+root_len, rest);
-}
-
-/* Return True if the path at src relative to dest is a directory */
-static int
-_check_dirW(WCHAR *src, WCHAR *dest)
-{
-    WIN32_FILE_ATTRIBUTE_DATA src_info;
-    WCHAR dest_parent[MAX_PATH];
-    WCHAR src_resolved[MAX_PATH] = L"";
-
-    /* dest_parent = os.path.dirname(dest) */
-    wcscpy(dest_parent, dest);
-    _dirnameW(dest_parent);
-    /* src_resolved = os.path.join(dest_parent, src) */
-    _joinW(src_resolved, dest_parent, src);
-    return (
-        GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
-        && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
-    );
-}
-
-/* Return True if the path at src relative to dest is a directory */
-static int
-_check_dirA(char *src, char *dest)
-{
-    WIN32_FILE_ATTRIBUTE_DATA src_info;
-    char dest_parent[MAX_PATH];
-    char src_resolved[MAX_PATH] = "";
-
-    /* dest_parent = os.path.dirname(dest) */
-    strcpy(dest_parent, dest);
-    _dirnameA(dest_parent);
-    /* src_resolved = os.path.join(dest_parent, src) */
-    _joinA(src_resolved, dest_parent, src);
-    return (
-        GetFileAttributesExA(src_resolved, GetFileExInfoStandard, &src_info)
-        && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
-    );
-}
-#endif
-
-
-/*[clinic input]
-os.symlink
-    src: path_t
-    dst: path_t
-    target_is_directory: bool = False
-    *
-    dir_fd: dir_fd(requires='symlinkat')=None
-
-# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
-
-Create a symbolic link pointing to src named dst.
-
-target_is_directory is required on Windows if the target is to be
-  interpreted as a directory.  (On Windows, symlink requires
-  Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
-  target_is_directory is ignored on non-Windows platforms.
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_WAIT) */
+
+#if defined(HAVE_SYMLINK)
 
 PyDoc_STRVAR(os_symlink__doc__,
 "symlink($module, /, src, dst, target_is_directory=False, *, dir_fd=None)\n"
@@ -10106,154 +2999,9 @@
     return return_value;
 }
 
-static PyObject *
-os_symlink_impl(PyModuleDef *module, path_t *src, path_t *dst, int target_is_directory, int dir_fd)
-/*[clinic end generated code: output=1a31e6d88aafe9b6 input=e820ec4472547bc3]*/
-{
-#ifdef MS_WINDOWS
-    DWORD result;
-#else
-    int result;
-#endif
-
-#ifdef MS_WINDOWS
-    if (!check_CreateSymbolicLink()) {
-        PyErr_SetString(PyExc_NotImplementedError,
-            "CreateSymbolicLink functions not found");
-        return NULL;
-        }
-    if (!win32_can_symlink) {
-        PyErr_SetString(PyExc_OSError, "symbolic link privilege not held");
-        return NULL;
-        }
-#endif
-
-    if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
-        PyErr_SetString(PyExc_ValueError,
-            "symlink: src and dst must be the same type");
-        return NULL;
-    }
-
-#ifdef MS_WINDOWS
-
-    Py_BEGIN_ALLOW_THREADS
-    if (dst->wide) {
-        /* if src is a directory, ensure target_is_directory==1 */
-        target_is_directory |= _check_dirW(src->wide, dst->wide);
-        result = Py_CreateSymbolicLinkW(dst->wide, src->wide,
-                                        target_is_directory);
-    }
-    else {
-        /* if src is a directory, ensure target_is_directory==1 */
-        target_is_directory |= _check_dirA(src->narrow, dst->narrow);
-        result = Py_CreateSymbolicLinkA(dst->narrow, src->narrow,
-                                        target_is_directory);
-    }
-    Py_END_ALLOW_THREADS
-
-    if (!result)
-        return path_error2(src, dst);
-
-#else
-
-    Py_BEGIN_ALLOW_THREADS
-#if HAVE_SYMLINKAT
-    if (dir_fd != DEFAULT_DIR_FD)
-        result = symlinkat(src->narrow, dir_fd, dst->narrow);
-    else
-#endif
-        result = symlink(src->narrow, dst->narrow);
-    Py_END_ALLOW_THREADS
-
-    if (result)
-        return path_error2(src, dst);
-#endif
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SYMLINK */
-
-
-
-
-static PyStructSequence_Field times_result_fields[] = {
-    {"user",    "user time"},
-    {"system",   "system time"},
-    {"children_user",    "user time of children"},
-    {"children_system",    "system time of children"},
-    {"elapsed",    "elapsed time since an arbitrary point in the past"},
-    {NULL}
-};
-
-PyDoc_STRVAR(times_result__doc__,
-"times_result: Result from os.times().\n\n\
-This object may be accessed either as a tuple of\n\
-  (user, system, children_user, children_system, elapsed),\n\
-or via the attributes user, system, children_user, children_system,\n\
-and elapsed.\n\
-\n\
-See os.times for more information.");
-
-static PyStructSequence_Desc times_result_desc = {
-    "times_result", /* name */
-    times_result__doc__, /* doc */
-    times_result_fields,
-    5
-};
-
-static PyTypeObject TimesResultType;
-
-#ifdef MS_WINDOWS
-#define HAVE_TIMES  /* mandatory, for the method table */
-#endif
-
-#ifdef HAVE_TIMES
-
-static PyObject *
-build_times_result(double user, double system,
-    double children_user, double children_system,
-    double elapsed)
-{
-    PyObject *value = PyStructSequence_New(&TimesResultType);
-    if (value == NULL)
-        return NULL;
-
-#define SET(i, field) \
-    { \
-    PyObject *o = PyFloat_FromDouble(field); \
-    if (!o) { \
-        Py_DECREF(value); \
-        return NULL; \
-    } \
-    PyStructSequence_SET_ITEM(value, i, o); \
-    } \
-
-    SET(0, user);
-    SET(1, system);
-    SET(2, children_user);
-    SET(3, children_system);
-    SET(4, elapsed);
-
-#undef SET
-
-    return value;
-}
-
-
-#ifndef MS_WINDOWS
-#define NEED_TICKS_PER_SECOND
-static long ticks_per_second = -1;
-#endif /* MS_WINDOWS */
-
-/*[clinic input]
-os.times
-
-Return a collection containing process timing information.
-
-The object returned behaves like a named tuple with these fields:
-  (utime, stime, cutime, cstime, elapsed_time)
-All fields are floating point numbers.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYMLINK) */
+
+#if defined(HAVE_TIMES)
 
 PyDoc_STRVAR(os_times__doc__,
 "times($module, /)\n"
@@ -10277,59 +3025,9 @@
     return os_times_impl(module);
 }
 
-static PyObject *
-os_times_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b86896d031a9b768 input=2bf9df3d6ab2e48b]*/
-#ifdef MS_WINDOWS
-{
-    FILETIME create, exit, kernel, user;
-    HANDLE hProc;
-    hProc = GetCurrentProcess();
-    GetProcessTimes(hProc, &create, &exit, &kernel, &user);
-    /* The fields of a FILETIME structure are the hi and lo part
-       of a 64-bit value expressed in 100 nanosecond units.
-       1e7 is one second in such units; 1e-7 the inverse.
-       429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
-    */
-    return build_times_result(
-        (double)(user.dwHighDateTime*429.4967296 +
-                 user.dwLowDateTime*1e-7),
-        (double)(kernel.dwHighDateTime*429.4967296 +
-                 kernel.dwLowDateTime*1e-7),
-        (double)0,
-        (double)0,
-        (double)0);
-}
-#else /* MS_WINDOWS */
-{
-
-
-    struct tms t;
-    clock_t c;
-    errno = 0;
-    c = times(&t);
-    if (c == (clock_t) -1)
-        return posix_error();
-    return build_times_result(
-                         (double)t.tms_utime / ticks_per_second,
-                         (double)t.tms_stime / ticks_per_second,
-                         (double)t.tms_cutime / ticks_per_second,
-                         (double)t.tms_cstime / ticks_per_second,
-                         (double)c / ticks_per_second);
-}
-#endif /* MS_WINDOWS */
-#endif /* HAVE_TIMES */
-
-
-#ifdef HAVE_GETSID
-/*[clinic input]
-os.getsid
-
-    pid: pid_t
-    /
-
-Call the system call getsid(pid) and return the result.
-[clinic start generated code]*/
+#endif /* defined(HAVE_TIMES) */
+
+#if defined(HAVE_GETSID)
 
 PyDoc_STRVAR(os_getsid__doc__,
 "getsid($module, pid, /)\n"
@@ -10359,25 +3057,9 @@
     return return_value;
 }
 
-static PyObject *
-os_getsid_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=ea8390f395f4e0e1 input=eeb2b923a30ce04e]*/
-{
-    int sid;
-    sid = getsid(pid);
-    if (sid < 0)
-        return posix_error();
-    return PyLong_FromLong((long)sid);
-}
-#endif /* HAVE_GETSID */
-
-
-#ifdef HAVE_SETSID
-/*[clinic input]
-os.setsid
-
-Call the system call setsid().
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETSID) */
+
+#if defined(HAVE_SETSID)
 
 PyDoc_STRVAR(os_setsid__doc__,
 "setsid($module, /)\n"
@@ -10397,27 +3079,9 @@
     return os_setsid_impl(module);
 }
 
-static PyObject *
-os_setsid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=2a9a1435d8d764d5 input=5fff45858e2f0776]*/
-{
-    if (setsid() < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETSID */
-
-
-#ifdef HAVE_SETPGID
-/*[clinic input]
-os.setpgid
-
-    pid: pid_t
-    pgrp: pid_t
-    /
-
-Call the system call setpgid(pid, pgrp).
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETSID) */
+
+#if defined(HAVE_SETPGID)
 
 PyDoc_STRVAR(os_setpgid__doc__,
 "setpgid($module, pid, pgrp, /)\n"
@@ -10448,26 +3112,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setpgid_impl(PyModuleDef *module, pid_t pid, pid_t pgrp)
-/*[clinic end generated code: output=7ad79b725f890e1f input=fceb395eca572e1a]*/
-{
-    if (setpgid(pid, pgrp) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETPGID */
-
-
-#ifdef HAVE_TCGETPGRP
-/*[clinic input]
-os.tcgetpgrp
-
-    fd: int
-    /
-
-Return the process group associated with the terminal specified by fd.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETPGID) */
+
+#if defined(HAVE_TCGETPGRP)
 
 PyDoc_STRVAR(os_tcgetpgrp__doc__,
 "tcgetpgrp($module, fd, /)\n"
@@ -10497,28 +3144,9 @@
     return return_value;
 }
 
-static PyObject *
-os_tcgetpgrp_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=abcf52ed4c8d22cb input=7f6c18eac10ada86]*/
-{
-    pid_t pgid = tcgetpgrp(fd);
-    if (pgid < 0)
-        return posix_error();
-    return PyLong_FromPid(pgid);
-}
-#endif /* HAVE_TCGETPGRP */
-
-
-#ifdef HAVE_TCSETPGRP
-/*[clinic input]
-os.tcsetpgrp
-
-    fd: int
-    pgid: pid_t
-    /
-
-Set the process group associated with the terminal specified by fd.
-[clinic start generated code]*/
+#endif /* defined(HAVE_TCGETPGRP) */
+
+#if defined(HAVE_TCSETPGRP)
 
 PyDoc_STRVAR(os_tcsetpgrp__doc__,
 "tcsetpgrp($module, fd, pgid, /)\n"
@@ -10549,40 +3177,7 @@
     return return_value;
 }
 
-static PyObject *
-os_tcsetpgrp_impl(PyModuleDef *module, int fd, pid_t pgid)
-/*[clinic end generated code: output=76f9bb8fd00f20f5 input=5bdc997c6a619020]*/
-{
-    if (tcsetpgrp(fd, pgid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_TCSETPGRP */
-
-/* Functions acting on file descriptors */
-
-#ifdef O_CLOEXEC
-extern int _Py_open_cloexec_works;
-#endif
-
-
-/*[clinic input]
-os.open -> int
-    path: path_t
-    flags: int
-    mode: int = 0o777
-    *
-    dir_fd: dir_fd(requires='openat') = None
-
-# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
-
-Open a file for low level IO.  Returns a file descriptor (integer).
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-[clinic start generated code]*/
+#endif /* defined(HAVE_TCSETPGRP) */
 
 PyDoc_STRVAR(os_open__doc__,
 "open($module, /, path, flags, mode=511, *, dir_fd=None)\n"
@@ -10628,66 +3223,6 @@
     return return_value;
 }
 
-static int
-os_open_impl(PyModuleDef *module, path_t *path, int flags, int mode, int dir_fd)
-/*[clinic end generated code: output=05b68fc4ed5e29c9 input=ad8623b29acd2934]*/
-{
-    int fd;
-    int async_err = 0;
-
-#ifdef O_CLOEXEC
-    int *atomic_flag_works = &_Py_open_cloexec_works;
-#elif !defined(MS_WINDOWS)
-    int *atomic_flag_works = NULL;
-#endif
-
-#ifdef MS_WINDOWS
-    flags |= O_NOINHERIT;
-#elif defined(O_CLOEXEC)
-    flags |= O_CLOEXEC;
-#endif
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-#ifdef MS_WINDOWS
-        if (path->wide)
-            fd = _wopen(path->wide, flags, mode);
-        else
-#endif
-#ifdef HAVE_OPENAT
-        if (dir_fd != DEFAULT_DIR_FD)
-            fd = openat(dir_fd, path->narrow, flags, mode);
-        else
-#endif
-            fd = open(path->narrow, flags, mode);
-        Py_END_ALLOW_THREADS
-    } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-
-    if (fd == -1) {
-        if (!async_err)
-            PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
-        return -1;
-    }
-
-#ifndef MS_WINDOWS
-    if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
-        close(fd);
-        return -1;
-    }
-#endif
-
-    return fd;
-}
-
-
-/*[clinic input]
-os.close
-
-    fd: int
-
-Close a file descriptor.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_close__doc__,
 "close($module, /, fd)\n"
 "--\n"
@@ -10717,36 +3252,6 @@
     return return_value;
 }
 
-static PyObject *
-os_close_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=927004e29ad55808 input=2bc42451ca5c3223]*/
-{
-    int res;
-    if (!_PyVerify_fd(fd))
-        return posix_error();
-    /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
-     * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
-     * for more details.
-     */
-    Py_BEGIN_ALLOW_THREADS
-    res = close(fd);
-    Py_END_ALLOW_THREADS
-    if (res < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.closerange
-
-    fd_low: int
-    fd_high: int
-    /
-
-Closes all file descriptors in [fd_low, fd_high), ignoring errors.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_closerange__doc__,
 "closerange($module, fd_low, fd_high, /)\n"
 "--\n"
@@ -10776,29 +3281,6 @@
     return return_value;
 }
 
-static PyObject *
-os_closerange_impl(PyModuleDef *module, int fd_low, int fd_high)
-/*[clinic end generated code: output=0a929ece386811c3 input=5855a3d053ebd4ec]*/
-{
-    int i;
-    Py_BEGIN_ALLOW_THREADS
-    for (i = fd_low; i < fd_high; i++)
-        if (_PyVerify_fd(i))
-            close(i);
-    Py_END_ALLOW_THREADS
-    Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.dup -> int
-
-    fd: int
-    /
-
-Return a duplicate of a file descriptor.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_dup__doc__,
 "dup($module, fd, /)\n"
 "--\n"
@@ -10831,23 +3313,6 @@
     return return_value;
 }
 
-static int
-os_dup_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=75943e057b25e1bd input=6f10f7ea97f7852a]*/
-{
-    return _Py_dup(fd);
-}
-
-
-/*[clinic input]
-os.dup2
-    fd: int
-    fd2: int
-    inheritable: bool=True
-
-Duplicate file descriptor.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_dup2__doc__,
 "dup2($module, /, fd, fd2, inheritable=True)\n"
 "--\n"
@@ -10879,100 +3344,7 @@
     return return_value;
 }
 
-static PyObject *
-os_dup2_impl(PyModuleDef *module, int fd, int fd2, int inheritable)
-/*[clinic end generated code: output=531e482dd11a99a0 input=76e96f511be0352f]*/
-{
-    int res;
-#if defined(HAVE_DUP3) && \
-    !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
-    /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
-    int dup3_works = -1;
-#endif
-
-    if (!_PyVerify_fd_dup2(fd, fd2))
-        return posix_error();
-
-    /* dup2() can fail with EINTR if the target FD is already open, because it
-     * then has to be closed. See os_close_impl() for why we don't handle EINTR
-     * upon close(), and therefore below.
-     */
-#ifdef MS_WINDOWS
-    Py_BEGIN_ALLOW_THREADS
-    res = dup2(fd, fd2);
-    Py_END_ALLOW_THREADS
-    if (res < 0)
-        return posix_error();
-
-    /* Character files like console cannot be make non-inheritable */
-    if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
-        close(fd2);
-        return NULL;
-    }
-
-#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
-    Py_BEGIN_ALLOW_THREADS
-    if (!inheritable)
-        res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
-    else
-        res = dup2(fd, fd2);
-    Py_END_ALLOW_THREADS
-    if (res < 0)
-        return posix_error();
-
-#else
-
-#ifdef HAVE_DUP3
-    if (!inheritable && dup3_works != 0) {
-        Py_BEGIN_ALLOW_THREADS
-        res = dup3(fd, fd2, O_CLOEXEC);
-        Py_END_ALLOW_THREADS
-        if (res < 0) {
-            if (dup3_works == -1)
-                dup3_works = (errno != ENOSYS);
-            if (dup3_works)
-                return posix_error();
-        }
-    }
-
-    if (inheritable || dup3_works == 0)
-    {
-#endif
-        Py_BEGIN_ALLOW_THREADS
-        res = dup2(fd, fd2);
-        Py_END_ALLOW_THREADS
-        if (res < 0)
-            return posix_error();
-
-        if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
-            close(fd2);
-            return NULL;
-        }
-#ifdef HAVE_DUP3
-    }
-#endif
-
-#endif
-
-    Py_RETURN_NONE;
-}
-
-
-#ifdef HAVE_LOCKF
-/*[clinic input]
-os.lockf
-
-    fd: int
-        An open file descriptor.
-    command: int
-        One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
-    length: Py_off_t
-        The number of bytes to lock, starting at the current position.
-    /
-
-Apply, test or remove a POSIX lock on an open file descriptor.
-
-[clinic start generated code]*/
+#if defined(HAVE_LOCKF)
 
 PyDoc_STRVAR(os_lockf__doc__,
 "lockf($module, fd, command, length, /)\n"
@@ -11011,37 +3383,7 @@
     return return_value;
 }
 
-static PyObject *
-os_lockf_impl(PyModuleDef *module, int fd, int command, Py_off_t length)
-/*[clinic end generated code: output=1b28346ac7335c0f input=65da41d2106e9b79]*/
-{
-    int res;
-
-    Py_BEGIN_ALLOW_THREADS
-    res = lockf(fd, command, length);
-    Py_END_ALLOW_THREADS
-
-    if (res < 0)
-        return posix_error();
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_LOCKF */
-
-
-/*[clinic input]
-os.lseek -> Py_off_t
-
-    fd: int
-    position: Py_off_t
-    how: int
-    /
-
-Set the position of a file descriptor.  Return the new position.
-
-Return the new cursor position in number of bytes
-relative to the beginning of the file.
-[clinic start generated code]*/
+#endif /* defined(HAVE_LOCKF) */
 
 PyDoc_STRVAR(os_lseek__doc__,
 "lseek($module, fd, position, how, /)\n"
@@ -11080,55 +3422,6 @@
     return return_value;
 }
 
-static Py_off_t
-os_lseek_impl(PyModuleDef *module, int fd, Py_off_t position, int how)
-/*[clinic end generated code: output=88cfc146f55667af input=902654ad3f96a6d3]*/
-{
-    Py_off_t result;
-
-    if (!_PyVerify_fd(fd)) {
-        posix_error();
-        return -1;
-    }
-#ifdef SEEK_SET
-    /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
-    switch (how) {
-        case 0: how = SEEK_SET; break;
-        case 1: how = SEEK_CUR; break;
-        case 2: how = SEEK_END; break;
-    }
-#endif /* SEEK_END */
-
-    if (PyErr_Occurred())
-        return -1;
-
-    if (!_PyVerify_fd(fd)) {
-        posix_error();
-        return -1;
-    }
-    Py_BEGIN_ALLOW_THREADS
-#ifdef MS_WINDOWS
-    result = _lseeki64(fd, position, how);
-#else
-    result = lseek(fd, position, how);
-#endif
-    Py_END_ALLOW_THREADS
-    if (result < 0)
-        posix_error();
-
-    return result;
-}
-
-
-/*[clinic input]
-os.read
-    fd: int
-    length: Py_ssize_t
-    /
-
-Read from a file descriptor.  Returns a bytes object.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_read__doc__,
 "read($module, fd, length, /)\n"
 "--\n"
@@ -11158,117 +3451,7 @@
     return return_value;
 }
 
-static PyObject *
-os_read_impl(PyModuleDef *module, int fd, Py_ssize_t length)
-/*[clinic end generated code: output=1f3bc27260a24968 input=1df2eaa27c0bf1d3]*/
-{
-    Py_ssize_t n;
-    PyObject *buffer;
-
-    if (length < 0) {
-        errno = EINVAL;
-        return posix_error();
-    }
-
-#ifdef MS_WINDOWS
-    /* On Windows, the count parameter of read() is an int */
-    if (length > INT_MAX)
-        length = INT_MAX;
-#endif
-
-    buffer = PyBytes_FromStringAndSize((char *)NULL, length);
-    if (buffer == NULL)
-        return NULL;
-
-    n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
-    if (n == -1) {
-        Py_DECREF(buffer);
-        return NULL;
-    }
-
-    if (n != length)
-        _PyBytes_Resize(&buffer, n);
-
-    return buffer;
-}
-
-#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
-    || defined(__APPLE__))) || defined(HAVE_READV) || defined(HAVE_WRITEV)
-static Py_ssize_t
-iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, int cnt, int type)
-{
-    int i, j;
-    Py_ssize_t blen, total = 0;
-
-    *iov = PyMem_New(struct iovec, cnt);
-    if (*iov == NULL) {
-        PyErr_NoMemory();
-        return -1;
-    }
-
-    *buf = PyMem_New(Py_buffer, cnt);
-    if (*buf == NULL) {
-        PyMem_Del(*iov);
-        PyErr_NoMemory();
-        return -1;
-    }
-
-    for (i = 0; i < cnt; i++) {
-        PyObject *item = PySequence_GetItem(seq, i);
-        if (item == NULL)
-            goto fail;
-        if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
-            Py_DECREF(item);
-            goto fail;
-        }
-        Py_DECREF(item);
-        (*iov)[i].iov_base = (*buf)[i].buf;
-        blen = (*buf)[i].len;
-        (*iov)[i].iov_len = blen;
-        total += blen;
-    }
-    return total;
-
-fail:
-    PyMem_Del(*iov);
-    for (j = 0; j < i; j++) {
-        PyBuffer_Release(&(*buf)[j]);
-    }
-    PyMem_Del(*buf);
-    return -1;
-}
-
-static void
-iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
-{
-    int i;
-    PyMem_Del(iov);
-    for (i = 0; i < cnt; i++) {
-        PyBuffer_Release(&buf[i]);
-    }
-    PyMem_Del(buf);
-}
-#endif
-
-
-#ifdef HAVE_READV
-/*[clinic input]
-os.readv -> Py_ssize_t
-
-    fd: int
-    buffers: object
-    /
-
-Read from a file descriptor fd into an iterable of buffers.
-
-The buffers should be mutable buffers accepting bytes.
-readv will transfer data into each buffer until it is full
-and then move on to the next buffer in the sequence to hold
-the rest of the data.
-
-readv returns the total number of bytes read,
-which may be less than the total capacity of all the buffers.
-[clinic start generated code]*/
+#if defined(HAVE_READV)
 
 PyDoc_STRVAR(os_readv__doc__,
 "readv($module, fd, buffers, /)\n"
@@ -11311,60 +3494,9 @@
     return return_value;
 }
 
-static Py_ssize_t
-os_readv_impl(PyModuleDef *module, int fd, PyObject *buffers)
-/*[clinic end generated code: output=72748b1c32a6e2a1 input=e679eb5dbfa0357d]*/
-{
-    int cnt;
-    Py_ssize_t n;
-    int async_err = 0;
-    struct iovec *iov;
-    Py_buffer *buf;
-
-    if (!PySequence_Check(buffers)) {
-        PyErr_SetString(PyExc_TypeError,
-            "readv() arg 2 must be a sequence");
-        return -1;
-    }
-
-    cnt = PySequence_Size(buffers);
-
-    if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
-        return -1;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        n = readv(fd, iov, cnt);
-        Py_END_ALLOW_THREADS
-    } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-
-    iov_cleanup(iov, buf, cnt);
-    if (n < 0) {
-        if (!async_err)
-            posix_error();
-        return -1;
-    }
-
-    return n;
-}
-#endif /* HAVE_READV */
-
-
-#ifdef HAVE_PREAD
-/*[clinic input]
-# TODO length should be size_t!  but Python doesn't support parsing size_t yet.
-os.pread
-
-    fd: int
-    length: int
-    offset: Py_off_t
-    /
-
-Read a number of bytes from a file descriptor starting at a particular offset.
-
-Read length bytes from file descriptor fd, starting at offset bytes from
-the beginning of the file.  The file offset remains unchanged.
-[clinic start generated code]*/
+#endif /* defined(HAVE_READV) */
+
+#if defined(HAVE_PREAD)
 
 PyDoc_STRVAR(os_pread__doc__,
 "pread($module, fd, length, offset, /)\n"
@@ -11399,52 +3531,7 @@
     return return_value;
 }
 
-static PyObject *
-os_pread_impl(PyModuleDef *module, int fd, int length, Py_off_t offset)
-/*[clinic end generated code: output=7b62bf6c06e20ae8 input=084948dcbaa35d4c]*/
-{
-    Py_ssize_t n;
-    int async_err = 0;
-    PyObject *buffer;
-
-    if (length < 0) {
-        errno = EINVAL;
-        return posix_error();
-    }
-    buffer = PyBytes_FromStringAndSize((char *)NULL, length);
-    if (buffer == NULL)
-        return NULL;
-    if (!_PyVerify_fd(fd)) {
-        Py_DECREF(buffer);
-        return posix_error();
-    }
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
-        Py_END_ALLOW_THREADS
-    } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-
-    if (n < 0) {
-        Py_DECREF(buffer);
-        return (!async_err) ? posix_error() : NULL;
-    }
-    if (n != length)
-        _PyBytes_Resize(&buffer, n);
-    return buffer;
-}
-#endif /* HAVE_PREAD */
-
-
-/*[clinic input]
-os.write -> Py_ssize_t
-
-    fd: int
-    data: Py_buffer
-    /
-
-Write a bytes object to a file descriptor.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PREAD) */
 
 PyDoc_STRVAR(os_write__doc__,
 "write($module, fd, data, /)\n"
@@ -11483,174 +3570,6 @@
     return return_value;
 }
 
-static Py_ssize_t
-os_write_impl(PyModuleDef *module, int fd, Py_buffer *data)
-/*[clinic end generated code: output=aeb96acfdd4d5112 input=3207e28963234f3c]*/
-{
-    return _Py_write(fd, data->buf, data->len);
-}
-
-#ifdef HAVE_SENDFILE
-PyDoc_STRVAR(posix_sendfile__doc__,
-"sendfile(out, in, offset, nbytes) -> byteswritten\n\
-sendfile(out, in, offset, nbytes, headers=None, trailers=None, flags=0)\n\
-            -> byteswritten\n\
-Copy nbytes bytes from file descriptor in to file descriptor out.");
-
-/* AC 3.5: don't bother converting, has optional group*/
-static PyObject *
-posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
-{
-    int in, out;
-    Py_ssize_t ret;
-    int async_err = 0;
-    off_t offset;
-
-#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
-#ifndef __APPLE__
-    Py_ssize_t len;
-#endif
-    PyObject *headers = NULL, *trailers = NULL;
-    Py_buffer *hbuf, *tbuf;
-    off_t sbytes;
-    struct sf_hdtr sf;
-    int flags = 0;
-    static char *keywords[] = {"out", "in",
-                                "offset", "count",
-                                "headers", "trailers", "flags", NULL};
-
-    sf.headers = NULL;
-    sf.trailers = NULL;
-
-#ifdef __APPLE__
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
-        keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
-#else
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
-        keywords, &out, &in, Py_off_t_converter, &offset, &len,
-#endif
-                &headers, &trailers, &flags))
-            return NULL;
-    if (headers != NULL) {
-        if (!PySequence_Check(headers)) {
-            PyErr_SetString(PyExc_TypeError,
-                "sendfile() headers must be a sequence or None");
-            return NULL;
-        } else {
-            Py_ssize_t i = 0; /* Avoid uninitialized warning */
-            sf.hdr_cnt = PySequence_Size(headers);
-            if (sf.hdr_cnt > 0 &&
-                (i = iov_setup(&(sf.headers), &hbuf,
-                                headers, sf.hdr_cnt, PyBUF_SIMPLE)) < 0)
-                return NULL;
-#ifdef __APPLE__
-            sbytes += i;
-#endif
-        }
-    }
-    if (trailers != NULL) {
-        if (!PySequence_Check(trailers)) {
-            PyErr_SetString(PyExc_TypeError,
-                "sendfile() trailers must be a sequence or None");
-            return NULL;
-        } else {
-            Py_ssize_t i = 0; /* Avoid uninitialized warning */
-            sf.trl_cnt = PySequence_Size(trailers);
-            if (sf.trl_cnt > 0 &&
-                (i = iov_setup(&(sf.trailers), &tbuf,
-                                trailers, sf.trl_cnt, PyBUF_SIMPLE)) < 0)
-                return NULL;
-#ifdef __APPLE__
-            sbytes += i;
-#endif
-        }
-    }
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-#ifdef __APPLE__
-        ret = sendfile(in, out, offset, &sbytes, &sf, flags);
-#else
-        ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
-#endif
-        Py_END_ALLOW_THREADS
-    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-
-    if (sf.headers != NULL)
-        iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
-    if (sf.trailers != NULL)
-        iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
-
-    if (ret < 0) {
-        if ((errno == EAGAIN) || (errno == EBUSY)) {
-            if (sbytes != 0) {
-                // some data has been sent
-                goto done;
-            }
-            else {
-                // no data has been sent; upper application is supposed
-                // to retry on EAGAIN or EBUSY
-                return posix_error();
-            }
-        }
-        return (!async_err) ? posix_error() : NULL;
-    }
-    goto done;
-
-done:
-    #if !defined(HAVE_LARGEFILE_SUPPORT)
-        return Py_BuildValue("l", sbytes);
-    #else
-        return Py_BuildValue("L", sbytes);
-    #endif
-
-#else
-    Py_ssize_t count;
-    PyObject *offobj;
-    static char *keywords[] = {"out", "in",
-                                "offset", "count", NULL};
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
-            keywords, &out, &in, &offobj, &count))
-        return NULL;
-#ifdef linux
-    if (offobj == Py_None) {
-        do {
-            Py_BEGIN_ALLOW_THREADS
-            ret = sendfile(out, in, NULL, count);
-            Py_END_ALLOW_THREADS
-        } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-        if (ret < 0)
-            return (!async_err) ? posix_error() : NULL;
-        return Py_BuildValue("n", ret);
-    }
-#endif
-    if (!Py_off_t_converter(offobj, &offset))
-        return NULL;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        ret = sendfile(out, in, &offset, count);
-        Py_END_ALLOW_THREADS
-    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (ret < 0)
-        return (!async_err) ? posix_error() : NULL;
-    return Py_BuildValue("n", ret);
-#endif
-}
-#endif /* HAVE_SENDFILE */
-
-
-/*[clinic input]
-os.fstat
-
-    fd : int
-
-Perform a stat system call on the given file descriptor.
-
-Like stat(), but for an open file descriptor.
-Equivalent to os.stat(fd).
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_fstat__doc__,
 "fstat($module, /, fd)\n"
 "--\n"
@@ -11683,42 +3602,6 @@
     return return_value;
 }
 
-static PyObject *
-os_fstat_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=dae4a9678c7bd881 input=27e0e0ebbe5600c9]*/
-{
-    STRUCT_STAT st;
-    int res;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        res = FSTAT(fd, &st);
-        Py_END_ALLOW_THREADS
-    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-    if (res != 0) {
-#ifdef MS_WINDOWS
-        return PyErr_SetFromWindowsErr(0);
-#else
-        return (!async_err) ? posix_error() : NULL;
-#endif
-    }
-
-    return _pystat_fromstructstat(&st);
-}
-
-
-/*[clinic input]
-os.isatty -> bool
-    fd: int
-    /
-
-Return True if the fd is connected to a terminal.
-
-Return True if the file descriptor is an open file descriptor
-connected to the slave end of a terminal.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_isatty__doc__,
 "isatty($module, fd, /)\n"
 "--\n"
@@ -11754,25 +3637,7 @@
     return return_value;
 }
 
-static int
-os_isatty_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=4bfadbfe22715097 input=08ce94aa1eaf7b5e]*/
-{
-    if (!_PyVerify_fd(fd))
-        return 0;
-    return isatty(fd);
-}
-
-
-#ifdef HAVE_PIPE
-/*[clinic input]
-os.pipe
-
-Create a pipe.
-
-Returns a tuple of two file descriptors:
-  (read_fd, write_fd)
-[clinic start generated code]*/
+#if defined(HAVE_PIPE)
 
 PyDoc_STRVAR(os_pipe__doc__,
 "pipe($module, /)\n"
@@ -11795,92 +3660,9 @@
     return os_pipe_impl(module);
 }
 
-static PyObject *
-os_pipe_impl(PyModuleDef *module)
-/*[clinic end generated code: output=0da2479f2266e774 input=02535e8c8fa6c4d4]*/
-{
-    int fds[2];
-#ifdef MS_WINDOWS
-    HANDLE read, write;
-    SECURITY_ATTRIBUTES attr;
-    BOOL ok;
-#else
-    int res;
-#endif
-
-#ifdef MS_WINDOWS
-    attr.nLength = sizeof(attr);
-    attr.lpSecurityDescriptor = NULL;
-    attr.bInheritHandle = FALSE;
-
-    Py_BEGIN_ALLOW_THREADS
-    ok = CreatePipe(&read, &write, &attr, 0);
-    if (ok) {
-        fds[0] = _open_osfhandle((Py_intptr_t)read, _O_RDONLY);
-        fds[1] = _open_osfhandle((Py_intptr_t)write, _O_WRONLY);
-        if (fds[0] == -1 || fds[1] == -1) {
-            CloseHandle(read);
-            CloseHandle(write);
-            ok = 0;
-        }
-    }
-    Py_END_ALLOW_THREADS
-
-    if (!ok)
-        return PyErr_SetFromWindowsErr(0);
-#else
-
-#ifdef HAVE_PIPE2
-    Py_BEGIN_ALLOW_THREADS
-    res = pipe2(fds, O_CLOEXEC);
-    Py_END_ALLOW_THREADS
-
-    if (res != 0 && errno == ENOSYS)
-    {
-#endif
-        Py_BEGIN_ALLOW_THREADS
-        res = pipe(fds);
-        Py_END_ALLOW_THREADS
-
-        if (res == 0) {
-            if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
-                close(fds[0]);
-                close(fds[1]);
-                return NULL;
-            }
-            if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
-                close(fds[0]);
-                close(fds[1]);
-                return NULL;
-            }
-        }
-#ifdef HAVE_PIPE2
-    }
-#endif
-
-    if (res != 0)
-        return PyErr_SetFromErrno(PyExc_OSError);
-#endif /* !MS_WINDOWS */
-    return Py_BuildValue("(ii)", fds[0], fds[1]);
-}
-#endif  /* HAVE_PIPE */
-
-
-#ifdef HAVE_PIPE2
-/*[clinic input]
-os.pipe2
-
-    flags: int
-    /
-
-Create a pipe with flags set atomically.
-
-Returns a tuple of two file descriptors:
-  (read_fd, write_fd)
-
-flags can be constructed by ORing together one or more of these values:
-O_NONBLOCK, O_CLOEXEC.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PIPE) */
+
+#if defined(HAVE_PIPE2)
 
 PyDoc_STRVAR(os_pipe2__doc__,
 "pipe2($module, flags, /)\n"
@@ -11916,33 +3698,9 @@
     return return_value;
 }
 
-static PyObject *
-os_pipe2_impl(PyModuleDef *module, int flags)
-/*[clinic end generated code: output=9e27c799ce19220b input=f261b6e7e63c6817]*/
-{
-    int fds[2];
-    int res;
-
-    res = pipe2(fds, flags);
-    if (res != 0)
-        return posix_error();
-    return Py_BuildValue("(ii)", fds[0], fds[1]);
-}
-#endif /* HAVE_PIPE2 */
-
-
-#ifdef HAVE_WRITEV
-/*[clinic input]
-os.writev -> Py_ssize_t
-    fd: int
-    buffers: object
-    /
-
-Iterate over buffers, and write the contents of each to a file descriptor.
-
-Returns the total number of bytes written.
-buffers must be a sequence of bytes-like objects.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PIPE2) */
+
+#if defined(HAVE_WRITEV)
 
 PyDoc_STRVAR(os_writev__doc__,
 "writev($module, fd, buffers, /)\n"
@@ -11980,57 +3738,9 @@
     return return_value;
 }
 
-static Py_ssize_t
-os_writev_impl(PyModuleDef *module, int fd, PyObject *buffers)
-/*[clinic end generated code: output=591c662dccbe4951 input=5b8d17fe4189d2fe]*/
-{
-    int cnt;
-    Py_ssize_t result;
-    int async_err = 0;
-    struct iovec *iov;
-    Py_buffer *buf;
-
-    if (!PySequence_Check(buffers)) {
-        PyErr_SetString(PyExc_TypeError,
-            "writev() arg 2 must be a sequence");
-        return -1;
-    }
-    cnt = PySequence_Size(buffers);
-
-    if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
-        return -1;
-    }
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        result = writev(fd, iov, cnt);
-        Py_END_ALLOW_THREADS
-    } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-
-    iov_cleanup(iov, buf, cnt);
-    if (result < 0 && !async_err)
-        posix_error();
-
-    return result;
-}
-#endif /* HAVE_WRITEV */
-
-
-#ifdef HAVE_PWRITE
-/*[clinic input]
-os.pwrite -> Py_ssize_t
-
-    fd: int
-    buffer: Py_buffer
-    offset: Py_off_t
-    /
-
-Write bytes to a file descriptor starting at a particular offset.
-
-Write buffer to fd, starting at offset bytes from the beginning of
-the file.  Returns the number of bytes writte.  Does not change the
-current file offset.
-[clinic start generated code]*/
+#endif /* defined(HAVE_WRITEV) */
+
+#if defined(HAVE_PWRITE)
 
 PyDoc_STRVAR(os_pwrite__doc__,
 "pwrite($module, fd, buffer, offset, /)\n"
@@ -12074,47 +3784,9 @@
     return return_value;
 }
 
-static Py_ssize_t
-os_pwrite_impl(PyModuleDef *module, int fd, Py_buffer *buffer, Py_off_t offset)
-/*[clinic end generated code: output=ec9cc5b2238e96a7 input=19903f1b3dd26377]*/
-{
-    Py_ssize_t size;
-    int async_err = 0;
-
-    if (!_PyVerify_fd(fd)) {
-        posix_error();
-        return -1;
-    }
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
-        Py_END_ALLOW_THREADS
-    } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
-
-    if (size < 0 && !async_err)
-        posix_error();
-    return size;
-}
-#endif /* HAVE_PWRITE */
-
-
-#ifdef HAVE_MKFIFO
-/*[clinic input]
-os.mkfifo
-
-    path: path_t
-    mode: int=0o666
-    *
-    dir_fd: dir_fd(requires='mkfifoat')=None
-
-Create a "fifo" (a POSIX named pipe).
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PWRITE) */
+
+#if defined(HAVE_MKFIFO)
 
 PyDoc_STRVAR(os_mkfifo__doc__,
 "mkfifo($module, /, path, mode=438, *, dir_fd=None)\n"
@@ -12155,56 +3827,9 @@
     return return_value;
 }
 
-static PyObject *
-os_mkfifo_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd)
-/*[clinic end generated code: output=b3321927546893d0 input=73032e98a36e0e19]*/
-{
-    int result;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_MKFIFOAT
-        if (dir_fd != DEFAULT_DIR_FD)
-            result = mkfifoat(dir_fd, path->narrow, mode);
-        else
-#endif
-            result = mkfifo(path->narrow, mode);
-        Py_END_ALLOW_THREADS
-    } while (result != 0 && errno == EINTR &&
-             !(async_err = PyErr_CheckSignals()));
-    if (result != 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_MKFIFO */
-
-
-#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
-/*[clinic input]
-os.mknod
-
-    path: path_t
-    mode: int=0o600
-    device: dev_t=0
-    *
-    dir_fd: dir_fd(requires='mknodat')=None
-
-Create a node in the file system.
-
-Create a node in the file system (file, device special file or named pipe)
-at path.  mode specifies both the permissions to use and the
-type of node to be created, being combined (bitwise OR) with one of
-S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO.  If S_IFCHR or S_IFBLK is set on mode,
-device defines the newly created device special file (probably using
-os.makedev()).  Otherwise device is ignored.
-
-If dir_fd is not None, it should be a file descriptor open to a directory,
-  and path should be relative; path will then be relative to that directory.
-dir_fd may not be implemented on your platform.
-  If it is unavailable, using it will raise a NotImplementedError.
-[clinic start generated code]*/
+#endif /* defined(HAVE_MKFIFO) */
+
+#if (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV))
 
 PyDoc_STRVAR(os_mknod__doc__,
 "mknod($module, /, path, mode=384, device=0, *, dir_fd=None)\n"
@@ -12253,41 +3878,9 @@
     return return_value;
 }
 
-static PyObject *
-os_mknod_impl(PyModuleDef *module, path_t *path, int mode, dev_t device, int dir_fd)
-/*[clinic end generated code: output=f71d54eaf9bb6f1a input=ee44531551a4d83b]*/
-{
-    int result;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_MKNODAT
-        if (dir_fd != DEFAULT_DIR_FD)
-            result = mknodat(dir_fd, path->narrow, mode, device);
-        else
-#endif
-            result = mknod(path->narrow, mode, device);
-        Py_END_ALLOW_THREADS
-    } while (result != 0 && errno == EINTR &&
-             !(async_err = PyErr_CheckSignals()));
-    if (result != 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    Py_RETURN_NONE;
-}
-#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
-
-
-#ifdef HAVE_DEVICE_MACROS
-/*[clinic input]
-os.major -> unsigned_int
-
-    device: dev_t
-    /
-
-Extracts a device major number from a raw device number.
-[clinic start generated code]*/
+#endif /* (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)) */
+
+#if defined(HAVE_DEVICE_MACROS)
 
 PyDoc_STRVAR(os_major__doc__,
 "major($module, device, /)\n"
@@ -12321,22 +3914,9 @@
     return return_value;
 }
 
-static unsigned int
-os_major_impl(PyModuleDef *module, dev_t device)
-/*[clinic end generated code: output=a2d06e908ebf95b5 input=1e16a4d30c4d4462]*/
-{
-    return major(device);
-}
-
-
-/*[clinic input]
-os.minor -> unsigned_int
-
-    device: dev_t
-    /
-
-Extracts a device minor number from a raw device number.
-[clinic start generated code]*/
+#endif /* defined(HAVE_DEVICE_MACROS) */
+
+#if defined(HAVE_DEVICE_MACROS)
 
 PyDoc_STRVAR(os_minor__doc__,
 "minor($module, device, /)\n"
@@ -12370,23 +3950,9 @@
     return return_value;
 }
 
-static unsigned int
-os_minor_impl(PyModuleDef *module, dev_t device)
-/*[clinic end generated code: output=6332287ee3f006e2 input=0842c6d23f24c65e]*/
-{
-    return minor(device);
-}
-
-
-/*[clinic input]
-os.makedev -> dev_t
-
-    major: int
-    minor: int
-    /
-
-Composes a raw device number from the major and minor device numbers.
-[clinic start generated code]*/
+#endif /* defined(HAVE_DEVICE_MACROS) */
+
+#if defined(HAVE_DEVICE_MACROS)
 
 PyDoc_STRVAR(os_makedev__doc__,
 "makedev($module, major, minor, /)\n"
@@ -12421,25 +3987,9 @@
     return return_value;
 }
 
-static dev_t
-os_makedev_impl(PyModuleDef *module, int major, int minor)
-/*[clinic end generated code: output=38e9a9774c96511a input=4b9fd8fc73cbe48f]*/
-{
-    return makedev(major, minor);
-}
-#endif /* HAVE_DEVICE_MACROS */
-
-
-#ifdef HAVE_FTRUNCATE
-/*[clinic input]
-os.ftruncate
-
-    fd: int
-    length: Py_off_t
-    /
-
-Truncate a file, specified by file descriptor, to a specific length.
-[clinic start generated code]*/
+#endif /* defined(HAVE_DEVICE_MACROS) */
+
+#if defined(HAVE_FTRUNCATE)
 
 PyDoc_STRVAR(os_ftruncate__doc__,
 "ftruncate($module, fd, length, /)\n"
@@ -12470,37 +4020,9 @@
     return return_value;
 }
 
-static PyObject *
-os_ftruncate_impl(PyModuleDef *module, int fd, Py_off_t length)
-/*[clinic end generated code: output=62326766cb9b76bf input=63b43641e52818f2]*/
-{
-    int result;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        result = ftruncate(fd, length);
-        Py_END_ALLOW_THREADS
-    } while (result != 0 && errno == EINTR &&
-             !(async_err = PyErr_CheckSignals()));
-    if (result != 0)
-        return (!async_err) ? posix_error() : NULL;
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_FTRUNCATE */
-
-
-#ifdef HAVE_TRUNCATE
-/*[clinic input]
-os.truncate
-    path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
-    length: Py_off_t
-
-Truncate a file, specified by path, to a specific length.
-
-On some platforms, path may also be specified as an open file descriptor.
-  If this functionality is unavailable, using it raises an exception.
-[clinic start generated code]*/
+#endif /* defined(HAVE_FTRUNCATE) */
+
+#if defined(HAVE_TRUNCATE)
 
 PyDoc_STRVAR(os_truncate__doc__,
 "truncate($module, /, path, length)\n"
@@ -12538,51 +4060,9 @@
     return return_value;
 }
 
-static PyObject *
-os_truncate_impl(PyModuleDef *module, path_t *path, Py_off_t length)
-/*[clinic end generated code: output=6bd76262d2e027c6 input=77229cf0b50a9b77]*/
-{
-    int result;
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_FTRUNCATE
-    if (path->fd != -1)
-        result = ftruncate(path->fd, length);
-    else
-#endif
-        result = truncate(path->narrow, length);
-    Py_END_ALLOW_THREADS
-    if (result < 0)
-        return path_error(path);
-
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_TRUNCATE */
-
-
-/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
-   and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
-   defined, which is the case in Python on AIX. AIX bug report:
-   http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
-#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
-#  define POSIX_FADVISE_AIX_BUG
-#endif
-
-
-#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
-/*[clinic input]
-os.posix_fallocate
-
-    fd: int
-    offset: Py_off_t
-    length: Py_off_t
-    /
-
-Ensure a file has allocated at least a particular number of bytes on disk.
-
-Ensure that the file specified by fd encompasses a range of bytes
-starting at offset bytes from the beginning and continuing for length bytes.
-[clinic start generated code]*/
+#endif /* defined(HAVE_TRUNCATE) */
+
+#if (defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG))
 
 PyDoc_STRVAR(os_posix_fallocate__doc__,
 "posix_fallocate($module, fd, offset, length, /)\n"
@@ -12617,46 +4097,9 @@
     return return_value;
 }
 
-static PyObject *
-os_posix_fallocate_impl(PyModuleDef *module, int fd, Py_off_t offset, Py_off_t length)
-/*[clinic end generated code: output=0cd702d2065c79db input=d7a2ef0ab2ca52fb]*/
-{
-    int result;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        result = posix_fallocate(fd, offset, length);
-        Py_END_ALLOW_THREADS
-    } while (result != 0 && errno == EINTR &&
-             !(async_err = PyErr_CheckSignals()));
-    if (result != 0)
-        return (!async_err) ? posix_error() : NULL;
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
-
-
-#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
-/*[clinic input]
-os.posix_fadvise
-
-    fd: int
-    offset: Py_off_t
-    length: Py_off_t
-    advice: int
-    /
-
-Announce an intention to access data in a specific pattern.
-
-Announce an intention to access data in a specific pattern, thus allowing
-the kernel to make optimizations.
-The advice applies to the region of the file specified by fd starting at
-offset and continuing for length bytes.
-advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
-POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
-POSIX_FADV_DONTNEED.
-[clinic start generated code]*/
+#endif /* (defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)) */
+
+#if (defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG))
 
 PyDoc_STRVAR(os_posix_fadvise__doc__,
 "posix_fadvise($module, fd, offset, length, advice, /)\n"
@@ -12697,56 +4140,9 @@
     return return_value;
 }
 
-static PyObject *
-os_posix_fadvise_impl(PyModuleDef *module, int fd, Py_off_t offset, Py_off_t length, int advice)
-/*[clinic end generated code: output=dad93f32c04dd4f7 input=0fbe554edc2f04b5]*/
-{
-    int result;
-    int async_err = 0;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        result = posix_fadvise(fd, offset, length, advice);
-        Py_END_ALLOW_THREADS
-    } while (result != 0 && errno == EINTR &&
-             !(async_err = PyErr_CheckSignals()));
-    if (result != 0)
-        return (!async_err) ? posix_error() : NULL;
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
-
-#ifdef HAVE_PUTENV
-
-/* Save putenv() parameters as values here, so we can collect them when they
- * get re-set with another call for the same key. */
-static PyObject *posix_putenv_garbage;
-
-static void
-posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
-{
-    /* Install the first arg and newstr in posix_putenv_garbage;
-     * this will cause previous value to be collected.  This has to
-     * happen after the real putenv() call because the old value
-     * was still accessible until then. */
-    if (PyDict_SetItem(posix_putenv_garbage, name, value))
-        /* really not much we can do; just leak */
-        PyErr_Clear();
-    else
-        Py_DECREF(value);
-}
-
-
-#ifdef MS_WINDOWS
-/*[clinic input]
-os.putenv
-
-    name: unicode
-    value: unicode
-    /
-
-Change or add an environment variable.
-[clinic start generated code]*/
+#endif /* (defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)) */
+
+#if defined(HAVE_PUTENV) && defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os_putenv__doc__,
 "putenv($module, name, value, /)\n"
@@ -12777,49 +4173,9 @@
     return return_value;
 }
 
-static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=5ce9ef9b15606e7e input=ba586581c2e6105f]*/
-{
-    wchar_t *env;
-
-    PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
-    if (unicode == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    if (_MAX_ENV < PyUnicode_GET_LENGTH(unicode)) {
-        PyErr_Format(PyExc_ValueError,
-                     "the environment variable is longer than %u characters",
-                     _MAX_ENV);
-        goto error;
-    }
-
-    env = PyUnicode_AsUnicode(unicode);
-    if (env == NULL)
-        goto error;
-    if (_wputenv(env)) {
-        posix_error();
-        goto error;
-    }
-
-    posix_putenv_garbage_setitem(name, unicode);
-    Py_RETURN_NONE;
-
-error:
-    Py_DECREF(unicode);
-    return NULL;
-}
-#else /* MS_WINDOWS */
-/*[clinic input]
-os.putenv
-
-    name: FSConverter
-    value: FSConverter
-    /
-
-Change or add an environment variable.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PUTENV) && defined(MS_WINDOWS) */
+
+#if defined(HAVE_PUTENV) && !defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os_putenv__doc__,
 "putenv($module, name, value, /)\n"
@@ -12855,42 +4211,9 @@
     return return_value;
 }
 
-static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=85ab223393dc7afd input=a97bc6152f688d31]*/
-{
-    PyObject *bytes = NULL;
-    char *env;
-    char *name_string = PyBytes_AsString(name);
-    char *value_string = PyBytes_AsString(value);
-
-    bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
-    if (bytes == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-
-    env = PyBytes_AS_STRING(bytes);
-    if (putenv(env)) {
-        Py_DECREF(bytes);
-        return posix_error();
-    }
-
-    posix_putenv_garbage_setitem(name, bytes);
-    Py_RETURN_NONE;
-}
-#endif /* MS_WINDOWS */
-#endif /* HAVE_PUTENV */
-
-
-#ifdef HAVE_UNSETENV
-/*[clinic input]
-os.unsetenv
-    name: FSConverter
-    /
-
-Delete an environment variable.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PUTENV) && !defined(MS_WINDOWS) */
+
+#if defined(HAVE_UNSETENV)
 
 PyDoc_STRVAR(os_unsetenv__doc__,
 "unsetenv($module, name, /)\n"
@@ -12923,44 +4246,7 @@
     return return_value;
 }
 
-static PyObject *
-os_unsetenv_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=91318c995f9a0767 input=2bb5288a599c7107]*/
-{
-#ifndef HAVE_BROKEN_UNSETENV
-    int err;
-#endif
-
-#ifdef HAVE_BROKEN_UNSETENV
-    unsetenv(PyBytes_AS_STRING(name));
-#else
-    err = unsetenv(PyBytes_AS_STRING(name));
-    if (err)
-        return posix_error();
-#endif
-
-    /* Remove the key from posix_putenv_garbage;
-     * this will cause it to be collected.  This has to
-     * happen after the real unsetenv() call because the
-     * old value was still accessible until then.
-     */
-    if (PyDict_DelItem(posix_putenv_garbage, name)) {
-        /* really not much we can do; just leak */
-        PyErr_Clear();
-    }
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_UNSETENV */
-
-
-/*[clinic input]
-os.strerror
-
-    code: int
-    /
-
-Translate an error code to a message string.
-[clinic start generated code]*/
+#endif /* defined(HAVE_UNSETENV) */
 
 PyDoc_STRVAR(os_strerror__doc__,
 "strerror($module, code, /)\n"
@@ -12990,30 +4276,7 @@
     return return_value;
 }
 
-static PyObject *
-os_strerror_impl(PyModuleDef *module, int code)
-/*[clinic end generated code: output=8665c70bb2ca4720 input=75a8673d97915a91]*/
-{
-    char *message = strerror(code);
-    if (message == NULL) {
-        PyErr_SetString(PyExc_ValueError,
-                        "strerror() argument out of range");
-        return NULL;
-    }
-    return PyUnicode_DecodeLocale(message, "surrogateescape");
-}
-
-
-#ifdef HAVE_SYS_WAIT_H
-#ifdef WCOREDUMP
-/*[clinic input]
-os.WCOREDUMP -> bool
-
-    status: int
-    /
-
-Return True if the process returning status was dumped to a core file.
-[clinic start generated code]*/
+#if defined(HAVE_SYS_WAIT_H) && defined(WCOREDUMP)
 
 PyDoc_STRVAR(os_WCOREDUMP__doc__,
 "WCOREDUMP($module, status, /)\n"
@@ -13047,28 +4310,9 @@
     return return_value;
 }
 
-static int
-os_WCOREDUMP_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=e04d55c09c299828 input=8b05e7ab38528d04]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WCOREDUMP(wait_status);
-}
-#endif /* WCOREDUMP */
-
-
-#ifdef WIFCONTINUED
-/*[clinic input]
-os.WIFCONTINUED -> bool
-
-    status: int
-
-Return True if a particular process was continued from a job control stop.
-
-Return True if the process returning status was continued from a
-job control stop.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WCOREDUMP) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WIFCONTINUED)
 
 PyDoc_STRVAR(os_WIFCONTINUED__doc__,
 "WIFCONTINUED($module, /, status)\n"
@@ -13106,25 +4350,9 @@
     return return_value;
 }
 
-static int
-os_WIFCONTINUED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=9c4e6105a4520ab5 input=e777e7d38eb25bd9]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WIFCONTINUED(wait_status);
-}
-#endif /* WIFCONTINUED */
-
-
-#ifdef WIFSTOPPED
-/*[clinic input]
-os.WIFSTOPPED -> bool
-
-    status: int
-
-Return True if the process returning status was stopped.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WIFCONTINUED) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WIFSTOPPED)
 
 PyDoc_STRVAR(os_WIFSTOPPED__doc__,
 "WIFSTOPPED($module, /, status)\n"
@@ -13159,25 +4387,9 @@
     return return_value;
 }
 
-static int
-os_WIFSTOPPED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=e0de2da8ec9593ff input=043cb7f1289ef904]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WIFSTOPPED(wait_status);
-}
-#endif /* WIFSTOPPED */
-
-
-#ifdef WIFSIGNALED
-/*[clinic input]
-os.WIFSIGNALED -> bool
-
-    status: int
-
-Return True if the process returning status was terminated by a signal.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WIFSTOPPED) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WIFSIGNALED)
 
 PyDoc_STRVAR(os_WIFSIGNALED__doc__,
 "WIFSIGNALED($module, /, status)\n"
@@ -13212,25 +4424,9 @@
     return return_value;
 }
 
-static int
-os_WIFSIGNALED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=f14d106558f406be input=d55ba7cc9ce5dc43]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WIFSIGNALED(wait_status);
-}
-#endif /* WIFSIGNALED */
-
-
-#ifdef WIFEXITED
-/*[clinic input]
-os.WIFEXITED -> bool
-
-    status: int
-
-Return True if the process returning status exited via the exit() system call.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WIFSIGNALED) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WIFEXITED)
 
 PyDoc_STRVAR(os_WIFEXITED__doc__,
 "WIFEXITED($module, /, status)\n"
@@ -13265,25 +4461,9 @@
     return return_value;
 }
 
-static int
-os_WIFEXITED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=2f76087d53721255 input=d63775a6791586c0]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WIFEXITED(wait_status);
-}
-#endif /* WIFEXITED */
-
-
-#ifdef WEXITSTATUS
-/*[clinic input]
-os.WEXITSTATUS -> int
-
-    status: int
-
-Return the process return code from status.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WIFEXITED) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WEXITSTATUS)
 
 PyDoc_STRVAR(os_WEXITSTATUS__doc__,
 "WEXITSTATUS($module, /, status)\n"
@@ -13318,25 +4498,9 @@
     return return_value;
 }
 
-static int
-os_WEXITSTATUS_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=13b6c270e2a326b1 input=e1fb4944e377585b]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WEXITSTATUS(wait_status);
-}
-#endif /* WEXITSTATUS */
-
-
-#ifdef WTERMSIG
-/*[clinic input]
-os.WTERMSIG -> int
-
-    status: int
-
-Return the signal that terminated the process that provided the status value.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WEXITSTATUS) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WTERMSIG)
 
 PyDoc_STRVAR(os_WTERMSIG__doc__,
 "WTERMSIG($module, /, status)\n"
@@ -13371,25 +4535,9 @@
     return return_value;
 }
 
-static int
-os_WTERMSIG_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=bf1fd4b002d0a9ed input=727fd7f84ec3f243]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WTERMSIG(wait_status);
-}
-#endif /* WTERMSIG */
-
-
-#ifdef WSTOPSIG
-/*[clinic input]
-os.WSTOPSIG -> int
-
-    status: int
-
-Return the signal that stopped the process that provided the status value.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WTERMSIG) */
+
+#if defined(HAVE_SYS_WAIT_H) && defined(WSTOPSIG)
 
 PyDoc_STRVAR(os_WSTOPSIG__doc__,
 "WSTOPSIG($module, /, status)\n"
@@ -13424,112 +4572,9 @@
     return return_value;
 }
 
-static int
-os_WSTOPSIG_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=92e1647d29ee0549 input=46ebf1d1b293c5c1]*/
-{
-    WAIT_TYPE wait_status;
-    WAIT_STATUS_INT(wait_status) = status;
-    return WSTOPSIG(wait_status);
-}
-#endif /* WSTOPSIG */
-#endif /* HAVE_SYS_WAIT_H */
-
-
-#ifndef OS_WCOREDUMP_METHODDEF
-#define OS_WCOREDUMP_METHODDEF
-#endif /* OS_WCOREDUMP_METHODDEF */
-
-#ifndef OS_WIFCONTINUED_METHODDEF
-#define OS_WIFCONTINUED_METHODDEF
-#endif /* OS_WIFCONTINUED_METHODDEF */
-
-#ifndef OS_WIFSTOPPED_METHODDEF
-#define OS_WIFSTOPPED_METHODDEF
-#endif /* OS_WIFSTOPPED_METHODDEF */
-
-#ifndef OS_WIFSIGNALED_METHODDEF
-#define OS_WIFSIGNALED_METHODDEF
-#endif /* OS_WIFSIGNALED_METHODDEF */
-
-#ifndef OS_WIFEXITED_METHODDEF
-#define OS_WIFEXITED_METHODDEF
-#endif /* OS_WIFEXITED_METHODDEF */
-
-#ifndef OS_WEXITSTATUS_METHODDEF
-#define OS_WEXITSTATUS_METHODDEF
-#endif /* OS_WEXITSTATUS_METHODDEF */
-
-#ifndef OS_WTERMSIG_METHODDEF
-#define OS_WTERMSIG_METHODDEF
-#endif /* OS_WTERMSIG_METHODDEF */
-
-#ifndef OS_WSTOPSIG_METHODDEF
-#define OS_WSTOPSIG_METHODDEF
-#endif /* OS_WSTOPSIG_METHODDEF */
-
-
-#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
-#ifdef _SCO_DS
-/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
-   needed definitions in sys/statvfs.h */
-#define _SVID3
-#endif
-#include <sys/statvfs.h>
-
-static PyObject*
-_pystatvfs_fromstructstatvfs(struct statvfs st) {
-    PyObject *v = PyStructSequence_New(&StatVFSResultType);
-    if (v == NULL)
-        return NULL;
-
-#if !defined(HAVE_LARGEFILE_SUPPORT)
-    PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
-    PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
-    PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
-    PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
-    PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
-    PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
-    PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
-    PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
-    PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
-    PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
-#else
-    PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
-    PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
-    PyStructSequence_SET_ITEM(v, 2,
-                              PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks));
-    PyStructSequence_SET_ITEM(v, 3,
-                              PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree));
-    PyStructSequence_SET_ITEM(v, 4,
-                              PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail));
-    PyStructSequence_SET_ITEM(v, 5,
-                              PyLong_FromLongLong((PY_LONG_LONG) st.f_files));
-    PyStructSequence_SET_ITEM(v, 6,
-                              PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree));
-    PyStructSequence_SET_ITEM(v, 7,
-                              PyLong_FromLongLong((PY_LONG_LONG) st.f_favail));
-    PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
-    PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
-#endif
-    if (PyErr_Occurred()) {
-        Py_DECREF(v);
-        return NULL;
-    }
-
-    return v;
-}
-
-
-/*[clinic input]
-os.fstatvfs
-    fd: int
-    /
-
-Perform an fstatvfs system call on the given fd.
-
-Equivalent to statvfs(fd).
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYS_WAIT_H) && defined(WSTOPSIG) */
+
+#if (defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H))
 
 PyDoc_STRVAR(os_fstatvfs__doc__,
 "fstatvfs($module, fd, /)\n"
@@ -13561,41 +4606,9 @@
     return return_value;
 }
 
-static PyObject *
-os_fstatvfs_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=0e32bf07f946ec0d input=d8122243ac50975e]*/
-{
-    int result;
-    int async_err = 0;
-    struct statvfs st;
-
-    do {
-        Py_BEGIN_ALLOW_THREADS
-        result = fstatvfs(fd, &st);
-        Py_END_ALLOW_THREADS
-    } while (result != 0 && errno == EINTR &&
-             !(async_err = PyErr_CheckSignals()));
-    if (result != 0)
-        return (!async_err) ? posix_error() : NULL;
-
-    return _pystatvfs_fromstructstatvfs(st);
-}
-#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
-
-
-#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
-#include <sys/statvfs.h>
-/*[clinic input]
-os.statvfs
-
-    path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
-
-Perform a statvfs system call on the given path.
-
-path may always be specified as a string.
-On some platforms, path may also be specified as an open file descriptor.
-  If this functionality is unavailable, using it raises an exception.
-[clinic start generated code]*/
+#endif /* (defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)) */
+
+#if (defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H))
 
 PyDoc_STRVAR(os_statvfs__doc__,
 "statvfs($module, /, path)\n"
@@ -13633,47 +4646,9 @@
     return return_value;
 }
 
-static PyObject *
-os_statvfs_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=00ff54983360b446 input=3f5c35791c669bd9]*/
-{
-    int result;
-    struct statvfs st;
-
-    Py_BEGIN_ALLOW_THREADS
-#ifdef HAVE_FSTATVFS
-    if (path->fd != -1) {
-#ifdef __APPLE__
-        /* handle weak-linking on Mac OS X 10.3 */
-        if (fstatvfs == NULL) {
-            fd_specified("statvfs", path->fd);
-            return NULL;
-        }
-#endif
-        result = fstatvfs(path->fd, &st);
-    }
-    else
-#endif
-        result = statvfs(path->narrow, &st);
-    Py_END_ALLOW_THREADS
-
-    if (result) {
-        return path_error(path);
-    }
-
-    return _pystatvfs_fromstructstatvfs(st);
-}
-#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
-
-
-#ifdef MS_WINDOWS
-/*[clinic input]
-os._getdiskusage
-
-    path: Py_UNICODE
-
-Return disk usage statistics about the given path as a (total, free) tuple.
-[clinic start generated code]*/
+#endif /* (defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)) */
+
+#if defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os__getdiskusage__doc__,
 "_getdiskusage($module, /, path)\n"
@@ -13704,191 +4679,9 @@
     return return_value;
 }
 
-static PyObject *
-os__getdiskusage_impl(PyModuleDef *module, Py_UNICODE *path)
-/*[clinic end generated code: output=054c972179b13708 input=6458133aed893c78]*/
-{
-    BOOL retval;
-    ULARGE_INTEGER _, total, free;
-
-    Py_BEGIN_ALLOW_THREADS
-    retval = GetDiskFreeSpaceExW(path, &_, &total, &free);
-    Py_END_ALLOW_THREADS
-    if (retval == 0)
-        return PyErr_SetFromWindowsErr(0);
-
-    return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
-}
-#endif /* MS_WINDOWS */
-
-
-/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
- * It maps strings representing configuration variable names to
- * integer values, allowing those functions to be called with the
- * magic names instead of polluting the module's namespace with tons of
- * rarely-used constants.  There are three separate tables that use
- * these definitions.
- *
- * This code is always included, even if none of the interfaces that
- * need it are included.  The #if hackery needed to avoid it would be
- * sufficiently pervasive that it's not worth the loss of readability.
- */
-struct constdef {
-    char *name;
-    long value;
-};
-
-static int
-conv_confname(PyObject *arg, int *valuep, struct constdef *table,
-              size_t tablesize)
-{
-    if (PyLong_Check(arg)) {
-        *valuep = PyLong_AS_LONG(arg);
-        return 1;
-    }
-    else {
-        /* look up the value in the table using a binary search */
-        size_t lo = 0;
-        size_t mid;
-        size_t hi = tablesize;
-        int cmp;
-        const char *confname;
-        if (!PyUnicode_Check(arg)) {
-            PyErr_SetString(PyExc_TypeError,
-                "configuration names must be strings or integers");
-            return 0;
-        }
-        confname = _PyUnicode_AsString(arg);
-        if (confname == NULL)
-            return 0;
-        while (lo < hi) {
-            mid = (lo + hi) / 2;
-            cmp = strcmp(confname, table[mid].name);
-            if (cmp < 0)
-                hi = mid;
-            else if (cmp > 0)
-                lo = mid + 1;
-            else {
-                *valuep = table[mid].value;
-                return 1;
-            }
-        }
-        PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
-        return 0;
-    }
-}
-
-
-#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
-static struct constdef  posix_constants_pathconf[] = {
-#ifdef _PC_ABI_AIO_XFER_MAX
-    {"PC_ABI_AIO_XFER_MAX",     _PC_ABI_AIO_XFER_MAX},
-#endif
-#ifdef _PC_ABI_ASYNC_IO
-    {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
-#endif
-#ifdef _PC_ASYNC_IO
-    {"PC_ASYNC_IO",     _PC_ASYNC_IO},
-#endif
-#ifdef _PC_CHOWN_RESTRICTED
-    {"PC_CHOWN_RESTRICTED",     _PC_CHOWN_RESTRICTED},
-#endif
-#ifdef _PC_FILESIZEBITS
-    {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
-#endif
-#ifdef _PC_LAST
-    {"PC_LAST", _PC_LAST},
-#endif
-#ifdef _PC_LINK_MAX
-    {"PC_LINK_MAX",     _PC_LINK_MAX},
-#endif
-#ifdef _PC_MAX_CANON
-    {"PC_MAX_CANON",    _PC_MAX_CANON},
-#endif
-#ifdef _PC_MAX_INPUT
-    {"PC_MAX_INPUT",    _PC_MAX_INPUT},
-#endif
-#ifdef _PC_NAME_MAX
-    {"PC_NAME_MAX",     _PC_NAME_MAX},
-#endif
-#ifdef _PC_NO_TRUNC
-    {"PC_NO_TRUNC",     _PC_NO_TRUNC},
-#endif
-#ifdef _PC_PATH_MAX
-    {"PC_PATH_MAX",     _PC_PATH_MAX},
-#endif
-#ifdef _PC_PIPE_BUF
-    {"PC_PIPE_BUF",     _PC_PIPE_BUF},
-#endif
-#ifdef _PC_PRIO_IO
-    {"PC_PRIO_IO",      _PC_PRIO_IO},
-#endif
-#ifdef _PC_SOCK_MAXBUF
-    {"PC_SOCK_MAXBUF",  _PC_SOCK_MAXBUF},
-#endif
-#ifdef _PC_SYNC_IO
-    {"PC_SYNC_IO",      _PC_SYNC_IO},
-#endif
-#ifdef _PC_VDISABLE
-    {"PC_VDISABLE",     _PC_VDISABLE},
-#endif
-#ifdef _PC_ACL_ENABLED
-    {"PC_ACL_ENABLED",  _PC_ACL_ENABLED},
-#endif
-#ifdef _PC_MIN_HOLE_SIZE
-    {"PC_MIN_HOLE_SIZE",    _PC_MIN_HOLE_SIZE},
-#endif
-#ifdef _PC_ALLOC_SIZE_MIN
-    {"PC_ALLOC_SIZE_MIN",   _PC_ALLOC_SIZE_MIN},
-#endif
-#ifdef _PC_REC_INCR_XFER_SIZE
-    {"PC_REC_INCR_XFER_SIZE",   _PC_REC_INCR_XFER_SIZE},
-#endif
-#ifdef _PC_REC_MAX_XFER_SIZE
-    {"PC_REC_MAX_XFER_SIZE",    _PC_REC_MAX_XFER_SIZE},
-#endif
-#ifdef _PC_REC_MIN_XFER_SIZE
-    {"PC_REC_MIN_XFER_SIZE",    _PC_REC_MIN_XFER_SIZE},
-#endif
-#ifdef _PC_REC_XFER_ALIGN
-    {"PC_REC_XFER_ALIGN",   _PC_REC_XFER_ALIGN},
-#endif
-#ifdef _PC_SYMLINK_MAX
-    {"PC_SYMLINK_MAX",  _PC_SYMLINK_MAX},
-#endif
-#ifdef _PC_XATTR_ENABLED
-    {"PC_XATTR_ENABLED",    _PC_XATTR_ENABLED},
-#endif
-#ifdef _PC_XATTR_EXISTS
-    {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
-#endif
-#ifdef _PC_TIMESTAMP_RESOLUTION
-    {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
-#endif
-};
-
-static int
-conv_path_confname(PyObject *arg, int *valuep)
-{
-    return conv_confname(arg, valuep, posix_constants_pathconf,
-                         sizeof(posix_constants_pathconf)
-                           / sizeof(struct constdef));
-}
-#endif
-
-
-#ifdef HAVE_FPATHCONF
-/*[clinic input]
-os.fpathconf -> long
-
-    fd: int
-    name: path_confname
-    /
-
-Return the configuration limit name for the file descriptor fd.
-
-If there is no limit, return -1.
-[clinic start generated code]*/
+#endif /* defined(MS_WINDOWS) */
+
+#if defined(HAVE_FPATHCONF)
 
 PyDoc_STRVAR(os_fpathconf__doc__,
 "fpathconf($module, fd, name, /)\n"
@@ -13925,34 +4718,9 @@
     return return_value;
 }
 
-static long
-os_fpathconf_impl(PyModuleDef *module, int fd, int name)
-/*[clinic end generated code: output=3bf04b40e0523a8c input=5942a024d3777810]*/
-{
-    long limit;
-
-    errno = 0;
-    limit = fpathconf(fd, name);
-    if (limit == -1 && errno != 0)
-        posix_error();
-
-    return limit;
-}
-#endif /* HAVE_FPATHCONF */
-
-
-#ifdef HAVE_PATHCONF
-/*[clinic input]
-os.pathconf -> long
-    path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
-    name: path_confname
-
-Return the configuration limit name for the file or directory path.
-
-If there is no limit, return -1.
-On some platforms, path may also be specified as an open file descriptor.
-  If this functionality is unavailable, using it raises an exception.
-[clinic start generated code]*/
+#endif /* defined(HAVE_FPATHCONF) */
+
+#if defined(HAVE_PATHCONF)
 
 PyDoc_STRVAR(os_pathconf__doc__,
 "pathconf($module, /, path, name)\n"
@@ -13995,202 +4763,9 @@
     return return_value;
 }
 
-static long
-os_pathconf_impl(PyModuleDef *module, path_t *path, int name)
-/*[clinic end generated code: output=1a53e125b6cf63e4 input=bc3e2a985af27e5e]*/
-{
-    long limit;
-
-    errno = 0;
-#ifdef HAVE_FPATHCONF
-    if (path->fd != -1)
-        limit = fpathconf(path->fd, name);
-    else
-#endif
-        limit = pathconf(path->narrow, name);
-    if (limit == -1 && errno != 0) {
-        if (errno == EINVAL)
-            /* could be a path or name problem */
-            posix_error();
-        else
-            path_error(path);
-    }
-
-    return limit;
-}
-#endif /* HAVE_PATHCONF */
-
-#ifdef HAVE_CONFSTR
-static struct constdef posix_constants_confstr[] = {
-#ifdef _CS_ARCHITECTURE
-    {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
-#endif
-#ifdef _CS_GNU_LIBC_VERSION
-    {"CS_GNU_LIBC_VERSION",     _CS_GNU_LIBC_VERSION},
-#endif
-#ifdef _CS_GNU_LIBPTHREAD_VERSION
-    {"CS_GNU_LIBPTHREAD_VERSION",       _CS_GNU_LIBPTHREAD_VERSION},
-#endif
-#ifdef _CS_HOSTNAME
-    {"CS_HOSTNAME",     _CS_HOSTNAME},
-#endif
-#ifdef _CS_HW_PROVIDER
-    {"CS_HW_PROVIDER",  _CS_HW_PROVIDER},
-#endif
-#ifdef _CS_HW_SERIAL
-    {"CS_HW_SERIAL",    _CS_HW_SERIAL},
-#endif
-#ifdef _CS_INITTAB_NAME
-    {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
-#endif
-#ifdef _CS_LFS64_CFLAGS
-    {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
-#endif
-#ifdef _CS_LFS64_LDFLAGS
-    {"CS_LFS64_LDFLAGS",        _CS_LFS64_LDFLAGS},
-#endif
-#ifdef _CS_LFS64_LIBS
-    {"CS_LFS64_LIBS",   _CS_LFS64_LIBS},
-#endif
-#ifdef _CS_LFS64_LINTFLAGS
-    {"CS_LFS64_LINTFLAGS",      _CS_LFS64_LINTFLAGS},
-#endif
-#ifdef _CS_LFS_CFLAGS
-    {"CS_LFS_CFLAGS",   _CS_LFS_CFLAGS},
-#endif
-#ifdef _CS_LFS_LDFLAGS
-    {"CS_LFS_LDFLAGS",  _CS_LFS_LDFLAGS},
-#endif
-#ifdef _CS_LFS_LIBS
-    {"CS_LFS_LIBS",     _CS_LFS_LIBS},
-#endif
-#ifdef _CS_LFS_LINTFLAGS
-    {"CS_LFS_LINTFLAGS",        _CS_LFS_LINTFLAGS},
-#endif
-#ifdef _CS_MACHINE
-    {"CS_MACHINE",      _CS_MACHINE},
-#endif
-#ifdef _CS_PATH
-    {"CS_PATH", _CS_PATH},
-#endif
-#ifdef _CS_RELEASE
-    {"CS_RELEASE",      _CS_RELEASE},
-#endif
-#ifdef _CS_SRPC_DOMAIN
-    {"CS_SRPC_DOMAIN",  _CS_SRPC_DOMAIN},
-#endif
-#ifdef _CS_SYSNAME
-    {"CS_SYSNAME",      _CS_SYSNAME},
-#endif
-#ifdef _CS_VERSION
-    {"CS_VERSION",      _CS_VERSION},
-#endif
-#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
-    {"CS_XBS5_ILP32_OFF32_CFLAGS",      _CS_XBS5_ILP32_OFF32_CFLAGS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
-    {"CS_XBS5_ILP32_OFF32_LDFLAGS",     _CS_XBS5_ILP32_OFF32_LDFLAGS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFF32_LIBS
-    {"CS_XBS5_ILP32_OFF32_LIBS",        _CS_XBS5_ILP32_OFF32_LIBS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
-    {"CS_XBS5_ILP32_OFF32_LINTFLAGS",   _CS_XBS5_ILP32_OFF32_LINTFLAGS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
-    {"CS_XBS5_ILP32_OFFBIG_CFLAGS",     _CS_XBS5_ILP32_OFFBIG_CFLAGS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
-    {"CS_XBS5_ILP32_OFFBIG_LDFLAGS",    _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
-    {"CS_XBS5_ILP32_OFFBIG_LIBS",       _CS_XBS5_ILP32_OFFBIG_LIBS},
-#endif
-#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
-    {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS",  _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
-#endif
-#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
-    {"CS_XBS5_LP64_OFF64_CFLAGS",       _CS_XBS5_LP64_OFF64_CFLAGS},
-#endif
-#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
-    {"CS_XBS5_LP64_OFF64_LDFLAGS",      _CS_XBS5_LP64_OFF64_LDFLAGS},
-#endif
-#ifdef _CS_XBS5_LP64_OFF64_LIBS
-    {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
-#endif
-#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
-    {"CS_XBS5_LP64_OFF64_LINTFLAGS",    _CS_XBS5_LP64_OFF64_LINTFLAGS},
-#endif
-#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
-    {"CS_XBS5_LPBIG_OFFBIG_CFLAGS",     _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
-#endif
-#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
-    {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS",    _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
-#endif
-#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
-    {"CS_XBS5_LPBIG_OFFBIG_LIBS",       _CS_XBS5_LPBIG_OFFBIG_LIBS},
-#endif
-#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
-    {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS",  _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
-#endif
-#ifdef _MIPS_CS_AVAIL_PROCESSORS
-    {"MIPS_CS_AVAIL_PROCESSORS",        _MIPS_CS_AVAIL_PROCESSORS},
-#endif
-#ifdef _MIPS_CS_BASE
-    {"MIPS_CS_BASE",    _MIPS_CS_BASE},
-#endif
-#ifdef _MIPS_CS_HOSTID
-    {"MIPS_CS_HOSTID",  _MIPS_CS_HOSTID},
-#endif
-#ifdef _MIPS_CS_HW_NAME
-    {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
-#endif
-#ifdef _MIPS_CS_NUM_PROCESSORS
-    {"MIPS_CS_NUM_PROCESSORS",  _MIPS_CS_NUM_PROCESSORS},
-#endif
-#ifdef _MIPS_CS_OSREL_MAJ
-    {"MIPS_CS_OSREL_MAJ",       _MIPS_CS_OSREL_MAJ},
-#endif
-#ifdef _MIPS_CS_OSREL_MIN
-    {"MIPS_CS_OSREL_MIN",       _MIPS_CS_OSREL_MIN},
-#endif
-#ifdef _MIPS_CS_OSREL_PATCH
-    {"MIPS_CS_OSREL_PATCH",     _MIPS_CS_OSREL_PATCH},
-#endif
-#ifdef _MIPS_CS_OS_NAME
-    {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
-#endif
-#ifdef _MIPS_CS_OS_PROVIDER
-    {"MIPS_CS_OS_PROVIDER",     _MIPS_CS_OS_PROVIDER},
-#endif
-#ifdef _MIPS_CS_PROCESSORS
-    {"MIPS_CS_PROCESSORS",      _MIPS_CS_PROCESSORS},
-#endif
-#ifdef _MIPS_CS_SERIAL
-    {"MIPS_CS_SERIAL",  _MIPS_CS_SERIAL},
-#endif
-#ifdef _MIPS_CS_VENDOR
-    {"MIPS_CS_VENDOR",  _MIPS_CS_VENDOR},
-#endif
-};
-
-static int
-conv_confstr_confname(PyObject *arg, int *valuep)
-{
-    return conv_confname(arg, valuep, posix_constants_confstr,
-                         sizeof(posix_constants_confstr)
-                           / sizeof(struct constdef));
-}
-
-
-/*[clinic input]
-os.confstr
-
-    name: confstr_confname
-    /
-
-Return a string-valued system configuration variable.
-[clinic start generated code]*/
+#endif /* defined(HAVE_PATHCONF) */
+
+#if defined(HAVE_CONFSTR)
 
 PyDoc_STRVAR(os_confstr__doc__,
 "confstr($module, name, /)\n"
@@ -14220,555 +4795,9 @@
     return return_value;
 }
 
-static PyObject *
-os_confstr_impl(PyModuleDef *module, int name)
-/*[clinic end generated code: output=3f5e8aba9f8e3174 input=18fb4d0567242e65]*/
-{
-    PyObject *result = NULL;
-    char buffer[255];
-    size_t len;
-
-    errno = 0;
-    len = confstr(name, buffer, sizeof(buffer));
-    if (len == 0) {
-        if (errno) {
-            posix_error();
-            return NULL;
-        }
-        else {
-            Py_RETURN_NONE;
-        }
-    }
-
-    if (len >= sizeof(buffer)) {
-        size_t len2;
-        char *buf = PyMem_Malloc(len);
-        if (buf == NULL)
-            return PyErr_NoMemory();
-        len2 = confstr(name, buf, len);
-        assert(len == len2);
-        result = PyUnicode_DecodeFSDefaultAndSize(buf, len-1);
-        PyMem_Free(buf);
-    }
-    else
-        result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
-    return result;
-}
-#endif /* HAVE_CONFSTR */
-
-
-#ifdef HAVE_SYSCONF
-static struct constdef posix_constants_sysconf[] = {
-#ifdef _SC_2_CHAR_TERM
-    {"SC_2_CHAR_TERM",  _SC_2_CHAR_TERM},
-#endif
-#ifdef _SC_2_C_BIND
-    {"SC_2_C_BIND",     _SC_2_C_BIND},
-#endif
-#ifdef _SC_2_C_DEV
-    {"SC_2_C_DEV",      _SC_2_C_DEV},
-#endif
-#ifdef _SC_2_C_VERSION
-    {"SC_2_C_VERSION",  _SC_2_C_VERSION},
-#endif
-#ifdef _SC_2_FORT_DEV
-    {"SC_2_FORT_DEV",   _SC_2_FORT_DEV},
-#endif
-#ifdef _SC_2_FORT_RUN
-    {"SC_2_FORT_RUN",   _SC_2_FORT_RUN},
-#endif
-#ifdef _SC_2_LOCALEDEF
-    {"SC_2_LOCALEDEF",  _SC_2_LOCALEDEF},
-#endif
-#ifdef _SC_2_SW_DEV
-    {"SC_2_SW_DEV",     _SC_2_SW_DEV},
-#endif
-#ifdef _SC_2_UPE
-    {"SC_2_UPE",        _SC_2_UPE},
-#endif
-#ifdef _SC_2_VERSION
-    {"SC_2_VERSION",    _SC_2_VERSION},
-#endif
-#ifdef _SC_ABI_ASYNCHRONOUS_IO
-    {"SC_ABI_ASYNCHRONOUS_IO",  _SC_ABI_ASYNCHRONOUS_IO},
-#endif
-#ifdef _SC_ACL
-    {"SC_ACL",  _SC_ACL},
-#endif
-#ifdef _SC_AIO_LISTIO_MAX
-    {"SC_AIO_LISTIO_MAX",       _SC_AIO_LISTIO_MAX},
-#endif
-#ifdef _SC_AIO_MAX
-    {"SC_AIO_MAX",      _SC_AIO_MAX},
-#endif
-#ifdef _SC_AIO_PRIO_DELTA_MAX
-    {"SC_AIO_PRIO_DELTA_MAX",   _SC_AIO_PRIO_DELTA_MAX},
-#endif
-#ifdef _SC_ARG_MAX
-    {"SC_ARG_MAX",      _SC_ARG_MAX},
-#endif
-#ifdef _SC_ASYNCHRONOUS_IO
-    {"SC_ASYNCHRONOUS_IO",      _SC_ASYNCHRONOUS_IO},
-#endif
-#ifdef _SC_ATEXIT_MAX
-    {"SC_ATEXIT_MAX",   _SC_ATEXIT_MAX},
-#endif
-#ifdef _SC_AUDIT
-    {"SC_AUDIT",        _SC_AUDIT},
-#endif
-#ifdef _SC_AVPHYS_PAGES
-    {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
-#endif
-#ifdef _SC_BC_BASE_MAX
-    {"SC_BC_BASE_MAX",  _SC_BC_BASE_MAX},
-#endif
-#ifdef _SC_BC_DIM_MAX
-    {"SC_BC_DIM_MAX",   _SC_BC_DIM_MAX},
-#endif
-#ifdef _SC_BC_SCALE_MAX
-    {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
-#endif
-#ifdef _SC_BC_STRING_MAX
-    {"SC_BC_STRING_MAX",        _SC_BC_STRING_MAX},
-#endif
-#ifdef _SC_CAP
-    {"SC_CAP",  _SC_CAP},
-#endif
-#ifdef _SC_CHARCLASS_NAME_MAX
-    {"SC_CHARCLASS_NAME_MAX",   _SC_CHARCLASS_NAME_MAX},
-#endif
-#ifdef _SC_CHAR_BIT
-    {"SC_CHAR_BIT",     _SC_CHAR_BIT},
-#endif
-#ifdef _SC_CHAR_MAX
-    {"SC_CHAR_MAX",     _SC_CHAR_MAX},
-#endif
-#ifdef _SC_CHAR_MIN
-    {"SC_CHAR_MIN",     _SC_CHAR_MIN},
-#endif
-#ifdef _SC_CHILD_MAX
-    {"SC_CHILD_MAX",    _SC_CHILD_MAX},
-#endif
-#ifdef _SC_CLK_TCK
-    {"SC_CLK_TCK",      _SC_CLK_TCK},
-#endif
-#ifdef _SC_COHER_BLKSZ
-    {"SC_COHER_BLKSZ",  _SC_COHER_BLKSZ},
-#endif
-#ifdef _SC_COLL_WEIGHTS_MAX
-    {"SC_COLL_WEIGHTS_MAX",     _SC_COLL_WEIGHTS_MAX},
-#endif
-#ifdef _SC_DCACHE_ASSOC
-    {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
-#endif
-#ifdef _SC_DCACHE_BLKSZ
-    {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
-#endif
-#ifdef _SC_DCACHE_LINESZ
-    {"SC_DCACHE_LINESZ",        _SC_DCACHE_LINESZ},
-#endif
-#ifdef _SC_DCACHE_SZ
-    {"SC_DCACHE_SZ",    _SC_DCACHE_SZ},
-#endif
-#ifdef _SC_DCACHE_TBLKSZ
-    {"SC_DCACHE_TBLKSZ",        _SC_DCACHE_TBLKSZ},
-#endif
-#ifdef _SC_DELAYTIMER_MAX
-    {"SC_DELAYTIMER_MAX",       _SC_DELAYTIMER_MAX},
-#endif
-#ifdef _SC_EQUIV_CLASS_MAX
-    {"SC_EQUIV_CLASS_MAX",      _SC_EQUIV_CLASS_MAX},
-#endif
-#ifdef _SC_EXPR_NEST_MAX
-    {"SC_EXPR_NEST_MAX",        _SC_EXPR_NEST_MAX},
-#endif
-#ifdef _SC_FSYNC
-    {"SC_FSYNC",        _SC_FSYNC},
-#endif
-#ifdef _SC_GETGR_R_SIZE_MAX
-    {"SC_GETGR_R_SIZE_MAX",     _SC_GETGR_R_SIZE_MAX},
-#endif
-#ifdef _SC_GETPW_R_SIZE_MAX
-    {"SC_GETPW_R_SIZE_MAX",     _SC_GETPW_R_SIZE_MAX},
-#endif
-#ifdef _SC_ICACHE_ASSOC
-    {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
-#endif
-#ifdef _SC_ICACHE_BLKSZ
-    {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
-#endif
-#ifdef _SC_ICACHE_LINESZ
-    {"SC_ICACHE_LINESZ",        _SC_ICACHE_LINESZ},
-#endif
-#ifdef _SC_ICACHE_SZ
-    {"SC_ICACHE_SZ",    _SC_ICACHE_SZ},
-#endif
-#ifdef _SC_INF
-    {"SC_INF",  _SC_INF},
-#endif
-#ifdef _SC_INT_MAX
-    {"SC_INT_MAX",      _SC_INT_MAX},
-#endif
-#ifdef _SC_INT_MIN
-    {"SC_INT_MIN",      _SC_INT_MIN},
-#endif
-#ifdef _SC_IOV_MAX
-    {"SC_IOV_MAX",      _SC_IOV_MAX},
-#endif
-#ifdef _SC_IP_SECOPTS
-    {"SC_IP_SECOPTS",   _SC_IP_SECOPTS},
-#endif
-#ifdef _SC_JOB_CONTROL
-    {"SC_JOB_CONTROL",  _SC_JOB_CONTROL},
-#endif
-#ifdef _SC_KERN_POINTERS
-    {"SC_KERN_POINTERS",        _SC_KERN_POINTERS},
-#endif
-#ifdef _SC_KERN_SIM
-    {"SC_KERN_SIM",     _SC_KERN_SIM},
-#endif
-#ifdef _SC_LINE_MAX
-    {"SC_LINE_MAX",     _SC_LINE_MAX},
-#endif
-#ifdef _SC_LOGIN_NAME_MAX
-    {"SC_LOGIN_NAME_MAX",       _SC_LOGIN_NAME_MAX},
-#endif
-#ifdef _SC_LOGNAME_MAX
-    {"SC_LOGNAME_MAX",  _SC_LOGNAME_MAX},
-#endif
-#ifdef _SC_LONG_BIT
-    {"SC_LONG_BIT",     _SC_LONG_BIT},
-#endif
-#ifdef _SC_MAC
-    {"SC_MAC",  _SC_MAC},
-#endif
-#ifdef _SC_MAPPED_FILES
-    {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
-#endif
-#ifdef _SC_MAXPID
-    {"SC_MAXPID",       _SC_MAXPID},
-#endif
-#ifdef _SC_MB_LEN_MAX
-    {"SC_MB_LEN_MAX",   _SC_MB_LEN_MAX},
-#endif
-#ifdef _SC_MEMLOCK
-    {"SC_MEMLOCK",      _SC_MEMLOCK},
-#endif
-#ifdef _SC_MEMLOCK_RANGE
-    {"SC_MEMLOCK_RANGE",        _SC_MEMLOCK_RANGE},
-#endif
-#ifdef _SC_MEMORY_PROTECTION
-    {"SC_MEMORY_PROTECTION",    _SC_MEMORY_PROTECTION},
-#endif
-#ifdef _SC_MESSAGE_PASSING
-    {"SC_MESSAGE_PASSING",      _SC_MESSAGE_PASSING},
-#endif
-#ifdef _SC_MMAP_FIXED_ALIGNMENT
-    {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
-#endif
-#ifdef _SC_MQ_OPEN_MAX
-    {"SC_MQ_OPEN_MAX",  _SC_MQ_OPEN_MAX},
-#endif
-#ifdef _SC_MQ_PRIO_MAX
-    {"SC_MQ_PRIO_MAX",  _SC_MQ_PRIO_MAX},
-#endif
-#ifdef _SC_NACLS_MAX
-    {"SC_NACLS_MAX",    _SC_NACLS_MAX},
-#endif
-#ifdef _SC_NGROUPS_MAX
-    {"SC_NGROUPS_MAX",  _SC_NGROUPS_MAX},
-#endif
-#ifdef _SC_NL_ARGMAX
-    {"SC_NL_ARGMAX",    _SC_NL_ARGMAX},
-#endif
-#ifdef _SC_NL_LANGMAX
-    {"SC_NL_LANGMAX",   _SC_NL_LANGMAX},
-#endif
-#ifdef _SC_NL_MSGMAX
-    {"SC_NL_MSGMAX",    _SC_NL_MSGMAX},
-#endif
-#ifdef _SC_NL_NMAX
-    {"SC_NL_NMAX",      _SC_NL_NMAX},
-#endif
-#ifdef _SC_NL_SETMAX
-    {"SC_NL_SETMAX",    _SC_NL_SETMAX},
-#endif
-#ifdef _SC_NL_TEXTMAX
-    {"SC_NL_TEXTMAX",   _SC_NL_TEXTMAX},
-#endif
-#ifdef _SC_NPROCESSORS_CONF
-    {"SC_NPROCESSORS_CONF",     _SC_NPROCESSORS_CONF},
-#endif
-#ifdef _SC_NPROCESSORS_ONLN
-    {"SC_NPROCESSORS_ONLN",     _SC_NPROCESSORS_ONLN},
-#endif
-#ifdef _SC_NPROC_CONF
-    {"SC_NPROC_CONF",   _SC_NPROC_CONF},
-#endif
-#ifdef _SC_NPROC_ONLN
-    {"SC_NPROC_ONLN",   _SC_NPROC_ONLN},
-#endif
-#ifdef _SC_NZERO
-    {"SC_NZERO",        _SC_NZERO},
-#endif
-#ifdef _SC_OPEN_MAX
-    {"SC_OPEN_MAX",     _SC_OPEN_MAX},
-#endif
-#ifdef _SC_PAGESIZE
-    {"SC_PAGESIZE",     _SC_PAGESIZE},
-#endif
-#ifdef _SC_PAGE_SIZE
-    {"SC_PAGE_SIZE",    _SC_PAGE_SIZE},
-#endif
-#ifdef _SC_PASS_MAX
-    {"SC_PASS_MAX",     _SC_PASS_MAX},
-#endif
-#ifdef _SC_PHYS_PAGES
-    {"SC_PHYS_PAGES",   _SC_PHYS_PAGES},
-#endif
-#ifdef _SC_PII
-    {"SC_PII",  _SC_PII},
-#endif
-#ifdef _SC_PII_INTERNET
-    {"SC_PII_INTERNET", _SC_PII_INTERNET},
-#endif
-#ifdef _SC_PII_INTERNET_DGRAM
-    {"SC_PII_INTERNET_DGRAM",   _SC_PII_INTERNET_DGRAM},
-#endif
-#ifdef _SC_PII_INTERNET_STREAM
-    {"SC_PII_INTERNET_STREAM",  _SC_PII_INTERNET_STREAM},
-#endif
-#ifdef _SC_PII_OSI
-    {"SC_PII_OSI",      _SC_PII_OSI},
-#endif
-#ifdef _SC_PII_OSI_CLTS
-    {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
-#endif
-#ifdef _SC_PII_OSI_COTS
-    {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
-#endif
-#ifdef _SC_PII_OSI_M
-    {"SC_PII_OSI_M",    _SC_PII_OSI_M},
-#endif
-#ifdef _SC_PII_SOCKET
-    {"SC_PII_SOCKET",   _SC_PII_SOCKET},
-#endif
-#ifdef _SC_PII_XTI
-    {"SC_PII_XTI",      _SC_PII_XTI},
-#endif
-#ifdef _SC_POLL
-    {"SC_POLL", _SC_POLL},
-#endif
-#ifdef _SC_PRIORITIZED_IO
-    {"SC_PRIORITIZED_IO",       _SC_PRIORITIZED_IO},
-#endif
-#ifdef _SC_PRIORITY_SCHEDULING
-    {"SC_PRIORITY_SCHEDULING",  _SC_PRIORITY_SCHEDULING},
-#endif
-#ifdef _SC_REALTIME_SIGNALS
-    {"SC_REALTIME_SIGNALS",     _SC_REALTIME_SIGNALS},
-#endif
-#ifdef _SC_RE_DUP_MAX
-    {"SC_RE_DUP_MAX",   _SC_RE_DUP_MAX},
-#endif
-#ifdef _SC_RTSIG_MAX
-    {"SC_RTSIG_MAX",    _SC_RTSIG_MAX},
-#endif
-#ifdef _SC_SAVED_IDS
-    {"SC_SAVED_IDS",    _SC_SAVED_IDS},
-#endif
-#ifdef _SC_SCHAR_MAX
-    {"SC_SCHAR_MAX",    _SC_SCHAR_MAX},
-#endif
-#ifdef _SC_SCHAR_MIN
-    {"SC_SCHAR_MIN",    _SC_SCHAR_MIN},
-#endif
-#ifdef _SC_SELECT
-    {"SC_SELECT",       _SC_SELECT},
-#endif
-#ifdef _SC_SEMAPHORES
-    {"SC_SEMAPHORES",   _SC_SEMAPHORES},
-#endif
-#ifdef _SC_SEM_NSEMS_MAX
-    {"SC_SEM_NSEMS_MAX",        _SC_SEM_NSEMS_MAX},
-#endif
-#ifdef _SC_SEM_VALUE_MAX
-    {"SC_SEM_VALUE_MAX",        _SC_SEM_VALUE_MAX},
-#endif
-#ifdef _SC_SHARED_MEMORY_OBJECTS
-    {"SC_SHARED_MEMORY_OBJECTS",        _SC_SHARED_MEMORY_OBJECTS},
-#endif
-#ifdef _SC_SHRT_MAX
-    {"SC_SHRT_MAX",     _SC_SHRT_MAX},
-#endif
-#ifdef _SC_SHRT_MIN
-    {"SC_SHRT_MIN",     _SC_SHRT_MIN},
-#endif
-#ifdef _SC_SIGQUEUE_MAX
-    {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
-#endif
-#ifdef _SC_SIGRT_MAX
-    {"SC_SIGRT_MAX",    _SC_SIGRT_MAX},
-#endif
-#ifdef _SC_SIGRT_MIN
-    {"SC_SIGRT_MIN",    _SC_SIGRT_MIN},
-#endif
-#ifdef _SC_SOFTPOWER
-    {"SC_SOFTPOWER",    _SC_SOFTPOWER},
-#endif
-#ifdef _SC_SPLIT_CACHE
-    {"SC_SPLIT_CACHE",  _SC_SPLIT_CACHE},
-#endif
-#ifdef _SC_SSIZE_MAX
-    {"SC_SSIZE_MAX",    _SC_SSIZE_MAX},
-#endif
-#ifdef _SC_STACK_PROT
-    {"SC_STACK_PROT",   _SC_STACK_PROT},
-#endif
-#ifdef _SC_STREAM_MAX
-    {"SC_STREAM_MAX",   _SC_STREAM_MAX},
-#endif
-#ifdef _SC_SYNCHRONIZED_IO
-    {"SC_SYNCHRONIZED_IO",      _SC_SYNCHRONIZED_IO},
-#endif
-#ifdef _SC_THREADS
-    {"SC_THREADS",      _SC_THREADS},
-#endif
-#ifdef _SC_THREAD_ATTR_STACKADDR
-    {"SC_THREAD_ATTR_STACKADDR",        _SC_THREAD_ATTR_STACKADDR},
-#endif
-#ifdef _SC_THREAD_ATTR_STACKSIZE
-    {"SC_THREAD_ATTR_STACKSIZE",        _SC_THREAD_ATTR_STACKSIZE},
-#endif
-#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
-    {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
-#endif
-#ifdef _SC_THREAD_KEYS_MAX
-    {"SC_THREAD_KEYS_MAX",      _SC_THREAD_KEYS_MAX},
-#endif
-#ifdef _SC_THREAD_PRIORITY_SCHEDULING
-    {"SC_THREAD_PRIORITY_SCHEDULING",   _SC_THREAD_PRIORITY_SCHEDULING},
-#endif
-#ifdef _SC_THREAD_PRIO_INHERIT
-    {"SC_THREAD_PRIO_INHERIT",  _SC_THREAD_PRIO_INHERIT},
-#endif
-#ifdef _SC_THREAD_PRIO_PROTECT
-    {"SC_THREAD_PRIO_PROTECT",  _SC_THREAD_PRIO_PROTECT},
-#endif
-#ifdef _SC_THREAD_PROCESS_SHARED
-    {"SC_THREAD_PROCESS_SHARED",        _SC_THREAD_PROCESS_SHARED},
-#endif
-#ifdef _SC_THREAD_SAFE_FUNCTIONS
-    {"SC_THREAD_SAFE_FUNCTIONS",        _SC_THREAD_SAFE_FUNCTIONS},
-#endif
-#ifdef _SC_THREAD_STACK_MIN
-    {"SC_THREAD_STACK_MIN",     _SC_THREAD_STACK_MIN},
-#endif
-#ifdef _SC_THREAD_THREADS_MAX
-    {"SC_THREAD_THREADS_MAX",   _SC_THREAD_THREADS_MAX},
-#endif
-#ifdef _SC_TIMERS
-    {"SC_TIMERS",       _SC_TIMERS},
-#endif
-#ifdef _SC_TIMER_MAX
-    {"SC_TIMER_MAX",    _SC_TIMER_MAX},
-#endif
-#ifdef _SC_TTY_NAME_MAX
-    {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
-#endif
-#ifdef _SC_TZNAME_MAX
-    {"SC_TZNAME_MAX",   _SC_TZNAME_MAX},
-#endif
-#ifdef _SC_T_IOV_MAX
-    {"SC_T_IOV_MAX",    _SC_T_IOV_MAX},
-#endif
-#ifdef _SC_UCHAR_MAX
-    {"SC_UCHAR_MAX",    _SC_UCHAR_MAX},
-#endif
-#ifdef _SC_UINT_MAX
-    {"SC_UINT_MAX",     _SC_UINT_MAX},
-#endif
-#ifdef _SC_UIO_MAXIOV
-    {"SC_UIO_MAXIOV",   _SC_UIO_MAXIOV},
-#endif
-#ifdef _SC_ULONG_MAX
-    {"SC_ULONG_MAX",    _SC_ULONG_MAX},
-#endif
-#ifdef _SC_USHRT_MAX
-    {"SC_USHRT_MAX",    _SC_USHRT_MAX},
-#endif
-#ifdef _SC_VERSION
-    {"SC_VERSION",      _SC_VERSION},
-#endif
-#ifdef _SC_WORD_BIT
-    {"SC_WORD_BIT",     _SC_WORD_BIT},
-#endif
-#ifdef _SC_XBS5_ILP32_OFF32
-    {"SC_XBS5_ILP32_OFF32",     _SC_XBS5_ILP32_OFF32},
-#endif
-#ifdef _SC_XBS5_ILP32_OFFBIG
-    {"SC_XBS5_ILP32_OFFBIG",    _SC_XBS5_ILP32_OFFBIG},
-#endif
-#ifdef _SC_XBS5_LP64_OFF64
-    {"SC_XBS5_LP64_OFF64",      _SC_XBS5_LP64_OFF64},
-#endif
-#ifdef _SC_XBS5_LPBIG_OFFBIG
-    {"SC_XBS5_LPBIG_OFFBIG",    _SC_XBS5_LPBIG_OFFBIG},
-#endif
-#ifdef _SC_XOPEN_CRYPT
-    {"SC_XOPEN_CRYPT",  _SC_XOPEN_CRYPT},
-#endif
-#ifdef _SC_XOPEN_ENH_I18N
-    {"SC_XOPEN_ENH_I18N",       _SC_XOPEN_ENH_I18N},
-#endif
-#ifdef _SC_XOPEN_LEGACY
-    {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
-#endif
-#ifdef _SC_XOPEN_REALTIME
-    {"SC_XOPEN_REALTIME",       _SC_XOPEN_REALTIME},
-#endif
-#ifdef _SC_XOPEN_REALTIME_THREADS
-    {"SC_XOPEN_REALTIME_THREADS",       _SC_XOPEN_REALTIME_THREADS},
-#endif
-#ifdef _SC_XOPEN_SHM
-    {"SC_XOPEN_SHM",    _SC_XOPEN_SHM},
-#endif
-#ifdef _SC_XOPEN_UNIX
-    {"SC_XOPEN_UNIX",   _SC_XOPEN_UNIX},
-#endif
-#ifdef _SC_XOPEN_VERSION
-    {"SC_XOPEN_VERSION",        _SC_XOPEN_VERSION},
-#endif
-#ifdef _SC_XOPEN_XCU_VERSION
-    {"SC_XOPEN_XCU_VERSION",    _SC_XOPEN_XCU_VERSION},
-#endif
-#ifdef _SC_XOPEN_XPG2
-    {"SC_XOPEN_XPG2",   _SC_XOPEN_XPG2},
-#endif
-#ifdef _SC_XOPEN_XPG3
-    {"SC_XOPEN_XPG3",   _SC_XOPEN_XPG3},
-#endif
-#ifdef _SC_XOPEN_XPG4
-    {"SC_XOPEN_XPG4",   _SC_XOPEN_XPG4},
-#endif
-};
-
-static int
-conv_sysconf_confname(PyObject *arg, int *valuep)
-{
-    return conv_confname(arg, valuep, posix_constants_sysconf,
-                         sizeof(posix_constants_sysconf)
-                           / sizeof(struct constdef));
-}
-
-
-/*[clinic input]
-os.sysconf -> long
-    name: sysconf_confname
-    /
-
-Return an integer-valued system configuration variable.
-[clinic start generated code]*/
+#endif /* defined(HAVE_CONFSTR) */
+
+#if defined(HAVE_SYSCONF)
 
 PyDoc_STRVAR(os_sysconf__doc__,
 "sysconf($module, name, /)\n"
@@ -14802,103 +4831,7 @@
     return return_value;
 }
 
-static long
-os_sysconf_impl(PyModuleDef *module, int name)
-/*[clinic end generated code: output=7b06dfdc472431e4 input=279e3430a33f29e4]*/
-{
-    long value;
-
-    errno = 0;
-    value = sysconf(name);
-    if (value == -1 && errno != 0)
-        posix_error();
-    return value;
-}
-#endif /* HAVE_SYSCONF */
-
-
-/* This code is used to ensure that the tables of configuration value names
- * are in sorted order as required by conv_confname(), and also to build
- * the exported dictionaries that are used to publish information about the
- * names available on the host platform.
- *
- * Sorting the table at runtime ensures that the table is properly ordered
- * when used, even for platforms we're not able to test on.  It also makes
- * it easier to add additional entries to the tables.
- */
-
-static int
-cmp_constdefs(const void *v1,  const void *v2)
-{
-    const struct constdef *c1 =
-    (const struct constdef *) v1;
-    const struct constdef *c2 =
-    (const struct constdef *) v2;
-
-    return strcmp(c1->name, c2->name);
-}
-
-static int
-setup_confname_table(struct constdef *table, size_t tablesize,
-                     char *tablename, PyObject *module)
-{
-    PyObject *d = NULL;
-    size_t i;
-
-    qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
-    d = PyDict_New();
-    if (d == NULL)
-        return -1;
-
-    for (i=0; i < tablesize; ++i) {
-        PyObject *o = PyLong_FromLong(table[i].value);
-        if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
-            Py_XDECREF(o);
-            Py_DECREF(d);
-            return -1;
-        }
-        Py_DECREF(o);
-    }
-    return PyModule_AddObject(module, tablename, d);
-}
-
-/* Return -1 on failure, 0 on success. */
-static int
-setup_confname_tables(PyObject *module)
-{
-#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
-    if (setup_confname_table(posix_constants_pathconf,
-                             sizeof(posix_constants_pathconf)
-                               / sizeof(struct constdef),
-                             "pathconf_names", module))
-        return -1;
-#endif
-#ifdef HAVE_CONFSTR
-    if (setup_confname_table(posix_constants_confstr,
-                             sizeof(posix_constants_confstr)
-                               / sizeof(struct constdef),
-                             "confstr_names", module))
-        return -1;
-#endif
-#ifdef HAVE_SYSCONF
-    if (setup_confname_table(posix_constants_sysconf,
-                             sizeof(posix_constants_sysconf)
-                               / sizeof(struct constdef),
-                             "sysconf_names", module))
-        return -1;
-#endif
-    return 0;
-}
-
-
-/*[clinic input]
-os.abort
-
-Abort the interpreter immediately.
-
-This function 'dumps core' or otherwise fails in the hardest way possible
-on the hosting operating system.  This function never returns.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SYSCONF) */
 
 PyDoc_STRVAR(os_abort__doc__,
 "abort($module, /)\n"
@@ -14921,163 +4854,7 @@
     return os_abort_impl(module);
 }
 
-static PyObject *
-os_abort_impl(PyModuleDef *module)
-/*[clinic end generated code: output=cded2cc8c5453d3a input=cf2c7d98bc504047]*/
-{
-    abort();
-    /*NOTREACHED*/
-    Py_FatalError("abort() called from Python code didn't abort!");
-    return NULL;
-}
-
-#ifdef MS_WINDOWS
-/* AC 3.5: change to path_t? but that might change exceptions */
-PyDoc_STRVAR(win32_startfile__doc__,
-"startfile(filepath [, operation])\n\
-\n\
-Start a file with its associated application.\n\
-\n\
-When \"operation\" is not specified or \"open\", this acts like\n\
-double-clicking the file in Explorer, or giving the file name as an\n\
-argument to the DOS \"start\" command: the file is opened with whatever\n\
-application (if any) its extension is associated.\n\
-When another \"operation\" is given, it specifies what should be done with\n\
-the file.  A typical operation is \"print\".\n\
-\n\
-startfile returns as soon as the associated application is launched.\n\
-There is no option to wait for the application to close, and no way\n\
-to retrieve the application's exit status.\n\
-\n\
-The filepath is relative to the current directory.  If you want to use\n\
-an absolute path, make sure the first character is not a slash (\"/\");\n\
-the underlying Win32 ShellExecute function doesn't work if it is.");
-
-/* Grab ShellExecute dynamically from shell32 */
-static int has_ShellExecute = -1;
-static HINSTANCE (CALLBACK *Py_ShellExecuteA)(HWND, LPCSTR, LPCSTR, LPCSTR,
-                                              LPCSTR, INT);
-static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
-                                              LPCWSTR, INT);
-static int
-check_ShellExecute()
-{
-    HINSTANCE hShell32;
-
-    /* only recheck */
-    if (-1 == has_ShellExecute) {
-        Py_BEGIN_ALLOW_THREADS
-        hShell32 = LoadLibraryW(L"SHELL32");
-        Py_END_ALLOW_THREADS
-        if (hShell32) {
-            *(FARPROC*)&Py_ShellExecuteA = GetProcAddress(hShell32,
-                                            "ShellExecuteA");
-            *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
-                                            "ShellExecuteW");
-            has_ShellExecute = Py_ShellExecuteA &&
-                               Py_ShellExecuteW;
-        } else {
-            has_ShellExecute = 0;
-        }
-    }
-    return has_ShellExecute;
-}
-
-
-static PyObject *
-win32_startfile(PyObject *self, PyObject *args)
-{
-    PyObject *ofilepath;
-    char *filepath;
-    char *operation = NULL;
-    wchar_t *wpath, *woperation;
-    HINSTANCE rc;
-
-    PyObject *unipath, *uoperation = NULL;
-
-    if(!check_ShellExecute()) {
-        /* If the OS doesn't have ShellExecute, return a
-           NotImplementedError. */
-        return PyErr_Format(PyExc_NotImplementedError,
-            "startfile not available on this platform");
-    }
-
-    if (!PyArg_ParseTuple(args, "U|s:startfile",
-                          &unipath, &operation)) {
-        PyErr_Clear();
-        goto normal;
-    }
-
-    if (operation) {
-        uoperation = PyUnicode_DecodeASCII(operation,
-                                           strlen(operation), NULL);
-        if (!uoperation) {
-            PyErr_Clear();
-            operation = NULL;
-            goto normal;
-        }
-    }
-
-    wpath = PyUnicode_AsUnicode(unipath);
-    if (wpath == NULL)
-        goto normal;
-    if (uoperation) {
-        woperation = PyUnicode_AsUnicode(uoperation);
-        if (woperation == NULL)
-            goto normal;
-    }
-    else
-        woperation = NULL;
-
-    Py_BEGIN_ALLOW_THREADS
-    rc = Py_ShellExecuteW((HWND)0, woperation, wpath,
-                          NULL, NULL, SW_SHOWNORMAL);
-    Py_END_ALLOW_THREADS
-
-    Py_XDECREF(uoperation);
-    if (rc <= (HINSTANCE)32) {
-        win32_error_object("startfile", unipath);
-        return NULL;
-    }
-    Py_INCREF(Py_None);
-    return Py_None;
-
-normal:
-    if (!PyArg_ParseTuple(args, "O&|s:startfile",
-                          PyUnicode_FSConverter, &ofilepath,
-                          &operation))
-        return NULL;
-    if (win32_warn_bytes_api()) {
-        Py_DECREF(ofilepath);
-        return NULL;
-    }
-    filepath = PyBytes_AsString(ofilepath);
-    Py_BEGIN_ALLOW_THREADS
-    rc = Py_ShellExecuteA((HWND)0, operation, filepath,
-                          NULL, NULL, SW_SHOWNORMAL);
-    Py_END_ALLOW_THREADS
-    if (rc <= (HINSTANCE)32) {
-        PyObject *errval = win32_error("startfile", filepath);
-        Py_DECREF(ofilepath);
-        return errval;
-    }
-    Py_DECREF(ofilepath);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-#endif /* MS_WINDOWS */
-
-
-#ifdef HAVE_GETLOADAVG
-/*[clinic input]
-os.getloadavg
-
-Return average recent system load information.
-
-Return the number of processes in the system run queue averaged over
-the last 1, 5, and 15 minutes as a tuple of three floats.
-Raises OSError if the load average was unobtainable.
-[clinic start generated code]*/
+#if defined(HAVE_GETLOADAVG)
 
 PyDoc_STRVAR(os_getloadavg__doc__,
 "getloadavg($module, /)\n"
@@ -15101,29 +4878,7 @@
     return os_getloadavg_impl(module);
 }
 
-static PyObject *
-os_getloadavg_impl(PyModuleDef *module)
-/*[clinic end generated code: output=67593a92457d55af input=3d6d826b76d8a34e]*/
-{
-    double loadavg[3];
-    if (getloadavg(loadavg, 3)!=3) {
-        PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
-        return NULL;
-    } else
-        return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
-}
-#endif /* HAVE_GETLOADAVG */
-
-
-/*[clinic input]
-os.device_encoding
-    fd: int
-
-Return a string describing the encoding of a terminal's file descriptor.
-
-The file descriptor must be attached to a terminal.
-If the device is not a terminal, return None.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETLOADAVG) */
 
 PyDoc_STRVAR(os_device_encoding__doc__,
 "device_encoding($module, /, fd)\n"
@@ -15157,25 +4912,7 @@
     return return_value;
 }
 
-static PyObject *
-os_device_encoding_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=e9f8274d42f5cce3 input=9e1d4a42b66df312]*/
-{
-    return _Py_device_encoding(fd);
-}
-
-
-#ifdef HAVE_SETRESUID
-/*[clinic input]
-os.setresuid
-
-    ruid: uid_t
-    euid: uid_t
-    suid: uid_t
-    /
-
-Set the current process's real, effective, and saved user ids.
-[clinic start generated code]*/
+#if defined(HAVE_SETRESUID)
 
 PyDoc_STRVAR(os_setresuid__doc__,
 "setresuid($module, ruid, euid, suid, /)\n"
@@ -15207,28 +4944,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setresuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid, uid_t suid)
-/*[clinic end generated code: output=2e3457cfe7cd1f94 input=9e33cb79a82792f3]*/
-{
-    if (setresuid(ruid, euid, suid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETRESUID */
-
-
-#ifdef HAVE_SETRESGID
-/*[clinic input]
-os.setresgid
-
-    rgid: gid_t
-    egid: gid_t
-    sgid: gid_t
-    /
-
-Set the current process's real, effective, and saved group ids.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETRESUID) */
+
+#if defined(HAVE_SETRESGID)
 
 PyDoc_STRVAR(os_setresgid__doc__,
 "setresgid($module, rgid, egid, sgid, /)\n"
@@ -15260,23 +4978,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setresgid_impl(PyModuleDef *module, gid_t rgid, gid_t egid, gid_t sgid)
-/*[clinic end generated code: output=8a7ee6c1f2482362 input=33e9e0785ef426b1]*/
-{
-    if (setresgid(rgid, egid, sgid) < 0)
-        return posix_error();
-    Py_RETURN_NONE;
-}
-#endif /* HAVE_SETRESGID */
-
-
-#ifdef HAVE_GETRESUID
-/*[clinic input]
-os.getresuid
-
-Return a tuple of the current process's real, effective, and saved user ids.
-[clinic start generated code]*/
+#endif /* defined(HAVE_SETRESGID) */
+
+#if defined(HAVE_GETRESUID)
 
 PyDoc_STRVAR(os_getresuid__doc__,
 "getresuid($module, /)\n"
@@ -15296,26 +5000,9 @@
     return os_getresuid_impl(module);
 }
 
-static PyObject *
-os_getresuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d0786686a6ef1320 input=41ccfa8e1f6517ad]*/
-{
-    uid_t ruid, euid, suid;
-    if (getresuid(&ruid, &euid, &suid) < 0)
-        return posix_error();
-    return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
-                                  _PyLong_FromUid(euid),
-                                  _PyLong_FromUid(suid));
-}
-#endif /* HAVE_GETRESUID */
-
-
-#ifdef HAVE_GETRESGID
-/*[clinic input]
-os.getresgid
-
-Return a tuple of the current process's real, effective, and saved group ids.
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETRESUID) */
+
+#if defined(HAVE_GETRESGID)
 
 PyDoc_STRVAR(os_getresgid__doc__,
 "getresgid($module, /)\n"
@@ -15335,37 +5022,9 @@
     return os_getresgid_impl(module);
 }
 
-static PyObject *
-os_getresgid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=05249ac795fa759f input=517e68db9ca32df6]*/
-{
-    gid_t rgid, egid, sgid;
-    if (getresgid(&rgid, &egid, &sgid) < 0)
-        return posix_error();
-    return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
-                                  _PyLong_FromGid(egid),
-                                  _PyLong_FromGid(sgid));
-}
-#endif /* HAVE_GETRESGID */
-
-
-#ifdef USE_XATTRS
-/*[clinic input]
-os.getxattr
-
-    path: path_t(allow_fd=True)
-    attribute: path_t
-    *
-    follow_symlinks: bool = True
-
-Return the value of extended attribute attribute on path.
-
-path may be either a string or an open file descriptor.
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, getxattr will examine the symbolic link itself instead of the file
-  the link points to.
-
-[clinic start generated code]*/
+#endif /* defined(HAVE_GETRESGID) */
+
+#if defined(USE_XATTRS)
 
 PyDoc_STRVAR(os_getxattr__doc__,
 "getxattr($module, /, path, attribute, *, follow_symlinks=True)\n"
@@ -15408,76 +5067,9 @@
     return return_value;
 }
 
-static PyObject *
-os_getxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, int follow_symlinks)
-/*[clinic end generated code: output=bbc9454fe2b9ea86 input=8c8ea3bab78d89c2]*/
-{
-    Py_ssize_t i;
-    PyObject *buffer = NULL;
-
-    if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
-        return NULL;
-
-    for (i = 0; ; i++) {
-        void *ptr;
-        ssize_t result;
-        static Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
-        Py_ssize_t buffer_size = buffer_sizes[i];
-        if (!buffer_size) {
-            path_error(path);
-            return NULL;
-        }
-        buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
-        if (!buffer)
-            return NULL;
-        ptr = PyBytes_AS_STRING(buffer);
-
-        Py_BEGIN_ALLOW_THREADS;
-        if (path->fd >= 0)
-            result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
-        else if (follow_symlinks)
-            result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
-        else
-            result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
-        Py_END_ALLOW_THREADS;
-
-        if (result < 0) {
-            Py_DECREF(buffer);
-            if (errno == ERANGE)
-                continue;
-            path_error(path);
-            return NULL;
-        }
-
-        if (result != buffer_size) {
-            /* Can only shrink. */
-            _PyBytes_Resize(&buffer, result);
-        }
-        break;
-    }
-
-    return buffer;
-}
-
-
-/*[clinic input]
-os.setxattr
-
-    path: path_t(allow_fd=True)
-    attribute: path_t
-    value: Py_buffer
-    flags: int = 0
-    *
-    follow_symlinks: bool = True
-
-Set extended attribute attribute on path to value.
-
-path may be either a string or an open file descriptor.
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, setxattr will modify the symbolic link itself instead of the file
-  the link points to.
-
-[clinic start generated code]*/
+#endif /* defined(USE_XATTRS) */
+
+#if defined(USE_XATTRS)
 
 PyDoc_STRVAR(os_setxattr__doc__,
 "setxattr($module, /, path, attribute, value, flags=0, *,\n"
@@ -15526,52 +5118,9 @@
     return return_value;
 }
 
-static PyObject *
-os_setxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, Py_buffer *value, int flags, int follow_symlinks)
-/*[clinic end generated code: output=2ff845d8e024b218 input=f0d26833992015c2]*/
-{
-    ssize_t result;
-
-    if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
-        return NULL;
-
-    Py_BEGIN_ALLOW_THREADS;
-    if (path->fd > -1)
-        result = fsetxattr(path->fd, attribute->narrow,
-                           value->buf, value->len, flags);
-    else if (follow_symlinks)
-        result = setxattr(path->narrow, attribute->narrow,
-                           value->buf, value->len, flags);
-    else
-        result = lsetxattr(path->narrow, attribute->narrow,
-                           value->buf, value->len, flags);
-    Py_END_ALLOW_THREADS;
-
-    if (result) {
-        path_error(path);
-        return NULL;
-    }
-
-    Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.removexattr
-
-    path: path_t(allow_fd=True)
-    attribute: path_t
-    *
-    follow_symlinks: bool = True
-
-Remove extended attribute attribute on path.
-
-path may be either a string or an open file descriptor.
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, removexattr will modify the symbolic link itself instead of the file
-  the link points to.
-
-[clinic start generated code]*/
+#endif /* defined(USE_XATTRS) */
+
+#if defined(USE_XATTRS)
 
 PyDoc_STRVAR(os_removexattr__doc__,
 "removexattr($module, /, path, attribute, *, follow_symlinks=True)\n"
@@ -15614,47 +5163,9 @@
     return return_value;
 }
 
-static PyObject *
-os_removexattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, int follow_symlinks)
-/*[clinic end generated code: output=8dfc715bf607c4cf input=cdb54834161e3329]*/
-{
-    ssize_t result;
-
-    if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
-        return NULL;
-
-    Py_BEGIN_ALLOW_THREADS;
-    if (path->fd > -1)
-        result = fremovexattr(path->fd, attribute->narrow);
-    else if (follow_symlinks)
-        result = removexattr(path->narrow, attribute->narrow);
-    else
-        result = lremovexattr(path->narrow, attribute->narrow);
-    Py_END_ALLOW_THREADS;
-
-    if (result) {
-        return path_error(path);
-    }
-
-    Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.listxattr
-
-    path: path_t(allow_fd=True, nullable=True) = None
-    *
-    follow_symlinks: bool = True
-
-Return a list of extended attributes on path.
-
-path may be either None, a string, or an open file descriptor.
-if path is None, listxattr will examine the current directory.
-If follow_symlinks is False, and the last element of the path is a symbolic
-  link, listxattr will examine the symbolic link itself instead of the file
-  the link points to.
-[clinic start generated code]*/
+#endif /* defined(USE_XATTRS) */
+
+#if defined(USE_XATTRS)
 
 PyDoc_STRVAR(os_listxattr__doc__,
 "listxattr($module, /, path=None, *, follow_symlinks=True)\n"
@@ -15695,99 +5206,7 @@
     return return_value;
 }
 
-static PyObject *
-os_listxattr_impl(PyModuleDef *module, path_t *path, int follow_symlinks)
-/*[clinic end generated code: output=3104cafda1a3d887 input=08cca53ac0b07c13]*/
-{
-    Py_ssize_t i;
-    PyObject *result = NULL;
-    const char *name;
-    char *buffer = NULL;
-
-    if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
-        goto exit;
-
-    name = path->narrow ? path->narrow : ".";
-
-    for (i = 0; ; i++) {
-        char *start, *trace, *end;
-        ssize_t length;
-        static Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
-        Py_ssize_t buffer_size = buffer_sizes[i];
-        if (!buffer_size) {
-            /* ERANGE */
-            path_error(path);
-            break;
-        }
-        buffer = PyMem_MALLOC(buffer_size);
-        if (!buffer) {
-            PyErr_NoMemory();
-            break;
-        }
-
-        Py_BEGIN_ALLOW_THREADS;
-        if (path->fd > -1)
-            length = flistxattr(path->fd, buffer, buffer_size);
-        else if (follow_symlinks)
-            length = listxattr(name, buffer, buffer_size);
-        else
-            length = llistxattr(name, buffer, buffer_size);
-        Py_END_ALLOW_THREADS;
-
-        if (length < 0) {
-            if (errno == ERANGE) {
-                PyMem_FREE(buffer);
-                buffer = NULL;
-                continue;
-            }
-            path_error(path);
-            break;
-        }
-
-        result = PyList_New(0);
-        if (!result) {
-            goto exit;
-        }
-
-        end = buffer + length;
-        for (trace = start = buffer; trace != end; trace++) {
-            if (!*trace) {
-                int error;
-                PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
-                                                                 trace - start);
-                if (!attribute) {
-                    Py_DECREF(result);
-                    result = NULL;
-                    goto exit;
-                }
-                error = PyList_Append(result, attribute);
-                Py_DECREF(attribute);
-                if (error) {
-                    Py_DECREF(result);
-                    result = NULL;
-                    goto exit;
-                }
-                start = trace + 1;
-            }
-        }
-    break;
-    }
-exit:
-    if (buffer)
-        PyMem_FREE(buffer);
-    return result;
-}
-#endif /* USE_XATTRS */
-
-
-/*[clinic input]
-os.urandom
-
-    size: Py_ssize_t
-    /
-
-Return a bytes object containing random bytes suitable for cryptographic use.
-[clinic start generated code]*/
+#endif /* defined(USE_XATTRS) */
 
 PyDoc_STRVAR(os_urandom__doc__,
 "urandom($module, size, /)\n"
@@ -15817,143 +5236,6 @@
     return return_value;
 }
 
-static PyObject *
-os_urandom_impl(PyModuleDef *module, Py_ssize_t size)
-/*[clinic end generated code: output=5dbff582cab94cb9 input=4067cdb1b6776c29]*/
-{
-    PyObject *bytes;
-    int result;
-
-    if (size < 0)
-        return PyErr_Format(PyExc_ValueError,
-                            "negative argument not allowed");
-    bytes = PyBytes_FromStringAndSize(NULL, size);
-    if (bytes == NULL)
-        return NULL;
-
-    result = _PyOS_URandom(PyBytes_AS_STRING(bytes),
-                        PyBytes_GET_SIZE(bytes));
-    if (result == -1) {
-        Py_DECREF(bytes);
-        return NULL;
-    }
-    return bytes;
-}
-
-/* Terminal size querying */
-
-static PyTypeObject TerminalSizeType;
-
-PyDoc_STRVAR(TerminalSize_docstring,
-    "A tuple of (columns, lines) for holding terminal window size");
-
-static PyStructSequence_Field TerminalSize_fields[] = {
-    {"columns", "width of the terminal window in characters"},
-    {"lines", "height of the terminal window in characters"},
-    {NULL, NULL}
-};
-
-static PyStructSequence_Desc TerminalSize_desc = {
-    "os.terminal_size",
-    TerminalSize_docstring,
-    TerminalSize_fields,
-    2,
-};
-
-#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
-/* AC 3.5: fd should accept None */
-PyDoc_STRVAR(termsize__doc__,
-    "Return the size of the terminal window as (columns, lines).\n"        \
-    "\n"                                                                   \
-    "The optional argument fd (default standard output) specifies\n"       \
-    "which file descriptor should be queried.\n"                           \
-    "\n"                                                                   \
-    "If the file descriptor is not connected to a terminal, an OSError\n"  \
-    "is thrown.\n"                                                         \
-    "\n"                                                                   \
-    "This function will only be defined if an implementation is\n"         \
-    "available for this system.\n"                                         \
-    "\n"                                                                   \
-    "shutil.get_terminal_size is the high-level function which should \n"  \
-    "normally be used, os.get_terminal_size is the low-level implementation.");
-
-static PyObject*
-get_terminal_size(PyObject *self, PyObject *args)
-{
-    int columns, lines;
-    PyObject *termsize;
-
-    int fd = fileno(stdout);
-    /* Under some conditions stdout may not be connected and
-     * fileno(stdout) may point to an invalid file descriptor. For example
-     * GUI apps don't have valid standard streams by default.
-     *
-     * If this happens, and the optional fd argument is not present,
-     * the ioctl below will fail returning EBADF. This is what we want.
-     */
-
-    if (!PyArg_ParseTuple(args, "|i", &fd))
-        return NULL;
-
-#ifdef TERMSIZE_USE_IOCTL
-    {
-        struct winsize w;
-        if (ioctl(fd, TIOCGWINSZ, &w))
-            return PyErr_SetFromErrno(PyExc_OSError);
-        columns = w.ws_col;
-        lines = w.ws_row;
-    }
-#endif /* TERMSIZE_USE_IOCTL */
-
-#ifdef TERMSIZE_USE_CONIO
-    {
-        DWORD nhandle;
-        HANDLE handle;
-        CONSOLE_SCREEN_BUFFER_INFO csbi;
-        switch (fd) {
-        case 0: nhandle = STD_INPUT_HANDLE;
-            break;
-        case 1: nhandle = STD_OUTPUT_HANDLE;
-            break;
-        case 2: nhandle = STD_ERROR_HANDLE;
-            break;
-        default:
-            return PyErr_Format(PyExc_ValueError, "bad file descriptor");
-        }
-        handle = GetStdHandle(nhandle);
-        if (handle == NULL)
-            return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
-        if (handle == INVALID_HANDLE_VALUE)
-            return PyErr_SetFromWindowsErr(0);
-
-        if (!GetConsoleScreenBufferInfo(handle, &csbi))
-            return PyErr_SetFromWindowsErr(0);
-
-        columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
-        lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
-    }
-#endif /* TERMSIZE_USE_CONIO */
-
-    termsize = PyStructSequence_New(&TerminalSizeType);
-    if (termsize == NULL)
-        return NULL;
-    PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
-    PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
-    if (PyErr_Occurred()) {
-        Py_DECREF(termsize);
-        return NULL;
-    }
-    return termsize;
-}
-#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
-
-
-/*[clinic input]
-os.cpu_count
-
-Return the number of CPUs in the system; return None if indeterminable.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_cpu_count__doc__,
 "cpu_count($module, /)\n"
 "--\n"
@@ -15972,47 +5254,6 @@
     return os_cpu_count_impl(module);
 }
 
-static PyObject *
-os_cpu_count_impl(PyModuleDef *module)
-/*[clinic end generated code: output=92e2a4a729eb7740 input=d55e2f8f3823a628]*/
-{
-    int ncpu = 0;
-#ifdef MS_WINDOWS
-    SYSTEM_INFO sysinfo;
-    GetSystemInfo(&sysinfo);
-    ncpu = sysinfo.dwNumberOfProcessors;
-#elif defined(__hpux)
-    ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
-#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
-    ncpu = sysconf(_SC_NPROCESSORS_ONLN);
-#elif defined(__DragonFly__) || \
-      defined(__OpenBSD__)   || \
-      defined(__FreeBSD__)   || \
-      defined(__NetBSD__)    || \
-      defined(__APPLE__)
-    int mib[2];
-    size_t len = sizeof(ncpu);
-    mib[0] = CTL_HW;
-    mib[1] = HW_NCPU;
-    if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
-        ncpu = 0;
-#endif
-    if (ncpu >= 1)
-        return PyLong_FromLong(ncpu);
-    else
-        Py_RETURN_NONE;
-}
-
-
-/*[clinic input]
-os.get_inheritable -> bool
-
-    fd: int
-    /
-
-Get the close-on-exe flag of the specified file descriptor.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_get_inheritable__doc__,
 "get_inheritable($module, fd, /)\n"
 "--\n"
@@ -16045,28 +5286,6 @@
     return return_value;
 }
 
-static int
-os_get_inheritable_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=261d1dd2b0dbdc35 input=89ac008dc9ab6b95]*/
-{
-    if (!_PyVerify_fd(fd)){
-        posix_error();
-        return -1;
-    }
-
-    return _Py_get_inheritable(fd);
-}
-
-
-/*[clinic input]
-os.set_inheritable
-    fd: int
-    inheritable: int
-    /
-
-Set the inheritable flag of the specified file descriptor.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(os_set_inheritable__doc__,
 "set_inheritable($module, fd, inheritable, /)\n"
 "--\n"
@@ -16096,27 +5315,7 @@
     return return_value;
 }
 
-static PyObject *
-os_set_inheritable_impl(PyModuleDef *module, int fd, int inheritable)
-/*[clinic end generated code: output=64dfe5e15c906539 input=9ceaead87a1e2402]*/
-{
-    if (!_PyVerify_fd(fd))
-        return posix_error();
-
-    if (_Py_set_inheritable(fd, inheritable, NULL) < 0)
-        return NULL;
-    Py_RETURN_NONE;
-}
-
-
-#ifdef MS_WINDOWS
-/*[clinic input]
-os.get_handle_inheritable -> bool
-    handle: Py_intptr_t
-    /
-
-Get the close-on-exe flag of the specified file descriptor.
-[clinic start generated code]*/
+#if defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os_get_handle_inheritable__doc__,
 "get_handle_inheritable($module, handle, /)\n"
@@ -16150,29 +5349,9 @@
     return return_value;
 }
 
-static int
-os_get_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle)
-/*[clinic end generated code: output=d5bf9d86900bf457 input=5f7759443aae3dc5]*/
-{
-    DWORD flags;
-
-    if (!GetHandleInformation((HANDLE)handle, &flags)) {
-        PyErr_SetFromWindowsErr(0);
-        return -1;
-    }
-
-    return flags & HANDLE_FLAG_INHERIT;
-}
-
-
-/*[clinic input]
-os.set_handle_inheritable
-    handle: Py_intptr_t
-    inheritable: bool
-    /
-
-Set the inheritable flag of the specified handle.
-[clinic start generated code]*/
+#endif /* defined(MS_WINDOWS) */
+
+#if defined(MS_WINDOWS)
 
 PyDoc_STRVAR(os_set_handle_inheritable__doc__,
 "set_handle_inheritable($module, handle, inheritable, /)\n"
@@ -16203,848 +5382,7 @@
     return return_value;
 }
 
-static PyObject *
-os_set_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle, int inheritable)
-/*[clinic end generated code: output=ee5fcc6d9f0d4f8b input=e64b2b2730469def]*/
-{
-    DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
-    if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
-        PyErr_SetFromWindowsErr(0);
-        return NULL;
-    }
-    Py_RETURN_NONE;
-}
-#endif /* MS_WINDOWS */
-
-#ifndef MS_WINDOWS
-PyDoc_STRVAR(get_blocking__doc__,
-    "get_blocking(fd) -> bool\n" \
-    "\n" \
-    "Get the blocking mode of the file descriptor:\n" \
-    "False if the O_NONBLOCK flag is set, True if the flag is cleared.");
-
-static PyObject*
-posix_get_blocking(PyObject *self, PyObject *args)
-{
-    int fd;
-    int blocking;
-
-    if (!PyArg_ParseTuple(args, "i:get_blocking", &fd))
-        return NULL;
-
-    if (!_PyVerify_fd(fd))
-        return posix_error();
-
-    blocking = _Py_get_blocking(fd);
-    if (blocking < 0)
-        return NULL;
-    return PyBool_FromLong(blocking);
-}
-
-PyDoc_STRVAR(set_blocking__doc__,
-    "set_blocking(fd, blocking)\n" \
-    "\n" \
-    "Set the blocking mode of the specified file descriptor.\n" \
-    "Set the O_NONBLOCK flag if blocking is False,\n" \
-    "clear the O_NONBLOCK flag otherwise.");
-
-static PyObject*
-posix_set_blocking(PyObject *self, PyObject *args)
-{
-    int fd, blocking;
-
-    if (!PyArg_ParseTuple(args, "ii:set_blocking", &fd, &blocking))
-        return NULL;
-
-    if (!_PyVerify_fd(fd))
-        return posix_error();
-
-    if (_Py_set_blocking(fd, blocking) < 0)
-        return NULL;
-    Py_RETURN_NONE;
-}
-#endif   /* !MS_WINDOWS */
-
-
-PyDoc_STRVAR(posix_scandir__doc__,
-"scandir(path='.') -> iterator of DirEntry objects for given path");
-
-static char *follow_symlinks_keywords[] = {"follow_symlinks", NULL};
-
-typedef struct {
-    PyObject_HEAD
-    PyObject *name;
-    PyObject *path;
-    PyObject *stat;
-    PyObject *lstat;
-#ifdef MS_WINDOWS
-    struct _Py_stat_struct win32_lstat;
-    __int64 win32_file_index;
-    int got_file_index;
-#else /* POSIX */
-#ifdef HAVE_DIRENT_D_TYPE
-    unsigned char d_type;
-#endif
-    ino_t d_ino;
-#endif
-} DirEntry;
-
-static void
-DirEntry_dealloc(DirEntry *entry)
-{
-    Py_XDECREF(entry->name);
-    Py_XDECREF(entry->path);
-    Py_XDECREF(entry->stat);
-    Py_XDECREF(entry->lstat);
-    Py_TYPE(entry)->tp_free((PyObject *)entry);
-}
-
-/* Forward reference */
-static int
-DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
-
-/* Set exception and return -1 on error, 0 for False, 1 for True */
-static int
-DirEntry_is_symlink(DirEntry *self)
-{
-#ifdef MS_WINDOWS
-    return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
-#elif defined(HAVE_DIRENT_D_TYPE)
-    /* POSIX */
-    if (self->d_type != DT_UNKNOWN)
-        return self->d_type == DT_LNK;
-    else
-        return DirEntry_test_mode(self, 0, S_IFLNK);
-#else
-    /* POSIX without d_type */
-    return DirEntry_test_mode(self, 0, S_IFLNK);
-#endif
-}
-
-static PyObject *
-DirEntry_py_is_symlink(DirEntry *self)
-{
-    int result;
-
-    result = DirEntry_is_symlink(self);
-    if (result == -1)
-        return NULL;
-    return PyBool_FromLong(result);
-}
-
-static PyObject *
-DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
-{
-    int result;
-    struct _Py_stat_struct st;
-
-#ifdef MS_WINDOWS
-    wchar_t *path;
-
-    path = PyUnicode_AsUnicode(self->path);
-    if (!path)
-        return NULL;
-
-    if (follow_symlinks)
-        result = win32_stat_w(path, &st);
-    else
-        result = win32_lstat_w(path, &st);
-
-    if (result != 0) {
-        return PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError,
-                                                            0, self->path);
-    }
-#else /* POSIX */
-    PyObject *bytes;
-    char *path;
-
-    if (!PyUnicode_FSConverter(self->path, &bytes))
-        return NULL;
-    path = PyBytes_AS_STRING(bytes);
-
-    if (follow_symlinks)
-        result = STAT(path, &st);
-    else
-        result = LSTAT(path, &st);
-    Py_DECREF(bytes);
-
-    if (result != 0)
-        return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, self->path);
-#endif
-
-    return _pystat_fromstructstat(&st);
-}
-
-static PyObject *
-DirEntry_get_lstat(DirEntry *self)
-{
-    if (!self->lstat) {
-#ifdef MS_WINDOWS
-        self->lstat = _pystat_fromstructstat(&self->win32_lstat);
-#else /* POSIX */
-        self->lstat = DirEntry_fetch_stat(self, 0);
-#endif
-    }
-    Py_XINCREF(self->lstat);
-    return self->lstat;
-}
-
-static PyObject *
-DirEntry_get_stat(DirEntry *self, int follow_symlinks)
-{
-    if (!follow_symlinks)
-        return DirEntry_get_lstat(self);
-
-    if (!self->stat) {
-        int result = DirEntry_is_symlink(self);
-        if (result == -1)
-            return NULL;
-        else if (result)
-            self->stat = DirEntry_fetch_stat(self, 1);
-        else
-            self->stat = DirEntry_get_lstat(self);
-    }
-
-    Py_XINCREF(self->stat);
-    return self->stat;
-}
-
-static PyObject *
-DirEntry_stat(DirEntry *self, PyObject *args, PyObject *kwargs)
-{
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$p:DirEntry.stat",
-                                     follow_symlinks_keywords, &follow_symlinks))
-        return NULL;
-
-    return DirEntry_get_stat(self, follow_symlinks);
-}
-
-/* Set exception and return -1 on error, 0 for False, 1 for True */
-static int
-DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
-{
-    PyObject *stat = NULL;
-    PyObject *st_mode = NULL;
-    long mode;
-    int result;
-#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
-    int is_symlink;
-    int need_stat;
-#endif
-#ifdef MS_WINDOWS
-    unsigned long dir_bits;
-#endif
-    _Py_IDENTIFIER(st_mode);
-
-#ifdef MS_WINDOWS
-    is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
-    need_stat = follow_symlinks && is_symlink;
-#elif defined(HAVE_DIRENT_D_TYPE)
-    is_symlink = self->d_type == DT_LNK;
-    need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
-#endif
-
-#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
-    if (need_stat) {
-#endif
-        stat = DirEntry_get_stat(self, follow_symlinks);
-        if (!stat) {
-            if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
-                /* If file doesn't exist (anymore), then return False
-                   (i.e., say it's not a file/directory) */
-                PyErr_Clear();
-                return 0;
-            }
-            goto error;
-        }
-        st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
-        if (!st_mode)
-            goto error;
-
-        mode = PyLong_AsLong(st_mode);
-        if (mode == -1 && PyErr_Occurred())
-            goto error;
-        Py_CLEAR(st_mode);
-        Py_CLEAR(stat);
-        result = (mode & S_IFMT) == mode_bits;
-#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
-    }
-    else if (is_symlink) {
-        assert(mode_bits != S_IFLNK);
-        result = 0;
-    }
-    else {
-        assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
-#ifdef MS_WINDOWS
-        dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
-        if (mode_bits == S_IFDIR)
-            result = dir_bits != 0;
-        else
-            result = dir_bits == 0;
-#else /* POSIX */
-        if (mode_bits == S_IFDIR)
-            result = self->d_type == DT_DIR;
-        else
-            result = self->d_type == DT_REG;
-#endif
-    }
-#endif
-
-    return result;
-
-error:
-    Py_XDECREF(st_mode);
-    Py_XDECREF(stat);
-    return -1;
-}
-
-static PyObject *
-DirEntry_py_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
-{
-    int result;
-
-    result = DirEntry_test_mode(self, follow_symlinks, mode_bits);
-    if (result == -1)
-        return NULL;
-    return PyBool_FromLong(result);
-}
-
-static PyObject *
-DirEntry_is_dir(DirEntry *self, PyObject *args, PyObject *kwargs)
-{
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$p:DirEntry.is_dir",
-                                     follow_symlinks_keywords, &follow_symlinks))
-        return NULL;
-
-    return DirEntry_py_test_mode(self, follow_symlinks, S_IFDIR);
-}
-
-static PyObject *
-DirEntry_is_file(DirEntry *self, PyObject *args, PyObject *kwargs)
-{
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$p:DirEntry.is_file",
-                                     follow_symlinks_keywords, &follow_symlinks))
-        return NULL;
-
-    return DirEntry_py_test_mode(self, follow_symlinks, S_IFREG);
-}
-
-static PyObject *
-DirEntry_inode(DirEntry *self)
-{
-#ifdef MS_WINDOWS
-    if (!self->got_file_index) {
-        wchar_t *path;
-        struct _Py_stat_struct stat;
-
-        path = PyUnicode_AsUnicode(self->path);
-        if (!path)
-            return NULL;
-
-        if (win32_lstat_w(path, &stat) != 0) {
-            return PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError,
-                                                                0, self->path);
-        }
-
-        self->win32_file_index = stat.st_ino;
-        self->got_file_index = 1;
-    }
-    return PyLong_FromLongLong((PY_LONG_LONG)self->win32_file_index);
-#else /* POSIX */
-#ifdef HAVE_LARGEFILE_SUPPORT
-    return PyLong_FromLongLong((PY_LONG_LONG)self->d_ino);
-#else
-    return PyLong_FromLong((long)self->d_ino);
-#endif
-#endif
-}
-
-static PyObject *
-DirEntry_repr(DirEntry *self)
-{
-    return PyUnicode_FromFormat("<DirEntry %R>", self->name);
-}
-
-static PyMemberDef DirEntry_members[] = {
-    {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
-     "the entry's base filename, relative to scandir() \"path\" argument"},
-    {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
-     "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
-    {NULL}
-};
-
-static PyMethodDef DirEntry_methods[] = {
-    {"is_dir", (PyCFunction)DirEntry_is_dir, METH_VARARGS | METH_KEYWORDS,
-     "return True if the entry is a directory; cached per entry"
-    },
-    {"is_file", (PyCFunction)DirEntry_is_file, METH_VARARGS | METH_KEYWORDS,
-     "return True if the entry is a file; cached per entry"
-    },
-    {"is_symlink", (PyCFunction)DirEntry_py_is_symlink, METH_NOARGS,
-     "return True if the entry is a symbolic link; cached per entry"
-    },
-    {"stat", (PyCFunction)DirEntry_stat, METH_VARARGS | METH_KEYWORDS,
-     "return stat_result object for the entry; cached per entry"
-    },
-    {"inode", (PyCFunction)DirEntry_inode, METH_NOARGS,
-     "return inode of the entry; cached per entry",
-    },
-    {NULL}
-};
-
-PyTypeObject DirEntryType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    MODNAME ".DirEntry",                    /* tp_name */
-    sizeof(DirEntry),                       /* tp_basicsize */
-    0,                                      /* tp_itemsize */
-    /* methods */
-    (destructor)DirEntry_dealloc,           /* tp_dealloc */
-    0,                                      /* tp_print */
-    0,                                      /* tp_getattr */
-    0,                                      /* tp_setattr */
-    0,                                      /* tp_compare */
-    (reprfunc)DirEntry_repr,                /* tp_repr */
-    0,                                      /* tp_as_number */
-    0,                                      /* tp_as_sequence */
-    0,                                      /* tp_as_mapping */
-    0,                                      /* tp_hash */
-    0,                                      /* tp_call */
-    0,                                      /* tp_str */
-    0,                                      /* tp_getattro */
-    0,                                      /* tp_setattro */
-    0,                                      /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,                     /* tp_flags */
-    0,                                      /* tp_doc */
-    0,                                      /* tp_traverse */
-    0,                                      /* tp_clear */
-    0,                                      /* tp_richcompare */
-    0,                                      /* tp_weaklistoffset */
-    0,                                      /* tp_iter */
-    0,                                      /* tp_iternext */
-    DirEntry_methods,                       /* tp_methods */
-    DirEntry_members,                       /* tp_members */
-};
-
-#ifdef MS_WINDOWS
-
-static wchar_t *
-join_path_filenameW(wchar_t *path_wide, wchar_t* filename)
-{
-    Py_ssize_t path_len;
-    Py_ssize_t size;
-    wchar_t *result;
-    wchar_t ch;
-
-    if (!path_wide) { /* Default arg: "." */
-        path_wide = L".";
-        path_len = 1;
-    }
-    else {
-        path_len = wcslen(path_wide);
-    }
-
-    /* The +1's are for the path separator and the NUL */
-    size = path_len + 1 + wcslen(filename) + 1;
-    result = PyMem_New(wchar_t, size);
-    if (!result) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    wcscpy(result, path_wide);
-    if (path_len > 0) {
-        ch = result[path_len - 1];
-        if (ch != SEP && ch != ALTSEP && ch != L':')
-            result[path_len++] = SEP;
-        wcscpy(result + path_len, filename);
-    }
-    return result;
-}
-
-static PyObject *
-DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
-{
-    DirEntry *entry;
-    BY_HANDLE_FILE_INFORMATION file_info;
-    ULONG reparse_tag;
-    wchar_t *joined_path;
-
-    entry = PyObject_New(DirEntry, &DirEntryType);
-    if (!entry)
-        return NULL;
-    entry->name = NULL;
-    entry->path = NULL;
-    entry->stat = NULL;
-    entry->lstat = NULL;
-    entry->got_file_index = 0;
-
-    entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
-    if (!entry->name)
-        goto error;
-
-    joined_path = join_path_filenameW(path->wide, dataW->cFileName);
-    if (!joined_path)
-        goto error;
-
-    entry->path = PyUnicode_FromWideChar(joined_path, -1);
-    PyMem_Free(joined_path);
-    if (!entry->path)
-        goto error;
-
-    find_data_to_file_info_w(dataW, &file_info, &reparse_tag);
-    _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
-
-    return (PyObject *)entry;
-
-error:
-    Py_DECREF(entry);
-    return NULL;
-}
-
-#else /* POSIX */
-
-static char *
-join_path_filename(char *path_narrow, char* filename, Py_ssize_t filename_len)
-{
-    Py_ssize_t path_len;
-    Py_ssize_t size;
-    char *result;
-
-    if (!path_narrow) { /* Default arg: "." */
-        path_narrow = ".";
-        path_len = 1;
-    }
-    else {
-        path_len = strlen(path_narrow);
-    }
-
-    if (filename_len == -1)
-        filename_len = strlen(filename);
-
-    /* The +1's are for the path separator and the NUL */
-    size = path_len + 1 + filename_len + 1;
-    result = PyMem_New(char, size);
-    if (!result) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    strcpy(result, path_narrow);
-    if (path_len > 0 && result[path_len - 1] != '/')
-        result[path_len++] = '/';
-    strcpy(result + path_len, filename);
-    return result;
-}
-
-static PyObject *
-DirEntry_from_posix_info(path_t *path, char *name, Py_ssize_t name_len,
-                         ino_t d_ino
-#ifdef HAVE_DIRENT_D_TYPE
-                         , unsigned char d_type
-#endif
-                         )
-{
-    DirEntry *entry;
-    char *joined_path;
-
-    entry = PyObject_New(DirEntry, &DirEntryType);
-    if (!entry)
-        return NULL;
-    entry->name = NULL;
-    entry->path = NULL;
-    entry->stat = NULL;
-    entry->lstat = NULL;
-
-    joined_path = join_path_filename(path->narrow, name, name_len);
-    if (!joined_path)
-        goto error;
-
-    if (!path->narrow || !PyBytes_Check(path->object)) {
-        entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
-        entry->path = PyUnicode_DecodeFSDefault(joined_path);
-    }
-    else {
-        entry->name = PyBytes_FromStringAndSize(name, name_len);
-        entry->path = PyBytes_FromString(joined_path);
-    }
-    PyMem_Free(joined_path);
-    if (!entry->name || !entry->path)
-        goto error;
-
-#ifdef HAVE_DIRENT_D_TYPE
-    entry->d_type = d_type;
-#endif
-    entry->d_ino = d_ino;
-
-    return (PyObject *)entry;
-
-error:
-    Py_XDECREF(entry);
-    return NULL;
-}
-
-#endif
-
-
-typedef struct {
-    PyObject_HEAD
-    path_t path;
-#ifdef MS_WINDOWS
-    HANDLE handle;
-    WIN32_FIND_DATAW file_data;
-    int first_time;
-#else /* POSIX */
-    DIR *dirp;
-#endif
-} ScandirIterator;
-
-#ifdef MS_WINDOWS
-
-static void
-ScandirIterator_close(ScandirIterator *iterator)
-{
-    if (iterator->handle == INVALID_HANDLE_VALUE)
-        return;
-
-    Py_BEGIN_ALLOW_THREADS
-    FindClose(iterator->handle);
-    Py_END_ALLOW_THREADS
-    iterator->handle = INVALID_HANDLE_VALUE;
-}
-
-static PyObject *
-ScandirIterator_iternext(ScandirIterator *iterator)
-{
-    WIN32_FIND_DATAW *file_data = &iterator->file_data;
-    BOOL success;
-
-    /* Happens if the iterator is iterated twice */
-    if (iterator->handle == INVALID_HANDLE_VALUE) {
-        PyErr_SetNone(PyExc_StopIteration);
-        return NULL;
-    }
-
-    while (1) {
-        if (!iterator->first_time) {
-            Py_BEGIN_ALLOW_THREADS
-            success = FindNextFileW(iterator->handle, file_data);
-            Py_END_ALLOW_THREADS
-            if (!success) {
-                if (GetLastError() != ERROR_NO_MORE_FILES)
-                    return path_error(&iterator->path);
-                /* No more files found in directory, stop iterating */
-                break;
-            }
-        }
-        iterator->first_time = 0;
-
-        /* Skip over . and .. */
-        if (wcscmp(file_data->cFileName, L".") != 0 &&
-                wcscmp(file_data->cFileName, L"..") != 0)
-            return DirEntry_from_find_data(&iterator->path, file_data);
-
-        /* Loop till we get a non-dot directory or finish iterating */
-    }
-
-    ScandirIterator_close(iterator);
-
-    PyErr_SetNone(PyExc_StopIteration);
-    return NULL;
-}
-
-#else /* POSIX */
-
-static void
-ScandirIterator_close(ScandirIterator *iterator)
-{
-    if (!iterator->dirp)
-        return;
-
-    Py_BEGIN_ALLOW_THREADS
-    closedir(iterator->dirp);
-    Py_END_ALLOW_THREADS
-    iterator->dirp = NULL;
-    return;
-}
-
-static PyObject *
-ScandirIterator_iternext(ScandirIterator *iterator)
-{
-    struct dirent *direntp;
-    Py_ssize_t name_len;
-    int is_dot;
-
-    /* Happens if the iterator is iterated twice */
-    if (!iterator->dirp) {
-        PyErr_SetNone(PyExc_StopIteration);
-        return NULL;
-    }
-
-    while (1) {
-        errno = 0;
-        Py_BEGIN_ALLOW_THREADS
-        direntp = readdir(iterator->dirp);
-        Py_END_ALLOW_THREADS
-
-        if (!direntp) {
-            if (errno != 0)
-                return path_error(&iterator->path);
-            /* No more files found in directory, stop iterating */
-            break;
-        }
-
-        /* Skip over . and .. */
-        name_len = NAMLEN(direntp);
-        is_dot = direntp->d_name[0] == '.' &&
-                 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
-        if (!is_dot) {
-            return DirEntry_from_posix_info(&iterator->path, direntp->d_name,
-                                            name_len, direntp->d_ino
-#ifdef HAVE_DIRENT_D_TYPE
-                                            , direntp->d_type
-#endif
-                                            );
-        }
-
-        /* Loop till we get a non-dot directory or finish iterating */
-    }
-
-    ScandirIterator_close(iterator);
-
-    PyErr_SetNone(PyExc_StopIteration);
-    return NULL;
-}
-
-#endif
-
-static void
-ScandirIterator_dealloc(ScandirIterator *iterator)
-{
-    ScandirIterator_close(iterator);
-    Py_XDECREF(iterator->path.object);
-    path_cleanup(&iterator->path);
-    Py_TYPE(iterator)->tp_free((PyObject *)iterator);
-}
-
-PyTypeObject ScandirIteratorType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    MODNAME ".ScandirIterator",             /* tp_name */
-    sizeof(ScandirIterator),                /* tp_basicsize */
-    0,                                      /* tp_itemsize */
-    /* methods */
-    (destructor)ScandirIterator_dealloc,    /* tp_dealloc */
-    0,                                      /* tp_print */
-    0,                                      /* tp_getattr */
-    0,                                      /* tp_setattr */
-    0,                                      /* tp_compare */
-    0,                                      /* tp_repr */
-    0,                                      /* tp_as_number */
-    0,                                      /* tp_as_sequence */
-    0,                                      /* tp_as_mapping */
-    0,                                      /* tp_hash */
-    0,                                      /* tp_call */
-    0,                                      /* tp_str */
-    0,                                      /* tp_getattro */
-    0,                                      /* tp_setattro */
-    0,                                      /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,                     /* tp_flags */
-    0,                                      /* tp_doc */
-    0,                                      /* tp_traverse */
-    0,                                      /* tp_clear */
-    0,                                      /* tp_richcompare */
-    0,                                      /* tp_weaklistoffset */
-    PyObject_SelfIter,                      /* tp_iter */
-    (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
-};
-
-static PyObject *
-posix_scandir(PyObject *self, PyObject *args, PyObject *kwargs)
-{
-    ScandirIterator *iterator;
-    static char *keywords[] = {"path", NULL};
-#ifdef MS_WINDOWS
-    wchar_t *path_strW;
-#else
-    char *path;
-#endif
-
-    iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
-    if (!iterator)
-        return NULL;
-    memset(&iterator->path, 0, sizeof(path_t));
-    iterator->path.function_name = "scandir";
-    iterator->path.nullable = 1;
-
-#ifdef MS_WINDOWS
-    iterator->handle = INVALID_HANDLE_VALUE;
-#else
-    iterator->dirp = NULL;
-#endif
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O&:scandir", keywords,
-                                     path_converter, &iterator->path))
-        goto error;
-
-    /* path_converter doesn't keep path.object around, so do it
-       manually for the lifetime of the iterator here (the refcount
-       is decremented in ScandirIterator_dealloc)
-    */
-    Py_XINCREF(iterator->path.object);
-
-#ifdef MS_WINDOWS
-    if (iterator->path.narrow) {
-        PyErr_SetString(PyExc_TypeError,
-                        "os.scandir() doesn't support bytes path on Windows, use Unicode instead");
-        goto error;
-    }
-    iterator->first_time = 1;
-
-    path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
-    if (!path_strW)
-        goto error;
-
-    Py_BEGIN_ALLOW_THREADS
-    iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
-    Py_END_ALLOW_THREADS
-
-    PyMem_Free(path_strW);
-
-    if (iterator->handle == INVALID_HANDLE_VALUE) {
-        path_error(&iterator->path);
-        goto error;
-    }
-#else /* POSIX */
-    if (iterator->path.narrow)
-        path = iterator->path.narrow;
-    else
-        path = ".";
-
-    errno = 0;
-    Py_BEGIN_ALLOW_THREADS
-    iterator->dirp = opendir(path);
-    Py_END_ALLOW_THREADS
-
-    if (!iterator->dirp) {
-        path_error(&iterator->path);
-        goto error;
-    }
-#endif
-
-    return (PyObject *)iterator;
-
-error:
-    Py_DECREF(iterator);
-    return NULL;
-}
-
-
-/*[clinic input]
-dump buffer
-[clinic start generated code]*/
+#endif /* defined(MS_WINDOWS) */
 
 #ifndef OS_TTYNAME_METHODDEF
     #define OS_TTYNAME_METHODDEF
@@ -17509,973 +5847,4 @@
 #ifndef OS_SET_HANDLE_INHERITABLE_METHODDEF
     #define OS_SET_HANDLE_INHERITABLE_METHODDEF
 #endif /* !defined(OS_SET_HANDLE_INHERITABLE_METHODDEF) */
-/*[clinic end generated code: output=b788c2d6010113e8 input=524ce2e021e4eba6]*/
-
-
-static PyMethodDef posix_methods[] = {
-
-    OS_STAT_METHODDEF
-    OS_ACCESS_METHODDEF
-    OS_TTYNAME_METHODDEF
-    OS_CHDIR_METHODDEF
-    OS_CHFLAGS_METHODDEF
-    OS_CHMOD_METHODDEF
-    OS_FCHMOD_METHODDEF
-    OS_LCHMOD_METHODDEF
-    OS_CHOWN_METHODDEF
-    OS_FCHOWN_METHODDEF
-    OS_LCHOWN_METHODDEF
-    OS_LCHFLAGS_METHODDEF
-    OS_CHROOT_METHODDEF
-    OS_CTERMID_METHODDEF
-    OS_GETCWD_METHODDEF
-    OS_GETCWDB_METHODDEF
-    OS_LINK_METHODDEF
-    OS_LISTDIR_METHODDEF
-    OS_LSTAT_METHODDEF
-    OS_MKDIR_METHODDEF
-    OS_NICE_METHODDEF
-    OS_GETPRIORITY_METHODDEF
-    OS_SETPRIORITY_METHODDEF
-#ifdef HAVE_READLINK
-    {"readlink",        (PyCFunction)posix_readlink,
-                        METH_VARARGS | METH_KEYWORDS,
-                        readlink__doc__},
-#endif /* HAVE_READLINK */
-#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
-    {"readlink",        (PyCFunction)win_readlink,
-                        METH_VARARGS | METH_KEYWORDS,
-                        readlink__doc__},
-#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
-    OS_RENAME_METHODDEF
-    OS_REPLACE_METHODDEF
-    OS_RMDIR_METHODDEF
-    {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
-    OS_SYMLINK_METHODDEF
-    OS_SYSTEM_METHODDEF
-    OS_UMASK_METHODDEF
-    OS_UNAME_METHODDEF
-    OS_UNLINK_METHODDEF
-    OS_REMOVE_METHODDEF
-    OS_UTIME_METHODDEF
-    OS_TIMES_METHODDEF
-    OS__EXIT_METHODDEF
-    OS_EXECV_METHODDEF
-    OS_EXECVE_METHODDEF
-    OS_SPAWNV_METHODDEF
-    OS_SPAWNVE_METHODDEF
-    OS_FORK1_METHODDEF
-    OS_FORK_METHODDEF
-    OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-    OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-    OS_SCHED_GETPARAM_METHODDEF
-    OS_SCHED_GETSCHEDULER_METHODDEF
-    OS_SCHED_RR_GET_INTERVAL_METHODDEF
-    OS_SCHED_SETPARAM_METHODDEF
-    OS_SCHED_SETSCHEDULER_METHODDEF
-    OS_SCHED_YIELD_METHODDEF
-    OS_SCHED_SETAFFINITY_METHODDEF
-    OS_SCHED_GETAFFINITY_METHODDEF
-    OS_OPENPTY_METHODDEF
-    OS_FORKPTY_METHODDEF
-    OS_GETEGID_METHODDEF
-    OS_GETEUID_METHODDEF
-    OS_GETGID_METHODDEF
-#ifdef HAVE_GETGROUPLIST
-    {"getgrouplist",    posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
-#endif
-    OS_GETGROUPS_METHODDEF
-    OS_GETPID_METHODDEF
-    OS_GETPGRP_METHODDEF
-    OS_GETPPID_METHODDEF
-    OS_GETUID_METHODDEF
-    OS_GETLOGIN_METHODDEF
-    OS_KILL_METHODDEF
-    OS_KILLPG_METHODDEF
-    OS_PLOCK_METHODDEF
-#ifdef MS_WINDOWS
-    {"startfile",       win32_startfile, METH_VARARGS, win32_startfile__doc__},
-#endif
-    OS_SETUID_METHODDEF
-    OS_SETEUID_METHODDEF
-    OS_SETREUID_METHODDEF
-    OS_SETGID_METHODDEF
-    OS_SETEGID_METHODDEF
-    OS_SETREGID_METHODDEF
-    OS_SETGROUPS_METHODDEF
-#ifdef HAVE_INITGROUPS
-    {"initgroups",      posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
-#endif /* HAVE_INITGROUPS */
-    OS_GETPGID_METHODDEF
-    OS_SETPGRP_METHODDEF
-    OS_WAIT_METHODDEF
-    OS_WAIT3_METHODDEF
-    OS_WAIT4_METHODDEF
-    OS_WAITID_METHODDEF
-    OS_WAITPID_METHODDEF
-    OS_GETSID_METHODDEF
-    OS_SETSID_METHODDEF
-    OS_SETPGID_METHODDEF
-    OS_TCGETPGRP_METHODDEF
-    OS_TCSETPGRP_METHODDEF
-    OS_OPEN_METHODDEF
-    OS_CLOSE_METHODDEF
-    OS_CLOSERANGE_METHODDEF
-    OS_DEVICE_ENCODING_METHODDEF
-    OS_DUP_METHODDEF
-    OS_DUP2_METHODDEF
-    OS_LOCKF_METHODDEF
-    OS_LSEEK_METHODDEF
-    OS_READ_METHODDEF
-    OS_READV_METHODDEF
-    OS_PREAD_METHODDEF
-    OS_WRITE_METHODDEF
-    OS_WRITEV_METHODDEF
-    OS_PWRITE_METHODDEF
-#ifdef HAVE_SENDFILE
-    {"sendfile",        (PyCFunction)posix_sendfile, METH_VARARGS | METH_KEYWORDS,
-                            posix_sendfile__doc__},
-#endif
-    OS_FSTAT_METHODDEF
-    OS_ISATTY_METHODDEF
-    OS_PIPE_METHODDEF
-    OS_PIPE2_METHODDEF
-    OS_MKFIFO_METHODDEF
-    OS_MKNOD_METHODDEF
-    OS_MAJOR_METHODDEF
-    OS_MINOR_METHODDEF
-    OS_MAKEDEV_METHODDEF
-    OS_FTRUNCATE_METHODDEF
-    OS_TRUNCATE_METHODDEF
-    OS_POSIX_FALLOCATE_METHODDEF
-    OS_POSIX_FADVISE_METHODDEF
-    OS_PUTENV_METHODDEF
-    OS_UNSETENV_METHODDEF
-    OS_STRERROR_METHODDEF
-    OS_FCHDIR_METHODDEF
-    OS_FSYNC_METHODDEF
-    OS_SYNC_METHODDEF
-    OS_FDATASYNC_METHODDEF
-    OS_WCOREDUMP_METHODDEF
-    OS_WIFCONTINUED_METHODDEF
-    OS_WIFSTOPPED_METHODDEF
-    OS_WIFSIGNALED_METHODDEF
-    OS_WIFEXITED_METHODDEF
-    OS_WEXITSTATUS_METHODDEF
-    OS_WTERMSIG_METHODDEF
-    OS_WSTOPSIG_METHODDEF
-    OS_FSTATVFS_METHODDEF
-    OS_STATVFS_METHODDEF
-    OS_CONFSTR_METHODDEF
-    OS_SYSCONF_METHODDEF
-    OS_FPATHCONF_METHODDEF
-    OS_PATHCONF_METHODDEF
-    OS_ABORT_METHODDEF
-#ifdef MS_WINDOWS
-    {"_getfullpathname",        posix__getfullpathname, METH_VARARGS, NULL},
-    {"_isdir",                  posix__isdir, METH_VARARGS, posix__isdir__doc__},
-#endif
-    OS__GETDISKUSAGE_METHODDEF
-    OS__GETFINALPATHNAME_METHODDEF
-    OS__GETVOLUMEPATHNAME_METHODDEF
-    OS_GETLOADAVG_METHODDEF
-    OS_URANDOM_METHODDEF
-    OS_SETRESUID_METHODDEF
-    OS_SETRESGID_METHODDEF
-    OS_GETRESUID_METHODDEF
-    OS_GETRESGID_METHODDEF
-
-    OS_GETXATTR_METHODDEF
-    OS_SETXATTR_METHODDEF
-    OS_REMOVEXATTR_METHODDEF
-    OS_LISTXATTR_METHODDEF
-
-#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
-    {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
-#endif
-    OS_CPU_COUNT_METHODDEF
-    OS_GET_INHERITABLE_METHODDEF
-    OS_SET_INHERITABLE_METHODDEF
-    OS_GET_HANDLE_INHERITABLE_METHODDEF
-    OS_SET_HANDLE_INHERITABLE_METHODDEF
-#ifndef MS_WINDOWS
-    {"get_blocking", posix_get_blocking, METH_VARARGS, get_blocking__doc__},
-    {"set_blocking", posix_set_blocking, METH_VARARGS, set_blocking__doc__},
-#endif
-    {"scandir",         (PyCFunction)posix_scandir,
-                        METH_VARARGS | METH_KEYWORDS,
-                        posix_scandir__doc__},
-    {NULL,              NULL}            /* Sentinel */
-};
-
-
-#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
-static int
-enable_symlink()
-{
-    HANDLE tok;
-    TOKEN_PRIVILEGES tok_priv;
-    LUID luid;
-    int meth_idx = 0;
-
-    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &tok))
-        return 0;
-
-    if (!LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &luid))
-        return 0;
-
-    tok_priv.PrivilegeCount = 1;
-    tok_priv.Privileges[0].Luid = luid;
-    tok_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
-
-    if (!AdjustTokenPrivileges(tok, FALSE, &tok_priv,
-                               sizeof(TOKEN_PRIVILEGES),
-                               (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL))
-        return 0;
-
-    /* ERROR_NOT_ALL_ASSIGNED returned when the privilege can't be assigned. */
-    return GetLastError() == ERROR_NOT_ALL_ASSIGNED ? 0 : 1;
-}
-#endif /* defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
-
-static int
-all_ins(PyObject *m)
-{
-#ifdef F_OK
-    if (PyModule_AddIntMacro(m, F_OK)) return -1;
-#endif
-#ifdef R_OK
-    if (PyModule_AddIntMacro(m, R_OK)) return -1;
-#endif
-#ifdef W_OK
-    if (PyModule_AddIntMacro(m, W_OK)) return -1;
-#endif
-#ifdef X_OK
-    if (PyModule_AddIntMacro(m, X_OK)) return -1;
-#endif
-#ifdef NGROUPS_MAX
-    if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
-#endif
-#ifdef TMP_MAX
-    if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
-#endif
-#ifdef WCONTINUED
-    if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
-#endif
-#ifdef WNOHANG
-    if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
-#endif
-#ifdef WUNTRACED
-    if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
-#endif
-#ifdef O_RDONLY
-    if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
-#endif
-#ifdef O_WRONLY
-    if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
-#endif
-#ifdef O_RDWR
-    if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
-#endif
-#ifdef O_NDELAY
-    if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
-#endif
-#ifdef O_NONBLOCK
-    if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
-#endif
-#ifdef O_APPEND
-    if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
-#endif
-#ifdef O_DSYNC
-    if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
-#endif
-#ifdef O_RSYNC
-    if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
-#endif
-#ifdef O_SYNC
-    if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
-#endif
-#ifdef O_NOCTTY
-    if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
-#endif
-#ifdef O_CREAT
-    if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
-#endif
-#ifdef O_EXCL
-    if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
-#endif
-#ifdef O_TRUNC
-    if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
-#endif
-#ifdef O_BINARY
-    if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
-#endif
-#ifdef O_TEXT
-    if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
-#endif
-#ifdef O_XATTR
-    if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
-#endif
-#ifdef O_LARGEFILE
-    if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
-#endif
-#ifdef O_SHLOCK
-    if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
-#endif
-#ifdef O_EXLOCK
-    if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
-#endif
-#ifdef O_EXEC
-    if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
-#endif
-#ifdef O_SEARCH
-    if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
-#endif
-#ifdef O_PATH
-    if (PyModule_AddIntMacro(m, O_PATH)) return -1;
-#endif
-#ifdef O_TTY_INIT
-    if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
-#endif
-#ifdef O_TMPFILE
-    if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
-#endif
-#ifdef PRIO_PROCESS
-    if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
-#endif
-#ifdef PRIO_PGRP
-    if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
-#endif
-#ifdef PRIO_USER
-    if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
-#endif
-#ifdef O_CLOEXEC
-    if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
-#endif
-#ifdef O_ACCMODE
-    if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
-#endif
-
-
-#ifdef SEEK_HOLE
-    if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
-#endif
-#ifdef SEEK_DATA
-    if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
-#endif
-
-/* MS Windows */
-#ifdef O_NOINHERIT
-    /* Don't inherit in child processes. */
-    if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
-#endif
-#ifdef _O_SHORT_LIVED
-    /* Optimize for short life (keep in memory). */
-    /* MS forgot to define this one with a non-underscore form too. */
-    if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
-#endif
-#ifdef O_TEMPORARY
-    /* Automatically delete when last handle is closed. */
-    if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
-#endif
-#ifdef O_RANDOM
-    /* Optimize for random access. */
-    if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
-#endif
-#ifdef O_SEQUENTIAL
-    /* Optimize for sequential access. */
-    if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
-#endif
-
-/* GNU extensions. */
-#ifdef O_ASYNC
-    /* Send a SIGIO signal whenever input or output
-       becomes available on file descriptor */
-    if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
-#endif
-#ifdef O_DIRECT
-    /* Direct disk access. */
-    if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
-#endif
-#ifdef O_DIRECTORY
-    /* Must be a directory.      */
-    if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
-#endif
-#ifdef O_NOFOLLOW
-    /* Do not follow links.      */
-    if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
-#endif
-#ifdef O_NOLINKS
-    /* Fails if link count of the named file is greater than 1 */
-    if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
-#endif
-#ifdef O_NOATIME
-    /* Do not update the access time. */
-    if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
-#endif
-
-    /* These come from sysexits.h */
-#ifdef EX_OK
-    if (PyModule_AddIntMacro(m, EX_OK)) return -1;
-#endif /* EX_OK */
-#ifdef EX_USAGE
-    if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
-#endif /* EX_USAGE */
-#ifdef EX_DATAERR
-    if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
-#endif /* EX_DATAERR */
-#ifdef EX_NOINPUT
-    if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
-#endif /* EX_NOINPUT */
-#ifdef EX_NOUSER
-    if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
-#endif /* EX_NOUSER */
-#ifdef EX_NOHOST
-    if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
-#endif /* EX_NOHOST */
-#ifdef EX_UNAVAILABLE
-    if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
-#endif /* EX_UNAVAILABLE */
-#ifdef EX_SOFTWARE
-    if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
-#endif /* EX_SOFTWARE */
-#ifdef EX_OSERR
-    if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
-#endif /* EX_OSERR */
-#ifdef EX_OSFILE
-    if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
-#endif /* EX_OSFILE */
-#ifdef EX_CANTCREAT
-    if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
-#endif /* EX_CANTCREAT */
-#ifdef EX_IOERR
-    if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
-#endif /* EX_IOERR */
-#ifdef EX_TEMPFAIL
-    if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
-#endif /* EX_TEMPFAIL */
-#ifdef EX_PROTOCOL
-    if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
-#endif /* EX_PROTOCOL */
-#ifdef EX_NOPERM
-    if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
-#endif /* EX_NOPERM */
-#ifdef EX_CONFIG
-    if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
-#endif /* EX_CONFIG */
-#ifdef EX_NOTFOUND
-    if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
-#endif /* EX_NOTFOUND */
-
-    /* statvfs */
-#ifdef ST_RDONLY
-    if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
-#endif /* ST_RDONLY */
-#ifdef ST_NOSUID
-    if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
-#endif /* ST_NOSUID */
-
-       /* GNU extensions */
-#ifdef ST_NODEV
-    if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
-#endif /* ST_NODEV */
-#ifdef ST_NOEXEC
-    if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
-#endif /* ST_NOEXEC */
-#ifdef ST_SYNCHRONOUS
-    if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
-#endif /* ST_SYNCHRONOUS */
-#ifdef ST_MANDLOCK
-    if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
-#endif /* ST_MANDLOCK */
-#ifdef ST_WRITE
-    if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
-#endif /* ST_WRITE */
-#ifdef ST_APPEND
-    if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
-#endif /* ST_APPEND */
-#ifdef ST_NOATIME
-    if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
-#endif /* ST_NOATIME */
-#ifdef ST_NODIRATIME
-    if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
-#endif /* ST_NODIRATIME */
-#ifdef ST_RELATIME
-    if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
-#endif /* ST_RELATIME */
-
-    /* FreeBSD sendfile() constants */
-#ifdef SF_NODISKIO
-    if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
-#endif
-#ifdef SF_MNOWAIT
-    if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
-#endif
-#ifdef SF_SYNC
-    if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
-#endif
-
-    /* constants for posix_fadvise */
-#ifdef POSIX_FADV_NORMAL
-    if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
-#endif
-#ifdef POSIX_FADV_SEQUENTIAL
-    if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
-#endif
-#ifdef POSIX_FADV_RANDOM
-    if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
-#endif
-#ifdef POSIX_FADV_NOREUSE
-    if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
-#endif
-#ifdef POSIX_FADV_WILLNEED
-    if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
-#endif
-#ifdef POSIX_FADV_DONTNEED
-    if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
-#endif
-
-    /* constants for waitid */
-#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
-    if (PyModule_AddIntMacro(m, P_PID)) return -1;
-    if (PyModule_AddIntMacro(m, P_PGID)) return -1;
-    if (PyModule_AddIntMacro(m, P_ALL)) return -1;
-#endif
-#ifdef WEXITED
-    if (PyModule_AddIntMacro(m, WEXITED)) return -1;
-#endif
-#ifdef WNOWAIT
-    if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
-#endif
-#ifdef WSTOPPED
-    if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
-#endif
-#ifdef CLD_EXITED
-    if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
-#endif
-#ifdef CLD_DUMPED
-    if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
-#endif
-#ifdef CLD_TRAPPED
-    if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
-#endif
-#ifdef CLD_CONTINUED
-    if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
-#endif
-
-    /* constants for lockf */
-#ifdef F_LOCK
-    if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
-#endif
-#ifdef F_TLOCK
-    if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
-#endif
-#ifdef F_ULOCK
-    if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
-#endif
-#ifdef F_TEST
-    if (PyModule_AddIntMacro(m, F_TEST)) return -1;
-#endif
-
-#ifdef HAVE_SPAWNV
-    if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
-    if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
-    if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
-    if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
-    if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
-#endif
-
-#ifdef HAVE_SCHED_H
-    if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
-    if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
-    if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
-#ifdef SCHED_SPORADIC
-    if (PyModule_AddIntMacro(m, SCHED_SPORADIC) return -1;
-#endif
-#ifdef SCHED_BATCH
-    if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
-#endif
-#ifdef SCHED_IDLE
-    if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
-#endif
-#ifdef SCHED_RESET_ON_FORK
-    if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
-#endif
-#ifdef SCHED_SYS
-    if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
-#endif
-#ifdef SCHED_IA
-    if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
-#endif
-#ifdef SCHED_FSS
-    if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
-#endif
-#ifdef SCHED_FX
-    if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
-#endif
-#endif
-
-#ifdef USE_XATTRS
-    if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
-    if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
-    if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
-#endif
-
-#ifdef RTLD_LAZY
-    if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
-#endif
-#ifdef RTLD_NOW
-    if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
-#endif
-#ifdef RTLD_GLOBAL
-    if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
-#endif
-#ifdef RTLD_LOCAL
-    if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
-#endif
-#ifdef RTLD_NODELETE
-    if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
-#endif
-#ifdef RTLD_NOLOAD
-    if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
-#endif
-#ifdef RTLD_DEEPBIND
-    if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
-#endif
-
-    return 0;
-}
-
-
-static struct PyModuleDef posixmodule = {
-    PyModuleDef_HEAD_INIT,
-    MODNAME,
-    posix__doc__,
-    -1,
-    posix_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-
-static char *have_functions[] = {
-
-#ifdef HAVE_FACCESSAT
-    "HAVE_FACCESSAT",
-#endif
-
-#ifdef HAVE_FCHDIR
-    "HAVE_FCHDIR",
-#endif
-
-#ifdef HAVE_FCHMOD
-    "HAVE_FCHMOD",
-#endif
-
-#ifdef HAVE_FCHMODAT
-    "HAVE_FCHMODAT",
-#endif
-
-#ifdef HAVE_FCHOWN
-    "HAVE_FCHOWN",
-#endif
-
-#ifdef HAVE_FCHOWNAT
-    "HAVE_FCHOWNAT",
-#endif
-
-#ifdef HAVE_FEXECVE
-    "HAVE_FEXECVE",
-#endif
-
-#ifdef HAVE_FDOPENDIR
-    "HAVE_FDOPENDIR",
-#endif
-
-#ifdef HAVE_FPATHCONF
-    "HAVE_FPATHCONF",
-#endif
-
-#ifdef HAVE_FSTATAT
-    "HAVE_FSTATAT",
-#endif
-
-#ifdef HAVE_FSTATVFS
-    "HAVE_FSTATVFS",
-#endif
-
-#ifdef HAVE_FTRUNCATE
-    "HAVE_FTRUNCATE",
-#endif
-
-#ifdef HAVE_FUTIMENS
-    "HAVE_FUTIMENS",
-#endif
-
-#ifdef HAVE_FUTIMES
-    "HAVE_FUTIMES",
-#endif
-
-#ifdef HAVE_FUTIMESAT
-    "HAVE_FUTIMESAT",
-#endif
-
-#ifdef HAVE_LINKAT
-    "HAVE_LINKAT",
-#endif
-
-#ifdef HAVE_LCHFLAGS
-    "HAVE_LCHFLAGS",
-#endif
-
-#ifdef HAVE_LCHMOD
-    "HAVE_LCHMOD",
-#endif
-
-#ifdef HAVE_LCHOWN
-    "HAVE_LCHOWN",
-#endif
-
-#ifdef HAVE_LSTAT
-    "HAVE_LSTAT",
-#endif
-
-#ifdef HAVE_LUTIMES
-    "HAVE_LUTIMES",
-#endif
-
-#ifdef HAVE_MKDIRAT
-    "HAVE_MKDIRAT",
-#endif
-
-#ifdef HAVE_MKFIFOAT
-    "HAVE_MKFIFOAT",
-#endif
-
-#ifdef HAVE_MKNODAT
-    "HAVE_MKNODAT",
-#endif
-
-#ifdef HAVE_OPENAT
-    "HAVE_OPENAT",
-#endif
-
-#ifdef HAVE_READLINKAT
-    "HAVE_READLINKAT",
-#endif
-
-#ifdef HAVE_RENAMEAT
-    "HAVE_RENAMEAT",
-#endif
-
-#ifdef HAVE_SYMLINKAT
-    "HAVE_SYMLINKAT",
-#endif
-
-#ifdef HAVE_UNLINKAT
-    "HAVE_UNLINKAT",
-#endif
-
-#ifdef HAVE_UTIMENSAT
-    "HAVE_UTIMENSAT",
-#endif
-
-#ifdef MS_WINDOWS
-    "MS_WINDOWS",
-#endif
-
-    NULL
-};
-
-
-PyMODINIT_FUNC
-INITFUNC(void)
-{
-    PyObject *m, *v;
-    PyObject *list;
-    char **trace;
-
-#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
-    win32_can_symlink = enable_symlink();
-#endif
-
-    m = PyModule_Create(&posixmodule);
-    if (m == NULL)
-        return NULL;
-
-    /* Initialize environ dictionary */
-    v = convertenviron();
-    Py_XINCREF(v);
-    if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
-        return NULL;
-    Py_DECREF(v);
-
-    if (all_ins(m))
-        return NULL;
-
-    if (setup_confname_tables(m))
-        return NULL;
-
-    Py_INCREF(PyExc_OSError);
-    PyModule_AddObject(m, "error", PyExc_OSError);
-
-#ifdef HAVE_PUTENV
-    if (posix_putenv_garbage == NULL)
-        posix_putenv_garbage = PyDict_New();
-#endif
-
-    if (!initialized) {
-#if defined(HAVE_WAITID) && !defined(__APPLE__)
-        waitid_result_desc.name = MODNAME ".waitid_result";
-        if (PyStructSequence_InitType2(&WaitidResultType, &waitid_result_desc) < 0)
-            return NULL;
-#endif
-
-        stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
-        stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
-        stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
-        stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
-        if (PyStructSequence_InitType2(&StatResultType, &stat_result_desc) < 0)
-            return NULL;
-        structseq_new = StatResultType.tp_new;
-        StatResultType.tp_new = statresult_new;
-
-        statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
-        if (PyStructSequence_InitType2(&StatVFSResultType,
-                                       &statvfs_result_desc) < 0)
-            return NULL;
-#ifdef NEED_TICKS_PER_SECOND
-#  if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
-        ticks_per_second = sysconf(_SC_CLK_TCK);
-#  elif defined(HZ)
-        ticks_per_second = HZ;
-#  else
-        ticks_per_second = 60; /* magic fallback value; may be bogus */
-#  endif
-#endif
-
-#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
-        sched_param_desc.name = MODNAME ".sched_param";
-        if (PyStructSequence_InitType2(&SchedParamType, &sched_param_desc) < 0)
-            return NULL;
-        SchedParamType.tp_new = os_sched_param;
-#endif
-
-        /* initialize TerminalSize_info */
-        if (PyStructSequence_InitType2(&TerminalSizeType,
-                                       &TerminalSize_desc) < 0)
-            return NULL;
-
-        /* initialize scandir types */
-        if (PyType_Ready(&ScandirIteratorType) < 0)
-            return NULL;
-        if (PyType_Ready(&DirEntryType) < 0)
-            return NULL;
-    }
-#if defined(HAVE_WAITID) && !defined(__APPLE__)
-    Py_INCREF((PyObject*) &WaitidResultType);
-    PyModule_AddObject(m, "waitid_result", (PyObject*) &WaitidResultType);
-#endif
-    Py_INCREF((PyObject*) &StatResultType);
-    PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
-    Py_INCREF((PyObject*) &StatVFSResultType);
-    PyModule_AddObject(m, "statvfs_result",
-                       (PyObject*) &StatVFSResultType);
-
-#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
-    Py_INCREF(&SchedParamType);
-    PyModule_AddObject(m, "sched_param", (PyObject *)&SchedParamType);
-#endif
-
-    times_result_desc.name = MODNAME ".times_result";
-    if (PyStructSequence_InitType2(&TimesResultType, &times_result_desc) < 0)
-        return NULL;
-    PyModule_AddObject(m, "times_result", (PyObject *)&TimesResultType);
-
-    uname_result_desc.name = MODNAME ".uname_result";
-    if (PyStructSequence_InitType2(&UnameResultType, &uname_result_desc) < 0)
-        return NULL;
-    PyModule_AddObject(m, "uname_result", (PyObject *)&UnameResultType);
-
-#ifdef __APPLE__
-    /*
-     * Step 2 of weak-linking support on Mac OS X.
-     *
-     * The code below removes functions that are not available on the
-     * currently active platform.
-     *
-     * This block allow one to use a python binary that was build on
-     * OSX 10.4 on OSX 10.3, without losing access to new APIs on
-     * OSX 10.4.
-     */
-#ifdef HAVE_FSTATVFS
-    if (fstatvfs == NULL) {
-        if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
-            return NULL;
-        }
-    }
-#endif /* HAVE_FSTATVFS */
-
-#ifdef HAVE_STATVFS
-    if (statvfs == NULL) {
-        if (PyObject_DelAttrString(m, "statvfs") == -1) {
-            return NULL;
-        }
-    }
-#endif /* HAVE_STATVFS */
-
-# ifdef HAVE_LCHOWN
-    if (lchown == NULL) {
-        if (PyObject_DelAttrString(m, "lchown") == -1) {
-            return NULL;
-        }
-    }
-#endif /* HAVE_LCHOWN */
-
-
-#endif /* __APPLE__ */
-
-    Py_INCREF(&TerminalSizeType);
-    PyModule_AddObject(m, "terminal_size", (PyObject*) &TerminalSizeType);
-
-    billion = PyLong_FromLong(1000000000);
-    if (!billion)
-        return NULL;
-
-    /* suppress "function not used" warnings */
-    {
-    int ignored;
-    fd_specified("", -1);
-    follow_symlinks_specified("", 1);
-    dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
-    dir_fd_converter(Py_None, &ignored);
-    dir_fd_unavailable(Py_None, &ignored);
-    }
-
-    /*
-     * provide list of locally available functions
-     * so os.py can populate support_* lists
-     */
-    list = PyList_New(0);
-    if (!list)
-        return NULL;
-    for (trace = have_functions; *trace; trace++) {
-        PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
-        if (!unicode)
-            return NULL;
-        if (PyList_Append(list, unicode))
-            return NULL;
-        Py_DECREF(unicode);
-    }
-    PyModule_AddObject(m, "_have_functions", list);
-
-    initialized = 1;
-
-    return m;
-}
-
-#ifdef __cplusplus
-}
-#endif
+/*[clinic end generated code: output=d17c625afa72886b input=a9049054013a1b77]*/
diff --git a/Modules/pyexpat.c b/Modules/clinic/pyexpat.c.h
copy from Modules/pyexpat.c
copy to Modules/clinic/pyexpat.c.h
--- a/Modules/pyexpat.c
+++ b/Modules/clinic/pyexpat.c.h
@@ -1,716 +1,5 @@
-#include "Python.h"
-#include <ctype.h>
-
-#include "frameobject.h"
-#include "expat.h"
-
-#include "pyexpat.h"
-
-/* Do not emit Clinic output to a file as that wreaks havoc with conditionally
-   included methods. */
 /*[clinic input]
-module pyexpat
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b168d503a4490c15]*/
-
-#define XML_COMBINED_VERSION (10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION)
-
-static XML_Memory_Handling_Suite ExpatMemoryHandler = {
-    PyObject_Malloc, PyObject_Realloc, PyObject_Free};
-
-enum HandlerTypes {
-    StartElement,
-    EndElement,
-    ProcessingInstruction,
-    CharacterData,
-    UnparsedEntityDecl,
-    NotationDecl,
-    StartNamespaceDecl,
-    EndNamespaceDecl,
-    Comment,
-    StartCdataSection,
-    EndCdataSection,
-    Default,
-    DefaultHandlerExpand,
-    NotStandalone,
-    ExternalEntityRef,
-    StartDoctypeDecl,
-    EndDoctypeDecl,
-    EntityDecl,
-    XmlDecl,
-    ElementDecl,
-    AttlistDecl,
-#if XML_COMBINED_VERSION >= 19504
-    SkippedEntity,
-#endif
-    _DummyDecl
-};
-
-static PyObject *ErrorObject;
-
-/* ----------------------------------------------------- */
-
-/* Declarations for objects of type xmlparser */
-
-typedef struct {
-    PyObject_HEAD
-
-    XML_Parser itself;
-    int ordered_attributes;     /* Return attributes as a list. */
-    int specified_attributes;   /* Report only specified attributes. */
-    int in_callback;            /* Is a callback active? */
-    int ns_prefixes;            /* Namespace-triplets mode? */
-    XML_Char *buffer;           /* Buffer used when accumulating characters */
-                                /* NULL if not enabled */
-    int buffer_size;            /* Size of buffer, in XML_Char units */
-    int buffer_used;            /* Buffer units in use */
-    PyObject *intern;           /* Dictionary to intern strings */
-    PyObject **handlers;
-} xmlparseobject;
-
-#define CHARACTER_DATA_BUFFER_SIZE 8192
-
-static PyTypeObject Xmlparsetype;
-
-typedef void (*xmlhandlersetter)(XML_Parser self, void *meth);
-typedef void* xmlhandler;
-
-struct HandlerInfo {
-    const char *name;
-    xmlhandlersetter setter;
-    xmlhandler handler;
-    PyCodeObject *tb_code;
-    PyObject *nameobj;
-};
-
-static struct HandlerInfo handler_info[64];
-
-/* Set an integer attribute on the error object; return true on success,
- * false on an exception.
- */
-static int
-set_error_attr(PyObject *err, char *name, int value)
-{
-    PyObject *v = PyLong_FromLong(value);
-
-    if (v == NULL || PyObject_SetAttrString(err, name, v) == -1) {
-        Py_XDECREF(v);
-        return 0;
-    }
-    Py_DECREF(v);
-    return 1;
-}
-
-/* Build and set an Expat exception, including positioning
- * information.  Always returns NULL.
- */
-static PyObject *
-set_error(xmlparseobject *self, enum XML_Error code)
-{
-    PyObject *err;
-    PyObject *buffer;
-    XML_Parser parser = self->itself;
-    int lineno = XML_GetErrorLineNumber(parser);
-    int column = XML_GetErrorColumnNumber(parser);
-
-    buffer = PyUnicode_FromFormat("%s: line %i, column %i",
-                                  XML_ErrorString(code), lineno, column);
-    if (buffer == NULL)
-        return NULL;
-    err = PyObject_CallFunction(ErrorObject, "O", buffer);
-    Py_DECREF(buffer);
-    if (  err != NULL
-          && set_error_attr(err, "code", code)
-          && set_error_attr(err, "offset", column)
-          && set_error_attr(err, "lineno", lineno)) {
-        PyErr_SetObject(ErrorObject, err);
-    }
-    Py_XDECREF(err);
-    return NULL;
-}
-
-static int
-have_handler(xmlparseobject *self, int type)
-{
-    PyObject *handler = self->handlers[type];
-    return handler != NULL;
-}
-
-static PyObject *
-get_handler_name(struct HandlerInfo *hinfo)
-{
-    PyObject *name = hinfo->nameobj;
-    if (name == NULL) {
-        name = PyUnicode_FromString(hinfo->name);
-        hinfo->nameobj = name;
-    }
-    Py_XINCREF(name);
-    return name;
-}
-
-
-/* Convert a string of XML_Chars into a Unicode string.
-   Returns None if str is a null pointer. */
-
-static PyObject *
-conv_string_to_unicode(const XML_Char *str)
-{
-    /* XXX currently this code assumes that XML_Char is 8-bit,
-       and hence in UTF-8.  */
-    /* UTF-8 from Expat, Unicode desired */
-    if (str == NULL) {
-        Py_INCREF(Py_None);
-        return Py_None;
-    }
-    return PyUnicode_DecodeUTF8(str, strlen(str), "strict");
-}
-
-static PyObject *
-conv_string_len_to_unicode(const XML_Char *str, int len)
-{
-    /* XXX currently this code assumes that XML_Char is 8-bit,
-       and hence in UTF-8.  */
-    /* UTF-8 from Expat, Unicode desired */
-    if (str == NULL) {
-        Py_INCREF(Py_None);
-        return Py_None;
-    }
-    return PyUnicode_DecodeUTF8((const char *)str, len, "strict");
-}
-
-/* Callback routines */
-
-static void clear_handlers(xmlparseobject *self, int initial);
-
-/* This handler is used when an error has been detected, in the hope
-   that actual parsing can be terminated early.  This will only help
-   if an external entity reference is encountered. */
-static int
-error_external_entity_ref_handler(XML_Parser parser,
-                                  const XML_Char *context,
-                                  const XML_Char *base,
-                                  const XML_Char *systemId,
-                                  const XML_Char *publicId)
-{
-    return 0;
-}
-
-/* Dummy character data handler used when an error (exception) has
-   been detected, and the actual parsing can be terminated early.
-   This is needed since character data handler can't be safely removed
-   from within the character data handler, but can be replaced.  It is
-   used only from the character data handler trampoline, and must be
-   used right after `flag_error()` is called. */
-static void
-noop_character_data_handler(void *userData, const XML_Char *data, int len)
-{
-    /* Do nothing. */
-}
-
-static void
-flag_error(xmlparseobject *self)
-{
-    clear_handlers(self, 0);
-    XML_SetExternalEntityRefHandler(self->itself,
-                                    error_external_entity_ref_handler);
-}
-
-static PyObject*
-call_with_frame(char *funcname, int lineno, PyObject* func, PyObject* args,
-                xmlparseobject *self)
-{
-    PyObject *res;
-
-    res = PyEval_CallObject(func, args);
-    if (res == NULL) {
-        _PyTraceback_Add(funcname, __FILE__, lineno);
-        XML_StopParser(self->itself, XML_FALSE);
-    }
-    return res;
-}
-
-static PyObject*
-string_intern(xmlparseobject *self, const char* str)
-{
-    PyObject *result = conv_string_to_unicode(str);
-    PyObject *value;
-    /* result can be NULL if the unicode conversion failed. */
-    if (!result)
-        return result;
-    if (!self->intern)
-        return result;
-    value = PyDict_GetItem(self->intern, result);
-    if (!value) {
-        if (PyDict_SetItem(self->intern, result, result) == 0)
-            return result;
-        else
-            return NULL;
-    }
-    Py_INCREF(value);
-    Py_DECREF(result);
-    return value;
-}
-
-/* Return 0 on success, -1 on exception.
- * flag_error() will be called before return if needed.
- */
-static int
-call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
-{
-    PyObject *args;
-    PyObject *temp;
-
-    if (!have_handler(self, CharacterData))
-        return -1;
-
-    args = PyTuple_New(1);
-    if (args == NULL)
-        return -1;
-    temp = (conv_string_len_to_unicode(buffer, len));
-    if (temp == NULL) {
-        Py_DECREF(args);
-        flag_error(self);
-        XML_SetCharacterDataHandler(self->itself,
-                                    noop_character_data_handler);
-        return -1;
-    }
-    PyTuple_SET_ITEM(args, 0, temp);
-    /* temp is now a borrowed reference; consider it unused. */
-    self->in_callback = 1;
-    temp = call_with_frame("CharacterData", __LINE__,
-                           self->handlers[CharacterData], args, self);
-    /* temp is an owned reference again, or NULL */
-    self->in_callback = 0;
-    Py_DECREF(args);
-    if (temp == NULL) {
-        flag_error(self);
-        XML_SetCharacterDataHandler(self->itself,
-                                    noop_character_data_handler);
-        return -1;
-    }
-    Py_DECREF(temp);
-    return 0;
-}
-
-static int
-flush_character_buffer(xmlparseobject *self)
-{
-    int rc;
-    if (self->buffer == NULL || self->buffer_used == 0)
-        return 0;
-    rc = call_character_handler(self, self->buffer, self->buffer_used);
-    self->buffer_used = 0;
-    return rc;
-}
-
-static void
-my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
-{
-    xmlparseobject *self = (xmlparseobject *) userData;
-
-    if (PyErr_Occurred())
-        return;
-
-    if (self->buffer == NULL)
-        call_character_handler(self, data, len);
-    else {
-        if ((self->buffer_used + len) > self->buffer_size) {
-            if (flush_character_buffer(self) < 0)
-                return;
-            /* handler might have changed; drop the rest on the floor
-             * if there isn't a handler anymore
-             */
-            if (!have_handler(self, CharacterData))
-                return;
-        }
-        if (len > self->buffer_size) {
-            call_character_handler(self, data, len);
-            self->buffer_used = 0;
-        }
-        else {
-            memcpy(self->buffer + self->buffer_used,
-                   data, len * sizeof(XML_Char));
-            self->buffer_used += len;
-        }
-    }
-}
-
-static void
-my_StartElementHandler(void *userData,
-                       const XML_Char *name, const XML_Char *atts[])
-{
-    xmlparseobject *self = (xmlparseobject *)userData;
-
-    if (have_handler(self, StartElement)) {
-        PyObject *container, *rv, *args;
-        int i, max;
-
-        if (PyErr_Occurred())
-            return;
-
-        if (flush_character_buffer(self) < 0)
-            return;
-        /* Set max to the number of slots filled in atts[]; max/2 is
-         * the number of attributes we need to process.
-         */
-        if (self->specified_attributes) {
-            max = XML_GetSpecifiedAttributeCount(self->itself);
-        }
-        else {
-            max = 0;
-            while (atts[max] != NULL)
-                max += 2;
-        }
-        /* Build the container. */
-        if (self->ordered_attributes)
-            container = PyList_New(max);
-        else
-            container = PyDict_New();
-        if (container == NULL) {
-            flag_error(self);
-            return;
-        }
-        for (i = 0; i < max; i += 2) {
-            PyObject *n = string_intern(self, (XML_Char *) atts[i]);
-            PyObject *v;
-            if (n == NULL) {
-                flag_error(self);
-                Py_DECREF(container);
-                return;
-            }
-            v = conv_string_to_unicode((XML_Char *) atts[i+1]);
-            if (v == NULL) {
-                flag_error(self);
-                Py_DECREF(container);
-                Py_DECREF(n);
-                return;
-            }
-            if (self->ordered_attributes) {
-                PyList_SET_ITEM(container, i, n);
-                PyList_SET_ITEM(container, i+1, v);
-            }
-            else if (PyDict_SetItem(container, n, v)) {
-                flag_error(self);
-                Py_DECREF(n);
-                Py_DECREF(v);
-                return;
-            }
-            else {
-                Py_DECREF(n);
-                Py_DECREF(v);
-            }
-        }
-        args = string_intern(self, name);
-        if (args != NULL)
-            args = Py_BuildValue("(NN)", args, container);
-        if (args == NULL) {
-            Py_DECREF(container);
-            return;
-        }
-        /* Container is now a borrowed reference; ignore it. */
-        self->in_callback = 1;
-        rv = call_with_frame("StartElement", __LINE__,
-                             self->handlers[StartElement], args, self);
-        self->in_callback = 0;
-        Py_DECREF(args);
-        if (rv == NULL) {
-            flag_error(self);
-            return;
-        }
-        Py_DECREF(rv);
-    }
-}
-
-#define RC_HANDLER(RC, NAME, PARAMS, INIT, PARAM_FORMAT, CONVERSION, \
-                RETURN, GETUSERDATA) \
-static RC \
-my_##NAME##Handler PARAMS {\
-    xmlparseobject *self = GETUSERDATA ; \
-    PyObject *args = NULL; \
-    PyObject *rv = NULL; \
-    INIT \
-\
-    if (have_handler(self, NAME)) { \
-        if (PyErr_Occurred()) \
-            return RETURN; \
-        if (flush_character_buffer(self) < 0) \
-            return RETURN; \
-        args = Py_BuildValue PARAM_FORMAT ;\
-        if (!args) { flag_error(self); return RETURN;} \
-        self->in_callback = 1; \
-        rv = call_with_frame(#NAME,__LINE__, \
-                             self->handlers[NAME], args, self); \
-        self->in_callback = 0; \
-        Py_DECREF(args); \
-        if (rv == NULL) { \
-            flag_error(self); \
-            return RETURN; \
-        } \
-        CONVERSION \
-        Py_DECREF(rv); \
-    } \
-    return RETURN; \
-}
-
-#define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
-        RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
-        (xmlparseobject *)userData)
-
-#define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
-        RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
-                        rc = PyLong_AsLong(rv);, rc, \
-        (xmlparseobject *)userData)
-
-VOID_HANDLER(EndElement,
-             (void *userData, const XML_Char *name),
-             ("(N)", string_intern(self, name)))
-
-VOID_HANDLER(ProcessingInstruction,
-             (void *userData,
-              const XML_Char *target,
-              const XML_Char *data),
-             ("(NO&)", string_intern(self, target), conv_string_to_unicode ,data))
-
-VOID_HANDLER(UnparsedEntityDecl,
-             (void *userData,
-              const XML_Char *entityName,
-              const XML_Char *base,
-              const XML_Char *systemId,
-              const XML_Char *publicId,
-              const XML_Char *notationName),
-             ("(NNNNN)",
-              string_intern(self, entityName), string_intern(self, base),
-              string_intern(self, systemId), string_intern(self, publicId),
-              string_intern(self, notationName)))
-
-VOID_HANDLER(EntityDecl,
-             (void *userData,
-              const XML_Char *entityName,
-              int is_parameter_entity,
-              const XML_Char *value,
-              int value_length,
-              const XML_Char *base,
-              const XML_Char *systemId,
-              const XML_Char *publicId,
-              const XML_Char *notationName),
-             ("NiNNNNN",
-              string_intern(self, entityName), is_parameter_entity,
-              (conv_string_len_to_unicode(value, value_length)),
-              string_intern(self, base), string_intern(self, systemId),
-              string_intern(self, publicId),
-              string_intern(self, notationName)))
-
-VOID_HANDLER(XmlDecl,
-             (void *userData,
-              const XML_Char *version,
-              const XML_Char *encoding,
-              int standalone),
-             ("(O&O&i)",
-              conv_string_to_unicode ,version, conv_string_to_unicode ,encoding,
-              standalone))
-
-static PyObject *
-conv_content_model(XML_Content * const model,
-                   PyObject *(*conv_string)(const XML_Char *))
-{
-    PyObject *result = NULL;
-    PyObject *children = PyTuple_New(model->numchildren);
-    int i;
-
-    if (children != NULL) {
-        assert(model->numchildren < INT_MAX);
-        for (i = 0; i < (int)model->numchildren; ++i) {
-            PyObject *child = conv_content_model(&model->children[i],
-                                                 conv_string);
-            if (child == NULL) {
-                Py_XDECREF(children);
-                return NULL;
-            }
-            PyTuple_SET_ITEM(children, i, child);
-        }
-        result = Py_BuildValue("(iiO&N)",
-                               model->type, model->quant,
-                               conv_string,model->name, children);
-    }
-    return result;
-}
-
-static void
-my_ElementDeclHandler(void *userData,
-                      const XML_Char *name,
-                      XML_Content *model)
-{
-    xmlparseobject *self = (xmlparseobject *)userData;
-    PyObject *args = NULL;
-
-    if (have_handler(self, ElementDecl)) {
-        PyObject *rv = NULL;
-        PyObject *modelobj, *nameobj;
-
-        if (PyErr_Occurred())
-            return;
-
-        if (flush_character_buffer(self) < 0)
-            goto finally;
-        modelobj = conv_content_model(model, (conv_string_to_unicode));
-        if (modelobj == NULL) {
-            flag_error(self);
-            goto finally;
-        }
-        nameobj = string_intern(self, name);
-        if (nameobj == NULL) {
-            Py_DECREF(modelobj);
-            flag_error(self);
-            goto finally;
-        }
-        args = Py_BuildValue("NN", nameobj, modelobj);
-        if (args == NULL) {
-            Py_DECREF(modelobj);
-            flag_error(self);
-            goto finally;
-        }
-        self->in_callback = 1;
-        rv = call_with_frame("ElementDecl", __LINE__,
-                             self->handlers[ElementDecl], args, self);
-        self->in_callback = 0;
-        if (rv == NULL) {
-            flag_error(self);
-            goto finally;
-        }
-        Py_DECREF(rv);
-    }
- finally:
-    Py_XDECREF(args);
-    XML_FreeContentModel(self->itself, model);
-    return;
-}
-
-VOID_HANDLER(AttlistDecl,
-             (void *userData,
-              const XML_Char *elname,
-              const XML_Char *attname,
-              const XML_Char *att_type,
-              const XML_Char *dflt,
-              int isrequired),
-             ("(NNO&O&i)",
-              string_intern(self, elname), string_intern(self, attname),
-              conv_string_to_unicode ,att_type, conv_string_to_unicode ,dflt,
-              isrequired))
-
-#if XML_COMBINED_VERSION >= 19504
-VOID_HANDLER(SkippedEntity,
-             (void *userData,
-              const XML_Char *entityName,
-              int is_parameter_entity),
-             ("Ni",
-              string_intern(self, entityName), is_parameter_entity))
-#endif
-
-VOID_HANDLER(NotationDecl,
-                (void *userData,
-                        const XML_Char *notationName,
-                        const XML_Char *base,
-                        const XML_Char *systemId,
-                        const XML_Char *publicId),
-                ("(NNNN)",
-                 string_intern(self, notationName), string_intern(self, base),
-                 string_intern(self, systemId), string_intern(self, publicId)))
-
-VOID_HANDLER(StartNamespaceDecl,
-                (void *userData,
-                      const XML_Char *prefix,
-                      const XML_Char *uri),
-                ("(NN)",
-                 string_intern(self, prefix), string_intern(self, uri)))
-
-VOID_HANDLER(EndNamespaceDecl,
-                (void *userData,
-                    const XML_Char *prefix),
-                ("(N)", string_intern(self, prefix)))
-
-VOID_HANDLER(Comment,
-               (void *userData, const XML_Char *data),
-                ("(O&)", conv_string_to_unicode ,data))
-
-VOID_HANDLER(StartCdataSection,
-               (void *userData),
-                ("()"))
-
-VOID_HANDLER(EndCdataSection,
-               (void *userData),
-                ("()"))
-
-VOID_HANDLER(Default,
-              (void *userData, const XML_Char *s, int len),
-              ("(N)", (conv_string_len_to_unicode(s,len))))
-
-VOID_HANDLER(DefaultHandlerExpand,
-              (void *userData, const XML_Char *s, int len),
-              ("(N)", (conv_string_len_to_unicode(s,len))))
-
-INT_HANDLER(NotStandalone,
-                (void *userData),
-                ("()"))
-
-RC_HANDLER(int, ExternalEntityRef,
-                (XML_Parser parser,
-                    const XML_Char *context,
-                    const XML_Char *base,
-                    const XML_Char *systemId,
-                    const XML_Char *publicId),
-                int rc=0;,
-                ("(O&NNN)",
-                 conv_string_to_unicode ,context, string_intern(self, base),
-                 string_intern(self, systemId), string_intern(self, publicId)),
-                rc = PyLong_AsLong(rv);, rc,
-                XML_GetUserData(parser))
-
-/* XXX UnknownEncodingHandler */
-
-VOID_HANDLER(StartDoctypeDecl,
-             (void *userData, const XML_Char *doctypeName,
-              const XML_Char *sysid, const XML_Char *pubid,
-              int has_internal_subset),
-             ("(NNNi)", string_intern(self, doctypeName),
-              string_intern(self, sysid), string_intern(self, pubid),
-              has_internal_subset))
-
-VOID_HANDLER(EndDoctypeDecl, (void *userData), ("()"))
-
-/* ---------------------------------------------------------------- */
-/*[clinic input]
-class pyexpat.xmlparser "xmlparseobject *" "&Xmlparsetype"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2393162385232e1c]*/
-
-
-static PyObject *
-get_parse_result(xmlparseobject *self, int rv)
-{
-    if (PyErr_Occurred()) {
-        return NULL;
-    }
-    if (rv == 0) {
-        return set_error(self, XML_GetErrorCode(self->itself));
-    }
-    if (flush_character_buffer(self) < 0) {
-        return NULL;
-    }
-    return PyLong_FromLong(rv);
-}
-
-#define MAX_CHUNK_SIZE (1 << 20)
-
-/*[clinic input]
-pyexpat.xmlparser.Parse
-
-    data: object
-    isFinal: int = 0
-    /
-
-Parse XML data.
-
-`isfinal' should be true at end of input.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(pyexpat_xmlparser_Parse__doc__,
@@ -744,98 +33,6 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyObject *data, int isFinal)
-/*[clinic end generated code: output=65b1652b01f20856 input=e37b81b8948ca7e0]*/
-{
-    const char *s;
-    Py_ssize_t slen;
-    Py_buffer view;
-    int rc;
-
-    if (PyUnicode_Check(data)) {
-        view.buf = NULL;
-        s = PyUnicode_AsUTF8AndSize(data, &slen);
-        if (s == NULL)
-            return NULL;
-        /* Explicitly set UTF-8 encoding. Return code ignored. */
-        (void)XML_SetEncoding(self->itself, "utf-8");
-    }
-    else {
-        if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
-            return NULL;
-        s = view.buf;
-        slen = view.len;
-    }
-
-    while (slen > MAX_CHUNK_SIZE) {
-        rc = XML_Parse(self->itself, s, MAX_CHUNK_SIZE, 0);
-        if (!rc)
-            goto done;
-        s += MAX_CHUNK_SIZE;
-        slen -= MAX_CHUNK_SIZE;
-    }
-    assert(MAX_CHUNK_SIZE < INT_MAX && slen < INT_MAX);
-    rc = XML_Parse(self->itself, s, (int)slen, isFinal);
-
-done:
-    if (view.buf != NULL)
-        PyBuffer_Release(&view);
-    return get_parse_result(self, rc);
-}
-
-/* File reading copied from cPickle */
-
-#define BUF_SIZE 2048
-
-static int
-readinst(char *buf, int buf_size, PyObject *meth)
-{
-    PyObject *str;
-    Py_ssize_t len;
-    char *ptr;
-
-    str = PyObject_CallFunction(meth, "n", buf_size);
-    if (str == NULL)
-        goto error;
-
-    if (PyBytes_Check(str))
-        ptr = PyBytes_AS_STRING(str);
-    else if (PyByteArray_Check(str))
-        ptr = PyByteArray_AS_STRING(str);
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "read() did not return a bytes object (type=%.400s)",
-                     Py_TYPE(str)->tp_name);
-        goto error;
-    }
-    len = Py_SIZE(str);
-    if (len > buf_size) {
-        PyErr_Format(PyExc_ValueError,
-                     "read() returned too much data: "
-                     "%i bytes requested, %zd returned",
-                     buf_size, len);
-        goto error;
-    }
-    memcpy(buf, ptr, len);
-    Py_DECREF(str);
-    /* len <= buf_size <= INT_MAX */
-    return (int)len;
-
-error:
-    Py_XDECREF(str);
-    return -1;
-}
-
-/*[clinic input]
-pyexpat.xmlparser.ParseFile
-
-    file: object
-    /
-
-Parse XML data from file-like object.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_xmlparser_ParseFile__doc__,
 "ParseFile($self, file, /)\n"
 "--\n"
@@ -845,55 +42,6 @@
 #define PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF    \
     {"ParseFile", (PyCFunction)pyexpat_xmlparser_ParseFile, METH_O, pyexpat_xmlparser_ParseFile__doc__},
 
-static PyObject *
-pyexpat_xmlparser_ParseFile(xmlparseobject *self, PyObject *file)
-/*[clinic end generated code: output=2e13803c3d8c22b2 input=fbb5a12b6038d735]*/
-{
-    int rv = 1;
-    PyObject *readmethod = NULL;
-    _Py_IDENTIFIER(read);
-
-    readmethod = _PyObject_GetAttrId(file, &PyId_read);
-    if (readmethod == NULL) {
-        PyErr_SetString(PyExc_TypeError,
-                        "argument must have 'read' attribute");
-        return NULL;
-    }
-    for (;;) {
-        int bytes_read;
-        void *buf = XML_GetBuffer(self->itself, BUF_SIZE);
-        if (buf == NULL) {
-            Py_XDECREF(readmethod);
-            return get_parse_result(self, 0);
-        }
-
-        bytes_read = readinst(buf, BUF_SIZE, readmethod);
-        if (bytes_read < 0) {
-            Py_DECREF(readmethod);
-            return NULL;
-        }
-        rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0);
-        if (PyErr_Occurred()) {
-            Py_XDECREF(readmethod);
-            return NULL;
-        }
-
-        if (!rv || bytes_read == 0)
-            break;
-    }
-    Py_XDECREF(readmethod);
-    return get_parse_result(self, rv);
-}
-
-/*[clinic input]
-pyexpat.xmlparser.SetBase
-
-    base: str
-    /
-
-Set the base URL for the parser.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_xmlparser_SetBase__doc__,
 "SetBase($self, base, /)\n"
 "--\n"
@@ -922,22 +70,6 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base)
-/*[clinic end generated code: output=5bdb49f6689a5f93 input=c684e5de895ee1a8]*/
-{
-    if (!XML_SetBase(self->itself, base)) {
-        return PyErr_NoMemory();
-    }
-    Py_RETURN_NONE;
-}
-
-/*[clinic input]
-pyexpat.xmlparser.GetBase
-
-Return base URL string for the parser.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_xmlparser_GetBase__doc__,
 "GetBase($self, /)\n"
 "--\n"
@@ -956,22 +88,6 @@
     return pyexpat_xmlparser_GetBase_impl(self);
 }
 
-static PyObject *
-pyexpat_xmlparser_GetBase_impl(xmlparseobject *self)
-/*[clinic end generated code: output=ef6046ee28f2b8ee input=918d71c38009620e]*/
-{
-    return Py_BuildValue("z", XML_GetBase(self->itself));
-}
-
-/*[clinic input]
-pyexpat.xmlparser.GetInputContext
-
-Return the untranslated text of the input that caused the current event.
-
-If the event was generated by a large amount of text (such as a start tag
-for an element with many attributes), not all of the text may be available.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_xmlparser_GetInputContext__doc__,
 "GetInputContext($self, /)\n"
 "--\n"
@@ -993,35 +109,6 @@
     return pyexpat_xmlparser_GetInputContext_impl(self);
 }
 
-static PyObject *
-pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self)
-/*[clinic end generated code: output=62ff03390f074cd2 input=034df8712db68379]*/
-{
-    if (self->in_callback) {
-        int offset, size;
-        const char *buffer
-            = XML_GetInputContext(self->itself, &offset, &size);
-
-        if (buffer != NULL)
-            return PyBytes_FromStringAndSize(buffer + offset,
-                                              size - offset);
-        else
-            Py_RETURN_NONE;
-    }
-    else
-        Py_RETURN_NONE;
-}
-
-/*[clinic input]
-pyexpat.xmlparser.ExternalEntityParserCreate
-
-    context: str(nullable=True)
-    encoding: str = NULL
-    /
-
-Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_xmlparser_ExternalEntityParserCreate__doc__,
 "ExternalEntityParserCreate($self, context, encoding=None, /)\n"
 "--\n"
@@ -1051,82 +138,6 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self, const char *context, const char *encoding)
-/*[clinic end generated code: output=4948c35f3dd01133 input=283206575d960272]*/
-{
-    xmlparseobject *new_parser;
-    int i;
-
-    new_parser = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
-    if (new_parser == NULL)
-        return NULL;
-    new_parser->buffer_size = self->buffer_size;
-    new_parser->buffer_used = 0;
-    new_parser->buffer = NULL;
-    new_parser->ordered_attributes = self->ordered_attributes;
-    new_parser->specified_attributes = self->specified_attributes;
-    new_parser->in_callback = 0;
-    new_parser->ns_prefixes = self->ns_prefixes;
-    new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
-                                                        encoding);
-    new_parser->handlers = 0;
-    new_parser->intern = self->intern;
-    Py_XINCREF(new_parser->intern);
-    PyObject_GC_Track(new_parser);
-
-    if (self->buffer != NULL) {
-        new_parser->buffer = PyMem_Malloc(new_parser->buffer_size);
-        if (new_parser->buffer == NULL) {
-            Py_DECREF(new_parser);
-            return PyErr_NoMemory();
-        }
-    }
-    if (!new_parser->itself) {
-        Py_DECREF(new_parser);
-        return PyErr_NoMemory();
-    }
-
-    XML_SetUserData(new_parser->itself, (void *)new_parser);
-
-    /* allocate and clear handlers first */
-    for (i = 0; handler_info[i].name != NULL; i++)
-        /* do nothing */;
-
-    new_parser->handlers = PyMem_New(PyObject *, i);
-    if (!new_parser->handlers) {
-        Py_DECREF(new_parser);
-        return PyErr_NoMemory();
-    }
-    clear_handlers(new_parser, 1);
-
-    /* then copy handlers from self */
-    for (i = 0; handler_info[i].name != NULL; i++) {
-        PyObject *handler = self->handlers[i];
-        if (handler != NULL) {
-            Py_INCREF(handler);
-            new_parser->handlers[i] = handler;
-            handler_info[i].setter(new_parser->itself,
-                                   handler_info[i].handler);
-        }
-    }
-    return (PyObject *)new_parser;
-}
-
-/*[clinic input]
-pyexpat.xmlparser.SetParamEntityParsing
-
-    flag: int
-    /
-
-Controls parsing of parameter entities (including the external DTD subset).
-
-Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,
-XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and
-XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag
-was successful.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_xmlparser_SetParamEntityParsing__doc__,
 "SetParamEntityParsing($self, flag, /)\n"
 "--\n"
@@ -1160,28 +171,7 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag)
-/*[clinic end generated code: output=0f820882bc7768cc input=8aea19b4b15e9af1]*/
-{
-    flag = XML_SetParamEntityParsing(self->itself, flag);
-    return PyLong_FromLong(flag);
-}
-
-
-#if XML_COMBINED_VERSION >= 19505
-/*[clinic input]
-pyexpat.xmlparser.UseForeignDTD
-
-    flag: bool = True
-    /
-
-Allows the application to provide an artificial external subset if one is not specified as part of the document instance.
-
-This readily allows the use of a 'default' document type controlled by the
-application, while still getting the advantage of providing document type
-information to the parser. 'flag' defaults to True if not provided.
-[clinic start generated code]*/
+#if (XML_COMBINED_VERSION >= 19505)
 
 PyDoc_STRVAR(pyexpat_xmlparser_UseForeignDTD__doc__,
 "UseForeignDTD($self, flag=True, /)\n"
@@ -1215,24 +205,7 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, int flag)
-/*[clinic end generated code: output=22e924ae6cad67d6 input=78144c519d116a6e]*/
-{
-    enum XML_Error rc;
-
-    rc = XML_UseForeignDTD(self->itself, flag ? XML_TRUE : XML_FALSE);
-    if (rc != XML_ERROR_NONE) {
-        return set_error(self, rc);
-    }
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-#endif
-
-/*[clinic input]
-pyexpat.xmlparser.__dir__
-[clinic start generated code]*/
+#endif /* (XML_COMBINED_VERSION >= 19505) */
 
 PyDoc_STRVAR(pyexpat_xmlparser___dir____doc__,
 "__dir__($self, /)\n"
@@ -1250,521 +223,6 @@
     return pyexpat_xmlparser___dir___impl(self);
 }
 
-static PyObject *
-pyexpat_xmlparser___dir___impl(xmlparseobject *self)
-/*[clinic end generated code: output=1ed6efe83bc304cc input=76aa455f2a661384]*/
-{
-#define APPEND(list, str)                               \
-        do {                                            \
-                PyObject *o = PyUnicode_FromString(str);        \
-                if (o != NULL)                          \
-                        PyList_Append(list, o);         \
-                Py_XDECREF(o);                          \
-        } while (0)
-
-    int i;
-    PyObject *rc = PyList_New(0);
-    if (!rc)
-        return NULL;
-    for (i = 0; handler_info[i].name != NULL; i++) {
-        PyObject *o = get_handler_name(&handler_info[i]);
-        if (o != NULL)
-            PyList_Append(rc, o);
-        Py_XDECREF(o);
-    }
-    APPEND(rc, "ErrorCode");
-    APPEND(rc, "ErrorLineNumber");
-    APPEND(rc, "ErrorColumnNumber");
-    APPEND(rc, "ErrorByteIndex");
-    APPEND(rc, "CurrentLineNumber");
-    APPEND(rc, "CurrentColumnNumber");
-    APPEND(rc, "CurrentByteIndex");
-    APPEND(rc, "buffer_size");
-    APPEND(rc, "buffer_text");
-    APPEND(rc, "buffer_used");
-    APPEND(rc, "namespace_prefixes");
-    APPEND(rc, "ordered_attributes");
-    APPEND(rc, "specified_attributes");
-    APPEND(rc, "intern");
-
-#undef APPEND
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(rc);
-        rc = NULL;
-    }
-
-    return rc;
-}
-
-static struct PyMethodDef xmlparse_methods[] = {
-    PYEXPAT_XMLPARSER_PARSE_METHODDEF
-    PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF
-    PYEXPAT_XMLPARSER_SETBASE_METHODDEF
-    PYEXPAT_XMLPARSER_GETBASE_METHODDEF
-    PYEXPAT_XMLPARSER_GETINPUTCONTEXT_METHODDEF
-    PYEXPAT_XMLPARSER_EXTERNALENTITYPARSERCREATE_METHODDEF
-    PYEXPAT_XMLPARSER_SETPARAMENTITYPARSING_METHODDEF
-#if XML_COMBINED_VERSION >= 19505
-    PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
-#endif
-    PYEXPAT_XMLPARSER___DIR___METHODDEF
-    {NULL, NULL}  /* sentinel */
-};
-
-/* ---------- */
-
-
-
-/* pyexpat international encoding support.
-   Make it as simple as possible.
-*/
-
-static int
-PyUnknownEncodingHandler(void *encodingHandlerData,
-                         const XML_Char *name,
-                         XML_Encoding *info)
-{
-    static unsigned char template_buffer[256] = {0};
-    PyObject* u;
-    int i;
-    void *data;
-    unsigned int kind;
-
-    if (PyErr_Occurred())
-        return XML_STATUS_ERROR;
-
-    if (template_buffer[1] == 0) {
-        for (i = 0; i < 256; i++)
-            template_buffer[i] = i;
-    }
-
-    u = PyUnicode_Decode((char*) template_buffer, 256, name, "replace");
-    if (u == NULL || PyUnicode_READY(u)) {
-        Py_XDECREF(u);
-        return XML_STATUS_ERROR;
-    }
-
-    if (PyUnicode_GET_LENGTH(u) != 256) {
-        Py_DECREF(u);
-        PyErr_SetString(PyExc_ValueError,
-                        "multi-byte encodings are not supported");
-        return XML_STATUS_ERROR;
-    }
-
-    kind = PyUnicode_KIND(u);
-    data = PyUnicode_DATA(u);
-    for (i = 0; i < 256; i++) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-        if (ch != Py_UNICODE_REPLACEMENT_CHARACTER)
-            info->map[i] = ch;
-        else
-            info->map[i] = -1;
-    }
-
-    info->data = NULL;
-    info->convert = NULL;
-    info->release = NULL;
-    Py_DECREF(u);
-
-    return XML_STATUS_OK;
-}
-
-
-static PyObject *
-newxmlparseobject(const char *encoding, const char *namespace_separator, PyObject *intern)
-{
-    int i;
-    xmlparseobject *self;
-
-    self = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
-    if (self == NULL)
-        return NULL;
-
-    self->buffer = NULL;
-    self->buffer_size = CHARACTER_DATA_BUFFER_SIZE;
-    self->buffer_used = 0;
-    self->ordered_attributes = 0;
-    self->specified_attributes = 0;
-    self->in_callback = 0;
-    self->ns_prefixes = 0;
-    self->handlers = NULL;
-    self->intern = intern;
-    Py_XINCREF(self->intern);
-    PyObject_GC_Track(self);
-
-    /* namespace_separator is either NULL or contains one char + \0 */
-    self->itself = XML_ParserCreate_MM(encoding, &ExpatMemoryHandler,
-                                       namespace_separator);
-    if (self->itself == NULL) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "XML_ParserCreate failed");
-        Py_DECREF(self);
-        return NULL;
-    }
-#if ((XML_MAJOR_VERSION >= 2) && (XML_MINOR_VERSION >= 1)) || defined(XML_HAS_SET_HASH_SALT)
-    /* This feature was added upstream in libexpat 2.1.0.  Our expat copy
-     * has a backport of this feature where we also define XML_HAS_SET_HASH_SALT
-     * to indicate that we can still use it. */
-    XML_SetHashSalt(self->itself,
-                    (unsigned long)_Py_HashSecret.expat.hashsalt);
-#endif
-    XML_SetUserData(self->itself, (void *)self);
-    XML_SetUnknownEncodingHandler(self->itself,
-                  (XML_UnknownEncodingHandler) PyUnknownEncodingHandler, NULL);
-
-    for (i = 0; handler_info[i].name != NULL; i++)
-        /* do nothing */;
-
-    self->handlers = PyMem_New(PyObject *, i);
-    if (!self->handlers) {
-        Py_DECREF(self);
-        return PyErr_NoMemory();
-    }
-    clear_handlers(self, 1);
-
-    return (PyObject*)self;
-}
-
-
-static void
-xmlparse_dealloc(xmlparseobject *self)
-{
-    int i;
-    PyObject_GC_UnTrack(self);
-    if (self->itself != NULL)
-        XML_ParserFree(self->itself);
-    self->itself = NULL;
-
-    if (self->handlers != NULL) {
-        PyObject *temp;
-        for (i = 0; handler_info[i].name != NULL; i++) {
-            temp = self->handlers[i];
-            self->handlers[i] = NULL;
-            Py_XDECREF(temp);
-        }
-        PyMem_Free(self->handlers);
-        self->handlers = NULL;
-    }
-    if (self->buffer != NULL) {
-        PyMem_Free(self->buffer);
-        self->buffer = NULL;
-    }
-    Py_XDECREF(self->intern);
-    PyObject_GC_Del(self);
-}
-
-static int
-handlername2int(PyObject *name)
-{
-    int i;
-    for (i = 0; handler_info[i].name != NULL; i++) {
-        if (PyUnicode_CompareWithASCIIString(
-                name, handler_info[i].name) == 0) {
-            return i;
-        }
-    }
-    return -1;
-}
-
-static PyObject *
-get_pybool(int istrue)
-{
-    PyObject *result = istrue ? Py_True : Py_False;
-    Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
-{
-    Py_UCS4 first_char;
-    int handlernum = -1;
-
-    if (!PyUnicode_Check(nameobj))
-        goto generic;
-    if (PyUnicode_READY(nameobj))
-        return NULL;
-
-    handlernum = handlername2int(nameobj);
-
-    if (handlernum != -1) {
-        PyObject *result = self->handlers[handlernum];
-        if (result == NULL)
-            result = Py_None;
-        Py_INCREF(result);
-        return result;
-    }
-
-    first_char = PyUnicode_READ_CHAR(nameobj, 0);
-    if (first_char == 'E') {
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorCode") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetErrorCode(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorLineNumber") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetErrorLineNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorColumnNumber") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetErrorColumnNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorByteIndex") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetErrorByteIndex(self->itself));
-    }
-    if (first_char == 'C') {
-        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentLineNumber") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetCurrentLineNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentColumnNumber") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetCurrentColumnNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentByteIndex") == 0)
-            return PyLong_FromLong((long)
-                                  XML_GetCurrentByteIndex(self->itself));
-    }
-    if (first_char == 'b') {
-        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_size") == 0)
-            return PyLong_FromLong((long) self->buffer_size);
-        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_text") == 0)
-            return get_pybool(self->buffer != NULL);
-        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_used") == 0)
-            return PyLong_FromLong((long) self->buffer_used);
-    }
-    if (PyUnicode_CompareWithASCIIString(nameobj, "namespace_prefixes") == 0)
-        return get_pybool(self->ns_prefixes);
-    if (PyUnicode_CompareWithASCIIString(nameobj, "ordered_attributes") == 0)
-        return get_pybool(self->ordered_attributes);
-    if (PyUnicode_CompareWithASCIIString(nameobj, "specified_attributes") == 0)
-        return get_pybool((long) self->specified_attributes);
-    if (PyUnicode_CompareWithASCIIString(nameobj, "intern") == 0) {
-        if (self->intern == NULL) {
-            Py_INCREF(Py_None);
-            return Py_None;
-        }
-        else {
-            Py_INCREF(self->intern);
-            return self->intern;
-        }
-    }
-  generic:
-    return PyObject_GenericGetAttr((PyObject*)self, nameobj);
-}
-
-static int
-sethandler(xmlparseobject *self, PyObject *name, PyObject* v)
-{
-    int handlernum = handlername2int(name);
-    if (handlernum >= 0) {
-        xmlhandler c_handler = NULL;
-        PyObject *temp = self->handlers[handlernum];
-
-        if (v == Py_None) {
-            /* If this is the character data handler, and a character
-               data handler is already active, we need to be more
-               careful.  What we can safely do is replace the existing
-               character data handler callback function with a no-op
-               function that will refuse to call Python.  The downside
-               is that this doesn't completely remove the character
-               data handler from the C layer if there's any callback
-               active, so Expat does a little more work than it
-               otherwise would, but that's really an odd case.  A more
-               elaborate system of handlers and state could remove the
-               C handler more effectively. */
-            if (handlernum == CharacterData && self->in_callback)
-                c_handler = noop_character_data_handler;
-            v = NULL;
-        }
-        else if (v != NULL) {
-            Py_INCREF(v);
-            c_handler = handler_info[handlernum].handler;
-        }
-        self->handlers[handlernum] = v;
-        Py_XDECREF(temp);
-        handler_info[handlernum].setter(self->itself, c_handler);
-        return 1;
-    }
-    return 0;
-}
-
-static int
-xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
-{
-    /* Set attribute 'name' to value 'v'. v==NULL means delete */
-    if (v == NULL) {
-        PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
-        return -1;
-    }
-    assert(PyUnicode_Check(name));
-    if (PyUnicode_CompareWithASCIIString(name, "buffer_text") == 0) {
-        int b = PyObject_IsTrue(v);
-        if (b < 0)
-            return -1;
-        if (b) {
-            if (self->buffer == NULL) {
-                self->buffer = PyMem_Malloc(self->buffer_size);
-                if (self->buffer == NULL) {
-                    PyErr_NoMemory();
-                    return -1;
-                }
-                self->buffer_used = 0;
-            }
-        }
-        else if (self->buffer != NULL) {
-            if (flush_character_buffer(self) < 0)
-                return -1;
-            PyMem_Free(self->buffer);
-            self->buffer = NULL;
-        }
-        return 0;
-    }
-    if (PyUnicode_CompareWithASCIIString(name, "namespace_prefixes") == 0) {
-        int b = PyObject_IsTrue(v);
-        if (b < 0)
-            return -1;
-        self->ns_prefixes = b;
-        XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
-        return 0;
-    }
-    if (PyUnicode_CompareWithASCIIString(name, "ordered_attributes") == 0) {
-        int b = PyObject_IsTrue(v);
-        if (b < 0)
-            return -1;
-        self->ordered_attributes = b;
-        return 0;
-    }
-    if (PyUnicode_CompareWithASCIIString(name, "specified_attributes") == 0) {
-        int b = PyObject_IsTrue(v);
-        if (b < 0)
-            return -1;
-        self->specified_attributes = b;
-        return 0;
-    }
-
-    if (PyUnicode_CompareWithASCIIString(name, "buffer_size") == 0) {
-      long new_buffer_size;
-      if (!PyLong_Check(v)) {
-        PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
-        return -1;
-      }
-
-      new_buffer_size=PyLong_AS_LONG(v);
-      /* trivial case -- no change */
-      if (new_buffer_size == self->buffer_size) {
-        return 0;
-      }
-
-      if (new_buffer_size <= 0) {
-        PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
-        return -1;
-      }
-
-      /* check maximum */
-      if (new_buffer_size > INT_MAX) {
-        char errmsg[100];
-        sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
-        PyErr_SetString(PyExc_ValueError, errmsg);
-        return -1;
-      }
-
-      if (self->buffer != NULL) {
-        /* there is already a buffer */
-        if (self->buffer_used != 0) {
-            if (flush_character_buffer(self) < 0) {
-                return -1;
-            }
-        }
-        /* free existing buffer */
-        PyMem_Free(self->buffer);
-      }
-      self->buffer = PyMem_Malloc(new_buffer_size);
-      if (self->buffer == NULL) {
-        PyErr_NoMemory();
-        return -1;
-      }
-      self->buffer_size = new_buffer_size;
-      return 0;
-    }
-
-    if (PyUnicode_CompareWithASCIIString(name, "CharacterDataHandler") == 0) {
-        /* If we're changing the character data handler, flush all
-         * cached data with the old handler.  Not sure there's a
-         * "right" thing to do, though, but this probably won't
-         * happen.
-         */
-        if (flush_character_buffer(self) < 0)
-            return -1;
-    }
-    if (sethandler(self, name, v)) {
-        return 0;
-    }
-    PyErr_SetObject(PyExc_AttributeError, name);
-    return -1;
-}
-
-static int
-xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg)
-{
-    int i;
-    for (i = 0; handler_info[i].name != NULL; i++)
-        Py_VISIT(op->handlers[i]);
-    return 0;
-}
-
-static int
-xmlparse_clear(xmlparseobject *op)
-{
-    clear_handlers(op, 0);
-    Py_CLEAR(op->intern);
-    return 0;
-}
-
-PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
-
-static PyTypeObject Xmlparsetype = {
-        PyVarObject_HEAD_INIT(NULL, 0)
-        "pyexpat.xmlparser",            /*tp_name*/
-        sizeof(xmlparseobject),         /*tp_basicsize*/
-        0,                              /*tp_itemsize*/
-        /* methods */
-        (destructor)xmlparse_dealloc,   /*tp_dealloc*/
-        (printfunc)0,           /*tp_print*/
-        0,                      /*tp_getattr*/
-        0,  /*tp_setattr*/
-        0,                      /*tp_reserved*/
-        (reprfunc)0,            /*tp_repr*/
-        0,                      /*tp_as_number*/
-        0,              /*tp_as_sequence*/
-        0,              /*tp_as_mapping*/
-        (hashfunc)0,            /*tp_hash*/
-        (ternaryfunc)0,         /*tp_call*/
-        (reprfunc)0,            /*tp_str*/
-        (getattrofunc)xmlparse_getattro, /* tp_getattro */
-        (setattrofunc)xmlparse_setattro,              /* tp_setattro */
-        0,              /* tp_as_buffer */
-        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
-        Xmlparsetype__doc__, /* tp_doc - Documentation string */
-        (traverseproc)xmlparse_traverse,        /* tp_traverse */
-        (inquiry)xmlparse_clear,                /* tp_clear */
-        0,                              /* tp_richcompare */
-        0,                              /* tp_weaklistoffset */
-        0,                              /* tp_iter */
-        0,                              /* tp_iternext */
-        xmlparse_methods,               /* tp_methods */
-};
-
-/* End of code for xmlparser objects */
-/* -------------------------------------------------------- */
-
-/*[clinic input]
-pyexpat.ParserCreate
-
-    encoding: str(nullable=True) = NULL
-    namespace_separator: str(nullable=True) = NULL
-    intern: object = NULL
-
-Return a new XML parser object.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_ParserCreate__doc__,
 "ParserCreate($module, /, encoding=None, namespace_separator=None,\n"
 "             intern=None)\n"
@@ -1797,51 +255,6 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding, const char *namespace_separator, PyObject *intern)
-/*[clinic end generated code: output=4fc027dd33b7a2ac input=71b9f471aa6f8f86]*/
-{
-    PyObject *result;
-    int intern_decref = 0;
-
-    if (namespace_separator != NULL
-        && strlen(namespace_separator) > 1) {
-        PyErr_SetString(PyExc_ValueError,
-                        "namespace_separator must be at most one"
-                        " character, omitted, or None");
-        return NULL;
-    }
-    /* Explicitly passing None means no interning is desired.
-       Not passing anything means that a new dictionary is used. */
-    if (intern == Py_None)
-        intern = NULL;
-    else if (intern == NULL) {
-        intern = PyDict_New();
-        if (!intern)
-            return NULL;
-        intern_decref = 1;
-    }
-    else if (!PyDict_Check(intern)) {
-        PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
-        return NULL;
-    }
-
-    result = newxmlparseobject(encoding, namespace_separator, intern);
-    if (intern_decref) {
-        Py_DECREF(intern);
-    }
-    return result;
-}
-
-/*[clinic input]
-pyexpat.ErrorString
-
-    code: long
-    /
-
-Returns string error for given number.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(pyexpat_ErrorString__doc__,
 "ErrorString($module, code, /)\n"
 "--\n"
@@ -1870,390 +283,7 @@
     return return_value;
 }
 
-static PyObject *
-pyexpat_ErrorString_impl(PyModuleDef *module, long code)
-/*[clinic end generated code: output=c70f3cd82bfaf067 input=cc67de010d9e62b3]*/
-{
-    return Py_BuildValue("z", XML_ErrorString((int)code));
-}
-
-/* List of methods defined in the module */
-
-static struct PyMethodDef pyexpat_methods[] = {
-    PYEXPAT_PARSERCREATE_METHODDEF
-    PYEXPAT_ERRORSTRING_METHODDEF
-    {NULL, NULL}  /* sentinel */
-};
-
-/* Module docstring */
-
-PyDoc_STRVAR(pyexpat_module_documentation,
-"Python wrapper for Expat parser.");
-
-/* Initialization function for the module */
-
-#ifndef MODULE_NAME
-#define MODULE_NAME "pyexpat"
-#endif
-
-#ifndef MODULE_INITFUNC
-#define MODULE_INITFUNC PyInit_pyexpat
-#endif
-
-static struct PyModuleDef pyexpatmodule = {
-        PyModuleDef_HEAD_INIT,
-        MODULE_NAME,
-        pyexpat_module_documentation,
-        -1,
-        pyexpat_methods,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-MODULE_INITFUNC(void)
-{
-    PyObject *m, *d;
-    PyObject *errmod_name = PyUnicode_FromString(MODULE_NAME ".errors");
-    PyObject *errors_module;
-    PyObject *modelmod_name;
-    PyObject *model_module;
-    PyObject *sys_modules;
-    PyObject *tmpnum, *tmpstr;
-    PyObject *codes_dict;
-    PyObject *rev_codes_dict;
-    int res;
-    static struct PyExpat_CAPI capi;
-    PyObject *capi_object;
-
-    if (errmod_name == NULL)
-        return NULL;
-    modelmod_name = PyUnicode_FromString(MODULE_NAME ".model");
-    if (modelmod_name == NULL)
-        return NULL;
-
-    if (PyType_Ready(&Xmlparsetype) < 0)
-        return NULL;
-
-    /* Create the module and add the functions */
-    m = PyModule_Create(&pyexpatmodule);
-    if (m == NULL)
-        return NULL;
-
-    /* Add some symbolic constants to the module */
-    if (ErrorObject == NULL) {
-        ErrorObject = PyErr_NewException("xml.parsers.expat.ExpatError",
-                                         NULL, NULL);
-        if (ErrorObject == NULL)
-            return NULL;
-    }
-    Py_INCREF(ErrorObject);
-    PyModule_AddObject(m, "error", ErrorObject);
-    Py_INCREF(ErrorObject);
-    PyModule_AddObject(m, "ExpatError", ErrorObject);
-    Py_INCREF(&Xmlparsetype);
-    PyModule_AddObject(m, "XMLParserType", (PyObject *) &Xmlparsetype);
-
-    PyModule_AddStringConstant(m, "EXPAT_VERSION",
-                               XML_ExpatVersion());
-    {
-        XML_Expat_Version info = XML_ExpatVersionInfo();
-        PyModule_AddObject(m, "version_info",
-                           Py_BuildValue("(iii)", info.major,
-                                         info.minor, info.micro));
-    }
-    /* XXX When Expat supports some way of figuring out how it was
-       compiled, this should check and set native_encoding
-       appropriately.
-    */
-    PyModule_AddStringConstant(m, "native_encoding", "UTF-8");
-
-    sys_modules = PySys_GetObject("modules");
-    d = PyModule_GetDict(m);
-    errors_module = PyDict_GetItem(d, errmod_name);
-    if (errors_module == NULL) {
-        errors_module = PyModule_New(MODULE_NAME ".errors");
-        if (errors_module != NULL) {
-            PyDict_SetItem(sys_modules, errmod_name, errors_module);
-            /* gives away the reference to errors_module */
-            PyModule_AddObject(m, "errors", errors_module);
-        }
-    }
-    Py_DECREF(errmod_name);
-    model_module = PyDict_GetItem(d, modelmod_name);
-    if (model_module == NULL) {
-        model_module = PyModule_New(MODULE_NAME ".model");
-        if (model_module != NULL) {
-            PyDict_SetItem(sys_modules, modelmod_name, model_module);
-            /* gives away the reference to model_module */
-            PyModule_AddObject(m, "model", model_module);
-        }
-    }
-    Py_DECREF(modelmod_name);
-    if (errors_module == NULL || model_module == NULL)
-        /* Don't core dump later! */
-        return NULL;
-
-#if XML_COMBINED_VERSION > 19505
-    {
-        const XML_Feature *features = XML_GetFeatureList();
-        PyObject *list = PyList_New(0);
-        if (list == NULL)
-            /* just ignore it */
-            PyErr_Clear();
-        else {
-            int i = 0;
-            for (; features[i].feature != XML_FEATURE_END; ++i) {
-                int ok;
-                PyObject *item = Py_BuildValue("si", features[i].name,
-                                               features[i].value);
-                if (item == NULL) {
-                    Py_DECREF(list);
-                    list = NULL;
-                    break;
-                }
-                ok = PyList_Append(list, item);
-                Py_DECREF(item);
-                if (ok < 0) {
-                    PyErr_Clear();
-                    break;
-                }
-            }
-            if (list != NULL)
-                PyModule_AddObject(m, "features", list);
-        }
-    }
-#endif
-
-    codes_dict = PyDict_New();
-    rev_codes_dict = PyDict_New();
-    if (codes_dict == NULL || rev_codes_dict == NULL) {
-        Py_XDECREF(codes_dict);
-        Py_XDECREF(rev_codes_dict);
-        return NULL;
-    }
-
-#define MYCONST(name) \
-    if (PyModule_AddStringConstant(errors_module, #name,               \
-                                   XML_ErrorString(name)) < 0)         \
-        return NULL;                                                   \
-    tmpnum = PyLong_FromLong(name);                                    \
-    if (tmpnum == NULL) return NULL;                                   \
-    res = PyDict_SetItemString(codes_dict,                             \
-                               XML_ErrorString(name), tmpnum);         \
-    if (res < 0) return NULL;                                          \
-    tmpstr = PyUnicode_FromString(XML_ErrorString(name));              \
-    if (tmpstr == NULL) return NULL;                                   \
-    res = PyDict_SetItem(rev_codes_dict, tmpnum, tmpstr);              \
-    Py_DECREF(tmpstr);                                                 \
-    Py_DECREF(tmpnum);                                                 \
-    if (res < 0) return NULL;                                          \
-
-    MYCONST(XML_ERROR_NO_MEMORY);
-    MYCONST(XML_ERROR_SYNTAX);
-    MYCONST(XML_ERROR_NO_ELEMENTS);
-    MYCONST(XML_ERROR_INVALID_TOKEN);
-    MYCONST(XML_ERROR_UNCLOSED_TOKEN);
-    MYCONST(XML_ERROR_PARTIAL_CHAR);
-    MYCONST(XML_ERROR_TAG_MISMATCH);
-    MYCONST(XML_ERROR_DUPLICATE_ATTRIBUTE);
-    MYCONST(XML_ERROR_JUNK_AFTER_DOC_ELEMENT);
-    MYCONST(XML_ERROR_PARAM_ENTITY_REF);
-    MYCONST(XML_ERROR_UNDEFINED_ENTITY);
-    MYCONST(XML_ERROR_RECURSIVE_ENTITY_REF);
-    MYCONST(XML_ERROR_ASYNC_ENTITY);
-    MYCONST(XML_ERROR_BAD_CHAR_REF);
-    MYCONST(XML_ERROR_BINARY_ENTITY_REF);
-    MYCONST(XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF);
-    MYCONST(XML_ERROR_MISPLACED_XML_PI);
-    MYCONST(XML_ERROR_UNKNOWN_ENCODING);
-    MYCONST(XML_ERROR_INCORRECT_ENCODING);
-    MYCONST(XML_ERROR_UNCLOSED_CDATA_SECTION);
-    MYCONST(XML_ERROR_EXTERNAL_ENTITY_HANDLING);
-    MYCONST(XML_ERROR_NOT_STANDALONE);
-    MYCONST(XML_ERROR_UNEXPECTED_STATE);
-    MYCONST(XML_ERROR_ENTITY_DECLARED_IN_PE);
-    MYCONST(XML_ERROR_FEATURE_REQUIRES_XML_DTD);
-    MYCONST(XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING);
-    /* Added in Expat 1.95.7. */
-    MYCONST(XML_ERROR_UNBOUND_PREFIX);
-    /* Added in Expat 1.95.8. */
-    MYCONST(XML_ERROR_UNDECLARING_PREFIX);
-    MYCONST(XML_ERROR_INCOMPLETE_PE);
-    MYCONST(XML_ERROR_XML_DECL);
-    MYCONST(XML_ERROR_TEXT_DECL);
-    MYCONST(XML_ERROR_PUBLICID);
-    MYCONST(XML_ERROR_SUSPENDED);
-    MYCONST(XML_ERROR_NOT_SUSPENDED);
-    MYCONST(XML_ERROR_ABORTED);
-    MYCONST(XML_ERROR_FINISHED);
-    MYCONST(XML_ERROR_SUSPEND_PE);
-
-    if (PyModule_AddStringConstant(errors_module, "__doc__",
-                                   "Constants used to describe "
-                                   "error conditions.") < 0)
-        return NULL;
-
-    if (PyModule_AddObject(errors_module, "codes", codes_dict) < 0)
-        return NULL;
-    if (PyModule_AddObject(errors_module, "messages", rev_codes_dict) < 0)
-        return NULL;
-
-#undef MYCONST
-
-#define MYCONST(c) PyModule_AddIntConstant(m, #c, c)
-    MYCONST(XML_PARAM_ENTITY_PARSING_NEVER);
-    MYCONST(XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
-    MYCONST(XML_PARAM_ENTITY_PARSING_ALWAYS);
-#undef MYCONST
-
-#define MYCONST(c) PyModule_AddIntConstant(model_module, #c, c)
-    PyModule_AddStringConstant(model_module, "__doc__",
-                     "Constants used to interpret content model information.");
-
-    MYCONST(XML_CTYPE_EMPTY);
-    MYCONST(XML_CTYPE_ANY);
-    MYCONST(XML_CTYPE_MIXED);
-    MYCONST(XML_CTYPE_NAME);
-    MYCONST(XML_CTYPE_CHOICE);
-    MYCONST(XML_CTYPE_SEQ);
-
-    MYCONST(XML_CQUANT_NONE);
-    MYCONST(XML_CQUANT_OPT);
-    MYCONST(XML_CQUANT_REP);
-    MYCONST(XML_CQUANT_PLUS);
-#undef MYCONST
-
-    /* initialize pyexpat dispatch table */
-    capi.size = sizeof(capi);
-    capi.magic = PyExpat_CAPI_MAGIC;
-    capi.MAJOR_VERSION = XML_MAJOR_VERSION;
-    capi.MINOR_VERSION = XML_MINOR_VERSION;
-    capi.MICRO_VERSION = XML_MICRO_VERSION;
-    capi.ErrorString = XML_ErrorString;
-    capi.GetErrorCode = XML_GetErrorCode;
-    capi.GetErrorColumnNumber = XML_GetErrorColumnNumber;
-    capi.GetErrorLineNumber = XML_GetErrorLineNumber;
-    capi.Parse = XML_Parse;
-    capi.ParserCreate_MM = XML_ParserCreate_MM;
-    capi.ParserFree = XML_ParserFree;
-    capi.SetCharacterDataHandler = XML_SetCharacterDataHandler;
-    capi.SetCommentHandler = XML_SetCommentHandler;
-    capi.SetDefaultHandlerExpand = XML_SetDefaultHandlerExpand;
-    capi.SetElementHandler = XML_SetElementHandler;
-    capi.SetNamespaceDeclHandler = XML_SetNamespaceDeclHandler;
-    capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
-    capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
-    capi.SetUserData = XML_SetUserData;
-    capi.SetStartDoctypeDeclHandler = XML_SetStartDoctypeDeclHandler;
-    capi.SetEncoding = XML_SetEncoding;
-    capi.DefaultUnknownEncodingHandler = PyUnknownEncodingHandler;
-
-    /* export using capsule */
-    capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);
-    if (capi_object)
-        PyModule_AddObject(m, "expat_CAPI", capi_object);
-    return m;
-}
-
-static void
-clear_handlers(xmlparseobject *self, int initial)
-{
-    int i = 0;
-    PyObject *temp;
-
-    for (; handler_info[i].name != NULL; i++) {
-        if (initial)
-            self->handlers[i] = NULL;
-        else {
-            temp = self->handlers[i];
-            self->handlers[i] = NULL;
-            Py_XDECREF(temp);
-            handler_info[i].setter(self->itself, NULL);
-        }
-    }
-}
-
-static struct HandlerInfo handler_info[] = {
-    {"StartElementHandler",
-     (xmlhandlersetter)XML_SetStartElementHandler,
-     (xmlhandler)my_StartElementHandler},
-    {"EndElementHandler",
-     (xmlhandlersetter)XML_SetEndElementHandler,
-     (xmlhandler)my_EndElementHandler},
-    {"ProcessingInstructionHandler",
-     (xmlhandlersetter)XML_SetProcessingInstructionHandler,
-     (xmlhandler)my_ProcessingInstructionHandler},
-    {"CharacterDataHandler",
-     (xmlhandlersetter)XML_SetCharacterDataHandler,
-     (xmlhandler)my_CharacterDataHandler},
-    {"UnparsedEntityDeclHandler",
-     (xmlhandlersetter)XML_SetUnparsedEntityDeclHandler,
-     (xmlhandler)my_UnparsedEntityDeclHandler},
-    {"NotationDeclHandler",
-     (xmlhandlersetter)XML_SetNotationDeclHandler,
-     (xmlhandler)my_NotationDeclHandler},
-    {"StartNamespaceDeclHandler",
-     (xmlhandlersetter)XML_SetStartNamespaceDeclHandler,
-     (xmlhandler)my_StartNamespaceDeclHandler},
-    {"EndNamespaceDeclHandler",
-     (xmlhandlersetter)XML_SetEndNamespaceDeclHandler,
-     (xmlhandler)my_EndNamespaceDeclHandler},
-    {"CommentHandler",
-     (xmlhandlersetter)XML_SetCommentHandler,
-     (xmlhandler)my_CommentHandler},
-    {"StartCdataSectionHandler",
-     (xmlhandlersetter)XML_SetStartCdataSectionHandler,
-     (xmlhandler)my_StartCdataSectionHandler},
-    {"EndCdataSectionHandler",
-     (xmlhandlersetter)XML_SetEndCdataSectionHandler,
-     (xmlhandler)my_EndCdataSectionHandler},
-    {"DefaultHandler",
-     (xmlhandlersetter)XML_SetDefaultHandler,
-     (xmlhandler)my_DefaultHandler},
-    {"DefaultHandlerExpand",
-     (xmlhandlersetter)XML_SetDefaultHandlerExpand,
-     (xmlhandler)my_DefaultHandlerExpandHandler},
-    {"NotStandaloneHandler",
-     (xmlhandlersetter)XML_SetNotStandaloneHandler,
-     (xmlhandler)my_NotStandaloneHandler},
-    {"ExternalEntityRefHandler",
-     (xmlhandlersetter)XML_SetExternalEntityRefHandler,
-     (xmlhandler)my_ExternalEntityRefHandler},
-    {"StartDoctypeDeclHandler",
-     (xmlhandlersetter)XML_SetStartDoctypeDeclHandler,
-     (xmlhandler)my_StartDoctypeDeclHandler},
-    {"EndDoctypeDeclHandler",
-     (xmlhandlersetter)XML_SetEndDoctypeDeclHandler,
-     (xmlhandler)my_EndDoctypeDeclHandler},
-    {"EntityDeclHandler",
-     (xmlhandlersetter)XML_SetEntityDeclHandler,
-     (xmlhandler)my_EntityDeclHandler},
-    {"XmlDeclHandler",
-     (xmlhandlersetter)XML_SetXmlDeclHandler,
-     (xmlhandler)my_XmlDeclHandler},
-    {"ElementDeclHandler",
-     (xmlhandlersetter)XML_SetElementDeclHandler,
-     (xmlhandler)my_ElementDeclHandler},
-    {"AttlistDeclHandler",
-     (xmlhandlersetter)XML_SetAttlistDeclHandler,
-     (xmlhandler)my_AttlistDeclHandler},
-#if XML_COMBINED_VERSION >= 19504
-    {"SkippedEntityHandler",
-     (xmlhandlersetter)XML_SetSkippedEntityHandler,
-     (xmlhandler)my_SkippedEntityHandler},
-#endif
-
-    {NULL, NULL, NULL} /* sentinel */
-};
-
-/*[clinic input]
-dump buffer
-[clinic start generated code]*/
-
 #ifndef PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
     #define PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
 #endif /* !defined(PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF) */
-/*[clinic end generated code: output=a7880cb78bbd58ce input=524ce2e021e4eba6]*/
+/*[clinic end generated code: output=0198390005e40e1c input=a9049054013a1b77]*/
diff --git a/Modules/sha1module.c b/Modules/clinic/sha1module.c.h
copy from Modules/sha1module.c
copy to Modules/clinic/sha1module.c.h
--- a/Modules/sha1module.c
+++ b/Modules/clinic/sha1module.c.h
@@ -1,323 +1,5 @@
-/* SHA1 module */
-
-/* This module provides an interface to the SHA1 algorithm */
-
-/* See below for information about the original code this module was
-   based upon. Additional work performed by:
-
-   Andrew Kuchling (amk at amk.ca)
-   Greg Stein (gstein at lyra.org)
-   Trevor Perrin (trevp at trevp.net)
-
-   Copyright (C) 2005-2007   Gregory P. Smith (greg at krypto.org)
-   Licensed to PSF under a Contributor Agreement.
-
-*/
-
-/* SHA1 objects */
-
-#include "Python.h"
-#include "hashlib.h"
-
 /*[clinic input]
-module _sha1
-class SHA1Type "SHA1object *" "&PyType_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3dc9a20d1becb759]*/
-
-/* Some useful types */
-
-#if SIZEOF_INT == 4
-typedef unsigned int SHA1_INT32;        /* 32-bit integer */
-typedef PY_LONG_LONG SHA1_INT64;        /* 64-bit integer */
-#else
-/* not defined. compilation will die. */
-#endif
-
-/* The SHA1 block size and message digest sizes, in bytes */
-
-#define SHA1_BLOCKSIZE    64
-#define SHA1_DIGESTSIZE   20
-
-/* The structure for storing SHA1 info */
-
-struct sha1_state {
-    SHA1_INT64 length;
-    SHA1_INT32 state[5], curlen;
-    unsigned char buf[SHA1_BLOCKSIZE];
-};
-
-typedef struct {
-    PyObject_HEAD
-
-    struct sha1_state hash_state;
-} SHA1object;
-
-
-/* ------------------------------------------------------------------------
- *
- * This code for the SHA1 algorithm was noted as public domain. The
- * original headers are pasted below.
- *
- * Several changes have been made to make it more compatible with the
- * Python environment and desired interface.
- *
- */
-
-/* LibTomCrypt, modular cryptographic library -- Tom St Denis
- *
- * LibTomCrypt is a library that provides various cryptographic
- * algorithms in a highly modular and flexible manner.
- *
- * The library is free for all purposes without any express
- * guarantee it works.
- *
- * Tom St Denis, tomstdenis at gmail.com, http://libtom.org
- */
-
-/* rotate the hard way (platform optimizations could be done) */
-#define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
-#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
-
-/* Endian Neutral macros that work on all platforms */
-
-#define STORE32H(x, y)                                                                     \
-     { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
-       (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
-
-#define LOAD32H(x, y)                            \
-     { x = ((unsigned long)((y)[0] & 255)<<24) | \
-           ((unsigned long)((y)[1] & 255)<<16) | \
-           ((unsigned long)((y)[2] & 255)<<8)  | \
-           ((unsigned long)((y)[3] & 255)); }
-
-#define STORE64H(x, y)                                                                     \
-   { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
-     (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
-     (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
-     (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
-
-
-/* SHA1 macros */
-
-#define F0(x,y,z)  (z ^ (x & (y ^ z)))
-#define F1(x,y,z)  (x ^ y ^ z)
-#define F2(x,y,z)  ((x & y) | (z & (x | y)))
-#define F3(x,y,z)  (x ^ y ^ z)
-
-static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
-{
-    SHA1_INT32 a,b,c,d,e,W[80],i;
-
-    /* copy the state into 512-bits into W[0..15] */
-    for (i = 0; i < 16; i++) {
-        LOAD32H(W[i], buf + (4*i));
-    }
-
-    /* copy state */
-    a = sha1->state[0];
-    b = sha1->state[1];
-    c = sha1->state[2];
-    d = sha1->state[3];
-    e = sha1->state[4];
-
-    /* expand it */
-    for (i = 16; i < 80; i++) {
-        W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
-    }
-
-    /* compress */
-    /* round one */
-    #define FF_0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
-    #define FF_1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
-    #define FF_2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
-    #define FF_3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
-
-    for (i = 0; i < 20; ) {
-       FF_0(a,b,c,d,e,i++);
-       FF_0(e,a,b,c,d,i++);
-       FF_0(d,e,a,b,c,i++);
-       FF_0(c,d,e,a,b,i++);
-       FF_0(b,c,d,e,a,i++);
-    }
-
-    /* round two */
-    for (; i < 40; )  {
-       FF_1(a,b,c,d,e,i++);
-       FF_1(e,a,b,c,d,i++);
-       FF_1(d,e,a,b,c,i++);
-       FF_1(c,d,e,a,b,i++);
-       FF_1(b,c,d,e,a,i++);
-    }
-
-    /* round three */
-    for (; i < 60; )  {
-       FF_2(a,b,c,d,e,i++);
-       FF_2(e,a,b,c,d,i++);
-       FF_2(d,e,a,b,c,i++);
-       FF_2(c,d,e,a,b,i++);
-       FF_2(b,c,d,e,a,i++);
-    }
-
-    /* round four */
-    for (; i < 80; )  {
-       FF_3(a,b,c,d,e,i++);
-       FF_3(e,a,b,c,d,i++);
-       FF_3(d,e,a,b,c,i++);
-       FF_3(c,d,e,a,b,i++);
-       FF_3(b,c,d,e,a,i++);
-    }
-
-    #undef FF_0
-    #undef FF_1
-    #undef FF_2
-    #undef FF_3
-
-    /* store */
-    sha1->state[0] = sha1->state[0] + a;
-    sha1->state[1] = sha1->state[1] + b;
-    sha1->state[2] = sha1->state[2] + c;
-    sha1->state[3] = sha1->state[3] + d;
-    sha1->state[4] = sha1->state[4] + e;
-}
-
-/**
-   Initialize the hash state
-   @param sha1   The hash state you wish to initialize
-*/
-static void
-sha1_init(struct sha1_state *sha1)
-{
-   assert(sha1 != NULL);
-   sha1->state[0] = 0x67452301UL;
-   sha1->state[1] = 0xefcdab89UL;
-   sha1->state[2] = 0x98badcfeUL;
-   sha1->state[3] = 0x10325476UL;
-   sha1->state[4] = 0xc3d2e1f0UL;
-   sha1->curlen = 0;
-   sha1->length = 0;
-}
-
-/**
-   Process a block of memory though the hash
-   @param sha1   The hash state
-   @param in     The data to hash
-   @param inlen  The length of the data (octets)
-*/
-static void
-sha1_process(struct sha1_state *sha1,
-                  const unsigned char *in, Py_ssize_t inlen)
-{
-    Py_ssize_t n;
-
-    assert(sha1 != NULL);
-    assert(in != NULL);
-    assert(sha1->curlen <= sizeof(sha1->buf));
-
-    while (inlen > 0) {
-        if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) {
-           sha1_compress(sha1, (unsigned char *)in);
-           sha1->length   += SHA1_BLOCKSIZE * 8;
-           in             += SHA1_BLOCKSIZE;
-           inlen          -= SHA1_BLOCKSIZE;
-        } else {
-           n = Py_MIN(inlen, (Py_ssize_t)(SHA1_BLOCKSIZE - sha1->curlen));
-           memcpy(sha1->buf + sha1->curlen, in, (size_t)n);
-           sha1->curlen   += (SHA1_INT32)n;
-           in             += n;
-           inlen          -= n;
-           if (sha1->curlen == SHA1_BLOCKSIZE) {
-              sha1_compress(sha1, sha1->buf);
-              sha1->length += 8*SHA1_BLOCKSIZE;
-              sha1->curlen = 0;
-           }
-       }
-    }
-}
-
-/**
-   Terminate the hash to get the digest
-   @param sha1  The hash state
-   @param out [out] The destination of the hash (20 bytes)
-*/
-static void
-sha1_done(struct sha1_state *sha1, unsigned char *out)
-{
-    int i;
-
-    assert(sha1 != NULL);
-    assert(out != NULL);
-    assert(sha1->curlen < sizeof(sha1->buf));
-
-    /* increase the length of the message */
-    sha1->length += sha1->curlen * 8;
-
-    /* append the '1' bit */
-    sha1->buf[sha1->curlen++] = (unsigned char)0x80;
-
-    /* if the length is currently above 56 bytes we append zeros
-     * then compress.  Then we can fall back to padding zeros and length
-     * encoding like normal.
-     */
-    if (sha1->curlen > 56) {
-        while (sha1->curlen < 64) {
-            sha1->buf[sha1->curlen++] = (unsigned char)0;
-        }
-        sha1_compress(sha1, sha1->buf);
-        sha1->curlen = 0;
-    }
-
-    /* pad upto 56 bytes of zeroes */
-    while (sha1->curlen < 56) {
-        sha1->buf[sha1->curlen++] = (unsigned char)0;
-    }
-
-    /* store length */
-    STORE64H(sha1->length, sha1->buf+56);
-    sha1_compress(sha1, sha1->buf);
-
-    /* copy output */
-    for (i = 0; i < 5; i++) {
-        STORE32H(sha1->state[i], out+(4*i));
-    }
-}
-
-
-/* .Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */
-/* .Revision: 1.10 $ */
-/* .Date: 2007/05/12 14:25:28 $ */
-
-/*
- * End of copied SHA1 code.
- *
- * ------------------------------------------------------------------------
- */
-
-static PyTypeObject SHA1type;
-
-
-static SHA1object *
-newSHA1object(void)
-{
-    return (SHA1object *)PyObject_New(SHA1object, &SHA1type);
-}
-
-
-/* Internal methods for a hash object */
-
-static void
-SHA1_dealloc(PyObject *ptr)
-{
-    PyObject_Del(ptr);
-}
-
-
-/* External methods for a hash object */
-
-/*[clinic input]
-SHA1Type.copy
-
-Return a copy of the hash object.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(SHA1Type_copy__doc__,
@@ -338,25 +20,6 @@
     return SHA1Type_copy_impl(self);
 }
 
-static PyObject *
-SHA1Type_copy_impl(SHA1object *self)
-/*[clinic end generated code: output=1a320e75a7444098 input=b7eae10df6f89b36]*/
-{
-    SHA1object *newobj;
-
-    if ((newobj = newSHA1object()) == NULL)
-        return NULL;
-
-    newobj->hash_state = self->hash_state;
-    return (PyObject *)newobj;
-}
-
-/*[clinic input]
-SHA1Type.digest
-
-Return the digest value as a string of binary data.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(SHA1Type_digest__doc__,
 "digest($self, /)\n"
 "--\n"
@@ -375,24 +38,6 @@
     return SHA1Type_digest_impl(self);
 }
 
-static PyObject *
-SHA1Type_digest_impl(SHA1object *self)
-/*[clinic end generated code: output=c4920f75228bfbfd input=205d47e1927fd009]*/
-{
-    unsigned char digest[SHA1_DIGESTSIZE];
-    struct sha1_state temp;
-
-    temp = self->hash_state;
-    sha1_done(&temp, digest);
-    return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE);
-}
-
-/*[clinic input]
-SHA1Type.hexdigest
-
-Return the digest value as a string of hexadecimal digits.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(SHA1Type_hexdigest__doc__,
 "hexdigest($self, /)\n"
 "--\n"
@@ -411,49 +56,6 @@
     return SHA1Type_hexdigest_impl(self);
 }
 
-static PyObject *
-SHA1Type_hexdigest_impl(SHA1object *self)
-/*[clinic end generated code: output=6e345aac201887b2 input=97691055c0c74ab0]*/
-{
-    unsigned char digest[SHA1_DIGESTSIZE];
-    struct sha1_state temp;
-    PyObject *retval;
-    Py_UCS1 *hex_digest;
-    int i, j;
-
-    /* Get the raw (binary) digest value */
-    temp = self->hash_state;
-    sha1_done(&temp, digest);
-
-    /* Create a new string */
-    retval = PyUnicode_New(SHA1_DIGESTSIZE * 2, 127);
-    if (!retval)
-            return NULL;
-    hex_digest = PyUnicode_1BYTE_DATA(retval);
-
-    /* Make hex version of the digest */
-    for(i=j=0; i<SHA1_DIGESTSIZE; i++) {
-        unsigned char c;
-        c = (digest[i] >> 4) & 0xf;
-        hex_digest[j++] = Py_hexdigits[c];
-        c = (digest[i] & 0xf);
-        hex_digest[j++] = Py_hexdigits[c];
-    }
-#ifdef Py_DEBUG
-    assert(_PyUnicode_CheckConsistency(retval, 1));
-#endif
-    return retval;
-}
-
-/*[clinic input]
-SHA1Type.update
-
-    obj: object
-    /
-
-Update this hash object's state with the provided string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(SHA1Type_update__doc__,
 "update($self, obj, /)\n"
 "--\n"
@@ -463,109 +65,6 @@
 #define SHA1TYPE_UPDATE_METHODDEF    \
     {"update", (PyCFunction)SHA1Type_update, METH_O, SHA1Type_update__doc__},
 
-static PyObject *
-SHA1Type_update(SHA1object *self, PyObject *obj)
-/*[clinic end generated code: output=ab20a86a25e7d255 input=aad8e07812edbba3]*/
-{
-    Py_buffer buf;
-
-    GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
-
-    sha1_process(&self->hash_state, buf.buf, buf.len);
-
-    PyBuffer_Release(&buf);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyMethodDef SHA1_methods[] = {
-    SHA1TYPE_COPY_METHODDEF
-    SHA1TYPE_DIGEST_METHODDEF
-    SHA1TYPE_HEXDIGEST_METHODDEF
-    SHA1TYPE_UPDATE_METHODDEF
-    {NULL,        NULL}         /* sentinel */
-};
-
-static PyObject *
-SHA1_get_block_size(PyObject *self, void *closure)
-{
-    return PyLong_FromLong(SHA1_BLOCKSIZE);
-}
-
-static PyObject *
-SHA1_get_name(PyObject *self, void *closure)
-{
-    return PyUnicode_FromStringAndSize("sha1", 4);
-}
-
-static PyObject *
-sha1_get_digest_size(PyObject *self, void *closure)
-{
-    return PyLong_FromLong(SHA1_DIGESTSIZE);
-}
-
-
-static PyGetSetDef SHA1_getseters[] = {
-    {"block_size",
-     (getter)SHA1_get_block_size, NULL,
-     NULL,
-     NULL},
-    {"name",
-     (getter)SHA1_get_name, NULL,
-     NULL,
-     NULL},
-    {"digest_size",
-     (getter)sha1_get_digest_size, NULL,
-     NULL,
-     NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyTypeObject SHA1type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_sha1.sha1",               /*tp_name*/
-    sizeof(SHA1object), /*tp_size*/
-    0,                  /*tp_itemsize*/
-    /* methods */
-    SHA1_dealloc,       /*tp_dealloc*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,                  /*tp_clear*/
-    0,                  /*tp_richcompare*/
-    0,                  /*tp_weaklistoffset*/
-    0,                  /*tp_iter*/
-    0,                  /*tp_iternext*/
-    SHA1_methods,       /* tp_methods */
-    NULL,               /* tp_members */
-    SHA1_getseters,      /* tp_getset */
-};
-
-
-/* The single module-level function: new() */
-
-/*[clinic input]
-_sha1.sha1
-
-    string: object(c_default="NULL") = b''
-
-Return a new SHA1 hash object; optionally initialized with a string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(_sha1_sha1__doc__,
 "sha1($module, /, string=b\'\')\n"
 "--\n"
@@ -594,79 +93,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-_sha1_sha1_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=c9068552f07b8954 input=27ea54281d995ec2]*/
-{
-    SHA1object *new;
-    Py_buffer buf;
-
-    if (string)
-        GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
-
-    if ((new = newSHA1object()) == NULL) {
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-
-    sha1_init(&new->hash_state);
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-    if (string) {
-        sha1_process(&new->hash_state, buf.buf, buf.len);
-        PyBuffer_Release(&buf);
-    }
-
-    return (PyObject *)new;
-}
-
-
-/* List of functions exported by this module */
-
-static struct PyMethodDef SHA1_functions[] = {
-    _SHA1_SHA1_METHODDEF
-    {NULL,      NULL}            /* Sentinel */
-};
-
-
-/* Initialize this module. */
-
-#define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
-
-
-static struct PyModuleDef _sha1module = {
-        PyModuleDef_HEAD_INIT,
-        "_sha1",
-        NULL,
-        -1,
-        SHA1_functions,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-PyInit__sha1(void)
-{
-    PyObject *m;
-
-    Py_TYPE(&SHA1type) = &PyType_Type;
-    if (PyType_Ready(&SHA1type) < 0)
-        return NULL;
-
-    m = PyModule_Create(&_sha1module);
-    if (m == NULL)
-        return NULL;
-
-    Py_INCREF((PyObject *)&SHA1type);
-    PyModule_AddObject(m, "SHA1Type", (PyObject *)&SHA1type);
-    return m;
-}
+/*[clinic end generated code: output=b2890b9ca964b217 input=a9049054013a1b77]*/
diff --git a/Modules/sha256module.c b/Modules/clinic/sha256module.c.h
copy from Modules/sha256module.c
copy to Modules/clinic/sha256module.c.h
--- a/Modules/sha256module.c
+++ b/Modules/clinic/sha256module.c.h
@@ -1,407 +1,5 @@
-/* SHA256 module */
-
-/* This module provides an interface to NIST's SHA-256 and SHA-224 Algorithms */
-
-/* See below for information about the original code this module was
-   based upon. Additional work performed by:
-
-   Andrew Kuchling (amk at amk.ca)
-   Greg Stein (gstein at lyra.org)
-   Trevor Perrin (trevp at trevp.net)
-
-   Copyright (C) 2005-2007   Gregory P. Smith (greg at krypto.org)
-   Licensed to PSF under a Contributor Agreement.
-
-*/
-
-/* SHA objects */
-
-#include "Python.h"
-#include "structmember.h"
-#include "hashlib.h"
-
 /*[clinic input]
-module _sha256
-class SHA256Type "SHAobject *" "&PyType_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=71a39174d4f0a744]*/
-
-/* Some useful types */
-
-typedef unsigned char SHA_BYTE;
-
-#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
-#else
-/* not defined. compilation will die. */
-#endif
-
-/* The SHA block size and message digest sizes, in bytes */
-
-#define SHA_BLOCKSIZE    64
-#define SHA_DIGESTSIZE  32
-
-/* The structure for storing SHA info */
-
-typedef struct {
-    PyObject_HEAD
-    SHA_INT32 digest[8];                /* Message digest */
-    SHA_INT32 count_lo, count_hi;       /* 64-bit bit count */
-    SHA_BYTE data[SHA_BLOCKSIZE];       /* SHA data buffer */
-    int local;                          /* unprocessed amount in data */
-    int digestsize;
-} SHAobject;
-
-/* When run on a little-endian CPU we need to perform byte reversal on an
-   array of longwords. */
-
-#if PY_LITTLE_ENDIAN
-static void longReverse(SHA_INT32 *buffer, int byteCount)
-{
-    SHA_INT32 value;
-
-    byteCount /= sizeof(*buffer);
-    while (byteCount--) {
-        value = *buffer;
-        value = ( ( value & 0xFF00FF00L ) >> 8  ) | \
-                ( ( value & 0x00FF00FFL ) << 8 );
-        *buffer++ = ( value << 16 ) | ( value >> 16 );
-    }
-}
-#endif
-
-static void SHAcopy(SHAobject *src, SHAobject *dest)
-{
-    dest->local = src->local;
-    dest->digestsize = src->digestsize;
-    dest->count_lo = src->count_lo;
-    dest->count_hi = src->count_hi;
-    memcpy(dest->digest, src->digest, sizeof(src->digest));
-    memcpy(dest->data, src->data, sizeof(src->data));
-}
-
-
-/* ------------------------------------------------------------------------
- *
- * This code for the SHA-256 algorithm was noted as public domain. The
- * original headers are pasted below.
- *
- * Several changes have been made to make it more compatible with the
- * Python environment and desired interface.
- *
- */
-
-/* LibTomCrypt, modular cryptographic library -- Tom St Denis
- *
- * LibTomCrypt is a library that provides various cryptographic
- * algorithms in a highly modular and flexible manner.
- *
- * The library is free for all purposes without any express
- * gurantee it works.
- *
- * Tom St Denis, tomstdenis at iahu.ca, http://libtom.org
- */
-
-
-/* SHA256 by Tom St Denis */
-
-/* Various logical functions */
-#define ROR(x, y)\
-( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \
-((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
-#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
-#define Maj(x,y,z)      (((x | y) & z) | (x & y))
-#define S(x, n)         ROR((x),(n))
-#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
-#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
-#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
-#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
-#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))
-
-
-static void
-sha_transform(SHAobject *sha_info)
-{
-    int i;
-        SHA_INT32 S[8], W[64], t0, t1;
-
-    memcpy(W, sha_info->data, sizeof(sha_info->data));
-#if PY_LITTLE_ENDIAN
-    longReverse(W, (int)sizeof(sha_info->data));
-#endif
-
-    for (i = 16; i < 64; ++i) {
-                W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
-    }
-    for (i = 0; i < 8; ++i) {
-        S[i] = sha_info->digest[i];
-    }
-
-    /* Compress */
-#define RND(a,b,c,d,e,f,g,h,i,ki)                    \
-     t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i];   \
-     t1 = Sigma0(a) + Maj(a, b, c);                  \
-     d += t0;                                        \
-     h  = t0 + t1;
-
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);
-
-#undef RND
-
-    /* feedback */
-    for (i = 0; i < 8; i++) {
-        sha_info->digest[i] = sha_info->digest[i] + S[i];
-    }
-
-}
-
-
-
-/* initialize the SHA digest */
-
-static void
-sha_init(SHAobject *sha_info)
-{
-    sha_info->digest[0] = 0x6A09E667L;
-    sha_info->digest[1] = 0xBB67AE85L;
-    sha_info->digest[2] = 0x3C6EF372L;
-    sha_info->digest[3] = 0xA54FF53AL;
-    sha_info->digest[4] = 0x510E527FL;
-    sha_info->digest[5] = 0x9B05688CL;
-    sha_info->digest[6] = 0x1F83D9ABL;
-    sha_info->digest[7] = 0x5BE0CD19L;
-    sha_info->count_lo = 0L;
-    sha_info->count_hi = 0L;
-    sha_info->local = 0;
-    sha_info->digestsize = 32;
-}
-
-static void
-sha224_init(SHAobject *sha_info)
-{
-    sha_info->digest[0] = 0xc1059ed8L;
-    sha_info->digest[1] = 0x367cd507L;
-    sha_info->digest[2] = 0x3070dd17L;
-    sha_info->digest[3] = 0xf70e5939L;
-    sha_info->digest[4] = 0xffc00b31L;
-    sha_info->digest[5] = 0x68581511L;
-    sha_info->digest[6] = 0x64f98fa7L;
-    sha_info->digest[7] = 0xbefa4fa4L;
-    sha_info->count_lo = 0L;
-    sha_info->count_hi = 0L;
-    sha_info->local = 0;
-    sha_info->digestsize = 28;
-}
-
-
-/* update the SHA digest */
-
-static void
-sha_update(SHAobject *sha_info, SHA_BYTE *buffer, Py_ssize_t count)
-{
-    Py_ssize_t i;
-    SHA_INT32 clo;
-
-    clo = sha_info->count_lo + ((SHA_INT32) count << 3);
-    if (clo < sha_info->count_lo) {
-        ++sha_info->count_hi;
-    }
-    sha_info->count_lo = clo;
-    sha_info->count_hi += (SHA_INT32) count >> 29;
-    if (sha_info->local) {
-        i = SHA_BLOCKSIZE - sha_info->local;
-        if (i > count) {
-            i = count;
-        }
-        memcpy(((SHA_BYTE *) sha_info->data) + sha_info->local, buffer, i);
-        count -= i;
-        buffer += i;
-        sha_info->local += (int)i;
-        if (sha_info->local == SHA_BLOCKSIZE) {
-            sha_transform(sha_info);
-        }
-        else {
-            return;
-        }
-    }
-    while (count >= SHA_BLOCKSIZE) {
-        memcpy(sha_info->data, buffer, SHA_BLOCKSIZE);
-        buffer += SHA_BLOCKSIZE;
-        count -= SHA_BLOCKSIZE;
-        sha_transform(sha_info);
-    }
-    memcpy(sha_info->data, buffer, count);
-    sha_info->local = (int)count;
-}
-
-/* finish computing the SHA digest */
-
-static void
-sha_final(unsigned char digest[SHA_DIGESTSIZE], SHAobject *sha_info)
-{
-    int count;
-    SHA_INT32 lo_bit_count, hi_bit_count;
-
-    lo_bit_count = sha_info->count_lo;
-    hi_bit_count = sha_info->count_hi;
-    count = (int) ((lo_bit_count >> 3) & 0x3f);
-    ((SHA_BYTE *) sha_info->data)[count++] = 0x80;
-    if (count > SHA_BLOCKSIZE - 8) {
-        memset(((SHA_BYTE *) sha_info->data) + count, 0,
-               SHA_BLOCKSIZE - count);
-        sha_transform(sha_info);
-        memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
-    }
-    else {
-        memset(((SHA_BYTE *) sha_info->data) + count, 0,
-               SHA_BLOCKSIZE - 8 - count);
-    }
-
-    /* GJS: note that we add the hi/lo in big-endian. sha_transform will
-       swap these values into host-order. */
-    sha_info->data[56] = (hi_bit_count >> 24) & 0xff;
-    sha_info->data[57] = (hi_bit_count >> 16) & 0xff;
-    sha_info->data[58] = (hi_bit_count >>  8) & 0xff;
-    sha_info->data[59] = (hi_bit_count >>  0) & 0xff;
-    sha_info->data[60] = (lo_bit_count >> 24) & 0xff;
-    sha_info->data[61] = (lo_bit_count >> 16) & 0xff;
-    sha_info->data[62] = (lo_bit_count >>  8) & 0xff;
-    sha_info->data[63] = (lo_bit_count >>  0) & 0xff;
-    sha_transform(sha_info);
-    digest[ 0] = (unsigned char) ((sha_info->digest[0] >> 24) & 0xff);
-    digest[ 1] = (unsigned char) ((sha_info->digest[0] >> 16) & 0xff);
-    digest[ 2] = (unsigned char) ((sha_info->digest[0] >>  8) & 0xff);
-    digest[ 3] = (unsigned char) ((sha_info->digest[0]      ) & 0xff);
-    digest[ 4] = (unsigned char) ((sha_info->digest[1] >> 24) & 0xff);
-    digest[ 5] = (unsigned char) ((sha_info->digest[1] >> 16) & 0xff);
-    digest[ 6] = (unsigned char) ((sha_info->digest[1] >>  8) & 0xff);
-    digest[ 7] = (unsigned char) ((sha_info->digest[1]      ) & 0xff);
-    digest[ 8] = (unsigned char) ((sha_info->digest[2] >> 24) & 0xff);
-    digest[ 9] = (unsigned char) ((sha_info->digest[2] >> 16) & 0xff);
-    digest[10] = (unsigned char) ((sha_info->digest[2] >>  8) & 0xff);
-    digest[11] = (unsigned char) ((sha_info->digest[2]      ) & 0xff);
-    digest[12] = (unsigned char) ((sha_info->digest[3] >> 24) & 0xff);
-    digest[13] = (unsigned char) ((sha_info->digest[3] >> 16) & 0xff);
-    digest[14] = (unsigned char) ((sha_info->digest[3] >>  8) & 0xff);
-    digest[15] = (unsigned char) ((sha_info->digest[3]      ) & 0xff);
-    digest[16] = (unsigned char) ((sha_info->digest[4] >> 24) & 0xff);
-    digest[17] = (unsigned char) ((sha_info->digest[4] >> 16) & 0xff);
-    digest[18] = (unsigned char) ((sha_info->digest[4] >>  8) & 0xff);
-    digest[19] = (unsigned char) ((sha_info->digest[4]      ) & 0xff);
-    digest[20] = (unsigned char) ((sha_info->digest[5] >> 24) & 0xff);
-    digest[21] = (unsigned char) ((sha_info->digest[5] >> 16) & 0xff);
-    digest[22] = (unsigned char) ((sha_info->digest[5] >>  8) & 0xff);
-    digest[23] = (unsigned char) ((sha_info->digest[5]      ) & 0xff);
-    digest[24] = (unsigned char) ((sha_info->digest[6] >> 24) & 0xff);
-    digest[25] = (unsigned char) ((sha_info->digest[6] >> 16) & 0xff);
-    digest[26] = (unsigned char) ((sha_info->digest[6] >>  8) & 0xff);
-    digest[27] = (unsigned char) ((sha_info->digest[6]      ) & 0xff);
-    digest[28] = (unsigned char) ((sha_info->digest[7] >> 24) & 0xff);
-    digest[29] = (unsigned char) ((sha_info->digest[7] >> 16) & 0xff);
-    digest[30] = (unsigned char) ((sha_info->digest[7] >>  8) & 0xff);
-    digest[31] = (unsigned char) ((sha_info->digest[7]      ) & 0xff);
-}
-
-/*
- * End of copied SHA code.
- *
- * ------------------------------------------------------------------------
- */
-
-static PyTypeObject SHA224type;
-static PyTypeObject SHA256type;
-
-
-static SHAobject *
-newSHA224object(void)
-{
-    return (SHAobject *)PyObject_New(SHAobject, &SHA224type);
-}
-
-static SHAobject *
-newSHA256object(void)
-{
-    return (SHAobject *)PyObject_New(SHAobject, &SHA256type);
-}
-
-/* Internal methods for a hash object */
-
-static void
-SHA_dealloc(PyObject *ptr)
-{
-    PyObject_Del(ptr);
-}
-
-
-/* External methods for a hash object */
-
-/*[clinic input]
-SHA256Type.copy
-
-Return a copy of the hash object.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(SHA256Type_copy__doc__,
@@ -422,30 +20,6 @@
     return SHA256Type_copy_impl(self);
 }
 
-static PyObject *
-SHA256Type_copy_impl(SHAobject *self)
-/*[clinic end generated code: output=f716c39d3f81c27c input=f58840a618d4f2a7]*/
-{
-    SHAobject *newobj;
-
-    if (Py_TYPE(self) == &SHA256type) {
-        if ( (newobj = newSHA256object())==NULL)
-            return NULL;
-    } else {
-        if ( (newobj = newSHA224object())==NULL)
-            return NULL;
-    }
-
-    SHAcopy(self, newobj);
-    return (PyObject *)newobj;
-}
-
-/*[clinic input]
-SHA256Type.digest
-
-Return the digest value as a string of binary data.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(SHA256Type_digest__doc__,
 "digest($self, /)\n"
 "--\n"
@@ -464,24 +38,6 @@
     return SHA256Type_digest_impl(self);
 }
 
-static PyObject *
-SHA256Type_digest_impl(SHAobject *self)
-/*[clinic end generated code: output=72d34723d7bb694c input=1fb752e58954157d]*/
-{
-    unsigned char digest[SHA_DIGESTSIZE];
-    SHAobject temp;
-
-    SHAcopy(self, &temp);
-    sha_final(digest, &temp);
-    return PyBytes_FromStringAndSize((const char *)digest, self->digestsize);
-}
-
-/*[clinic input]
-SHA256Type.hexdigest
-
-Return the digest value as a string of hexadecimal digits.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(SHA256Type_hexdigest__doc__,
 "hexdigest($self, /)\n"
 "--\n"
@@ -500,49 +56,6 @@
     return SHA256Type_hexdigest_impl(self);
 }
 
-static PyObject *
-SHA256Type_hexdigest_impl(SHAobject *self)
-/*[clinic end generated code: output=3687aa6183c7d27f input=0cc4c714693010d1]*/
-{
-    unsigned char digest[SHA_DIGESTSIZE];
-    SHAobject temp;
-    PyObject *retval;
-    Py_UCS1 *hex_digest;
-    int i, j;
-
-    /* Get the raw (binary) digest value */
-    SHAcopy(self, &temp);
-    sha_final(digest, &temp);
-
-    /* Create a new string */
-    retval = PyUnicode_New(self->digestsize * 2, 127);
-    if (!retval)
-            return NULL;
-    hex_digest = PyUnicode_1BYTE_DATA(retval);
-
-    /* Make hex version of the digest */
-    for(i=j=0; i<self->digestsize; i++) {
-        unsigned char c;
-        c = (digest[i] >> 4) & 0xf;
-        hex_digest[j++] = Py_hexdigits[c];
-        c = (digest[i] & 0xf);
-        hex_digest[j++] = Py_hexdigits[c];
-    }
-#ifdef Py_DEBUG
-    assert(_PyUnicode_CheckConsistency(retval, 1));
-#endif
-    return retval;
-}
-
-/*[clinic input]
-SHA256Type.update
-
-    obj: object
-    /
-
-Update this hash object's state with the provided string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(SHA256Type_update__doc__,
 "update($self, obj, /)\n"
 "--\n"
@@ -552,140 +65,6 @@
 #define SHA256TYPE_UPDATE_METHODDEF    \
     {"update", (PyCFunction)SHA256Type_update, METH_O, SHA256Type_update__doc__},
 
-static PyObject *
-SHA256Type_update(SHAobject *self, PyObject *obj)
-/*[clinic end generated code: output=b47f53d7cbeabee4 input=b2d449d5b30f0f5a]*/
-{
-    Py_buffer buf;
-
-    GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
-
-    sha_update(self, buf.buf, buf.len);
-
-    PyBuffer_Release(&buf);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyMethodDef SHA_methods[] = {
-    SHA256TYPE_COPY_METHODDEF
-    SHA256TYPE_DIGEST_METHODDEF
-    SHA256TYPE_HEXDIGEST_METHODDEF
-    SHA256TYPE_UPDATE_METHODDEF
-    {NULL,        NULL}         /* sentinel */
-};
-
-static PyObject *
-SHA256_get_block_size(PyObject *self, void *closure)
-{
-    return PyLong_FromLong(SHA_BLOCKSIZE);
-}
-
-static PyObject *
-SHA256_get_name(PyObject *self, void *closure)
-{
-    if (((SHAobject *)self)->digestsize == 32)
-        return PyUnicode_FromStringAndSize("sha256", 6);
-    else
-        return PyUnicode_FromStringAndSize("sha224", 6);
-}
-
-static PyGetSetDef SHA_getseters[] = {
-    {"block_size",
-     (getter)SHA256_get_block_size, NULL,
-     NULL,
-     NULL},
-    {"name",
-     (getter)SHA256_get_name, NULL,
-     NULL,
-     NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyMemberDef SHA_members[] = {
-    {"digest_size", T_INT, offsetof(SHAobject, digestsize), READONLY, NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyTypeObject SHA224type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_sha256.sha224",   /*tp_name*/
-    sizeof(SHAobject),  /*tp_size*/
-    0,                  /*tp_itemsize*/
-    /* methods */
-    SHA_dealloc,        /*tp_dealloc*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,                  /*tp_clear*/
-    0,                  /*tp_richcompare*/
-    0,                  /*tp_weaklistoffset*/
-    0,                  /*tp_iter*/
-    0,                  /*tp_iternext*/
-    SHA_methods,        /* tp_methods */
-    SHA_members,        /* tp_members */
-    SHA_getseters,      /* tp_getset */
-};
-
-static PyTypeObject SHA256type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_sha256.sha256",   /*tp_name*/
-    sizeof(SHAobject),  /*tp_size*/
-    0,                  /*tp_itemsize*/
-    /* methods */
-    SHA_dealloc,        /*tp_dealloc*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,                  /*tp_clear*/
-    0,                  /*tp_richcompare*/
-    0,                  /*tp_weaklistoffset*/
-    0,                  /*tp_iter*/
-    0,                  /*tp_iternext*/
-    SHA_methods,        /* tp_methods */
-    SHA_members,        /* tp_members */
-    SHA_getseters,      /* tp_getset */
-};
-
-
-/* The single module-level function: new() */
-
-/*[clinic input]
-_sha256.sha256
-
-    string: object(c_default="NULL") = b''
-
-Return a new SHA-256 hash object; optionally initialized with a string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(_sha256_sha256__doc__,
 "sha256($module, /, string=b\'\')\n"
 "--\n"
@@ -715,46 +94,6 @@
     return return_value;
 }
 
-static PyObject *
-_sha256_sha256_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=4b1263d1e2fcdb98 input=09cce3fb855056b2]*/
-{
-    SHAobject *new;
-    Py_buffer buf;
-
-    if (string)
-        GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
-
-    if ((new = newSHA256object()) == NULL) {
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-
-    sha_init(new);
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-    if (string) {
-        sha_update(new, buf.buf, buf.len);
-        PyBuffer_Release(&buf);
-    }
-
-    return (PyObject *)new;
-}
-
-/*[clinic input]
-_sha256.sha224
-
-    string: object(c_default="NULL") = b''
-
-Return a new SHA-224 hash object; optionally initialized with a string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(_sha256_sha224__doc__,
 "sha224($module, /, string=b\'\')\n"
 "--\n"
@@ -783,86 +122,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-_sha256_sha224_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=4dde0eb1cdaebc06 input=27a04ba24c353a73]*/
-{
-    SHAobject *new;
-    Py_buffer buf;
-
-    if (string)
-        GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
-
-    if ((new = newSHA224object()) == NULL) {
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-
-    sha224_init(new);
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-    if (string) {
-        sha_update(new, buf.buf, buf.len);
-        PyBuffer_Release(&buf);
-    }
-
-    return (PyObject *)new;
-}
-
-
-/* List of functions exported by this module */
-
-static struct PyMethodDef SHA_functions[] = {
-    _SHA256_SHA256_METHODDEF
-    _SHA256_SHA224_METHODDEF
-    {NULL,      NULL}            /* Sentinel */
-};
-
-
-/* Initialize this module. */
-
-#define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
-
-
-static struct PyModuleDef _sha256module = {
-        PyModuleDef_HEAD_INIT,
-        "_sha256",
-        NULL,
-        -1,
-        SHA_functions,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-PyInit__sha256(void)
-{
-    PyObject *m;
-
-    Py_TYPE(&SHA224type) = &PyType_Type;
-    if (PyType_Ready(&SHA224type) < 0)
-        return NULL;
-    Py_TYPE(&SHA256type) = &PyType_Type;
-    if (PyType_Ready(&SHA256type) < 0)
-        return NULL;
-
-    m = PyModule_Create(&_sha256module);
-    if (m == NULL)
-        return NULL;
-
-    Py_INCREF((PyObject *)&SHA224type);
-    PyModule_AddObject(m, "SHA224Type", (PyObject *)&SHA224type);
-    Py_INCREF((PyObject *)&SHA256type);
-    PyModule_AddObject(m, "SHA256Type", (PyObject *)&SHA256type);
-    return m;
-
-}
+/*[clinic end generated code: output=8a0520371b097358 input=a9049054013a1b77]*/
diff --git a/Modules/sha512module.c b/Modules/clinic/sha512module.c.h
copy from Modules/sha512module.c
copy to Modules/clinic/sha512module.c.h
--- a/Modules/sha512module.c
+++ b/Modules/clinic/sha512module.c.h
@@ -1,475 +1,8 @@
-/* SHA512 module */
+/*[clinic input]
+preserve
+[clinic start generated code]*/
 
-/* This module provides an interface to NIST's SHA-512 and SHA-384 Algorithms */
-
-/* See below for information about the original code this module was
-   based upon. Additional work performed by:
-
-   Andrew Kuchling (amk at amk.ca)
-   Greg Stein (gstein at lyra.org)
-   Trevor Perrin (trevp at trevp.net)
-
-   Copyright (C) 2005-2007   Gregory P. Smith (greg at krypto.org)
-   Licensed to PSF under a Contributor Agreement.
-
-*/
-
-/* SHA objects */
-
-#include "Python.h"
-#include "structmember.h"
-#include "hashlib.h"
-
-/*[clinic input]
-module _sha512
-class SHA512Type "SHAobject *" "&PyType_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=81a3ccde92bcfe8d]*/
-
-#ifdef PY_LONG_LONG /* If no PY_LONG_LONG, don't compile anything! */
-
-/* Some useful types */
-
-typedef unsigned char SHA_BYTE;
-
-#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
-typedef unsigned PY_LONG_LONG SHA_INT64;        /* 64-bit integer */
-#else
-/* not defined. compilation will die. */
-#endif
-
-/* The SHA block size and message digest sizes, in bytes */
-
-#define SHA_BLOCKSIZE   128
-#define SHA_DIGESTSIZE  64
-
-/* The structure for storing SHA info */
-
-typedef struct {
-    PyObject_HEAD
-    SHA_INT64 digest[8];                /* Message digest */
-    SHA_INT32 count_lo, count_hi;       /* 64-bit bit count */
-    SHA_BYTE data[SHA_BLOCKSIZE];       /* SHA data buffer */
-    int local;                          /* unprocessed amount in data */
-    int digestsize;
-} SHAobject;
-
-/* When run on a little-endian CPU we need to perform byte reversal on an
-   array of longwords. */
-
-#if PY_LITTLE_ENDIAN
-static void longReverse(SHA_INT64 *buffer, int byteCount)
-{
-    SHA_INT64 value;
-
-    byteCount /= sizeof(*buffer);
-    while (byteCount--) {
-        value = *buffer;
-
-                ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff;
-                ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff;
-                ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff;
-                ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff;
-                ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff;
-                ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff;
-                ((unsigned char*)buffer)[6] = (unsigned char)(value >>  8) & 0xff;
-                ((unsigned char*)buffer)[7] = (unsigned char)(value      ) & 0xff;
-
-                buffer++;
-    }
-}
-#endif
-
-static void SHAcopy(SHAobject *src, SHAobject *dest)
-{
-    dest->local = src->local;
-    dest->digestsize = src->digestsize;
-    dest->count_lo = src->count_lo;
-    dest->count_hi = src->count_hi;
-    memcpy(dest->digest, src->digest, sizeof(src->digest));
-    memcpy(dest->data, src->data, sizeof(src->data));
-}
-
-
-/* ------------------------------------------------------------------------
- *
- * This code for the SHA-512 algorithm was noted as public domain. The
- * original headers are pasted below.
- *
- * Several changes have been made to make it more compatible with the
- * Python environment and desired interface.
- *
- */
-
-/* LibTomCrypt, modular cryptographic library -- Tom St Denis
- *
- * LibTomCrypt is a library that provides various cryptographic
- * algorithms in a highly modular and flexible manner.
- *
- * The library is free for all purposes without any express
- * gurantee it works.
- *
- * Tom St Denis, tomstdenis at iahu.ca, http://libtom.org
- */
-
-
-/* SHA512 by Tom St Denis */
-
-/* Various logical functions */
-#define ROR64(x, y) \
-    ( ((((x) & Py_ULL(0xFFFFFFFFFFFFFFFF))>>((unsigned PY_LONG_LONG)(y) & 63)) | \
-      ((x)<<((unsigned PY_LONG_LONG)(64-((y) & 63))))) & Py_ULL(0xFFFFFFFFFFFFFFFF))
-#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
-#define Maj(x,y,z)      (((x | y) & z) | (x & y))
-#define S(x, n)         ROR64((x),(n))
-#define R(x, n)         (((x) & Py_ULL(0xFFFFFFFFFFFFFFFF)) >> ((unsigned PY_LONG_LONG)n))
-#define Sigma0(x)       (S(x, 28) ^ S(x, 34) ^ S(x, 39))
-#define Sigma1(x)       (S(x, 14) ^ S(x, 18) ^ S(x, 41))
-#define Gamma0(x)       (S(x, 1) ^ S(x, 8) ^ R(x, 7))
-#define Gamma1(x)       (S(x, 19) ^ S(x, 61) ^ R(x, 6))
-
-
-static void
-sha512_transform(SHAobject *sha_info)
-{
-    int i;
-    SHA_INT64 S[8], W[80], t0, t1;
-
-    memcpy(W, sha_info->data, sizeof(sha_info->data));
-#if PY_LITTLE_ENDIAN
-    longReverse(W, (int)sizeof(sha_info->data));
-#endif
-
-    for (i = 16; i < 80; ++i) {
-                W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
-    }
-    for (i = 0; i < 8; ++i) {
-        S[i] = sha_info->digest[i];
-    }
-
-    /* Compress */
-#define RND(a,b,c,d,e,f,g,h,i,ki)                    \
-     t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i];   \
-     t1 = Sigma0(a) + Maj(a, b, c);                  \
-     d += t0;                                        \
-     h  = t0 + t1;
-
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,Py_ULL(0x428a2f98d728ae22));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,Py_ULL(0x7137449123ef65cd));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,Py_ULL(0xb5c0fbcfec4d3b2f));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,Py_ULL(0xe9b5dba58189dbbc));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,Py_ULL(0x3956c25bf348b538));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,Py_ULL(0x59f111f1b605d019));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,Py_ULL(0x923f82a4af194f9b));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,Py_ULL(0xab1c5ed5da6d8118));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,Py_ULL(0xd807aa98a3030242));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,Py_ULL(0x12835b0145706fbe));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,Py_ULL(0x243185be4ee4b28c));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,Py_ULL(0x550c7dc3d5ffb4e2));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,Py_ULL(0x72be5d74f27b896f));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,Py_ULL(0x80deb1fe3b1696b1));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,Py_ULL(0x9bdc06a725c71235));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,Py_ULL(0xc19bf174cf692694));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,Py_ULL(0xe49b69c19ef14ad2));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,Py_ULL(0xefbe4786384f25e3));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,Py_ULL(0x0fc19dc68b8cd5b5));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,Py_ULL(0x240ca1cc77ac9c65));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,Py_ULL(0x2de92c6f592b0275));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,Py_ULL(0x4a7484aa6ea6e483));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,Py_ULL(0x5cb0a9dcbd41fbd4));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,Py_ULL(0x76f988da831153b5));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,Py_ULL(0x983e5152ee66dfab));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,Py_ULL(0xa831c66d2db43210));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,Py_ULL(0xb00327c898fb213f));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,Py_ULL(0xbf597fc7beef0ee4));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,Py_ULL(0xc6e00bf33da88fc2));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,Py_ULL(0xd5a79147930aa725));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,Py_ULL(0x06ca6351e003826f));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,Py_ULL(0x142929670a0e6e70));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,Py_ULL(0x27b70a8546d22ffc));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,Py_ULL(0x2e1b21385c26c926));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,Py_ULL(0x4d2c6dfc5ac42aed));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,Py_ULL(0x53380d139d95b3df));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,Py_ULL(0x650a73548baf63de));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,Py_ULL(0x766a0abb3c77b2a8));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,Py_ULL(0x81c2c92e47edaee6));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,Py_ULL(0x92722c851482353b));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,Py_ULL(0xa2bfe8a14cf10364));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,Py_ULL(0xa81a664bbc423001));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,Py_ULL(0xc24b8b70d0f89791));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,Py_ULL(0xc76c51a30654be30));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,Py_ULL(0xd192e819d6ef5218));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,Py_ULL(0xd69906245565a910));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,Py_ULL(0xf40e35855771202a));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,Py_ULL(0x106aa07032bbd1b8));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,Py_ULL(0x19a4c116b8d2d0c8));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,Py_ULL(0x1e376c085141ab53));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,Py_ULL(0x2748774cdf8eeb99));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,Py_ULL(0x34b0bcb5e19b48a8));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,Py_ULL(0x391c0cb3c5c95a63));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,Py_ULL(0x4ed8aa4ae3418acb));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,Py_ULL(0x5b9cca4f7763e373));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,Py_ULL(0x682e6ff3d6b2b8a3));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,Py_ULL(0x748f82ee5defb2fc));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,Py_ULL(0x78a5636f43172f60));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,Py_ULL(0x84c87814a1f0ab72));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,Py_ULL(0x8cc702081a6439ec));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,Py_ULL(0x90befffa23631e28));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,Py_ULL(0xa4506cebde82bde9));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,Py_ULL(0xbef9a3f7b2c67915));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,Py_ULL(0xc67178f2e372532b));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],64,Py_ULL(0xca273eceea26619c));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],65,Py_ULL(0xd186b8c721c0c207));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],66,Py_ULL(0xeada7dd6cde0eb1e));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],67,Py_ULL(0xf57d4f7fee6ed178));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],68,Py_ULL(0x06f067aa72176fba));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],69,Py_ULL(0x0a637dc5a2c898a6));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],70,Py_ULL(0x113f9804bef90dae));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],71,Py_ULL(0x1b710b35131c471b));
-    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],72,Py_ULL(0x28db77f523047d84));
-    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],73,Py_ULL(0x32caab7b40c72493));
-    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],74,Py_ULL(0x3c9ebe0a15c9bebc));
-    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],75,Py_ULL(0x431d67c49c100d4c));
-    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],76,Py_ULL(0x4cc5d4becb3e42b6));
-    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],77,Py_ULL(0x597f299cfc657e2a));
-    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],78,Py_ULL(0x5fcb6fab3ad6faec));
-    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],79,Py_ULL(0x6c44198c4a475817));
-
-#undef RND
-
-    /* feedback */
-    for (i = 0; i < 8; i++) {
-        sha_info->digest[i] = sha_info->digest[i] + S[i];
-    }
-
-}
-
-
-
-/* initialize the SHA digest */
-
-static void
-sha512_init(SHAobject *sha_info)
-{
-    sha_info->digest[0] = Py_ULL(0x6a09e667f3bcc908);
-    sha_info->digest[1] = Py_ULL(0xbb67ae8584caa73b);
-    sha_info->digest[2] = Py_ULL(0x3c6ef372fe94f82b);
-    sha_info->digest[3] = Py_ULL(0xa54ff53a5f1d36f1);
-    sha_info->digest[4] = Py_ULL(0x510e527fade682d1);
-    sha_info->digest[5] = Py_ULL(0x9b05688c2b3e6c1f);
-    sha_info->digest[6] = Py_ULL(0x1f83d9abfb41bd6b);
-    sha_info->digest[7] = Py_ULL(0x5be0cd19137e2179);
-    sha_info->count_lo = 0L;
-    sha_info->count_hi = 0L;
-    sha_info->local = 0;
-    sha_info->digestsize = 64;
-}
-
-static void
-sha384_init(SHAobject *sha_info)
-{
-    sha_info->digest[0] = Py_ULL(0xcbbb9d5dc1059ed8);
-    sha_info->digest[1] = Py_ULL(0x629a292a367cd507);
-    sha_info->digest[2] = Py_ULL(0x9159015a3070dd17);
-    sha_info->digest[3] = Py_ULL(0x152fecd8f70e5939);
-    sha_info->digest[4] = Py_ULL(0x67332667ffc00b31);
-    sha_info->digest[5] = Py_ULL(0x8eb44a8768581511);
-    sha_info->digest[6] = Py_ULL(0xdb0c2e0d64f98fa7);
-    sha_info->digest[7] = Py_ULL(0x47b5481dbefa4fa4);
-    sha_info->count_lo = 0L;
-    sha_info->count_hi = 0L;
-    sha_info->local = 0;
-    sha_info->digestsize = 48;
-}
-
-
-/* update the SHA digest */
-
-static void
-sha512_update(SHAobject *sha_info, SHA_BYTE *buffer, Py_ssize_t count)
-{
-    Py_ssize_t i;
-    SHA_INT32 clo;
-
-    clo = sha_info->count_lo + ((SHA_INT32) count << 3);
-    if (clo < sha_info->count_lo) {
-        ++sha_info->count_hi;
-    }
-    sha_info->count_lo = clo;
-    sha_info->count_hi += (SHA_INT32) count >> 29;
-    if (sha_info->local) {
-        i = SHA_BLOCKSIZE - sha_info->local;
-        if (i > count) {
-            i = count;
-        }
-        memcpy(((SHA_BYTE *) sha_info->data) + sha_info->local, buffer, i);
-        count -= i;
-        buffer += i;
-        sha_info->local += (int)i;
-        if (sha_info->local == SHA_BLOCKSIZE) {
-            sha512_transform(sha_info);
-        }
-        else {
-            return;
-        }
-    }
-    while (count >= SHA_BLOCKSIZE) {
-        memcpy(sha_info->data, buffer, SHA_BLOCKSIZE);
-        buffer += SHA_BLOCKSIZE;
-        count -= SHA_BLOCKSIZE;
-        sha512_transform(sha_info);
-    }
-    memcpy(sha_info->data, buffer, count);
-    sha_info->local = (int)count;
-}
-
-/* finish computing the SHA digest */
-
-static void
-sha512_final(unsigned char digest[SHA_DIGESTSIZE], SHAobject *sha_info)
-{
-    int count;
-    SHA_INT32 lo_bit_count, hi_bit_count;
-
-    lo_bit_count = sha_info->count_lo;
-    hi_bit_count = sha_info->count_hi;
-    count = (int) ((lo_bit_count >> 3) & 0x7f);
-    ((SHA_BYTE *) sha_info->data)[count++] = 0x80;
-    if (count > SHA_BLOCKSIZE - 16) {
-        memset(((SHA_BYTE *) sha_info->data) + count, 0,
-               SHA_BLOCKSIZE - count);
-        sha512_transform(sha_info);
-        memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16);
-    }
-    else {
-        memset(((SHA_BYTE *) sha_info->data) + count, 0,
-               SHA_BLOCKSIZE - 16 - count);
-    }
-
-    /* GJS: note that we add the hi/lo in big-endian. sha512_transform will
-       swap these values into host-order. */
-    sha_info->data[112] = 0;
-    sha_info->data[113] = 0;
-    sha_info->data[114] = 0;
-    sha_info->data[115] = 0;
-    sha_info->data[116] = 0;
-    sha_info->data[117] = 0;
-    sha_info->data[118] = 0;
-    sha_info->data[119] = 0;
-    sha_info->data[120] = (hi_bit_count >> 24) & 0xff;
-    sha_info->data[121] = (hi_bit_count >> 16) & 0xff;
-    sha_info->data[122] = (hi_bit_count >>  8) & 0xff;
-    sha_info->data[123] = (hi_bit_count >>  0) & 0xff;
-    sha_info->data[124] = (lo_bit_count >> 24) & 0xff;
-    sha_info->data[125] = (lo_bit_count >> 16) & 0xff;
-    sha_info->data[126] = (lo_bit_count >>  8) & 0xff;
-    sha_info->data[127] = (lo_bit_count >>  0) & 0xff;
-    sha512_transform(sha_info);
-    digest[ 0] = (unsigned char) ((sha_info->digest[0] >> 56) & 0xff);
-    digest[ 1] = (unsigned char) ((sha_info->digest[0] >> 48) & 0xff);
-    digest[ 2] = (unsigned char) ((sha_info->digest[0] >> 40) & 0xff);
-    digest[ 3] = (unsigned char) ((sha_info->digest[0] >> 32) & 0xff);
-    digest[ 4] = (unsigned char) ((sha_info->digest[0] >> 24) & 0xff);
-    digest[ 5] = (unsigned char) ((sha_info->digest[0] >> 16) & 0xff);
-    digest[ 6] = (unsigned char) ((sha_info->digest[0] >>  8) & 0xff);
-    digest[ 7] = (unsigned char) ((sha_info->digest[0]      ) & 0xff);
-    digest[ 8] = (unsigned char) ((sha_info->digest[1] >> 56) & 0xff);
-    digest[ 9] = (unsigned char) ((sha_info->digest[1] >> 48) & 0xff);
-    digest[10] = (unsigned char) ((sha_info->digest[1] >> 40) & 0xff);
-    digest[11] = (unsigned char) ((sha_info->digest[1] >> 32) & 0xff);
-    digest[12] = (unsigned char) ((sha_info->digest[1] >> 24) & 0xff);
-    digest[13] = (unsigned char) ((sha_info->digest[1] >> 16) & 0xff);
-    digest[14] = (unsigned char) ((sha_info->digest[1] >>  8) & 0xff);
-    digest[15] = (unsigned char) ((sha_info->digest[1]      ) & 0xff);
-    digest[16] = (unsigned char) ((sha_info->digest[2] >> 56) & 0xff);
-    digest[17] = (unsigned char) ((sha_info->digest[2] >> 48) & 0xff);
-    digest[18] = (unsigned char) ((sha_info->digest[2] >> 40) & 0xff);
-    digest[19] = (unsigned char) ((sha_info->digest[2] >> 32) & 0xff);
-    digest[20] = (unsigned char) ((sha_info->digest[2] >> 24) & 0xff);
-    digest[21] = (unsigned char) ((sha_info->digest[2] >> 16) & 0xff);
-    digest[22] = (unsigned char) ((sha_info->digest[2] >>  8) & 0xff);
-    digest[23] = (unsigned char) ((sha_info->digest[2]      ) & 0xff);
-    digest[24] = (unsigned char) ((sha_info->digest[3] >> 56) & 0xff);
-    digest[25] = (unsigned char) ((sha_info->digest[3] >> 48) & 0xff);
-    digest[26] = (unsigned char) ((sha_info->digest[3] >> 40) & 0xff);
-    digest[27] = (unsigned char) ((sha_info->digest[3] >> 32) & 0xff);
-    digest[28] = (unsigned char) ((sha_info->digest[3] >> 24) & 0xff);
-    digest[29] = (unsigned char) ((sha_info->digest[3] >> 16) & 0xff);
-    digest[30] = (unsigned char) ((sha_info->digest[3] >>  8) & 0xff);
-    digest[31] = (unsigned char) ((sha_info->digest[3]      ) & 0xff);
-    digest[32] = (unsigned char) ((sha_info->digest[4] >> 56) & 0xff);
-    digest[33] = (unsigned char) ((sha_info->digest[4] >> 48) & 0xff);
-    digest[34] = (unsigned char) ((sha_info->digest[4] >> 40) & 0xff);
-    digest[35] = (unsigned char) ((sha_info->digest[4] >> 32) & 0xff);
-    digest[36] = (unsigned char) ((sha_info->digest[4] >> 24) & 0xff);
-    digest[37] = (unsigned char) ((sha_info->digest[4] >> 16) & 0xff);
-    digest[38] = (unsigned char) ((sha_info->digest[4] >>  8) & 0xff);
-    digest[39] = (unsigned char) ((sha_info->digest[4]      ) & 0xff);
-    digest[40] = (unsigned char) ((sha_info->digest[5] >> 56) & 0xff);
-    digest[41] = (unsigned char) ((sha_info->digest[5] >> 48) & 0xff);
-    digest[42] = (unsigned char) ((sha_info->digest[5] >> 40) & 0xff);
-    digest[43] = (unsigned char) ((sha_info->digest[5] >> 32) & 0xff);
-    digest[44] = (unsigned char) ((sha_info->digest[5] >> 24) & 0xff);
-    digest[45] = (unsigned char) ((sha_info->digest[5] >> 16) & 0xff);
-    digest[46] = (unsigned char) ((sha_info->digest[5] >>  8) & 0xff);
-    digest[47] = (unsigned char) ((sha_info->digest[5]      ) & 0xff);
-    digest[48] = (unsigned char) ((sha_info->digest[6] >> 56) & 0xff);
-    digest[49] = (unsigned char) ((sha_info->digest[6] >> 48) & 0xff);
-    digest[50] = (unsigned char) ((sha_info->digest[6] >> 40) & 0xff);
-    digest[51] = (unsigned char) ((sha_info->digest[6] >> 32) & 0xff);
-    digest[52] = (unsigned char) ((sha_info->digest[6] >> 24) & 0xff);
-    digest[53] = (unsigned char) ((sha_info->digest[6] >> 16) & 0xff);
-    digest[54] = (unsigned char) ((sha_info->digest[6] >>  8) & 0xff);
-    digest[55] = (unsigned char) ((sha_info->digest[6]      ) & 0xff);
-    digest[56] = (unsigned char) ((sha_info->digest[7] >> 56) & 0xff);
-    digest[57] = (unsigned char) ((sha_info->digest[7] >> 48) & 0xff);
-    digest[58] = (unsigned char) ((sha_info->digest[7] >> 40) & 0xff);
-    digest[59] = (unsigned char) ((sha_info->digest[7] >> 32) & 0xff);
-    digest[60] = (unsigned char) ((sha_info->digest[7] >> 24) & 0xff);
-    digest[61] = (unsigned char) ((sha_info->digest[7] >> 16) & 0xff);
-    digest[62] = (unsigned char) ((sha_info->digest[7] >>  8) & 0xff);
-    digest[63] = (unsigned char) ((sha_info->digest[7]      ) & 0xff);
-}
-
-/*
- * End of copied SHA code.
- *
- * ------------------------------------------------------------------------
- */
-
-static PyTypeObject SHA384type;
-static PyTypeObject SHA512type;
-
-
-static SHAobject *
-newSHA384object(void)
-{
-    return (SHAobject *)PyObject_New(SHAobject, &SHA384type);
-}
-
-static SHAobject *
-newSHA512object(void)
-{
-    return (SHAobject *)PyObject_New(SHAobject, &SHA512type);
-}
-
-/* Internal methods for a hash object */
-
-static void
-SHA512_dealloc(PyObject *ptr)
-{
-    PyObject_Del(ptr);
-}
-
-
-/* External methods for a hash object */
-
-/*[clinic input]
-SHA512Type.copy
-
-Return a copy of the hash object.
-[clinic start generated code]*/
+#if defined(PY_LONG_LONG)
 
 PyDoc_STRVAR(SHA512Type_copy__doc__,
 "copy($self, /)\n"
@@ -489,29 +22,9 @@
     return SHA512Type_copy_impl(self);
 }
 
-static PyObject *
-SHA512Type_copy_impl(SHAobject *self)
-/*[clinic end generated code: output=14f8e6ce9c61ece0 input=9f5f31e6c457776a]*/
-{
-    SHAobject *newobj;
+#endif /* defined(PY_LONG_LONG) */
 
-    if (((PyObject*)self)->ob_type == &SHA512type) {
-        if ( (newobj = newSHA512object())==NULL)
-            return NULL;
-    } else {
-        if ( (newobj = newSHA384object())==NULL)
-            return NULL;
-    }
-
-    SHAcopy(self, newobj);
-    return (PyObject *)newobj;
-}
-
-/*[clinic input]
-SHA512Type.digest
-
-Return the digest value as a string of binary data.
-[clinic start generated code]*/
+#if defined(PY_LONG_LONG)
 
 PyDoc_STRVAR(SHA512Type_digest__doc__,
 "digest($self, /)\n"
@@ -531,23 +44,9 @@
     return SHA512Type_digest_impl(self);
 }
 
-static PyObject *
-SHA512Type_digest_impl(SHAobject *self)
-/*[clinic end generated code: output=be8de024b232977e input=60c2cede9e023018]*/
-{
-    unsigned char digest[SHA_DIGESTSIZE];
-    SHAobject temp;
+#endif /* defined(PY_LONG_LONG) */
 
-    SHAcopy(self, &temp);
-    sha512_final(digest, &temp);
-    return PyBytes_FromStringAndSize((const char *)digest, self->digestsize);
-}
-
-/*[clinic input]
-SHA512Type.hexdigest
-
-Return the digest value as a string of hexadecimal digits.
-[clinic start generated code]*/
+#if defined(PY_LONG_LONG)
 
 PyDoc_STRVAR(SHA512Type_hexdigest__doc__,
 "hexdigest($self, /)\n"
@@ -567,48 +66,9 @@
     return SHA512Type_hexdigest_impl(self);
 }
 
-static PyObject *
-SHA512Type_hexdigest_impl(SHAobject *self)
-/*[clinic end generated code: output=28a4ab2f9a1781b8 input=498b877b25cbe0a2]*/
-{
-    unsigned char digest[SHA_DIGESTSIZE];
-    SHAobject temp;
-    PyObject *retval;
-    Py_UCS1 *hex_digest;
-    int i, j;
+#endif /* defined(PY_LONG_LONG) */
 
-    /* Get the raw (binary) digest value */
-    SHAcopy(self, &temp);
-    sha512_final(digest, &temp);
-
-    /* Create a new string */
-    retval = PyUnicode_New(self->digestsize * 2, 127);
-    if (!retval)
-            return NULL;
-    hex_digest = PyUnicode_1BYTE_DATA(retval);
-
-    /* Make hex version of the digest */
-    for (i=j=0; i<self->digestsize; i++) {
-        unsigned char c;
-        c = (digest[i] >> 4) & 0xf;
-        hex_digest[j++] = Py_hexdigits[c];
-        c = (digest[i] & 0xf);
-        hex_digest[j++] = Py_hexdigits[c];
-    }
-#ifdef Py_DEBUG
-    assert(_PyUnicode_CheckConsistency(retval, 1));
-#endif
-    return retval;
-}
-
-/*[clinic input]
-SHA512Type.update
-
-    obj: object
-    /
-
-Update this hash object's state with the provided string.
-[clinic start generated code]*/
+#if defined(PY_LONG_LONG)
 
 PyDoc_STRVAR(SHA512Type_update__doc__,
 "update($self, obj, /)\n"
@@ -619,159 +79,9 @@
 #define SHA512TYPE_UPDATE_METHODDEF    \
     {"update", (PyCFunction)SHA512Type_update, METH_O, SHA512Type_update__doc__},
 
-static PyObject *
-SHA512Type_update(SHAobject *self, PyObject *obj)
-/*[clinic end generated code: output=6be574cdc3a9c52d input=ded2b46656566283]*/
-{
-    Py_buffer buf;
+#endif /* defined(PY_LONG_LONG) */
 
-    GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
-
-    sha512_update(self, buf.buf, buf.len);
-
-    PyBuffer_Release(&buf);
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-/*[clinic input]
-dump buffer
-[clinic start generated code]*/
-
-#ifndef SHA512TYPE_COPY_METHODDEF
-    #define SHA512TYPE_COPY_METHODDEF
-#endif /* !defined(SHA512TYPE_COPY_METHODDEF) */
-
-#ifndef SHA512TYPE_DIGEST_METHODDEF
-    #define SHA512TYPE_DIGEST_METHODDEF
-#endif /* !defined(SHA512TYPE_DIGEST_METHODDEF) */
-
-#ifndef SHA512TYPE_HEXDIGEST_METHODDEF
-    #define SHA512TYPE_HEXDIGEST_METHODDEF
-#endif /* !defined(SHA512TYPE_HEXDIGEST_METHODDEF) */
-
-#ifndef SHA512TYPE_UPDATE_METHODDEF
-    #define SHA512TYPE_UPDATE_METHODDEF
-#endif /* !defined(SHA512TYPE_UPDATE_METHODDEF) */
-/*[clinic end generated code: output=de713947d31130e9 input=524ce2e021e4eba6]*/
-
-static PyMethodDef SHA_methods[] = {
-    SHA512TYPE_COPY_METHODDEF
-    SHA512TYPE_DIGEST_METHODDEF
-    SHA512TYPE_HEXDIGEST_METHODDEF
-    SHA512TYPE_UPDATE_METHODDEF
-    {NULL,        NULL}         /* sentinel */
-};
-
-static PyObject *
-SHA512_get_block_size(PyObject *self, void *closure)
-{
-    return PyLong_FromLong(SHA_BLOCKSIZE);
-}
-
-static PyObject *
-SHA512_get_name(PyObject *self, void *closure)
-{
-    if (((SHAobject *)self)->digestsize == 64)
-        return PyUnicode_FromStringAndSize("sha512", 6);
-    else
-        return PyUnicode_FromStringAndSize("sha384", 6);
-}
-
-static PyGetSetDef SHA_getseters[] = {
-    {"block_size",
-     (getter)SHA512_get_block_size, NULL,
-     NULL,
-     NULL},
-    {"name",
-     (getter)SHA512_get_name, NULL,
-     NULL,
-     NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyMemberDef SHA_members[] = {
-    {"digest_size", T_INT, offsetof(SHAobject, digestsize), READONLY, NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyTypeObject SHA384type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_sha512.sha384",   /*tp_name*/
-    sizeof(SHAobject),  /*tp_size*/
-    0,                  /*tp_itemsize*/
-    /* methods */
-    SHA512_dealloc,     /*tp_dealloc*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,                  /*tp_clear*/
-    0,                  /*tp_richcompare*/
-    0,                  /*tp_weaklistoffset*/
-    0,                  /*tp_iter*/
-    0,                  /*tp_iternext*/
-    SHA_methods,        /* tp_methods */
-    SHA_members,        /* tp_members */
-    SHA_getseters,      /* tp_getset */
-};
-
-static PyTypeObject SHA512type = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "_sha512.sha512",   /*tp_name*/
-    sizeof(SHAobject),  /*tp_size*/
-    0,                  /*tp_itemsize*/
-    /* methods */
-    SHA512_dealloc,     /*tp_dealloc*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,                  /*tp_clear*/
-    0,                  /*tp_richcompare*/
-    0,                  /*tp_weaklistoffset*/
-    0,                  /*tp_iter*/
-    0,                  /*tp_iternext*/
-    SHA_methods,        /* tp_methods */
-    SHA_members,        /* tp_members */
-    SHA_getseters,      /* tp_getset */
-};
-
-
-/* The single module-level function: new() */
-
-/*[clinic input]
-_sha512.sha512
-
-    string: object(c_default="NULL") = b''
-
-Return a new SHA-512 hash object; optionally initialized with a string.
-[clinic start generated code]*/
+#if defined(PY_LONG_LONG)
 
 PyDoc_STRVAR(_sha512_sha512__doc__,
 "sha512($module, /, string=b\'\')\n"
@@ -802,45 +112,9 @@
     return return_value;
 }
 
-static PyObject *
-_sha512_sha512_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=9e39b11115f36878 input=e69bad9ae9b6a308]*/
-{
-    SHAobject *new;
-    Py_buffer buf;
+#endif /* defined(PY_LONG_LONG) */
 
-    if (string)
-        GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
-
-    if ((new = newSHA512object()) == NULL) {
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-
-    sha512_init(new);
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-    if (string) {
-        sha512_update(new, buf.buf, buf.len);
-        PyBuffer_Release(&buf);
-    }
-
-    return (PyObject *)new;
-}
-
-/*[clinic input]
-_sha512.sha384
-
-    string: object(c_default="NULL") = b''
-
-Return a new SHA-384 hash object; optionally initialized with a string.
-[clinic start generated code]*/
+#if defined(PY_LONG_LONG)
 
 PyDoc_STRVAR(_sha512_sha384__doc__,
 "sha384($module, /, string=b\'\')\n"
@@ -871,42 +145,23 @@
     return return_value;
 }
 
-static PyObject *
-_sha512_sha384_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=397c6fba3525b93a input=c9327788d4ea4545]*/
-{
-    SHAobject *new;
-    Py_buffer buf;
+#endif /* defined(PY_LONG_LONG) */
 
-    if (string)
-        GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
+#ifndef SHA512TYPE_COPY_METHODDEF
+    #define SHA512TYPE_COPY_METHODDEF
+#endif /* !defined(SHA512TYPE_COPY_METHODDEF) */
 
-    if ((new = newSHA384object()) == NULL) {
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
+#ifndef SHA512TYPE_DIGEST_METHODDEF
+    #define SHA512TYPE_DIGEST_METHODDEF
+#endif /* !defined(SHA512TYPE_DIGEST_METHODDEF) */
 
-    sha384_init(new);
+#ifndef SHA512TYPE_HEXDIGEST_METHODDEF
+    #define SHA512TYPE_HEXDIGEST_METHODDEF
+#endif /* !defined(SHA512TYPE_HEXDIGEST_METHODDEF) */
 
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        if (string)
-            PyBuffer_Release(&buf);
-        return NULL;
-    }
-    if (string) {
-        sha512_update(new, buf.buf, buf.len);
-        PyBuffer_Release(&buf);
-    }
-
-    return (PyObject *)new;
-}
-
-
-/*[clinic input]
-dump buffer
-[clinic start generated code]*/
+#ifndef SHA512TYPE_UPDATE_METHODDEF
+    #define SHA512TYPE_UPDATE_METHODDEF
+#endif /* !defined(SHA512TYPE_UPDATE_METHODDEF) */
 
 #ifndef _SHA512_SHA512_METHODDEF
     #define _SHA512_SHA512_METHODDEF
@@ -915,55 +170,4 @@
 #ifndef _SHA512_SHA384_METHODDEF
     #define _SHA512_SHA384_METHODDEF
 #endif /* !defined(_SHA512_SHA384_METHODDEF) */
-/*[clinic end generated code: output=69d84aa9445b01d8 input=524ce2e021e4eba6]*/
-
-/* List of functions exported by this module */
-
-static struct PyMethodDef SHA_functions[] = {
-    _SHA512_SHA512_METHODDEF
-    _SHA512_SHA384_METHODDEF
-    {NULL,      NULL}            /* Sentinel */
-};
-
-
-/* Initialize this module. */
-
-#define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
-
-
-static struct PyModuleDef _sha512module = {
-        PyModuleDef_HEAD_INIT,
-        "_sha512",
-        NULL,
-        -1,
-        SHA_functions,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-PyInit__sha512(void)
-{
-    PyObject *m;
-
-    Py_TYPE(&SHA384type) = &PyType_Type;
-    if (PyType_Ready(&SHA384type) < 0)
-        return NULL;
-    Py_TYPE(&SHA512type) = &PyType_Type;
-    if (PyType_Ready(&SHA512type) < 0)
-        return NULL;
-
-    m = PyModule_Create(&_sha512module);
-    if (m == NULL)
-        return NULL;
-
-    Py_INCREF((PyObject *)&SHA384type);
-    PyModule_AddObject(m, "SHA384Type", (PyObject *)&SHA384type);
-    Py_INCREF((PyObject *)&SHA512type);
-    PyModule_AddObject(m, "SHA512Type", (PyObject *)&SHA512type);
-    return m;
-}
-
-#endif
+/*[clinic end generated code: output=de7bda19fde49310 input=a9049054013a1b77]*/
diff --git a/Modules/unicodedata.c b/Modules/clinic/unicodedata.c.h
copy from Modules/unicodedata.c
copy to Modules/clinic/unicodedata.c.h
--- a/Modules/unicodedata.c
+++ b/Modules/clinic/unicodedata.c.h
@@ -1,133 +1,5 @@
-/* ------------------------------------------------------------------------
-
-   unicodedata -- Provides access to the Unicode database.
-
-   Data was extracted from the UnicodeData.txt file.
-   The current version number is reported in the unidata_version constant.
-
-   Written by Marc-Andre Lemburg (mal at lemburg.com).
-   Modified for Python 2.0 by Fredrik Lundh (fredrik at pythonware.com)
-   Modified by Martin v. Löwis (martin at v.loewis.de)
-
-   Copyright (c) Corporation for National Research Initiatives.
-
-   ------------------------------------------------------------------------ */
-
-#define PY_SSIZE_T_CLEAN
-
-#include "Python.h"
-#include "ucnhash.h"
-#include "structmember.h"
-
 /*[clinic input]
-module unicodedata
-class unicodedata.UCD 'PreviousDBVersion *' '&UCD_Type'
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=6dac153082d150bc]*/
-
-/* character properties */
-
-typedef struct {
-    const unsigned char category;       /* index into
-                                           _PyUnicode_CategoryNames */
-    const unsigned char combining;      /* combining class value 0 - 255 */
-    const unsigned char bidirectional;  /* index into
-                                           _PyUnicode_BidirectionalNames */
-    const unsigned char mirrored;       /* true if mirrored in bidir mode */
-    const unsigned char east_asian_width;       /* index into
-                                                   _PyUnicode_EastAsianWidth */
-    const unsigned char normalization_quick_check; /* see is_normalized() */
-} _PyUnicode_DatabaseRecord;
-
-typedef struct change_record {
-    /* sequence of fields should be the same as in merge_old_version */
-    const unsigned char bidir_changed;
-    const unsigned char category_changed;
-    const unsigned char decimal_changed;
-    const unsigned char mirrored_changed;
-    const double numeric_changed;
-} change_record;
-
-/* data file generated by Tools/unicode/makeunicodedata.py */
-#include "unicodedata_db.h"
-
-static const _PyUnicode_DatabaseRecord*
-_getrecord_ex(Py_UCS4 code)
-{
-    int index;
-    if (code >= 0x110000)
-        index = 0;
-    else {
-        index = index1[(code>>SHIFT)];
-        index = index2[(index<<SHIFT)+(code&((1<<SHIFT)-1))];
-    }
-
-    return &_PyUnicode_Database_Records[index];
-}
-
-/* ------------- Previous-version API ------------------------------------- */
-typedef struct previous_version {
-    PyObject_HEAD
-    const char *name;
-    const change_record* (*getrecord)(Py_UCS4);
-    Py_UCS4 (*normalization)(Py_UCS4);
-} PreviousDBVersion;
-
-#define get_old_record(self, v)    ((((PreviousDBVersion*)self)->getrecord)(v))
-
-static PyMemberDef DB_members[] = {
-        {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
-        {NULL}
-};
-
-/* forward declaration */
-static PyTypeObject UCD_Type;
-#define UCD_Check(o) (Py_TYPE(o)==&UCD_Type)
-
-static PyObject*
-new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4),
-                     Py_UCS4 (*normalization)(Py_UCS4))
-{
-        PreviousDBVersion *self;
-        self = PyObject_New(PreviousDBVersion, &UCD_Type);
-        if (self == NULL)
-                return NULL;
-        self->name = name;
-        self->getrecord = getrecord;
-        self->normalization = normalization;
-        return (PyObject*)self;
-}
-
-
-static Py_UCS4 getuchar(PyUnicodeObject *obj)
-{
-    if (PyUnicode_READY(obj))
-        return (Py_UCS4)-1;
-    if (PyUnicode_GET_LENGTH(obj) == 1) {
-        if (PyUnicode_READY(obj))
-            return (Py_UCS4)-1;
-        return PyUnicode_READ_CHAR(obj, 0);
-    }
-    PyErr_SetString(PyExc_TypeError,
-                    "need a single Unicode character as parameter");
-    return (Py_UCS4)-1;
-}
-
-/* --- Module API --------------------------------------------------------- */
-
-/*[clinic input]
-
-unicodedata.UCD.decimal
-
-    unichr: object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')
-    default: object=NULL
-    /
-
-Converts a Unicode character into its equivalent decimal value.
-
-Returns the decimal value assigned to the Unicode character unichr
-as integer. If no such value is defined, default is returned, or, if
-not given, ValueError is raised.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(unicodedata_UCD_decimal__doc__,
@@ -162,1270 +34,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-unicodedata_UCD_decimal_impl(PreviousDBVersion *self, PyUnicodeObject *unichr, PyObject *default_value)
-/*[clinic end generated code: output=8689669896d293df input=c25c9d2b4de076b1]*/
-{
-    int have_old = 0;
-    long rc;
-    Py_UCS4 c;
-
-    c = getuchar(unichr);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0) {
-            /* unassigned */
-            have_old = 1;
-            rc = -1;
-        }
-        else if (old->decimal_changed != 0xFF) {
-            have_old = 1;
-            rc = old->decimal_changed;
-        }
-    }
-
-    if (!have_old)
-        rc = Py_UNICODE_TODECIMAL(c);
-    if (rc < 0) {
-        if (default_value == NULL) {
-            PyErr_SetString(PyExc_ValueError,
-                            "not a decimal");
-            return NULL;
-        }
-        else {
-            Py_INCREF(default_value);
-            return default_value;
-        }
-    }
-    return PyLong_FromLong(rc);
-}
-
-PyDoc_STRVAR(unicodedata_digit__doc__,
-"digit(unichr[, default])\n\
-\n\
-Returns the digit value assigned to the Unicode character unichr as\n\
-integer. If no such value is defined, default is returned, or, if\n\
-not given, ValueError is raised.");
-
-static PyObject *
-unicodedata_digit(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    PyObject *defobj = NULL;
-    long rc;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!|O:digit", &PyUnicode_Type, &v, &defobj))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-    rc = Py_UNICODE_TODIGIT(c);
-    if (rc < 0) {
-        if (defobj == NULL) {
-            PyErr_SetString(PyExc_ValueError, "not a digit");
-            return NULL;
-        }
-        else {
-            Py_INCREF(defobj);
-            return defobj;
-        }
-    }
-    return PyLong_FromLong(rc);
-}
-
-PyDoc_STRVAR(unicodedata_numeric__doc__,
-"numeric(unichr[, default])\n\
-\n\
-Returns the numeric value assigned to the Unicode character unichr\n\
-as float. If no such value is defined, default is returned, or, if\n\
-not given, ValueError is raised.");
-
-static PyObject *
-unicodedata_numeric(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    PyObject *defobj = NULL;
-    int have_old = 0;
-    double rc;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!|O:numeric", &PyUnicode_Type, &v, &defobj))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0) {
-            /* unassigned */
-            have_old = 1;
-            rc = -1.0;
-        }
-        else if (old->decimal_changed != 0xFF) {
-            have_old = 1;
-            rc = old->decimal_changed;
-        }
-    }
-
-    if (!have_old)
-        rc = Py_UNICODE_TONUMERIC(c);
-    if (rc == -1.0) {
-        if (defobj == NULL) {
-            PyErr_SetString(PyExc_ValueError, "not a numeric character");
-            return NULL;
-        }
-        else {
-            Py_INCREF(defobj);
-            return defobj;
-        }
-    }
-    return PyFloat_FromDouble(rc);
-}
-
-PyDoc_STRVAR(unicodedata_category__doc__,
-"category(unichr)\n\
-\n\
-Returns the general category assigned to the Unicode character\n\
-unichr as string.");
-
-static PyObject *
-unicodedata_category(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    int index;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!:category",
-                          &PyUnicode_Type, &v))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-    index = (int) _getrecord_ex(c)->category;
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed != 0xFF)
-            index = old->category_changed;
-    }
-    return PyUnicode_FromString(_PyUnicode_CategoryNames[index]);
-}
-
-PyDoc_STRVAR(unicodedata_bidirectional__doc__,
-"bidirectional(unichr)\n\
-\n\
-Returns the bidirectional class assigned to the Unicode character\n\
-unichr as string. If no such value is defined, an empty string is\n\
-returned.");
-
-static PyObject *
-unicodedata_bidirectional(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    int index;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!:bidirectional",
-                          &PyUnicode_Type, &v))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-    index = (int) _getrecord_ex(c)->bidirectional;
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0)
-            index = 0; /* unassigned */
-        else if (old->bidir_changed != 0xFF)
-            index = old->bidir_changed;
-    }
-    return PyUnicode_FromString(_PyUnicode_BidirectionalNames[index]);
-}
-
-PyDoc_STRVAR(unicodedata_combining__doc__,
-"combining(unichr)\n\
-\n\
-Returns the canonical combining class assigned to the Unicode\n\
-character unichr as integer. Returns 0 if no combining class is\n\
-defined.");
-
-static PyObject *
-unicodedata_combining(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    int index;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!:combining",
-                          &PyUnicode_Type, &v))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-    index = (int) _getrecord_ex(c)->combining;
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0)
-            index = 0; /* unassigned */
-    }
-    return PyLong_FromLong(index);
-}
-
-PyDoc_STRVAR(unicodedata_mirrored__doc__,
-"mirrored(unichr)\n\
-\n\
-Returns the mirrored property assigned to the Unicode character\n\
-unichr as integer. Returns 1 if the character has been identified as\n\
-a \"mirrored\" character in bidirectional text, 0 otherwise.");
-
-static PyObject *
-unicodedata_mirrored(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    int index;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!:mirrored",
-                          &PyUnicode_Type, &v))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-    index = (int) _getrecord_ex(c)->mirrored;
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0)
-            index = 0; /* unassigned */
-        else if (old->mirrored_changed != 0xFF)
-            index = old->mirrored_changed;
-    }
-    return PyLong_FromLong(index);
-}
-
-PyDoc_STRVAR(unicodedata_east_asian_width__doc__,
-"east_asian_width(unichr)\n\
-\n\
-Returns the east asian width assigned to the Unicode character\n\
-unichr as string.");
-
-static PyObject *
-unicodedata_east_asian_width(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    int index;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!:east_asian_width",
-                          &PyUnicode_Type, &v))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-    index = (int) _getrecord_ex(c)->east_asian_width;
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0)
-            index = 0; /* unassigned */
-    }
-    return PyUnicode_FromString(_PyUnicode_EastAsianWidthNames[index]);
-}
-
-PyDoc_STRVAR(unicodedata_decomposition__doc__,
-"decomposition(unichr)\n\
-\n\
-Returns the character decomposition mapping assigned to the Unicode\n\
-character unichr as string. An empty string is returned in case no\n\
-such mapping is defined.");
-
-static PyObject *
-unicodedata_decomposition(PyObject *self, PyObject *args)
-{
-    PyUnicodeObject *v;
-    char decomp[256];
-    int code, index, count;
-    size_t i;
-    unsigned int prefix_index;
-    Py_UCS4 c;
-
-    if (!PyArg_ParseTuple(args, "O!:decomposition",
-                          &PyUnicode_Type, &v))
-        return NULL;
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-
-    code = (int)c;
-
-    if (self && UCD_Check(self)) {
-        const change_record *old = get_old_record(self, c);
-        if (old->category_changed == 0)
-            return PyUnicode_FromString(""); /* unassigned */
-    }
-
-    if (code < 0 || code >= 0x110000)
-        index = 0;
-    else {
-        index = decomp_index1[(code>>DECOMP_SHIFT)];
-        index = decomp_index2[(index<<DECOMP_SHIFT)+
-                             (code&((1<<DECOMP_SHIFT)-1))];
-    }
-
-    /* high byte is number of hex bytes (usually one or two), low byte
-       is prefix code (from*/
-    count = decomp_data[index] >> 8;
-
-    /* XXX: could allocate the PyString up front instead
-       (strlen(prefix) + 5 * count + 1 bytes) */
-
-    /* Based on how index is calculated above and decomp_data is generated
-       from Tools/unicode/makeunicodedata.py, it should not be possible
-       to overflow decomp_prefix. */
-    prefix_index = decomp_data[index] & 255;
-    assert(prefix_index < Py_ARRAY_LENGTH(decomp_prefix));
-
-    /* copy prefix */
-    i = strlen(decomp_prefix[prefix_index]);
-    memcpy(decomp, decomp_prefix[prefix_index], i);
-
-    while (count-- > 0) {
-        if (i)
-            decomp[i++] = ' ';
-        assert(i < sizeof(decomp));
-        PyOS_snprintf(decomp + i, sizeof(decomp) - i, "%04X",
-                      decomp_data[++index]);
-        i += strlen(decomp + i);
-    }
-    return PyUnicode_FromStringAndSize(decomp, i);
-}
-
-static void
-get_decomp_record(PyObject *self, Py_UCS4 code, int *index, int *prefix, int *count)
-{
-    if (code >= 0x110000) {
-        *index = 0;
-    } else if (self && UCD_Check(self) &&
-               get_old_record(self, code)->category_changed==0) {
-        /* unassigned in old version */
-        *index = 0;
-    }
-    else {
-        *index = decomp_index1[(code>>DECOMP_SHIFT)];
-        *index = decomp_index2[(*index<<DECOMP_SHIFT)+
-                               (code&((1<<DECOMP_SHIFT)-1))];
-    }
-
-    /* high byte is number of hex bytes (usually one or two), low byte
-       is prefix code (from*/
-    *count = decomp_data[*index] >> 8;
-    *prefix = decomp_data[*index] & 255;
-
-    (*index)++;
-}
-
-#define SBase   0xAC00
-#define LBase   0x1100
-#define VBase   0x1161
-#define TBase   0x11A7
-#define LCount  19
-#define VCount  21
-#define TCount  28
-#define NCount  (VCount*TCount)
-#define SCount  (LCount*NCount)
-
-static PyObject*
-nfd_nfkd(PyObject *self, PyObject *input, int k)
-{
-    PyObject *result;
-    Py_UCS4 *output;
-    Py_ssize_t i, o, osize;
-    int kind;
-    void *data;
-    /* Longest decomposition in Unicode 3.2: U+FDFA */
-    Py_UCS4 stack[20];
-    Py_ssize_t space, isize;
-    int index, prefix, count, stackptr;
-    unsigned char prev, cur;
-
-    stackptr = 0;
-    isize = PyUnicode_GET_LENGTH(input);
-    space = isize;
-    /* Overallocate at most 10 characters. */
-    if (space > 10) {
-        if (space <= PY_SSIZE_T_MAX - 10)
-            space += 10;
-    }
-    else {
-        space *= 2;
-    }
-    osize = space;
-    output = PyMem_NEW(Py_UCS4, space);
-    if (!output) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    i = o = 0;
-    kind = PyUnicode_KIND(input);
-    data = PyUnicode_DATA(input);
-
-    while (i < isize) {
-        stack[stackptr++] = PyUnicode_READ(kind, data, i++);
-        while(stackptr) {
-            Py_UCS4 code = stack[--stackptr];
-            /* Hangul Decomposition adds three characters in
-               a single step, so we need at least that much room. */
-            if (space < 3) {
-                Py_UCS4 *new_output;
-                osize += 10;
-                space += 10;
-                new_output = PyMem_Realloc(output, osize*sizeof(Py_UCS4));
-                if (new_output == NULL) {
-                    PyMem_Free(output);
-                    PyErr_NoMemory();
-                    return NULL;
-                }
-                output = new_output;
-            }
-            /* Hangul Decomposition. */
-            if (SBase <= code && code < (SBase+SCount)) {
-                int SIndex = code - SBase;
-                int L = LBase + SIndex / NCount;
-                int V = VBase + (SIndex % NCount) / TCount;
-                int T = TBase + SIndex % TCount;
-                output[o++] = L;
-                output[o++] = V;
-                space -= 2;
-                if (T != TBase) {
-                    output[o++] = T;
-                    space --;
-                }
-                continue;
-            }
-            /* normalization changes */
-            if (self && UCD_Check(self)) {
-                Py_UCS4 value = ((PreviousDBVersion*)self)->normalization(code);
-                if (value != 0) {
-                    stack[stackptr++] = value;
-                    continue;
-                }
-            }
-
-            /* Other decompositions. */
-            get_decomp_record(self, code, &index, &prefix, &count);
-
-            /* Copy character if it is not decomposable, or has a
-               compatibility decomposition, but we do NFD. */
-            if (!count || (prefix && !k)) {
-                output[o++] = code;
-                space--;
-                continue;
-            }
-            /* Copy decomposition onto the stack, in reverse
-               order.  */
-            while(count) {
-                code = decomp_data[index + (--count)];
-                stack[stackptr++] = code;
-            }
-        }
-    }
-
-    result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
-                                       output, o);
-    PyMem_Free(output);
-    if (!result)
-        return NULL;
-    /* result is guaranteed to be ready, as it is compact. */
-    kind = PyUnicode_KIND(result);
-    data = PyUnicode_DATA(result);
-
-    /* Sort canonically. */
-    i = 0;
-    prev = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
-    for (i++; i < PyUnicode_GET_LENGTH(result); i++) {
-        cur = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
-        if (prev == 0 || cur == 0 || prev <= cur) {
-            prev = cur;
-            continue;
-        }
-        /* Non-canonical order. Need to switch *i with previous. */
-        o = i - 1;
-        while (1) {
-            Py_UCS4 tmp = PyUnicode_READ(kind, data, o+1);
-            PyUnicode_WRITE(kind, data, o+1,
-                            PyUnicode_READ(kind, data, o));
-            PyUnicode_WRITE(kind, data, o, tmp);
-            o--;
-            if (o < 0)
-                break;
-            prev = _getrecord_ex(PyUnicode_READ(kind, data, o))->combining;
-            if (prev == 0 || prev <= cur)
-                break;
-        }
-        prev = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
-    }
-    return result;
-}
-
-static int
-find_nfc_index(PyObject *self, struct reindex* nfc, Py_UCS4 code)
-{
-    unsigned int index;
-    for (index = 0; nfc[index].start; index++) {
-        unsigned int start = nfc[index].start;
-        if (code < start)
-            return -1;
-        if (code <= start + nfc[index].count) {
-            unsigned int delta = code - start;
-            return nfc[index].index + delta;
-        }
-    }
-    return -1;
-}
-
-static PyObject*
-nfc_nfkc(PyObject *self, PyObject *input, int k)
-{
-    PyObject *result;
-    int kind;
-    void *data;
-    Py_UCS4 *output;
-    Py_ssize_t i, i1, o, len;
-    int f,l,index,index1,comb;
-    Py_UCS4 code;
-    Py_ssize_t skipped[20];
-    int cskipped = 0;
-
-    result = nfd_nfkd(self, input, k);
-    if (!result)
-        return NULL;
-    /* result will be "ready". */
-    kind = PyUnicode_KIND(result);
-    data = PyUnicode_DATA(result);
-    len = PyUnicode_GET_LENGTH(result);
-
-    /* We allocate a buffer for the output.
-       If we find that we made no changes, we still return
-       the NFD result. */
-    output = PyMem_NEW(Py_UCS4, len);
-    if (!output) {
-        PyErr_NoMemory();
-        Py_DECREF(result);
-        return 0;
-    }
-    i = o = 0;
-
-  again:
-    while (i < len) {
-      for (index = 0; index < cskipped; index++) {
-          if (skipped[index] == i) {
-              /* *i character is skipped.
-                 Remove from list. */
-              skipped[index] = skipped[cskipped-1];
-              cskipped--;
-              i++;
-              goto again; /* continue while */
-          }
-      }
-      /* Hangul Composition. We don't need to check for <LV,T>
-         pairs, since we always have decomposed data. */
-      code = PyUnicode_READ(kind, data, i);
-      if (LBase <= code && code < (LBase+LCount) &&
-          i + 1 < len &&
-          VBase <= PyUnicode_READ(kind, data, i+1) &&
-          PyUnicode_READ(kind, data, i+1) <= (VBase+VCount)) {
-          int LIndex, VIndex;
-          LIndex = code - LBase;
-          VIndex = PyUnicode_READ(kind, data, i+1) - VBase;
-          code = SBase + (LIndex*VCount+VIndex)*TCount;
-          i+=2;
-          if (i < len &&
-              TBase <= PyUnicode_READ(kind, data, i) &&
-              PyUnicode_READ(kind, data, i) <= (TBase+TCount)) {
-              code += PyUnicode_READ(kind, data, i)-TBase;
-              i++;
-          }
-          output[o++] = code;
-          continue;
-      }
-
-      /* code is still input[i] here */
-      f = find_nfc_index(self, nfc_first, code);
-      if (f == -1) {
-          output[o++] = code;
-          i++;
-          continue;
-      }
-      /* Find next unblocked character. */
-      i1 = i+1;
-      comb = 0;
-      /* output base character for now; might be updated later. */
-      output[o] = PyUnicode_READ(kind, data, i);
-      while (i1 < len) {
-          Py_UCS4 code1 = PyUnicode_READ(kind, data, i1);
-          int comb1 = _getrecord_ex(code1)->combining;
-          if (comb) {
-              if (comb1 == 0)
-                  break;
-              if (comb >= comb1) {
-                  /* Character is blocked. */
-                  i1++;
-                  continue;
-              }
-          }
-          l = find_nfc_index(self, nfc_last, code1);
-          /* i1 cannot be combined with i. If i1
-             is a starter, we don't need to look further.
-             Otherwise, record the combining class. */
-          if (l == -1) {
-            not_combinable:
-              if (comb1 == 0)
-                  break;
-              comb = comb1;
-              i1++;
-              continue;
-          }
-          index = f*TOTAL_LAST + l;
-          index1 = comp_index[index >> COMP_SHIFT];
-          code = comp_data[(index1<<COMP_SHIFT)+
-                           (index&((1<<COMP_SHIFT)-1))];
-          if (code == 0)
-              goto not_combinable;
-
-          /* Replace the original character. */
-          output[o] = code;
-          /* Mark the second character unused. */
-          assert(cskipped < 20);
-          skipped[cskipped++] = i1;
-          i1++;
-          f = find_nfc_index(self, nfc_first, output[o]);
-          if (f == -1)
-              break;
-      }
-      /* Output character was already written.
-         Just advance the indices. */
-      o++; i++;
-    }
-    if (o == len) {
-        /* No changes. Return original string. */
-        PyMem_Free(output);
-        return result;
-    }
-    Py_DECREF(result);
-    result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
-                                       output, o);
-    PyMem_Free(output);
-    return result;
-}
-
-/* Return 1 if the input is certainly normalized, 0 if it might not be. */
-static int
-is_normalized(PyObject *self, PyObject *input, int nfc, int k)
-{
-    Py_ssize_t i, len;
-    int kind;
-    void *data;
-    unsigned char prev_combining = 0, quickcheck_mask;
-
-    /* An older version of the database is requested, quickchecks must be
-       disabled. */
-    if (self && UCD_Check(self))
-        return 0;
-
-    /* The two quickcheck bits at this shift mean 0=Yes, 1=Maybe, 2=No,
-       as described in http://unicode.org/reports/tr15/#Annex8. */
-    quickcheck_mask = 3 << ((nfc ? 4 : 0) + (k ? 2 : 0));
-
-    i = 0;
-    kind = PyUnicode_KIND(input);
-    data = PyUnicode_DATA(input);
-    len = PyUnicode_GET_LENGTH(input);
-    while (i < len) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
-        const _PyUnicode_DatabaseRecord *record = _getrecord_ex(ch);
-        unsigned char combining = record->combining;
-        unsigned char quickcheck = record->normalization_quick_check;
-
-        if (quickcheck & quickcheck_mask)
-            return 0; /* this string might need normalization */
-        if (combining && prev_combining > combining)
-            return 0; /* non-canonical sort order, not normalized */
-        prev_combining = combining;
-    }
-    return 1; /* certainly normalized */
-}
-
-PyDoc_STRVAR(unicodedata_normalize__doc__,
-"normalize(form, unistr)\n\
-\n\
-Return the normal form 'form' for the Unicode string unistr.  Valid\n\
-values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'.");
-
-static PyObject*
-unicodedata_normalize(PyObject *self, PyObject *args)
-{
-    char *form;
-    PyObject *input;
-
-    if(!PyArg_ParseTuple(args, "sO!:normalize",
-                         &form, &PyUnicode_Type, &input))
-        return NULL;
-
-    if (PyUnicode_READY(input) == -1)
-        return NULL;
-
-    if (PyUnicode_GET_LENGTH(input) == 0) {
-        /* Special case empty input strings, since resizing
-           them  later would cause internal errors. */
-        Py_INCREF(input);
-        return input;
-    }
-
-    if (strcmp(form, "NFC") == 0) {
-        if (is_normalized(self, input, 1, 0)) {
-            Py_INCREF(input);
-            return input;
-        }
-        return nfc_nfkc(self, input, 0);
-    }
-    if (strcmp(form, "NFKC") == 0) {
-        if (is_normalized(self, input, 1, 1)) {
-            Py_INCREF(input);
-            return input;
-        }
-        return nfc_nfkc(self, input, 1);
-    }
-    if (strcmp(form, "NFD") == 0) {
-        if (is_normalized(self, input, 0, 0)) {
-            Py_INCREF(input);
-            return input;
-        }
-        return nfd_nfkd(self, input, 0);
-    }
-    if (strcmp(form, "NFKD") == 0) {
-        if (is_normalized(self, input, 0, 1)) {
-            Py_INCREF(input);
-            return input;
-        }
-        return nfd_nfkd(self, input, 1);
-    }
-    PyErr_SetString(PyExc_ValueError, "invalid normalization form");
-    return NULL;
-}
-
-/* -------------------------------------------------------------------- */
-/* unicode character name tables */
-
-/* data file generated by Tools/unicode/makeunicodedata.py */
-#include "unicodename_db.h"
-
-/* -------------------------------------------------------------------- */
-/* database code (cut and pasted from the unidb package) */
-
-static unsigned long
-_gethash(const char *s, int len, int scale)
-{
-    int i;
-    unsigned long h = 0;
-    unsigned long ix;
-    for (i = 0; i < len; i++) {
-        h = (h * scale) + (unsigned char) Py_TOUPPER(Py_CHARMASK(s[i]));
-        ix = h & 0xff000000;
-        if (ix)
-            h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff;
-    }
-    return h;
-}
-
-static char *hangul_syllables[][3] = {
-    { "G",  "A",   ""   },
-    { "GG", "AE",  "G"  },
-    { "N",  "YA",  "GG" },
-    { "D",  "YAE", "GS" },
-    { "DD", "EO",  "N", },
-    { "R",  "E",   "NJ" },
-    { "M",  "YEO", "NH" },
-    { "B",  "YE",  "D"  },
-    { "BB", "O",   "L"  },
-    { "S",  "WA",  "LG" },
-    { "SS", "WAE", "LM" },
-    { "",   "OE",  "LB" },
-    { "J",  "YO",  "LS" },
-    { "JJ", "U",   "LT" },
-    { "C",  "WEO", "LP" },
-    { "K",  "WE",  "LH" },
-    { "T",  "WI",  "M"  },
-    { "P",  "YU",  "B"  },
-    { "H",  "EU",  "BS" },
-    { 0,    "YI",  "S"  },
-    { 0,    "I",   "SS" },
-    { 0,    0,     "NG" },
-    { 0,    0,     "J"  },
-    { 0,    0,     "C"  },
-    { 0,    0,     "K"  },
-    { 0,    0,     "T"  },
-    { 0,    0,     "P"  },
-    { 0,    0,     "H"  }
-};
-
-/* These ranges need to match makeunicodedata.py:cjk_ranges. */
-static int
-is_unified_ideograph(Py_UCS4 code)
-{
-    return
-        (0x3400 <= code && code <= 0x4DB5)   || /* CJK Ideograph Extension A */
-        (0x4E00 <= code && code <= 0x9FCC)   || /* CJK Ideograph */
-        (0x20000 <= code && code <= 0x2A6D6) || /* CJK Ideograph Extension B */
-        (0x2A700 <= code && code <= 0x2B734) || /* CJK Ideograph Extension C */
-        (0x2B740 <= code && code <= 0x2B81D);   /* CJK Ideograph Extension D */
-}
-
-/* macros used to determine if the given code point is in the PUA range that
- * we are using to store aliases and named sequences */
-#define IS_ALIAS(cp) ((cp >= aliases_start) && (cp < aliases_end))
-#define IS_NAMED_SEQ(cp) ((cp >= named_sequences_start) && \
-                          (cp < named_sequences_end))
-
-static int
-_getucname(PyObject *self, Py_UCS4 code, char* buffer, int buflen,
-           int with_alias_and_seq)
-{
-    /* Find the name associated with the given code point.
-     * If with_alias_and_seq is 1, check for names in the Private Use Area 15
-     * that we are using for aliases and named sequences. */
-    int offset;
-    int i;
-    int word;
-    unsigned char* w;
-
-    if (code >= 0x110000)
-        return 0;
-
-    /* XXX should we just skip all the code points in the PUAs here? */
-    if (!with_alias_and_seq && (IS_ALIAS(code) || IS_NAMED_SEQ(code)))
-        return 0;
-
-    if (self && UCD_Check(self)) {
-        /* in 3.2.0 there are no aliases and named sequences */
-        const change_record *old;
-        if (IS_ALIAS(code) || IS_NAMED_SEQ(code))
-            return 0;
-        old = get_old_record(self, code);
-        if (old->category_changed == 0) {
-            /* unassigned */
-            return 0;
-        }
-    }
-
-    if (SBase <= code && code < SBase+SCount) {
-        /* Hangul syllable. */
-        int SIndex = code - SBase;
-        int L = SIndex / NCount;
-        int V = (SIndex % NCount) / TCount;
-        int T = SIndex % TCount;
-
-        if (buflen < 27)
-            /* Worst case: HANGUL SYLLABLE <10chars>. */
-            return 0;
-        strcpy(buffer, "HANGUL SYLLABLE ");
-        buffer += 16;
-        strcpy(buffer, hangul_syllables[L][0]);
-        buffer += strlen(hangul_syllables[L][0]);
-        strcpy(buffer, hangul_syllables[V][1]);
-        buffer += strlen(hangul_syllables[V][1]);
-        strcpy(buffer, hangul_syllables[T][2]);
-        buffer += strlen(hangul_syllables[T][2]);
-        *buffer = '\0';
-        return 1;
-    }
-
-    if (is_unified_ideograph(code)) {
-        if (buflen < 28)
-            /* Worst case: CJK UNIFIED IDEOGRAPH-20000 */
-            return 0;
-        sprintf(buffer, "CJK UNIFIED IDEOGRAPH-%X", code);
-        return 1;
-    }
-
-    /* get offset into phrasebook */
-    offset = phrasebook_offset1[(code>>phrasebook_shift)];
-    offset = phrasebook_offset2[(offset<<phrasebook_shift) +
-                               (code&((1<<phrasebook_shift)-1))];
-    if (!offset)
-        return 0;
-
-    i = 0;
-
-    for (;;) {
-        /* get word index */
-        word = phrasebook[offset] - phrasebook_short;
-        if (word >= 0) {
-            word = (word << 8) + phrasebook[offset+1];
-            offset += 2;
-        } else
-            word = phrasebook[offset++];
-        if (i) {
-            if (i > buflen)
-                return 0; /* buffer overflow */
-            buffer[i++] = ' ';
-        }
-        /* copy word string from lexicon.  the last character in the
-           word has bit 7 set.  the last word in a string ends with
-           0x80 */
-        w = lexicon + lexicon_offset[word];
-        while (*w < 128) {
-            if (i >= buflen)
-                return 0; /* buffer overflow */
-            buffer[i++] = *w++;
-        }
-        if (i >= buflen)
-            return 0; /* buffer overflow */
-        buffer[i++] = *w & 127;
-        if (*w == 128)
-            break; /* end of word */
-    }
-
-    return 1;
-}
-
-static int
-_cmpname(PyObject *self, int code, const char* name, int namelen)
-{
-    /* check if code corresponds to the given name */
-    int i;
-    char buffer[NAME_MAXLEN];
-    if (!_getucname(self, code, buffer, sizeof(buffer), 1))
-        return 0;
-    for (i = 0; i < namelen; i++) {
-        if (Py_TOUPPER(Py_CHARMASK(name[i])) != buffer[i])
-            return 0;
-    }
-    return buffer[namelen] == '\0';
-}
-
-static void
-find_syllable(const char *str, int *len, int *pos, int count, int column)
-{
-    int i, len1;
-    *len = -1;
-    for (i = 0; i < count; i++) {
-        char *s = hangul_syllables[i][column];
-        len1 = Py_SAFE_DOWNCAST(strlen(s), size_t, int);
-        if (len1 <= *len)
-            continue;
-        if (strncmp(str, s, len1) == 0) {
-            *len = len1;
-            *pos = i;
-        }
-    }
-    if (*len == -1) {
-        *len = 0;
-    }
-}
-
-static int
-_check_alias_and_seq(unsigned int cp, Py_UCS4* code, int with_named_seq)
-{
-    /* check if named sequences are allowed */
-    if (!with_named_seq && IS_NAMED_SEQ(cp))
-        return 0;
-    /* if the code point is in the PUA range that we use for aliases,
-     * convert it to obtain the right code point */
-    if (IS_ALIAS(cp))
-        *code = name_aliases[cp-aliases_start];
-    else
-        *code = cp;
-    return 1;
-}
-
-static int
-_getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code,
-         int with_named_seq)
-{
-    /* Return the code point associated with the given name.
-     * Named aliases are resolved too (unless self != NULL (i.e. we are using
-     * 3.2.0)).  If with_named_seq is 1, returns the PUA code point that we are
-     * using for the named sequence, and the caller must then convert it. */
-    unsigned int h, v;
-    unsigned int mask = code_size-1;
-    unsigned int i, incr;
-
-    /* Check for hangul syllables. */
-    if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) {
-        int len, L = -1, V = -1, T = -1;
-        const char *pos = name + 16;
-        find_syllable(pos, &len, &L, LCount, 0);
-        pos += len;
-        find_syllable(pos, &len, &V, VCount, 1);
-        pos += len;
-        find_syllable(pos, &len, &T, TCount, 2);
-        pos += len;
-        if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
-            *code = SBase + (L*VCount+V)*TCount + T;
-            return 1;
-        }
-        /* Otherwise, it's an illegal syllable name. */
-        return 0;
-    }
-
-    /* Check for unified ideographs. */
-    if (strncmp(name, "CJK UNIFIED IDEOGRAPH-", 22) == 0) {
-        /* Four or five hexdigits must follow. */
-        v = 0;
-        name += 22;
-        namelen -= 22;
-        if (namelen != 4 && namelen != 5)
-            return 0;
-        while (namelen--) {
-            v *= 16;
-            if (*name >= '0' && *name <= '9')
-                v += *name - '0';
-            else if (*name >= 'A' && *name <= 'F')
-                v += *name - 'A' + 10;
-            else
-                return 0;
-            name++;
-        }
-        if (!is_unified_ideograph(v))
-            return 0;
-        *code = v;
-        return 1;
-    }
-
-    /* the following is the same as python's dictionary lookup, with
-       only minor changes.  see the makeunicodedata script for more
-       details */
-
-    h = (unsigned int) _gethash(name, namelen, code_magic);
-    i = (~h) & mask;
-    v = code_hash[i];
-    if (!v)
-        return 0;
-    if (_cmpname(self, v, name, namelen))
-        return _check_alias_and_seq(v, code, with_named_seq);
-    incr = (h ^ (h >> 3)) & mask;
-    if (!incr)
-        incr = mask;
-    for (;;) {
-        i = (i + incr) & mask;
-        v = code_hash[i];
-        if (!v)
-            return 0;
-        if (_cmpname(self, v, name, namelen))
-            return _check_alias_and_seq(v, code, with_named_seq);
-        incr = incr << 1;
-        if (incr > mask)
-            incr = incr ^ code_poly;
-    }
-}
-
-static const _PyUnicode_Name_CAPI hashAPI =
-{
-    sizeof(_PyUnicode_Name_CAPI),
-    _getucname,
-    _getcode
-};
-
-/* -------------------------------------------------------------------- */
-/* Python bindings */
-
-PyDoc_STRVAR(unicodedata_name__doc__,
-"name(unichr[, default])\n\
-Returns the name assigned to the Unicode character unichr as a\n\
-string. If no name is defined, default is returned, or, if not\n\
-given, ValueError is raised.");
-
-static PyObject *
-unicodedata_name(PyObject* self, PyObject* args)
-{
-    char name[NAME_MAXLEN];
-    Py_UCS4 c;
-
-    PyUnicodeObject* v;
-    PyObject* defobj = NULL;
-    if (!PyArg_ParseTuple(args, "O!|O:name", &PyUnicode_Type, &v, &defobj))
-        return NULL;
-
-    c = getuchar(v);
-    if (c == (Py_UCS4)-1)
-        return NULL;
-
-    if (!_getucname(self, c, name, sizeof(name), 0)) {
-        if (defobj == NULL) {
-            PyErr_SetString(PyExc_ValueError, "no such name");
-            return NULL;
-        }
-        else {
-            Py_INCREF(defobj);
-            return defobj;
-        }
-    }
-
-    return PyUnicode_FromString(name);
-}
-
-PyDoc_STRVAR(unicodedata_lookup__doc__,
-"lookup(name)\n\
-\n\
-Look up character by name.  If a character with the\n\
-given name is found, return the corresponding Unicode\n\
-character.  If not found, KeyError is raised.");
-
-static PyObject *
-unicodedata_lookup(PyObject* self, PyObject* args)
-{
-    Py_UCS4 code;
-
-    char* name;
-    Py_ssize_t namelen;
-    unsigned int index;
-    if (!PyArg_ParseTuple(args, "s#:lookup", &name, &namelen))
-        return NULL;
-    if (namelen > INT_MAX) {
-        PyErr_SetString(PyExc_KeyError, "name too long");
-        return NULL;
-    }
-
-    if (!_getcode(self, name, (int)namelen, &code, 1)) {
-        PyErr_Format(PyExc_KeyError, "undefined character name '%s'", name);
-        return NULL;
-    }
-    /* check if code is in the PUA range that we use for named sequences
-       and convert it */
-    if (IS_NAMED_SEQ(code)) {
-        index = code-named_sequences_start;
-        return PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND,
-                                         named_sequences[index].seq,
-                                         named_sequences[index].seqlen);
-    }
-    return PyUnicode_FromOrdinal(code);
-}
-
-/* XXX Add doc strings. */
-
-static PyMethodDef unicodedata_functions[] = {
-    UNICODEDATA_UCD_DECIMAL_METHODDEF
-    {"digit", unicodedata_digit, METH_VARARGS, unicodedata_digit__doc__},
-    {"numeric", unicodedata_numeric, METH_VARARGS, unicodedata_numeric__doc__},
-    {"category", unicodedata_category, METH_VARARGS,
-                 unicodedata_category__doc__},
-    {"bidirectional", unicodedata_bidirectional, METH_VARARGS,
-                      unicodedata_bidirectional__doc__},
-    {"combining", unicodedata_combining, METH_VARARGS,
-                  unicodedata_combining__doc__},
-    {"mirrored", unicodedata_mirrored, METH_VARARGS,
-                 unicodedata_mirrored__doc__},
-    {"east_asian_width", unicodedata_east_asian_width, METH_VARARGS,
-                         unicodedata_east_asian_width__doc__},
-    {"decomposition", unicodedata_decomposition, METH_VARARGS,
-                      unicodedata_decomposition__doc__},
-    {"name", unicodedata_name, METH_VARARGS, unicodedata_name__doc__},
-    {"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__},
-    {"normalize", unicodedata_normalize, METH_VARARGS,
-                  unicodedata_normalize__doc__},
-    {NULL, NULL}                /* sentinel */
-};
-
-static PyTypeObject UCD_Type = {
-        /* The ob_type field must be initialized in the module init function
-         * to be portable to Windows without using C++. */
-        PyVarObject_HEAD_INIT(NULL, 0)
-        "unicodedata.UCD",              /*tp_name*/
-        sizeof(PreviousDBVersion),      /*tp_basicsize*/
-        0,                      /*tp_itemsize*/
-        /* methods */
-        (destructor)PyObject_Del, /*tp_dealloc*/
-        0,                      /*tp_print*/
-        0,                      /*tp_getattr*/
-        0,                      /*tp_setattr*/
-        0,                      /*tp_reserved*/
-        0,                      /*tp_repr*/
-        0,                      /*tp_as_number*/
-        0,                      /*tp_as_sequence*/
-        0,                      /*tp_as_mapping*/
-        0,                      /*tp_hash*/
-        0,                      /*tp_call*/
-        0,                      /*tp_str*/
-        PyObject_GenericGetAttr,/*tp_getattro*/
-        0,                      /*tp_setattro*/
-        0,                      /*tp_as_buffer*/
-        Py_TPFLAGS_DEFAULT,     /*tp_flags*/
-        0,                      /*tp_doc*/
-        0,                      /*tp_traverse*/
-        0,                      /*tp_clear*/
-        0,                      /*tp_richcompare*/
-        0,                      /*tp_weaklistoffset*/
-        0,                      /*tp_iter*/
-        0,                      /*tp_iternext*/
-        unicodedata_functions,  /*tp_methods*/
-        DB_members,             /*tp_members*/
-        0,                      /*tp_getset*/
-        0,                      /*tp_base*/
-        0,                      /*tp_dict*/
-        0,                      /*tp_descr_get*/
-        0,                      /*tp_descr_set*/
-        0,                      /*tp_dictoffset*/
-        0,                      /*tp_init*/
-        0,                      /*tp_alloc*/
-        0,                      /*tp_new*/
-        0,                      /*tp_free*/
-        0,                      /*tp_is_gc*/
-};
-
-PyDoc_STRVAR(unicodedata_docstring,
-"This module provides access to the Unicode Character Database which\n\
-defines character properties for all Unicode characters. The data in\n\
-this database is based on the UnicodeData.txt file version\n\
-" UNIDATA_VERSION " which is publically available from ftp://ftp.unicode.org/.\n\
-\n\
-The module uses the same names and symbols as defined by the\n\
-UnicodeData File Format " UNIDATA_VERSION ".");
-
-static struct PyModuleDef unicodedatamodule = {
-        PyModuleDef_HEAD_INIT,
-        "unicodedata",
-        unicodedata_docstring,
-        -1,
-        unicodedata_functions,
-        NULL,
-        NULL,
-        NULL,
-        NULL
-};
-
-PyMODINIT_FUNC
-PyInit_unicodedata(void)
-{
-    PyObject *m, *v;
-
-    Py_TYPE(&UCD_Type) = &PyType_Type;
-
-    m = PyModule_Create(&unicodedatamodule);
-    if (!m)
-        return NULL;
-
-    PyModule_AddStringConstant(m, "unidata_version", UNIDATA_VERSION);
-    Py_INCREF(&UCD_Type);
-    PyModule_AddObject(m, "UCD", (PyObject*)&UCD_Type);
-
-    /* Previous versions */
-    v = new_previous_version("3.2.0", get_change_3_2_0, normalization_3_2_0);
-    if (v != NULL)
-        PyModule_AddObject(m, "ucd_3_2_0", v);
-
-    /* Export C API */
-    v = PyCapsule_New((void *)&hashAPI, PyUnicodeData_CAPSULE_NAME, NULL);
-    if (v != NULL)
-        PyModule_AddObject(m, "ucnhash_CAPI", v);
-    return m;
-}
-
-/*
-Local variables:
-c-basic-offset: 4
-indent-tabs-mode: nil
-End:
-*/
+/*[clinic end generated code: output=15b82651419cc823 input=a9049054013a1b77]*/
diff --git a/Modules/cmathmodule.c b/Modules/cmathmodule.c
--- a/Modules/cmathmodule.c
+++ b/Modules/cmathmodule.c
@@ -10,10 +10,9 @@
 
 #include "clinic/cmathmodule.c.h"
 /*[clinic input]
-output preset file
 module cmath
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ef7e0fdd8a143c03]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=308d6839f4a46333]*/
 
 /*[python input]
 class Py_complex_protected_converter(Py_complex_converter):
diff --git a/Modules/fcntlmodule.c b/Modules/fcntlmodule.c
--- a/Modules/fcntlmodule.c
+++ b/Modules/fcntlmodule.c
@@ -16,10 +16,9 @@
 #endif
 
 /*[clinic input]
-output preset file
 module fcntl
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c7356fdb126a904a]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=124b58387c158179]*/
 
 static int
 conv_descriptor(PyObject *object, int *target)
diff --git a/Modules/grpmodule.c b/Modules/grpmodule.c
--- a/Modules/grpmodule.c
+++ b/Modules/grpmodule.c
@@ -8,10 +8,9 @@
 
 #include "clinic/grpmodule.c.h"
 /*[clinic input]
-output preset file
 module grp
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=68180a9a9efb8506]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=cade63f2ed1bd9f8]*/
 
 static PyStructSequence_Field struct_group_type_fields[] = {
    {"gr_name", "group name"},
diff --git a/Modules/md5module.c b/Modules/md5module.c
--- a/Modules/md5module.c
+++ b/Modules/md5module.c
@@ -53,6 +53,7 @@
     struct md5_state hash_state;
 } MD5object;
 
+#include "clinic/md5module.c.h"
 
 /* ------------------------------------------------------------------------
  *
@@ -343,27 +344,9 @@
 Return a copy of the hash object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(MD5Type_copy__doc__,
-"copy($self, /)\n"
-"--\n"
-"\n"
-"Return a copy of the hash object.");
-
-#define MD5TYPE_COPY_METHODDEF    \
-    {"copy", (PyCFunction)MD5Type_copy, METH_NOARGS, MD5Type_copy__doc__},
-
-static PyObject *
-MD5Type_copy_impl(MD5object *self);
-
-static PyObject *
-MD5Type_copy(MD5object *self, PyObject *Py_UNUSED(ignored))
-{
-    return MD5Type_copy_impl(self);
-}
-
 static PyObject *
 MD5Type_copy_impl(MD5object *self)
-/*[clinic end generated code: output=3b3a88920b3dc7f4 input=2c09e6d2493f3079]*/
+/*[clinic end generated code: output=596eb36852f02071 input=2c09e6d2493f3079]*/
 {
     MD5object *newobj;
 
@@ -385,27 +368,9 @@
 Return the digest value as a string of binary data.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(MD5Type_digest__doc__,
-"digest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of binary data.");
-
-#define MD5TYPE_DIGEST_METHODDEF    \
-    {"digest", (PyCFunction)MD5Type_digest, METH_NOARGS, MD5Type_digest__doc__},
-
-static PyObject *
-MD5Type_digest_impl(MD5object *self);
-
-static PyObject *
-MD5Type_digest(MD5object *self, PyObject *Py_UNUSED(ignored))
-{
-    return MD5Type_digest_impl(self);
-}
-
 static PyObject *
 MD5Type_digest_impl(MD5object *self)
-/*[clinic end generated code: output=7a796b28fa89485f input=7b96e65389412a34]*/
+/*[clinic end generated code: output=eb691dc4190a07ec input=7b96e65389412a34]*/
 {
     unsigned char digest[MD5_DIGESTSIZE];
     struct md5_state temp;
@@ -421,27 +386,9 @@
 Return the digest value as a string of hexadecimal digits.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(MD5Type_hexdigest__doc__,
-"hexdigest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of hexadecimal digits.");
-
-#define MD5TYPE_HEXDIGEST_METHODDEF    \
-    {"hexdigest", (PyCFunction)MD5Type_hexdigest, METH_NOARGS, MD5Type_hexdigest__doc__},
-
-static PyObject *
-MD5Type_hexdigest_impl(MD5object *self);
-
-static PyObject *
-MD5Type_hexdigest(MD5object *self, PyObject *Py_UNUSED(ignored))
-{
-    return MD5Type_hexdigest_impl(self);
-}
-
 static PyObject *
 MD5Type_hexdigest_impl(MD5object *self)
-/*[clinic end generated code: output=daa73609f94f92e1 input=b60b19de644798dd]*/
+/*[clinic end generated code: output=17badced1f3ac932 input=b60b19de644798dd]*/
 {
     unsigned char digest[MD5_DIGESTSIZE];
     struct md5_state temp;
@@ -482,18 +429,9 @@
 Update this hash object's state with the provided string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(MD5Type_update__doc__,
-"update($self, obj, /)\n"
-"--\n"
-"\n"
-"Update this hash object\'s state with the provided string.");
-
-#define MD5TYPE_UPDATE_METHODDEF    \
-    {"update", (PyCFunction)MD5Type_update, METH_O, MD5Type_update__doc__},
-
 static PyObject *
 MD5Type_update(MD5object *self, PyObject *obj)
-/*[clinic end generated code: output=9d09b6c6cdc6cac3 input=6e1efcd9ecf17032]*/
+/*[clinic end generated code: output=f6ad168416338423 input=6e1efcd9ecf17032]*/
 {
     Py_buffer buf;
 
@@ -594,38 +532,9 @@
 Return a new MD5 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_md5_md5__doc__,
-"md5($module, /, string=b\'\')\n"
-"--\n"
-"\n"
-"Return a new MD5 hash object; optionally initialized with a string.");
-
-#define _MD5_MD5_METHODDEF    \
-    {"md5", (PyCFunction)_md5_md5, METH_VARARGS|METH_KEYWORDS, _md5_md5__doc__},
-
-static PyObject *
-_md5_md5_impl(PyModuleDef *module, PyObject *string);
-
-static PyObject *
-_md5_md5(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"string", NULL};
-    PyObject *string = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:md5", _keywords,
-        &string))
-        goto exit;
-    return_value = _md5_md5_impl(module, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _md5_md5_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=1039e912d919880e input=d12ef8f72d684f7b]*/
+/*[clinic end generated code: output=3527436a2090b956 input=d12ef8f72d684f7b]*/
 {
     MD5object *new;
     Py_buffer buf;
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -2470,61 +2470,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_stat__doc__,
-"stat($module, /, path, *, dir_fd=None, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Perform a stat system call on the given path.\n"
-"\n"
-"  path\n"
-"    Path to be examined; can be string, bytes, or open-file-descriptor int.\n"
-"  dir_fd\n"
-"    If not None, it should be a file descriptor open to a directory,\n"
-"    and path should be a relative string; path will then be relative to\n"
-"    that directory.\n"
-"  follow_symlinks\n"
-"    If False, and the last element of the path is a symbolic link,\n"
-"    stat will examine the symbolic link itself instead of the file\n"
-"    the link points to.\n"
-"\n"
-"dir_fd and follow_symlinks may not be implemented\n"
-"  on your platform.  If they are unavailable, using them will raise a\n"
-"  NotImplementedError.\n"
-"\n"
-"It\'s an error to use dir_fd or follow_symlinks when specifying path as\n"
-"  an open file descriptor.");
-
-#define OS_STAT_METHODDEF    \
-    {"stat", (PyCFunction)os_stat, METH_VARARGS|METH_KEYWORDS, os_stat__doc__},
-
-static PyObject *
-os_stat_impl(PyModuleDef *module, path_t *path, int dir_fd, int follow_symlinks);
-
-static PyObject *
-os_stat(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "dir_fd", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("stat", "path", 0, 1);
-    int dir_fd = DEFAULT_DIR_FD;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|$O&p:stat", _keywords,
-        path_converter, &path, FSTATAT_DIR_FD_CONVERTER, &dir_fd, &follow_symlinks))
-        goto exit;
-    return_value = os_stat_impl(module, &path, dir_fd, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_stat_impl(PyModuleDef *module, path_t *path, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=0e9f9508fa0c0607 input=099d356c306fa24a]*/
+/*[clinic end generated code: output=708c225f94fcfc8e input=099d356c306fa24a]*/
 {
     return posix_do_stat("stat", path, dir_fd, follow_symlinks);
 }
@@ -2545,45 +2493,9 @@
 Equivalent to stat(path, follow_symlinks=False).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_lstat__doc__,
-"lstat($module, /, path, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Perform a stat system call on the given path, without following symbolic links.\n"
-"\n"
-"Like stat(), but do not follow symbolic links.\n"
-"Equivalent to stat(path, follow_symlinks=False).");
-
-#define OS_LSTAT_METHODDEF    \
-    {"lstat", (PyCFunction)os_lstat, METH_VARARGS|METH_KEYWORDS, os_lstat__doc__},
-
-static PyObject *
-os_lstat_impl(PyModuleDef *module, path_t *path, int dir_fd);
-
-static PyObject *
-os_lstat(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("lstat", "path", 0, 0);
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|$O&:lstat", _keywords,
-        path_converter, &path, FSTATAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_lstat_impl(module, &path, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_lstat_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=85702247224a2b1c input=0b7474765927b925]*/
+/*[clinic end generated code: output=7a748e333fcb39bd input=0b7474765927b925]*/
 {
     int follow_symlinks = 0;
     return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
@@ -2629,75 +2541,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_access__doc__,
-"access($module, /, path, mode, *, dir_fd=None, effective_ids=False,\n"
-"       follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Use the real uid/gid to test for access to a path.\n"
-"\n"
-"  path\n"
-"    Path to be tested; can be string, bytes, or open-file-descriptor int.\n"
-"  mode\n"
-"    Operating-system mode bitfield.  Can be F_OK to test existence,\n"
-"    or the inclusive-OR of R_OK, W_OK, and X_OK.\n"
-"  dir_fd\n"
-"    If not None, it should be a file descriptor open to a directory,\n"
-"    and path should be relative; path will then be relative to that\n"
-"    directory.\n"
-"  effective_ids\n"
-"    If True, access will use the effective uid/gid instead of\n"
-"    the real uid/gid.\n"
-"  follow_symlinks\n"
-"    If False, and the last element of the path is a symbolic link,\n"
-"    access will examine the symbolic link itself instead of the file\n"
-"    the link points to.\n"
-"\n"
-"dir_fd, effective_ids, and follow_symlinks may not be implemented\n"
-"  on your platform.  If they are unavailable, using them will raise a\n"
-"  NotImplementedError.\n"
-"\n"
-"Note that most operations will use the effective uid/gid, therefore this\n"
-"  routine can be used in a suid/sgid environment to test if the invoking user\n"
-"  has the specified access to the path.");
-
-#define OS_ACCESS_METHODDEF    \
-    {"access", (PyCFunction)os_access, METH_VARARGS|METH_KEYWORDS, os_access__doc__},
-
-static int
-os_access_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd, int effective_ids, int follow_symlinks);
-
-static PyObject *
-os_access(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "mode", "dir_fd", "effective_ids", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("access", "path", 0, 1);
-    int mode;
-    int dir_fd = DEFAULT_DIR_FD;
-    int effective_ids = 0;
-    int follow_symlinks = 1;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&i|$O&pp:access", _keywords,
-        path_converter, &path, &mode, FACCESSAT_DIR_FD_CONVERTER, &dir_fd, &effective_ids, &follow_symlinks))
-        goto exit;
-    _return_value = os_access_impl(module, &path, mode, dir_fd, effective_ids, follow_symlinks);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static int
 os_access_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd, int effective_ids, int follow_symlinks)
-/*[clinic end generated code: output=dfd404666906f012 input=b75a756797af45ec]*/
+/*[clinic end generated code: output=f9e734db3d88b767 input=b75a756797af45ec]*/
 {
     int return_value;
 
@@ -2787,44 +2633,9 @@
 Return the name of the terminal device connected to 'fd'.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_ttyname__doc__,
-"ttyname($module, fd, /)\n"
-"--\n"
-"\n"
-"Return the name of the terminal device connected to \'fd\'.\n"
-"\n"
-"  fd\n"
-"    Integer file descriptor handle.");
-
-#define OS_TTYNAME_METHODDEF    \
-    {"ttyname", (PyCFunction)os_ttyname, METH_VARARGS, os_ttyname__doc__},
-
-static char *
-os_ttyname_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_ttyname(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    char *_return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "i:ttyname",
-        &fd))
-        goto exit;
-    _return_value = os_ttyname_impl(module, fd);
-    if (_return_value == NULL)
-        goto exit;
-    return_value = PyUnicode_DecodeFSDefault(_return_value);
-
-exit:
-    return return_value;
-}
-
 static char *
 os_ttyname_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=cee7bc4cffec01a2 input=5f72ca83e76b3b45]*/
+/*[clinic end generated code: output=03ad3d5ccaef75c3 input=5f72ca83e76b3b45]*/
 {
     char *ret;
 
@@ -2842,27 +2653,9 @@
 Return the name of the controlling terminal for this process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_ctermid__doc__,
-"ctermid($module, /)\n"
-"--\n"
-"\n"
-"Return the name of the controlling terminal for this process.");
-
-#define OS_CTERMID_METHODDEF    \
-    {"ctermid", (PyCFunction)os_ctermid, METH_NOARGS, os_ctermid__doc__},
-
-static PyObject *
-os_ctermid_impl(PyModuleDef *module);
-
-static PyObject *
-os_ctermid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_ctermid_impl(module);
-}
-
 static PyObject *
 os_ctermid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=277bf7964ec2d782 input=3b87fdd52556382d]*/
+/*[clinic end generated code: output=1b73788201e0aebd input=3b87fdd52556382d]*/
 {
     char *ret;
     char buffer[L_ctermid];
@@ -2891,45 +2684,9 @@
   If this functionality is unavailable, using it raises an exception.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_chdir__doc__,
-"chdir($module, /, path)\n"
-"--\n"
-"\n"
-"Change the current working directory to the specified path.\n"
-"\n"
-"path may always be specified as a string.\n"
-"On some platforms, path may also be specified as an open file descriptor.\n"
-"  If this functionality is unavailable, using it raises an exception.");
-
-#define OS_CHDIR_METHODDEF    \
-    {"chdir", (PyCFunction)os_chdir, METH_VARARGS|METH_KEYWORDS, os_chdir__doc__},
-
-static PyObject *
-os_chdir_impl(PyModuleDef *module, path_t *path);
-
-static PyObject *
-os_chdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", NULL};
-    path_t path = PATH_T_INITIALIZE("chdir", "path", 0, PATH_HAVE_FCHDIR);
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:chdir", _keywords,
-        path_converter, &path))
-        goto exit;
-    return_value = os_chdir_impl(module, &path);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_chdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=cc07592dd23ca9e0 input=1a4a15b4d12cb15d]*/
+/*[clinic end generated code: output=7358e3a20fb5aa93 input=1a4a15b4d12cb15d]*/
 {
     int result;
 
@@ -2971,41 +2728,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fchdir__doc__,
-"fchdir($module, /, fd)\n"
-"--\n"
-"\n"
-"Change to the directory of the given file descriptor.\n"
-"\n"
-"fd must be opened on a directory, not a file.\n"
-"Equivalent to os.chdir(fd).");
-
-#define OS_FCHDIR_METHODDEF    \
-    {"fchdir", (PyCFunction)os_fchdir, METH_VARARGS|METH_KEYWORDS, os_fchdir__doc__},
-
-static PyObject *
-os_fchdir_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_fchdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", NULL};
-    int fd;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:fchdir", _keywords,
-        fildes_converter, &fd))
-        goto exit;
-    return_value = os_fchdir_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fchdir_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=9f6dbc89b2778834 input=18e816479a2fa985]*/
+/*[clinic end generated code: output=361d30df6b2d3418 input=18e816479a2fa985]*/
 {
     return posix_fildes_fd(fd, fchdir);
 }
@@ -3044,64 +2769,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_chmod__doc__,
-"chmod($module, /, path, mode, *, dir_fd=None, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Change the access permissions of a file.\n"
-"\n"
-"  path\n"
-"    Path to be modified.  May always be specified as a str or bytes.\n"
-"    On some platforms, path may also be specified as an open file descriptor.\n"
-"    If this functionality is unavailable, using it raises an exception.\n"
-"  mode\n"
-"    Operating-system mode bitfield.\n"
-"  dir_fd\n"
-"    If not None, it should be a file descriptor open to a directory,\n"
-"    and path should be relative; path will then be relative to that\n"
-"    directory.\n"
-"  follow_symlinks\n"
-"    If False, and the last element of the path is a symbolic link,\n"
-"    chmod will modify the symbolic link itself instead of the file\n"
-"    the link points to.\n"
-"\n"
-"It is an error to use dir_fd or follow_symlinks when specifying path as\n"
-"  an open file descriptor.\n"
-"dir_fd and follow_symlinks may not be implemented on your platform.\n"
-"  If they are unavailable, using them will raise a NotImplementedError.");
-
-#define OS_CHMOD_METHODDEF    \
-    {"chmod", (PyCFunction)os_chmod, METH_VARARGS|METH_KEYWORDS, os_chmod__doc__},
-
-static PyObject *
-os_chmod_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd, int follow_symlinks);
-
-static PyObject *
-os_chmod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "mode", "dir_fd", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("chmod", "path", 0, PATH_HAVE_FCHMOD);
-    int mode;
-    int dir_fd = DEFAULT_DIR_FD;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&i|$O&p:chmod", _keywords,
-        path_converter, &path, &mode, FCHMODAT_DIR_FD_CONVERTER, &dir_fd, &follow_symlinks))
-        goto exit;
-    return_value = os_chmod_impl(module, &path, mode, dir_fd, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_chmod_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=1e9db031aea46422 input=7f1618e5e15cc196]*/
+/*[clinic end generated code: output=96063c976f23106a input=7f1618e5e15cc196]*/
 {
     int result;
 
@@ -3212,41 +2882,9 @@
 Equivalent to os.chmod(fd, mode).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fchmod__doc__,
-"fchmod($module, /, fd, mode)\n"
-"--\n"
-"\n"
-"Change the access permissions of the file given by file descriptor fd.\n"
-"\n"
-"Equivalent to os.chmod(fd, mode).");
-
-#define OS_FCHMOD_METHODDEF    \
-    {"fchmod", (PyCFunction)os_fchmod, METH_VARARGS|METH_KEYWORDS, os_fchmod__doc__},
-
-static PyObject *
-os_fchmod_impl(PyModuleDef *module, int fd, int mode);
-
-static PyObject *
-os_fchmod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", "mode", NULL};
-    int fd;
-    int mode;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "ii:fchmod", _keywords,
-        &fd, &mode))
-        goto exit;
-    return_value = os_fchmod_impl(module, fd, mode);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fchmod_impl(PyModuleDef *module, int fd, int mode)
-/*[clinic end generated code: output=3c19fbfd724a8e0f input=8ab11975ca01ee5b]*/
+/*[clinic end generated code: output=2ee31ca226d1ed33 input=8ab11975ca01ee5b]*/
 {
     int res;
     int async_err = 0;
@@ -3277,45 +2915,9 @@
 Equivalent to chmod(path, mode, follow_symlinks=False)."
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_lchmod__doc__,
-"lchmod($module, /, path, mode)\n"
-"--\n"
-"\n"
-"Change the access permissions of a file, without following symbolic links.\n"
-"\n"
-"If path is a symlink, this affects the link itself rather than the target.\n"
-"Equivalent to chmod(path, mode, follow_symlinks=False).\"");
-
-#define OS_LCHMOD_METHODDEF    \
-    {"lchmod", (PyCFunction)os_lchmod, METH_VARARGS|METH_KEYWORDS, os_lchmod__doc__},
-
-static PyObject *
-os_lchmod_impl(PyModuleDef *module, path_t *path, int mode);
-
-static PyObject *
-os_lchmod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "mode", NULL};
-    path_t path = PATH_T_INITIALIZE("lchmod", "path", 0, 0);
-    int mode;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&i:lchmod", _keywords,
-        path_converter, &path, &mode))
-        goto exit;
-    return_value = os_lchmod_impl(module, &path, mode);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_lchmod_impl(PyModuleDef *module, path_t *path, int mode)
-/*[clinic end generated code: output=2849977d65f8c68c input=90c5663c7465d24f]*/
+/*[clinic end generated code: output=7c0cc46588d89e46 input=90c5663c7465d24f]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -3348,49 +2950,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_chflags__doc__,
-"chflags($module, /, path, flags, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Set file flags.\n"
-"\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, chflags will change flags on the symbolic link itself instead of the\n"
-"  file the link points to.\n"
-"follow_symlinks may not be implemented on your platform.  If it is\n"
-"unavailable, using it will raise a NotImplementedError.");
-
-#define OS_CHFLAGS_METHODDEF    \
-    {"chflags", (PyCFunction)os_chflags, METH_VARARGS|METH_KEYWORDS, os_chflags__doc__},
-
-static PyObject *
-os_chflags_impl(PyModuleDef *module, path_t *path, unsigned long flags, int follow_symlinks);
-
-static PyObject *
-os_chflags(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "flags", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("chflags", "path", 0, 0);
-    unsigned long flags;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&k|p:chflags", _keywords,
-        path_converter, &path, &flags, &follow_symlinks))
-        goto exit;
-    return_value = os_chflags_impl(module, &path, flags, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_chflags_impl(PyModuleDef *module, path_t *path, unsigned long flags, int follow_symlinks)
-/*[clinic end generated code: output=2767927bf071e3cf input=0327e29feb876236]*/
+/*[clinic end generated code: output=9e5f9417afc20c4b input=0327e29feb876236]*/
 {
     int result;
 
@@ -3429,45 +2991,9 @@
 Equivalent to chflags(path, flags, follow_symlinks=False).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_lchflags__doc__,
-"lchflags($module, /, path, flags)\n"
-"--\n"
-"\n"
-"Set file flags.\n"
-"\n"
-"This function will not follow symbolic links.\n"
-"Equivalent to chflags(path, flags, follow_symlinks=False).");
-
-#define OS_LCHFLAGS_METHODDEF    \
-    {"lchflags", (PyCFunction)os_lchflags, METH_VARARGS|METH_KEYWORDS, os_lchflags__doc__},
-
-static PyObject *
-os_lchflags_impl(PyModuleDef *module, path_t *path, unsigned long flags);
-
-static PyObject *
-os_lchflags(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "flags", NULL};
-    path_t path = PATH_T_INITIALIZE("lchflags", "path", 0, 0);
-    unsigned long flags;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&k:lchflags", _keywords,
-        path_converter, &path, &flags))
-        goto exit;
-    return_value = os_lchflags_impl(module, &path, flags);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_lchflags_impl(PyModuleDef *module, path_t *path, unsigned long flags)
-/*[clinic end generated code: output=bb93b6b8a5e45aa7 input=f9f82ea8b585ca9d]*/
+/*[clinic end generated code: output=6741322fb949661b input=f9f82ea8b585ca9d]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -3490,41 +3016,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_chroot__doc__,
-"chroot($module, /, path)\n"
-"--\n"
-"\n"
-"Change root directory to path.");
-
-#define OS_CHROOT_METHODDEF    \
-    {"chroot", (PyCFunction)os_chroot, METH_VARARGS|METH_KEYWORDS, os_chroot__doc__},
-
-static PyObject *
-os_chroot_impl(PyModuleDef *module, path_t *path);
-
-static PyObject *
-os_chroot(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", NULL};
-    path_t path = PATH_T_INITIALIZE("chroot", "path", 0, 0);
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:chroot", _keywords,
-        path_converter, &path))
-        goto exit;
-    return_value = os_chroot_impl(module, &path);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_chroot_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=15b1256cbe4f24a1 input=14822965652c3dc3]*/
+/*[clinic end generated code: output=b6dbfabe74ecaa9d input=14822965652c3dc3]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -3546,38 +3040,9 @@
 Force write of fd to disk.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fsync__doc__,
-"fsync($module, /, fd)\n"
-"--\n"
-"\n"
-"Force write of fd to disk.");
-
-#define OS_FSYNC_METHODDEF    \
-    {"fsync", (PyCFunction)os_fsync, METH_VARARGS|METH_KEYWORDS, os_fsync__doc__},
-
-static PyObject *
-os_fsync_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_fsync(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", NULL};
-    int fd;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:fsync", _keywords,
-        fildes_converter, &fd))
-        goto exit;
-    return_value = os_fsync_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fsync_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=59f32d3a0b360133 input=21c3645c056967f2]*/
+/*[clinic end generated code: output=83a350851064aea7 input=21c3645c056967f2]*/
 {
     return posix_fildes_fd(fd, fsync);
 }
@@ -3591,27 +3056,9 @@
 Force write of everything to disk.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sync__doc__,
-"sync($module, /)\n"
-"--\n"
-"\n"
-"Force write of everything to disk.");
-
-#define OS_SYNC_METHODDEF    \
-    {"sync", (PyCFunction)os_sync, METH_NOARGS, os_sync__doc__},
-
-static PyObject *
-os_sync_impl(PyModuleDef *module);
-
-static PyObject *
-os_sync(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_sync_impl(module);
-}
-
 static PyObject *
 os_sync_impl(PyModuleDef *module)
-/*[clinic end generated code: output=526c495683d0bb38 input=84749fe5e9b404ff]*/
+/*[clinic end generated code: output=ba524f656c201c40 input=84749fe5e9b404ff]*/
 {
     Py_BEGIN_ALLOW_THREADS
     sync();
@@ -3634,38 +3081,9 @@
 Force write of fd to disk without forcing update of metadata.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fdatasync__doc__,
-"fdatasync($module, /, fd)\n"
-"--\n"
-"\n"
-"Force write of fd to disk without forcing update of metadata.");
-
-#define OS_FDATASYNC_METHODDEF    \
-    {"fdatasync", (PyCFunction)os_fdatasync, METH_VARARGS|METH_KEYWORDS, os_fdatasync__doc__},
-
-static PyObject *
-os_fdatasync_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_fdatasync(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", NULL};
-    int fd;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:fdatasync", _keywords,
-        fildes_converter, &fd))
-        goto exit;
-    return_value = os_fdatasync_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fdatasync_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=2335fdfd37c92180 input=bc74791ee54dd291]*/
+/*[clinic end generated code: output=e0f04a3aff515b75 input=bc74791ee54dd291]*/
 {
     return posix_fildes_fd(fd, fdatasync);
 }
@@ -3712,69 +3130,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_chown__doc__,
-"chown($module, /, path, uid, gid, *, dir_fd=None, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Change the owner and group id of path to the numeric uid and gid.\\\n"
-"\n"
-"  path\n"
-"    Path to be examined; can be string, bytes, or open-file-descriptor int.\n"
-"  dir_fd\n"
-"    If not None, it should be a file descriptor open to a directory,\n"
-"    and path should be relative; path will then be relative to that\n"
-"    directory.\n"
-"  follow_symlinks\n"
-"    If False, and the last element of the path is a symbolic link,\n"
-"    stat will examine the symbolic link itself instead of the file\n"
-"    the link points to.\n"
-"\n"
-"path may always be specified as a string.\n"
-"On some platforms, path may also be specified as an open file descriptor.\n"
-"  If this functionality is unavailable, using it raises an exception.\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, chown will modify the symbolic link itself instead of the file the\n"
-"  link points to.\n"
-"It is an error to use dir_fd or follow_symlinks when specifying path as\n"
-"  an open file descriptor.\n"
-"dir_fd and follow_symlinks may not be implemented on your platform.\n"
-"  If they are unavailable, using them will raise a NotImplementedError.");
-
-#define OS_CHOWN_METHODDEF    \
-    {"chown", (PyCFunction)os_chown, METH_VARARGS|METH_KEYWORDS, os_chown__doc__},
-
-static PyObject *
-os_chown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid, int dir_fd, int follow_symlinks);
-
-static PyObject *
-os_chown(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "uid", "gid", "dir_fd", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("chown", "path", 0, PATH_HAVE_FCHOWN);
-    uid_t uid;
-    gid_t gid;
-    int dir_fd = DEFAULT_DIR_FD;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&O&|$O&p:chown", _keywords,
-        path_converter, &path, _Py_Uid_Converter, &uid, _Py_Gid_Converter, &gid, FCHOWNAT_DIR_FD_CONVERTER, &dir_fd, &follow_symlinks))
-        goto exit;
-    return_value = os_chown_impl(module, &path, uid, gid, dir_fd, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_chown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=22f011e3b4f9ff49 input=a61cc35574814d5d]*/
+/*[clinic end generated code: output=59a8db91897fb46c input=a61cc35574814d5d]*/
 {
     int result;
 
@@ -3841,42 +3199,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fchown__doc__,
-"fchown($module, /, fd, uid, gid)\n"
-"--\n"
-"\n"
-"Change the owner and group id of the file specified by file descriptor.\n"
-"\n"
-"Equivalent to os.chown(fd, uid, gid).");
-
-#define OS_FCHOWN_METHODDEF    \
-    {"fchown", (PyCFunction)os_fchown, METH_VARARGS|METH_KEYWORDS, os_fchown__doc__},
-
-static PyObject *
-os_fchown_impl(PyModuleDef *module, int fd, uid_t uid, gid_t gid);
-
-static PyObject *
-os_fchown(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", "uid", "gid", NULL};
-    int fd;
-    uid_t uid;
-    gid_t gid;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "iO&O&:fchown", _keywords,
-        &fd, _Py_Uid_Converter, &uid, _Py_Gid_Converter, &gid))
-        goto exit;
-    return_value = os_fchown_impl(module, fd, uid, gid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fchown_impl(PyModuleDef *module, int fd, uid_t uid, gid_t gid)
-/*[clinic end generated code: output=687781cb7d8974d6 input=3af544ba1b13a0d7]*/
+/*[clinic end generated code: output=7545abf8f6086d76 input=3af544ba1b13a0d7]*/
 {
     int res;
     int async_err = 0;
@@ -3908,46 +3233,9 @@
 Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_lchown__doc__,
-"lchown($module, /, path, uid, gid)\n"
-"--\n"
-"\n"
-"Change the owner and group id of path to the numeric uid and gid.\n"
-"\n"
-"This function will not follow symbolic links.\n"
-"Equivalent to os.chown(path, uid, gid, follow_symlinks=False).");
-
-#define OS_LCHOWN_METHODDEF    \
-    {"lchown", (PyCFunction)os_lchown, METH_VARARGS|METH_KEYWORDS, os_lchown__doc__},
-
-static PyObject *
-os_lchown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid);
-
-static PyObject *
-os_lchown(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "uid", "gid", NULL};
-    path_t path = PATH_T_INITIALIZE("lchown", "path", 0, 0);
-    uid_t uid;
-    gid_t gid;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&O&:lchown", _keywords,
-        path_converter, &path, _Py_Uid_Converter, &uid, _Py_Gid_Converter, &gid))
-        goto exit;
-    return_value = os_lchown_impl(module, &path, uid, gid);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_lchown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid)
-/*[clinic end generated code: output=bf25fdb0d25130e2 input=b1c6014d563a7161]*/
+/*[clinic end generated code: output=bb0d2da1579ac275 input=b1c6014d563a7161]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -4020,27 +3308,9 @@
 Return a unicode string representing the current working directory.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getcwd__doc__,
-"getcwd($module, /)\n"
-"--\n"
-"\n"
-"Return a unicode string representing the current working directory.");
-
-#define OS_GETCWD_METHODDEF    \
-    {"getcwd", (PyCFunction)os_getcwd, METH_NOARGS, os_getcwd__doc__},
-
-static PyObject *
-os_getcwd_impl(PyModuleDef *module);
-
-static PyObject *
-os_getcwd(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getcwd_impl(module);
-}
-
 static PyObject *
 os_getcwd_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d70b281db5c78ff7 input=f069211bb70e3d39]*/
+/*[clinic end generated code: output=efe3a8c0121525ea input=f069211bb70e3d39]*/
 {
     return posix_getcwd(0);
 }
@@ -4052,27 +3322,9 @@
 Return a bytes string representing the current working directory.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getcwdb__doc__,
-"getcwdb($module, /)\n"
-"--\n"
-"\n"
-"Return a bytes string representing the current working directory.");
-
-#define OS_GETCWDB_METHODDEF    \
-    {"getcwdb", (PyCFunction)os_getcwdb, METH_NOARGS, os_getcwdb__doc__},
-
-static PyObject *
-os_getcwdb_impl(PyModuleDef *module);
-
-static PyObject *
-os_getcwdb(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getcwdb_impl(module);
-}
-
 static PyObject *
 os_getcwdb_impl(PyModuleDef *module)
-/*[clinic end generated code: output=75da47f2d75f9166 input=f6f6a378dad3d9cb]*/
+/*[clinic end generated code: output=7fce42ee4b2a296a input=f6f6a378dad3d9cb]*/
 {
     return posix_getcwd(1);
 }
@@ -4107,58 +3359,9 @@
   NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_link__doc__,
-"link($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None,\n"
-"     follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Create a hard link to a file.\n"
-"\n"
-"If either src_dir_fd or dst_dir_fd is not None, it should be a file\n"
-"  descriptor open to a directory, and the respective path string (src or dst)\n"
-"  should be relative; the path will then be relative to that directory.\n"
-"If follow_symlinks is False, and the last element of src is a symbolic\n"
-"  link, link will create a link to the symbolic link itself instead of the\n"
-"  file the link points to.\n"
-"src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your\n"
-"  platform.  If they are unavailable, using them will raise a\n"
-"  NotImplementedError.");
-
-#define OS_LINK_METHODDEF    \
-    {"link", (PyCFunction)os_link, METH_VARARGS|METH_KEYWORDS, os_link__doc__},
-
-static PyObject *
-os_link_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int follow_symlinks);
-
-static PyObject *
-os_link(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"src", "dst", "src_dir_fd", "dst_dir_fd", "follow_symlinks", NULL};
-    path_t src = PATH_T_INITIALIZE("link", "src", 0, 0);
-    path_t dst = PATH_T_INITIALIZE("link", "dst", 0, 0);
-    int src_dir_fd = DEFAULT_DIR_FD;
-    int dst_dir_fd = DEFAULT_DIR_FD;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&|$O&O&p:link", _keywords,
-        path_converter, &src, path_converter, &dst, dir_fd_converter, &src_dir_fd, dir_fd_converter, &dst_dir_fd, &follow_symlinks))
-        goto exit;
-    return_value = os_link_impl(module, &src, &dst, src_dir_fd, dst_dir_fd, follow_symlinks);
-
-exit:
-    /* Cleanup for src */
-    path_cleanup(&src);
-    /* Cleanup for dst */
-    path_cleanup(&dst);
-
-    return return_value;
-}
-
 static PyObject *
 os_link_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=53477662fe02e183 input=b0095ebbcbaa7e04]*/
+/*[clinic end generated code: output=c0a9ded8111d2a79 input=b0095ebbcbaa7e04]*/
 {
 #ifdef MS_WINDOWS
     BOOL result;
@@ -4496,52 +3699,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_listdir__doc__,
-"listdir($module, /, path=None)\n"
-"--\n"
-"\n"
-"Return a list containing the names of the files in the directory.\n"
-"\n"
-"path can be specified as either str or bytes.  If path is bytes,\n"
-"  the filenames returned will also be bytes; in all other circumstances\n"
-"  the filenames returned will be str.\n"
-"If path is None, uses the path=\'.\'.\n"
-"On some platforms, path may also be specified as an open file descriptor;\\\n"
-"  the file descriptor must refer to a directory.\n"
-"  If this functionality is unavailable, using it raises NotImplementedError.\n"
-"\n"
-"The list is in arbitrary order.  It does not include the special\n"
-"entries \'.\' and \'..\' even if they are present in the directory.");
-
-#define OS_LISTDIR_METHODDEF    \
-    {"listdir", (PyCFunction)os_listdir, METH_VARARGS|METH_KEYWORDS, os_listdir__doc__},
-
-static PyObject *
-os_listdir_impl(PyModuleDef *module, path_t *path);
-
-static PyObject *
-os_listdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", NULL};
-    path_t path = PATH_T_INITIALIZE("listdir", "path", 1, PATH_HAVE_FDOPENDIR);
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O&:listdir", _keywords,
-        path_converter, &path))
-        goto exit;
-    return_value = os_listdir_impl(module, &path);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_listdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=e159bd9be6909018 input=09e300416e3cd729]*/
+/*[clinic end generated code: output=1fbe67c1f780c8b7 input=09e300416e3cd729]*/
 {
 #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
     return _listdir_windows_no_opendir(path, NULL);
@@ -4620,37 +3780,9 @@
 A helper function for samepath on windows.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os__getfinalpathname__doc__,
-"_getfinalpathname($module, path, /)\n"
-"--\n"
-"\n"
-"A helper function for samepath on windows.");
-
-#define OS__GETFINALPATHNAME_METHODDEF    \
-    {"_getfinalpathname", (PyCFunction)os__getfinalpathname, METH_VARARGS, os__getfinalpathname__doc__},
-
-static PyObject *
-os__getfinalpathname_impl(PyModuleDef *module, PyObject *path);
-
-static PyObject *
-os__getfinalpathname(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *path;
-
-    if (!PyArg_ParseTuple(args,
-        "U:_getfinalpathname",
-        &path))
-        goto exit;
-    return_value = os__getfinalpathname_impl(module, path);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os__getfinalpathname_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=4563c6eacf1b0881 input=71d5e89334891bf4]*/
+/*[clinic end generated code: output=8be81a5f51a34bcf input=71d5e89334891bf4]*/
 {
     HANDLE hFile;
     int buf_size;
@@ -4750,38 +3882,9 @@
 A helper function for ismount on Win32.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os__getvolumepathname__doc__,
-"_getvolumepathname($module, /, path)\n"
-"--\n"
-"\n"
-"A helper function for ismount on Win32.");
-
-#define OS__GETVOLUMEPATHNAME_METHODDEF    \
-    {"_getvolumepathname", (PyCFunction)os__getvolumepathname, METH_VARARGS|METH_KEYWORDS, os__getvolumepathname__doc__},
-
-static PyObject *
-os__getvolumepathname_impl(PyModuleDef *module, PyObject *path);
-
-static PyObject *
-os__getvolumepathname(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", NULL};
-    PyObject *path;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "U:_getvolumepathname", _keywords,
-        &path))
-        goto exit;
-    return_value = os__getvolumepathname_impl(module, path);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os__getvolumepathname_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=ac0833b6d6da7657 input=7eacadc40acbda6b]*/
+/*[clinic end generated code: output=79a0ba729f956dbe input=7eacadc40acbda6b]*/
 {
     PyObject *result;
     wchar_t *path_wchar, *mountpath=NULL;
@@ -4847,50 +3950,9 @@
 The mode argument is ignored on Windows.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_mkdir__doc__,
-"mkdir($module, /, path, mode=511, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Create a directory.\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.\n"
-"\n"
-"The mode argument is ignored on Windows.");
-
-#define OS_MKDIR_METHODDEF    \
-    {"mkdir", (PyCFunction)os_mkdir, METH_VARARGS|METH_KEYWORDS, os_mkdir__doc__},
-
-static PyObject *
-os_mkdir_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd);
-
-static PyObject *
-os_mkdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "mode", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("mkdir", "path", 0, 0);
-    int mode = 511;
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|i$O&:mkdir", _keywords,
-        path_converter, &path, &mode, MKDIRAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_mkdir_impl(module, &path, mode, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_mkdir_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd)
-/*[clinic end generated code: output=55c6ef2bc1b207e6 input=e965f68377e9b1ce]*/
+/*[clinic end generated code: output=8bf1f738873ef2c5 input=e965f68377e9b1ce]*/
 {
     int result;
 
@@ -4940,37 +4002,9 @@
 Add increment to the priority of process and return the new priority.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_nice__doc__,
-"nice($module, increment, /)\n"
-"--\n"
-"\n"
-"Add increment to the priority of process and return the new priority.");
-
-#define OS_NICE_METHODDEF    \
-    {"nice", (PyCFunction)os_nice, METH_VARARGS, os_nice__doc__},
-
-static PyObject *
-os_nice_impl(PyModuleDef *module, int increment);
-
-static PyObject *
-os_nice(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int increment;
-
-    if (!PyArg_ParseTuple(args,
-        "i:nice",
-        &increment))
-        goto exit;
-    return_value = os_nice_impl(module, increment);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_nice_impl(PyModuleDef *module, int increment)
-/*[clinic end generated code: output=c360dc2a3bd8e3d0 input=864be2d402a21da2]*/
+/*[clinic end generated code: output=8870418a3fc07b51 input=864be2d402a21da2]*/
 {
     int value;
 
@@ -5008,39 +4042,9 @@
 Return program scheduling priority.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getpriority__doc__,
-"getpriority($module, /, which, who)\n"
-"--\n"
-"\n"
-"Return program scheduling priority.");
-
-#define OS_GETPRIORITY_METHODDEF    \
-    {"getpriority", (PyCFunction)os_getpriority, METH_VARARGS|METH_KEYWORDS, os_getpriority__doc__},
-
-static PyObject *
-os_getpriority_impl(PyModuleDef *module, int which, int who);
-
-static PyObject *
-os_getpriority(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"which", "who", NULL};
-    int which;
-    int who;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "ii:getpriority", _keywords,
-        &which, &who))
-        goto exit;
-    return_value = os_getpriority_impl(module, which, who);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_getpriority_impl(PyModuleDef *module, int which, int who)
-/*[clinic end generated code: output=81639cf765f05dae input=9be615d40e2544ef]*/
+/*[clinic end generated code: output=4759937aa5b67ed6 input=9be615d40e2544ef]*/
 {
     int retval;
 
@@ -5064,40 +4068,9 @@
 Set program scheduling priority.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setpriority__doc__,
-"setpriority($module, /, which, who, priority)\n"
-"--\n"
-"\n"
-"Set program scheduling priority.");
-
-#define OS_SETPRIORITY_METHODDEF    \
-    {"setpriority", (PyCFunction)os_setpriority, METH_VARARGS|METH_KEYWORDS, os_setpriority__doc__},
-
-static PyObject *
-os_setpriority_impl(PyModuleDef *module, int which, int who, int priority);
-
-static PyObject *
-os_setpriority(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"which", "who", "priority", NULL};
-    int which;
-    int who;
-    int priority;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "iii:setpriority", _keywords,
-        &which, &who, &priority))
-        goto exit;
-    return_value = os_setpriority_impl(module, which, who, priority);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setpriority_impl(PyModuleDef *module, int which, int who, int priority)
-/*[clinic end generated code: output=ddad62651fb2120c input=710ccbf65b9dc513]*/
+/*[clinic end generated code: output=6497d3301547e7d5 input=710ccbf65b9dc513]*/
 {
     int retval;
 
@@ -5183,52 +4156,9 @@
   If they are unavailable, using them will raise a NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_rename__doc__,
-"rename($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None)\n"
-"--\n"
-"\n"
-"Rename a file or directory.\n"
-"\n"
-"If either src_dir_fd or dst_dir_fd is not None, it should be a file\n"
-"  descriptor open to a directory, and the respective path string (src or dst)\n"
-"  should be relative; the path will then be relative to that directory.\n"
-"src_dir_fd and dst_dir_fd, may not be implemented on your platform.\n"
-"  If they are unavailable, using them will raise a NotImplementedError.");
-
-#define OS_RENAME_METHODDEF    \
-    {"rename", (PyCFunction)os_rename, METH_VARARGS|METH_KEYWORDS, os_rename__doc__},
-
-static PyObject *
-os_rename_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd);
-
-static PyObject *
-os_rename(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"src", "dst", "src_dir_fd", "dst_dir_fd", NULL};
-    path_t src = PATH_T_INITIALIZE("rename", "src", 0, 0);
-    path_t dst = PATH_T_INITIALIZE("rename", "dst", 0, 0);
-    int src_dir_fd = DEFAULT_DIR_FD;
-    int dst_dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&|$O&O&:rename", _keywords,
-        path_converter, &src, path_converter, &dst, dir_fd_converter, &src_dir_fd, dir_fd_converter, &dst_dir_fd))
-        goto exit;
-    return_value = os_rename_impl(module, &src, &dst, src_dir_fd, dst_dir_fd);
-
-exit:
-    /* Cleanup for src */
-    path_cleanup(&src);
-    /* Cleanup for dst */
-    path_cleanup(&dst);
-
-    return return_value;
-}
-
 static PyObject *
 os_rename_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd)
-/*[clinic end generated code: output=c936bdc81f460a1e input=faa61c847912c850]*/
+/*[clinic end generated code: output=1bb520bf2fad186d input=faa61c847912c850]*/
 {
     return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
 }
@@ -5246,52 +4176,9 @@
   If they are unavailable, using them will raise a NotImplementedError."
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_replace__doc__,
-"replace($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None)\n"
-"--\n"
-"\n"
-"Rename a file or directory, overwriting the destination.\n"
-"\n"
-"If either src_dir_fd or dst_dir_fd is not None, it should be a file\n"
-"  descriptor open to a directory, and the respective path string (src or dst)\n"
-"  should be relative; the path will then be relative to that directory.\n"
-"src_dir_fd and dst_dir_fd, may not be implemented on your platform.\n"
-"  If they are unavailable, using them will raise a NotImplementedError.\"");
-
-#define OS_REPLACE_METHODDEF    \
-    {"replace", (PyCFunction)os_replace, METH_VARARGS|METH_KEYWORDS, os_replace__doc__},
-
-static PyObject *
-os_replace_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd);
-
-static PyObject *
-os_replace(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"src", "dst", "src_dir_fd", "dst_dir_fd", NULL};
-    path_t src = PATH_T_INITIALIZE("replace", "src", 0, 0);
-    path_t dst = PATH_T_INITIALIZE("replace", "dst", 0, 0);
-    int src_dir_fd = DEFAULT_DIR_FD;
-    int dst_dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&|$O&O&:replace", _keywords,
-        path_converter, &src, path_converter, &dst, dir_fd_converter, &src_dir_fd, dir_fd_converter, &dst_dir_fd))
-        goto exit;
-    return_value = os_replace_impl(module, &src, &dst, src_dir_fd, dst_dir_fd);
-
-exit:
-    /* Cleanup for src */
-    path_cleanup(&src);
-    /* Cleanup for dst */
-    path_cleanup(&dst);
-
-    return return_value;
-}
-
 static PyObject *
 os_replace_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd)
-/*[clinic end generated code: output=224e4710d290d171 input=25515dfb107c8421]*/
+/*[clinic end generated code: output=aa9ddad55fdef8e3 input=25515dfb107c8421]*/
 {
     return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
 }
@@ -5312,47 +4199,9 @@
   If it is unavailable, using it will raise a NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_rmdir__doc__,
-"rmdir($module, /, path, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Remove a directory.\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_RMDIR_METHODDEF    \
-    {"rmdir", (PyCFunction)os_rmdir, METH_VARARGS|METH_KEYWORDS, os_rmdir__doc__},
-
-static PyObject *
-os_rmdir_impl(PyModuleDef *module, path_t *path, int dir_fd);
-
-static PyObject *
-os_rmdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("rmdir", "path", 0, 0);
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|$O&:rmdir", _keywords,
-        path_converter, &path, UNLINKAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_rmdir_impl(module, &path, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_rmdir_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=70b9fdbe3bee0591 input=38c8b375ca34a7e2]*/
+/*[clinic end generated code: output=cabadec80d5a77c7 input=38c8b375ca34a7e2]*/
 {
     int result;
 
@@ -5390,42 +4239,9 @@
 Execute the command in a subshell.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_system__doc__,
-"system($module, /, command)\n"
-"--\n"
-"\n"
-"Execute the command in a subshell.");
-
-#define OS_SYSTEM_METHODDEF    \
-    {"system", (PyCFunction)os_system, METH_VARARGS|METH_KEYWORDS, os_system__doc__},
-
-static long
-os_system_impl(PyModuleDef *module, Py_UNICODE *command);
-
-static PyObject *
-os_system(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"command", NULL};
-    Py_UNICODE *command;
-    long _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "u:system", _keywords,
-        &command))
-        goto exit;
-    _return_value = os_system_impl(module, command);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong(_return_value);
-
-exit:
-    return return_value;
-}
-
 static long
 os_system_impl(PyModuleDef *module, Py_UNICODE *command)
-/*[clinic end generated code: output=29fe699c0b2e9d38 input=303f5ce97df606b0]*/
+/*[clinic end generated code: output=4c3bd5abcd9c29e7 input=303f5ce97df606b0]*/
 {
     long result;
     Py_BEGIN_ALLOW_THREADS
@@ -5442,45 +4258,9 @@
 Execute the command in a subshell.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_system__doc__,
-"system($module, /, command)\n"
-"--\n"
-"\n"
-"Execute the command in a subshell.");
-
-#define OS_SYSTEM_METHODDEF    \
-    {"system", (PyCFunction)os_system, METH_VARARGS|METH_KEYWORDS, os_system__doc__},
-
-static long
-os_system_impl(PyModuleDef *module, PyObject *command);
-
-static PyObject *
-os_system(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"command", NULL};
-    PyObject *command = NULL;
-    long _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:system", _keywords,
-        PyUnicode_FSConverter, &command))
-        goto exit;
-    _return_value = os_system_impl(module, command);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong(_return_value);
-
-exit:
-    /* Cleanup for command */
-    Py_XDECREF(command);
-
-    return return_value;
-}
-
 static long
 os_system_impl(PyModuleDef *module, PyObject *command)
-/*[clinic end generated code: output=5be9f3c40ead3bad input=86a58554ba6094af]*/
+/*[clinic end generated code: output=800f775e10b7be55 input=86a58554ba6094af]*/
 {
     long result;
     char *bytes = PyBytes_AsString(command);
@@ -5502,37 +4282,9 @@
 Set the current numeric umask and return the previous umask.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_umask__doc__,
-"umask($module, mask, /)\n"
-"--\n"
-"\n"
-"Set the current numeric umask and return the previous umask.");
-
-#define OS_UMASK_METHODDEF    \
-    {"umask", (PyCFunction)os_umask, METH_VARARGS, os_umask__doc__},
-
-static PyObject *
-os_umask_impl(PyModuleDef *module, int mask);
-
-static PyObject *
-os_umask(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int mask;
-
-    if (!PyArg_ParseTuple(args,
-        "i:umask",
-        &mask))
-        goto exit;
-    return_value = os_umask_impl(module, mask);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_umask_impl(PyModuleDef *module, int mask)
-/*[clinic end generated code: output=90048b39d2d4a961 input=ab6bfd9b24d8a7e8]*/
+/*[clinic end generated code: output=9e1fe3c9f14d6a05 input=ab6bfd9b24d8a7e8]*/
 {
     int i = (int)umask(mask);
     if (i < 0)
@@ -5596,47 +4348,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_unlink__doc__,
-"unlink($module, /, path, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Remove a file (same as remove()).\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_UNLINK_METHODDEF    \
-    {"unlink", (PyCFunction)os_unlink, METH_VARARGS|METH_KEYWORDS, os_unlink__doc__},
-
-static PyObject *
-os_unlink_impl(PyModuleDef *module, path_t *path, int dir_fd);
-
-static PyObject *
-os_unlink(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("unlink", "path", 0, 0);
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|$O&:unlink", _keywords,
-        path_converter, &path, UNLINKAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_unlink_impl(module, &path, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_unlink_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=59a6e66d67ff2e75 input=d7bcde2b1b2a2552]*/
+/*[clinic end generated code: output=474afd5cd09b237e input=d7bcde2b1b2a2552]*/
 {
     int result;
 
@@ -5675,47 +4389,9 @@
   If it is unavailable, using it will raise a NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_remove__doc__,
-"remove($module, /, path, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Remove a file (same as unlink()).\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_REMOVE_METHODDEF    \
-    {"remove", (PyCFunction)os_remove, METH_VARARGS|METH_KEYWORDS, os_remove__doc__},
-
-static PyObject *
-os_remove_impl(PyModuleDef *module, path_t *path, int dir_fd);
-
-static PyObject *
-os_remove(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("remove", "path", 0, 0);
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|$O&:remove", _keywords,
-        path_converter, &path, UNLINKAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_remove_impl(module, &path, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_remove_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=cb170cf1e195b8ed input=e05c5ab55cd30983]*/
+/*[clinic end generated code: output=d0d5149e64832b9e input=e05c5ab55cd30983]*/
 {
     return os_unlink_impl(module, path, dir_fd);
 }
@@ -5759,30 +4435,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_uname__doc__,
-"uname($module, /)\n"
-"--\n"
-"\n"
-"Return an object identifying the current operating system.\n"
-"\n"
-"The object behaves like a named tuple with the following fields:\n"
-"  (sysname, nodename, release, version, machine)");
-
-#define OS_UNAME_METHODDEF    \
-    {"uname", (PyCFunction)os_uname, METH_NOARGS, os_uname__doc__},
-
-static PyObject *
-os_uname_impl(PyModuleDef *module);
-
-static PyObject *
-os_uname(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_uname_impl(module);
-}
-
 static PyObject *
 os_uname_impl(PyModuleDef *module)
-/*[clinic end generated code: output=459a86521ff5041c input=e68bd246db3043ed]*/
+/*[clinic end generated code: output=01e1421b757e753f input=e68bd246db3043ed]*/
 {
     struct utsname u;
     int res;
@@ -6034,68 +4689,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_utime__doc__,
-"utime($module, /, path, times=None, *, ns=None, dir_fd=None,\n"
-"      follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Set the access and modified time of path.\n"
-"\n"
-"path may always be specified as a string.\n"
-"On some platforms, path may also be specified as an open file descriptor.\n"
-"  If this functionality is unavailable, using it raises an exception.\n"
-"\n"
-"If times is not None, it must be a tuple (atime, mtime);\n"
-"    atime and mtime should be expressed as float seconds since the epoch.\n"
-"If ns is not None, it must be a tuple (atime_ns, mtime_ns);\n"
-"    atime_ns and mtime_ns should be expressed as integer nanoseconds\n"
-"    since the epoch.\n"
-"If both times and ns are None, utime uses the current time.\n"
-"Specifying tuples for both times and ns is an error.\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, utime will modify the symbolic link itself instead of the file the\n"
-"  link points to.\n"
-"It is an error to use dir_fd or follow_symlinks when specifying path\n"
-"  as an open file descriptor.\n"
-"dir_fd and follow_symlinks may not be available on your platform.\n"
-"  If they are unavailable, using them will raise a NotImplementedError.");
-
-#define OS_UTIME_METHODDEF    \
-    {"utime", (PyCFunction)os_utime, METH_VARARGS|METH_KEYWORDS, os_utime__doc__},
-
-static PyObject *
-os_utime_impl(PyModuleDef *module, path_t *path, PyObject *times, PyObject *ns, int dir_fd, int follow_symlinks);
-
-static PyObject *
-os_utime(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "times", "ns", "dir_fd", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("utime", "path", 0, PATH_UTIME_HAVE_FD);
-    PyObject *times = NULL;
-    PyObject *ns = NULL;
-    int dir_fd = DEFAULT_DIR_FD;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|O$OO&p:utime", _keywords,
-        path_converter, &path, &times, &ns, FUTIMENSAT_DIR_FD_CONVERTER, &dir_fd, &follow_symlinks))
-        goto exit;
-    return_value = os_utime_impl(module, &path, times, ns, dir_fd, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_utime_impl(PyModuleDef *module, path_t *path, PyObject *times, PyObject *ns, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=891489c35cc68c5d input=1f18c17d5941aa82]*/
+/*[clinic end generated code: output=c52d8fd0d1067f0b input=1f18c17d5941aa82]*/
 {
 #ifdef MS_WINDOWS
     HANDLE hFile;
@@ -6262,38 +4858,9 @@
 Exit to the system with specified status, without normal exit processing.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os__exit__doc__,
-"_exit($module, /, status)\n"
-"--\n"
-"\n"
-"Exit to the system with specified status, without normal exit processing.");
-
-#define OS__EXIT_METHODDEF    \
-    {"_exit", (PyCFunction)os__exit, METH_VARARGS|METH_KEYWORDS, os__exit__doc__},
-
-static PyObject *
-os__exit_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os__exit(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:_exit", _keywords,
-        &status))
-        goto exit;
-    return_value = os__exit_impl(module, status);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os__exit_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=4f9858c4cc2dcb89 input=5e6d57556b0c4a62]*/
+/*[clinic end generated code: output=472a3cbaf68f3621 input=5e6d57556b0c4a62]*/
 {
     _exit(status);
     return NULL; /* Make gcc -Wall happy */
@@ -6447,46 +5014,9 @@
 Execute an executable path with arguments, replacing current process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_execv__doc__,
-"execv($module, path, argv, /)\n"
-"--\n"
-"\n"
-"Execute an executable path with arguments, replacing current process.\n"
-"\n"
-"  path\n"
-"    Path of executable file.\n"
-"  argv\n"
-"    Tuple or list of strings.");
-
-#define OS_EXECV_METHODDEF    \
-    {"execv", (PyCFunction)os_execv, METH_VARARGS, os_execv__doc__},
-
-static PyObject *
-os_execv_impl(PyModuleDef *module, PyObject *path, PyObject *argv);
-
-static PyObject *
-os_execv(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *path = NULL;
-    PyObject *argv;
-
-    if (!PyArg_ParseTuple(args,
-        "O&O:execv",
-        PyUnicode_FSConverter, &path, &argv))
-        goto exit;
-    return_value = os_execv_impl(module, path, argv);
-
-exit:
-    /* Cleanup for path */
-    Py_XDECREF(path);
-
-    return return_value;
-}
-
 static PyObject *
 os_execv_impl(PyModuleDef *module, PyObject *path, PyObject *argv)
-/*[clinic end generated code: output=b0f5f2caa6097edc input=96041559925e5229]*/
+/*[clinic end generated code: output=9221f08143146fff input=96041559925e5229]*/
 {
     char *path_char;
     char **argvlist;
@@ -6534,50 +5064,9 @@
 Execute an executable path with arguments, replacing current process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_execve__doc__,
-"execve($module, /, path, argv, env)\n"
-"--\n"
-"\n"
-"Execute an executable path with arguments, replacing current process.\n"
-"\n"
-"  path\n"
-"    Path of executable file.\n"
-"  argv\n"
-"    Tuple or list of strings.\n"
-"  env\n"
-"    Dictionary of strings mapping to strings.");
-
-#define OS_EXECVE_METHODDEF    \
-    {"execve", (PyCFunction)os_execve, METH_VARARGS|METH_KEYWORDS, os_execve__doc__},
-
-static PyObject *
-os_execve_impl(PyModuleDef *module, path_t *path, PyObject *argv, PyObject *env);
-
-static PyObject *
-os_execve(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "argv", "env", NULL};
-    path_t path = PATH_T_INITIALIZE("execve", "path", 0, PATH_HAVE_FEXECVE);
-    PyObject *argv;
-    PyObject *env;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&OO:execve", _keywords,
-        path_converter, &path, &argv, &env))
-        goto exit;
-    return_value = os_execve_impl(module, &path, argv, env);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_execve_impl(PyModuleDef *module, path_t *path, PyObject *argv, PyObject *env)
-/*[clinic end generated code: output=fb283760f5d15ab7 input=626804fa092606d9]*/
+/*[clinic end generated code: output=7758d4f230d8aac6 input=626804fa092606d9]*/
 {
     char **argvlist = NULL;
     char **envlist;
@@ -6645,49 +5134,9 @@
 Execute the program specified by path in a new process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_spawnv__doc__,
-"spawnv($module, mode, path, argv, /)\n"
-"--\n"
-"\n"
-"Execute the program specified by path in a new process.\n"
-"\n"
-"  mode\n"
-"    Mode of process creation.\n"
-"  path\n"
-"    Path of executable file.\n"
-"  argv\n"
-"    Tuple or list of strings.");
-
-#define OS_SPAWNV_METHODDEF    \
-    {"spawnv", (PyCFunction)os_spawnv, METH_VARARGS, os_spawnv__doc__},
-
-static PyObject *
-os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv);
-
-static PyObject *
-os_spawnv(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int mode;
-    PyObject *path = NULL;
-    PyObject *argv;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&O:spawnv",
-        &mode, PyUnicode_FSConverter, &path, &argv))
-        goto exit;
-    return_value = os_spawnv_impl(module, mode, path, argv);
-
-exit:
-    /* Cleanup for path */
-    Py_XDECREF(path);
-
-    return return_value;
-}
-
 static PyObject *
 os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv)
-/*[clinic end generated code: output=dfee6be062e780e3 input=042c91dfc1e6debc]*/
+/*[clinic end generated code: output=140a7945484c8cc5 input=042c91dfc1e6debc]*/
 {
     char *path_char;
     char **argvlist;
@@ -6762,52 +5211,9 @@
 Execute the program specified by path in a new process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_spawnve__doc__,
-"spawnve($module, mode, path, argv, env, /)\n"
-"--\n"
-"\n"
-"Execute the program specified by path in a new process.\n"
-"\n"
-"  mode\n"
-"    Mode of process creation.\n"
-"  path\n"
-"    Path of executable file.\n"
-"  argv\n"
-"    Tuple or list of strings.\n"
-"  env\n"
-"    Dictionary of strings mapping to strings.");
-
-#define OS_SPAWNVE_METHODDEF    \
-    {"spawnve", (PyCFunction)os_spawnve, METH_VARARGS, os_spawnve__doc__},
-
-static PyObject *
-os_spawnve_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv, PyObject *env);
-
-static PyObject *
-os_spawnve(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int mode;
-    PyObject *path = NULL;
-    PyObject *argv;
-    PyObject *env;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&OO:spawnve",
-        &mode, PyUnicode_FSConverter, &path, &argv, &env))
-        goto exit;
-    return_value = os_spawnve_impl(module, mode, path, argv, env);
-
-exit:
-    /* Cleanup for path */
-    Py_XDECREF(path);
-
-    return return_value;
-}
-
 static PyObject *
 os_spawnve_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv, PyObject *env)
-/*[clinic end generated code: output=6f7df38473f63c7c input=02362fd937963f8f]*/
+/*[clinic end generated code: output=1c52955789461be8 input=02362fd937963f8f]*/
 {
     char *path_char;
     char **argvlist;
@@ -6895,29 +5301,9 @@
 Return 0 to child process and PID of child to parent process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fork1__doc__,
-"fork1($module, /)\n"
-"--\n"
-"\n"
-"Fork a child process with a single multiplexed (i.e., not bound) thread.\n"
-"\n"
-"Return 0 to child process and PID of child to parent process.");
-
-#define OS_FORK1_METHODDEF    \
-    {"fork1", (PyCFunction)os_fork1, METH_NOARGS, os_fork1__doc__},
-
-static PyObject *
-os_fork1_impl(PyModuleDef *module);
-
-static PyObject *
-os_fork1(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_fork1_impl(module);
-}
-
 static PyObject *
 os_fork1_impl(PyModuleDef *module)
-/*[clinic end generated code: output=fa04088d6bc02efa input=12db02167893926e]*/
+/*[clinic end generated code: output=e27b4f66419c9dcf input=12db02167893926e]*/
 {
     pid_t pid;
     int result = 0;
@@ -6952,29 +5338,9 @@
 Return 0 to child process and PID of child to parent process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fork__doc__,
-"fork($module, /)\n"
-"--\n"
-"\n"
-"Fork a child process.\n"
-"\n"
-"Return 0 to child process and PID of child to parent process.");
-
-#define OS_FORK_METHODDEF    \
-    {"fork", (PyCFunction)os_fork, METH_NOARGS, os_fork__doc__},
-
-static PyObject *
-os_fork_impl(PyModuleDef *module);
-
-static PyObject *
-os_fork(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_fork_impl(module);
-}
-
 static PyObject *
 os_fork_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b3c8e6bdc11eedc6 input=13c956413110eeaa]*/
+/*[clinic end generated code: output=898b1ecd3498ba12 input=13c956413110eeaa]*/
 {
     pid_t pid;
     int result = 0;
@@ -7010,38 +5376,9 @@
 Get the maximum scheduling priority for policy.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_get_priority_max__doc__,
-"sched_get_priority_max($module, /, policy)\n"
-"--\n"
-"\n"
-"Get the maximum scheduling priority for policy.");
-
-#define OS_SCHED_GET_PRIORITY_MAX_METHODDEF    \
-    {"sched_get_priority_max", (PyCFunction)os_sched_get_priority_max, METH_VARARGS|METH_KEYWORDS, os_sched_get_priority_max__doc__},
-
-static PyObject *
-os_sched_get_priority_max_impl(PyModuleDef *module, int policy);
-
-static PyObject *
-os_sched_get_priority_max(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"policy", NULL};
-    int policy;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:sched_get_priority_max", _keywords,
-        &policy))
-        goto exit;
-    return_value = os_sched_get_priority_max_impl(module, policy);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_get_priority_max_impl(PyModuleDef *module, int policy)
-/*[clinic end generated code: output=a580a52f25238c1f input=2097b7998eca6874]*/
+/*[clinic end generated code: output=a6a30fa5071f2d81 input=2097b7998eca6874]*/
 {
     int max;
 
@@ -7060,38 +5397,9 @@
 Get the minimum scheduling priority for policy.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_get_priority_min__doc__,
-"sched_get_priority_min($module, /, policy)\n"
-"--\n"
-"\n"
-"Get the minimum scheduling priority for policy.");
-
-#define OS_SCHED_GET_PRIORITY_MIN_METHODDEF    \
-    {"sched_get_priority_min", (PyCFunction)os_sched_get_priority_min, METH_VARARGS|METH_KEYWORDS, os_sched_get_priority_min__doc__},
-
-static PyObject *
-os_sched_get_priority_min_impl(PyModuleDef *module, int policy);
-
-static PyObject *
-os_sched_get_priority_min(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"policy", NULL};
-    int policy;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:sched_get_priority_min", _keywords,
-        &policy))
-        goto exit;
-    return_value = os_sched_get_priority_min_impl(module, policy);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_get_priority_min_impl(PyModuleDef *module, int policy)
-/*[clinic end generated code: output=bad8ba10e7d0e977 input=21bc8fa0d70983bf]*/
+/*[clinic end generated code: output=5ca3ed6bc43e9b20 input=21bc8fa0d70983bf]*/
 {
     int min = sched_get_priority_min(policy);
     if (min < 0)
@@ -7112,39 +5420,9 @@
 Passing 0 for pid returns the scheduling policy for the calling process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_getscheduler__doc__,
-"sched_getscheduler($module, pid, /)\n"
-"--\n"
-"\n"
-"Get the scheduling policy for the process identifiedy by pid.\n"
-"\n"
-"Passing 0 for pid returns the scheduling policy for the calling process.");
-
-#define OS_SCHED_GETSCHEDULER_METHODDEF    \
-    {"sched_getscheduler", (PyCFunction)os_sched_getscheduler, METH_VARARGS, os_sched_getscheduler__doc__},
-
-static PyObject *
-os_sched_getscheduler_impl(PyModuleDef *module, pid_t pid);
-
-static PyObject *
-os_sched_getscheduler(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID ":sched_getscheduler",
-        &pid))
-        goto exit;
-    return_value = os_sched_getscheduler_impl(module, pid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_getscheduler_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=e0d6244207b1d828 input=5f14cfd1f189e1a0]*/
+/*[clinic end generated code: output=8cd63c15caf54fa9 input=5f14cfd1f189e1a0]*/
 {
     int policy;
 
@@ -7169,38 +5447,9 @@
 Current has only one field: sched_priority");
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_param__doc__,
-"sched_param(sched_priority)\n"
-"--\n"
-"\n"
-"Current has only one field: sched_priority\");\n"
-"\n"
-"  sched_priority\n"
-"    A scheduling parameter.");
-
-static PyObject *
-os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority);
-
-static PyObject *
-os_sched_param(PyTypeObject *type, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"sched_priority", NULL};
-    PyObject *sched_priority;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O:sched_param", _keywords,
-        &sched_priority))
-        goto exit;
-    return_value = os_sched_param_impl(type, sched_priority);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
-/*[clinic end generated code: output=d3791e345f7fe573 input=73a4c22f7071fc62]*/
+/*[clinic end generated code: output=48f4067d60f48c13 input=73a4c22f7071fc62]*/
 {
     PyObject *res;
 
@@ -7213,6 +5462,8 @@
 }
 
 
+PyDoc_VAR(os_sched_param__doc__);
+
 static PyStructSequence_Field sched_param_fields[] = {
     {"sched_priority", "the scheduling priority"},
     {0}
@@ -7262,42 +5513,9 @@
 param is an instance of sched_param.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_setscheduler__doc__,
-"sched_setscheduler($module, pid, policy, param, /)\n"
-"--\n"
-"\n"
-"Set the scheduling policy for the process identified by pid.\n"
-"\n"
-"If pid is 0, the calling process is changed.\n"
-"param is an instance of sched_param.");
-
-#define OS_SCHED_SETSCHEDULER_METHODDEF    \
-    {"sched_setscheduler", (PyCFunction)os_sched_setscheduler, METH_VARARGS, os_sched_setscheduler__doc__},
-
-static PyObject *
-os_sched_setscheduler_impl(PyModuleDef *module, pid_t pid, int policy, struct sched_param *param);
-
-static PyObject *
-os_sched_setscheduler(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    int policy;
-    struct sched_param param;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "iO&:sched_setscheduler",
-        &pid, &policy, convert_sched_param, &param))
-        goto exit;
-    return_value = os_sched_setscheduler_impl(module, pid, policy, &param);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_setscheduler_impl(PyModuleDef *module, pid_t pid, int policy, struct sched_param *param)
-/*[clinic end generated code: output=36abdb73f81c224f input=c581f9469a5327dd]*/
+/*[clinic end generated code: output=97f40f8384e554b0 input=c581f9469a5327dd]*/
 {
     /*
     ** sched_setscheduler() returns 0 in Linux, but the previous
@@ -7323,40 +5541,9 @@
 Return value is an instance of sched_param.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_getparam__doc__,
-"sched_getparam($module, pid, /)\n"
-"--\n"
-"\n"
-"Returns scheduling parameters for the process identified by pid.\n"
-"\n"
-"If pid is 0, returns parameters for the calling process.\n"
-"Return value is an instance of sched_param.");
-
-#define OS_SCHED_GETPARAM_METHODDEF    \
-    {"sched_getparam", (PyCFunction)os_sched_getparam, METH_VARARGS, os_sched_getparam__doc__},
-
-static PyObject *
-os_sched_getparam_impl(PyModuleDef *module, pid_t pid);
-
-static PyObject *
-os_sched_getparam(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID ":sched_getparam",
-        &pid))
-        goto exit;
-    return_value = os_sched_getparam_impl(module, pid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_getparam_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=b33acc8db004a8c9 input=18a1ef9c2efae296]*/
+/*[clinic end generated code: output=f42c5bd2604ecd08 input=18a1ef9c2efae296]*/
 {
     struct sched_param param;
     PyObject *result;
@@ -7389,41 +5576,9 @@
 param should be an instance of sched_param.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_setparam__doc__,
-"sched_setparam($module, pid, param, /)\n"
-"--\n"
-"\n"
-"Set scheduling parameters for the process identified by pid.\n"
-"\n"
-"If pid is 0, sets parameters for the calling process.\n"
-"param should be an instance of sched_param.");
-
-#define OS_SCHED_SETPARAM_METHODDEF    \
-    {"sched_setparam", (PyCFunction)os_sched_setparam, METH_VARARGS, os_sched_setparam__doc__},
-
-static PyObject *
-os_sched_setparam_impl(PyModuleDef *module, pid_t pid, struct sched_param *param);
-
-static PyObject *
-os_sched_setparam(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    struct sched_param param;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "O&:sched_setparam",
-        &pid, convert_sched_param, &param))
-        goto exit;
-    return_value = os_sched_setparam_impl(module, pid, &param);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_setparam_impl(PyModuleDef *module, pid_t pid, struct sched_param *param)
-/*[clinic end generated code: output=488bdf5bcbe0d4e8 input=6b8d6dfcecdc21bd]*/
+/*[clinic end generated code: output=c6560b34395bb343 input=6b8d6dfcecdc21bd]*/
 {
     if (sched_setparam(pid, param))
         return posix_error();
@@ -7443,43 +5598,9 @@
 Value returned is a float.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_rr_get_interval__doc__,
-"sched_rr_get_interval($module, pid, /)\n"
-"--\n"
-"\n"
-"Return the round-robin quantum for the process identified by pid, in seconds.\n"
-"\n"
-"Value returned is a float.");
-
-#define OS_SCHED_RR_GET_INTERVAL_METHODDEF    \
-    {"sched_rr_get_interval", (PyCFunction)os_sched_rr_get_interval, METH_VARARGS, os_sched_rr_get_interval__doc__},
-
-static double
-os_sched_rr_get_interval_impl(PyModuleDef *module, pid_t pid);
-
-static PyObject *
-os_sched_rr_get_interval(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    double _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID ":sched_rr_get_interval",
-        &pid))
-        goto exit;
-    _return_value = os_sched_rr_get_interval_impl(module, pid);
-    if ((_return_value == -1.0) && PyErr_Occurred())
-        goto exit;
-    return_value = PyFloat_FromDouble(_return_value);
-
-exit:
-    return return_value;
-}
-
 static double
 os_sched_rr_get_interval_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=5b3b8d1f27fb2c0a input=2a973da15cca6fae]*/
+/*[clinic end generated code: output=7adc137a86dea581 input=2a973da15cca6fae]*/
 {
     struct timespec interval;
     if (sched_rr_get_interval(pid, &interval)) {
@@ -7497,27 +5618,9 @@
 Voluntarily relinquish the CPU.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_yield__doc__,
-"sched_yield($module, /)\n"
-"--\n"
-"\n"
-"Voluntarily relinquish the CPU.");
-
-#define OS_SCHED_YIELD_METHODDEF    \
-    {"sched_yield", (PyCFunction)os_sched_yield, METH_NOARGS, os_sched_yield__doc__},
-
-static PyObject *
-os_sched_yield_impl(PyModuleDef *module);
-
-static PyObject *
-os_sched_yield(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_sched_yield_impl(module);
-}
-
 static PyObject *
 os_sched_yield_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9d2e5f29f1370324 input=e54d6f98189391d4]*/
+/*[clinic end generated code: output=d7bd51869c4cb6a8 input=e54d6f98189391d4]*/
 {
     if (sched_yield())
         return posix_error();
@@ -7539,40 +5642,9 @@
 mask should be an iterable of integers identifying CPUs.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_setaffinity__doc__,
-"sched_setaffinity($module, pid, mask, /)\n"
-"--\n"
-"\n"
-"Set the CPU affinity of the process identified by pid to mask.\n"
-"\n"
-"mask should be an iterable of integers identifying CPUs.");
-
-#define OS_SCHED_SETAFFINITY_METHODDEF    \
-    {"sched_setaffinity", (PyCFunction)os_sched_setaffinity, METH_VARARGS, os_sched_setaffinity__doc__},
-
-static PyObject *
-os_sched_setaffinity_impl(PyModuleDef *module, pid_t pid, PyObject *mask);
-
-static PyObject *
-os_sched_setaffinity(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    PyObject *mask;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "O:sched_setaffinity",
-        &pid, &mask))
-        goto exit;
-    return_value = os_sched_setaffinity_impl(module, pid, mask);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_setaffinity_impl(PyModuleDef *module, pid_t pid, PyObject *mask)
-/*[clinic end generated code: output=5199929738130196 input=a0791a597c7085ba]*/
+/*[clinic end generated code: output=582bcbf40d3253a9 input=a0791a597c7085ba]*/
 {
     int ncpus;
     size_t setsize;
@@ -7666,39 +5738,9 @@
 The affinity is returned as a set of CPU identifiers.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sched_getaffinity__doc__,
-"sched_getaffinity($module, pid, /)\n"
-"--\n"
-"\n"
-"Return the affinity of the process identified by pid.\n"
-"\n"
-"The affinity is returned as a set of CPU identifiers.");
-
-#define OS_SCHED_GETAFFINITY_METHODDEF    \
-    {"sched_getaffinity", (PyCFunction)os_sched_getaffinity, METH_VARARGS, os_sched_getaffinity__doc__},
-
-static PyObject *
-os_sched_getaffinity_impl(PyModuleDef *module, pid_t pid);
-
-static PyObject *
-os_sched_getaffinity(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID ":sched_getaffinity",
-        &pid))
-        goto exit;
-    return_value = os_sched_getaffinity_impl(module, pid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_sched_getaffinity_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=7b273b0fca9830f0 input=eaf161936874b8a1]*/
+/*[clinic end generated code: output=b431a8f310e369e7 input=eaf161936874b8a1]*/
 {
     int cpu, ncpus, count;
     size_t setsize;
@@ -7754,46 +5796,6 @@
 
 #endif /* HAVE_SCHED_H */
 
-#ifndef OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-#define OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-#endif  /* OS_SCHED_GET_PRIORITY_MAX_METHODDEF */
-
-#ifndef OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-#define OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-#endif  /* OS_SCHED_GET_PRIORITY_MIN_METHODDEF */
-
-#ifndef OS_SCHED_GETSCHEDULER_METHODDEF
-#define OS_SCHED_GETSCHEDULER_METHODDEF
-#endif  /* OS_SCHED_GETSCHEDULER_METHODDEF */
-
-#ifndef OS_SCHED_SETSCHEDULER_METHODDEF
-#define OS_SCHED_SETSCHEDULER_METHODDEF
-#endif  /* OS_SCHED_SETSCHEDULER_METHODDEF */
-
-#ifndef OS_SCHED_GETPARAM_METHODDEF
-#define OS_SCHED_GETPARAM_METHODDEF
-#endif  /* OS_SCHED_GETPARAM_METHODDEF */
-
-#ifndef OS_SCHED_SETPARAM_METHODDEF
-#define OS_SCHED_SETPARAM_METHODDEF
-#endif  /* OS_SCHED_SETPARAM_METHODDEF */
-
-#ifndef OS_SCHED_RR_GET_INTERVAL_METHODDEF
-#define OS_SCHED_RR_GET_INTERVAL_METHODDEF
-#endif  /* OS_SCHED_RR_GET_INTERVAL_METHODDEF */
-
-#ifndef OS_SCHED_YIELD_METHODDEF
-#define OS_SCHED_YIELD_METHODDEF
-#endif  /* OS_SCHED_YIELD_METHODDEF */
-
-#ifndef OS_SCHED_SETAFFINITY_METHODDEF
-#define OS_SCHED_SETAFFINITY_METHODDEF
-#endif  /* OS_SCHED_SETAFFINITY_METHODDEF */
-
-#ifndef OS_SCHED_GETAFFINITY_METHODDEF
-#define OS_SCHED_GETAFFINITY_METHODDEF
-#endif  /* OS_SCHED_GETAFFINITY_METHODDEF */
-
 
 /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
 /* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
@@ -7832,30 +5834,9 @@
 for both the master and slave ends.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_openpty__doc__,
-"openpty($module, /)\n"
-"--\n"
-"\n"
-"Open a pseudo-terminal.\n"
-"\n"
-"Return a tuple of (master_fd, slave_fd) containing open file descriptors\n"
-"for both the master and slave ends.");
-
-#define OS_OPENPTY_METHODDEF    \
-    {"openpty", (PyCFunction)os_openpty, METH_NOARGS, os_openpty__doc__},
-
-static PyObject *
-os_openpty_impl(PyModuleDef *module);
-
-static PyObject *
-os_openpty(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_openpty_impl(module);
-}
-
 static PyObject *
 os_openpty_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b12d3c1735468464 input=f3d99fd99e762907]*/
+/*[clinic end generated code: output=358e571c1ba135ee input=f3d99fd99e762907]*/
 {
     int master_fd = -1, slave_fd = -1;
 #ifndef HAVE_OPENPTY
@@ -7955,32 +5936,9 @@
 To both, return fd of newly opened pseudo-terminal.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_forkpty__doc__,
-"forkpty($module, /)\n"
-"--\n"
-"\n"
-"Fork a new process with a new pseudo-terminal as controlling tty.\n"
-"\n"
-"Returns a tuple of (pid, master_fd).\n"
-"Like fork(), return pid of 0 to the child process,\n"
-"and pid of child to the parent process.\n"
-"To both, return fd of newly opened pseudo-terminal.");
-
-#define OS_FORKPTY_METHODDEF    \
-    {"forkpty", (PyCFunction)os_forkpty, METH_NOARGS, os_forkpty__doc__},
-
-static PyObject *
-os_forkpty_impl(PyModuleDef *module);
-
-static PyObject *
-os_forkpty(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_forkpty_impl(module);
-}
-
 static PyObject *
 os_forkpty_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d4f82958d2ed5cad input=f1f7f4bae3966010]*/
+/*[clinic end generated code: output=a11b8391dce3cb57 input=f1f7f4bae3966010]*/
 {
     int master_fd = -1, result = 0;
     pid_t pid;
@@ -8014,27 +5972,9 @@
 Return the current process's effective group id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getegid__doc__,
-"getegid($module, /)\n"
-"--\n"
-"\n"
-"Return the current process\'s effective group id.");
-
-#define OS_GETEGID_METHODDEF    \
-    {"getegid", (PyCFunction)os_getegid, METH_NOARGS, os_getegid__doc__},
-
-static PyObject *
-os_getegid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getegid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getegid_impl(module);
-}
-
 static PyObject *
 os_getegid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=fd12c346fa41cccb input=1596f79ad1107d5d]*/
+/*[clinic end generated code: output=90f433a8c0b1d919 input=1596f79ad1107d5d]*/
 {
     return _PyLong_FromGid(getegid());
 }
@@ -8048,27 +5988,9 @@
 Return the current process's effective user id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_geteuid__doc__,
-"geteuid($module, /)\n"
-"--\n"
-"\n"
-"Return the current process\'s effective user id.");
-
-#define OS_GETEUID_METHODDEF    \
-    {"geteuid", (PyCFunction)os_geteuid, METH_NOARGS, os_geteuid__doc__},
-
-static PyObject *
-os_geteuid_impl(PyModuleDef *module);
-
-static PyObject *
-os_geteuid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_geteuid_impl(module);
-}
-
 static PyObject *
 os_geteuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=03d98e07f4bc03d4 input=4644c662d3bd9f19]*/
+/*[clinic end generated code: output=1a532c4a66874357 input=4644c662d3bd9f19]*/
 {
     return _PyLong_FromUid(geteuid());
 }
@@ -8082,27 +6004,9 @@
 Return the current process's group id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getgid__doc__,
-"getgid($module, /)\n"
-"--\n"
-"\n"
-"Return the current process\'s group id.");
-
-#define OS_GETGID_METHODDEF    \
-    {"getgid", (PyCFunction)os_getgid, METH_NOARGS, os_getgid__doc__},
-
-static PyObject *
-os_getgid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getgid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getgid_impl(module);
-}
-
 static PyObject *
 os_getgid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=07b0356121b8098d input=58796344cd87c0f6]*/
+/*[clinic end generated code: output=91a22021b74ea46b input=58796344cd87c0f6]*/
 {
     return _PyLong_FromGid(getgid());
 }
@@ -8115,27 +6019,9 @@
 Return the current process id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getpid__doc__,
-"getpid($module, /)\n"
-"--\n"
-"\n"
-"Return the current process id.");
-
-#define OS_GETPID_METHODDEF    \
-    {"getpid", (PyCFunction)os_getpid, METH_NOARGS, os_getpid__doc__},
-
-static PyObject *
-os_getpid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getpid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getpid_impl(module);
-}
-
 static PyObject *
 os_getpid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d63a01a3cebc573d input=5a9a00f0ab68aa00]*/
+/*[clinic end generated code: output=8fbf3a934ee09e62 input=5a9a00f0ab68aa00]*/
 {
     return PyLong_FromPid(getpid());
 }
@@ -8225,27 +6111,9 @@
 Return list of supplemental group IDs for the process.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getgroups__doc__,
-"getgroups($module, /)\n"
-"--\n"
-"\n"
-"Return list of supplemental group IDs for the process.");
-
-#define OS_GETGROUPS_METHODDEF    \
-    {"getgroups", (PyCFunction)os_getgroups, METH_NOARGS, os_getgroups__doc__},
-
-static PyObject *
-os_getgroups_impl(PyModuleDef *module);
-
-static PyObject *
-os_getgroups(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getgroups_impl(module);
-}
-
 static PyObject *
 os_getgroups_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d9a3559b2e6f4ab8 input=d3f109412e6a155c]*/
+/*[clinic end generated code: output=6e7c4fd2db6d5c60 input=d3f109412e6a155c]*/
 {
     PyObject *result = NULL;
 
@@ -8398,38 +6266,9 @@
 Call the system call getpgid(), and return the result.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getpgid__doc__,
-"getpgid($module, /, pid)\n"
-"--\n"
-"\n"
-"Call the system call getpgid(), and return the result.");
-
-#define OS_GETPGID_METHODDEF    \
-    {"getpgid", (PyCFunction)os_getpgid, METH_VARARGS|METH_KEYWORDS, os_getpgid__doc__},
-
-static PyObject *
-os_getpgid_impl(PyModuleDef *module, pid_t pid);
-
-static PyObject *
-os_getpgid(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"pid", NULL};
-    pid_t pid;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "" _Py_PARSE_PID ":getpgid", _keywords,
-        &pid))
-        goto exit;
-    return_value = os_getpgid_impl(module, pid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_getpgid_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=3db4ed686179160d input=39d710ae3baaf1c7]*/
+/*[clinic end generated code: output=70e713b4d54b7c61 input=39d710ae3baaf1c7]*/
 {
     pid_t pgid = getpgid(pid);
     if (pgid < 0)
@@ -8446,27 +6285,9 @@
 Return the current process group id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getpgrp__doc__,
-"getpgrp($module, /)\n"
-"--\n"
-"\n"
-"Return the current process group id.");
-
-#define OS_GETPGRP_METHODDEF    \
-    {"getpgrp", (PyCFunction)os_getpgrp, METH_NOARGS, os_getpgrp__doc__},
-
-static PyObject *
-os_getpgrp_impl(PyModuleDef *module);
-
-static PyObject *
-os_getpgrp(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getpgrp_impl(module);
-}
-
 static PyObject *
 os_getpgrp_impl(PyModuleDef *module)
-/*[clinic end generated code: output=3b0d3663ea054277 input=6846fb2bb9a3705e]*/
+/*[clinic end generated code: output=cf3403585846811f input=6846fb2bb9a3705e]*/
 {
 #ifdef GETPGRP_HAVE_ARG
     return PyLong_FromPid(getpgrp(0));
@@ -8484,27 +6305,9 @@
 Make the current process the leader of its process group.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setpgrp__doc__,
-"setpgrp($module, /)\n"
-"--\n"
-"\n"
-"Make the current process the leader of its process group.");
-
-#define OS_SETPGRP_METHODDEF    \
-    {"setpgrp", (PyCFunction)os_setpgrp, METH_NOARGS, os_setpgrp__doc__},
-
-static PyObject *
-os_setpgrp_impl(PyModuleDef *module);
-
-static PyObject *
-os_setpgrp(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_setpgrp_impl(module);
-}
-
 static PyObject *
 os_setpgrp_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8fbb0ee29ef6fb2d input=1f0619fcb5731e7e]*/
+/*[clinic end generated code: output=59650f55a963d7ac input=1f0619fcb5731e7e]*/
 {
 #ifdef SETPGRP_HAVE_ARG
     if (setpgrp(0, 0) < 0)
@@ -8571,30 +6374,9 @@
 return its id; others systems will return the id of the 'init' process (1).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getppid__doc__,
-"getppid($module, /)\n"
-"--\n"
-"\n"
-"Return the parent\'s process id.\n"
-"\n"
-"If the parent process has already exited, Windows machines will still\n"
-"return its id; others systems will return the id of the \'init\' process (1).");
-
-#define OS_GETPPID_METHODDEF    \
-    {"getppid", (PyCFunction)os_getppid, METH_NOARGS, os_getppid__doc__},
-
-static PyObject *
-os_getppid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getppid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getppid_impl(module);
-}
-
 static PyObject *
 os_getppid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9ff3b387781edf3a input=e637cb87539c030e]*/
+/*[clinic end generated code: output=4e49c8e7a8738cd2 input=e637cb87539c030e]*/
 {
 #ifdef MS_WINDOWS
     return win32_getppid();
@@ -8612,27 +6394,9 @@
 Return the actual login name.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getlogin__doc__,
-"getlogin($module, /)\n"
-"--\n"
-"\n"
-"Return the actual login name.");
-
-#define OS_GETLOGIN_METHODDEF    \
-    {"getlogin", (PyCFunction)os_getlogin, METH_NOARGS, os_getlogin__doc__},
-
-static PyObject *
-os_getlogin_impl(PyModuleDef *module);
-
-static PyObject *
-os_getlogin(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getlogin_impl(module);
-}
-
 static PyObject *
 os_getlogin_impl(PyModuleDef *module)
-/*[clinic end generated code: output=ab6211dab104cbb2 input=2a21ab1e917163df]*/
+/*[clinic end generated code: output=037ebdb3e4b5dac1 input=2a21ab1e917163df]*/
 {
     PyObject *result = NULL;
 #ifdef MS_WINDOWS
@@ -8673,27 +6437,9 @@
 Return the current process's user id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getuid__doc__,
-"getuid($module, /)\n"
-"--\n"
-"\n"
-"Return the current process\'s user id.");
-
-#define OS_GETUID_METHODDEF    \
-    {"getuid", (PyCFunction)os_getuid, METH_NOARGS, os_getuid__doc__},
-
-static PyObject *
-os_getuid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getuid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getuid_impl(module);
-}
-
 static PyObject *
 os_getuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=77e0dcf2e37d1e89 input=b53c8b35f110a516]*/
+/*[clinic end generated code: output=03a8b894cefb3fa5 input=b53c8b35f110a516]*/
 {
     return _PyLong_FromUid(getuid());
 }
@@ -8715,38 +6461,9 @@
 Kill a process with a signal.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_kill__doc__,
-"kill($module, pid, signal, /)\n"
-"--\n"
-"\n"
-"Kill a process with a signal.");
-
-#define OS_KILL_METHODDEF    \
-    {"kill", (PyCFunction)os_kill, METH_VARARGS, os_kill__doc__},
-
-static PyObject *
-os_kill_impl(PyModuleDef *module, pid_t pid, Py_ssize_t signal);
-
-static PyObject *
-os_kill(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    Py_ssize_t signal;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "n:kill",
-        &pid, &signal))
-        goto exit;
-    return_value = os_kill_impl(module, pid, signal);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_kill_impl(PyModuleDef *module, pid_t pid, Py_ssize_t signal)
-/*[clinic end generated code: output=2f5c77920ed575e6 input=61a36b86ca275ab9]*/
+/*[clinic end generated code: output=74f907dd00a83c26 input=61a36b86ca275ab9]*/
 #ifndef MS_WINDOWS
 {
     if (kill(pid, (int)signal) == -1)
@@ -8805,38 +6522,9 @@
 Kill a process group with a signal.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_killpg__doc__,
-"killpg($module, pgid, signal, /)\n"
-"--\n"
-"\n"
-"Kill a process group with a signal.");
-
-#define OS_KILLPG_METHODDEF    \
-    {"killpg", (PyCFunction)os_killpg, METH_VARARGS, os_killpg__doc__},
-
-static PyObject *
-os_killpg_impl(PyModuleDef *module, pid_t pgid, int signal);
-
-static PyObject *
-os_killpg(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pgid;
-    int signal;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "i:killpg",
-        &pgid, &signal))
-        goto exit;
-    return_value = os_killpg_impl(module, pgid, signal);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_killpg_impl(PyModuleDef *module, pid_t pgid, int signal)
-/*[clinic end generated code: output=0e05215d1c007e01 input=38b5449eb8faec19]*/
+/*[clinic end generated code: output=3434a766ef945f93 input=38b5449eb8faec19]*/
 {
     /* XXX some man pages make the `pgid` parameter an int, others
        a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
@@ -8862,37 +6550,9 @@
 Lock program segments into memory.");
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_plock__doc__,
-"plock($module, op, /)\n"
-"--\n"
-"\n"
-"Lock program segments into memory.\");");
-
-#define OS_PLOCK_METHODDEF    \
-    {"plock", (PyCFunction)os_plock, METH_VARARGS, os_plock__doc__},
-
-static PyObject *
-os_plock_impl(PyModuleDef *module, int op);
-
-static PyObject *
-os_plock(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int op;
-
-    if (!PyArg_ParseTuple(args,
-        "i:plock",
-        &op))
-        goto exit;
-    return_value = os_plock_impl(module, op);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_plock_impl(PyModuleDef *module, int op)
-/*[clinic end generated code: output=2744fe4b6e5f4dbc input=e6e5e348e1525f60]*/
+/*[clinic end generated code: output=5cb851f81b914984 input=e6e5e348e1525f60]*/
 {
     if (plock(op) == -1)
         return posix_error();
@@ -8911,37 +6571,9 @@
 Set the current process's user id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setuid__doc__,
-"setuid($module, uid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s user id.");
-
-#define OS_SETUID_METHODDEF    \
-    {"setuid", (PyCFunction)os_setuid, METH_VARARGS, os_setuid__doc__},
-
-static PyObject *
-os_setuid_impl(PyModuleDef *module, uid_t uid);
-
-static PyObject *
-os_setuid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    uid_t uid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:setuid",
-        _Py_Uid_Converter, &uid))
-        goto exit;
-    return_value = os_setuid_impl(module, uid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setuid_impl(PyModuleDef *module, uid_t uid)
-/*[clinic end generated code: output=aea344bc22ccf400 input=c921a3285aa22256]*/
+/*[clinic end generated code: output=941ea9a8d1e5d565 input=c921a3285aa22256]*/
 {
     if (setuid(uid) < 0)
         return posix_error();
@@ -8960,37 +6592,9 @@
 Set the current process's effective user id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_seteuid__doc__,
-"seteuid($module, euid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s effective user id.");
-
-#define OS_SETEUID_METHODDEF    \
-    {"seteuid", (PyCFunction)os_seteuid, METH_VARARGS, os_seteuid__doc__},
-
-static PyObject *
-os_seteuid_impl(PyModuleDef *module, uid_t euid);
-
-static PyObject *
-os_seteuid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    uid_t euid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:seteuid",
-        _Py_Uid_Converter, &euid))
-        goto exit;
-    return_value = os_seteuid_impl(module, euid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_seteuid_impl(PyModuleDef *module, uid_t euid)
-/*[clinic end generated code: output=6e824cce4f3b8a5d input=ba93d927e4781aa9]*/
+/*[clinic end generated code: output=66f4f6823a648d6d input=ba93d927e4781aa9]*/
 {
     if (seteuid(euid) < 0)
         return posix_error();
@@ -9009,37 +6613,9 @@
 Set the current process's effective group id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setegid__doc__,
-"setegid($module, egid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s effective group id.");
-
-#define OS_SETEGID_METHODDEF    \
-    {"setegid", (PyCFunction)os_setegid, METH_VARARGS, os_setegid__doc__},
-
-static PyObject *
-os_setegid_impl(PyModuleDef *module, gid_t egid);
-
-static PyObject *
-os_setegid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    gid_t egid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:setegid",
-        _Py_Gid_Converter, &egid))
-        goto exit;
-    return_value = os_setegid_impl(module, egid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setegid_impl(PyModuleDef *module, gid_t egid)
-/*[clinic end generated code: output=80a32263a4d56a9c input=4080526d0ccd6ce3]*/
+/*[clinic end generated code: output=ca094a69a081a60f input=4080526d0ccd6ce3]*/
 {
     if (setegid(egid) < 0)
         return posix_error();
@@ -9059,38 +6635,9 @@
 Set the current process's real and effective user ids.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setreuid__doc__,
-"setreuid($module, ruid, euid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s real and effective user ids.");
-
-#define OS_SETREUID_METHODDEF    \
-    {"setreuid", (PyCFunction)os_setreuid, METH_VARARGS, os_setreuid__doc__},
-
-static PyObject *
-os_setreuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid);
-
-static PyObject *
-os_setreuid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    uid_t ruid;
-    uid_t euid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&O&:setreuid",
-        _Py_Uid_Converter, &ruid, _Py_Uid_Converter, &euid))
-        goto exit;
-    return_value = os_setreuid_impl(module, ruid, euid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setreuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid)
-/*[clinic end generated code: output=d7f226f943dad739 input=0ca8978de663880c]*/
+/*[clinic end generated code: output=b2938c3e73d27ec7 input=0ca8978de663880c]*/
 {
     if (setreuid(ruid, euid) < 0) {
         return posix_error();
@@ -9113,38 +6660,9 @@
 Set the current process's real and effective group ids.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setregid__doc__,
-"setregid($module, rgid, egid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s real and effective group ids.");
-
-#define OS_SETREGID_METHODDEF    \
-    {"setregid", (PyCFunction)os_setregid, METH_VARARGS, os_setregid__doc__},
-
-static PyObject *
-os_setregid_impl(PyModuleDef *module, gid_t rgid, gid_t egid);
-
-static PyObject *
-os_setregid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    gid_t rgid;
-    gid_t egid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&O&:setregid",
-        _Py_Gid_Converter, &rgid, _Py_Gid_Converter, &egid))
-        goto exit;
-    return_value = os_setregid_impl(module, rgid, egid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setregid_impl(PyModuleDef *module, gid_t rgid, gid_t egid)
-/*[clinic end generated code: output=a82d9ab70f8e6562 input=c59499f72846db78]*/
+/*[clinic end generated code: output=db18f1839ababe3d input=c59499f72846db78]*/
 {
     if (setregid(rgid, egid) < 0)
         return posix_error();
@@ -9162,37 +6680,9 @@
 Set the current process's group id.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setgid__doc__,
-"setgid($module, gid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s group id.");
-
-#define OS_SETGID_METHODDEF    \
-    {"setgid", (PyCFunction)os_setgid, METH_VARARGS, os_setgid__doc__},
-
-static PyObject *
-os_setgid_impl(PyModuleDef *module, gid_t gid);
-
-static PyObject *
-os_setgid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    gid_t gid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:setgid",
-        _Py_Gid_Converter, &gid))
-        goto exit;
-    return_value = os_setgid_impl(module, gid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setgid_impl(PyModuleDef *module, gid_t gid)
-/*[clinic end generated code: output=08287886db435f23 input=27d30c4059045dc6]*/
+/*[clinic end generated code: output=756cb42c6abd9d87 input=27d30c4059045dc6]*/
 {
     if (setgid(gid) < 0)
         return posix_error();
@@ -9211,18 +6701,9 @@
 Set the groups of the current process to list.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setgroups__doc__,
-"setgroups($module, groups, /)\n"
-"--\n"
-"\n"
-"Set the groups of the current process to list.");
-
-#define OS_SETGROUPS_METHODDEF    \
-    {"setgroups", (PyCFunction)os_setgroups, METH_O, os_setgroups__doc__},
-
 static PyObject *
 os_setgroups(PyModuleDef *module, PyObject *groups)
-/*[clinic end generated code: output=0b8de65d5b3cda94 input=fa742ca3daf85a7e]*/
+/*[clinic end generated code: output=7945c2e3cc817c58 input=fa742ca3daf85a7e]*/
 {
     int i, len;
     gid_t grouplist[MAX_GROUPS];
@@ -9335,41 +6816,9 @@
   (pid, status, rusage)
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_wait3__doc__,
-"wait3($module, /, options)\n"
-"--\n"
-"\n"
-"Wait for completion of a child process.\n"
-"\n"
-"Returns a tuple of information about the child process:\n"
-"  (pid, status, rusage)");
-
-#define OS_WAIT3_METHODDEF    \
-    {"wait3", (PyCFunction)os_wait3, METH_VARARGS|METH_KEYWORDS, os_wait3__doc__},
-
-static PyObject *
-os_wait3_impl(PyModuleDef *module, int options);
-
-static PyObject *
-os_wait3(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"options", NULL};
-    int options;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:wait3", _keywords,
-        &options))
-        goto exit;
-    return_value = os_wait3_impl(module, options);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_wait3_impl(PyModuleDef *module, int options)
-/*[clinic end generated code: output=1f2a63b6a93cbb57 input=8ac4c56956b61710]*/
+/*[clinic end generated code: output=e18af4924dc54945 input=8ac4c56956b61710]*/
 {
     pid_t pid;
     struct rusage ru;
@@ -9404,42 +6853,9 @@
   (pid, status, rusage)
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_wait4__doc__,
-"wait4($module, /, pid, options)\n"
-"--\n"
-"\n"
-"Wait for completion of a specific child process.\n"
-"\n"
-"Returns a tuple of information about the child process:\n"
-"  (pid, status, rusage)");
-
-#define OS_WAIT4_METHODDEF    \
-    {"wait4", (PyCFunction)os_wait4, METH_VARARGS|METH_KEYWORDS, os_wait4__doc__},
-
-static PyObject *
-os_wait4_impl(PyModuleDef *module, pid_t pid, int options);
-
-static PyObject *
-os_wait4(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"pid", "options", NULL};
-    pid_t pid;
-    int options;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "" _Py_PARSE_PID "i:wait4", _keywords,
-        &pid, &options))
-        goto exit;
-    return_value = os_wait4_impl(module, pid, options);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_wait4_impl(PyModuleDef *module, pid_t pid, int options)
-/*[clinic end generated code: output=20dfb05289d37dc6 input=d11deed0750600ba]*/
+/*[clinic end generated code: output=714f19e6ff01e099 input=d11deed0750600ba]*/
 {
     pid_t res;
     struct rusage ru;
@@ -9479,50 +6895,9 @@
 no children in a waitable state.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_waitid__doc__,
-"waitid($module, idtype, id, options, /)\n"
-"--\n"
-"\n"
-"Returns the result of waiting for a process or processes.\n"
-"\n"
-"  idtype\n"
-"    Must be one of be P_PID, P_PGID or P_ALL.\n"
-"  id\n"
-"    The id to wait on.\n"
-"  options\n"
-"    Constructed from the ORing of one or more of WEXITED, WSTOPPED\n"
-"    or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.\n"
-"\n"
-"Returns either waitid_result or None if WNOHANG is specified and there are\n"
-"no children in a waitable state.");
-
-#define OS_WAITID_METHODDEF    \
-    {"waitid", (PyCFunction)os_waitid, METH_VARARGS, os_waitid__doc__},
-
-static PyObject *
-os_waitid_impl(PyModuleDef *module, idtype_t idtype, id_t id, int options);
-
-static PyObject *
-os_waitid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    idtype_t idtype;
-    id_t id;
-    int options;
-
-    if (!PyArg_ParseTuple(args,
-        "i" _Py_PARSE_PID "i:waitid",
-        &idtype, &id, &options))
-        goto exit;
-    return_value = os_waitid_impl(module, idtype, id, options);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_waitid_impl(PyModuleDef *module, idtype_t idtype, id_t id, int options)
-/*[clinic end generated code: output=fb44bf97f01021b2 input=d8e7f76e052b7920]*/
+/*[clinic end generated code: output=5c0192750e22fa2e input=d8e7f76e052b7920]*/
 {
     PyObject *result;
     int res;
@@ -9575,43 +6950,9 @@
 The options argument is ignored on Windows.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_waitpid__doc__,
-"waitpid($module, pid, options, /)\n"
-"--\n"
-"\n"
-"Wait for completion of a given child process.\n"
-"\n"
-"Returns a tuple of information regarding the child process:\n"
-"    (pid, status)\n"
-"\n"
-"The options argument is ignored on Windows.");
-
-#define OS_WAITPID_METHODDEF    \
-    {"waitpid", (PyCFunction)os_waitpid, METH_VARARGS, os_waitpid__doc__},
-
-static PyObject *
-os_waitpid_impl(PyModuleDef *module, pid_t pid, int options);
-
-static PyObject *
-os_waitpid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    int options;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "i:waitpid",
-        &pid, &options))
-        goto exit;
-    return_value = os_waitpid_impl(module, pid, options);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_waitpid_impl(PyModuleDef *module, pid_t pid, int options)
-/*[clinic end generated code: output=095a6b00af70b7ac input=0bf1666b8758fda3]*/
+/*[clinic end generated code: output=5e3593353d54b15b input=0bf1666b8758fda3]*/
 {
     pid_t res;
     int async_err = 0;
@@ -9644,43 +6985,9 @@
 The options argument is ignored on Windows.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_waitpid__doc__,
-"waitpid($module, pid, options, /)\n"
-"--\n"
-"\n"
-"Wait for completion of a given process.\n"
-"\n"
-"Returns a tuple of information regarding the process:\n"
-"    (pid, status << 8)\n"
-"\n"
-"The options argument is ignored on Windows.");
-
-#define OS_WAITPID_METHODDEF    \
-    {"waitpid", (PyCFunction)os_waitpid, METH_VARARGS, os_waitpid__doc__},
-
-static PyObject *
-os_waitpid_impl(PyModuleDef *module, Py_intptr_t pid, int options);
-
-static PyObject *
-os_waitpid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_intptr_t pid;
-    int options;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_INTPTR "i:waitpid",
-        &pid, &options))
-        goto exit;
-    return_value = os_waitpid_impl(module, pid, options);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_waitpid_impl(PyModuleDef *module, Py_intptr_t pid, int options)
-/*[clinic end generated code: output=c20b95b15ad44a3a input=444c8f51cca5b862]*/
+/*[clinic end generated code: output=fc1d520db019625f input=444c8f51cca5b862]*/
 {
     int status;
     Py_intptr_t res;
@@ -9710,30 +7017,9 @@
     (pid, status)
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_wait__doc__,
-"wait($module, /)\n"
-"--\n"
-"\n"
-"Wait for completion of a child process.\n"
-"\n"
-"Returns a tuple of information about the child process:\n"
-"    (pid, status)");
-
-#define OS_WAIT_METHODDEF    \
-    {"wait", (PyCFunction)os_wait, METH_NOARGS, os_wait__doc__},
-
-static PyObject *
-os_wait_impl(PyModuleDef *module);
-
-static PyObject *
-os_wait(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_wait_impl(module);
-}
-
 static PyObject *
 os_wait_impl(PyModuleDef *module)
-/*[clinic end generated code: output=2a83a9d164e7e6a8 input=03b0182d4a4700ce]*/
+/*[clinic end generated code: output=4a7f4978393e0654 input=03b0182d4a4700ce]*/
 {
     pid_t pid;
     int async_err = 0;
@@ -10059,56 +7345,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_symlink__doc__,
-"symlink($module, /, src, dst, target_is_directory=False, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Create a symbolic link pointing to src named dst.\n"
-"\n"
-"target_is_directory is required on Windows if the target is to be\n"
-"  interpreted as a directory.  (On Windows, symlink requires\n"
-"  Windows 6.0 or greater, and raises a NotImplementedError otherwise.)\n"
-"  target_is_directory is ignored on non-Windows platforms.\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_SYMLINK_METHODDEF    \
-    {"symlink", (PyCFunction)os_symlink, METH_VARARGS|METH_KEYWORDS, os_symlink__doc__},
-
-static PyObject *
-os_symlink_impl(PyModuleDef *module, path_t *src, path_t *dst, int target_is_directory, int dir_fd);
-
-static PyObject *
-os_symlink(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"src", "dst", "target_is_directory", "dir_fd", NULL};
-    path_t src = PATH_T_INITIALIZE("symlink", "src", 0, 0);
-    path_t dst = PATH_T_INITIALIZE("symlink", "dst", 0, 0);
-    int target_is_directory = 0;
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&|p$O&:symlink", _keywords,
-        path_converter, &src, path_converter, &dst, &target_is_directory, SYMLINKAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_symlink_impl(module, &src, &dst, target_is_directory, dir_fd);
-
-exit:
-    /* Cleanup for src */
-    path_cleanup(&src);
-    /* Cleanup for dst */
-    path_cleanup(&dst);
-
-    return return_value;
-}
-
 static PyObject *
 os_symlink_impl(PyModuleDef *module, path_t *src, path_t *dst, int target_is_directory, int dir_fd)
-/*[clinic end generated code: output=1a31e6d88aafe9b6 input=e820ec4472547bc3]*/
+/*[clinic end generated code: output=11aa03f278bb2c8a input=e820ec4472547bc3]*/
 {
 #ifdef MS_WINDOWS
     DWORD result;
@@ -10255,31 +7494,9 @@
 All fields are floating point numbers.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_times__doc__,
-"times($module, /)\n"
-"--\n"
-"\n"
-"Return a collection containing process timing information.\n"
-"\n"
-"The object returned behaves like a named tuple with these fields:\n"
-"  (utime, stime, cutime, cstime, elapsed_time)\n"
-"All fields are floating point numbers.");
-
-#define OS_TIMES_METHODDEF    \
-    {"times", (PyCFunction)os_times, METH_NOARGS, os_times__doc__},
-
-static PyObject *
-os_times_impl(PyModuleDef *module);
-
-static PyObject *
-os_times(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_times_impl(module);
-}
-
 static PyObject *
 os_times_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b86896d031a9b768 input=2bf9df3d6ab2e48b]*/
+/*[clinic end generated code: output=df0a63ebe6e6f091 input=2bf9df3d6ab2e48b]*/
 #ifdef MS_WINDOWS
 {
     FILETIME create, exit, kernel, user;
@@ -10331,37 +7548,9 @@
 Call the system call getsid(pid) and return the result.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getsid__doc__,
-"getsid($module, pid, /)\n"
-"--\n"
-"\n"
-"Call the system call getsid(pid) and return the result.");
-
-#define OS_GETSID_METHODDEF    \
-    {"getsid", (PyCFunction)os_getsid, METH_VARARGS, os_getsid__doc__},
-
-static PyObject *
-os_getsid_impl(PyModuleDef *module, pid_t pid);
-
-static PyObject *
-os_getsid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID ":getsid",
-        &pid))
-        goto exit;
-    return_value = os_getsid_impl(module, pid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_getsid_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=ea8390f395f4e0e1 input=eeb2b923a30ce04e]*/
+/*[clinic end generated code: output=a074f80c0e6bfb38 input=eeb2b923a30ce04e]*/
 {
     int sid;
     sid = getsid(pid);
@@ -10379,27 +7568,9 @@
 Call the system call setsid().
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setsid__doc__,
-"setsid($module, /)\n"
-"--\n"
-"\n"
-"Call the system call setsid().");
-
-#define OS_SETSID_METHODDEF    \
-    {"setsid", (PyCFunction)os_setsid, METH_NOARGS, os_setsid__doc__},
-
-static PyObject *
-os_setsid_impl(PyModuleDef *module);
-
-static PyObject *
-os_setsid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_setsid_impl(module);
-}
-
 static PyObject *
 os_setsid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=2a9a1435d8d764d5 input=5fff45858e2f0776]*/
+/*[clinic end generated code: output=398fc152ae327330 input=5fff45858e2f0776]*/
 {
     if (setsid() < 0)
         return posix_error();
@@ -10419,38 +7590,9 @@
 Call the system call setpgid(pid, pgrp).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setpgid__doc__,
-"setpgid($module, pid, pgrp, /)\n"
-"--\n"
-"\n"
-"Call the system call setpgid(pid, pgrp).");
-
-#define OS_SETPGID_METHODDEF    \
-    {"setpgid", (PyCFunction)os_setpgid, METH_VARARGS, os_setpgid__doc__},
-
-static PyObject *
-os_setpgid_impl(PyModuleDef *module, pid_t pid, pid_t pgrp);
-
-static PyObject *
-os_setpgid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    pid_t pid;
-    pid_t pgrp;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_PID "" _Py_PARSE_PID ":setpgid",
-        &pid, &pgrp))
-        goto exit;
-    return_value = os_setpgid_impl(module, pid, pgrp);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setpgid_impl(PyModuleDef *module, pid_t pid, pid_t pgrp)
-/*[clinic end generated code: output=7ad79b725f890e1f input=fceb395eca572e1a]*/
+/*[clinic end generated code: output=7079a8e932912841 input=fceb395eca572e1a]*/
 {
     if (setpgid(pid, pgrp) < 0)
         return posix_error();
@@ -10469,37 +7611,9 @@
 Return the process group associated with the terminal specified by fd.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_tcgetpgrp__doc__,
-"tcgetpgrp($module, fd, /)\n"
-"--\n"
-"\n"
-"Return the process group associated with the terminal specified by fd.");
-
-#define OS_TCGETPGRP_METHODDEF    \
-    {"tcgetpgrp", (PyCFunction)os_tcgetpgrp, METH_VARARGS, os_tcgetpgrp__doc__},
-
-static PyObject *
-os_tcgetpgrp_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_tcgetpgrp(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-
-    if (!PyArg_ParseTuple(args,
-        "i:tcgetpgrp",
-        &fd))
-        goto exit;
-    return_value = os_tcgetpgrp_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_tcgetpgrp_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=abcf52ed4c8d22cb input=7f6c18eac10ada86]*/
+/*[clinic end generated code: output=ebb6dc5f111c7dc0 input=7f6c18eac10ada86]*/
 {
     pid_t pgid = tcgetpgrp(fd);
     if (pgid < 0)
@@ -10520,38 +7634,9 @@
 Set the process group associated with the terminal specified by fd.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_tcsetpgrp__doc__,
-"tcsetpgrp($module, fd, pgid, /)\n"
-"--\n"
-"\n"
-"Set the process group associated with the terminal specified by fd.");
-
-#define OS_TCSETPGRP_METHODDEF    \
-    {"tcsetpgrp", (PyCFunction)os_tcsetpgrp, METH_VARARGS, os_tcsetpgrp__doc__},
-
-static PyObject *
-os_tcsetpgrp_impl(PyModuleDef *module, int fd, pid_t pgid);
-
-static PyObject *
-os_tcsetpgrp(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    pid_t pgid;
-
-    if (!PyArg_ParseTuple(args,
-        "i" _Py_PARSE_PID ":tcsetpgrp",
-        &fd, &pgid))
-        goto exit;
-    return_value = os_tcsetpgrp_impl(module, fd, pgid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_tcsetpgrp_impl(PyModuleDef *module, int fd, pid_t pgid)
-/*[clinic end generated code: output=76f9bb8fd00f20f5 input=5bdc997c6a619020]*/
+/*[clinic end generated code: output=3e4b05177462cd22 input=5bdc997c6a619020]*/
 {
     if (tcsetpgrp(fd, pgid) < 0)
         return posix_error();
@@ -10584,53 +7669,9 @@
   If it is unavailable, using it will raise a NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_open__doc__,
-"open($module, /, path, flags, mode=511, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Open a file for low level IO.  Returns a file descriptor (integer).\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_OPEN_METHODDEF    \
-    {"open", (PyCFunction)os_open, METH_VARARGS|METH_KEYWORDS, os_open__doc__},
-
-static int
-os_open_impl(PyModuleDef *module, path_t *path, int flags, int mode, int dir_fd);
-
-static PyObject *
-os_open(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "flags", "mode", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("open", "path", 0, 0);
-    int flags;
-    int mode = 511;
-    int dir_fd = DEFAULT_DIR_FD;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&i|i$O&:open", _keywords,
-        path_converter, &path, &flags, &mode, OPENAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    _return_value = os_open_impl(module, &path, flags, mode, dir_fd);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong((long)_return_value);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static int
 os_open_impl(PyModuleDef *module, path_t *path, int flags, int mode, int dir_fd)
-/*[clinic end generated code: output=05b68fc4ed5e29c9 input=ad8623b29acd2934]*/
+/*[clinic end generated code: output=c95a64f0e62f199b input=ad8623b29acd2934]*/
 {
     int fd;
     int async_err = 0;
@@ -10688,38 +7729,9 @@
 Close a file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_close__doc__,
-"close($module, /, fd)\n"
-"--\n"
-"\n"
-"Close a file descriptor.");
-
-#define OS_CLOSE_METHODDEF    \
-    {"close", (PyCFunction)os_close, METH_VARARGS|METH_KEYWORDS, os_close__doc__},
-
-static PyObject *
-os_close_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_close(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", NULL};
-    int fd;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:close", _keywords,
-        &fd))
-        goto exit;
-    return_value = os_close_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_close_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=927004e29ad55808 input=2bc42451ca5c3223]*/
+/*[clinic end generated code: output=47bf2ea536445a26 input=2bc42451ca5c3223]*/
 {
     int res;
     if (!_PyVerify_fd(fd))
@@ -10747,38 +7759,9 @@
 Closes all file descriptors in [fd_low, fd_high), ignoring errors.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_closerange__doc__,
-"closerange($module, fd_low, fd_high, /)\n"
-"--\n"
-"\n"
-"Closes all file descriptors in [fd_low, fd_high), ignoring errors.");
-
-#define OS_CLOSERANGE_METHODDEF    \
-    {"closerange", (PyCFunction)os_closerange, METH_VARARGS, os_closerange__doc__},
-
-static PyObject *
-os_closerange_impl(PyModuleDef *module, int fd_low, int fd_high);
-
-static PyObject *
-os_closerange(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd_low;
-    int fd_high;
-
-    if (!PyArg_ParseTuple(args,
-        "ii:closerange",
-        &fd_low, &fd_high))
-        goto exit;
-    return_value = os_closerange_impl(module, fd_low, fd_high);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_closerange_impl(PyModuleDef *module, int fd_low, int fd_high)
-/*[clinic end generated code: output=0a929ece386811c3 input=5855a3d053ebd4ec]*/
+/*[clinic end generated code: output=70e6adb95220ba96 input=5855a3d053ebd4ec]*/
 {
     int i;
     Py_BEGIN_ALLOW_THREADS
@@ -10799,41 +7782,9 @@
 Return a duplicate of a file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_dup__doc__,
-"dup($module, fd, /)\n"
-"--\n"
-"\n"
-"Return a duplicate of a file descriptor.");
-
-#define OS_DUP_METHODDEF    \
-    {"dup", (PyCFunction)os_dup, METH_VARARGS, os_dup__doc__},
-
-static int
-os_dup_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_dup(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "i:dup",
-        &fd))
-        goto exit;
-    _return_value = os_dup_impl(module, fd);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_dup_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=75943e057b25e1bd input=6f10f7ea97f7852a]*/
+/*[clinic end generated code: output=f4bbac8c7652d05e input=6f10f7ea97f7852a]*/
 {
     return _Py_dup(fd);
 }
@@ -10848,40 +7799,9 @@
 Duplicate file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_dup2__doc__,
-"dup2($module, /, fd, fd2, inheritable=True)\n"
-"--\n"
-"\n"
-"Duplicate file descriptor.");
-
-#define OS_DUP2_METHODDEF    \
-    {"dup2", (PyCFunction)os_dup2, METH_VARARGS|METH_KEYWORDS, os_dup2__doc__},
-
-static PyObject *
-os_dup2_impl(PyModuleDef *module, int fd, int fd2, int inheritable);
-
-static PyObject *
-os_dup2(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", "fd2", "inheritable", NULL};
-    int fd;
-    int fd2;
-    int inheritable = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "ii|p:dup2", _keywords,
-        &fd, &fd2, &inheritable))
-        goto exit;
-    return_value = os_dup2_impl(module, fd, fd2, inheritable);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_dup2_impl(PyModuleDef *module, int fd, int fd2, int inheritable)
-/*[clinic end generated code: output=531e482dd11a99a0 input=76e96f511be0352f]*/
+/*[clinic end generated code: output=9a099d95881a7923 input=76e96f511be0352f]*/
 {
     int res;
 #if defined(HAVE_DUP3) && \
@@ -10974,46 +7894,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_lockf__doc__,
-"lockf($module, fd, command, length, /)\n"
-"--\n"
-"\n"
-"Apply, test or remove a POSIX lock on an open file descriptor.\n"
-"\n"
-"  fd\n"
-"    An open file descriptor.\n"
-"  command\n"
-"    One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.\n"
-"  length\n"
-"    The number of bytes to lock, starting at the current position.");
-
-#define OS_LOCKF_METHODDEF    \
-    {"lockf", (PyCFunction)os_lockf, METH_VARARGS, os_lockf__doc__},
-
-static PyObject *
-os_lockf_impl(PyModuleDef *module, int fd, int command, Py_off_t length);
-
-static PyObject *
-os_lockf(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int command;
-    Py_off_t length;
-
-    if (!PyArg_ParseTuple(args,
-        "iiO&:lockf",
-        &fd, &command, Py_off_t_converter, &length))
-        goto exit;
-    return_value = os_lockf_impl(module, fd, command, length);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_lockf_impl(PyModuleDef *module, int fd, int command, Py_off_t length)
-/*[clinic end generated code: output=1b28346ac7335c0f input=65da41d2106e9b79]*/
+/*[clinic end generated code: output=25ff778f9e2fbf1b input=65da41d2106e9b79]*/
 {
     int res;
 
@@ -11043,46 +7926,9 @@
 relative to the beginning of the file.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_lseek__doc__,
-"lseek($module, fd, position, how, /)\n"
-"--\n"
-"\n"
-"Set the position of a file descriptor.  Return the new position.\n"
-"\n"
-"Return the new cursor position in number of bytes\n"
-"relative to the beginning of the file.");
-
-#define OS_LSEEK_METHODDEF    \
-    {"lseek", (PyCFunction)os_lseek, METH_VARARGS, os_lseek__doc__},
-
-static Py_off_t
-os_lseek_impl(PyModuleDef *module, int fd, Py_off_t position, int how);
-
-static PyObject *
-os_lseek(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_off_t position;
-    int how;
-    Py_off_t _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&i:lseek",
-        &fd, Py_off_t_converter, &position, &how))
-        goto exit;
-    _return_value = os_lseek_impl(module, fd, position, how);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromPy_off_t(_return_value);
-
-exit:
-    return return_value;
-}
-
 static Py_off_t
 os_lseek_impl(PyModuleDef *module, int fd, Py_off_t position, int how)
-/*[clinic end generated code: output=88cfc146f55667af input=902654ad3f96a6d3]*/
+/*[clinic end generated code: output=65d4ab96d664998c input=902654ad3f96a6d3]*/
 {
     Py_off_t result;
 
@@ -11129,38 +7975,9 @@
 Read from a file descriptor.  Returns a bytes object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_read__doc__,
-"read($module, fd, length, /)\n"
-"--\n"
-"\n"
-"Read from a file descriptor.  Returns a bytes object.");
-
-#define OS_READ_METHODDEF    \
-    {"read", (PyCFunction)os_read, METH_VARARGS, os_read__doc__},
-
-static PyObject *
-os_read_impl(PyModuleDef *module, int fd, Py_ssize_t length);
-
-static PyObject *
-os_read(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_ssize_t length;
-
-    if (!PyArg_ParseTuple(args,
-        "in:read",
-        &fd, &length))
-        goto exit;
-    return_value = os_read_impl(module, fd, length);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_read_impl(PyModuleDef *module, int fd, Py_ssize_t length)
-/*[clinic end generated code: output=1f3bc27260a24968 input=1df2eaa27c0bf1d3]*/
+/*[clinic end generated code: output=be24f44178455e8b input=1df2eaa27c0bf1d3]*/
 {
     Py_ssize_t n;
     PyObject *buffer;
@@ -11270,50 +8087,9 @@
 which may be less than the total capacity of all the buffers.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_readv__doc__,
-"readv($module, fd, buffers, /)\n"
-"--\n"
-"\n"
-"Read from a file descriptor fd into an iterable of buffers.\n"
-"\n"
-"The buffers should be mutable buffers accepting bytes.\n"
-"readv will transfer data into each buffer until it is full\n"
-"and then move on to the next buffer in the sequence to hold\n"
-"the rest of the data.\n"
-"\n"
-"readv returns the total number of bytes read,\n"
-"which may be less than the total capacity of all the buffers.");
-
-#define OS_READV_METHODDEF    \
-    {"readv", (PyCFunction)os_readv, METH_VARARGS, os_readv__doc__},
-
-static Py_ssize_t
-os_readv_impl(PyModuleDef *module, int fd, PyObject *buffers);
-
-static PyObject *
-os_readv(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    PyObject *buffers;
-    Py_ssize_t _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "iO:readv",
-        &fd, &buffers))
-        goto exit;
-    _return_value = os_readv_impl(module, fd, buffers);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromSsize_t(_return_value);
-
-exit:
-    return return_value;
-}
-
 static Py_ssize_t
 os_readv_impl(PyModuleDef *module, int fd, PyObject *buffers)
-/*[clinic end generated code: output=72748b1c32a6e2a1 input=e679eb5dbfa0357d]*/
+/*[clinic end generated code: output=00fc56ff1800059f input=e679eb5dbfa0357d]*/
 {
     int cnt;
     Py_ssize_t n;
@@ -11366,42 +8142,9 @@
 the beginning of the file.  The file offset remains unchanged.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_pread__doc__,
-"pread($module, fd, length, offset, /)\n"
-"--\n"
-"\n"
-"Read a number of bytes from a file descriptor starting at a particular offset.\n"
-"\n"
-"Read length bytes from file descriptor fd, starting at offset bytes from\n"
-"the beginning of the file.  The file offset remains unchanged.");
-
-#define OS_PREAD_METHODDEF    \
-    {"pread", (PyCFunction)os_pread, METH_VARARGS, os_pread__doc__},
-
-static PyObject *
-os_pread_impl(PyModuleDef *module, int fd, int length, Py_off_t offset);
-
-static PyObject *
-os_pread(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int length;
-    Py_off_t offset;
-
-    if (!PyArg_ParseTuple(args,
-        "iiO&:pread",
-        &fd, &length, Py_off_t_converter, &offset))
-        goto exit;
-    return_value = os_pread_impl(module, fd, length, offset);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_pread_impl(PyModuleDef *module, int fd, int length, Py_off_t offset)
-/*[clinic end generated code: output=7b62bf6c06e20ae8 input=084948dcbaa35d4c]*/
+/*[clinic end generated code: output=90d1fed87f68fa33 input=084948dcbaa35d4c]*/
 {
     Py_ssize_t n;
     int async_err = 0;
@@ -11446,46 +8189,9 @@
 Write a bytes object to a file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_write__doc__,
-"write($module, fd, data, /)\n"
-"--\n"
-"\n"
-"Write a bytes object to a file descriptor.");
-
-#define OS_WRITE_METHODDEF    \
-    {"write", (PyCFunction)os_write, METH_VARARGS, os_write__doc__},
-
-static Py_ssize_t
-os_write_impl(PyModuleDef *module, int fd, Py_buffer *data);
-
-static PyObject *
-os_write(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_buffer data = {NULL, NULL};
-    Py_ssize_t _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "iy*:write",
-        &fd, &data))
-        goto exit;
-    _return_value = os_write_impl(module, fd, &data);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromSsize_t(_return_value);
-
-exit:
-    /* Cleanup for data */
-    if (data.obj)
-       PyBuffer_Release(&data);
-
-    return return_value;
-}
-
 static Py_ssize_t
 os_write_impl(PyModuleDef *module, int fd, Py_buffer *data)
-/*[clinic end generated code: output=aeb96acfdd4d5112 input=3207e28963234f3c]*/
+/*[clinic end generated code: output=58845c93c9ee1dda input=3207e28963234f3c]*/
 {
     return _Py_write(fd, data->buf, data->len);
 }
@@ -11651,41 +8357,9 @@
 Equivalent to os.stat(fd).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fstat__doc__,
-"fstat($module, /, fd)\n"
-"--\n"
-"\n"
-"Perform a stat system call on the given file descriptor.\n"
-"\n"
-"Like stat(), but for an open file descriptor.\n"
-"Equivalent to os.stat(fd).");
-
-#define OS_FSTAT_METHODDEF    \
-    {"fstat", (PyCFunction)os_fstat, METH_VARARGS|METH_KEYWORDS, os_fstat__doc__},
-
-static PyObject *
-os_fstat_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_fstat(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", NULL};
-    int fd;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:fstat", _keywords,
-        &fd))
-        goto exit;
-    return_value = os_fstat_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fstat_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=dae4a9678c7bd881 input=27e0e0ebbe5600c9]*/
+/*[clinic end generated code: output=d71fe98bf042b626 input=27e0e0ebbe5600c9]*/
 {
     STRUCT_STAT st;
     int res;
@@ -11719,44 +8393,9 @@
 connected to the slave end of a terminal.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_isatty__doc__,
-"isatty($module, fd, /)\n"
-"--\n"
-"\n"
-"Return True if the fd is connected to a terminal.\n"
-"\n"
-"Return True if the file descriptor is an open file descriptor\n"
-"connected to the slave end of a terminal.");
-
-#define OS_ISATTY_METHODDEF    \
-    {"isatty", (PyCFunction)os_isatty, METH_VARARGS, os_isatty__doc__},
-
-static int
-os_isatty_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_isatty(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "i:isatty",
-        &fd))
-        goto exit;
-    _return_value = os_isatty_impl(module, fd);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_isatty_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=4bfadbfe22715097 input=08ce94aa1eaf7b5e]*/
+/*[clinic end generated code: output=acec9d3c29d16d33 input=08ce94aa1eaf7b5e]*/
 {
     if (!_PyVerify_fd(fd))
         return 0;
@@ -11774,30 +8413,9 @@
   (read_fd, write_fd)
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_pipe__doc__,
-"pipe($module, /)\n"
-"--\n"
-"\n"
-"Create a pipe.\n"
-"\n"
-"Returns a tuple of two file descriptors:\n"
-"  (read_fd, write_fd)");
-
-#define OS_PIPE_METHODDEF    \
-    {"pipe", (PyCFunction)os_pipe, METH_NOARGS, os_pipe__doc__},
-
-static PyObject *
-os_pipe_impl(PyModuleDef *module);
-
-static PyObject *
-os_pipe(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_pipe_impl(module);
-}
-
 static PyObject *
 os_pipe_impl(PyModuleDef *module)
-/*[clinic end generated code: output=0da2479f2266e774 input=02535e8c8fa6c4d4]*/
+/*[clinic end generated code: output=6b0cd3f868ec3c40 input=02535e8c8fa6c4d4]*/
 {
     int fds[2];
 #ifdef MS_WINDOWS
@@ -11882,43 +8500,9 @@
 O_NONBLOCK, O_CLOEXEC.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_pipe2__doc__,
-"pipe2($module, flags, /)\n"
-"--\n"
-"\n"
-"Create a pipe with flags set atomically.\n"
-"\n"
-"Returns a tuple of two file descriptors:\n"
-"  (read_fd, write_fd)\n"
-"\n"
-"flags can be constructed by ORing together one or more of these values:\n"
-"O_NONBLOCK, O_CLOEXEC.");
-
-#define OS_PIPE2_METHODDEF    \
-    {"pipe2", (PyCFunction)os_pipe2, METH_VARARGS, os_pipe2__doc__},
-
-static PyObject *
-os_pipe2_impl(PyModuleDef *module, int flags);
-
-static PyObject *
-os_pipe2(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int flags;
-
-    if (!PyArg_ParseTuple(args,
-        "i:pipe2",
-        &flags))
-        goto exit;
-    return_value = os_pipe2_impl(module, flags);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_pipe2_impl(PyModuleDef *module, int flags)
-/*[clinic end generated code: output=9e27c799ce19220b input=f261b6e7e63c6817]*/
+/*[clinic end generated code: output=c15b6075d0c6b2e7 input=f261b6e7e63c6817]*/
 {
     int fds[2];
     int res;
@@ -11944,45 +8528,9 @@
 buffers must be a sequence of bytes-like objects.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_writev__doc__,
-"writev($module, fd, buffers, /)\n"
-"--\n"
-"\n"
-"Iterate over buffers, and write the contents of each to a file descriptor.\n"
-"\n"
-"Returns the total number of bytes written.\n"
-"buffers must be a sequence of bytes-like objects.");
-
-#define OS_WRITEV_METHODDEF    \
-    {"writev", (PyCFunction)os_writev, METH_VARARGS, os_writev__doc__},
-
-static Py_ssize_t
-os_writev_impl(PyModuleDef *module, int fd, PyObject *buffers);
-
-static PyObject *
-os_writev(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    PyObject *buffers;
-    Py_ssize_t _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "iO:writev",
-        &fd, &buffers))
-        goto exit;
-    _return_value = os_writev_impl(module, fd, buffers);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromSsize_t(_return_value);
-
-exit:
-    return return_value;
-}
-
 static Py_ssize_t
 os_writev_impl(PyModuleDef *module, int fd, PyObject *buffers)
-/*[clinic end generated code: output=591c662dccbe4951 input=5b8d17fe4189d2fe]*/
+/*[clinic end generated code: output=a48925dbf2d5c238 input=5b8d17fe4189d2fe]*/
 {
     int cnt;
     Py_ssize_t result;
@@ -12032,51 +8580,9 @@
 current file offset.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_pwrite__doc__,
-"pwrite($module, fd, buffer, offset, /)\n"
-"--\n"
-"\n"
-"Write bytes to a file descriptor starting at a particular offset.\n"
-"\n"
-"Write buffer to fd, starting at offset bytes from the beginning of\n"
-"the file.  Returns the number of bytes writte.  Does not change the\n"
-"current file offset.");
-
-#define OS_PWRITE_METHODDEF    \
-    {"pwrite", (PyCFunction)os_pwrite, METH_VARARGS, os_pwrite__doc__},
-
-static Py_ssize_t
-os_pwrite_impl(PyModuleDef *module, int fd, Py_buffer *buffer, Py_off_t offset);
-
-static PyObject *
-os_pwrite(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_buffer buffer = {NULL, NULL};
-    Py_off_t offset;
-    Py_ssize_t _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "iy*O&:pwrite",
-        &fd, &buffer, Py_off_t_converter, &offset))
-        goto exit;
-    _return_value = os_pwrite_impl(module, fd, &buffer, offset);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromSsize_t(_return_value);
-
-exit:
-    /* Cleanup for buffer */
-    if (buffer.obj)
-       PyBuffer_Release(&buffer);
-
-    return return_value;
-}
-
 static Py_ssize_t
 os_pwrite_impl(PyModuleDef *module, int fd, Py_buffer *buffer, Py_off_t offset)
-/*[clinic end generated code: output=ec9cc5b2238e96a7 input=19903f1b3dd26377]*/
+/*[clinic end generated code: output=95225f3b496feaf3 input=19903f1b3dd26377]*/
 {
     Py_ssize_t size;
     int async_err = 0;
@@ -12116,48 +8622,9 @@
   If it is unavailable, using it will raise a NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_mkfifo__doc__,
-"mkfifo($module, /, path, mode=438, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Create a \"fifo\" (a POSIX named pipe).\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_MKFIFO_METHODDEF    \
-    {"mkfifo", (PyCFunction)os_mkfifo, METH_VARARGS|METH_KEYWORDS, os_mkfifo__doc__},
-
-static PyObject *
-os_mkfifo_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd);
-
-static PyObject *
-os_mkfifo(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "mode", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("mkfifo", "path", 0, 0);
-    int mode = 438;
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|i$O&:mkfifo", _keywords,
-        path_converter, &path, &mode, MKFIFOAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_mkfifo_impl(module, &path, mode, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_mkfifo_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd)
-/*[clinic end generated code: output=b3321927546893d0 input=73032e98a36e0e19]*/
+/*[clinic end generated code: output=8f5f5e72c630049a input=73032e98a36e0e19]*/
 {
     int result;
     int async_err = 0;
@@ -12206,56 +8673,9 @@
   If it is unavailable, using it will raise a NotImplementedError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_mknod__doc__,
-"mknod($module, /, path, mode=384, device=0, *, dir_fd=None)\n"
-"--\n"
-"\n"
-"Create a node in the file system.\n"
-"\n"
-"Create a node in the file system (file, device special file or named pipe)\n"
-"at path.  mode specifies both the permissions to use and the\n"
-"type of node to be created, being combined (bitwise OR) with one of\n"
-"S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO.  If S_IFCHR or S_IFBLK is set on mode,\n"
-"device defines the newly created device special file (probably using\n"
-"os.makedev()).  Otherwise device is ignored.\n"
-"\n"
-"If dir_fd is not None, it should be a file descriptor open to a directory,\n"
-"  and path should be relative; path will then be relative to that directory.\n"
-"dir_fd may not be implemented on your platform.\n"
-"  If it is unavailable, using it will raise a NotImplementedError.");
-
-#define OS_MKNOD_METHODDEF    \
-    {"mknod", (PyCFunction)os_mknod, METH_VARARGS|METH_KEYWORDS, os_mknod__doc__},
-
-static PyObject *
-os_mknod_impl(PyModuleDef *module, path_t *path, int mode, dev_t device, int dir_fd);
-
-static PyObject *
-os_mknod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "mode", "device", "dir_fd", NULL};
-    path_t path = PATH_T_INITIALIZE("mknod", "path", 0, 0);
-    int mode = 384;
-    dev_t device = 0;
-    int dir_fd = DEFAULT_DIR_FD;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&|iO&$O&:mknod", _keywords,
-        path_converter, &path, &mode, _Py_Dev_Converter, &device, MKNODAT_DIR_FD_CONVERTER, &dir_fd))
-        goto exit;
-    return_value = os_mknod_impl(module, &path, mode, device, dir_fd);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_mknod_impl(PyModuleDef *module, path_t *path, int mode, dev_t device, int dir_fd)
-/*[clinic end generated code: output=f71d54eaf9bb6f1a input=ee44531551a4d83b]*/
+/*[clinic end generated code: output=f7f813e8847de12f input=ee44531551a4d83b]*/
 {
     int result;
     int async_err = 0;
@@ -12289,41 +8709,9 @@
 Extracts a device major number from a raw device number.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_major__doc__,
-"major($module, device, /)\n"
-"--\n"
-"\n"
-"Extracts a device major number from a raw device number.");
-
-#define OS_MAJOR_METHODDEF    \
-    {"major", (PyCFunction)os_major, METH_VARARGS, os_major__doc__},
-
-static unsigned int
-os_major_impl(PyModuleDef *module, dev_t device);
-
-static PyObject *
-os_major(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    dev_t device;
-    unsigned int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:major",
-        _Py_Dev_Converter, &device))
-        goto exit;
-    _return_value = os_major_impl(module, device);
-    if ((_return_value == (unsigned int)-1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromUnsignedLong((unsigned long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static unsigned int
 os_major_impl(PyModuleDef *module, dev_t device)
-/*[clinic end generated code: output=a2d06e908ebf95b5 input=1e16a4d30c4d4462]*/
+/*[clinic end generated code: output=ba55693ab49bac34 input=1e16a4d30c4d4462]*/
 {
     return major(device);
 }
@@ -12338,41 +8726,9 @@
 Extracts a device minor number from a raw device number.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_minor__doc__,
-"minor($module, device, /)\n"
-"--\n"
-"\n"
-"Extracts a device minor number from a raw device number.");
-
-#define OS_MINOR_METHODDEF    \
-    {"minor", (PyCFunction)os_minor, METH_VARARGS, os_minor__doc__},
-
-static unsigned int
-os_minor_impl(PyModuleDef *module, dev_t device);
-
-static PyObject *
-os_minor(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    dev_t device;
-    unsigned int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:minor",
-        _Py_Dev_Converter, &device))
-        goto exit;
-    _return_value = os_minor_impl(module, device);
-    if ((_return_value == (unsigned int)-1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromUnsignedLong((unsigned long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static unsigned int
 os_minor_impl(PyModuleDef *module, dev_t device)
-/*[clinic end generated code: output=6332287ee3f006e2 input=0842c6d23f24c65e]*/
+/*[clinic end generated code: output=2867219ebf274e27 input=0842c6d23f24c65e]*/
 {
     return minor(device);
 }
@@ -12388,42 +8744,9 @@
 Composes a raw device number from the major and minor device numbers.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_makedev__doc__,
-"makedev($module, major, minor, /)\n"
-"--\n"
-"\n"
-"Composes a raw device number from the major and minor device numbers.");
-
-#define OS_MAKEDEV_METHODDEF    \
-    {"makedev", (PyCFunction)os_makedev, METH_VARARGS, os_makedev__doc__},
-
-static dev_t
-os_makedev_impl(PyModuleDef *module, int major, int minor);
-
-static PyObject *
-os_makedev(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int major;
-    int minor;
-    dev_t _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "ii:makedev",
-        &major, &minor))
-        goto exit;
-    _return_value = os_makedev_impl(module, major, minor);
-    if ((_return_value == (dev_t)-1) && PyErr_Occurred())
-        goto exit;
-    return_value = _PyLong_FromDev(_return_value);
-
-exit:
-    return return_value;
-}
-
 static dev_t
 os_makedev_impl(PyModuleDef *module, int major, int minor)
-/*[clinic end generated code: output=38e9a9774c96511a input=4b9fd8fc73cbe48f]*/
+/*[clinic end generated code: output=7cb6264352437660 input=4b9fd8fc73cbe48f]*/
 {
     return makedev(major, minor);
 }
@@ -12441,38 +8764,9 @@
 Truncate a file, specified by file descriptor, to a specific length.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_ftruncate__doc__,
-"ftruncate($module, fd, length, /)\n"
-"--\n"
-"\n"
-"Truncate a file, specified by file descriptor, to a specific length.");
-
-#define OS_FTRUNCATE_METHODDEF    \
-    {"ftruncate", (PyCFunction)os_ftruncate, METH_VARARGS, os_ftruncate__doc__},
-
-static PyObject *
-os_ftruncate_impl(PyModuleDef *module, int fd, Py_off_t length);
-
-static PyObject *
-os_ftruncate(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_off_t length;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&:ftruncate",
-        &fd, Py_off_t_converter, &length))
-        goto exit;
-    return_value = os_ftruncate_impl(module, fd, length);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_ftruncate_impl(PyModuleDef *module, int fd, Py_off_t length)
-/*[clinic end generated code: output=62326766cb9b76bf input=63b43641e52818f2]*/
+/*[clinic end generated code: output=3666f401d76bf834 input=63b43641e52818f2]*/
 {
     int result;
     int async_err = 0;
@@ -12502,45 +8796,9 @@
   If this functionality is unavailable, using it raises an exception.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_truncate__doc__,
-"truncate($module, /, path, length)\n"
-"--\n"
-"\n"
-"Truncate a file, specified by path, to a specific length.\n"
-"\n"
-"On some platforms, path may also be specified as an open file descriptor.\n"
-"  If this functionality is unavailable, using it raises an exception.");
-
-#define OS_TRUNCATE_METHODDEF    \
-    {"truncate", (PyCFunction)os_truncate, METH_VARARGS|METH_KEYWORDS, os_truncate__doc__},
-
-static PyObject *
-os_truncate_impl(PyModuleDef *module, path_t *path, Py_off_t length);
-
-static PyObject *
-os_truncate(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "length", NULL};
-    path_t path = PATH_T_INITIALIZE("truncate", "path", 0, PATH_HAVE_FTRUNCATE);
-    Py_off_t length;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&:truncate", _keywords,
-        path_converter, &path, Py_off_t_converter, &length))
-        goto exit;
-    return_value = os_truncate_impl(module, &path, length);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_truncate_impl(PyModuleDef *module, path_t *path, Py_off_t length)
-/*[clinic end generated code: output=6bd76262d2e027c6 input=77229cf0b50a9b77]*/
+/*[clinic end generated code: output=f60a9e08370e9e2e input=77229cf0b50a9b77]*/
 {
     int result;
 
@@ -12584,42 +8842,9 @@
 starting at offset bytes from the beginning and continuing for length bytes.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_posix_fallocate__doc__,
-"posix_fallocate($module, fd, offset, length, /)\n"
-"--\n"
-"\n"
-"Ensure a file has allocated at least a particular number of bytes on disk.\n"
-"\n"
-"Ensure that the file specified by fd encompasses a range of bytes\n"
-"starting at offset bytes from the beginning and continuing for length bytes.");
-
-#define OS_POSIX_FALLOCATE_METHODDEF    \
-    {"posix_fallocate", (PyCFunction)os_posix_fallocate, METH_VARARGS, os_posix_fallocate__doc__},
-
-static PyObject *
-os_posix_fallocate_impl(PyModuleDef *module, int fd, Py_off_t offset, Py_off_t length);
-
-static PyObject *
-os_posix_fallocate(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_off_t offset;
-    Py_off_t length;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&O&:posix_fallocate",
-        &fd, Py_off_t_converter, &offset, Py_off_t_converter, &length))
-        goto exit;
-    return_value = os_posix_fallocate_impl(module, fd, offset, length);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_posix_fallocate_impl(PyModuleDef *module, int fd, Py_off_t offset, Py_off_t length)
-/*[clinic end generated code: output=0cd702d2065c79db input=d7a2ef0ab2ca52fb]*/
+/*[clinic end generated code: output=8ae5f7837004d454 input=d7a2ef0ab2ca52fb]*/
 {
     int result;
     int async_err = 0;
@@ -12658,48 +8883,9 @@
 POSIX_FADV_DONTNEED.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_posix_fadvise__doc__,
-"posix_fadvise($module, fd, offset, length, advice, /)\n"
-"--\n"
-"\n"
-"Announce an intention to access data in a specific pattern.\n"
-"\n"
-"Announce an intention to access data in a specific pattern, thus allowing\n"
-"the kernel to make optimizations.\n"
-"The advice applies to the region of the file specified by fd starting at\n"
-"offset and continuing for length bytes.\n"
-"advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,\n"
-"POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or\n"
-"POSIX_FADV_DONTNEED.");
-
-#define OS_POSIX_FADVISE_METHODDEF    \
-    {"posix_fadvise", (PyCFunction)os_posix_fadvise, METH_VARARGS, os_posix_fadvise__doc__},
-
-static PyObject *
-os_posix_fadvise_impl(PyModuleDef *module, int fd, Py_off_t offset, Py_off_t length, int advice);
-
-static PyObject *
-os_posix_fadvise(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    Py_off_t offset;
-    Py_off_t length;
-    int advice;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&O&i:posix_fadvise",
-        &fd, Py_off_t_converter, &offset, Py_off_t_converter, &length, &advice))
-        goto exit;
-    return_value = os_posix_fadvise_impl(module, fd, offset, length, advice);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_posix_fadvise_impl(PyModuleDef *module, int fd, Py_off_t offset, Py_off_t length, int advice)
-/*[clinic end generated code: output=dad93f32c04dd4f7 input=0fbe554edc2f04b5]*/
+/*[clinic end generated code: output=0e3f09f651661257 input=0fbe554edc2f04b5]*/
 {
     int result;
     int async_err = 0;
@@ -12748,38 +8934,9 @@
 Change or add an environment variable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_putenv__doc__,
-"putenv($module, name, value, /)\n"
-"--\n"
-"\n"
-"Change or add an environment variable.");
-
-#define OS_PUTENV_METHODDEF    \
-    {"putenv", (PyCFunction)os_putenv, METH_VARARGS, os_putenv__doc__},
-
-static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value);
-
-static PyObject *
-os_putenv(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *name;
-    PyObject *value;
-
-    if (!PyArg_ParseTuple(args,
-        "UU:putenv",
-        &name, &value))
-        goto exit;
-    return_value = os_putenv_impl(module, name, value);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=5ce9ef9b15606e7e input=ba586581c2e6105f]*/
+/*[clinic end generated code: output=a2438cf95e5a0c1c input=ba586581c2e6105f]*/
 {
     wchar_t *env;
 
@@ -12821,43 +8978,9 @@
 Change or add an environment variable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_putenv__doc__,
-"putenv($module, name, value, /)\n"
-"--\n"
-"\n"
-"Change or add an environment variable.");
-
-#define OS_PUTENV_METHODDEF    \
-    {"putenv", (PyCFunction)os_putenv, METH_VARARGS, os_putenv__doc__},
-
-static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value);
-
-static PyObject *
-os_putenv(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *name = NULL;
-    PyObject *value = NULL;
-
-    if (!PyArg_ParseTuple(args,
-        "O&O&:putenv",
-        PyUnicode_FSConverter, &name, PyUnicode_FSConverter, &value))
-        goto exit;
-    return_value = os_putenv_impl(module, name, value);
-
-exit:
-    /* Cleanup for name */
-    Py_XDECREF(name);
-    /* Cleanup for value */
-    Py_XDECREF(value);
-
-    return return_value;
-}
-
 static PyObject *
 os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=85ab223393dc7afd input=a97bc6152f688d31]*/
+/*[clinic end generated code: output=a2438cf95e5a0c1c input=a97bc6152f688d31]*/
 {
     PyObject *bytes = NULL;
     char *env;
@@ -12892,40 +9015,9 @@
 Delete an environment variable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_unsetenv__doc__,
-"unsetenv($module, name, /)\n"
-"--\n"
-"\n"
-"Delete an environment variable.");
-
-#define OS_UNSETENV_METHODDEF    \
-    {"unsetenv", (PyCFunction)os_unsetenv, METH_VARARGS, os_unsetenv__doc__},
-
-static PyObject *
-os_unsetenv_impl(PyModuleDef *module, PyObject *name);
-
-static PyObject *
-os_unsetenv(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *name = NULL;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:unsetenv",
-        PyUnicode_FSConverter, &name))
-        goto exit;
-    return_value = os_unsetenv_impl(module, name);
-
-exit:
-    /* Cleanup for name */
-    Py_XDECREF(name);
-
-    return return_value;
-}
-
 static PyObject *
 os_unsetenv_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=91318c995f9a0767 input=2bb5288a599c7107]*/
+/*[clinic end generated code: output=25994b57016a2dc9 input=2bb5288a599c7107]*/
 {
 #ifndef HAVE_BROKEN_UNSETENV
     int err;
@@ -12962,37 +9054,9 @@
 Translate an error code to a message string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_strerror__doc__,
-"strerror($module, code, /)\n"
-"--\n"
-"\n"
-"Translate an error code to a message string.");
-
-#define OS_STRERROR_METHODDEF    \
-    {"strerror", (PyCFunction)os_strerror, METH_VARARGS, os_strerror__doc__},
-
-static PyObject *
-os_strerror_impl(PyModuleDef *module, int code);
-
-static PyObject *
-os_strerror(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int code;
-
-    if (!PyArg_ParseTuple(args,
-        "i:strerror",
-        &code))
-        goto exit;
-    return_value = os_strerror_impl(module, code);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_strerror_impl(PyModuleDef *module, int code)
-/*[clinic end generated code: output=8665c70bb2ca4720 input=75a8673d97915a91]*/
+/*[clinic end generated code: output=0280c6af51e5c9fe input=75a8673d97915a91]*/
 {
     char *message = strerror(code);
     if (message == NULL) {
@@ -13015,41 +9079,9 @@
 Return True if the process returning status was dumped to a core file.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WCOREDUMP__doc__,
-"WCOREDUMP($module, status, /)\n"
-"--\n"
-"\n"
-"Return True if the process returning status was dumped to a core file.");
-
-#define OS_WCOREDUMP_METHODDEF    \
-    {"WCOREDUMP", (PyCFunction)os_WCOREDUMP, METH_VARARGS, os_WCOREDUMP__doc__},
-
-static int
-os_WCOREDUMP_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WCOREDUMP(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "i:WCOREDUMP",
-        &status))
-        goto exit;
-    _return_value = os_WCOREDUMP_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WCOREDUMP_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=e04d55c09c299828 input=8b05e7ab38528d04]*/
+/*[clinic end generated code: output=134f70bbe63fbf41 input=8b05e7ab38528d04]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13070,45 +9102,9 @@
 job control stop.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WIFCONTINUED__doc__,
-"WIFCONTINUED($module, /, status)\n"
-"--\n"
-"\n"
-"Return True if a particular process was continued from a job control stop.\n"
-"\n"
-"Return True if the process returning status was continued from a\n"
-"job control stop.");
-
-#define OS_WIFCONTINUED_METHODDEF    \
-    {"WIFCONTINUED", (PyCFunction)os_WIFCONTINUED, METH_VARARGS|METH_KEYWORDS, os_WIFCONTINUED__doc__},
-
-static int
-os_WIFCONTINUED_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WIFCONTINUED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WIFCONTINUED", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WIFCONTINUED_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WIFCONTINUED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=9c4e6105a4520ab5 input=e777e7d38eb25bd9]*/
+/*[clinic end generated code: output=9cdd26543ebb6dcd input=e777e7d38eb25bd9]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13126,42 +9122,9 @@
 Return True if the process returning status was stopped.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WIFSTOPPED__doc__,
-"WIFSTOPPED($module, /, status)\n"
-"--\n"
-"\n"
-"Return True if the process returning status was stopped.");
-
-#define OS_WIFSTOPPED_METHODDEF    \
-    {"WIFSTOPPED", (PyCFunction)os_WIFSTOPPED, METH_VARARGS|METH_KEYWORDS, os_WIFSTOPPED__doc__},
-
-static int
-os_WIFSTOPPED_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WIFSTOPPED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WIFSTOPPED", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WIFSTOPPED_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WIFSTOPPED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=e0de2da8ec9593ff input=043cb7f1289ef904]*/
+/*[clinic end generated code: output=73bf35e44994a724 input=043cb7f1289ef904]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13179,42 +9142,9 @@
 Return True if the process returning status was terminated by a signal.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WIFSIGNALED__doc__,
-"WIFSIGNALED($module, /, status)\n"
-"--\n"
-"\n"
-"Return True if the process returning status was terminated by a signal.");
-
-#define OS_WIFSIGNALED_METHODDEF    \
-    {"WIFSIGNALED", (PyCFunction)os_WIFSIGNALED, METH_VARARGS|METH_KEYWORDS, os_WIFSIGNALED__doc__},
-
-static int
-os_WIFSIGNALED_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WIFSIGNALED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WIFSIGNALED", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WIFSIGNALED_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WIFSIGNALED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=f14d106558f406be input=d55ba7cc9ce5dc43]*/
+/*[clinic end generated code: output=2697975771872420 input=d55ba7cc9ce5dc43]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13232,42 +9162,9 @@
 Return True if the process returning status exited via the exit() system call.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WIFEXITED__doc__,
-"WIFEXITED($module, /, status)\n"
-"--\n"
-"\n"
-"Return True if the process returning status exited via the exit() system call.");
-
-#define OS_WIFEXITED_METHODDEF    \
-    {"WIFEXITED", (PyCFunction)os_WIFEXITED, METH_VARARGS|METH_KEYWORDS, os_WIFEXITED__doc__},
-
-static int
-os_WIFEXITED_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WIFEXITED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WIFEXITED", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WIFEXITED_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WIFEXITED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=2f76087d53721255 input=d63775a6791586c0]*/
+/*[clinic end generated code: output=ca8f8c61f0b8532e input=d63775a6791586c0]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13285,42 +9182,9 @@
 Return the process return code from status.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WEXITSTATUS__doc__,
-"WEXITSTATUS($module, /, status)\n"
-"--\n"
-"\n"
-"Return the process return code from status.");
-
-#define OS_WEXITSTATUS_METHODDEF    \
-    {"WEXITSTATUS", (PyCFunction)os_WEXITSTATUS, METH_VARARGS|METH_KEYWORDS, os_WEXITSTATUS__doc__},
-
-static int
-os_WEXITSTATUS_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WEXITSTATUS(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WEXITSTATUS", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WEXITSTATUS_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WEXITSTATUS_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=13b6c270e2a326b1 input=e1fb4944e377585b]*/
+/*[clinic end generated code: output=ea54da23d9e0f6af input=e1fb4944e377585b]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13338,42 +9202,9 @@
 Return the signal that terminated the process that provided the status value.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WTERMSIG__doc__,
-"WTERMSIG($module, /, status)\n"
-"--\n"
-"\n"
-"Return the signal that terminated the process that provided the status value.");
-
-#define OS_WTERMSIG_METHODDEF    \
-    {"WTERMSIG", (PyCFunction)os_WTERMSIG, METH_VARARGS|METH_KEYWORDS, os_WTERMSIG__doc__},
-
-static int
-os_WTERMSIG_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WTERMSIG(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WTERMSIG", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WTERMSIG_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WTERMSIG_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=bf1fd4b002d0a9ed input=727fd7f84ec3f243]*/
+/*[clinic end generated code: output=4d25367026cb852c input=727fd7f84ec3f243]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13391,42 +9222,9 @@
 Return the signal that stopped the process that provided the status value.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_WSTOPSIG__doc__,
-"WSTOPSIG($module, /, status)\n"
-"--\n"
-"\n"
-"Return the signal that stopped the process that provided the status value.");
-
-#define OS_WSTOPSIG_METHODDEF    \
-    {"WSTOPSIG", (PyCFunction)os_WSTOPSIG, METH_VARARGS|METH_KEYWORDS, os_WSTOPSIG__doc__},
-
-static int
-os_WSTOPSIG_impl(PyModuleDef *module, int status);
-
-static PyObject *
-os_WSTOPSIG(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"status", NULL};
-    int status;
-    int _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:WSTOPSIG", _keywords,
-        &status))
-        goto exit;
-    _return_value = os_WSTOPSIG_impl(module, status);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_WSTOPSIG_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=92e1647d29ee0549 input=46ebf1d1b293c5c1]*/
+/*[clinic end generated code: output=54eb9c13b001adb4 input=46ebf1d1b293c5c1]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -13436,39 +9234,6 @@
 #endif /* HAVE_SYS_WAIT_H */
 
 
-#ifndef OS_WCOREDUMP_METHODDEF
-#define OS_WCOREDUMP_METHODDEF
-#endif /* OS_WCOREDUMP_METHODDEF */
-
-#ifndef OS_WIFCONTINUED_METHODDEF
-#define OS_WIFCONTINUED_METHODDEF
-#endif /* OS_WIFCONTINUED_METHODDEF */
-
-#ifndef OS_WIFSTOPPED_METHODDEF
-#define OS_WIFSTOPPED_METHODDEF
-#endif /* OS_WIFSTOPPED_METHODDEF */
-
-#ifndef OS_WIFSIGNALED_METHODDEF
-#define OS_WIFSIGNALED_METHODDEF
-#endif /* OS_WIFSIGNALED_METHODDEF */
-
-#ifndef OS_WIFEXITED_METHODDEF
-#define OS_WIFEXITED_METHODDEF
-#endif /* OS_WIFEXITED_METHODDEF */
-
-#ifndef OS_WEXITSTATUS_METHODDEF
-#define OS_WEXITSTATUS_METHODDEF
-#endif /* OS_WEXITSTATUS_METHODDEF */
-
-#ifndef OS_WTERMSIG_METHODDEF
-#define OS_WTERMSIG_METHODDEF
-#endif /* OS_WTERMSIG_METHODDEF */
-
-#ifndef OS_WSTOPSIG_METHODDEF
-#define OS_WSTOPSIG_METHODDEF
-#endif /* OS_WSTOPSIG_METHODDEF */
-
-
 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
 #ifdef _SCO_DS
 /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
@@ -13531,39 +9296,9 @@
 Equivalent to statvfs(fd).
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fstatvfs__doc__,
-"fstatvfs($module, fd, /)\n"
-"--\n"
-"\n"
-"Perform an fstatvfs system call on the given fd.\n"
-"\n"
-"Equivalent to statvfs(fd).");
-
-#define OS_FSTATVFS_METHODDEF    \
-    {"fstatvfs", (PyCFunction)os_fstatvfs, METH_VARARGS, os_fstatvfs__doc__},
-
-static PyObject *
-os_fstatvfs_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_fstatvfs(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-
-    if (!PyArg_ParseTuple(args,
-        "i:fstatvfs",
-        &fd))
-        goto exit;
-    return_value = os_fstatvfs_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_fstatvfs_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=0e32bf07f946ec0d input=d8122243ac50975e]*/
+/*[clinic end generated code: output=584a94a754497ac0 input=d8122243ac50975e]*/
 {
     int result;
     int async_err = 0;
@@ -13597,45 +9332,9 @@
   If this functionality is unavailable, using it raises an exception.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_statvfs__doc__,
-"statvfs($module, /, path)\n"
-"--\n"
-"\n"
-"Perform a statvfs system call on the given path.\n"
-"\n"
-"path may always be specified as a string.\n"
-"On some platforms, path may also be specified as an open file descriptor.\n"
-"  If this functionality is unavailable, using it raises an exception.");
-
-#define OS_STATVFS_METHODDEF    \
-    {"statvfs", (PyCFunction)os_statvfs, METH_VARARGS|METH_KEYWORDS, os_statvfs__doc__},
-
-static PyObject *
-os_statvfs_impl(PyModuleDef *module, path_t *path);
-
-static PyObject *
-os_statvfs(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", NULL};
-    path_t path = PATH_T_INITIALIZE("statvfs", "path", 0, PATH_HAVE_FSTATVFS);
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&:statvfs", _keywords,
-        path_converter, &path))
-        goto exit;
-    return_value = os_statvfs_impl(module, &path);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_statvfs_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=00ff54983360b446 input=3f5c35791c669bd9]*/
+/*[clinic end generated code: output=5ced07a2cf931f41 input=3f5c35791c669bd9]*/
 {
     int result;
     struct statvfs st;
@@ -13675,38 +9374,9 @@
 Return disk usage statistics about the given path as a (total, free) tuple.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os__getdiskusage__doc__,
-"_getdiskusage($module, /, path)\n"
-"--\n"
-"\n"
-"Return disk usage statistics about the given path as a (total, free) tuple.");
-
-#define OS__GETDISKUSAGE_METHODDEF    \
-    {"_getdiskusage", (PyCFunction)os__getdiskusage, METH_VARARGS|METH_KEYWORDS, os__getdiskusage__doc__},
-
-static PyObject *
-os__getdiskusage_impl(PyModuleDef *module, Py_UNICODE *path);
-
-static PyObject *
-os__getdiskusage(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", NULL};
-    Py_UNICODE *path;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "u:_getdiskusage", _keywords,
-        &path))
-        goto exit;
-    return_value = os__getdiskusage_impl(module, path);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os__getdiskusage_impl(PyModuleDef *module, Py_UNICODE *path)
-/*[clinic end generated code: output=054c972179b13708 input=6458133aed893c78]*/
+/*[clinic end generated code: output=60a9cf33449db1dd input=6458133aed893c78]*/
 {
     BOOL retval;
     ULARGE_INTEGER _, total, free;
@@ -13890,44 +9560,9 @@
 If there is no limit, return -1.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_fpathconf__doc__,
-"fpathconf($module, fd, name, /)\n"
-"--\n"
-"\n"
-"Return the configuration limit name for the file descriptor fd.\n"
-"\n"
-"If there is no limit, return -1.");
-
-#define OS_FPATHCONF_METHODDEF    \
-    {"fpathconf", (PyCFunction)os_fpathconf, METH_VARARGS, os_fpathconf__doc__},
-
-static long
-os_fpathconf_impl(PyModuleDef *module, int fd, int name);
-
-static PyObject *
-os_fpathconf(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int name;
-    long _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "iO&:fpathconf",
-        &fd, conv_path_confname, &name))
-        goto exit;
-    _return_value = os_fpathconf_impl(module, fd, name);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong(_return_value);
-
-exit:
-    return return_value;
-}
-
 static long
 os_fpathconf_impl(PyModuleDef *module, int fd, int name)
-/*[clinic end generated code: output=3bf04b40e0523a8c input=5942a024d3777810]*/
+/*[clinic end generated code: output=082b2922d4441de7 input=5942a024d3777810]*/
 {
     long limit;
 
@@ -13954,50 +9589,9 @@
   If this functionality is unavailable, using it raises an exception.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_pathconf__doc__,
-"pathconf($module, /, path, name)\n"
-"--\n"
-"\n"
-"Return the configuration limit name for the file or directory path.\n"
-"\n"
-"If there is no limit, return -1.\n"
-"On some platforms, path may also be specified as an open file descriptor.\n"
-"  If this functionality is unavailable, using it raises an exception.");
-
-#define OS_PATHCONF_METHODDEF    \
-    {"pathconf", (PyCFunction)os_pathconf, METH_VARARGS|METH_KEYWORDS, os_pathconf__doc__},
-
-static long
-os_pathconf_impl(PyModuleDef *module, path_t *path, int name);
-
-static PyObject *
-os_pathconf(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "name", NULL};
-    path_t path = PATH_T_INITIALIZE("pathconf", "path", 0, PATH_HAVE_FPATHCONF);
-    int name;
-    long _return_value;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&:pathconf", _keywords,
-        path_converter, &path, conv_path_confname, &name))
-        goto exit;
-    _return_value = os_pathconf_impl(module, &path, name);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong(_return_value);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static long
 os_pathconf_impl(PyModuleDef *module, path_t *path, int name)
-/*[clinic end generated code: output=1a53e125b6cf63e4 input=bc3e2a985af27e5e]*/
+/*[clinic end generated code: output=3713029e9501f5ab input=bc3e2a985af27e5e]*/
 {
     long limit;
 
@@ -14192,37 +9786,9 @@
 Return a string-valued system configuration variable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_confstr__doc__,
-"confstr($module, name, /)\n"
-"--\n"
-"\n"
-"Return a string-valued system configuration variable.");
-
-#define OS_CONFSTR_METHODDEF    \
-    {"confstr", (PyCFunction)os_confstr, METH_VARARGS, os_confstr__doc__},
-
-static PyObject *
-os_confstr_impl(PyModuleDef *module, int name);
-
-static PyObject *
-os_confstr(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int name;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:confstr",
-        conv_confstr_confname, &name))
-        goto exit;
-    return_value = os_confstr_impl(module, name);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_confstr_impl(PyModuleDef *module, int name)
-/*[clinic end generated code: output=3f5e8aba9f8e3174 input=18fb4d0567242e65]*/
+/*[clinic end generated code: output=6ff79c9eed8c2daf input=18fb4d0567242e65]*/
 {
     PyObject *result = NULL;
     char buffer[255];
@@ -14761,6 +10327,8 @@
                            / sizeof(struct constdef));
 }
 
+#include "clinic/posixmodule.c.h"
+
 
 /*[clinic input]
 os.sysconf -> long
@@ -14770,41 +10338,9 @@
 Return an integer-valued system configuration variable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_sysconf__doc__,
-"sysconf($module, name, /)\n"
-"--\n"
-"\n"
-"Return an integer-valued system configuration variable.");
-
-#define OS_SYSCONF_METHODDEF    \
-    {"sysconf", (PyCFunction)os_sysconf, METH_VARARGS, os_sysconf__doc__},
-
-static long
-os_sysconf_impl(PyModuleDef *module, int name);
-
-static PyObject *
-os_sysconf(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int name;
-    long _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:sysconf",
-        conv_sysconf_confname, &name))
-        goto exit;
-    _return_value = os_sysconf_impl(module, name);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyLong_FromLong(_return_value);
-
-exit:
-    return return_value;
-}
-
 static long
 os_sysconf_impl(PyModuleDef *module, int name)
-/*[clinic end generated code: output=7b06dfdc472431e4 input=279e3430a33f29e4]*/
+/*[clinic end generated code: output=ed567306f58d69c4 input=279e3430a33f29e4]*/
 {
     long value;
 
@@ -14900,30 +10436,9 @@
 on the hosting operating system.  This function never returns.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_abort__doc__,
-"abort($module, /)\n"
-"--\n"
-"\n"
-"Abort the interpreter immediately.\n"
-"\n"
-"This function \'dumps core\' or otherwise fails in the hardest way possible\n"
-"on the hosting operating system.  This function never returns.");
-
-#define OS_ABORT_METHODDEF    \
-    {"abort", (PyCFunction)os_abort, METH_NOARGS, os_abort__doc__},
-
-static PyObject *
-os_abort_impl(PyModuleDef *module);
-
-static PyObject *
-os_abort(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_abort_impl(module);
-}
-
 static PyObject *
 os_abort_impl(PyModuleDef *module)
-/*[clinic end generated code: output=cded2cc8c5453d3a input=cf2c7d98bc504047]*/
+/*[clinic end generated code: output=486bb96647c299b3 input=cf2c7d98bc504047]*/
 {
     abort();
     /*NOTREACHED*/
@@ -15079,31 +10594,9 @@
 Raises OSError if the load average was unobtainable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getloadavg__doc__,
-"getloadavg($module, /)\n"
-"--\n"
-"\n"
-"Return average recent system load information.\n"
-"\n"
-"Return the number of processes in the system run queue averaged over\n"
-"the last 1, 5, and 15 minutes as a tuple of three floats.\n"
-"Raises OSError if the load average was unobtainable.");
-
-#define OS_GETLOADAVG_METHODDEF    \
-    {"getloadavg", (PyCFunction)os_getloadavg, METH_NOARGS, os_getloadavg__doc__},
-
-static PyObject *
-os_getloadavg_impl(PyModuleDef *module);
-
-static PyObject *
-os_getloadavg(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getloadavg_impl(module);
-}
-
 static PyObject *
 os_getloadavg_impl(PyModuleDef *module)
-/*[clinic end generated code: output=67593a92457d55af input=3d6d826b76d8a34e]*/
+/*[clinic end generated code: output=2b64c5b675d74c14 input=3d6d826b76d8a34e]*/
 {
     double loadavg[3];
     if (getloadavg(loadavg, 3)!=3) {
@@ -15125,41 +10618,9 @@
 If the device is not a terminal, return None.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_device_encoding__doc__,
-"device_encoding($module, /, fd)\n"
-"--\n"
-"\n"
-"Return a string describing the encoding of a terminal\'s file descriptor.\n"
-"\n"
-"The file descriptor must be attached to a terminal.\n"
-"If the device is not a terminal, return None.");
-
-#define OS_DEVICE_ENCODING_METHODDEF    \
-    {"device_encoding", (PyCFunction)os_device_encoding, METH_VARARGS|METH_KEYWORDS, os_device_encoding__doc__},
-
-static PyObject *
-os_device_encoding_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_device_encoding(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"fd", NULL};
-    int fd;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "i:device_encoding", _keywords,
-        &fd))
-        goto exit;
-    return_value = os_device_encoding_impl(module, fd);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_device_encoding_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=e9f8274d42f5cce3 input=9e1d4a42b66df312]*/
+/*[clinic end generated code: output=34f14e33468419c1 input=9e1d4a42b66df312]*/
 {
     return _Py_device_encoding(fd);
 }
@@ -15177,39 +10638,9 @@
 Set the current process's real, effective, and saved user ids.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setresuid__doc__,
-"setresuid($module, ruid, euid, suid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s real, effective, and saved user ids.");
-
-#define OS_SETRESUID_METHODDEF    \
-    {"setresuid", (PyCFunction)os_setresuid, METH_VARARGS, os_setresuid__doc__},
-
-static PyObject *
-os_setresuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid, uid_t suid);
-
-static PyObject *
-os_setresuid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    uid_t ruid;
-    uid_t euid;
-    uid_t suid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&O&O&:setresuid",
-        _Py_Uid_Converter, &ruid, _Py_Uid_Converter, &euid, _Py_Uid_Converter, &suid))
-        goto exit;
-    return_value = os_setresuid_impl(module, ruid, euid, suid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setresuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid, uid_t suid)
-/*[clinic end generated code: output=2e3457cfe7cd1f94 input=9e33cb79a82792f3]*/
+/*[clinic end generated code: output=92cc330812c6ed0f input=9e33cb79a82792f3]*/
 {
     if (setresuid(ruid, euid, suid) < 0)
         return posix_error();
@@ -15230,39 +10661,9 @@
 Set the current process's real, effective, and saved group ids.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setresgid__doc__,
-"setresgid($module, rgid, egid, sgid, /)\n"
-"--\n"
-"\n"
-"Set the current process\'s real, effective, and saved group ids.");
-
-#define OS_SETRESGID_METHODDEF    \
-    {"setresgid", (PyCFunction)os_setresgid, METH_VARARGS, os_setresgid__doc__},
-
-static PyObject *
-os_setresgid_impl(PyModuleDef *module, gid_t rgid, gid_t egid, gid_t sgid);
-
-static PyObject *
-os_setresgid(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    gid_t rgid;
-    gid_t egid;
-    gid_t sgid;
-
-    if (!PyArg_ParseTuple(args,
-        "O&O&O&:setresgid",
-        _Py_Gid_Converter, &rgid, _Py_Gid_Converter, &egid, _Py_Gid_Converter, &sgid))
-        goto exit;
-    return_value = os_setresgid_impl(module, rgid, egid, sgid);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_setresgid_impl(PyModuleDef *module, gid_t rgid, gid_t egid, gid_t sgid)
-/*[clinic end generated code: output=8a7ee6c1f2482362 input=33e9e0785ef426b1]*/
+/*[clinic end generated code: output=e91dc4842a604429 input=33e9e0785ef426b1]*/
 {
     if (setresgid(rgid, egid, sgid) < 0)
         return posix_error();
@@ -15278,27 +10679,9 @@
 Return a tuple of the current process's real, effective, and saved user ids.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getresuid__doc__,
-"getresuid($module, /)\n"
-"--\n"
-"\n"
-"Return a tuple of the current process\'s real, effective, and saved user ids.");
-
-#define OS_GETRESUID_METHODDEF    \
-    {"getresuid", (PyCFunction)os_getresuid, METH_NOARGS, os_getresuid__doc__},
-
-static PyObject *
-os_getresuid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getresuid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getresuid_impl(module);
-}
-
 static PyObject *
 os_getresuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d0786686a6ef1320 input=41ccfa8e1f6517ad]*/
+/*[clinic end generated code: output=9ddef62faae8e477 input=41ccfa8e1f6517ad]*/
 {
     uid_t ruid, euid, suid;
     if (getresuid(&ruid, &euid, &suid) < 0)
@@ -15317,27 +10700,9 @@
 Return a tuple of the current process's real, effective, and saved group ids.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getresgid__doc__,
-"getresgid($module, /)\n"
-"--\n"
-"\n"
-"Return a tuple of the current process\'s real, effective, and saved group ids.");
-
-#define OS_GETRESGID_METHODDEF    \
-    {"getresgid", (PyCFunction)os_getresgid, METH_NOARGS, os_getresgid__doc__},
-
-static PyObject *
-os_getresgid_impl(PyModuleDef *module);
-
-static PyObject *
-os_getresgid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_getresgid_impl(module);
-}
-
 static PyObject *
 os_getresgid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=05249ac795fa759f input=517e68db9ca32df6]*/
+/*[clinic end generated code: output=e1a553cbcf16234c input=517e68db9ca32df6]*/
 {
     gid_t rgid, egid, sgid;
     if (getresgid(&rgid, &egid, &sgid) < 0)
@@ -15367,50 +10732,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_getxattr__doc__,
-"getxattr($module, /, path, attribute, *, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Return the value of extended attribute attribute on path.\n"
-"\n"
-"path may be either a string or an open file descriptor.\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, getxattr will examine the symbolic link itself instead of the file\n"
-"  the link points to.");
-
-#define OS_GETXATTR_METHODDEF    \
-    {"getxattr", (PyCFunction)os_getxattr, METH_VARARGS|METH_KEYWORDS, os_getxattr__doc__},
-
-static PyObject *
-os_getxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, int follow_symlinks);
-
-static PyObject *
-os_getxattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "attribute", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("getxattr", "path", 0, 1);
-    path_t attribute = PATH_T_INITIALIZE("getxattr", "attribute", 0, 0);
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&|$p:getxattr", _keywords,
-        path_converter, &path, path_converter, &attribute, &follow_symlinks))
-        goto exit;
-    return_value = os_getxattr_impl(module, &path, &attribute, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-    /* Cleanup for attribute */
-    path_cleanup(&attribute);
-
-    return return_value;
-}
-
 static PyObject *
 os_getxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, int follow_symlinks)
-/*[clinic end generated code: output=bbc9454fe2b9ea86 input=8c8ea3bab78d89c2]*/
+/*[clinic end generated code: output=d90086b314859f8b input=8c8ea3bab78d89c2]*/
 {
     Py_ssize_t i;
     PyObject *buffer = NULL;
@@ -15479,56 +10803,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_setxattr__doc__,
-"setxattr($module, /, path, attribute, value, flags=0, *,\n"
-"         follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Set extended attribute attribute on path to value.\n"
-"\n"
-"path may be either a string or an open file descriptor.\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, setxattr will modify the symbolic link itself instead of the file\n"
-"  the link points to.");
-
-#define OS_SETXATTR_METHODDEF    \
-    {"setxattr", (PyCFunction)os_setxattr, METH_VARARGS|METH_KEYWORDS, os_setxattr__doc__},
-
-static PyObject *
-os_setxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, Py_buffer *value, int flags, int follow_symlinks);
-
-static PyObject *
-os_setxattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "attribute", "value", "flags", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("setxattr", "path", 0, 1);
-    path_t attribute = PATH_T_INITIALIZE("setxattr", "attribute", 0, 0);
-    Py_buffer value = {NULL, NULL};
-    int flags = 0;
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&y*|i$p:setxattr", _keywords,
-        path_converter, &path, path_converter, &attribute, &value, &flags, &follow_symlinks))
-        goto exit;
-    return_value = os_setxattr_impl(module, &path, &attribute, &value, flags, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-    /* Cleanup for attribute */
-    path_cleanup(&attribute);
-    /* Cleanup for value */
-    if (value.obj)
-       PyBuffer_Release(&value);
-
-    return return_value;
-}
-
 static PyObject *
 os_setxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, Py_buffer *value, int flags, int follow_symlinks)
-/*[clinic end generated code: output=2ff845d8e024b218 input=f0d26833992015c2]*/
+/*[clinic end generated code: output=e3defa5c4b1ad0ae input=f0d26833992015c2]*/
 {
     ssize_t result;
 
@@ -15573,50 +10850,9 @@
 
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_removexattr__doc__,
-"removexattr($module, /, path, attribute, *, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Remove extended attribute attribute on path.\n"
-"\n"
-"path may be either a string or an open file descriptor.\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, removexattr will modify the symbolic link itself instead of the file\n"
-"  the link points to.");
-
-#define OS_REMOVEXATTR_METHODDEF    \
-    {"removexattr", (PyCFunction)os_removexattr, METH_VARARGS|METH_KEYWORDS, os_removexattr__doc__},
-
-static PyObject *
-os_removexattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, int follow_symlinks);
-
-static PyObject *
-os_removexattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "attribute", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("removexattr", "path", 0, 1);
-    path_t attribute = PATH_T_INITIALIZE("removexattr", "attribute", 0, 0);
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "O&O&|$p:removexattr", _keywords,
-        path_converter, &path, path_converter, &attribute, &follow_symlinks))
-        goto exit;
-    return_value = os_removexattr_impl(module, &path, &attribute, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-    /* Cleanup for attribute */
-    path_cleanup(&attribute);
-
-    return return_value;
-}
-
 static PyObject *
 os_removexattr_impl(PyModuleDef *module, path_t *path, path_t *attribute, int follow_symlinks)
-/*[clinic end generated code: output=8dfc715bf607c4cf input=cdb54834161e3329]*/
+/*[clinic end generated code: output=4870ec90249af875 input=cdb54834161e3329]*/
 {
     ssize_t result;
 
@@ -15656,48 +10892,9 @@
   the link points to.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_listxattr__doc__,
-"listxattr($module, /, path=None, *, follow_symlinks=True)\n"
-"--\n"
-"\n"
-"Return a list of extended attributes on path.\n"
-"\n"
-"path may be either None, a string, or an open file descriptor.\n"
-"if path is None, listxattr will examine the current directory.\n"
-"If follow_symlinks is False, and the last element of the path is a symbolic\n"
-"  link, listxattr will examine the symbolic link itself instead of the file\n"
-"  the link points to.");
-
-#define OS_LISTXATTR_METHODDEF    \
-    {"listxattr", (PyCFunction)os_listxattr, METH_VARARGS|METH_KEYWORDS, os_listxattr__doc__},
-
-static PyObject *
-os_listxattr_impl(PyModuleDef *module, path_t *path, int follow_symlinks);
-
-static PyObject *
-os_listxattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"path", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("listxattr", "path", 1, 1);
-    int follow_symlinks = 1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O&$p:listxattr", _keywords,
-        path_converter, &path, &follow_symlinks))
-        goto exit;
-    return_value = os_listxattr_impl(module, &path, follow_symlinks);
-
-exit:
-    /* Cleanup for path */
-    path_cleanup(&path);
-
-    return return_value;
-}
-
 static PyObject *
 os_listxattr_impl(PyModuleDef *module, path_t *path, int follow_symlinks)
-/*[clinic end generated code: output=3104cafda1a3d887 input=08cca53ac0b07c13]*/
+/*[clinic end generated code: output=a87ad6ce56e42a4f input=08cca53ac0b07c13]*/
 {
     Py_ssize_t i;
     PyObject *result = NULL;
@@ -15789,37 +10986,9 @@
 Return a bytes object containing random bytes suitable for cryptographic use.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_urandom__doc__,
-"urandom($module, size, /)\n"
-"--\n"
-"\n"
-"Return a bytes object containing random bytes suitable for cryptographic use.");
-
-#define OS_URANDOM_METHODDEF    \
-    {"urandom", (PyCFunction)os_urandom, METH_VARARGS, os_urandom__doc__},
-
-static PyObject *
-os_urandom_impl(PyModuleDef *module, Py_ssize_t size);
-
-static PyObject *
-os_urandom(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_ssize_t size;
-
-    if (!PyArg_ParseTuple(args,
-        "n:urandom",
-        &size))
-        goto exit;
-    return_value = os_urandom_impl(module, size);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_urandom_impl(PyModuleDef *module, Py_ssize_t size)
-/*[clinic end generated code: output=5dbff582cab94cb9 input=4067cdb1b6776c29]*/
+/*[clinic end generated code: output=e0011f021501f03b input=4067cdb1b6776c29]*/
 {
     PyObject *bytes;
     int result;
@@ -15954,27 +11123,9 @@
 Return the number of CPUs in the system; return None if indeterminable.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_cpu_count__doc__,
-"cpu_count($module, /)\n"
-"--\n"
-"\n"
-"Return the number of CPUs in the system; return None if indeterminable.");
-
-#define OS_CPU_COUNT_METHODDEF    \
-    {"cpu_count", (PyCFunction)os_cpu_count, METH_NOARGS, os_cpu_count__doc__},
-
-static PyObject *
-os_cpu_count_impl(PyModuleDef *module);
-
-static PyObject *
-os_cpu_count(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return os_cpu_count_impl(module);
-}
-
 static PyObject *
 os_cpu_count_impl(PyModuleDef *module)
-/*[clinic end generated code: output=92e2a4a729eb7740 input=d55e2f8f3823a628]*/
+/*[clinic end generated code: output=c59ee7f6bce832b8 input=d55e2f8f3823a628]*/
 {
     int ncpu = 0;
 #ifdef MS_WINDOWS
@@ -16013,41 +11164,9 @@
 Get the close-on-exe flag of the specified file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_get_inheritable__doc__,
-"get_inheritable($module, fd, /)\n"
-"--\n"
-"\n"
-"Get the close-on-exe flag of the specified file descriptor.");
-
-#define OS_GET_INHERITABLE_METHODDEF    \
-    {"get_inheritable", (PyCFunction)os_get_inheritable, METH_VARARGS, os_get_inheritable__doc__},
-
-static int
-os_get_inheritable_impl(PyModuleDef *module, int fd);
-
-static PyObject *
-os_get_inheritable(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "i:get_inheritable",
-        &fd))
-        goto exit;
-    _return_value = os_get_inheritable_impl(module, fd);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_get_inheritable_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=261d1dd2b0dbdc35 input=89ac008dc9ab6b95]*/
+/*[clinic end generated code: output=36110bb36efaa21e input=89ac008dc9ab6b95]*/
 {
     if (!_PyVerify_fd(fd)){
         posix_error();
@@ -16067,38 +11186,9 @@
 Set the inheritable flag of the specified file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_set_inheritable__doc__,
-"set_inheritable($module, fd, inheritable, /)\n"
-"--\n"
-"\n"
-"Set the inheritable flag of the specified file descriptor.");
-
-#define OS_SET_INHERITABLE_METHODDEF    \
-    {"set_inheritable", (PyCFunction)os_set_inheritable, METH_VARARGS, os_set_inheritable__doc__},
-
-static PyObject *
-os_set_inheritable_impl(PyModuleDef *module, int fd, int inheritable);
-
-static PyObject *
-os_set_inheritable(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int fd;
-    int inheritable;
-
-    if (!PyArg_ParseTuple(args,
-        "ii:set_inheritable",
-        &fd, &inheritable))
-        goto exit;
-    return_value = os_set_inheritable_impl(module, fd, inheritable);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_set_inheritable_impl(PyModuleDef *module, int fd, int inheritable)
-/*[clinic end generated code: output=64dfe5e15c906539 input=9ceaead87a1e2402]*/
+/*[clinic end generated code: output=2ac5c6ce8623f045 input=9ceaead87a1e2402]*/
 {
     if (!_PyVerify_fd(fd))
         return posix_error();
@@ -16118,41 +11208,9 @@
 Get the close-on-exe flag of the specified file descriptor.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_get_handle_inheritable__doc__,
-"get_handle_inheritable($module, handle, /)\n"
-"--\n"
-"\n"
-"Get the close-on-exe flag of the specified file descriptor.");
-
-#define OS_GET_HANDLE_INHERITABLE_METHODDEF    \
-    {"get_handle_inheritable", (PyCFunction)os_get_handle_inheritable, METH_VARARGS, os_get_handle_inheritable__doc__},
-
-static int
-os_get_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle);
-
-static PyObject *
-os_get_handle_inheritable(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_intptr_t handle;
-    int _return_value;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_INTPTR ":get_handle_inheritable",
-        &handle))
-        goto exit;
-    _return_value = os_get_handle_inheritable_impl(module, handle);
-    if ((_return_value == -1) && PyErr_Occurred())
-        goto exit;
-    return_value = PyBool_FromLong((long)_return_value);
-
-exit:
-    return return_value;
-}
-
 static int
 os_get_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle)
-/*[clinic end generated code: output=d5bf9d86900bf457 input=5f7759443aae3dc5]*/
+/*[clinic end generated code: output=3b7b3e1b43f312b6 input=5f7759443aae3dc5]*/
 {
     DWORD flags;
 
@@ -16174,38 +11232,9 @@
 Set the inheritable flag of the specified handle.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(os_set_handle_inheritable__doc__,
-"set_handle_inheritable($module, handle, inheritable, /)\n"
-"--\n"
-"\n"
-"Set the inheritable flag of the specified handle.");
-
-#define OS_SET_HANDLE_INHERITABLE_METHODDEF    \
-    {"set_handle_inheritable", (PyCFunction)os_set_handle_inheritable, METH_VARARGS, os_set_handle_inheritable__doc__},
-
-static PyObject *
-os_set_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle, int inheritable);
-
-static PyObject *
-os_set_handle_inheritable(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_intptr_t handle;
-    int inheritable;
-
-    if (!PyArg_ParseTuple(args,
-        "" _Py_PARSE_INTPTR "p:set_handle_inheritable",
-        &handle, &inheritable))
-        goto exit;
-    return_value = os_set_handle_inheritable_impl(module, handle, inheritable);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 os_set_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle, int inheritable)
-/*[clinic end generated code: output=ee5fcc6d9f0d4f8b input=e64b2b2730469def]*/
+/*[clinic end generated code: output=627aa5b158b69338 input=e64b2b2730469def]*/
 {
     DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
     if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
@@ -17045,471 +12074,7 @@
 /*[clinic input]
 dump buffer
 [clinic start generated code]*/
-
-#ifndef OS_TTYNAME_METHODDEF
-    #define OS_TTYNAME_METHODDEF
-#endif /* !defined(OS_TTYNAME_METHODDEF) */
-
-#ifndef OS_CTERMID_METHODDEF
-    #define OS_CTERMID_METHODDEF
-#endif /* !defined(OS_CTERMID_METHODDEF) */
-
-#ifndef OS_FCHDIR_METHODDEF
-    #define OS_FCHDIR_METHODDEF
-#endif /* !defined(OS_FCHDIR_METHODDEF) */
-
-#ifndef OS_FCHMOD_METHODDEF
-    #define OS_FCHMOD_METHODDEF
-#endif /* !defined(OS_FCHMOD_METHODDEF) */
-
-#ifndef OS_LCHMOD_METHODDEF
-    #define OS_LCHMOD_METHODDEF
-#endif /* !defined(OS_LCHMOD_METHODDEF) */
-
-#ifndef OS_CHFLAGS_METHODDEF
-    #define OS_CHFLAGS_METHODDEF
-#endif /* !defined(OS_CHFLAGS_METHODDEF) */
-
-#ifndef OS_LCHFLAGS_METHODDEF
-    #define OS_LCHFLAGS_METHODDEF
-#endif /* !defined(OS_LCHFLAGS_METHODDEF) */
-
-#ifndef OS_CHROOT_METHODDEF
-    #define OS_CHROOT_METHODDEF
-#endif /* !defined(OS_CHROOT_METHODDEF) */
-
-#ifndef OS_FSYNC_METHODDEF
-    #define OS_FSYNC_METHODDEF
-#endif /* !defined(OS_FSYNC_METHODDEF) */
-
-#ifndef OS_SYNC_METHODDEF
-    #define OS_SYNC_METHODDEF
-#endif /* !defined(OS_SYNC_METHODDEF) */
-
-#ifndef OS_FDATASYNC_METHODDEF
-    #define OS_FDATASYNC_METHODDEF
-#endif /* !defined(OS_FDATASYNC_METHODDEF) */
-
-#ifndef OS_CHOWN_METHODDEF
-    #define OS_CHOWN_METHODDEF
-#endif /* !defined(OS_CHOWN_METHODDEF) */
-
-#ifndef OS_FCHOWN_METHODDEF
-    #define OS_FCHOWN_METHODDEF
-#endif /* !defined(OS_FCHOWN_METHODDEF) */
-
-#ifndef OS_LCHOWN_METHODDEF
-    #define OS_LCHOWN_METHODDEF
-#endif /* !defined(OS_LCHOWN_METHODDEF) */
-
-#ifndef OS_LINK_METHODDEF
-    #define OS_LINK_METHODDEF
-#endif /* !defined(OS_LINK_METHODDEF) */
-
-#ifndef OS__GETFINALPATHNAME_METHODDEF
-    #define OS__GETFINALPATHNAME_METHODDEF
-#endif /* !defined(OS__GETFINALPATHNAME_METHODDEF) */
-
-#ifndef OS__GETVOLUMEPATHNAME_METHODDEF
-    #define OS__GETVOLUMEPATHNAME_METHODDEF
-#endif /* !defined(OS__GETVOLUMEPATHNAME_METHODDEF) */
-
-#ifndef OS_NICE_METHODDEF
-    #define OS_NICE_METHODDEF
-#endif /* !defined(OS_NICE_METHODDEF) */
-
-#ifndef OS_GETPRIORITY_METHODDEF
-    #define OS_GETPRIORITY_METHODDEF
-#endif /* !defined(OS_GETPRIORITY_METHODDEF) */
-
-#ifndef OS_SETPRIORITY_METHODDEF
-    #define OS_SETPRIORITY_METHODDEF
-#endif /* !defined(OS_SETPRIORITY_METHODDEF) */
-
-#ifndef OS_SYSTEM_METHODDEF
-    #define OS_SYSTEM_METHODDEF
-#endif /* !defined(OS_SYSTEM_METHODDEF) */
-
-#ifndef OS_UNAME_METHODDEF
-    #define OS_UNAME_METHODDEF
-#endif /* !defined(OS_UNAME_METHODDEF) */
-
-#ifndef OS_EXECV_METHODDEF
-    #define OS_EXECV_METHODDEF
-#endif /* !defined(OS_EXECV_METHODDEF) */
-
-#ifndef OS_EXECVE_METHODDEF
-    #define OS_EXECVE_METHODDEF
-#endif /* !defined(OS_EXECVE_METHODDEF) */
-
-#ifndef OS_SPAWNV_METHODDEF
-    #define OS_SPAWNV_METHODDEF
-#endif /* !defined(OS_SPAWNV_METHODDEF) */
-
-#ifndef OS_SPAWNVE_METHODDEF
-    #define OS_SPAWNVE_METHODDEF
-#endif /* !defined(OS_SPAWNVE_METHODDEF) */
-
-#ifndef OS_FORK1_METHODDEF
-    #define OS_FORK1_METHODDEF
-#endif /* !defined(OS_FORK1_METHODDEF) */
-
-#ifndef OS_FORK_METHODDEF
-    #define OS_FORK_METHODDEF
-#endif /* !defined(OS_FORK_METHODDEF) */
-
-#ifndef OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-    #define OS_SCHED_GET_PRIORITY_MAX_METHODDEF
-#endif /* !defined(OS_SCHED_GET_PRIORITY_MAX_METHODDEF) */
-
-#ifndef OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-    #define OS_SCHED_GET_PRIORITY_MIN_METHODDEF
-#endif /* !defined(OS_SCHED_GET_PRIORITY_MIN_METHODDEF) */
-
-#ifndef OS_SCHED_GETSCHEDULER_METHODDEF
-    #define OS_SCHED_GETSCHEDULER_METHODDEF
-#endif /* !defined(OS_SCHED_GETSCHEDULER_METHODDEF) */
-
-#ifndef OS_SCHED_SETSCHEDULER_METHODDEF
-    #define OS_SCHED_SETSCHEDULER_METHODDEF
-#endif /* !defined(OS_SCHED_SETSCHEDULER_METHODDEF) */
-
-#ifndef OS_SCHED_GETPARAM_METHODDEF
-    #define OS_SCHED_GETPARAM_METHODDEF
-#endif /* !defined(OS_SCHED_GETPARAM_METHODDEF) */
-
-#ifndef OS_SCHED_SETPARAM_METHODDEF
-    #define OS_SCHED_SETPARAM_METHODDEF
-#endif /* !defined(OS_SCHED_SETPARAM_METHODDEF) */
-
-#ifndef OS_SCHED_RR_GET_INTERVAL_METHODDEF
-    #define OS_SCHED_RR_GET_INTERVAL_METHODDEF
-#endif /* !defined(OS_SCHED_RR_GET_INTERVAL_METHODDEF) */
-
-#ifndef OS_SCHED_YIELD_METHODDEF
-    #define OS_SCHED_YIELD_METHODDEF
-#endif /* !defined(OS_SCHED_YIELD_METHODDEF) */
-
-#ifndef OS_SCHED_SETAFFINITY_METHODDEF
-    #define OS_SCHED_SETAFFINITY_METHODDEF
-#endif /* !defined(OS_SCHED_SETAFFINITY_METHODDEF) */
-
-#ifndef OS_SCHED_GETAFFINITY_METHODDEF
-    #define OS_SCHED_GETAFFINITY_METHODDEF
-#endif /* !defined(OS_SCHED_GETAFFINITY_METHODDEF) */
-
-#ifndef OS_OPENPTY_METHODDEF
-    #define OS_OPENPTY_METHODDEF
-#endif /* !defined(OS_OPENPTY_METHODDEF) */
-
-#ifndef OS_FORKPTY_METHODDEF
-    #define OS_FORKPTY_METHODDEF
-#endif /* !defined(OS_FORKPTY_METHODDEF) */
-
-#ifndef OS_GETEGID_METHODDEF
-    #define OS_GETEGID_METHODDEF
-#endif /* !defined(OS_GETEGID_METHODDEF) */
-
-#ifndef OS_GETEUID_METHODDEF
-    #define OS_GETEUID_METHODDEF
-#endif /* !defined(OS_GETEUID_METHODDEF) */
-
-#ifndef OS_GETGID_METHODDEF
-    #define OS_GETGID_METHODDEF
-#endif /* !defined(OS_GETGID_METHODDEF) */
-
-#ifndef OS_GETGROUPS_METHODDEF
-    #define OS_GETGROUPS_METHODDEF
-#endif /* !defined(OS_GETGROUPS_METHODDEF) */
-
-#ifndef OS_GETPGID_METHODDEF
-    #define OS_GETPGID_METHODDEF
-#endif /* !defined(OS_GETPGID_METHODDEF) */
-
-#ifndef OS_GETPGRP_METHODDEF
-    #define OS_GETPGRP_METHODDEF
-#endif /* !defined(OS_GETPGRP_METHODDEF) */
-
-#ifndef OS_SETPGRP_METHODDEF
-    #define OS_SETPGRP_METHODDEF
-#endif /* !defined(OS_SETPGRP_METHODDEF) */
-
-#ifndef OS_GETPPID_METHODDEF
-    #define OS_GETPPID_METHODDEF
-#endif /* !defined(OS_GETPPID_METHODDEF) */
-
-#ifndef OS_GETLOGIN_METHODDEF
-    #define OS_GETLOGIN_METHODDEF
-#endif /* !defined(OS_GETLOGIN_METHODDEF) */
-
-#ifndef OS_GETUID_METHODDEF
-    #define OS_GETUID_METHODDEF
-#endif /* !defined(OS_GETUID_METHODDEF) */
-
-#ifndef OS_KILL_METHODDEF
-    #define OS_KILL_METHODDEF
-#endif /* !defined(OS_KILL_METHODDEF) */
-
-#ifndef OS_KILLPG_METHODDEF
-    #define OS_KILLPG_METHODDEF
-#endif /* !defined(OS_KILLPG_METHODDEF) */
-
-#ifndef OS_PLOCK_METHODDEF
-    #define OS_PLOCK_METHODDEF
-#endif /* !defined(OS_PLOCK_METHODDEF) */
-
-#ifndef OS_SETUID_METHODDEF
-    #define OS_SETUID_METHODDEF
-#endif /* !defined(OS_SETUID_METHODDEF) */
-
-#ifndef OS_SETEUID_METHODDEF
-    #define OS_SETEUID_METHODDEF
-#endif /* !defined(OS_SETEUID_METHODDEF) */
-
-#ifndef OS_SETEGID_METHODDEF
-    #define OS_SETEGID_METHODDEF
-#endif /* !defined(OS_SETEGID_METHODDEF) */
-
-#ifndef OS_SETREUID_METHODDEF
-    #define OS_SETREUID_METHODDEF
-#endif /* !defined(OS_SETREUID_METHODDEF) */
-
-#ifndef OS_SETREGID_METHODDEF
-    #define OS_SETREGID_METHODDEF
-#endif /* !defined(OS_SETREGID_METHODDEF) */
-
-#ifndef OS_SETGID_METHODDEF
-    #define OS_SETGID_METHODDEF
-#endif /* !defined(OS_SETGID_METHODDEF) */
-
-#ifndef OS_SETGROUPS_METHODDEF
-    #define OS_SETGROUPS_METHODDEF
-#endif /* !defined(OS_SETGROUPS_METHODDEF) */
-
-#ifndef OS_WAIT3_METHODDEF
-    #define OS_WAIT3_METHODDEF
-#endif /* !defined(OS_WAIT3_METHODDEF) */
-
-#ifndef OS_WAIT4_METHODDEF
-    #define OS_WAIT4_METHODDEF
-#endif /* !defined(OS_WAIT4_METHODDEF) */
-
-#ifndef OS_WAITID_METHODDEF
-    #define OS_WAITID_METHODDEF
-#endif /* !defined(OS_WAITID_METHODDEF) */
-
-#ifndef OS_WAITPID_METHODDEF
-    #define OS_WAITPID_METHODDEF
-#endif /* !defined(OS_WAITPID_METHODDEF) */
-
-#ifndef OS_WAIT_METHODDEF
-    #define OS_WAIT_METHODDEF
-#endif /* !defined(OS_WAIT_METHODDEF) */
-
-#ifndef OS_SYMLINK_METHODDEF
-    #define OS_SYMLINK_METHODDEF
-#endif /* !defined(OS_SYMLINK_METHODDEF) */
-
-#ifndef OS_TIMES_METHODDEF
-    #define OS_TIMES_METHODDEF
-#endif /* !defined(OS_TIMES_METHODDEF) */
-
-#ifndef OS_GETSID_METHODDEF
-    #define OS_GETSID_METHODDEF
-#endif /* !defined(OS_GETSID_METHODDEF) */
-
-#ifndef OS_SETSID_METHODDEF
-    #define OS_SETSID_METHODDEF
-#endif /* !defined(OS_SETSID_METHODDEF) */
-
-#ifndef OS_SETPGID_METHODDEF
-    #define OS_SETPGID_METHODDEF
-#endif /* !defined(OS_SETPGID_METHODDEF) */
-
-#ifndef OS_TCGETPGRP_METHODDEF
-    #define OS_TCGETPGRP_METHODDEF
-#endif /* !defined(OS_TCGETPGRP_METHODDEF) */
-
-#ifndef OS_TCSETPGRP_METHODDEF
-    #define OS_TCSETPGRP_METHODDEF
-#endif /* !defined(OS_TCSETPGRP_METHODDEF) */
-
-#ifndef OS_LOCKF_METHODDEF
-    #define OS_LOCKF_METHODDEF
-#endif /* !defined(OS_LOCKF_METHODDEF) */
-
-#ifndef OS_READV_METHODDEF
-    #define OS_READV_METHODDEF
-#endif /* !defined(OS_READV_METHODDEF) */
-
-#ifndef OS_PREAD_METHODDEF
-    #define OS_PREAD_METHODDEF
-#endif /* !defined(OS_PREAD_METHODDEF) */
-
-#ifndef OS_PIPE_METHODDEF
-    #define OS_PIPE_METHODDEF
-#endif /* !defined(OS_PIPE_METHODDEF) */
-
-#ifndef OS_PIPE2_METHODDEF
-    #define OS_PIPE2_METHODDEF
-#endif /* !defined(OS_PIPE2_METHODDEF) */
-
-#ifndef OS_WRITEV_METHODDEF
-    #define OS_WRITEV_METHODDEF
-#endif /* !defined(OS_WRITEV_METHODDEF) */
-
-#ifndef OS_PWRITE_METHODDEF
-    #define OS_PWRITE_METHODDEF
-#endif /* !defined(OS_PWRITE_METHODDEF) */
-
-#ifndef OS_MKFIFO_METHODDEF
-    #define OS_MKFIFO_METHODDEF
-#endif /* !defined(OS_MKFIFO_METHODDEF) */
-
-#ifndef OS_MKNOD_METHODDEF
-    #define OS_MKNOD_METHODDEF
-#endif /* !defined(OS_MKNOD_METHODDEF) */
-
-#ifndef OS_MAJOR_METHODDEF
-    #define OS_MAJOR_METHODDEF
-#endif /* !defined(OS_MAJOR_METHODDEF) */
-
-#ifndef OS_MINOR_METHODDEF
-    #define OS_MINOR_METHODDEF
-#endif /* !defined(OS_MINOR_METHODDEF) */
-
-#ifndef OS_MAKEDEV_METHODDEF
-    #define OS_MAKEDEV_METHODDEF
-#endif /* !defined(OS_MAKEDEV_METHODDEF) */
-
-#ifndef OS_FTRUNCATE_METHODDEF
-    #define OS_FTRUNCATE_METHODDEF
-#endif /* !defined(OS_FTRUNCATE_METHODDEF) */
-
-#ifndef OS_TRUNCATE_METHODDEF
-    #define OS_TRUNCATE_METHODDEF
-#endif /* !defined(OS_TRUNCATE_METHODDEF) */
-
-#ifndef OS_POSIX_FALLOCATE_METHODDEF
-    #define OS_POSIX_FALLOCATE_METHODDEF
-#endif /* !defined(OS_POSIX_FALLOCATE_METHODDEF) */
-
-#ifndef OS_POSIX_FADVISE_METHODDEF
-    #define OS_POSIX_FADVISE_METHODDEF
-#endif /* !defined(OS_POSIX_FADVISE_METHODDEF) */
-
-#ifndef OS_PUTENV_METHODDEF
-    #define OS_PUTENV_METHODDEF
-#endif /* !defined(OS_PUTENV_METHODDEF) */
-
-#ifndef OS_UNSETENV_METHODDEF
-    #define OS_UNSETENV_METHODDEF
-#endif /* !defined(OS_UNSETENV_METHODDEF) */
-
-#ifndef OS_WCOREDUMP_METHODDEF
-    #define OS_WCOREDUMP_METHODDEF
-#endif /* !defined(OS_WCOREDUMP_METHODDEF) */
-
-#ifndef OS_WIFCONTINUED_METHODDEF
-    #define OS_WIFCONTINUED_METHODDEF
-#endif /* !defined(OS_WIFCONTINUED_METHODDEF) */
-
-#ifndef OS_WIFSTOPPED_METHODDEF
-    #define OS_WIFSTOPPED_METHODDEF
-#endif /* !defined(OS_WIFSTOPPED_METHODDEF) */
-
-#ifndef OS_WIFSIGNALED_METHODDEF
-    #define OS_WIFSIGNALED_METHODDEF
-#endif /* !defined(OS_WIFSIGNALED_METHODDEF) */
-
-#ifndef OS_WIFEXITED_METHODDEF
-    #define OS_WIFEXITED_METHODDEF
-#endif /* !defined(OS_WIFEXITED_METHODDEF) */
-
-#ifndef OS_WEXITSTATUS_METHODDEF
-    #define OS_WEXITSTATUS_METHODDEF
-#endif /* !defined(OS_WEXITSTATUS_METHODDEF) */
-
-#ifndef OS_WTERMSIG_METHODDEF
-    #define OS_WTERMSIG_METHODDEF
-#endif /* !defined(OS_WTERMSIG_METHODDEF) */
-
-#ifndef OS_WSTOPSIG_METHODDEF
-    #define OS_WSTOPSIG_METHODDEF
-#endif /* !defined(OS_WSTOPSIG_METHODDEF) */
-
-#ifndef OS_FSTATVFS_METHODDEF
-    #define OS_FSTATVFS_METHODDEF
-#endif /* !defined(OS_FSTATVFS_METHODDEF) */
-
-#ifndef OS_STATVFS_METHODDEF
-    #define OS_STATVFS_METHODDEF
-#endif /* !defined(OS_STATVFS_METHODDEF) */
-
-#ifndef OS__GETDISKUSAGE_METHODDEF
-    #define OS__GETDISKUSAGE_METHODDEF
-#endif /* !defined(OS__GETDISKUSAGE_METHODDEF) */
-
-#ifndef OS_FPATHCONF_METHODDEF
-    #define OS_FPATHCONF_METHODDEF
-#endif /* !defined(OS_FPATHCONF_METHODDEF) */
-
-#ifndef OS_PATHCONF_METHODDEF
-    #define OS_PATHCONF_METHODDEF
-#endif /* !defined(OS_PATHCONF_METHODDEF) */
-
-#ifndef OS_CONFSTR_METHODDEF
-    #define OS_CONFSTR_METHODDEF
-#endif /* !defined(OS_CONFSTR_METHODDEF) */
-
-#ifndef OS_SYSCONF_METHODDEF
-    #define OS_SYSCONF_METHODDEF
-#endif /* !defined(OS_SYSCONF_METHODDEF) */
-
-#ifndef OS_GETLOADAVG_METHODDEF
-    #define OS_GETLOADAVG_METHODDEF
-#endif /* !defined(OS_GETLOADAVG_METHODDEF) */
-
-#ifndef OS_SETRESUID_METHODDEF
-    #define OS_SETRESUID_METHODDEF
-#endif /* !defined(OS_SETRESUID_METHODDEF) */
-
-#ifndef OS_SETRESGID_METHODDEF
-    #define OS_SETRESGID_METHODDEF
-#endif /* !defined(OS_SETRESGID_METHODDEF) */
-
-#ifndef OS_GETRESUID_METHODDEF
-    #define OS_GETRESUID_METHODDEF
-#endif /* !defined(OS_GETRESUID_METHODDEF) */
-
-#ifndef OS_GETRESGID_METHODDEF
-    #define OS_GETRESGID_METHODDEF
-#endif /* !defined(OS_GETRESGID_METHODDEF) */
-
-#ifndef OS_GETXATTR_METHODDEF
-    #define OS_GETXATTR_METHODDEF
-#endif /* !defined(OS_GETXATTR_METHODDEF) */
-
-#ifndef OS_SETXATTR_METHODDEF
-    #define OS_SETXATTR_METHODDEF
-#endif /* !defined(OS_SETXATTR_METHODDEF) */
-
-#ifndef OS_REMOVEXATTR_METHODDEF
-    #define OS_REMOVEXATTR_METHODDEF
-#endif /* !defined(OS_REMOVEXATTR_METHODDEF) */
-
-#ifndef OS_LISTXATTR_METHODDEF
-    #define OS_LISTXATTR_METHODDEF
-#endif /* !defined(OS_LISTXATTR_METHODDEF) */
-
-#ifndef OS_GET_HANDLE_INHERITABLE_METHODDEF
-    #define OS_GET_HANDLE_INHERITABLE_METHODDEF
-#endif /* !defined(OS_GET_HANDLE_INHERITABLE_METHODDEF) */
-
-#ifndef OS_SET_HANDLE_INHERITABLE_METHODDEF
-    #define OS_SET_HANDLE_INHERITABLE_METHODDEF
-#endif /* !defined(OS_SET_HANDLE_INHERITABLE_METHODDEF) */
-/*[clinic end generated code: output=b788c2d6010113e8 input=524ce2e021e4eba6]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
 
 
 static PyMethodDef posix_methods[] = {
diff --git a/Modules/pwdmodule.c b/Modules/pwdmodule.c
--- a/Modules/pwdmodule.c
+++ b/Modules/pwdmodule.c
@@ -8,10 +8,9 @@
 
 #include "clinic/pwdmodule.c.h"
 /*[clinic input]
-output preset file
 module pwd
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bbcf68b1f549f917]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=60f628ef356b97b6]*/
 
 static PyStructSequence_Field struct_pwd_type_fields[] = {
     {"pw_name", "user name"},
diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c
--- a/Modules/pyexpat.c
+++ b/Modules/pyexpat.c
@@ -68,6 +68,8 @@
     PyObject **handlers;
 } xmlparseobject;
 
+#include "clinic/pyexpat.c.h"
+
 #define CHARACTER_DATA_BUFFER_SIZE 8192
 
 static PyTypeObject Xmlparsetype;
@@ -713,40 +715,9 @@
 `isfinal' should be true at end of input.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_Parse__doc__,
-"Parse($self, data, isFinal=0, /)\n"
-"--\n"
-"\n"
-"Parse XML data.\n"
-"\n"
-"`isfinal\' should be true at end of input.");
-
-#define PYEXPAT_XMLPARSER_PARSE_METHODDEF    \
-    {"Parse", (PyCFunction)pyexpat_xmlparser_Parse, METH_VARARGS, pyexpat_xmlparser_Parse__doc__},
-
-static PyObject *
-pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyObject *data, int isFinal);
-
-static PyObject *
-pyexpat_xmlparser_Parse(xmlparseobject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *data;
-    int isFinal = 0;
-
-    if (!PyArg_ParseTuple(args,
-        "O|i:Parse",
-        &data, &isFinal))
-        goto exit;
-    return_value = pyexpat_xmlparser_Parse_impl(self, data, isFinal);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyObject *data, int isFinal)
-/*[clinic end generated code: output=65b1652b01f20856 input=e37b81b8948ca7e0]*/
+/*[clinic end generated code: output=2d4dc77f4d434854 input=e37b81b8948ca7e0]*/
 {
     const char *s;
     Py_ssize_t slen;
@@ -836,18 +807,9 @@
 Parse XML data from file-like object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_ParseFile__doc__,
-"ParseFile($self, file, /)\n"
-"--\n"
-"\n"
-"Parse XML data from file-like object.");
-
-#define PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF    \
-    {"ParseFile", (PyCFunction)pyexpat_xmlparser_ParseFile, METH_O, pyexpat_xmlparser_ParseFile__doc__},
-
 static PyObject *
 pyexpat_xmlparser_ParseFile(xmlparseobject *self, PyObject *file)
-/*[clinic end generated code: output=2e13803c3d8c22b2 input=fbb5a12b6038d735]*/
+/*[clinic end generated code: output=2adc6a13100cc42b input=fbb5a12b6038d735]*/
 {
     int rv = 1;
     PyObject *readmethod = NULL;
@@ -894,37 +856,9 @@
 Set the base URL for the parser.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_SetBase__doc__,
-"SetBase($self, base, /)\n"
-"--\n"
-"\n"
-"Set the base URL for the parser.");
-
-#define PYEXPAT_XMLPARSER_SETBASE_METHODDEF    \
-    {"SetBase", (PyCFunction)pyexpat_xmlparser_SetBase, METH_VARARGS, pyexpat_xmlparser_SetBase__doc__},
-
-static PyObject *
-pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base);
-
-static PyObject *
-pyexpat_xmlparser_SetBase(xmlparseobject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    const char *base;
-
-    if (!PyArg_ParseTuple(args,
-        "s:SetBase",
-        &base))
-        goto exit;
-    return_value = pyexpat_xmlparser_SetBase_impl(self, base);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base)
-/*[clinic end generated code: output=5bdb49f6689a5f93 input=c684e5de895ee1a8]*/
+/*[clinic end generated code: output=c212ddceb607b539 input=c684e5de895ee1a8]*/
 {
     if (!XML_SetBase(self->itself, base)) {
         return PyErr_NoMemory();
@@ -938,27 +872,9 @@
 Return base URL string for the parser.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_GetBase__doc__,
-"GetBase($self, /)\n"
-"--\n"
-"\n"
-"Return base URL string for the parser.");
-
-#define PYEXPAT_XMLPARSER_GETBASE_METHODDEF    \
-    {"GetBase", (PyCFunction)pyexpat_xmlparser_GetBase, METH_NOARGS, pyexpat_xmlparser_GetBase__doc__},
-
-static PyObject *
-pyexpat_xmlparser_GetBase_impl(xmlparseobject *self);
-
-static PyObject *
-pyexpat_xmlparser_GetBase(xmlparseobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return pyexpat_xmlparser_GetBase_impl(self);
-}
-
 static PyObject *
 pyexpat_xmlparser_GetBase_impl(xmlparseobject *self)
-/*[clinic end generated code: output=ef6046ee28f2b8ee input=918d71c38009620e]*/
+/*[clinic end generated code: output=2886cb21f9a8739a input=918d71c38009620e]*/
 {
     return Py_BuildValue("z", XML_GetBase(self->itself));
 }
@@ -972,30 +888,9 @@
 for an element with many attributes), not all of the text may be available.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_GetInputContext__doc__,
-"GetInputContext($self, /)\n"
-"--\n"
-"\n"
-"Return the untranslated text of the input that caused the current event.\n"
-"\n"
-"If the event was generated by a large amount of text (such as a start tag\n"
-"for an element with many attributes), not all of the text may be available.");
-
-#define PYEXPAT_XMLPARSER_GETINPUTCONTEXT_METHODDEF    \
-    {"GetInputContext", (PyCFunction)pyexpat_xmlparser_GetInputContext, METH_NOARGS, pyexpat_xmlparser_GetInputContext__doc__},
-
-static PyObject *
-pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self);
-
-static PyObject *
-pyexpat_xmlparser_GetInputContext(xmlparseobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return pyexpat_xmlparser_GetInputContext_impl(self);
-}
-
 static PyObject *
 pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self)
-/*[clinic end generated code: output=62ff03390f074cd2 input=034df8712db68379]*/
+/*[clinic end generated code: output=a88026d683fc22cc input=034df8712db68379]*/
 {
     if (self->in_callback) {
         int offset, size;
@@ -1022,38 +917,9 @@
 Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_ExternalEntityParserCreate__doc__,
-"ExternalEntityParserCreate($self, context, encoding=None, /)\n"
-"--\n"
-"\n"
-"Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.");
-
-#define PYEXPAT_XMLPARSER_EXTERNALENTITYPARSERCREATE_METHODDEF    \
-    {"ExternalEntityParserCreate", (PyCFunction)pyexpat_xmlparser_ExternalEntityParserCreate, METH_VARARGS, pyexpat_xmlparser_ExternalEntityParserCreate__doc__},
-
-static PyObject *
-pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self, const char *context, const char *encoding);
-
-static PyObject *
-pyexpat_xmlparser_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    const char *context;
-    const char *encoding = NULL;
-
-    if (!PyArg_ParseTuple(args,
-        "z|s:ExternalEntityParserCreate",
-        &context, &encoding))
-        goto exit;
-    return_value = pyexpat_xmlparser_ExternalEntityParserCreate_impl(self, context, encoding);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self, const char *context, const char *encoding)
-/*[clinic end generated code: output=4948c35f3dd01133 input=283206575d960272]*/
+/*[clinic end generated code: output=942f300ed0e56054 input=283206575d960272]*/
 {
     xmlparseobject *new_parser;
     int i;
@@ -1127,42 +993,9 @@
 was successful.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_SetParamEntityParsing__doc__,
-"SetParamEntityParsing($self, flag, /)\n"
-"--\n"
-"\n"
-"Controls parsing of parameter entities (including the external DTD subset).\n"
-"\n"
-"Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,\n"
-"XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and\n"
-"XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag\n"
-"was successful.");
-
-#define PYEXPAT_XMLPARSER_SETPARAMENTITYPARSING_METHODDEF    \
-    {"SetParamEntityParsing", (PyCFunction)pyexpat_xmlparser_SetParamEntityParsing, METH_VARARGS, pyexpat_xmlparser_SetParamEntityParsing__doc__},
-
-static PyObject *
-pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag);
-
-static PyObject *
-pyexpat_xmlparser_SetParamEntityParsing(xmlparseobject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int flag;
-
-    if (!PyArg_ParseTuple(args,
-        "i:SetParamEntityParsing",
-        &flag))
-        goto exit;
-    return_value = pyexpat_xmlparser_SetParamEntityParsing_impl(self, flag);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag)
-/*[clinic end generated code: output=0f820882bc7768cc input=8aea19b4b15e9af1]*/
+/*[clinic end generated code: output=18668ee8e760d64c input=8aea19b4b15e9af1]*/
 {
     flag = XML_SetParamEntityParsing(self->itself, flag);
     return PyLong_FromLong(flag);
@@ -1183,41 +1016,9 @@
 information to the parser. 'flag' defaults to True if not provided.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser_UseForeignDTD__doc__,
-"UseForeignDTD($self, flag=True, /)\n"
-"--\n"
-"\n"
-"Allows the application to provide an artificial external subset if one is not specified as part of the document instance.\n"
-"\n"
-"This readily allows the use of a \'default\' document type controlled by the\n"
-"application, while still getting the advantage of providing document type\n"
-"information to the parser. \'flag\' defaults to True if not provided.");
-
-#define PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF    \
-    {"UseForeignDTD", (PyCFunction)pyexpat_xmlparser_UseForeignDTD, METH_VARARGS, pyexpat_xmlparser_UseForeignDTD__doc__},
-
-static PyObject *
-pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, int flag);
-
-static PyObject *
-pyexpat_xmlparser_UseForeignDTD(xmlparseobject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int flag = 1;
-
-    if (!PyArg_ParseTuple(args,
-        "|p:UseForeignDTD",
-        &flag))
-        goto exit;
-    return_value = pyexpat_xmlparser_UseForeignDTD_impl(self, flag);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, int flag)
-/*[clinic end generated code: output=22e924ae6cad67d6 input=78144c519d116a6e]*/
+/*[clinic end generated code: output=cfaa9aa50bb0f65c input=78144c519d116a6e]*/
 {
     enum XML_Error rc;
 
@@ -1234,25 +1035,9 @@
 pyexpat.xmlparser.__dir__
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_xmlparser___dir____doc__,
-"__dir__($self, /)\n"
-"--");
-
-#define PYEXPAT_XMLPARSER___DIR___METHODDEF    \
-    {"__dir__", (PyCFunction)pyexpat_xmlparser___dir__, METH_NOARGS, pyexpat_xmlparser___dir____doc__},
-
-static PyObject *
-pyexpat_xmlparser___dir___impl(xmlparseobject *self);
-
-static PyObject *
-pyexpat_xmlparser___dir__(xmlparseobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return pyexpat_xmlparser___dir___impl(self);
-}
-
 static PyObject *
 pyexpat_xmlparser___dir___impl(xmlparseobject *self)
-/*[clinic end generated code: output=1ed6efe83bc304cc input=76aa455f2a661384]*/
+/*[clinic end generated code: output=bc22451efb9e4d17 input=76aa455f2a661384]*/
 {
 #define APPEND(list, str)                               \
         do {                                            \
@@ -1765,41 +1550,9 @@
 Return a new XML parser object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_ParserCreate__doc__,
-"ParserCreate($module, /, encoding=None, namespace_separator=None,\n"
-"             intern=None)\n"
-"--\n"
-"\n"
-"Return a new XML parser object.");
-
-#define PYEXPAT_PARSERCREATE_METHODDEF    \
-    {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},
-
-static PyObject *
-pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding, const char *namespace_separator, PyObject *intern);
-
-static PyObject *
-pyexpat_ParserCreate(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"encoding", "namespace_separator", "intern", NULL};
-    const char *encoding = NULL;
-    const char *namespace_separator = NULL;
-    PyObject *intern = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|zzO:ParserCreate", _keywords,
-        &encoding, &namespace_separator, &intern))
-        goto exit;
-    return_value = pyexpat_ParserCreate_impl(module, encoding, namespace_separator, intern);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding, const char *namespace_separator, PyObject *intern)
-/*[clinic end generated code: output=4fc027dd33b7a2ac input=71b9f471aa6f8f86]*/
+/*[clinic end generated code: output=b839b60992d8ce71 input=71b9f471aa6f8f86]*/
 {
     PyObject *result;
     int intern_decref = 0;
@@ -1842,37 +1595,9 @@
 Returns string error for given number.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(pyexpat_ErrorString__doc__,
-"ErrorString($module, code, /)\n"
-"--\n"
-"\n"
-"Returns string error for given number.");
-
-#define PYEXPAT_ERRORSTRING_METHODDEF    \
-    {"ErrorString", (PyCFunction)pyexpat_ErrorString, METH_VARARGS, pyexpat_ErrorString__doc__},
-
-static PyObject *
-pyexpat_ErrorString_impl(PyModuleDef *module, long code);
-
-static PyObject *
-pyexpat_ErrorString(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    long code;
-
-    if (!PyArg_ParseTuple(args,
-        "l:ErrorString",
-        &code))
-        goto exit;
-    return_value = pyexpat_ErrorString_impl(module, code);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 pyexpat_ErrorString_impl(PyModuleDef *module, long code)
-/*[clinic end generated code: output=c70f3cd82bfaf067 input=cc67de010d9e62b3]*/
+/*[clinic end generated code: output=d87668108b6868e5 input=cc67de010d9e62b3]*/
 {
     return Py_BuildValue("z", XML_ErrorString((int)code));
 }
@@ -2252,8 +1977,4 @@
 /*[clinic input]
 dump buffer
 [clinic start generated code]*/
-
-#ifndef PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
-    #define PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
-#endif /* !defined(PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF) */
-/*[clinic end generated code: output=a7880cb78bbd58ce input=524ce2e021e4eba6]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
diff --git a/Modules/sha1module.c b/Modules/sha1module.c
--- a/Modules/sha1module.c
+++ b/Modules/sha1module.c
@@ -53,6 +53,7 @@
     struct sha1_state hash_state;
 } SHA1object;
 
+#include "clinic/sha1module.c.h"
 
 /* ------------------------------------------------------------------------
  *
@@ -320,27 +321,9 @@
 Return a copy of the hash object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA1Type_copy__doc__,
-"copy($self, /)\n"
-"--\n"
-"\n"
-"Return a copy of the hash object.");
-
-#define SHA1TYPE_COPY_METHODDEF    \
-    {"copy", (PyCFunction)SHA1Type_copy, METH_NOARGS, SHA1Type_copy__doc__},
-
-static PyObject *
-SHA1Type_copy_impl(SHA1object *self);
-
-static PyObject *
-SHA1Type_copy(SHA1object *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA1Type_copy_impl(self);
-}
-
 static PyObject *
 SHA1Type_copy_impl(SHA1object *self)
-/*[clinic end generated code: output=1a320e75a7444098 input=b7eae10df6f89b36]*/
+/*[clinic end generated code: output=b4e001264620f02a input=b7eae10df6f89b36]*/
 {
     SHA1object *newobj;
 
@@ -357,27 +340,9 @@
 Return the digest value as a string of binary data.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA1Type_digest__doc__,
-"digest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of binary data.");
-
-#define SHA1TYPE_DIGEST_METHODDEF    \
-    {"digest", (PyCFunction)SHA1Type_digest, METH_NOARGS, SHA1Type_digest__doc__},
-
-static PyObject *
-SHA1Type_digest_impl(SHA1object *self);
-
-static PyObject *
-SHA1Type_digest(SHA1object *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA1Type_digest_impl(self);
-}
-
 static PyObject *
 SHA1Type_digest_impl(SHA1object *self)
-/*[clinic end generated code: output=c4920f75228bfbfd input=205d47e1927fd009]*/
+/*[clinic end generated code: output=2f05302a7aa2b5cb input=205d47e1927fd009]*/
 {
     unsigned char digest[SHA1_DIGESTSIZE];
     struct sha1_state temp;
@@ -393,27 +358,9 @@
 Return the digest value as a string of hexadecimal digits.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA1Type_hexdigest__doc__,
-"hexdigest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of hexadecimal digits.");
-
-#define SHA1TYPE_HEXDIGEST_METHODDEF    \
-    {"hexdigest", (PyCFunction)SHA1Type_hexdigest, METH_NOARGS, SHA1Type_hexdigest__doc__},
-
-static PyObject *
-SHA1Type_hexdigest_impl(SHA1object *self);
-
-static PyObject *
-SHA1Type_hexdigest(SHA1object *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA1Type_hexdigest_impl(self);
-}
-
 static PyObject *
 SHA1Type_hexdigest_impl(SHA1object *self)
-/*[clinic end generated code: output=6e345aac201887b2 input=97691055c0c74ab0]*/
+/*[clinic end generated code: output=4161fd71e68c6659 input=97691055c0c74ab0]*/
 {
     unsigned char digest[SHA1_DIGESTSIZE];
     struct sha1_state temp;
@@ -454,18 +401,9 @@
 Update this hash object's state with the provided string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA1Type_update__doc__,
-"update($self, obj, /)\n"
-"--\n"
-"\n"
-"Update this hash object\'s state with the provided string.");
-
-#define SHA1TYPE_UPDATE_METHODDEF    \
-    {"update", (PyCFunction)SHA1Type_update, METH_O, SHA1Type_update__doc__},
-
 static PyObject *
 SHA1Type_update(SHA1object *self, PyObject *obj)
-/*[clinic end generated code: output=ab20a86a25e7d255 input=aad8e07812edbba3]*/
+/*[clinic end generated code: output=d9902f0e5015e9ae input=aad8e07812edbba3]*/
 {
     Py_buffer buf;
 
@@ -566,38 +504,9 @@
 Return a new SHA1 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_sha1_sha1__doc__,
-"sha1($module, /, string=b\'\')\n"
-"--\n"
-"\n"
-"Return a new SHA1 hash object; optionally initialized with a string.");
-
-#define _SHA1_SHA1_METHODDEF    \
-    {"sha1", (PyCFunction)_sha1_sha1, METH_VARARGS|METH_KEYWORDS, _sha1_sha1__doc__},
-
-static PyObject *
-_sha1_sha1_impl(PyModuleDef *module, PyObject *string);
-
-static PyObject *
-_sha1_sha1(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"string", NULL};
-    PyObject *string = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:sha1", _keywords,
-        &string))
-        goto exit;
-    return_value = _sha1_sha1_impl(module, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _sha1_sha1_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=c9068552f07b8954 input=27ea54281d995ec2]*/
+/*[clinic end generated code: output=3e4e841386b9e8db input=27ea54281d995ec2]*/
 {
     SHA1object *new;
     Py_buffer buf;
diff --git a/Modules/sha256module.c b/Modules/sha256module.c
--- a/Modules/sha256module.c
+++ b/Modules/sha256module.c
@@ -52,6 +52,8 @@
     int digestsize;
 } SHAobject;
 
+#include "clinic/sha256module.c.h"
+
 /* When run on a little-endian CPU we need to perform byte reversal on an
    array of longwords. */
 
@@ -404,27 +406,9 @@
 Return a copy of the hash object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA256Type_copy__doc__,
-"copy($self, /)\n"
-"--\n"
-"\n"
-"Return a copy of the hash object.");
-
-#define SHA256TYPE_COPY_METHODDEF    \
-    {"copy", (PyCFunction)SHA256Type_copy, METH_NOARGS, SHA256Type_copy__doc__},
-
-static PyObject *
-SHA256Type_copy_impl(SHAobject *self);
-
-static PyObject *
-SHA256Type_copy(SHAobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA256Type_copy_impl(self);
-}
-
 static PyObject *
 SHA256Type_copy_impl(SHAobject *self)
-/*[clinic end generated code: output=f716c39d3f81c27c input=f58840a618d4f2a7]*/
+/*[clinic end generated code: output=1a8bbd66a0c9c168 input=f58840a618d4f2a7]*/
 {
     SHAobject *newobj;
 
@@ -446,27 +430,9 @@
 Return the digest value as a string of binary data.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA256Type_digest__doc__,
-"digest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of binary data.");
-
-#define SHA256TYPE_DIGEST_METHODDEF    \
-    {"digest", (PyCFunction)SHA256Type_digest, METH_NOARGS, SHA256Type_digest__doc__},
-
-static PyObject *
-SHA256Type_digest_impl(SHAobject *self);
-
-static PyObject *
-SHA256Type_digest(SHAobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA256Type_digest_impl(self);
-}
-
 static PyObject *
 SHA256Type_digest_impl(SHAobject *self)
-/*[clinic end generated code: output=72d34723d7bb694c input=1fb752e58954157d]*/
+/*[clinic end generated code: output=46616a5e909fbc3d input=1fb752e58954157d]*/
 {
     unsigned char digest[SHA_DIGESTSIZE];
     SHAobject temp;
@@ -482,27 +448,9 @@
 Return the digest value as a string of hexadecimal digits.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA256Type_hexdigest__doc__,
-"hexdigest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of hexadecimal digits.");
-
-#define SHA256TYPE_HEXDIGEST_METHODDEF    \
-    {"hexdigest", (PyCFunction)SHA256Type_hexdigest, METH_NOARGS, SHA256Type_hexdigest__doc__},
-
-static PyObject *
-SHA256Type_hexdigest_impl(SHAobject *self);
-
-static PyObject *
-SHA256Type_hexdigest(SHAobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA256Type_hexdigest_impl(self);
-}
-
 static PyObject *
 SHA256Type_hexdigest_impl(SHAobject *self)
-/*[clinic end generated code: output=3687aa6183c7d27f input=0cc4c714693010d1]*/
+/*[clinic end generated code: output=725f8a7041ae97f3 input=0cc4c714693010d1]*/
 {
     unsigned char digest[SHA_DIGESTSIZE];
     SHAobject temp;
@@ -543,18 +491,9 @@
 Update this hash object's state with the provided string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA256Type_update__doc__,
-"update($self, obj, /)\n"
-"--\n"
-"\n"
-"Update this hash object\'s state with the provided string.");
-
-#define SHA256TYPE_UPDATE_METHODDEF    \
-    {"update", (PyCFunction)SHA256Type_update, METH_O, SHA256Type_update__doc__},
-
 static PyObject *
 SHA256Type_update(SHAobject *self, PyObject *obj)
-/*[clinic end generated code: output=b47f53d7cbeabee4 input=b2d449d5b30f0f5a]*/
+/*[clinic end generated code: output=0967fb2860c66af7 input=b2d449d5b30f0f5a]*/
 {
     Py_buffer buf;
 
@@ -686,38 +625,9 @@
 Return a new SHA-256 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_sha256_sha256__doc__,
-"sha256($module, /, string=b\'\')\n"
-"--\n"
-"\n"
-"Return a new SHA-256 hash object; optionally initialized with a string.");
-
-#define _SHA256_SHA256_METHODDEF    \
-    {"sha256", (PyCFunction)_sha256_sha256, METH_VARARGS|METH_KEYWORDS, _sha256_sha256__doc__},
-
-static PyObject *
-_sha256_sha256_impl(PyModuleDef *module, PyObject *string);
-
-static PyObject *
-_sha256_sha256(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"string", NULL};
-    PyObject *string = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:sha256", _keywords,
-        &string))
-        goto exit;
-    return_value = _sha256_sha256_impl(module, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _sha256_sha256_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=4b1263d1e2fcdb98 input=09cce3fb855056b2]*/
+/*[clinic end generated code: output=d70e6e2d97112844 input=09cce3fb855056b2]*/
 {
     SHAobject *new;
     Py_buffer buf;
@@ -755,38 +665,9 @@
 Return a new SHA-224 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_sha256_sha224__doc__,
-"sha224($module, /, string=b\'\')\n"
-"--\n"
-"\n"
-"Return a new SHA-224 hash object; optionally initialized with a string.");
-
-#define _SHA256_SHA224_METHODDEF    \
-    {"sha224", (PyCFunction)_sha256_sha224, METH_VARARGS|METH_KEYWORDS, _sha256_sha224__doc__},
-
-static PyObject *
-_sha256_sha224_impl(PyModuleDef *module, PyObject *string);
-
-static PyObject *
-_sha256_sha224(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"string", NULL};
-    PyObject *string = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:sha224", _keywords,
-        &string))
-        goto exit;
-    return_value = _sha256_sha224_impl(module, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _sha256_sha224_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=4dde0eb1cdaebc06 input=27a04ba24c353a73]*/
+/*[clinic end generated code: output=f2822bf28416b42a input=27a04ba24c353a73]*/
 {
     SHAobject *new;
     Py_buffer buf;
diff --git a/Modules/sha512module.c b/Modules/sha512module.c
--- a/Modules/sha512module.c
+++ b/Modules/sha512module.c
@@ -55,6 +55,8 @@
     int digestsize;
 } SHAobject;
 
+#include "clinic/sha512module.c.h"
+
 /* When run on a little-endian CPU we need to perform byte reversal on an
    array of longwords. */
 
@@ -471,27 +473,9 @@
 Return a copy of the hash object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA512Type_copy__doc__,
-"copy($self, /)\n"
-"--\n"
-"\n"
-"Return a copy of the hash object.");
-
-#define SHA512TYPE_COPY_METHODDEF    \
-    {"copy", (PyCFunction)SHA512Type_copy, METH_NOARGS, SHA512Type_copy__doc__},
-
-static PyObject *
-SHA512Type_copy_impl(SHAobject *self);
-
-static PyObject *
-SHA512Type_copy(SHAobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA512Type_copy_impl(self);
-}
-
 static PyObject *
 SHA512Type_copy_impl(SHAobject *self)
-/*[clinic end generated code: output=14f8e6ce9c61ece0 input=9f5f31e6c457776a]*/
+/*[clinic end generated code: output=adea896ed3164821 input=9f5f31e6c457776a]*/
 {
     SHAobject *newobj;
 
@@ -513,27 +497,9 @@
 Return the digest value as a string of binary data.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA512Type_digest__doc__,
-"digest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of binary data.");
-
-#define SHA512TYPE_DIGEST_METHODDEF    \
-    {"digest", (PyCFunction)SHA512Type_digest, METH_NOARGS, SHA512Type_digest__doc__},
-
-static PyObject *
-SHA512Type_digest_impl(SHAobject *self);
-
-static PyObject *
-SHA512Type_digest(SHAobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA512Type_digest_impl(self);
-}
-
 static PyObject *
 SHA512Type_digest_impl(SHAobject *self)
-/*[clinic end generated code: output=be8de024b232977e input=60c2cede9e023018]*/
+/*[clinic end generated code: output=1080bbeeef7dde1b input=60c2cede9e023018]*/
 {
     unsigned char digest[SHA_DIGESTSIZE];
     SHAobject temp;
@@ -549,27 +515,9 @@
 Return the digest value as a string of hexadecimal digits.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA512Type_hexdigest__doc__,
-"hexdigest($self, /)\n"
-"--\n"
-"\n"
-"Return the digest value as a string of hexadecimal digits.");
-
-#define SHA512TYPE_HEXDIGEST_METHODDEF    \
-    {"hexdigest", (PyCFunction)SHA512Type_hexdigest, METH_NOARGS, SHA512Type_hexdigest__doc__},
-
-static PyObject *
-SHA512Type_hexdigest_impl(SHAobject *self);
-
-static PyObject *
-SHA512Type_hexdigest(SHAobject *self, PyObject *Py_UNUSED(ignored))
-{
-    return SHA512Type_hexdigest_impl(self);
-}
-
 static PyObject *
 SHA512Type_hexdigest_impl(SHAobject *self)
-/*[clinic end generated code: output=28a4ab2f9a1781b8 input=498b877b25cbe0a2]*/
+/*[clinic end generated code: output=7373305b8601e18b input=498b877b25cbe0a2]*/
 {
     unsigned char digest[SHA_DIGESTSIZE];
     SHAobject temp;
@@ -610,18 +558,9 @@
 Update this hash object's state with the provided string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(SHA512Type_update__doc__,
-"update($self, obj, /)\n"
-"--\n"
-"\n"
-"Update this hash object\'s state with the provided string.");
-
-#define SHA512TYPE_UPDATE_METHODDEF    \
-    {"update", (PyCFunction)SHA512Type_update, METH_O, SHA512Type_update__doc__},
-
 static PyObject *
 SHA512Type_update(SHAobject *self, PyObject *obj)
-/*[clinic end generated code: output=6be574cdc3a9c52d input=ded2b46656566283]*/
+/*[clinic end generated code: output=1cf333e73995a79e input=ded2b46656566283]*/
 {
     Py_buffer buf;
 
@@ -636,23 +575,7 @@
 /*[clinic input]
 dump buffer
 [clinic start generated code]*/
-
-#ifndef SHA512TYPE_COPY_METHODDEF
-    #define SHA512TYPE_COPY_METHODDEF
-#endif /* !defined(SHA512TYPE_COPY_METHODDEF) */
-
-#ifndef SHA512TYPE_DIGEST_METHODDEF
-    #define SHA512TYPE_DIGEST_METHODDEF
-#endif /* !defined(SHA512TYPE_DIGEST_METHODDEF) */
-
-#ifndef SHA512TYPE_HEXDIGEST_METHODDEF
-    #define SHA512TYPE_HEXDIGEST_METHODDEF
-#endif /* !defined(SHA512TYPE_HEXDIGEST_METHODDEF) */
-
-#ifndef SHA512TYPE_UPDATE_METHODDEF
-    #define SHA512TYPE_UPDATE_METHODDEF
-#endif /* !defined(SHA512TYPE_UPDATE_METHODDEF) */
-/*[clinic end generated code: output=de713947d31130e9 input=524ce2e021e4eba6]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
 
 static PyMethodDef SHA_methods[] = {
     SHA512TYPE_COPY_METHODDEF
@@ -773,38 +696,9 @@
 Return a new SHA-512 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_sha512_sha512__doc__,
-"sha512($module, /, string=b\'\')\n"
-"--\n"
-"\n"
-"Return a new SHA-512 hash object; optionally initialized with a string.");
-
-#define _SHA512_SHA512_METHODDEF    \
-    {"sha512", (PyCFunction)_sha512_sha512, METH_VARARGS|METH_KEYWORDS, _sha512_sha512__doc__},
-
-static PyObject *
-_sha512_sha512_impl(PyModuleDef *module, PyObject *string);
-
-static PyObject *
-_sha512_sha512(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"string", NULL};
-    PyObject *string = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:sha512", _keywords,
-        &string))
-        goto exit;
-    return_value = _sha512_sha512_impl(module, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _sha512_sha512_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=9e39b11115f36878 input=e69bad9ae9b6a308]*/
+/*[clinic end generated code: output=da13bc0a94da6de3 input=e69bad9ae9b6a308]*/
 {
     SHAobject *new;
     Py_buffer buf;
@@ -842,38 +736,9 @@
 Return a new SHA-384 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(_sha512_sha384__doc__,
-"sha384($module, /, string=b\'\')\n"
-"--\n"
-"\n"
-"Return a new SHA-384 hash object; optionally initialized with a string.");
-
-#define _SHA512_SHA384_METHODDEF    \
-    {"sha384", (PyCFunction)_sha512_sha384, METH_VARARGS|METH_KEYWORDS, _sha512_sha384__doc__},
-
-static PyObject *
-_sha512_sha384_impl(PyModuleDef *module, PyObject *string);
-
-static PyObject *
-_sha512_sha384(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"string", NULL};
-    PyObject *string = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|O:sha384", _keywords,
-        &string))
-        goto exit;
-    return_value = _sha512_sha384_impl(module, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 _sha512_sha384_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=397c6fba3525b93a input=c9327788d4ea4545]*/
+/*[clinic end generated code: output=ac731aea5509174d input=c9327788d4ea4545]*/
 {
     SHAobject *new;
     Py_buffer buf;
@@ -907,15 +772,7 @@
 /*[clinic input]
 dump buffer
 [clinic start generated code]*/
-
-#ifndef _SHA512_SHA512_METHODDEF
-    #define _SHA512_SHA512_METHODDEF
-#endif /* !defined(_SHA512_SHA512_METHODDEF) */
-
-#ifndef _SHA512_SHA384_METHODDEF
-    #define _SHA512_SHA384_METHODDEF
-#endif /* !defined(_SHA512_SHA384_METHODDEF) */
-/*[clinic end generated code: output=69d84aa9445b01d8 input=524ce2e021e4eba6]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
 
 /* List of functions exported by this module */
 
diff --git a/Modules/spwdmodule.c b/Modules/spwdmodule.c
--- a/Modules/spwdmodule.c
+++ b/Modules/spwdmodule.c
@@ -13,10 +13,9 @@
 #include "clinic/spwdmodule.c.h"
 
 /*[clinic input]
-output preset file
 module spwd
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b3464a3667278fae]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c0b841b90a6a07ce]*/
 
 PyDoc_STRVAR(spwd__doc__,
 "This module provides access to the Unix shadow password database.\n\
diff --git a/Modules/unicodedata.c b/Modules/unicodedata.c
--- a/Modules/unicodedata.c
+++ b/Modules/unicodedata.c
@@ -73,6 +73,8 @@
     Py_UCS4 (*normalization)(Py_UCS4);
 } PreviousDBVersion;
 
+#include "clinic/unicodedata.c.h"
+
 #define get_old_record(self, v)    ((((PreviousDBVersion*)self)->getrecord)(v))
 
 static PyMemberDef DB_members[] = {
@@ -130,42 +132,9 @@
 not given, ValueError is raised.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(unicodedata_UCD_decimal__doc__,
-"decimal($self, unichr, default=None, /)\n"
-"--\n"
-"\n"
-"Converts a Unicode character into its equivalent decimal value.\n"
-"\n"
-"Returns the decimal value assigned to the Unicode character unichr\n"
-"as integer. If no such value is defined, default is returned, or, if\n"
-"not given, ValueError is raised.");
-
-#define UNICODEDATA_UCD_DECIMAL_METHODDEF    \
-    {"decimal", (PyCFunction)unicodedata_UCD_decimal, METH_VARARGS, unicodedata_UCD_decimal__doc__},
-
-static PyObject *
-unicodedata_UCD_decimal_impl(PreviousDBVersion *self, PyUnicodeObject *unichr, PyObject *default_value);
-
-static PyObject *
-unicodedata_UCD_decimal(PreviousDBVersion *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyUnicodeObject *unichr;
-    PyObject *default_value = NULL;
-
-    if (!PyArg_ParseTuple(args,
-        "O!|O:decimal",
-        &PyUnicode_Type, &unichr, &default_value))
-        goto exit;
-    return_value = unicodedata_UCD_decimal_impl(self, unichr, default_value);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 unicodedata_UCD_decimal_impl(PreviousDBVersion *self, PyUnicodeObject *unichr, PyObject *default_value)
-/*[clinic end generated code: output=8689669896d293df input=c25c9d2b4de076b1]*/
+/*[clinic end generated code: output=d285215533b58b28 input=c25c9d2b4de076b1]*/
 {
     int have_old = 0;
     long rc;
diff --git a/Modules/zlibmodule.c b/Modules/zlibmodule.c
--- a/Modules/zlibmodule.c
+++ b/Modules/zlibmodule.c
@@ -82,12 +82,11 @@
 }
 
 /*[clinic input]
-output preset file
 module zlib
 class zlib.Compress "compobject *" "&Comptype"
 class zlib.Decompress "compobject *" "&Decomptype"
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bfd4c340573ba91d]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=093935115c3e3158]*/
 
 static compobject *
 newcompobject(PyTypeObject *type)
diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c
--- a/Objects/bytearrayobject.c
+++ b/Objects/bytearrayobject.c
@@ -90,6 +90,8 @@
     return 1;
 }
 
+#include "clinic/bytearrayobject.c.h"
+
 /* Direct API functions */
 
 PyObject *
@@ -1266,27 +1268,9 @@
 Remove all items from the bytearray.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_clear__doc__,
-"clear($self, /)\n"
-"--\n"
-"\n"
-"Remove all items from the bytearray.");
-
-#define BYTEARRAY_CLEAR_METHODDEF    \
-    {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, bytearray_clear__doc__},
-
-static PyObject *
-bytearray_clear_impl(PyByteArrayObject *self);
-
-static PyObject *
-bytearray_clear(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
-{
-    return bytearray_clear_impl(self);
-}
-
 static PyObject *
 bytearray_clear_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=5344093031e2f36c input=e524fd330abcdc18]*/
+/*[clinic end generated code: output=85c2fe6aede0956c input=e524fd330abcdc18]*/
 {
     if (PyByteArray_Resize((PyObject *)self, 0) < 0)
         return NULL;
@@ -1301,27 +1285,9 @@
 Return a copy of B.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_copy__doc__,
-"copy($self, /)\n"
-"--\n"
-"\n"
-"Return a copy of B.");
-
-#define BYTEARRAY_COPY_METHODDEF    \
-    {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, bytearray_copy__doc__},
-
-static PyObject *
-bytearray_copy_impl(PyByteArrayObject *self);
-
-static PyObject *
-bytearray_copy(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
-{
-    return bytearray_copy_impl(self);
-}
-
 static PyObject *
 bytearray_copy_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=8788ed299f7f2214 input=6d5d2975aa0f33f3]*/
+/*[clinic end generated code: output=68cfbcfed484c132 input=6d5d2975aa0f33f3]*/
 {
     return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
                                          PyByteArray_GET_SIZE(self));
@@ -1557,53 +1523,9 @@
 The remaining characters are mapped through the given translation table.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_translate__doc__,
-"translate(table, [deletechars])\n"
-"Return a copy with each character mapped by the given translation table.\n"
-"\n"
-"  table\n"
-"    Translation table, which must be a bytes object of length 256.\n"
-"\n"
-"All characters occurring in the optional argument deletechars are removed.\n"
-"The remaining characters are mapped through the given translation table.");
-
-#define BYTEARRAY_TRANSLATE_METHODDEF    \
-    {"translate", (PyCFunction)bytearray_translate, METH_VARARGS, bytearray_translate__doc__},
-
-static PyObject *
-bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars);
-
-static PyObject *
-bytearray_translate(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *table;
-    int group_right_1 = 0;
-    PyObject *deletechars = NULL;
-
-    switch (PyTuple_GET_SIZE(args)) {
-        case 1:
-            if (!PyArg_ParseTuple(args, "O:translate", &table))
-                goto exit;
-            break;
-        case 2:
-            if (!PyArg_ParseTuple(args, "OO:translate", &table, &deletechars))
-                goto exit;
-            group_right_1 = 1;
-            break;
-        default:
-            PyErr_SetString(PyExc_TypeError, "bytearray.translate requires 1 to 2 arguments");
-            goto exit;
-    }
-    return_value = bytearray_translate_impl(self, table, group_right_1, deletechars);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
-/*[clinic end generated code: output=a709df81d41db4b7 input=b749ad85f4860824]*/
+/*[clinic end generated code: output=fa3ea4f9a8d58bc7 input=b749ad85f4860824]*/
 {
     char *input, *output;
     const char *table_chars;
@@ -1708,50 +1630,9 @@
 The bytes objects frm and to must be of the same length.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_maketrans__doc__,
-"maketrans(frm, to, /)\n"
-"--\n"
-"\n"
-"Return a translation table useable for the bytes or bytearray translate method.\n"
-"\n"
-"The returned table will be one where each byte in frm is mapped to the byte at\n"
-"the same position in to.\n"
-"\n"
-"The bytes objects frm and to must be of the same length.");
-
-#define BYTEARRAY_MAKETRANS_METHODDEF    \
-    {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC, bytearray_maketrans__doc__},
-
-static PyObject *
-bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to);
-
-static PyObject *
-bytearray_maketrans(void *null, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_buffer frm = {NULL, NULL};
-    Py_buffer to = {NULL, NULL};
-
-    if (!PyArg_ParseTuple(args,
-        "y*y*:maketrans",
-        &frm, &to))
-        goto exit;
-    return_value = bytearray_maketrans_impl(&frm, &to);
-
-exit:
-    /* Cleanup for frm */
-    if (frm.obj)
-       PyBuffer_Release(&frm);
-    /* Cleanup for to */
-    if (to.obj)
-       PyBuffer_Release(&to);
-
-    return return_value;
-}
-
 static PyObject *
 bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
-/*[clinic end generated code: output=d332622814c26f4b input=5925a81d2fbbf151]*/
+/*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
 {
     return _Py_bytes_maketrans(frm, to);
 }
@@ -2260,53 +2141,9 @@
 replaced.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_replace__doc__,
-"replace($self, old, new, count=-1, /)\n"
-"--\n"
-"\n"
-"Return a copy with all occurrences of substring old replaced by new.\n"
-"\n"
-"  count\n"
-"    Maximum number of occurrences to replace.\n"
-"    -1 (the default value) means replace all occurrences.\n"
-"\n"
-"If the optional argument count is given, only the first count occurrences are\n"
-"replaced.");
-
-#define BYTEARRAY_REPLACE_METHODDEF    \
-    {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, bytearray_replace__doc__},
-
-static PyObject *
-bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count);
-
-static PyObject *
-bytearray_replace(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_buffer old = {NULL, NULL};
-    Py_buffer new = {NULL, NULL};
-    Py_ssize_t count = -1;
-
-    if (!PyArg_ParseTuple(args,
-        "y*y*|n:replace",
-        &old, &new, &count))
-        goto exit;
-    return_value = bytearray_replace_impl(self, &old, &new, count);
-
-exit:
-    /* Cleanup for old */
-    if (old.obj)
-       PyBuffer_Release(&old);
-    /* Cleanup for new */
-    if (new.obj)
-       PyBuffer_Release(&new);
-
-    return return_value;
-}
-
 static PyObject *
 bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count)
-/*[clinic end generated code: output=9997fbbd5bac4883 input=aa379d988637c7fb]*/
+/*[clinic end generated code: output=3fc105c8232d7b3f input=aa379d988637c7fb]*/
 {
     return (PyObject *)replace((PyByteArrayObject *) self,
                                old->buf, old->len,
@@ -2327,47 +2164,9 @@
 Return a list of the sections in the bytearray, using sep as the delimiter.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_split__doc__,
-"split($self, /, sep=None, maxsplit=-1)\n"
-"--\n"
-"\n"
-"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
-"\n"
-"  sep\n"
-"    The delimiter according which to split the bytearray.\n"
-"    None (the default value) means split on ASCII whitespace characters\n"
-"    (space, tab, return, newline, formfeed, vertical tab).\n"
-"  maxsplit\n"
-"    Maximum number of splits to do.\n"
-"    -1 (the default value) means no limit.");
-
-#define BYTEARRAY_SPLIT_METHODDEF    \
-    {"split", (PyCFunction)bytearray_split, METH_VARARGS|METH_KEYWORDS, bytearray_split__doc__},
-
-static PyObject *
-bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
-
-static PyObject *
-bytearray_split(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"sep", "maxsplit", NULL};
-    PyObject *sep = Py_None;
-    Py_ssize_t maxsplit = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|On:split", _keywords,
-        &sep, &maxsplit))
-        goto exit;
-    return_value = bytearray_split_impl(self, sep, maxsplit);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=062a3d87d6f918fa input=24f82669f41bf523]*/
+/*[clinic end generated code: output=cdccf5a29dbf7eb5 input=24f82669f41bf523]*/
 {
     Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
     const char *s = PyByteArray_AS_STRING(self), *sub;
@@ -2409,25 +2208,9 @@
 bytearray object and two empty bytearray objects.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_partition__doc__,
-"partition($self, sep, /)\n"
-"--\n"
-"\n"
-"Partition the bytearray into three parts using the given separator.\n"
-"\n"
-"This will search for the separator sep in the bytearray. If the separator is\n"
-"found, returns a 3-tuple containing the part before the separator, the\n"
-"separator itself, and the part after it.\n"
-"\n"
-"If the separator is not found, returns a 3-tuple containing the original\n"
-"bytearray object and two empty bytearray objects.");
-
-#define BYTEARRAY_PARTITION_METHODDEF    \
-    {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__},
-
 static PyObject *
 bytearray_partition(PyByteArrayObject *self, PyObject *sep)
-/*[clinic end generated code: output=2645138221fe6f4d input=7d7fe37b1696d506]*/
+/*[clinic end generated code: output=45d2525ddd35f957 input=7d7fe37b1696d506]*/
 {
     PyObject *bytesep, *result;
 
@@ -2463,25 +2246,9 @@
 objects and the original bytearray object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_rpartition__doc__,
-"rpartition($self, sep, /)\n"
-"--\n"
-"\n"
-"Partition the bytes into three parts using the given separator.\n"
-"\n"
-"This will search for the separator sep in the bytearray, starting and the end.\n"
-"If the separator is found, returns a 3-tuple containing the part before the\n"
-"separator, the separator itself, and the part after it.\n"
-"\n"
-"If the separator is not found, returns a 3-tuple containing two empty bytearray\n"
-"objects and the original bytearray object.");
-
-#define BYTEARRAY_RPARTITION_METHODDEF    \
-    {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__},
-
 static PyObject *
 bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
-/*[clinic end generated code: output=ed13e54605d007de input=9b8cd540c1b75853]*/
+/*[clinic end generated code: output=440de3c9426115e8 input=9b8cd540c1b75853]*/
 {
     PyObject *bytesep, *result;
 
@@ -2508,49 +2275,9 @@
 Splitting is done starting at the end of the bytearray and working to the front.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_rsplit__doc__,
-"rsplit($self, /, sep=None, maxsplit=-1)\n"
-"--\n"
-"\n"
-"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
-"\n"
-"  sep\n"
-"    The delimiter according which to split the bytearray.\n"
-"    None (the default value) means split on ASCII whitespace characters\n"
-"    (space, tab, return, newline, formfeed, vertical tab).\n"
-"  maxsplit\n"
-"    Maximum number of splits to do.\n"
-"    -1 (the default value) means no limit.\n"
-"\n"
-"Splitting is done starting at the end of the bytearray and working to the front.");
-
-#define BYTEARRAY_RSPLIT_METHODDEF    \
-    {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS|METH_KEYWORDS, bytearray_rsplit__doc__},
-
-static PyObject *
-bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
-
-static PyObject *
-bytearray_rsplit(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"sep", "maxsplit", NULL};
-    PyObject *sep = Py_None;
-    Py_ssize_t maxsplit = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|On:rsplit", _keywords,
-        &sep, &maxsplit))
-        goto exit;
-    return_value = bytearray_rsplit_impl(self, sep, maxsplit);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=affaf9fc2aae8d41 input=a68286e4dd692ffe]*/
+/*[clinic end generated code: output=4d648cf3ac65c9e9 input=a68286e4dd692ffe]*/
 {
     Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
     const char *s = PyByteArray_AS_STRING(self), *sub;
@@ -2583,27 +2310,9 @@
 Reverse the order of the values in B in place.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_reverse__doc__,
-"reverse($self, /)\n"
-"--\n"
-"\n"
-"Reverse the order of the values in B in place.");
-
-#define BYTEARRAY_REVERSE_METHODDEF    \
-    {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, bytearray_reverse__doc__},
-
-static PyObject *
-bytearray_reverse_impl(PyByteArrayObject *self);
-
-static PyObject *
-bytearray_reverse(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
-{
-    return bytearray_reverse_impl(self);
-}
-
 static PyObject *
 bytearray_reverse_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=5d5e5f0bfc67f476 input=7933a499b8597bd1]*/
+/*[clinic end generated code: output=9f7616f29ab309d3 input=7933a499b8597bd1]*/
 {
     char swap, *head, *tail;
     Py_ssize_t i, j, n = Py_SIZE(self);
@@ -2642,43 +2351,9 @@
 Insert a single item into the bytearray before the given index.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_insert__doc__,
-"insert($self, index, item, /)\n"
-"--\n"
-"\n"
-"Insert a single item into the bytearray before the given index.\n"
-"\n"
-"  index\n"
-"    The index where the value is to be inserted.\n"
-"  item\n"
-"    The item to be inserted.");
-
-#define BYTEARRAY_INSERT_METHODDEF    \
-    {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, bytearray_insert__doc__},
-
-static PyObject *
-bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item);
-
-static PyObject *
-bytearray_insert(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_ssize_t index;
-    int item;
-
-    if (!PyArg_ParseTuple(args,
-        "nO&:insert",
-        &index, _getbytevalue, &item))
-        goto exit;
-    return_value = bytearray_insert_impl(self, index, item);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
-/*[clinic end generated code: output=5ec9340d4ad19080 input=833766836ba30e1e]*/
+/*[clinic end generated code: output=76c775a70e7b07b7 input=833766836ba30e1e]*/
 {
     Py_ssize_t n = Py_SIZE(self);
     char *buf;
@@ -2716,40 +2391,9 @@
 Append a single item to the end of the bytearray.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_append__doc__,
-"append($self, item, /)\n"
-"--\n"
-"\n"
-"Append a single item to the end of the bytearray.\n"
-"\n"
-"  item\n"
-"    The item to be appended.");
-
-#define BYTEARRAY_APPEND_METHODDEF    \
-    {"append", (PyCFunction)bytearray_append, METH_VARARGS, bytearray_append__doc__},
-
-static PyObject *
-bytearray_append_impl(PyByteArrayObject *self, int item);
-
-static PyObject *
-bytearray_append(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int item;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:append",
-        _getbytevalue, &item))
-        goto exit;
-    return_value = bytearray_append_impl(self, item);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_append_impl(PyByteArrayObject *self, int item)
-/*[clinic end generated code: output=b5b3325bb3bbaf85 input=ae56ea87380407cc]*/
+/*[clinic end generated code: output=a154e19ed1886cb6 input=ae56ea87380407cc]*/
 {
     Py_ssize_t n = Py_SIZE(self);
 
@@ -2777,21 +2421,9 @@
 Append all the items from the iterator or sequence to the end of the bytearray.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_extend__doc__,
-"extend($self, iterable_of_ints, /)\n"
-"--\n"
-"\n"
-"Append all the items from the iterator or sequence to the end of the bytearray.\n"
-"\n"
-"  iterable_of_ints\n"
-"    The iterable of items to append.");
-
-#define BYTEARRAY_EXTEND_METHODDEF    \
-    {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__},
-
 static PyObject *
 bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
-/*[clinic end generated code: output=13b0c13ad5110dfb input=ce83a5d75b70d850]*/
+/*[clinic end generated code: output=98155dbe249170b1 input=ce83a5d75b70d850]*/
 {
     PyObject *it, *item, *bytearray_obj;
     Py_ssize_t buf_size = 0, len = 0;
@@ -2877,43 +2509,9 @@
 If no index argument is given, will pop the last item.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_pop__doc__,
-"pop($self, index=-1, /)\n"
-"--\n"
-"\n"
-"Remove and return a single item from B.\n"
-"\n"
-"  index\n"
-"    The index from where to remove the item.\n"
-"    -1 (the default value) means remove the last item.\n"
-"\n"
-"If no index argument is given, will pop the last item.");
-
-#define BYTEARRAY_POP_METHODDEF    \
-    {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, bytearray_pop__doc__},
-
-static PyObject *
-bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index);
-
-static PyObject *
-bytearray_pop(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_ssize_t index = -1;
-
-    if (!PyArg_ParseTuple(args,
-        "|n:pop",
-        &index))
-        goto exit;
-    return_value = bytearray_pop_impl(self, index);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
-/*[clinic end generated code: output=3b763e548e79af96 input=0797e6c0ca9d5a85]*/
+/*[clinic end generated code: output=e0ccd401f8021da8 input=0797e6c0ca9d5a85]*/
 {
     int value;
     Py_ssize_t n = Py_SIZE(self);
@@ -2953,40 +2551,9 @@
 Remove the first occurrence of a value in the bytearray.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_remove__doc__,
-"remove($self, value, /)\n"
-"--\n"
-"\n"
-"Remove the first occurrence of a value in the bytearray.\n"
-"\n"
-"  value\n"
-"    The value to remove.");
-
-#define BYTEARRAY_REMOVE_METHODDEF    \
-    {"remove", (PyCFunction)bytearray_remove, METH_VARARGS, bytearray_remove__doc__},
-
-static PyObject *
-bytearray_remove_impl(PyByteArrayObject *self, int value);
-
-static PyObject *
-bytearray_remove(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int value;
-
-    if (!PyArg_ParseTuple(args,
-        "O&:remove",
-        _getbytevalue, &value))
-        goto exit;
-    return_value = bytearray_remove_impl(self, value);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_remove_impl(PyByteArrayObject *self, int value)
-/*[clinic end generated code: output=c71c8bcf4703abfc input=47560b11fd856c24]*/
+/*[clinic end generated code: output=d659e37866709c13 input=47560b11fd856c24]*/
 {
     Py_ssize_t where, n = Py_SIZE(self);
     char *buf = PyByteArray_AS_STRING(self);
@@ -3042,39 +2609,9 @@
 If the argument is omitted or None, strip leading and trailing ASCII whitespace.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_strip__doc__,
-"strip($self, bytes=None, /)\n"
-"--\n"
-"\n"
-"Strip leading and trailing bytes contained in the argument.\n"
-"\n"
-"If the argument is omitted or None, strip leading and trailing ASCII whitespace.");
-
-#define BYTEARRAY_STRIP_METHODDEF    \
-    {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, bytearray_strip__doc__},
-
-static PyObject *
-bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes);
-
-static PyObject *
-bytearray_strip(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *bytes = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "strip",
-        0, 1,
-        &bytes))
-        goto exit;
-    return_value = bytearray_strip_impl(self, bytes);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
-/*[clinic end generated code: output=2e3d3358acc4c235 input=ef7bb59b09c21d62]*/
+/*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
 {
     Py_ssize_t left, right, mysize, byteslen;
     char *myptr, *bytesptr;
@@ -3113,39 +2650,9 @@
 If the argument is omitted or None, strip leading ASCII whitespace.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_lstrip__doc__,
-"lstrip($self, bytes=None, /)\n"
-"--\n"
-"\n"
-"Strip leading bytes contained in the argument.\n"
-"\n"
-"If the argument is omitted or None, strip leading ASCII whitespace.");
-
-#define BYTEARRAY_LSTRIP_METHODDEF    \
-    {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, bytearray_lstrip__doc__},
-
-static PyObject *
-bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes);
-
-static PyObject *
-bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *bytes = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "lstrip",
-        0, 1,
-        &bytes))
-        goto exit;
-    return_value = bytearray_lstrip_impl(self, bytes);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
-/*[clinic end generated code: output=2599309808a9ec02 input=80843f975dd7c480]*/
+/*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
 {
     Py_ssize_t left, right, mysize, byteslen;
     char *myptr, *bytesptr;
@@ -3181,39 +2688,9 @@
 If the argument is omitted or None, strip trailing ASCII whitespace.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_rstrip__doc__,
-"rstrip($self, bytes=None, /)\n"
-"--\n"
-"\n"
-"Strip trailing bytes contained in the argument.\n"
-"\n"
-"If the argument is omitted or None, strip trailing ASCII whitespace.");
-
-#define BYTEARRAY_RSTRIP_METHODDEF    \
-    {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, bytearray_rstrip__doc__},
-
-static PyObject *
-bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes);
-
-static PyObject *
-bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *bytes = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "rstrip",
-        0, 1,
-        &bytes))
-        goto exit;
-    return_value = bytearray_rstrip_impl(self, bytes);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
-/*[clinic end generated code: output=b5ca6259f4f4f2a3 input=e728b994954cfd91]*/
+/*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
 {
     Py_ssize_t right, mysize, byteslen;
     char *myptr, *bytesptr;
@@ -3252,48 +2729,9 @@
 Decode the bytearray using the codec registered for encoding.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_decode__doc__,
-"decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
-"--\n"
-"\n"
-"Decode the bytearray using the codec registered for encoding.\n"
-"\n"
-"  encoding\n"
-"    The encoding with which to decode the bytearray.\n"
-"  errors\n"
-"    The error handling scheme to use for the handling of decoding errors.\n"
-"    The default is \'strict\' meaning that decoding errors raise a\n"
-"    UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n"
-"    as well as any other name registered with codecs.register_error that\n"
-"    can handle UnicodeDecodeErrors.");
-
-#define BYTEARRAY_DECODE_METHODDEF    \
-    {"decode", (PyCFunction)bytearray_decode, METH_VARARGS|METH_KEYWORDS, bytearray_decode__doc__},
-
-static PyObject *
-bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors);
-
-static PyObject *
-bytearray_decode(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"encoding", "errors", NULL};
-    const char *encoding = NULL;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|ss:decode", _keywords,
-        &encoding, &errors))
-        goto exit;
-    return_value = bytearray_decode_impl(self, encoding, errors);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors)
-/*[clinic end generated code: output=38b83681f1e38a6c input=f28d8f903020257b]*/
+/*[clinic end generated code: output=7e64e2cc91573b26 input=f28d8f903020257b]*/
 {
     if (encoding == NULL)
         encoding = PyUnicode_GetDefaultEncoding();
@@ -3324,22 +2762,9 @@
 The result is returned as a new bytearray object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_join__doc__,
-"join($self, iterable_of_bytes, /)\n"
-"--\n"
-"\n"
-"Concatenate any number of bytes/bytearray objects.\n"
-"\n"
-"The bytearray whose method is called is inserted in between each pair.\n"
-"\n"
-"The result is returned as a new bytearray object.");
-
-#define BYTEARRAY_JOIN_METHODDEF    \
-    {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__},
-
 static PyObject *
 bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
-/*[clinic end generated code: output=544e7430032dfdf4 input=aba6b1f9b30fcb8e]*/
+/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
 {
     return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
 }
@@ -3355,41 +2780,9 @@
 true.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_splitlines__doc__,
-"splitlines($self, /, keepends=False)\n"
-"--\n"
-"\n"
-"Return a list of the lines in the bytearray, breaking at line boundaries.\n"
-"\n"
-"Line breaks are not included in the resulting list unless keepends is given and\n"
-"true.");
-
-#define BYTEARRAY_SPLITLINES_METHODDEF    \
-    {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS|METH_KEYWORDS, bytearray_splitlines__doc__},
-
-static PyObject *
-bytearray_splitlines_impl(PyByteArrayObject *self, int keepends);
-
-static PyObject *
-bytearray_splitlines(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"keepends", NULL};
-    int keepends = 0;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|i:splitlines", _keywords,
-        &keepends))
-        goto exit;
-    return_value = bytearray_splitlines_impl(self, keepends);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
-/*[clinic end generated code: output=a837fd0512ad46ff input=36f0b25bc792f6c0]*/
+/*[clinic end generated code: output=4223c94b895f6ad9 input=36f0b25bc792f6c0]*/
 {
     return stringlib_splitlines(
         (PyObject*) self, PyByteArray_AS_STRING(self),
@@ -3427,40 +2820,9 @@
 Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_fromhex__doc__,
-"fromhex($type, string, /)\n"
-"--\n"
-"\n"
-"Create a bytearray object from a string of hexadecimal numbers.\n"
-"\n"
-"Spaces between two numbers are accepted.\n"
-"Example: bytearray.fromhex(\'B9 01EF\') -> bytearray(b\'\\\\xb9\\\\x01\\\\xef\')");
-
-#define BYTEARRAY_FROMHEX_METHODDEF    \
-    {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS, bytearray_fromhex__doc__},
-
-static PyObject *
-bytearray_fromhex_impl(PyObject*cls, PyObject *string);
-
-static PyObject *
-bytearray_fromhex(PyTypeObject *cls, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *string;
-
-    if (!PyArg_ParseTuple(args,
-        "U:fromhex",
-        &string))
-        goto exit;
-    return_value = bytearray_fromhex_impl((PyObject*)cls, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_fromhex_impl(PyObject*cls, PyObject *string)
-/*[clinic end generated code: output=adc3c804a74e56d4 input=907bbd2d34d9367a]*/
+/*[clinic end generated code: output=df3da60129b3700c input=907bbd2d34d9367a]*/
 {
     PyObject *newbytes;
     char *buf;
@@ -3550,27 +2912,9 @@
 Return state information for pickling.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_reduce__doc__,
-"__reduce__($self, /)\n"
-"--\n"
-"\n"
-"Return state information for pickling.");
-
-#define BYTEARRAY_REDUCE_METHODDEF    \
-    {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, bytearray_reduce__doc__},
-
-static PyObject *
-bytearray_reduce_impl(PyByteArrayObject *self);
-
-static PyObject *
-bytearray_reduce(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
-{
-    return bytearray_reduce_impl(self);
-}
-
 static PyObject *
 bytearray_reduce_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=b1b56fe87bf30fb0 input=fbb07de4d102a03a]*/
+/*[clinic end generated code: output=52bf304086464cab input=fbb07de4d102a03a]*/
 {
     return _common_reduce(self, 2);
 }
@@ -3585,37 +2929,9 @@
 Return state information for pickling.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_reduce_ex__doc__,
-"__reduce_ex__($self, proto=0, /)\n"
-"--\n"
-"\n"
-"Return state information for pickling.");
-
-#define BYTEARRAY_REDUCE_EX_METHODDEF    \
-    {"__reduce_ex__", (PyCFunction)bytearray_reduce_ex, METH_VARARGS, bytearray_reduce_ex__doc__},
-
-static PyObject *
-bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto);
-
-static PyObject *
-bytearray_reduce_ex(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int proto = 0;
-
-    if (!PyArg_ParseTuple(args,
-        "|i:__reduce_ex__",
-        &proto))
-        goto exit;
-    return_value = bytearray_reduce_ex_impl(self, proto);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
-/*[clinic end generated code: output=bbd9afb2f5953dc1 input=0e091a42ca6dbd91]*/
+/*[clinic end generated code: output=52eac33377197520 input=0e091a42ca6dbd91]*/
 {
     return _common_reduce(self, proto);
 }
@@ -3628,27 +2944,9 @@
 Returns the size of the bytearray object in memory, in bytes.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytearray_sizeof__doc__,
-"__sizeof__($self, /)\n"
-"--\n"
-"\n"
-"Returns the size of the bytearray object in memory, in bytes.");
-
-#define BYTEARRAY_SIZEOF_METHODDEF    \
-    {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, bytearray_sizeof__doc__},
-
-static PyObject *
-bytearray_sizeof_impl(PyByteArrayObject *self);
-
-static PyObject *
-bytearray_sizeof(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
-{
-    return bytearray_sizeof_impl(self);
-}
-
 static PyObject *
 bytearray_sizeof_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=4a2254b0a85630c6 input=6b23d305362b462b]*/
+/*[clinic end generated code: output=738abdd17951c427 input=6b23d305362b462b]*/
 {
     Py_ssize_t res;
 
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c
--- a/Objects/bytesobject.c
+++ b/Objects/bytesobject.c
@@ -12,6 +12,8 @@
 [clinic start generated code]*/
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=1a1d9102afc1b00c]*/
 
+#include "clinic/bytesobject.c.h"
+
 #ifdef COUNT_ALLOCS
 Py_ssize_t null_strings, one_strings;
 #endif
@@ -1614,47 +1616,9 @@
 Return a list of the sections in the bytes, using sep as the delimiter.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_split__doc__,
-"split($self, /, sep=None, maxsplit=-1)\n"
-"--\n"
-"\n"
-"Return a list of the sections in the bytes, using sep as the delimiter.\n"
-"\n"
-"  sep\n"
-"    The delimiter according which to split the bytes.\n"
-"    None (the default value) means split on ASCII whitespace characters\n"
-"    (space, tab, return, newline, formfeed, vertical tab).\n"
-"  maxsplit\n"
-"    Maximum number of splits to do.\n"
-"    -1 (the default value) means no limit.");
-
-#define BYTES_SPLIT_METHODDEF    \
-    {"split", (PyCFunction)bytes_split, METH_VARARGS|METH_KEYWORDS, bytes_split__doc__},
-
-static PyObject *
-bytes_split_impl(PyBytesObject*self, PyObject *sep, Py_ssize_t maxsplit);
-
-static PyObject *
-bytes_split(PyBytesObject*self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"sep", "maxsplit", NULL};
-    PyObject *sep = Py_None;
-    Py_ssize_t maxsplit = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|On:split", _keywords,
-        &sep, &maxsplit))
-        goto exit;
-    return_value = bytes_split_impl(self, sep, maxsplit);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_split_impl(PyBytesObject*self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=c80a47afdd505975 input=8b809b39074abbfa]*/
+/*[clinic end generated code: output=8bde44dacb36ef2e input=8b809b39074abbfa]*/
 {
     Py_ssize_t len = PyBytes_GET_SIZE(self), n;
     const char *s = PyBytes_AS_STRING(self), *sub;
@@ -1692,48 +1656,9 @@
 object and two empty bytes objects.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_partition__doc__,
-"partition($self, sep, /)\n"
-"--\n"
-"\n"
-"Partition the bytes into three parts using the given separator.\n"
-"\n"
-"This will search for the separator sep in the bytes. If the separator is found,\n"
-"returns a 3-tuple containing the part before the separator, the separator\n"
-"itself, and the part after it.\n"
-"\n"
-"If the separator is not found, returns a 3-tuple containing the original bytes\n"
-"object and two empty bytes objects.");
-
-#define BYTES_PARTITION_METHODDEF    \
-    {"partition", (PyCFunction)bytes_partition, METH_VARARGS, bytes_partition__doc__},
-
-static PyObject *
-bytes_partition_impl(PyBytesObject *self, Py_buffer *sep);
-
-static PyObject *
-bytes_partition(PyBytesObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_buffer sep = {NULL, NULL};
-
-    if (!PyArg_ParseTuple(args,
-        "y*:partition",
-        &sep))
-        goto exit;
-    return_value = bytes_partition_impl(self, &sep);
-
-exit:
-    /* Cleanup for sep */
-    if (sep.obj)
-       PyBuffer_Release(&sep);
-
-    return return_value;
-}
-
 static PyObject *
 bytes_partition_impl(PyBytesObject *self, Py_buffer *sep)
-/*[clinic end generated code: output=3006727cfbf83aa4 input=bc855dc63ca949de]*/
+/*[clinic end generated code: output=f532b392a17ff695 input=bc855dc63ca949de]*/
 {
     return stringlib_partition(
         (PyObject*) self,
@@ -1759,48 +1684,9 @@
 objects and the original bytes object.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_rpartition__doc__,
-"rpartition($self, sep, /)\n"
-"--\n"
-"\n"
-"Partition the bytes into three parts using the given separator.\n"
-"\n"
-"This will search for the separator sep in the bytes, starting and the end. If\n"
-"the separator is found, returns a 3-tuple containing the part before the\n"
-"separator, the separator itself, and the part after it.\n"
-"\n"
-"If the separator is not found, returns a 3-tuple containing two empty bytes\n"
-"objects and the original bytes object.");
-
-#define BYTES_RPARTITION_METHODDEF    \
-    {"rpartition", (PyCFunction)bytes_rpartition, METH_VARARGS, bytes_rpartition__doc__},
-
-static PyObject *
-bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep);
-
-static PyObject *
-bytes_rpartition(PyBytesObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_buffer sep = {NULL, NULL};
-
-    if (!PyArg_ParseTuple(args,
-        "y*:rpartition",
-        &sep))
-        goto exit;
-    return_value = bytes_rpartition_impl(self, &sep);
-
-exit:
-    /* Cleanup for sep */
-    if (sep.obj)
-       PyBuffer_Release(&sep);
-
-    return return_value;
-}
-
 static PyObject *
 bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep)
-/*[clinic end generated code: output=57b169dc47fa90e8 input=6588fff262a9170e]*/
+/*[clinic end generated code: output=191b114cbb028e50 input=6588fff262a9170e]*/
 {
     return stringlib_rpartition(
         (PyObject*) self,
@@ -1817,49 +1703,9 @@
 Splitting is done starting at the end of the bytes and working to the front.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_rsplit__doc__,
-"rsplit($self, /, sep=None, maxsplit=-1)\n"
-"--\n"
-"\n"
-"Return a list of the sections in the bytes, using sep as the delimiter.\n"
-"\n"
-"  sep\n"
-"    The delimiter according which to split the bytes.\n"
-"    None (the default value) means split on ASCII whitespace characters\n"
-"    (space, tab, return, newline, formfeed, vertical tab).\n"
-"  maxsplit\n"
-"    Maximum number of splits to do.\n"
-"    -1 (the default value) means no limit.\n"
-"\n"
-"Splitting is done starting at the end of the bytes and working to the front.");
-
-#define BYTES_RSPLIT_METHODDEF    \
-    {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS|METH_KEYWORDS, bytes_rsplit__doc__},
-
-static PyObject *
-bytes_rsplit_impl(PyBytesObject*self, PyObject *sep, Py_ssize_t maxsplit);
-
-static PyObject *
-bytes_rsplit(PyBytesObject*self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"sep", "maxsplit", NULL};
-    PyObject *sep = Py_None;
-    Py_ssize_t maxsplit = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|On:rsplit", _keywords,
-        &sep, &maxsplit))
-        goto exit;
-    return_value = bytes_rsplit_impl(self, sep, maxsplit);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_rsplit_impl(PyBytesObject*self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=f86feddedbd7b26d input=0f86c9f28f7d7b7b]*/
+/*[clinic end generated code: output=0b6570b977911d88 input=0f86c9f28f7d7b7b]*/
 {
     Py_ssize_t len = PyBytes_GET_SIZE(self), n;
     const char *s = PyBytes_AS_STRING(self), *sub;
@@ -1896,24 +1742,9 @@
 Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_join__doc__,
-"join($self, iterable_of_bytes, /)\n"
-"--\n"
-"\n"
-"Concatenate any number of bytes objects.\n"
-"\n"
-"The bytes whose method is called is inserted in between each pair.\n"
-"\n"
-"The result is returned as a new bytes object.\n"
-"\n"
-"Example: b\'.\'.join([b\'ab\', b\'pq\', b\'rs\']) -> b\'ab.pq.rs\'.");
-
-#define BYTES_JOIN_METHODDEF    \
-    {"join", (PyCFunction)bytes_join, METH_O, bytes_join__doc__},
-
 static PyObject *
 bytes_join(PyBytesObject*self, PyObject *iterable_of_bytes)
-/*[clinic end generated code: output=e541a14a8da97908 input=7fe377b95bd549d2]*/
+/*[clinic end generated code: output=634aff14764ff997 input=7fe377b95bd549d2]*/
 {
     return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
 }
@@ -2170,39 +2001,9 @@
 If the argument is omitted or None, strip leading and trailing ASCII whitespace.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_strip__doc__,
-"strip($self, bytes=None, /)\n"
-"--\n"
-"\n"
-"Strip leading and trailing bytes contained in the argument.\n"
-"\n"
-"If the argument is omitted or None, strip leading and trailing ASCII whitespace.");
-
-#define BYTES_STRIP_METHODDEF    \
-    {"strip", (PyCFunction)bytes_strip, METH_VARARGS, bytes_strip__doc__},
-
-static PyObject *
-bytes_strip_impl(PyBytesObject *self, PyObject *bytes);
-
-static PyObject *
-bytes_strip(PyBytesObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *bytes = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "strip",
-        0, 1,
-        &bytes))
-        goto exit;
-    return_value = bytes_strip_impl(self, bytes);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_strip_impl(PyBytesObject *self, PyObject *bytes)
-/*[clinic end generated code: output=c8234a599ba5ec35 input=37daa5fad1395d95]*/
+/*[clinic end generated code: output=c7c228d3bd104a1b input=37daa5fad1395d95]*/
 {
     return do_argstrip(self, BOTHSTRIP, bytes);
 }
@@ -2219,39 +2020,9 @@
 If the argument is omitted or None, strip leading  ASCII whitespace.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_lstrip__doc__,
-"lstrip($self, bytes=None, /)\n"
-"--\n"
-"\n"
-"Strip leading bytes contained in the argument.\n"
-"\n"
-"If the argument is omitted or None, strip leading  ASCII whitespace.");
-
-#define BYTES_LSTRIP_METHODDEF    \
-    {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, bytes_lstrip__doc__},
-
-static PyObject *
-bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes);
-
-static PyObject *
-bytes_lstrip(PyBytesObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *bytes = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "lstrip",
-        0, 1,
-        &bytes))
-        goto exit;
-    return_value = bytes_lstrip_impl(self, bytes);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes)
-/*[clinic end generated code: output=529e8511ab6f1115 input=88811b09dfbc2988]*/
+/*[clinic end generated code: output=28602e586f524e82 input=88811b09dfbc2988]*/
 {
     return do_argstrip(self, LEFTSTRIP, bytes);
 }
@@ -2268,39 +2039,9 @@
 If the argument is omitted or None, strip trailing ASCII whitespace.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_rstrip__doc__,
-"rstrip($self, bytes=None, /)\n"
-"--\n"
-"\n"
-"Strip trailing bytes contained in the argument.\n"
-"\n"
-"If the argument is omitted or None, strip trailing ASCII whitespace.");
-
-#define BYTES_RSTRIP_METHODDEF    \
-    {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, bytes_rstrip__doc__},
-
-static PyObject *
-bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes);
-
-static PyObject *
-bytes_rstrip(PyBytesObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *bytes = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "rstrip",
-        0, 1,
-        &bytes))
-        goto exit;
-    return_value = bytes_rstrip_impl(self, bytes);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes)
-/*[clinic end generated code: output=e98730bd133e6593 input=8f93c9cd361f0140]*/
+/*[clinic end generated code: output=547e3815c95447da input=8f93c9cd361f0140]*/
 {
     return do_argstrip(self, RIGHTSTRIP, bytes);
 }
@@ -2371,53 +2112,9 @@
 The remaining characters are mapped through the given translation table.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_translate__doc__,
-"translate(table, [deletechars])\n"
-"Return a copy with each character mapped by the given translation table.\n"
-"\n"
-"  table\n"
-"    Translation table, which must be a bytes object of length 256.\n"
-"\n"
-"All characters occurring in the optional argument deletechars are removed.\n"
-"The remaining characters are mapped through the given translation table.");
-
-#define BYTES_TRANSLATE_METHODDEF    \
-    {"translate", (PyCFunction)bytes_translate, METH_VARARGS, bytes_translate__doc__},
-
-static PyObject *
-bytes_translate_impl(PyBytesObject *self, PyObject *table, int group_right_1, PyObject *deletechars);
-
-static PyObject *
-bytes_translate(PyBytesObject *self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *table;
-    int group_right_1 = 0;
-    PyObject *deletechars = NULL;
-
-    switch (PyTuple_GET_SIZE(args)) {
-        case 1:
-            if (!PyArg_ParseTuple(args, "O:translate", &table))
-                goto exit;
-            break;
-        case 2:
-            if (!PyArg_ParseTuple(args, "OO:translate", &table, &deletechars))
-                goto exit;
-            group_right_1 = 1;
-            break;
-        default:
-            PyErr_SetString(PyExc_TypeError, "bytes.translate requires 1 to 2 arguments");
-            goto exit;
-    }
-    return_value = bytes_translate_impl(self, table, group_right_1, deletechars);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_translate_impl(PyBytesObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
-/*[clinic end generated code: output=f0f29a57f41df5d8 input=d8fa5519d7cc4be7]*/
+/*[clinic end generated code: output=0ddd2cef4f4918f2 input=d8fa5519d7cc4be7]*/
 {
     char *input, *output;
     Py_buffer table_view = {NULL, NULL};
@@ -2547,50 +2244,9 @@
 The bytes objects frm and to must be of the same length.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_maketrans__doc__,
-"maketrans(frm, to, /)\n"
-"--\n"
-"\n"
-"Return a translation table useable for the bytes or bytearray translate method.\n"
-"\n"
-"The returned table will be one where each byte in frm is mapped to the byte at\n"
-"the same position in to.\n"
-"\n"
-"The bytes objects frm and to must be of the same length.");
-
-#define BYTES_MAKETRANS_METHODDEF    \
-    {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, bytes_maketrans__doc__},
-
-static PyObject *
-bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to);
-
-static PyObject *
-bytes_maketrans(void *null, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_buffer frm = {NULL, NULL};
-    Py_buffer to = {NULL, NULL};
-
-    if (!PyArg_ParseTuple(args,
-        "y*y*:maketrans",
-        &frm, &to))
-        goto exit;
-    return_value = bytes_maketrans_impl(&frm, &to);
-
-exit:
-    /* Cleanup for frm */
-    if (frm.obj)
-       PyBuffer_Release(&frm);
-    /* Cleanup for to */
-    if (to.obj)
-       PyBuffer_Release(&to);
-
-    return return_value;
-}
-
 static PyObject *
 bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to)
-/*[clinic end generated code: output=7df47390c476ac60 input=de7a8fc5632bb8f1]*/
+/*[clinic end generated code: output=a36f6399d4b77f6f input=de7a8fc5632bb8f1]*/
 {
     return _Py_bytes_maketrans(frm, to);
 }
@@ -3104,53 +2760,9 @@
 replaced.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_replace__doc__,
-"replace($self, old, new, count=-1, /)\n"
-"--\n"
-"\n"
-"Return a copy with all occurrences of substring old replaced by new.\n"
-"\n"
-"  count\n"
-"    Maximum number of occurrences to replace.\n"
-"    -1 (the default value) means replace all occurrences.\n"
-"\n"
-"If the optional argument count is given, only the first count occurrences are\n"
-"replaced.");
-
-#define BYTES_REPLACE_METHODDEF    \
-    {"replace", (PyCFunction)bytes_replace, METH_VARARGS, bytes_replace__doc__},
-
-static PyObject *
-bytes_replace_impl(PyBytesObject*self, Py_buffer *old, Py_buffer *new, Py_ssize_t count);
-
-static PyObject *
-bytes_replace(PyBytesObject*self, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    Py_buffer old = {NULL, NULL};
-    Py_buffer new = {NULL, NULL};
-    Py_ssize_t count = -1;
-
-    if (!PyArg_ParseTuple(args,
-        "y*y*|n:replace",
-        &old, &new, &count))
-        goto exit;
-    return_value = bytes_replace_impl(self, &old, &new, count);
-
-exit:
-    /* Cleanup for old */
-    if (old.obj)
-       PyBuffer_Release(&old);
-    /* Cleanup for new */
-    if (new.obj)
-       PyBuffer_Release(&new);
-
-    return return_value;
-}
-
 static PyObject *
 bytes_replace_impl(PyBytesObject*self, Py_buffer *old, Py_buffer *new, Py_ssize_t count)
-/*[clinic end generated code: output=f07bd9ecf29ee8d8 input=b2fbbf0bf04de8e5]*/
+/*[clinic end generated code: output=3fe052c3c60cffc2 input=b2fbbf0bf04de8e5]*/
 {
     return (PyObject *)replace((PyBytesObject *) self,
                                (const char *)old->buf, old->len,
@@ -3316,48 +2928,9 @@
 Decode the bytes using the codec registered for encoding.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_decode__doc__,
-"decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
-"--\n"
-"\n"
-"Decode the bytes using the codec registered for encoding.\n"
-"\n"
-"  encoding\n"
-"    The encoding with which to decode the bytes.\n"
-"  errors\n"
-"    The error handling scheme to use for the handling of decoding errors.\n"
-"    The default is \'strict\' meaning that decoding errors raise a\n"
-"    UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n"
-"    as well as any other name registered with codecs.register_error that\n"
-"    can handle UnicodeDecodeErrors.");
-
-#define BYTES_DECODE_METHODDEF    \
-    {"decode", (PyCFunction)bytes_decode, METH_VARARGS|METH_KEYWORDS, bytes_decode__doc__},
-
-static PyObject *
-bytes_decode_impl(PyBytesObject*self, const char *encoding, const char *errors);
-
-static PyObject *
-bytes_decode(PyBytesObject*self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"encoding", "errors", NULL};
-    const char *encoding = NULL;
-    const char *errors = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|ss:decode", _keywords,
-        &encoding, &errors))
-        goto exit;
-    return_value = bytes_decode_impl(self, encoding, errors);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_decode_impl(PyBytesObject*self, const char *encoding, const char *errors)
-/*[clinic end generated code: output=61a80290bbfce696 input=958174769d2a40ca]*/
+/*[clinic end generated code: output=8038751c823b9038 input=958174769d2a40ca]*/
 {
     return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
 }
@@ -3374,41 +2947,9 @@
 true.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_splitlines__doc__,
-"splitlines($self, /, keepends=False)\n"
-"--\n"
-"\n"
-"Return a list of the lines in the bytes, breaking at line boundaries.\n"
-"\n"
-"Line breaks are not included in the resulting list unless keepends is given and\n"
-"true.");
-
-#define BYTES_SPLITLINES_METHODDEF    \
-    {"splitlines", (PyCFunction)bytes_splitlines, METH_VARARGS|METH_KEYWORDS, bytes_splitlines__doc__},
-
-static PyObject *
-bytes_splitlines_impl(PyBytesObject*self, int keepends);
-
-static PyObject *
-bytes_splitlines(PyBytesObject*self, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"keepends", NULL};
-    int keepends = 0;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "|i:splitlines", _keywords,
-        &keepends))
-        goto exit;
-    return_value = bytes_splitlines_impl(self, keepends);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_splitlines_impl(PyBytesObject*self, int keepends)
-/*[clinic end generated code: output=79da057d05d126de input=ddb93e3351080c8c]*/
+/*[clinic end generated code: output=995c3598f7833cad input=ddb93e3351080c8c]*/
 {
     return stringlib_splitlines(
         (PyObject*) self, PyBytes_AS_STRING(self),
@@ -3445,40 +2986,9 @@
 Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(bytes_fromhex__doc__,
-"fromhex($type, string, /)\n"
-"--\n"
-"\n"
-"Create a bytes object from a string of hexadecimal numbers.\n"
-"\n"
-"Spaces between two numbers are accepted.\n"
-"Example: bytes.fromhex(\'B9 01EF\') -> b\'\\\\xb9\\\\x01\\\\xef\'.");
-
-#define BYTES_FROMHEX_METHODDEF    \
-    {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, bytes_fromhex__doc__},
-
-static PyObject *
-bytes_fromhex_impl(PyTypeObject *type, PyObject *string);
-
-static PyObject *
-bytes_fromhex(PyTypeObject *type, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *string;
-
-    if (!PyArg_ParseTuple(args,
-        "U:fromhex",
-        &string))
-        goto exit;
-    return_value = bytes_fromhex_impl(type, string);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 bytes_fromhex_impl(PyTypeObject *type, PyObject *string)
-/*[clinic end generated code: output=09e6cbef56cbbb65 input=bf4d1c361670acd3]*/
+/*[clinic end generated code: output=0973acc63661bb2e input=bf4d1c361670acd3]*/
 {
     PyObject *newstring;
     char *buf;
diff --git a/Objects/bytearrayobject.c b/Objects/clinic/bytearrayobject.c.h
copy from Objects/bytearrayobject.c
copy to Objects/clinic/bytearrayobject.c.h
--- a/Objects/bytearrayobject.c
+++ b/Objects/clinic/bytearrayobject.c.h
@@ -1,1269 +1,5 @@
-/* PyByteArray (bytearray) implementation */
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-#include "structmember.h"
-#include "bytes_methods.h"
-#include "bytesobject.h"
-
 /*[clinic input]
-class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
-
-char _PyByteArray_empty_string[] = "";
-
-void
-PyByteArray_Fini(void)
-{
-}
-
-int
-PyByteArray_Init(void)
-{
-    return 1;
-}
-
-/* end nullbytes support */
-
-/* Helpers */
-
-static int
-_getbytevalue(PyObject* arg, int *value)
-{
-    long face_value;
-
-    if (PyLong_Check(arg)) {
-        face_value = PyLong_AsLong(arg);
-    } else {
-        PyObject *index = PyNumber_Index(arg);
-        if (index == NULL) {
-            PyErr_Format(PyExc_TypeError, "an integer is required");
-            *value = -1;
-            return 0;
-        }
-        face_value = PyLong_AsLong(index);
-        Py_DECREF(index);
-    }
-
-    if (face_value < 0 || face_value >= 256) {
-        /* this includes the OverflowError in case the long is too large */
-        PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
-        *value = -1;
-        return 0;
-    }
-
-    *value = face_value;
-    return 1;
-}
-
-static int
-bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
-{
-    void *ptr;
-    if (view == NULL) {
-        PyErr_SetString(PyExc_BufferError,
-            "bytearray_getbuffer: view==NULL argument is obsolete");
-        return -1;
-    }
-    ptr = (void *) PyByteArray_AS_STRING(obj);
-    /* cannot fail if view != NULL and readonly == 0 */
-    (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
-    obj->ob_exports++;
-    return 0;
-}
-
-static void
-bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
-{
-    obj->ob_exports--;
-}
-
-static int
-_canresize(PyByteArrayObject *self)
-{
-    if (self->ob_exports > 0) {
-        PyErr_SetString(PyExc_BufferError,
-                "Existing exports of data: object cannot be re-sized");
-        return 0;
-    }
-    return 1;
-}
-
-/* Direct API functions */
-
-PyObject *
-PyByteArray_FromObject(PyObject *input)
-{
-    return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
-                                        input, NULL);
-}
-
-PyObject *
-PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
-{
-    PyByteArrayObject *new;
-    Py_ssize_t alloc;
-
-    if (size < 0) {
-        PyErr_SetString(PyExc_SystemError,
-            "Negative size passed to PyByteArray_FromStringAndSize");
-        return NULL;
-    }
-
-    /* Prevent buffer overflow when setting alloc to size+1. */
-    if (size == PY_SSIZE_T_MAX) {
-        return PyErr_NoMemory();
-    }
-
-    new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
-    if (new == NULL)
-        return NULL;
-
-    if (size == 0) {
-        new->ob_bytes = NULL;
-        alloc = 0;
-    }
-    else {
-        alloc = size + 1;
-        new->ob_bytes = PyObject_Malloc(alloc);
-        if (new->ob_bytes == NULL) {
-            Py_DECREF(new);
-            return PyErr_NoMemory();
-        }
-        if (bytes != NULL && size > 0)
-            memcpy(new->ob_bytes, bytes, size);
-        new->ob_bytes[size] = '\0';  /* Trailing null byte */
-    }
-    Py_SIZE(new) = size;
-    new->ob_alloc = alloc;
-    new->ob_start = new->ob_bytes;
-    new->ob_exports = 0;
-
-    return (PyObject *)new;
-}
-
-Py_ssize_t
-PyByteArray_Size(PyObject *self)
-{
-    assert(self != NULL);
-    assert(PyByteArray_Check(self));
-
-    return PyByteArray_GET_SIZE(self);
-}
-
-char  *
-PyByteArray_AsString(PyObject *self)
-{
-    assert(self != NULL);
-    assert(PyByteArray_Check(self));
-
-    return PyByteArray_AS_STRING(self);
-}
-
-int
-PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
-{
-    void *sval;
-    PyByteArrayObject *obj = ((PyByteArrayObject *)self);
-    /* All computations are done unsigned to avoid integer overflows
-       (see issue #22335). */
-    size_t alloc = (size_t) obj->ob_alloc;
-    size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
-    size_t size = (size_t) requested_size;
-
-    assert(self != NULL);
-    assert(PyByteArray_Check(self));
-    assert(logical_offset <= alloc);
-    assert(requested_size >= 0);
-
-    if (requested_size == Py_SIZE(self)) {
-        return 0;
-    }
-    if (!_canresize(obj)) {
-        return -1;
-    }
-
-    if (size + logical_offset + 1 < alloc) {
-        /* Current buffer is large enough to host the requested size,
-           decide on a strategy. */
-        if (size < alloc / 2) {
-            /* Major downsize; resize down to exact size */
-            alloc = size + 1;
-        }
-        else {
-            /* Minor downsize; quick exit */
-            Py_SIZE(self) = size;
-            PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
-            return 0;
-        }
-    }
-    else {
-        /* Need growing, decide on a strategy */
-        if (size <= alloc * 1.125) {
-            /* Moderate upsize; overallocate similar to list_resize() */
-            alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
-        }
-        else {
-            /* Major upsize; resize up to exact size */
-            alloc = size + 1;
-        }
-    }
-    if (alloc > PY_SSIZE_T_MAX) {
-        PyErr_NoMemory();
-        return -1;
-    }
-
-    if (logical_offset > 0) {
-        sval = PyObject_Malloc(alloc);
-        if (sval == NULL) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        memcpy(sval, PyByteArray_AS_STRING(self),
-               Py_MIN(requested_size, Py_SIZE(self)));
-        PyObject_Free(obj->ob_bytes);
-    }
-    else {
-        sval = PyObject_Realloc(obj->ob_bytes, alloc);
-        if (sval == NULL) {
-            PyErr_NoMemory();
-            return -1;
-        }
-    }
-
-    obj->ob_bytes = obj->ob_start = sval;
-    Py_SIZE(self) = size;
-    obj->ob_alloc = alloc;
-    obj->ob_bytes[size] = '\0'; /* Trailing null byte */
-
-    return 0;
-}
-
-PyObject *
-PyByteArray_Concat(PyObject *a, PyObject *b)
-{
-    Py_ssize_t size;
-    Py_buffer va, vb;
-    PyByteArrayObject *result = NULL;
-
-    va.len = -1;
-    vb.len = -1;
-    if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
-        PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
-            PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
-                         Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
-            goto done;
-    }
-
-    size = va.len + vb.len;
-    if (size < 0) {
-            PyErr_NoMemory();
-            goto done;
-    }
-
-    result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
-    if (result != NULL) {
-        memcpy(result->ob_bytes, va.buf, va.len);
-        memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
-    }
-
-  done:
-    if (va.len != -1)
-        PyBuffer_Release(&va);
-    if (vb.len != -1)
-        PyBuffer_Release(&vb);
-    return (PyObject *)result;
-}
-
-static PyObject *
-bytearray_format(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *bytes_in, *bytes_out, *res;
-    char *bytestring;
-
-    if (self == NULL || !PyByteArray_Check(self) || args == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    bytestring = PyByteArray_AS_STRING(self);
-    bytes_in = PyBytes_FromString(bytestring);
-    if (bytes_in == NULL)
-        return NULL;
-    bytes_out = _PyBytes_Format(bytes_in, args);
-    Py_DECREF(bytes_in);
-    if (bytes_out == NULL)
-        return NULL;
-    res = PyByteArray_FromObject(bytes_out);
-    Py_DECREF(bytes_out);
-    if (res == NULL)
-        return NULL;
-    return res;
-}
-
-/* Functions stuffed into the type object */
-
-static Py_ssize_t
-bytearray_length(PyByteArrayObject *self)
-{
-    return Py_SIZE(self);
-}
-
-static PyObject *
-bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
-{
-    Py_ssize_t mysize;
-    Py_ssize_t size;
-    Py_buffer vo;
-
-    if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
-        PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
-                     Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
-        return NULL;
-    }
-
-    mysize = Py_SIZE(self);
-    size = mysize + vo.len;
-    if (size < 0) {
-        PyBuffer_Release(&vo);
-        return PyErr_NoMemory();
-    }
-    if (size < self->ob_alloc) {
-        Py_SIZE(self) = size;
-        PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
-    }
-    else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
-        PyBuffer_Release(&vo);
-        return NULL;
-    }
-    memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
-    PyBuffer_Release(&vo);
-    Py_INCREF(self);
-    return (PyObject *)self;
-}
-
-static PyObject *
-bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
-{
-    PyByteArrayObject *result;
-    Py_ssize_t mysize;
-    Py_ssize_t size;
-
-    if (count < 0)
-        count = 0;
-    mysize = Py_SIZE(self);
-    if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
-        return PyErr_NoMemory();
-    size = mysize * count;
-    result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
-    if (result != NULL && size != 0) {
-        if (mysize == 1)
-            memset(result->ob_bytes, self->ob_bytes[0], size);
-        else {
-            Py_ssize_t i;
-            for (i = 0; i < count; i++)
-                memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
-        }
-    }
-    return (PyObject *)result;
-}
-
-static PyObject *
-bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
-{
-    Py_ssize_t mysize;
-    Py_ssize_t size;
-    char *buf;
-
-    if (count < 0)
-        count = 0;
-    mysize = Py_SIZE(self);
-    if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
-        return PyErr_NoMemory();
-    size = mysize * count;
-    if (PyByteArray_Resize((PyObject *)self, size) < 0)
-        return NULL;
-
-    buf = PyByteArray_AS_STRING(self);
-    if (mysize == 1)
-        memset(buf, buf[0], size);
-    else {
-        Py_ssize_t i;
-        for (i = 1; i < count; i++)
-            memcpy(buf + i*mysize, buf, mysize);
-    }
-
-    Py_INCREF(self);
-    return (PyObject *)self;
-}
-
-static PyObject *
-bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
-{
-    if (i < 0)
-        i += Py_SIZE(self);
-    if (i < 0 || i >= Py_SIZE(self)) {
-        PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
-        return NULL;
-    }
-    return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
-}
-
-static PyObject *
-bytearray_subscript(PyByteArrayObject *self, PyObject *index)
-{
-    if (PyIndex_Check(index)) {
-        Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
-
-        if (i == -1 && PyErr_Occurred())
-            return NULL;
-
-        if (i < 0)
-            i += PyByteArray_GET_SIZE(self);
-
-        if (i < 0 || i >= Py_SIZE(self)) {
-            PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
-            return NULL;
-        }
-        return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
-    }
-    else if (PySlice_Check(index)) {
-        Py_ssize_t start, stop, step, slicelength, cur, i;
-        if (PySlice_GetIndicesEx(index,
-                                 PyByteArray_GET_SIZE(self),
-                                 &start, &stop, &step, &slicelength) < 0) {
-            return NULL;
-        }
-
-        if (slicelength <= 0)
-            return PyByteArray_FromStringAndSize("", 0);
-        else if (step == 1) {
-            return PyByteArray_FromStringAndSize(
-                PyByteArray_AS_STRING(self) + start, slicelength);
-        }
-        else {
-            char *source_buf = PyByteArray_AS_STRING(self);
-            char *result_buf;
-            PyObject *result;
-
-            result = PyByteArray_FromStringAndSize(NULL, slicelength);
-            if (result == NULL)
-                return NULL;
-
-            result_buf = PyByteArray_AS_STRING(result);
-            for (cur = start, i = 0; i < slicelength;
-                 cur += step, i++) {
-                     result_buf[i] = source_buf[cur];
-            }
-            return result;
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "bytearray indices must be integers or slices, not %.200s",
-                     Py_TYPE(index)->tp_name);
-        return NULL;
-    }
-}
-
-static int
-bytearray_setslice_linear(PyByteArrayObject *self,
-                          Py_ssize_t lo, Py_ssize_t hi,
-                          char *bytes, Py_ssize_t bytes_len)
-{
-    Py_ssize_t avail = hi - lo;
-    char *buf = PyByteArray_AS_STRING(self);
-    Py_ssize_t growth = bytes_len - avail;
-    int res = 0;
-    assert(avail >= 0);
-
-    if (growth < 0) {
-        if (!_canresize(self))
-            return -1;
-
-        if (lo == 0) {
-            /* Shrink the buffer by advancing its logical start */
-            self->ob_start -= growth;
-            /*
-              0   lo               hi             old_size
-              |   |<----avail----->|<-----tail------>|
-              |      |<-bytes_len->|<-----tail------>|
-              0    new_lo         new_hi          new_size
-            */
-        }
-        else {
-            /*
-              0   lo               hi               old_size
-              |   |<----avail----->|<-----tomove------>|
-              |   |<-bytes_len->|<-----tomove------>|
-              0   lo         new_hi              new_size
-            */
-            memmove(buf + lo + bytes_len, buf + hi,
-                    Py_SIZE(self) - hi);
-        }
-        if (PyByteArray_Resize((PyObject *)self,
-                               Py_SIZE(self) + growth) < 0) {
-            /* Issue #19578: Handling the memory allocation failure here is
-               tricky here because the bytearray object has already been
-               modified. Depending on growth and lo, the behaviour is
-               different.
-
-               If growth < 0 and lo != 0, the operation is completed, but a
-               MemoryError is still raised and the memory block is not
-               shrinked. Otherwise, the bytearray is restored in its previous
-               state and a MemoryError is raised. */
-            if (lo == 0) {
-                self->ob_start += growth;
-                return -1;
-            }
-            /* memmove() removed bytes, the bytearray object cannot be
-               restored in its previous state. */
-            Py_SIZE(self) += growth;
-            res = -1;
-        }
-        buf = PyByteArray_AS_STRING(self);
-    }
-    else if (growth > 0) {
-        if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
-            PyErr_NoMemory();
-            return -1;
-        }
-
-        if (PyByteArray_Resize((PyObject *)self,
-                               Py_SIZE(self) + growth) < 0) {
-            return -1;
-        }
-        buf = PyByteArray_AS_STRING(self);
-        /* Make the place for the additional bytes */
-        /*
-          0   lo        hi               old_size
-          |   |<-avail->|<-----tomove------>|
-          |   |<---bytes_len-->|<-----tomove------>|
-          0   lo            new_hi              new_size
-         */
-        memmove(buf + lo + bytes_len, buf + hi,
-                Py_SIZE(self) - lo - bytes_len);
-    }
-
-    if (bytes_len > 0)
-        memcpy(buf + lo, bytes, bytes_len);
-    return res;
-}
-
-static int
-bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
-               PyObject *values)
-{
-    Py_ssize_t needed;
-    void *bytes;
-    Py_buffer vbytes;
-    int res = 0;
-
-    vbytes.len = -1;
-    if (values == (PyObject *)self) {
-        /* Make a copy and call this function recursively */
-        int err;
-        values = PyByteArray_FromObject(values);
-        if (values == NULL)
-            return -1;
-        err = bytearray_setslice(self, lo, hi, values);
-        Py_DECREF(values);
-        return err;
-    }
-    if (values == NULL) {
-        /* del b[lo:hi] */
-        bytes = NULL;
-        needed = 0;
-    }
-    else {
-        if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
-            PyErr_Format(PyExc_TypeError,
-                         "can't set bytearray slice from %.100s",
-                         Py_TYPE(values)->tp_name);
-            return -1;
-        }
-        needed = vbytes.len;
-        bytes = vbytes.buf;
-    }
-
-    if (lo < 0)
-        lo = 0;
-    if (hi < lo)
-        hi = lo;
-    if (hi > Py_SIZE(self))
-        hi = Py_SIZE(self);
-
-    res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
-    if (vbytes.len != -1)
-        PyBuffer_Release(&vbytes);
-    return res;
-}
-
-static int
-bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
-{
-    int ival;
-
-    if (i < 0)
-        i += Py_SIZE(self);
-
-    if (i < 0 || i >= Py_SIZE(self)) {
-        PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
-        return -1;
-    }
-
-    if (value == NULL)
-        return bytearray_setslice(self, i, i+1, NULL);
-
-    if (!_getbytevalue(value, &ival))
-        return -1;
-
-    PyByteArray_AS_STRING(self)[i] = ival;
-    return 0;
-}
-
-static int
-bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
-{
-    Py_ssize_t start, stop, step, slicelen, needed;
-    char *buf, *bytes;
-    buf = PyByteArray_AS_STRING(self);
-
-    if (PyIndex_Check(index)) {
-        Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
-
-        if (i == -1 && PyErr_Occurred())
-            return -1;
-
-        if (i < 0)
-            i += PyByteArray_GET_SIZE(self);
-
-        if (i < 0 || i >= Py_SIZE(self)) {
-            PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
-            return -1;
-        }
-
-        if (values == NULL) {
-            /* Fall through to slice assignment */
-            start = i;
-            stop = i + 1;
-            step = 1;
-            slicelen = 1;
-        }
-        else {
-            int ival;
-            if (!_getbytevalue(values, &ival))
-                return -1;
-            buf[i] = (char)ival;
-            return 0;
-        }
-    }
-    else if (PySlice_Check(index)) {
-        if (PySlice_GetIndicesEx(index,
-                                 PyByteArray_GET_SIZE(self),
-                                 &start, &stop, &step, &slicelen) < 0) {
-            return -1;
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "bytearray indices must be integers or slices, not %.200s",
-                      Py_TYPE(index)->tp_name);
-        return -1;
-    }
-
-    if (values == NULL) {
-        bytes = NULL;
-        needed = 0;
-    }
-    else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
-        int err;
-        if (PyNumber_Check(values) || PyUnicode_Check(values)) {
-            PyErr_SetString(PyExc_TypeError,
-                            "can assign only bytes, buffers, or iterables "
-                            "of ints in range(0, 256)");
-            return -1;
-        }
-        /* Make a copy and call this function recursively */
-        values = PyByteArray_FromObject(values);
-        if (values == NULL)
-            return -1;
-        err = bytearray_ass_subscript(self, index, values);
-        Py_DECREF(values);
-        return err;
-    }
-    else {
-        assert(PyByteArray_Check(values));
-        bytes = PyByteArray_AS_STRING(values);
-        needed = Py_SIZE(values);
-    }
-    /* Make sure b[5:2] = ... inserts before 5, not before 2. */
-    if ((step < 0 && start < stop) ||
-        (step > 0 && start > stop))
-        stop = start;
-    if (step == 1) {
-        return bytearray_setslice_linear(self, start, stop, bytes, needed);
-    }
-    else {
-        if (needed == 0) {
-            /* Delete slice */
-            size_t cur;
-            Py_ssize_t i;
-
-            if (!_canresize(self))
-                return -1;
-
-            if (slicelen == 0)
-                /* Nothing to do here. */
-                return 0;
-
-            if (step < 0) {
-                stop = start + 1;
-                start = stop + step * (slicelen - 1) - 1;
-                step = -step;
-            }
-            for (cur = start, i = 0;
-                 i < slicelen; cur += step, i++) {
-                Py_ssize_t lim = step - 1;
-
-                if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
-                    lim = PyByteArray_GET_SIZE(self) - cur - 1;
-
-                memmove(buf + cur - i,
-                        buf + cur + 1, lim);
-            }
-            /* Move the tail of the bytes, in one chunk */
-            cur = start + (size_t)slicelen*step;
-            if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
-                memmove(buf + cur - slicelen,
-                        buf + cur,
-                        PyByteArray_GET_SIZE(self) - cur);
-            }
-            if (PyByteArray_Resize((PyObject *)self,
-                               PyByteArray_GET_SIZE(self) - slicelen) < 0)
-                return -1;
-
-            return 0;
-        }
-        else {
-            /* Assign slice */
-            Py_ssize_t i;
-            size_t cur;
-
-            if (needed != slicelen) {
-                PyErr_Format(PyExc_ValueError,
-                             "attempt to assign bytes of size %zd "
-                             "to extended slice of size %zd",
-                             needed, slicelen);
-                return -1;
-            }
-            for (cur = start, i = 0; i < slicelen; cur += step, i++)
-                buf[cur] = bytes[i];
-            return 0;
-        }
-    }
-}
-
-static int
-bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
-{
-    static char *kwlist[] = {"source", "encoding", "errors", 0};
-    PyObject *arg = NULL;
-    const char *encoding = NULL;
-    const char *errors = NULL;
-    Py_ssize_t count;
-    PyObject *it;
-    PyObject *(*iternext)(PyObject *);
-
-    if (Py_SIZE(self) != 0) {
-        /* Empty previous contents (yes, do this first of all!) */
-        if (PyByteArray_Resize((PyObject *)self, 0) < 0)
-            return -1;
-    }
-
-    /* Parse arguments */
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
-                                     &arg, &encoding, &errors))
-        return -1;
-
-    /* Make a quick exit if no first argument */
-    if (arg == NULL) {
-        if (encoding != NULL || errors != NULL) {
-            PyErr_SetString(PyExc_TypeError,
-                            "encoding or errors without sequence argument");
-            return -1;
-        }
-        return 0;
-    }
-
-    if (PyUnicode_Check(arg)) {
-        /* Encode via the codec registry */
-        PyObject *encoded, *new;
-        if (encoding == NULL) {
-            PyErr_SetString(PyExc_TypeError,
-                            "string argument without an encoding");
-            return -1;
-        }
-        encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
-        if (encoded == NULL)
-            return -1;
-        assert(PyBytes_Check(encoded));
-        new = bytearray_iconcat(self, encoded);
-        Py_DECREF(encoded);
-        if (new == NULL)
-            return -1;
-        Py_DECREF(new);
-        return 0;
-    }
-
-    /* If it's not unicode, there can't be encoding or errors */
-    if (encoding != NULL || errors != NULL) {
-        PyErr_SetString(PyExc_TypeError,
-                        "encoding or errors without a string argument");
-        return -1;
-    }
-
-    /* Is it an int? */
-    count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
-    if (count == -1 && PyErr_Occurred()) {
-        if (PyErr_ExceptionMatches(PyExc_OverflowError))
-            return -1;
-        PyErr_Clear();
-    }
-    else if (count < 0) {
-        PyErr_SetString(PyExc_ValueError, "negative count");
-        return -1;
-    }
-    else {
-        if (count > 0) {
-            if (PyByteArray_Resize((PyObject *)self, count))
-                return -1;
-            memset(PyByteArray_AS_STRING(self), 0, count);
-        }
-        return 0;
-    }
-
-    /* Use the buffer API */
-    if (PyObject_CheckBuffer(arg)) {
-        Py_ssize_t size;
-        Py_buffer view;
-        if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
-            return -1;
-        size = view.len;
-        if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
-        if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
-            &view, size, 'C') < 0)
-            goto fail;
-        PyBuffer_Release(&view);
-        return 0;
-    fail:
-        PyBuffer_Release(&view);
-        return -1;
-    }
-
-    /* XXX Optimize this if the arguments is a list, tuple */
-
-    /* Get the iterator */
-    it = PyObject_GetIter(arg);
-    if (it == NULL)
-        return -1;
-    iternext = *Py_TYPE(it)->tp_iternext;
-
-    /* Run the iterator to exhaustion */
-    for (;;) {
-        PyObject *item;
-        int rc, value;
-
-        /* Get the next item */
-        item = iternext(it);
-        if (item == NULL) {
-            if (PyErr_Occurred()) {
-                if (!PyErr_ExceptionMatches(PyExc_StopIteration))
-                    goto error;
-                PyErr_Clear();
-            }
-            break;
-        }
-
-        /* Interpret it as an int (__index__) */
-        rc = _getbytevalue(item, &value);
-        Py_DECREF(item);
-        if (!rc)
-            goto error;
-
-        /* Append the byte */
-        if (Py_SIZE(self) < self->ob_alloc)
-            Py_SIZE(self)++;
-        else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
-            goto error;
-        PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
-    }
-
-    /* Clean up and return success */
-    Py_DECREF(it);
-    return 0;
-
- error:
-    /* Error handling when it != NULL */
-    Py_DECREF(it);
-    return -1;
-}
-
-/* Mostly copied from string_repr, but without the
-   "smart quote" functionality. */
-static PyObject *
-bytearray_repr(PyByteArrayObject *self)
-{
-    const char *quote_prefix = "bytearray(b";
-    const char *quote_postfix = ")";
-    Py_ssize_t length = Py_SIZE(self);
-    /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
-    size_t newsize;
-    PyObject *v;
-    Py_ssize_t i;
-    char *bytes;
-    char c;
-    char *p;
-    int quote;
-    char *test, *start;
-    char *buffer;
-
-    if (length > (PY_SSIZE_T_MAX - 15) / 4) {
-        PyErr_SetString(PyExc_OverflowError,
-            "bytearray object is too large to make repr");
-        return NULL;
-    }
-
-    newsize = 15 + length * 4;
-    buffer = PyObject_Malloc(newsize);
-    if (buffer == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-
-    /* Figure out which quote to use; single is preferred */
-    quote = '\'';
-    start = PyByteArray_AS_STRING(self);
-    for (test = start; test < start+length; ++test) {
-        if (*test == '"') {
-            quote = '\''; /* back to single */
-            break;
-        }
-        else if (*test == '\'')
-            quote = '"';
-    }
-
-    p = buffer;
-    while (*quote_prefix)
-        *p++ = *quote_prefix++;
-    *p++ = quote;
-
-    bytes = PyByteArray_AS_STRING(self);
-    for (i = 0; i < length; i++) {
-        /* There's at least enough room for a hex escape
-           and a closing quote. */
-        assert(newsize - (p - buffer) >= 5);
-        c = bytes[i];
-        if (c == '\'' || c == '\\')
-            *p++ = '\\', *p++ = c;
-        else if (c == '\t')
-            *p++ = '\\', *p++ = 't';
-        else if (c == '\n')
-            *p++ = '\\', *p++ = 'n';
-        else if (c == '\r')
-            *p++ = '\\', *p++ = 'r';
-        else if (c == 0)
-            *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
-        else if (c < ' ' || c >= 0x7f) {
-            *p++ = '\\';
-            *p++ = 'x';
-            *p++ = Py_hexdigits[(c & 0xf0) >> 4];
-            *p++ = Py_hexdigits[c & 0xf];
-        }
-        else
-            *p++ = c;
-    }
-    assert(newsize - (p - buffer) >= 1);
-    *p++ = quote;
-    while (*quote_postfix) {
-       *p++ = *quote_postfix++;
-    }
-
-    v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
-    PyObject_Free(buffer);
-    return v;
-}
-
-static PyObject *
-bytearray_str(PyObject *op)
-{
-        if (Py_BytesWarningFlag) {
-                if (PyErr_WarnEx(PyExc_BytesWarning,
-                                 "str() on a bytearray instance", 1))
-                        return NULL;
-        }
-        return bytearray_repr((PyByteArrayObject*)op);
-}
-
-static PyObject *
-bytearray_richcompare(PyObject *self, PyObject *other, int op)
-{
-    Py_ssize_t self_size, other_size;
-    Py_buffer self_bytes, other_bytes;
-    PyObject *res;
-    Py_ssize_t minsize;
-    int cmp;
-
-    /* Bytes can be compared to anything that supports the (binary)
-       buffer API.  Except that a comparison with Unicode is always an
-       error, even if the comparison is for equality. */
-    if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
-        PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
-        if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
-            if (PyErr_WarnEx(PyExc_BytesWarning,
-                            "Comparison between bytearray and string", 1))
-                return NULL;
-        }
-
-        Py_RETURN_NOTIMPLEMENTED;
-    }
-
-    if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
-        PyErr_Clear();
-        Py_RETURN_NOTIMPLEMENTED;
-    }
-    self_size = self_bytes.len;
-
-    if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
-        PyErr_Clear();
-        PyBuffer_Release(&self_bytes);
-        Py_RETURN_NOTIMPLEMENTED;
-    }
-    other_size = other_bytes.len;
-
-    if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
-        /* Shortcut: if the lengths differ, the objects differ */
-        cmp = (op == Py_NE);
-    }
-    else {
-        minsize = self_size;
-        if (other_size < minsize)
-            minsize = other_size;
-
-        cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
-        /* In ISO C, memcmp() guarantees to use unsigned bytes! */
-
-        if (cmp == 0) {
-            if (self_size < other_size)
-                cmp = -1;
-            else if (self_size > other_size)
-                cmp = 1;
-        }
-
-        switch (op) {
-        case Py_LT: cmp = cmp <  0; break;
-        case Py_LE: cmp = cmp <= 0; break;
-        case Py_EQ: cmp = cmp == 0; break;
-        case Py_NE: cmp = cmp != 0; break;
-        case Py_GT: cmp = cmp >  0; break;
-        case Py_GE: cmp = cmp >= 0; break;
-        }
-    }
-
-    res = cmp ? Py_True : Py_False;
-    PyBuffer_Release(&self_bytes);
-    PyBuffer_Release(&other_bytes);
-    Py_INCREF(res);
-    return res;
-}
-
-static void
-bytearray_dealloc(PyByteArrayObject *self)
-{
-    if (self->ob_exports > 0) {
-        PyErr_SetString(PyExc_SystemError,
-                        "deallocated bytearray object has exported buffers");
-        PyErr_Print();
-    }
-    if (self->ob_bytes != 0) {
-        PyObject_Free(self->ob_bytes);
-    }
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-
-/* -------------------------------------------------------------------- */
-/* Methods */
-
-#define FASTSEARCH fastsearch
-#define STRINGLIB(F) stringlib_##F
-#define STRINGLIB_CHAR char
-#define STRINGLIB_SIZEOF_CHAR 1
-#define STRINGLIB_LEN PyByteArray_GET_SIZE
-#define STRINGLIB_STR PyByteArray_AS_STRING
-#define STRINGLIB_NEW PyByteArray_FromStringAndSize
-#define STRINGLIB_ISSPACE Py_ISSPACE
-#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
-#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
-#define STRINGLIB_MUTABLE 1
-
-#include "stringlib/fastsearch.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/join.h"
-#include "stringlib/partition.h"
-#include "stringlib/split.h"
-#include "stringlib/ctype.h"
-#include "stringlib/transmogrify.h"
-
-
-/* The following Py_LOCAL_INLINE and Py_LOCAL functions
-were copied from the old char* style string object. */
-
-/* helper macro to fixup start/end slice values */
-#define ADJUST_INDICES(start, end, len)         \
-    if (end > len)                              \
-        end = len;                              \
-    else if (end < 0) {                         \
-        end += len;                             \
-        if (end < 0)                            \
-            end = 0;                            \
-    }                                           \
-    if (start < 0) {                            \
-        start += len;                           \
-        if (start < 0)                          \
-            start = 0;                          \
-    }
-
-Py_LOCAL_INLINE(Py_ssize_t)
-bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
-{
-    PyObject *subobj;
-    char byte;
-    Py_buffer subbuf;
-    const char *sub;
-    Py_ssize_t len, sub_len;
-    Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
-    Py_ssize_t res;
-
-    if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
-                                         args, &subobj, &byte, &start, &end))
-        return -2;
-
-    if (subobj) {
-        if (PyObject_GetBuffer(subobj, &subbuf, PyBUF_SIMPLE) != 0)
-            return -2;
-
-        sub = subbuf.buf;
-        sub_len = subbuf.len;
-    }
-    else {
-        sub = &byte;
-        sub_len = 1;
-    }
-    len = PyByteArray_GET_SIZE(self);
-
-    ADJUST_INDICES(start, end, len);
-    if (end - start < sub_len)
-        res = -1;
-    /* Issue #23573: FIXME, windows has no memrchr() */
-    else if (sub_len == 1 && dir > 0) {
-        unsigned char needle = *sub;
-        int mode = (dir > 0) ? FAST_SEARCH : FAST_RSEARCH;
-        res = stringlib_fastsearch_memchr_1char(
-            PyByteArray_AS_STRING(self) + start, end - start,
-            needle, needle, mode);
-        if (res >= 0)
-            res += start;
-    }
-    else {
-        if (dir > 0)
-            res = stringlib_find_slice(
-                PyByteArray_AS_STRING(self), len,
-                sub, sub_len, start, end);
-        else
-            res = stringlib_rfind_slice(
-                PyByteArray_AS_STRING(self), len,
-                sub, sub_len, start, end);
-    }
-
-    if (subobj)
-        PyBuffer_Release(&subbuf);
-
-    return res;
-}
-
-PyDoc_STRVAR(find__doc__,
-"B.find(sub[, start[, end]]) -> int\n\
-\n\
-Return the lowest index in B where subsection sub is found,\n\
-such that sub is contained within B[start,end].  Optional\n\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-bytearray_find(PyByteArrayObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytearray_find_internal(self, args, +1);
-    if (result == -2)
-        return NULL;
-    return PyLong_FromSsize_t(result);
-}
-
-PyDoc_STRVAR(count__doc__,
-"B.count(sub[, start[, end]]) -> int\n\
-\n\
-Return the number of non-overlapping occurrences of subsection sub in\n\
-bytes B[start:end].  Optional arguments start and end are interpreted\n\
-as in slice notation.");
-
-static PyObject *
-bytearray_count(PyByteArrayObject *self, PyObject *args)
-{
-    PyObject *sub_obj;
-    const char *str = PyByteArray_AS_STRING(self), *sub;
-    Py_ssize_t sub_len;
-    char byte;
-    Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
-
-    Py_buffer vsub;
-    PyObject *count_obj;
-
-    if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
-                                         &start, &end))
-        return NULL;
-
-    if (sub_obj) {
-        if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0)
-            return NULL;
-
-        sub = vsub.buf;
-        sub_len = vsub.len;
-    }
-    else {
-        sub = &byte;
-        sub_len = 1;
-    }
-
-    ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
-
-    count_obj = PyLong_FromSsize_t(
-        stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
-        );
-
-    if (sub_obj)
-        PyBuffer_Release(&vsub);
-
-    return count_obj;
-}
-
-/*[clinic input]
-bytearray.clear
-
-    self: self(type="PyByteArrayObject *")
-
-Remove all items from the bytearray.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(bytearray_clear__doc__,
@@ -1284,23 +20,6 @@
     return bytearray_clear_impl(self);
 }
 
-static PyObject *
-bytearray_clear_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=5344093031e2f36c input=e524fd330abcdc18]*/
-{
-    if (PyByteArray_Resize((PyObject *)self, 0) < 0)
-        return NULL;
-    Py_RETURN_NONE;
-}
-
-/*[clinic input]
-bytearray.copy
-
-    self: self(type="PyByteArrayObject *")
-
-Return a copy of B.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_copy__doc__,
 "copy($self, /)\n"
 "--\n"
@@ -1319,244 +38,6 @@
     return bytearray_copy_impl(self);
 }
 
-static PyObject *
-bytearray_copy_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=8788ed299f7f2214 input=6d5d2975aa0f33f3]*/
-{
-    return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
-                                         PyByteArray_GET_SIZE(self));
-}
-
-PyDoc_STRVAR(index__doc__,
-"B.index(sub[, start[, end]]) -> int\n\
-\n\
-Like B.find() but raise ValueError when the subsection is not found.");
-
-static PyObject *
-bytearray_index(PyByteArrayObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytearray_find_internal(self, args, +1);
-    if (result == -2)
-        return NULL;
-    if (result == -1) {
-        PyErr_SetString(PyExc_ValueError,
-                        "subsection not found");
-        return NULL;
-    }
-    return PyLong_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(rfind__doc__,
-"B.rfind(sub[, start[, end]]) -> int\n\
-\n\
-Return the highest index in B where subsection sub is found,\n\
-such that sub is contained within B[start,end].  Optional\n\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-bytearray_rfind(PyByteArrayObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytearray_find_internal(self, args, -1);
-    if (result == -2)
-        return NULL;
-    return PyLong_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(rindex__doc__,
-"B.rindex(sub[, start[, end]]) -> int\n\
-\n\
-Like B.rfind() but raise ValueError when the subsection is not found.");
-
-static PyObject *
-bytearray_rindex(PyByteArrayObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytearray_find_internal(self, args, -1);
-    if (result == -2)
-        return NULL;
-    if (result == -1) {
-        PyErr_SetString(PyExc_ValueError,
-                        "subsection not found");
-        return NULL;
-    }
-    return PyLong_FromSsize_t(result);
-}
-
-
-static int
-bytearray_contains(PyObject *self, PyObject *arg)
-{
-    Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
-    if (ival == -1 && PyErr_Occurred()) {
-        Py_buffer varg;
-        Py_ssize_t pos;
-        PyErr_Clear();
-        if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
-            return -1;
-        pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
-                             varg.buf, varg.len, 0);
-        PyBuffer_Release(&varg);
-        return pos >= 0;
-    }
-    if (ival < 0 || ival >= 256) {
-        PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
-        return -1;
-    }
-
-    return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
-}
-
-
-/* Matches the end (direction >= 0) or start (direction < 0) of self
- * against substr, using the start and end arguments. Returns
- * -1 on error, 0 if not found and 1 if found.
- */
-Py_LOCAL(int)
-_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
-                 Py_ssize_t end, int direction)
-{
-    Py_ssize_t len = PyByteArray_GET_SIZE(self);
-    const char* str;
-    Py_buffer vsubstr;
-    int rv = 0;
-
-    str = PyByteArray_AS_STRING(self);
-
-    if (PyObject_GetBuffer(substr, &vsubstr, PyBUF_SIMPLE) != 0)
-        return -1;
-
-    ADJUST_INDICES(start, end, len);
-
-    if (direction < 0) {
-        /* startswith */
-        if (start+vsubstr.len > len) {
-            goto done;
-        }
-    } else {
-        /* endswith */
-        if (end-start < vsubstr.len || start > len) {
-            goto done;
-        }
-
-        if (end-vsubstr.len > start)
-            start = end - vsubstr.len;
-    }
-    if (end-start >= vsubstr.len)
-        rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
-
-done:
-    PyBuffer_Release(&vsubstr);
-    return rv;
-}
-
-
-PyDoc_STRVAR(startswith__doc__,
-"B.startswith(prefix[, start[, end]]) -> bool\n\
-\n\
-Return True if B starts with the specified prefix, False otherwise.\n\
-With optional start, test B beginning at that position.\n\
-With optional end, stop comparing B at that position.\n\
-prefix can also be a tuple of bytes to try.");
-
-static PyObject *
-bytearray_startswith(PyByteArrayObject *self, PyObject *args)
-{
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    PyObject *subobj;
-    int result;
-
-    if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
-        return NULL;
-    if (PyTuple_Check(subobj)) {
-        Py_ssize_t i;
-        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-            result = _bytearray_tailmatch(self,
-                                      PyTuple_GET_ITEM(subobj, i),
-                                      start, end, -1);
-            if (result == -1)
-                return NULL;
-            else if (result) {
-                Py_RETURN_TRUE;
-            }
-        }
-        Py_RETURN_FALSE;
-    }
-    result = _bytearray_tailmatch(self, subobj, start, end, -1);
-    if (result == -1) {
-        if (PyErr_ExceptionMatches(PyExc_TypeError))
-            PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
-                         "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
-        return NULL;
-    }
-    else
-        return PyBool_FromLong(result);
-}
-
-PyDoc_STRVAR(endswith__doc__,
-"B.endswith(suffix[, start[, end]]) -> bool\n\
-\n\
-Return True if B ends with the specified suffix, False otherwise.\n\
-With optional start, test B beginning at that position.\n\
-With optional end, stop comparing B at that position.\n\
-suffix can also be a tuple of bytes to try.");
-
-static PyObject *
-bytearray_endswith(PyByteArrayObject *self, PyObject *args)
-{
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    PyObject *subobj;
-    int result;
-
-    if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
-        return NULL;
-    if (PyTuple_Check(subobj)) {
-        Py_ssize_t i;
-        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-            result = _bytearray_tailmatch(self,
-                                      PyTuple_GET_ITEM(subobj, i),
-                                      start, end, +1);
-            if (result == -1)
-                return NULL;
-            else if (result) {
-                Py_RETURN_TRUE;
-            }
-        }
-        Py_RETURN_FALSE;
-    }
-    result = _bytearray_tailmatch(self, subobj, start, end, +1);
-    if (result == -1) {
-        if (PyErr_ExceptionMatches(PyExc_TypeError))
-            PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
-                         "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
-        return NULL;
-    }
-    else
-        return PyBool_FromLong(result);
-}
-
-
-/*[clinic input]
-bytearray.translate
-
-    self: self(type="PyByteArrayObject *")
-    table: object
-        Translation table, which must be a bytes object of length 256.
-    [
-    deletechars: object
-    ]
-    /
-
-Return a copy with each character mapped by the given translation table.
-
-All characters occurring in the optional argument deletechars are removed.
-The remaining characters are mapped through the given translation table.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_translate__doc__,
 "translate(table, [deletechars])\n"
 "Return a copy with each character mapped by the given translation table.\n"
@@ -1601,113 +82,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
-/*[clinic end generated code: output=a709df81d41db4b7 input=b749ad85f4860824]*/
-{
-    char *input, *output;
-    const char *table_chars;
-    Py_ssize_t i, c;
-    PyObject *input_obj = (PyObject*)self;
-    const char *output_start;
-    Py_ssize_t inlen;
-    PyObject *result = NULL;
-    int trans_table[256];
-    Py_buffer vtable, vdel;
-
-    if (table == Py_None) {
-        table_chars = NULL;
-        table = NULL;
-    } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
-        return NULL;
-    } else {
-        if (vtable.len != 256) {
-            PyErr_SetString(PyExc_ValueError,
-                            "translation table must be 256 characters long");
-            PyBuffer_Release(&vtable);
-            return NULL;
-        }
-        table_chars = (const char*)vtable.buf;
-    }
-
-    if (deletechars != NULL) {
-        if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
-            if (table != NULL)
-                PyBuffer_Release(&vtable);
-            return NULL;
-        }
-    }
-    else {
-        vdel.buf = NULL;
-        vdel.len = 0;
-    }
-
-    inlen = PyByteArray_GET_SIZE(input_obj);
-    result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
-    if (result == NULL)
-        goto done;
-    output_start = output = PyByteArray_AsString(result);
-    input = PyByteArray_AS_STRING(input_obj);
-
-    if (vdel.len == 0 && table_chars != NULL) {
-        /* If no deletions are required, use faster code */
-        for (i = inlen; --i >= 0; ) {
-            c = Py_CHARMASK(*input++);
-            *output++ = table_chars[c];
-        }
-        goto done;
-    }
-
-    if (table_chars == NULL) {
-        for (i = 0; i < 256; i++)
-            trans_table[i] = Py_CHARMASK(i);
-    } else {
-        for (i = 0; i < 256; i++)
-            trans_table[i] = Py_CHARMASK(table_chars[i]);
-    }
-
-    for (i = 0; i < vdel.len; i++)
-        trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
-
-    for (i = inlen; --i >= 0; ) {
-        c = Py_CHARMASK(*input++);
-        if (trans_table[c] != -1)
-            if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
-                    continue;
-    }
-    /* Fix the size of the resulting string */
-    if (inlen > 0)
-        if (PyByteArray_Resize(result, output - output_start) < 0) {
-            Py_CLEAR(result);
-            goto done;
-        }
-
-done:
-    if (table != NULL)
-        PyBuffer_Release(&vtable);
-    if (deletechars != NULL)
-        PyBuffer_Release(&vdel);
-    return result;
-}
-
-
-/*[clinic input]
-
- at staticmethod
-bytearray.maketrans
-
-    frm: Py_buffer
-    to: Py_buffer
-    /
-
-Return a translation table useable for the bytes or bytearray translate method.
-
-The returned table will be one where each byte in frm is mapped to the byte at
-the same position in to.
-
-The bytes objects frm and to must be of the same length.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_maketrans__doc__,
 "maketrans(frm, to, /)\n"
 "--\n"
@@ -1749,517 +123,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
-/*[clinic end generated code: output=d332622814c26f4b input=5925a81d2fbbf151]*/
-{
-    return _Py_bytes_maketrans(frm, to);
-}
-
-
-/* find and count characters and substrings */
-
-#define findchar(target, target_len, c)                         \
-  ((char *)memchr((const void *)(target), c, target_len))
-
-
-/* Bytes ops must return a string, create a copy */
-Py_LOCAL(PyByteArrayObject *)
-return_self(PyByteArrayObject *self)
-{
-    /* always return a new bytearray */
-    return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
-            PyByteArray_AS_STRING(self),
-            PyByteArray_GET_SIZE(self));
-}
-
-Py_LOCAL_INLINE(Py_ssize_t)
-countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
-{
-    Py_ssize_t count=0;
-    const char *start=target;
-    const char *end=target+target_len;
-
-    while ( (start=findchar(start, end-start, c)) != NULL ) {
-        count++;
-        if (count >= maxcount)
-            break;
-        start += 1;
-    }
-    return count;
-}
-
-
-/* Algorithms for different cases of string replacement */
-
-/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
-Py_LOCAL(PyByteArrayObject *)
-replace_interleave(PyByteArrayObject *self,
-                   const char *to_s, Py_ssize_t to_len,
-                   Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count, i;
-    PyByteArrayObject *result;
-
-    self_len = PyByteArray_GET_SIZE(self);
-
-    /* 1 at the end plus 1 after every character;
-       count = min(maxcount, self_len + 1) */
-    if (maxcount <= self_len)
-        count = maxcount;
-    else
-        /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
-        count = self_len + 1;
-
-    /* Check for overflow */
-    /*   result_len = count * to_len + self_len; */
-    assert(count > 0);
-    if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replace string is too long");
-        return NULL;
-    }
-    result_len = count * to_len + self_len;
-
-    if (! (result = (PyByteArrayObject *)
-                     PyByteArray_FromStringAndSize(NULL, result_len)) )
-        return NULL;
-
-    self_s = PyByteArray_AS_STRING(self);
-    result_s = PyByteArray_AS_STRING(result);
-
-    /* TODO: special case single character, which doesn't need memcpy */
-
-    /* Lay the first one down (guaranteed this will occur) */
-    Py_MEMCPY(result_s, to_s, to_len);
-    result_s += to_len;
-    count -= 1;
-
-    for (i=0; i<count; i++) {
-        *result_s++ = *self_s++;
-        Py_MEMCPY(result_s, to_s, to_len);
-        result_s += to_len;
-    }
-
-    /* Copy the rest of the original string */
-    Py_MEMCPY(result_s, self_s, self_len-i);
-
-    return result;
-}
-
-/* Special case for deleting a single character */
-/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
-Py_LOCAL(PyByteArrayObject *)
-replace_delete_single_character(PyByteArrayObject *self,
-                                char from_c, Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count;
-    PyByteArrayObject *result;
-
-    self_len = PyByteArray_GET_SIZE(self);
-    self_s = PyByteArray_AS_STRING(self);
-
-    count = countchar(self_s, self_len, from_c, maxcount);
-    if (count == 0) {
-        return return_self(self);
-    }
-
-    result_len = self_len - count;  /* from_len == 1 */
-    assert(result_len>=0);
-
-    if ( (result = (PyByteArrayObject *)
-                    PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
-        return NULL;
-    result_s = PyByteArray_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        next = findchar(start, end-start, from_c);
-        if (next == NULL)
-            break;
-        Py_MEMCPY(result_s, start, next-start);
-        result_s += (next-start);
-        start = next+1;
-    }
-    Py_MEMCPY(result_s, start, end-start);
-
-    return result;
-}
-
-/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
-
-Py_LOCAL(PyByteArrayObject *)
-replace_delete_substring(PyByteArrayObject *self,
-                         const char *from_s, Py_ssize_t from_len,
-                         Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count, offset;
-    PyByteArrayObject *result;
-
-    self_len = PyByteArray_GET_SIZE(self);
-    self_s = PyByteArray_AS_STRING(self);
-
-    count = stringlib_count(self_s, self_len,
-                            from_s, from_len,
-                            maxcount);
-
-    if (count == 0) {
-        /* no matches */
-        return return_self(self);
-    }
-
-    result_len = self_len - (count * from_len);
-    assert (result_len>=0);
-
-    if ( (result = (PyByteArrayObject *)
-        PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
-            return NULL;
-
-    result_s = PyByteArray_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        offset = stringlib_find(start, end-start,
-                                from_s, from_len,
-                                0);
-        if (offset == -1)
-            break;
-        next = start + offset;
-
-        Py_MEMCPY(result_s, start, next-start);
-
-        result_s += (next-start);
-        start = next+from_len;
-    }
-    Py_MEMCPY(result_s, start, end-start);
-    return result;
-}
-
-/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
-Py_LOCAL(PyByteArrayObject *)
-replace_single_character_in_place(PyByteArrayObject *self,
-                                  char from_c, char to_c,
-                                  Py_ssize_t maxcount)
-{
-    char *self_s, *result_s, *start, *end, *next;
-    Py_ssize_t self_len;
-    PyByteArrayObject *result;
-
-    /* The result string will be the same size */
-    self_s = PyByteArray_AS_STRING(self);
-    self_len = PyByteArray_GET_SIZE(self);
-
-    next = findchar(self_s, self_len, from_c);
-
-    if (next == NULL) {
-        /* No matches; return the original bytes */
-        return return_self(self);
-    }
-
-    /* Need to make a new bytes */
-    result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
-    if (result == NULL)
-        return NULL;
-    result_s = PyByteArray_AS_STRING(result);
-    Py_MEMCPY(result_s, self_s, self_len);
-
-    /* change everything in-place, starting with this one */
-    start =  result_s + (next-self_s);
-    *start = to_c;
-    start++;
-    end = result_s + self_len;
-
-    while (--maxcount > 0) {
-        next = findchar(start, end-start, from_c);
-        if (next == NULL)
-            break;
-        *next = to_c;
-        start = next+1;
-    }
-
-    return result;
-}
-
-/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyByteArrayObject *)
-replace_substring_in_place(PyByteArrayObject *self,
-                           const char *from_s, Py_ssize_t from_len,
-                           const char *to_s, Py_ssize_t to_len,
-                           Py_ssize_t maxcount)
-{
-    char *result_s, *start, *end;
-    char *self_s;
-    Py_ssize_t self_len, offset;
-    PyByteArrayObject *result;
-
-    /* The result bytes will be the same size */
-
-    self_s = PyByteArray_AS_STRING(self);
-    self_len = PyByteArray_GET_SIZE(self);
-
-    offset = stringlib_find(self_s, self_len,
-                            from_s, from_len,
-                            0);
-    if (offset == -1) {
-        /* No matches; return the original bytes */
-        return return_self(self);
-    }
-
-    /* Need to make a new bytes */
-    result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
-    if (result == NULL)
-        return NULL;
-    result_s = PyByteArray_AS_STRING(result);
-    Py_MEMCPY(result_s, self_s, self_len);
-
-    /* change everything in-place, starting with this one */
-    start =  result_s + offset;
-    Py_MEMCPY(start, to_s, from_len);
-    start += from_len;
-    end = result_s + self_len;
-
-    while ( --maxcount > 0) {
-        offset = stringlib_find(start, end-start,
-                                from_s, from_len,
-                                0);
-        if (offset==-1)
-            break;
-        Py_MEMCPY(start+offset, to_s, from_len);
-        start += offset+from_len;
-    }
-
-    return result;
-}
-
-/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyByteArrayObject *)
-replace_single_character(PyByteArrayObject *self,
-                         char from_c,
-                         const char *to_s, Py_ssize_t to_len,
-                         Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count;
-    PyByteArrayObject *result;
-
-    self_s = PyByteArray_AS_STRING(self);
-    self_len = PyByteArray_GET_SIZE(self);
-
-    count = countchar(self_s, self_len, from_c, maxcount);
-    if (count == 0) {
-        /* no matches, return unchanged */
-        return return_self(self);
-    }
-
-    /* use the difference between current and new, hence the "-1" */
-    /*   result_len = self_len + count * (to_len-1)  */
-    assert(count > 0);
-    if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
-        PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
-        return NULL;
-    }
-    result_len = self_len + count * (to_len - 1);
-
-    if ( (result = (PyByteArrayObject *)
-          PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
-            return NULL;
-    result_s = PyByteArray_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        next = findchar(start, end-start, from_c);
-        if (next == NULL)
-            break;
-
-        if (next == start) {
-            /* replace with the 'to' */
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start += 1;
-        } else {
-            /* copy the unchanged old then the 'to' */
-            Py_MEMCPY(result_s, start, next-start);
-            result_s += (next-start);
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start = next+1;
-        }
-    }
-    /* Copy the remainder of the remaining bytes */
-    Py_MEMCPY(result_s, start, end-start);
-
-    return result;
-}
-
-/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyByteArrayObject *)
-replace_substring(PyByteArrayObject *self,
-                  const char *from_s, Py_ssize_t from_len,
-                  const char *to_s, Py_ssize_t to_len,
-                  Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count, offset;
-    PyByteArrayObject *result;
-
-    self_s = PyByteArray_AS_STRING(self);
-    self_len = PyByteArray_GET_SIZE(self);
-
-    count = stringlib_count(self_s, self_len,
-                            from_s, from_len,
-                            maxcount);
-
-    if (count == 0) {
-        /* no matches, return unchanged */
-        return return_self(self);
-    }
-
-    /* Check for overflow */
-    /*    result_len = self_len + count * (to_len-from_len) */
-    assert(count > 0);
-    if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
-        PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
-        return NULL;
-    }
-    result_len = self_len + count * (to_len - from_len);
-
-    if ( (result = (PyByteArrayObject *)
-          PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
-        return NULL;
-    result_s = PyByteArray_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        offset = stringlib_find(start, end-start,
-                                from_s, from_len,
-                                0);
-        if (offset == -1)
-            break;
-        next = start+offset;
-        if (next == start) {
-            /* replace with the 'to' */
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start += from_len;
-        } else {
-            /* copy the unchanged old then the 'to' */
-            Py_MEMCPY(result_s, start, next-start);
-            result_s += (next-start);
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start = next+from_len;
-        }
-    }
-    /* Copy the remainder of the remaining bytes */
-    Py_MEMCPY(result_s, start, end-start);
-
-    return result;
-}
-
-
-Py_LOCAL(PyByteArrayObject *)
-replace(PyByteArrayObject *self,
-        const char *from_s, Py_ssize_t from_len,
-        const char *to_s, Py_ssize_t to_len,
-        Py_ssize_t maxcount)
-{
-    if (maxcount < 0) {
-        maxcount = PY_SSIZE_T_MAX;
-    } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
-        /* nothing to do; return the original bytes */
-        return return_self(self);
-    }
-
-    if (maxcount == 0 ||
-        (from_len == 0 && to_len == 0)) {
-        /* nothing to do; return the original bytes */
-        return return_self(self);
-    }
-
-    /* Handle zero-length special cases */
-
-    if (from_len == 0) {
-        /* insert the 'to' bytes everywhere.   */
-        /*    >>> "Python".replace("", ".")     */
-        /*    '.P.y.t.h.o.n.'                   */
-        return replace_interleave(self, to_s, to_len, maxcount);
-    }
-
-    /* Except for "".replace("", "A") == "A" there is no way beyond this */
-    /* point for an empty self bytes to generate a non-empty bytes */
-    /* Special case so the remaining code always gets a non-empty bytes */
-    if (PyByteArray_GET_SIZE(self) == 0) {
-        return return_self(self);
-    }
-
-    if (to_len == 0) {
-        /* delete all occurrences of 'from' bytes */
-        if (from_len == 1) {
-            return replace_delete_single_character(
-                    self, from_s[0], maxcount);
-        } else {
-            return replace_delete_substring(self, from_s, from_len, maxcount);
-        }
-    }
-
-    /* Handle special case where both bytes have the same length */
-
-    if (from_len == to_len) {
-        if (from_len == 1) {
-            return replace_single_character_in_place(
-                    self,
-                    from_s[0],
-                    to_s[0],
-                    maxcount);
-        } else {
-            return replace_substring_in_place(
-                self, from_s, from_len, to_s, to_len, maxcount);
-        }
-    }
-
-    /* Otherwise use the more generic algorithms */
-    if (from_len == 1) {
-        return replace_single_character(self, from_s[0],
-                                        to_s, to_len, maxcount);
-    } else {
-        /* len('from')>=2, len('to')>=1 */
-        return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
-    }
-}
-
-
-/*[clinic input]
-bytearray.replace
-
-    old: Py_buffer
-    new: Py_buffer
-    count: Py_ssize_t = -1
-        Maximum number of occurrences to replace.
-        -1 (the default value) means replace all occurrences.
-    /
-
-Return a copy with all occurrences of substring old replaced by new.
-
-If the optional argument count is given, only the first count occurrences are
-replaced.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_replace__doc__,
 "replace($self, old, new, count=-1, /)\n"
 "--\n"
@@ -2304,29 +167,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count)
-/*[clinic end generated code: output=9997fbbd5bac4883 input=aa379d988637c7fb]*/
-{
-    return (PyObject *)replace((PyByteArrayObject *) self,
-                               old->buf, old->len,
-                               new->buf, new->len, count);
-}
-
-/*[clinic input]
-bytearray.split
-
-    sep: object = None
-        The delimiter according which to split the bytearray.
-        None (the default value) means split on ASCII whitespace characters
-        (space, tab, return, newline, formfeed, vertical tab).
-    maxsplit: Py_ssize_t = -1
-        Maximum number of splits to do.
-        -1 (the default value) means no limit.
-
-Return a list of the sections in the bytearray, using sep as the delimiter.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_split__doc__,
 "split($self, /, sep=None, maxsplit=-1)\n"
 "--\n"
@@ -2365,50 +205,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=062a3d87d6f918fa input=24f82669f41bf523]*/
-{
-    Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
-    const char *s = PyByteArray_AS_STRING(self), *sub;
-    PyObject *list;
-    Py_buffer vsub;
-
-    if (maxsplit < 0)
-        maxsplit = PY_SSIZE_T_MAX;
-
-    if (sep == Py_None)
-        return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
-
-    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
-        return NULL;
-    sub = vsub.buf;
-    n = vsub.len;
-
-    list = stringlib_split(
-        (PyObject*) self, s, len, sub, n, maxsplit
-        );
-    PyBuffer_Release(&vsub);
-    return list;
-}
-
-/*[clinic input]
-bytearray.partition
-
-    self: self(type="PyByteArrayObject *")
-    sep: object
-    /
-
-Partition the bytearray into three parts using the given separator.
-
-This will search for the separator sep in the bytearray. If the separator is
-found, returns a 3-tuple containing the part before the separator, the
-separator itself, and the part after it.
-
-If the separator is not found, returns a 3-tuple containing the original
-bytearray object and two empty bytearray objects.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_partition__doc__,
 "partition($self, sep, /)\n"
 "--\n"
@@ -2425,44 +221,6 @@
 #define BYTEARRAY_PARTITION_METHODDEF    \
     {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__},
 
-static PyObject *
-bytearray_partition(PyByteArrayObject *self, PyObject *sep)
-/*[clinic end generated code: output=2645138221fe6f4d input=7d7fe37b1696d506]*/
-{
-    PyObject *bytesep, *result;
-
-    bytesep = PyByteArray_FromObject(sep);
-    if (! bytesep)
-        return NULL;
-
-    result = stringlib_partition(
-            (PyObject*) self,
-            PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
-            bytesep,
-            PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
-            );
-
-    Py_DECREF(bytesep);
-    return result;
-}
-
-/*[clinic input]
-bytearray.rpartition
-
-    self: self(type="PyByteArrayObject *")
-    sep: object
-    /
-
-Partition the bytes into three parts using the given separator.
-
-This will search for the separator sep in the bytearray, starting and the end.
-If the separator is found, returns a 3-tuple containing the part before the
-separator, the separator itself, and the part after it.
-
-If the separator is not found, returns a 3-tuple containing two empty bytearray
-objects and the original bytearray object.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_rpartition__doc__,
 "rpartition($self, sep, /)\n"
 "--\n"
@@ -2479,35 +237,6 @@
 #define BYTEARRAY_RPARTITION_METHODDEF    \
     {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__},
 
-static PyObject *
-bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
-/*[clinic end generated code: output=ed13e54605d007de input=9b8cd540c1b75853]*/
-{
-    PyObject *bytesep, *result;
-
-    bytesep = PyByteArray_FromObject(sep);
-    if (! bytesep)
-        return NULL;
-
-    result = stringlib_rpartition(
-            (PyObject*) self,
-            PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
-            bytesep,
-            PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
-            );
-
-    Py_DECREF(bytesep);
-    return result;
-}
-
-/*[clinic input]
-bytearray.rsplit = bytearray.split
-
-Return a list of the sections in the bytearray, using sep as the delimiter.
-
-Splitting is done starting at the end of the bytearray and working to the front.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_rsplit__doc__,
 "rsplit($self, /, sep=None, maxsplit=-1)\n"
 "--\n"
@@ -2548,41 +277,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=affaf9fc2aae8d41 input=a68286e4dd692ffe]*/
-{
-    Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
-    const char *s = PyByteArray_AS_STRING(self), *sub;
-    PyObject *list;
-    Py_buffer vsub;
-
-    if (maxsplit < 0)
-        maxsplit = PY_SSIZE_T_MAX;
-
-    if (sep == Py_None)
-        return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
-
-    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
-        return NULL;
-    sub = vsub.buf;
-    n = vsub.len;
-
-    list = stringlib_rsplit(
-        (PyObject*) self, s, len, sub, n, maxsplit
-        );
-    PyBuffer_Release(&vsub);
-    return list;
-}
-
-/*[clinic input]
-bytearray.reverse
-
-    self: self(type="PyByteArrayObject *")
-
-Reverse the order of the values in B in place.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_reverse__doc__,
 "reverse($self, /)\n"
 "--\n"
@@ -2601,47 +295,6 @@
     return bytearray_reverse_impl(self);
 }
 
-static PyObject *
-bytearray_reverse_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=5d5e5f0bfc67f476 input=7933a499b8597bd1]*/
-{
-    char swap, *head, *tail;
-    Py_ssize_t i, j, n = Py_SIZE(self);
-
-    j = n / 2;
-    head = PyByteArray_AS_STRING(self);
-    tail = head + n - 1;
-    for (i = 0; i < j; i++) {
-        swap = *head;
-        *head++ = *tail;
-        *tail-- = swap;
-    }
-
-    Py_RETURN_NONE;
-}
-
-
-/*[python input]
-class bytesvalue_converter(CConverter):
-    type = 'int'
-    converter = '_getbytevalue'
-[python start generated code]*/
-/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
-
-
-/*[clinic input]
-bytearray.insert
-
-    self: self(type="PyByteArrayObject *")
-    index: Py_ssize_t
-        The index where the value is to be inserted.
-    item: bytesvalue
-        The item to be inserted.
-    /
-
-Insert a single item into the bytearray before the given index.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_insert__doc__,
 "insert($self, index, item, /)\n"
 "--\n"
@@ -2676,46 +329,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
-/*[clinic end generated code: output=5ec9340d4ad19080 input=833766836ba30e1e]*/
-{
-    Py_ssize_t n = Py_SIZE(self);
-    char *buf;
-
-    if (n == PY_SSIZE_T_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "cannot add more objects to bytearray");
-        return NULL;
-    }
-    if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
-        return NULL;
-    buf = PyByteArray_AS_STRING(self);
-
-    if (index < 0) {
-        index += n;
-        if (index < 0)
-            index = 0;
-    }
-    if (index > n)
-        index = n;
-    memmove(buf + index + 1, buf + index, n - index);
-    buf[index] = item;
-
-    Py_RETURN_NONE;
-}
-
-/*[clinic input]
-bytearray.append
-
-    self: self(type="PyByteArrayObject *")
-    item: bytesvalue
-        The item to be appended.
-    /
-
-Append a single item to the end of the bytearray.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_append__doc__,
 "append($self, item, /)\n"
 "--\n"
@@ -2747,36 +360,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_append_impl(PyByteArrayObject *self, int item)
-/*[clinic end generated code: output=b5b3325bb3bbaf85 input=ae56ea87380407cc]*/
-{
-    Py_ssize_t n = Py_SIZE(self);
-
-    if (n == PY_SSIZE_T_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "cannot add more objects to bytearray");
-        return NULL;
-    }
-    if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
-        return NULL;
-
-    PyByteArray_AS_STRING(self)[n] = item;
-
-    Py_RETURN_NONE;
-}
-
-/*[clinic input]
-bytearray.extend
-
-    self: self(type="PyByteArrayObject *")
-    iterable_of_ints: object
-        The iterable of items to append.
-    /
-
-Append all the items from the iterator or sequence to the end of the bytearray.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_extend__doc__,
 "extend($self, iterable_of_ints, /)\n"
 "--\n"
@@ -2789,94 +372,6 @@
 #define BYTEARRAY_EXTEND_METHODDEF    \
     {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__},
 
-static PyObject *
-bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
-/*[clinic end generated code: output=13b0c13ad5110dfb input=ce83a5d75b70d850]*/
-{
-    PyObject *it, *item, *bytearray_obj;
-    Py_ssize_t buf_size = 0, len = 0;
-    int value;
-    char *buf;
-
-    /* bytearray_setslice code only accepts something supporting PEP 3118. */
-    if (PyObject_CheckBuffer(iterable_of_ints)) {
-        if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
-            return NULL;
-
-        Py_RETURN_NONE;
-    }
-
-    it = PyObject_GetIter(iterable_of_ints);
-    if (it == NULL)
-        return NULL;
-
-    /* Try to determine the length of the argument. 32 is arbitrary. */
-    buf_size = PyObject_LengthHint(iterable_of_ints, 32);
-    if (buf_size == -1) {
-        Py_DECREF(it);
-        return NULL;
-    }
-
-    bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
-    if (bytearray_obj == NULL) {
-        Py_DECREF(it);
-        return NULL;
-    }
-    buf = PyByteArray_AS_STRING(bytearray_obj);
-
-    while ((item = PyIter_Next(it)) != NULL) {
-        if (! _getbytevalue(item, &value)) {
-            Py_DECREF(item);
-            Py_DECREF(it);
-            Py_DECREF(bytearray_obj);
-            return NULL;
-        }
-        buf[len++] = value;
-        Py_DECREF(item);
-
-        if (len >= buf_size) {
-            buf_size = len + (len >> 1) + 1;
-            if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
-                Py_DECREF(it);
-                Py_DECREF(bytearray_obj);
-                return NULL;
-            }
-            /* Recompute the `buf' pointer, since the resizing operation may
-               have invalidated it. */
-            buf = PyByteArray_AS_STRING(bytearray_obj);
-        }
-    }
-    Py_DECREF(it);
-
-    /* Resize down to exact size. */
-    if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
-        Py_DECREF(bytearray_obj);
-        return NULL;
-    }
-
-    if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
-        Py_DECREF(bytearray_obj);
-        return NULL;
-    }
-    Py_DECREF(bytearray_obj);
-
-    Py_RETURN_NONE;
-}
-
-/*[clinic input]
-bytearray.pop
-
-    self: self(type="PyByteArrayObject *")
-    index: Py_ssize_t = -1
-        The index from where to remove the item.
-        -1 (the default value) means remove the last item.
-    /
-
-Remove and return a single item from B.
-
-If no index argument is given, will pop the last item.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_pop__doc__,
 "pop($self, index=-1, /)\n"
 "--\n"
@@ -2911,48 +406,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
-/*[clinic end generated code: output=3b763e548e79af96 input=0797e6c0ca9d5a85]*/
-{
-    int value;
-    Py_ssize_t n = Py_SIZE(self);
-    char *buf;
-
-    if (n == 0) {
-        PyErr_SetString(PyExc_IndexError,
-                        "pop from empty bytearray");
-        return NULL;
-    }
-    if (index < 0)
-        index += Py_SIZE(self);
-    if (index < 0 || index >= Py_SIZE(self)) {
-        PyErr_SetString(PyExc_IndexError, "pop index out of range");
-        return NULL;
-    }
-    if (!_canresize(self))
-        return NULL;
-
-    buf = PyByteArray_AS_STRING(self);
-    value = buf[index];
-    memmove(buf + index, buf + index + 1, n - index);
-    if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
-        return NULL;
-
-    return PyLong_FromLong((unsigned char)value);
-}
-
-/*[clinic input]
-bytearray.remove
-
-    self: self(type="PyByteArrayObject *")
-    value: bytesvalue
-        The value to remove.
-    /
-
-Remove the first occurrence of a value in the bytearray.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_remove__doc__,
 "remove($self, value, /)\n"
 "--\n"
@@ -2984,64 +437,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_remove_impl(PyByteArrayObject *self, int value)
-/*[clinic end generated code: output=c71c8bcf4703abfc input=47560b11fd856c24]*/
-{
-    Py_ssize_t where, n = Py_SIZE(self);
-    char *buf = PyByteArray_AS_STRING(self);
-
-    for (where = 0; where < n; where++) {
-        if (buf[where] == value)
-            break;
-    }
-    if (where == n) {
-        PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
-        return NULL;
-    }
-    if (!_canresize(self))
-        return NULL;
-
-    memmove(buf + where, buf + where + 1, n - where);
-    if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
-        return NULL;
-
-    Py_RETURN_NONE;
-}
-
-/* XXX These two helpers could be optimized if argsize == 1 */
-
-static Py_ssize_t
-lstrip_helper(char *myptr, Py_ssize_t mysize,
-              void *argptr, Py_ssize_t argsize)
-{
-    Py_ssize_t i = 0;
-    while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
-        i++;
-    return i;
-}
-
-static Py_ssize_t
-rstrip_helper(char *myptr, Py_ssize_t mysize,
-              void *argptr, Py_ssize_t argsize)
-{
-    Py_ssize_t i = mysize - 1;
-    while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
-        i--;
-    return i + 1;
-}
-
-/*[clinic input]
-bytearray.strip
-
-    bytes: object = None
-    /
-
-Strip leading and trailing bytes contained in the argument.
-
-If the argument is omitted or None, strip leading and trailing ASCII whitespace.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_strip__doc__,
 "strip($self, bytes=None, /)\n"
 "--\n"
@@ -3072,47 +467,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
-/*[clinic end generated code: output=2e3d3358acc4c235 input=ef7bb59b09c21d62]*/
-{
-    Py_ssize_t left, right, mysize, byteslen;
-    char *myptr, *bytesptr;
-    Py_buffer vbytes;
-
-    if (bytes == Py_None) {
-        bytesptr = "\t\n\r\f\v ";
-        byteslen = 6;
-    }
-    else {
-        if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
-            return NULL;
-        bytesptr = (char *) vbytes.buf;
-        byteslen = vbytes.len;
-    }
-    myptr = PyByteArray_AS_STRING(self);
-    mysize = Py_SIZE(self);
-    left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
-    if (left == mysize)
-        right = left;
-    else
-        right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
-    if (bytes != Py_None)
-        PyBuffer_Release(&vbytes);
-    return PyByteArray_FromStringAndSize(myptr + left, right - left);
-}
-
-/*[clinic input]
-bytearray.lstrip
-
-    bytes: object = None
-    /
-
-Strip leading bytes contained in the argument.
-
-If the argument is omitted or None, strip leading ASCII whitespace.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_lstrip__doc__,
 "lstrip($self, bytes=None, /)\n"
 "--\n"
@@ -3143,44 +497,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
-/*[clinic end generated code: output=2599309808a9ec02 input=80843f975dd7c480]*/
-{
-    Py_ssize_t left, right, mysize, byteslen;
-    char *myptr, *bytesptr;
-    Py_buffer vbytes;
-
-    if (bytes == Py_None) {
-        bytesptr = "\t\n\r\f\v ";
-        byteslen = 6;
-    }
-    else {
-        if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
-            return NULL;
-        bytesptr = (char *) vbytes.buf;
-        byteslen = vbytes.len;
-    }
-    myptr = PyByteArray_AS_STRING(self);
-    mysize = Py_SIZE(self);
-    left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
-    right = mysize;
-    if (bytes != Py_None)
-        PyBuffer_Release(&vbytes);
-    return PyByteArray_FromStringAndSize(myptr + left, right - left);
-}
-
-/*[clinic input]
-bytearray.rstrip
-
-    bytes: object = None
-    /
-
-Strip trailing bytes contained in the argument.
-
-If the argument is omitted or None, strip trailing ASCII whitespace.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_rstrip__doc__,
 "rstrip($self, bytes=None, /)\n"
 "--\n"
@@ -3211,47 +527,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
-/*[clinic end generated code: output=b5ca6259f4f4f2a3 input=e728b994954cfd91]*/
-{
-    Py_ssize_t right, mysize, byteslen;
-    char *myptr, *bytesptr;
-    Py_buffer vbytes;
-
-    if (bytes == Py_None) {
-        bytesptr = "\t\n\r\f\v ";
-        byteslen = 6;
-    }
-    else {
-        if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
-            return NULL;
-        bytesptr = (char *) vbytes.buf;
-        byteslen = vbytes.len;
-    }
-    myptr = PyByteArray_AS_STRING(self);
-    mysize = Py_SIZE(self);
-    right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
-    if (bytes != Py_None)
-        PyBuffer_Release(&vbytes);
-    return PyByteArray_FromStringAndSize(myptr, right);
-}
-
-/*[clinic input]
-bytearray.decode
-
-    encoding: str(c_default="NULL") = 'utf-8'
-        The encoding with which to decode the bytearray.
-    errors: str(c_default="NULL") = 'strict'
-        The error handling scheme to use for the handling of decoding errors.
-        The default is 'strict' meaning that decoding errors raise a
-        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
-        as well as any other name registered with codecs.register_error that
-        can handle UnicodeDecodeErrors.
-
-Decode the bytearray using the codec registered for encoding.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_decode__doc__,
 "decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
 "--\n"
@@ -3291,39 +566,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors)
-/*[clinic end generated code: output=38b83681f1e38a6c input=f28d8f903020257b]*/
-{
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-    return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
-}
-
-PyDoc_STRVAR(alloc_doc,
-"B.__alloc__() -> int\n\
-\n\
-Return the number of bytes actually allocated.");
-
-static PyObject *
-bytearray_alloc(PyByteArrayObject *self)
-{
-    return PyLong_FromSsize_t(self->ob_alloc);
-}
-
-/*[clinic input]
-bytearray.join
-
-    iterable_of_bytes: object
-    /
-
-Concatenate any number of bytes/bytearray objects.
-
-The bytearray whose method is called is inserted in between each pair.
-
-The result is returned as a new bytearray object.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_join__doc__,
 "join($self, iterable_of_bytes, /)\n"
 "--\n"
@@ -3337,24 +579,6 @@
 #define BYTEARRAY_JOIN_METHODDEF    \
     {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__},
 
-static PyObject *
-bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
-/*[clinic end generated code: output=544e7430032dfdf4 input=aba6b1f9b30fcb8e]*/
-{
-    return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
-}
-
-/*[clinic input]
-bytearray.splitlines
-
-    keepends: int(py_default="False") = 0
-
-Return a list of the lines in the bytearray, breaking at line boundaries.
-
-Line breaks are not included in the resulting list unless keepends is given and
-true.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_splitlines__doc__,
 "splitlines($self, /, keepends=False)\n"
 "--\n"
@@ -3387,46 +611,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
-/*[clinic end generated code: output=a837fd0512ad46ff input=36f0b25bc792f6c0]*/
-{
-    return stringlib_splitlines(
-        (PyObject*) self, PyByteArray_AS_STRING(self),
-        PyByteArray_GET_SIZE(self), keepends
-        );
-}
-
-static int
-hex_digit_to_int(Py_UCS4 c)
-{
-    if (c >= 128)
-        return -1;
-    if (Py_ISDIGIT(c))
-        return c - '0';
-    else {
-        if (Py_ISUPPER(c))
-            c = Py_TOLOWER(c);
-        if (c >= 'a' && c <= 'f')
-            return c - 'a' + 10;
-    }
-    return -1;
-}
-
-/*[clinic input]
- at classmethod
-bytearray.fromhex
-
-    cls: self(type="PyObject*")
-    string: unicode
-    /
-
-Create a bytearray object from a string of hexadecimal numbers.
-
-Spaces between two numbers are accepted.
-Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_fromhex__doc__,
 "fromhex($type, string, /)\n"
 "--\n"
@@ -3458,98 +642,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_fromhex_impl(PyObject*cls, PyObject *string)
-/*[clinic end generated code: output=adc3c804a74e56d4 input=907bbd2d34d9367a]*/
-{
-    PyObject *newbytes;
-    char *buf;
-    Py_ssize_t hexlen, byteslen, i, j;
-    int top, bot;
-    void *data;
-    unsigned int kind;
-
-    assert(PyUnicode_Check(string));
-    if (PyUnicode_READY(string))
-        return NULL;
-    kind = PyUnicode_KIND(string);
-    data = PyUnicode_DATA(string);
-    hexlen = PyUnicode_GET_LENGTH(string);
-
-    byteslen = hexlen/2; /* This overestimates if there are spaces */
-    newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
-    if (!newbytes)
-        return NULL;
-    buf = PyByteArray_AS_STRING(newbytes);
-    for (i = j = 0; i < hexlen; i += 2) {
-        /* skip over spaces in the input */
-        while (PyUnicode_READ(kind, data, i) == ' ')
-            i++;
-        if (i >= hexlen)
-            break;
-        top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
-        bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
-        if (top == -1 || bot == -1) {
-            PyErr_Format(PyExc_ValueError,
-                         "non-hexadecimal number found in "
-                         "fromhex() arg at position %zd", i);
-            goto error;
-        }
-        buf[j++] = (top << 4) + bot;
-    }
-    if (PyByteArray_Resize(newbytes, j) < 0)
-        goto error;
-    return newbytes;
-
-  error:
-    Py_DECREF(newbytes);
-    return NULL;
-}
-
-
-static PyObject *
-_common_reduce(PyByteArrayObject *self, int proto)
-{
-    PyObject *dict;
-    _Py_IDENTIFIER(__dict__);
-    char *buf;
-
-    dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
-    if (dict == NULL) {
-        PyErr_Clear();
-        dict = Py_None;
-        Py_INCREF(dict);
-    }
-
-    buf = PyByteArray_AS_STRING(self);
-    if (proto < 3) {
-        /* use str based reduction for backwards compatibility with Python 2.x */
-        PyObject *latin1;
-        if (Py_SIZE(self))
-            latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
-        else
-            latin1 = PyUnicode_FromString("");
-        return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
-    }
-    else {
-        /* use more efficient byte based reduction */
-        if (Py_SIZE(self)) {
-            return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
-        }
-        else {
-            return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
-        }
-    }
-}
-
-/*[clinic input]
-bytearray.__reduce__ as bytearray_reduce
-
-    self: self(type="PyByteArrayObject *")
-
-Return state information for pickling.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_reduce__doc__,
 "__reduce__($self, /)\n"
 "--\n"
@@ -3568,23 +660,6 @@
     return bytearray_reduce_impl(self);
 }
 
-static PyObject *
-bytearray_reduce_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=b1b56fe87bf30fb0 input=fbb07de4d102a03a]*/
-{
-    return _common_reduce(self, 2);
-}
-
-/*[clinic input]
-bytearray.__reduce_ex__ as bytearray_reduce_ex
-
-    self: self(type="PyByteArrayObject *")
-    proto: int = 0
-    /
-
-Return state information for pickling.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_reduce_ex__doc__,
 "__reduce_ex__($self, proto=0, /)\n"
 "--\n"
@@ -3613,21 +688,6 @@
     return return_value;
 }
 
-static PyObject *
-bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
-/*[clinic end generated code: output=bbd9afb2f5953dc1 input=0e091a42ca6dbd91]*/
-{
-    return _common_reduce(self, proto);
-}
-
-/*[clinic input]
-bytearray.__sizeof__ as bytearray_sizeof
-
-    self: self(type="PyByteArrayObject *")
-
-Returns the size of the bytearray object in memory, in bytes.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytearray_sizeof__doc__,
 "__sizeof__($self, /)\n"
 "--\n"
@@ -3645,331 +705,4 @@
 {
     return bytearray_sizeof_impl(self);
 }
-
-static PyObject *
-bytearray_sizeof_impl(PyByteArrayObject *self)
-/*[clinic end generated code: output=4a2254b0a85630c6 input=6b23d305362b462b]*/
-{
-    Py_ssize_t res;
-
-    res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
-    return PyLong_FromSsize_t(res);
-}
-
-static PySequenceMethods bytearray_as_sequence = {
-    (lenfunc)bytearray_length,              /* sq_length */
-    (binaryfunc)PyByteArray_Concat,         /* sq_concat */
-    (ssizeargfunc)bytearray_repeat,         /* sq_repeat */
-    (ssizeargfunc)bytearray_getitem,        /* sq_item */
-    0,                                      /* sq_slice */
-    (ssizeobjargproc)bytearray_setitem,     /* sq_ass_item */
-    0,                                      /* sq_ass_slice */
-    (objobjproc)bytearray_contains,         /* sq_contains */
-    (binaryfunc)bytearray_iconcat,          /* sq_inplace_concat */
-    (ssizeargfunc)bytearray_irepeat,        /* sq_inplace_repeat */
-};
-
-static PyMappingMethods bytearray_as_mapping = {
-    (lenfunc)bytearray_length,
-    (binaryfunc)bytearray_subscript,
-    (objobjargproc)bytearray_ass_subscript,
-};
-
-static PyBufferProcs bytearray_as_buffer = {
-    (getbufferproc)bytearray_getbuffer,
-    (releasebufferproc)bytearray_releasebuffer,
-};
-
-static PyMethodDef
-bytearray_methods[] = {
-    {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
-    BYTEARRAY_REDUCE_METHODDEF
-    BYTEARRAY_REDUCE_EX_METHODDEF
-    BYTEARRAY_SIZEOF_METHODDEF
-    BYTEARRAY_APPEND_METHODDEF
-    {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
-     _Py_capitalize__doc__},
-    {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
-    BYTEARRAY_CLEAR_METHODDEF
-    BYTEARRAY_COPY_METHODDEF
-    {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
-    BYTEARRAY_DECODE_METHODDEF
-    {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
-    {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
-     expandtabs__doc__},
-    BYTEARRAY_EXTEND_METHODDEF
-    {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
-    BYTEARRAY_FROMHEX_METHODDEF
-    {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
-    BYTEARRAY_INSERT_METHODDEF
-    {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
-     _Py_isalnum__doc__},
-    {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
-     _Py_isalpha__doc__},
-    {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
-     _Py_isdigit__doc__},
-    {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
-     _Py_islower__doc__},
-    {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
-     _Py_isspace__doc__},
-    {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
-     _Py_istitle__doc__},
-    {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
-     _Py_isupper__doc__},
-    BYTEARRAY_JOIN_METHODDEF
-    {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
-    {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
-    BYTEARRAY_LSTRIP_METHODDEF
-    BYTEARRAY_MAKETRANS_METHODDEF
-    BYTEARRAY_PARTITION_METHODDEF
-    BYTEARRAY_POP_METHODDEF
-    BYTEARRAY_REMOVE_METHODDEF
-    BYTEARRAY_REPLACE_METHODDEF
-    BYTEARRAY_REVERSE_METHODDEF
-    {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
-    {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
-    {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
-    BYTEARRAY_RPARTITION_METHODDEF
-    BYTEARRAY_RSPLIT_METHODDEF
-    BYTEARRAY_RSTRIP_METHODDEF
-    BYTEARRAY_SPLIT_METHODDEF
-    BYTEARRAY_SPLITLINES_METHODDEF
-    {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
-     startswith__doc__},
-    BYTEARRAY_STRIP_METHODDEF
-    {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
-     _Py_swapcase__doc__},
-    {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
-    BYTEARRAY_TRANSLATE_METHODDEF
-    {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
-    {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
-    {NULL}
-};
-
-static PyObject *
-bytearray_mod(PyObject *v, PyObject *w)
-{
-    if (!PyByteArray_Check(v))
-        Py_RETURN_NOTIMPLEMENTED;
-    return bytearray_format((PyByteArrayObject *)v, w);
-}
-
-static PyNumberMethods bytearray_as_number = {
-    0,              /*nb_add*/
-    0,              /*nb_subtract*/
-    0,              /*nb_multiply*/
-    bytearray_mod,  /*nb_remainder*/
-};
-
-PyDoc_STRVAR(bytearray_doc,
-"bytearray(iterable_of_ints) -> bytearray\n\
-bytearray(string, encoding[, errors]) -> bytearray\n\
-bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
-bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
-bytearray() -> empty bytes array\n\
-\n\
-Construct an mutable bytearray object from:\n\
-  - an iterable yielding integers in range(256)\n\
-  - a text string encoded using the specified encoding\n\
-  - a bytes or a buffer object\n\
-  - any object implementing the buffer API.\n\
-  - an integer");
-
-
-static PyObject *bytearray_iter(PyObject *seq);
-
-PyTypeObject PyByteArray_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "bytearray",
-    sizeof(PyByteArrayObject),
-    0,
-    (destructor)bytearray_dealloc,       /* tp_dealloc */
-    0,                                  /* tp_print */
-    0,                                  /* tp_getattr */
-    0,                                  /* tp_setattr */
-    0,                                  /* tp_reserved */
-    (reprfunc)bytearray_repr,           /* tp_repr */
-    &bytearray_as_number,               /* tp_as_number */
-    &bytearray_as_sequence,             /* tp_as_sequence */
-    &bytearray_as_mapping,              /* tp_as_mapping */
-    0,                                  /* tp_hash */
-    0,                                  /* tp_call */
-    bytearray_str,                      /* tp_str */
-    PyObject_GenericGetAttr,            /* tp_getattro */
-    0,                                  /* tp_setattro */
-    &bytearray_as_buffer,               /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
-    bytearray_doc,                      /* tp_doc */
-    0,                                  /* tp_traverse */
-    0,                                  /* tp_clear */
-    (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
-    0,                                  /* tp_weaklistoffset */
-    bytearray_iter,                     /* tp_iter */
-    0,                                  /* tp_iternext */
-    bytearray_methods,                  /* tp_methods */
-    0,                                  /* tp_members */
-    0,                                  /* tp_getset */
-    0,                                  /* tp_base */
-    0,                                  /* tp_dict */
-    0,                                  /* tp_descr_get */
-    0,                                  /* tp_descr_set */
-    0,                                  /* tp_dictoffset */
-    (initproc)bytearray_init,           /* tp_init */
-    PyType_GenericAlloc,                /* tp_alloc */
-    PyType_GenericNew,                  /* tp_new */
-    PyObject_Del,                       /* tp_free */
-};
-
-/*********************** Bytes Iterator ****************************/
-
-typedef struct {
-    PyObject_HEAD
-    Py_ssize_t it_index;
-    PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
-} bytesiterobject;
-
-static void
-bytearrayiter_dealloc(bytesiterobject *it)
-{
-    _PyObject_GC_UNTRACK(it);
-    Py_XDECREF(it->it_seq);
-    PyObject_GC_Del(it);
-}
-
-static int
-bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
-{
-    Py_VISIT(it->it_seq);
-    return 0;
-}
-
-static PyObject *
-bytearrayiter_next(bytesiterobject *it)
-{
-    PyByteArrayObject *seq;
-    PyObject *item;
-
-    assert(it != NULL);
-    seq = it->it_seq;
-    if (seq == NULL)
-        return NULL;
-    assert(PyByteArray_Check(seq));
-
-    if (it->it_index < PyByteArray_GET_SIZE(seq)) {
-        item = PyLong_FromLong(
-            (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
-        if (item != NULL)
-            ++it->it_index;
-        return item;
-    }
-
-    Py_DECREF(seq);
-    it->it_seq = NULL;
-    return NULL;
-}
-
-static PyObject *
-bytearrayiter_length_hint(bytesiterobject *it)
-{
-    Py_ssize_t len = 0;
-    if (it->it_seq)
-        len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
-    return PyLong_FromSsize_t(len);
-}
-
-PyDoc_STRVAR(length_hint_doc,
-    "Private method returning an estimate of len(list(it)).");
-
-static PyObject *
-bytearrayiter_reduce(bytesiterobject *it)
-{
-    if (it->it_seq != NULL) {
-        return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
-                             it->it_seq, it->it_index);
-    } else {
-        PyObject *u = PyUnicode_FromUnicode(NULL, 0);
-        if (u == NULL)
-            return NULL;
-        return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
-    }
-}
-
-static PyObject *
-bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
-{
-    Py_ssize_t index = PyLong_AsSsize_t(state);
-    if (index == -1 && PyErr_Occurred())
-        return NULL;
-    if (it->it_seq != NULL) {
-        if (index < 0)
-            index = 0;
-        else if (index > PyByteArray_GET_SIZE(it->it_seq))
-            index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
-        it->it_index = index;
-    }
-    Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
-
-static PyMethodDef bytearrayiter_methods[] = {
-    {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
-     length_hint_doc},
-     {"__reduce__",      (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
-     bytearray_reduce__doc__},
-    {"__setstate__",    (PyCFunction)bytearrayiter_setstate, METH_O,
-     setstate_doc},
-    {NULL, NULL} /* sentinel */
-};
-
-PyTypeObject PyByteArrayIter_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "bytearray_iterator",              /* tp_name */
-    sizeof(bytesiterobject),           /* tp_basicsize */
-    0,                                 /* tp_itemsize */
-    /* methods */
-    (destructor)bytearrayiter_dealloc, /* tp_dealloc */
-    0,                                 /* tp_print */
-    0,                                 /* tp_getattr */
-    0,                                 /* tp_setattr */
-    0,                                 /* tp_reserved */
-    0,                                 /* tp_repr */
-    0,                                 /* tp_as_number */
-    0,                                 /* tp_as_sequence */
-    0,                                 /* tp_as_mapping */
-    0,                                 /* tp_hash */
-    0,                                 /* tp_call */
-    0,                                 /* tp_str */
-    PyObject_GenericGetAttr,           /* tp_getattro */
-    0,                                 /* tp_setattro */
-    0,                                 /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
-    0,                                 /* tp_doc */
-    (traverseproc)bytearrayiter_traverse,  /* tp_traverse */
-    0,                                 /* tp_clear */
-    0,                                 /* tp_richcompare */
-    0,                                 /* tp_weaklistoffset */
-    PyObject_SelfIter,                 /* tp_iter */
-    (iternextfunc)bytearrayiter_next,  /* tp_iternext */
-    bytearrayiter_methods,             /* tp_methods */
-    0,
-};
-
-static PyObject *
-bytearray_iter(PyObject *seq)
-{
-    bytesiterobject *it;
-
-    if (!PyByteArray_Check(seq)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
-    if (it == NULL)
-        return NULL;
-    it->it_index = 0;
-    Py_INCREF(seq);
-    it->it_seq = (PyByteArrayObject *)seq;
-    _PyObject_GC_TRACK(it);
-    return (PyObject *)it;
-}
+/*[clinic end generated code: output=70ea384faeca8d16 input=a9049054013a1b77]*/
diff --git a/Objects/bytesobject.c b/Objects/clinic/bytesobject.c.h
copy from Objects/bytesobject.c
copy to Objects/clinic/bytesobject.c.h
--- a/Objects/bytesobject.c
+++ b/Objects/clinic/bytesobject.c.h
@@ -1,1617 +1,5 @@
-/* bytes object implementation */
-
-#define PY_SSIZE_T_CLEAN
-
-#include "Python.h"
-
-#include "bytes_methods.h"
-#include <stddef.h>
-
 /*[clinic input]
-class bytes "PyBytesObject*" "&PyBytes_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=1a1d9102afc1b00c]*/
-
-#ifdef COUNT_ALLOCS
-Py_ssize_t null_strings, one_strings;
-#endif
-
-static PyBytesObject *characters[UCHAR_MAX + 1];
-static PyBytesObject *nullstring;
-
-/* PyBytesObject_SIZE gives the basic size of a string; any memory allocation
-   for a string of length n should request PyBytesObject_SIZE + n bytes.
-
-   Using PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves
-   3 bytes per string allocation on a typical system.
-*/
-#define PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1)
-
-/*
-   For PyBytes_FromString(), the parameter `str' points to a null-terminated
-   string containing exactly `size' bytes.
-
-   For PyBytes_FromStringAndSize(), the parameter the parameter `str' is
-   either NULL or else points to a string containing at least `size' bytes.
-   For PyBytes_FromStringAndSize(), the string in the `str' parameter does
-   not have to be null-terminated.  (Therefore it is safe to construct a
-   substring by calling `PyBytes_FromStringAndSize(origstring, substrlen)'.)
-   If `str' is NULL then PyBytes_FromStringAndSize() will allocate `size+1'
-   bytes (setting the last byte to the null terminating character) and you can
-   fill in the data yourself.  If `str' is non-NULL then the resulting
-   PyBytes object must be treated as immutable and you must not fill in nor
-   alter the data yourself, since the strings may be shared.
-
-   The PyObject member `op->ob_size', which denotes the number of "extra
-   items" in a variable-size object, will contain the number of bytes
-   allocated for string data, not counting the null terminating character.
-   It is therefore equal to the `size' parameter (for
-   PyBytes_FromStringAndSize()) or the length of the string in the `str'
-   parameter (for PyBytes_FromString()).
-*/
-static PyObject *
-_PyBytes_FromSize(Py_ssize_t size, int use_calloc)
-{
-    PyBytesObject *op;
-    assert(size >= 0);
-
-    if (size == 0 && (op = nullstring) != NULL) {
-#ifdef COUNT_ALLOCS
-        null_strings++;
-#endif
-        Py_INCREF(op);
-        return (PyObject *)op;
-    }
-
-    if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "byte string is too large");
-        return NULL;
-    }
-
-    /* Inline PyObject_NewVar */
-    if (use_calloc)
-        op = (PyBytesObject *)PyObject_Calloc(1, PyBytesObject_SIZE + size);
-    else
-        op = (PyBytesObject *)PyObject_Malloc(PyBytesObject_SIZE + size);
-    if (op == NULL)
-        return PyErr_NoMemory();
-    (void)PyObject_INIT_VAR(op, &PyBytes_Type, size);
-    op->ob_shash = -1;
-    if (!use_calloc)
-        op->ob_sval[size] = '\0';
-    /* empty byte string singleton */
-    if (size == 0) {
-        nullstring = op;
-        Py_INCREF(op);
-    }
-    return (PyObject *) op;
-}
-
-PyObject *
-PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
-{
-    PyBytesObject *op;
-    if (size < 0) {
-        PyErr_SetString(PyExc_SystemError,
-            "Negative size passed to PyBytes_FromStringAndSize");
-        return NULL;
-    }
-    if (size == 1 && str != NULL &&
-        (op = characters[*str & UCHAR_MAX]) != NULL)
-    {
-#ifdef COUNT_ALLOCS
-        one_strings++;
-#endif
-        Py_INCREF(op);
-        return (PyObject *)op;
-    }
-
-    op = (PyBytesObject *)_PyBytes_FromSize(size, 0);
-    if (op == NULL)
-        return NULL;
-    if (str == NULL)
-        return (PyObject *) op;
-
-    Py_MEMCPY(op->ob_sval, str, size);
-    /* share short strings */
-    if (size == 1) {
-        characters[*str & UCHAR_MAX] = op;
-        Py_INCREF(op);
-    }
-    return (PyObject *) op;
-}
-
-PyObject *
-PyBytes_FromString(const char *str)
-{
-    size_t size;
-    PyBytesObject *op;
-
-    assert(str != NULL);
-    size = strlen(str);
-    if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
-        PyErr_SetString(PyExc_OverflowError,
-            "byte string is too long");
-        return NULL;
-    }
-    if (size == 0 && (op = nullstring) != NULL) {
-#ifdef COUNT_ALLOCS
-        null_strings++;
-#endif
-        Py_INCREF(op);
-        return (PyObject *)op;
-    }
-    if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
-#ifdef COUNT_ALLOCS
-        one_strings++;
-#endif
-        Py_INCREF(op);
-        return (PyObject *)op;
-    }
-
-    /* Inline PyObject_NewVar */
-    op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size);
-    if (op == NULL)
-        return PyErr_NoMemory();
-    (void)PyObject_INIT_VAR(op, &PyBytes_Type, size);
-    op->ob_shash = -1;
-    Py_MEMCPY(op->ob_sval, str, size+1);
-    /* share short strings */
-    if (size == 0) {
-        nullstring = op;
-        Py_INCREF(op);
-    } else if (size == 1) {
-        characters[*str & UCHAR_MAX] = op;
-        Py_INCREF(op);
-    }
-    return (PyObject *) op;
-}
-
-PyObject *
-PyBytes_FromFormatV(const char *format, va_list vargs)
-{
-    va_list count;
-    Py_ssize_t n = 0;
-    const char* f;
-    char *s;
-    PyObject* string;
-
-    Py_VA_COPY(count, vargs);
-    /* step 1: figure out how large a buffer we need */
-    for (f = format; *f; f++) {
-        if (*f == '%') {
-            const char* p = f;
-            while (*++f && *f != '%' && !Py_ISALPHA(*f))
-                ;
-
-            /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
-             * they don't affect the amount of space we reserve.
-             */
-            if ((*f == 'l' || *f == 'z') &&
-                            (f[1] == 'd' || f[1] == 'u'))
-                ++f;
-
-            switch (*f) {
-            case 'c':
-            {
-                int c = va_arg(count, int);
-                if (c < 0 || c > 255) {
-                    PyErr_SetString(PyExc_OverflowError,
-                                    "PyBytes_FromFormatV(): %c format "
-                                    "expects an integer in range [0; 255]");
-                    return NULL;
-                }
-                n++;
-                break;
-            }
-            case '%':
-                n++;
-                break;
-            case 'd': case 'u': case 'i': case 'x':
-                (void) va_arg(count, int);
-                /* 20 bytes is enough to hold a 64-bit
-                   integer.  Decimal takes the most space.
-                   This isn't enough for octal. */
-                n += 20;
-                break;
-            case 's':
-                s = va_arg(count, char*);
-                n += strlen(s);
-                break;
-            case 'p':
-                (void) va_arg(count, int);
-                /* maximum 64-bit pointer representation:
-                 * 0xffffffffffffffff
-                 * so 19 characters is enough.
-                 * XXX I count 18 -- what's the extra for?
-                 */
-                n += 19;
-                break;
-            default:
-                /* if we stumble upon an unknown
-                   formatting code, copy the rest of
-                   the format string to the output
-                   string. (we cannot just skip the
-                   code, since there's no way to know
-                   what's in the argument list) */
-                n += strlen(p);
-                goto expand;
-            }
-        } else
-            n++;
-    }
- expand:
-    /* step 2: fill the buffer */
-    /* Since we've analyzed how much space we need for the worst case,
-       use sprintf directly instead of the slower PyOS_snprintf. */
-    string = PyBytes_FromStringAndSize(NULL, n);
-    if (!string)
-        return NULL;
-
-    s = PyBytes_AsString(string);
-
-    for (f = format; *f; f++) {
-        if (*f == '%') {
-            const char* p = f++;
-            Py_ssize_t i;
-            int longflag = 0;
-            int size_tflag = 0;
-            /* parse the width.precision part (we're only
-               interested in the precision value, if any) */
-            n = 0;
-            while (Py_ISDIGIT(*f))
-                n = (n*10) + *f++ - '0';
-            if (*f == '.') {
-                f++;
-                n = 0;
-                while (Py_ISDIGIT(*f))
-                    n = (n*10) + *f++ - '0';
-            }
-            while (*f && *f != '%' && !Py_ISALPHA(*f))
-                f++;
-            /* handle the long flag, but only for %ld and %lu.
-               others can be added when necessary. */
-            if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
-                longflag = 1;
-                ++f;
-            }
-            /* handle the size_t flag. */
-            if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
-                size_tflag = 1;
-                ++f;
-            }
-
-            switch (*f) {
-            case 'c':
-            {
-                int c = va_arg(vargs, int);
-                /* c has been checked for overflow in the first step */
-                *s++ = (unsigned char)c;
-                break;
-            }
-            case 'd':
-                if (longflag)
-                    sprintf(s, "%ld", va_arg(vargs, long));
-                else if (size_tflag)
-                    sprintf(s, "%" PY_FORMAT_SIZE_T "d",
-                        va_arg(vargs, Py_ssize_t));
-                else
-                    sprintf(s, "%d", va_arg(vargs, int));
-                s += strlen(s);
-                break;
-            case 'u':
-                if (longflag)
-                    sprintf(s, "%lu",
-                        va_arg(vargs, unsigned long));
-                else if (size_tflag)
-                    sprintf(s, "%" PY_FORMAT_SIZE_T "u",
-                        va_arg(vargs, size_t));
-                else
-                    sprintf(s, "%u",
-                        va_arg(vargs, unsigned int));
-                s += strlen(s);
-                break;
-            case 'i':
-                sprintf(s, "%i", va_arg(vargs, int));
-                s += strlen(s);
-                break;
-            case 'x':
-                sprintf(s, "%x", va_arg(vargs, int));
-                s += strlen(s);
-                break;
-            case 's':
-                p = va_arg(vargs, char*);
-                i = strlen(p);
-                if (n > 0 && i > n)
-                    i = n;
-                Py_MEMCPY(s, p, i);
-                s += i;
-                break;
-            case 'p':
-                sprintf(s, "%p", va_arg(vargs, void*));
-                /* %p is ill-defined:  ensure leading 0x. */
-                if (s[1] == 'X')
-                    s[1] = 'x';
-                else if (s[1] != 'x') {
-                    memmove(s+2, s, strlen(s)+1);
-                    s[0] = '0';
-                    s[1] = 'x';
-                }
-                s += strlen(s);
-                break;
-            case '%':
-                *s++ = '%';
-                break;
-            default:
-                strcpy(s, p);
-                s += strlen(s);
-                goto end;
-            }
-        } else
-            *s++ = *f;
-    }
-
- end:
-    _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string));
-    return string;
-}
-
-PyObject *
-PyBytes_FromFormat(const char *format, ...)
-{
-    PyObject* ret;
-    va_list vargs;
-
-#ifdef HAVE_STDARG_PROTOTYPES
-    va_start(vargs, format);
-#else
-    va_start(vargs);
-#endif
-    ret = PyBytes_FromFormatV(format, vargs);
-    va_end(vargs);
-    return ret;
-}
-
-/* Helpers for formatstring */
-
-Py_LOCAL_INLINE(PyObject *)
-getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
-{
-    Py_ssize_t argidx = *p_argidx;
-    if (argidx < arglen) {
-        (*p_argidx)++;
-        if (arglen < 0)
-            return args;
-        else
-            return PyTuple_GetItem(args, argidx);
-    }
-    PyErr_SetString(PyExc_TypeError,
-                    "not enough arguments for format string");
-    return NULL;
-}
-
-/* Format codes
- * F_LJUST      '-'
- * F_SIGN       '+'
- * F_BLANK      ' '
- * F_ALT        '#'
- * F_ZERO       '0'
- */
-#define F_LJUST (1<<0)
-#define F_SIGN  (1<<1)
-#define F_BLANK (1<<2)
-#define F_ALT   (1<<3)
-#define F_ZERO  (1<<4)
-
-/* Returns a new reference to a PyBytes object, or NULL on failure. */
-
-static PyObject *
-formatfloat(PyObject *v, int flags, int prec, int type)
-{
-    char *p;
-    PyObject *result;
-    double x;
-
-    x = PyFloat_AsDouble(v);
-    if (x == -1.0 && PyErr_Occurred()) {
-        PyErr_Format(PyExc_TypeError, "float argument required, "
-                     "not %.200s", Py_TYPE(v)->tp_name);
-        return NULL;
-    }
-
-    if (prec < 0)
-        prec = 6;
-
-    p = PyOS_double_to_string(x, type, prec,
-                              (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
-
-    if (p == NULL)
-        return NULL;
-    result = PyBytes_FromStringAndSize(p, strlen(p));
-    PyMem_Free(p);
-    return result;
-}
-
-static PyObject *
-formatlong(PyObject *v, int flags, int prec, int type)
-{
-    PyObject *result, *iobj;
-    if (type == 'i')
-        type = 'd';
-    if (PyLong_Check(v))
-        return _PyUnicode_FormatLong(v, flags & F_ALT, prec, type);
-    if (PyNumber_Check(v)) {
-        /* make sure number is a type of integer for o, x, and X */
-        if (type == 'o' || type == 'x' || type == 'X')
-            iobj = PyNumber_Index(v);
-        else
-            iobj = PyNumber_Long(v);
-        if (iobj == NULL) {
-            if (!PyErr_ExceptionMatches(PyExc_TypeError))
-                return NULL;
-        }
-        else if (!PyLong_Check(iobj))
-            Py_CLEAR(iobj);
-        if (iobj != NULL) {
-            result = _PyUnicode_FormatLong(iobj, flags & F_ALT, prec, type);
-            Py_DECREF(iobj);
-            return result;
-        }
-    }
-    PyErr_Format(PyExc_TypeError,
-        "%%%c format: %s is required, not %.200s", type,
-        (type == 'o' || type == 'x' || type == 'X') ? "an integer"
-                                                    : "a number",
-        Py_TYPE(v)->tp_name);
-    return NULL;
-}
-
-static int
-byte_converter(PyObject *arg, char *p)
-{
-    if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) {
-        *p = PyBytes_AS_STRING(arg)[0];
-        return 1;
-    }
-    else if (PyByteArray_Check(arg) && PyByteArray_Size(arg) == 1) {
-        *p = PyByteArray_AS_STRING(arg)[0];
-        return 1;
-    }
-    else {
-        PyObject *iobj;
-        long ival;
-        int overflow;
-        /* make sure number is a type of integer */
-        if (PyLong_Check(arg)) {
-            ival = PyLong_AsLongAndOverflow(arg, &overflow);
-        }
-        else {
-            iobj = PyNumber_Index(arg);
-            if (iobj == NULL) {
-                if (!PyErr_ExceptionMatches(PyExc_TypeError))
-                    return 0;
-                goto onError;
-            }
-            ival = PyLong_AsLongAndOverflow(iobj, &overflow);
-            Py_DECREF(iobj);
-        }
-        if (!overflow && ival == -1 && PyErr_Occurred())
-            goto onError;
-        if (overflow || !(0 <= ival && ival <= 255)) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "%c arg not in range(256)");
-            return 0;
-        }
-        *p = (char)ival;
-        return 1;
-    }
-  onError:
-    PyErr_SetString(PyExc_TypeError,
-        "%c requires an integer in range(256) or a single byte");
-    return 0;
-}
-
-static PyObject *
-format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen)
-{
-    PyObject *func, *result;
-    _Py_IDENTIFIER(__bytes__);
-    /* is it a bytes object? */
-    if (PyBytes_Check(v)) {
-        *pbuf = PyBytes_AS_STRING(v);
-        *plen = PyBytes_GET_SIZE(v);
-        Py_INCREF(v);
-        return v;
-    }
-    if (PyByteArray_Check(v)) {
-        *pbuf = PyByteArray_AS_STRING(v);
-        *plen = PyByteArray_GET_SIZE(v);
-        Py_INCREF(v);
-        return v;
-    }
-    /* does it support __bytes__? */
-    func = _PyObject_LookupSpecial(v, &PyId___bytes__);
-    if (func != NULL) {
-        result = PyObject_CallFunctionObjArgs(func, NULL);
-        Py_DECREF(func);
-        if (result == NULL)
-            return NULL;
-        if (!PyBytes_Check(result)) {
-            PyErr_Format(PyExc_TypeError,
-                         "__bytes__ returned non-bytes (type %.200s)",
-                         Py_TYPE(result)->tp_name);
-            Py_DECREF(result);
-            return NULL;
-        }
-        *pbuf = PyBytes_AS_STRING(result);
-        *plen = PyBytes_GET_SIZE(result);
-        return result;
-    }
-    PyErr_Format(PyExc_TypeError,
-                 "%%b requires bytes, or an object that implements __bytes__, not '%.100s'",
-                 Py_TYPE(v)->tp_name);
-    return NULL;
-}
-
-/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
-
-   FORMATBUFLEN is the length of the buffer in which the ints &
-   chars are formatted. XXX This is a magic number. Each formatting
-   routine does bounds checking to ensure no overflow, but a better
-   solution may be to malloc a buffer of appropriate size for each
-   format. For now, the current solution is sufficient.
-*/
-#define FORMATBUFLEN (size_t)120
-
-PyObject *
-_PyBytes_Format(PyObject *format, PyObject *args)
-{
-    char *fmt, *res;
-    Py_ssize_t arglen, argidx;
-    Py_ssize_t reslen, rescnt, fmtcnt;
-    int args_owned = 0;
-    PyObject *result;
-    PyObject *dict = NULL;
-    if (format == NULL || !PyBytes_Check(format) || args == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    fmt = PyBytes_AS_STRING(format);
-    fmtcnt = PyBytes_GET_SIZE(format);
-    reslen = rescnt = fmtcnt + 100;
-    result = PyBytes_FromStringAndSize((char *)NULL, reslen);
-    if (result == NULL)
-        return NULL;
-    res = PyBytes_AsString(result);
-    if (PyTuple_Check(args)) {
-        arglen = PyTuple_GET_SIZE(args);
-        argidx = 0;
-    }
-    else {
-        arglen = -1;
-        argidx = -2;
-    }
-    if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript &&
-        !PyTuple_Check(args) && !PyBytes_Check(args) && !PyUnicode_Check(args) &&
-        !PyByteArray_Check(args)) {
-            dict = args;
-    }
-    while (--fmtcnt >= 0) {
-        if (*fmt != '%') {
-            if (--rescnt < 0) {
-                rescnt = fmtcnt + 100;
-                reslen += rescnt;
-                if (_PyBytes_Resize(&result, reslen))
-                    return NULL;
-                res = PyBytes_AS_STRING(result)
-                    + reslen - rescnt;
-                --rescnt;
-            }
-            *res++ = *fmt++;
-        }
-        else {
-            /* Got a format specifier */
-            int flags = 0;
-            Py_ssize_t width = -1;
-            int prec = -1;
-            int c = '\0';
-            int fill;
-            PyObject *v = NULL;
-            PyObject *temp = NULL;
-            const char *pbuf = NULL;
-            int sign;
-            Py_ssize_t len = 0;
-            char onechar; /* For byte_converter() */
-
-            fmt++;
-            if (*fmt == '(') {
-                char *keystart;
-                Py_ssize_t keylen;
-                PyObject *key;
-                int pcount = 1;
-
-                if (dict == NULL) {
-                    PyErr_SetString(PyExc_TypeError,
-                             "format requires a mapping");
-                    goto error;
-                }
-                ++fmt;
-                --fmtcnt;
-                keystart = fmt;
-                /* Skip over balanced parentheses */
-                while (pcount > 0 && --fmtcnt >= 0) {
-                    if (*fmt == ')')
-                        --pcount;
-                    else if (*fmt == '(')
-                        ++pcount;
-                    fmt++;
-                }
-                keylen = fmt - keystart - 1;
-                if (fmtcnt < 0 || pcount > 0) {
-                    PyErr_SetString(PyExc_ValueError,
-                               "incomplete format key");
-                    goto error;
-                }
-                key = PyBytes_FromStringAndSize(keystart,
-                                                 keylen);
-                if (key == NULL)
-                    goto error;
-                if (args_owned) {
-                    Py_DECREF(args);
-                    args_owned = 0;
-                }
-                args = PyObject_GetItem(dict, key);
-                Py_DECREF(key);
-                if (args == NULL) {
-                    goto error;
-                }
-                args_owned = 1;
-                arglen = -1;
-                argidx = -2;
-            }
-            while (--fmtcnt >= 0) {
-                switch (c = *fmt++) {
-                case '-': flags |= F_LJUST; continue;
-                case '+': flags |= F_SIGN; continue;
-                case ' ': flags |= F_BLANK; continue;
-                case '#': flags |= F_ALT; continue;
-                case '0': flags |= F_ZERO; continue;
-                }
-                break;
-            }
-            if (c == '*') {
-                v = getnextarg(args, arglen, &argidx);
-                if (v == NULL)
-                    goto error;
-                if (!PyLong_Check(v)) {
-                    PyErr_SetString(PyExc_TypeError,
-                                    "* wants int");
-                    goto error;
-                }
-                width = PyLong_AsSsize_t(v);
-                if (width == -1 && PyErr_Occurred())
-                    goto error;
-                if (width < 0) {
-                    flags |= F_LJUST;
-                    width = -width;
-                }
-                if (--fmtcnt >= 0)
-                    c = *fmt++;
-            }
-            else if (c >= 0 && isdigit(c)) {
-                width = c - '0';
-                while (--fmtcnt >= 0) {
-                    c = Py_CHARMASK(*fmt++);
-                    if (!isdigit(c))
-                        break;
-                    if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
-                        PyErr_SetString(
-                            PyExc_ValueError,
-                            "width too big");
-                        goto error;
-                    }
-                    width = width*10 + (c - '0');
-                }
-            }
-            if (c == '.') {
-                prec = 0;
-                if (--fmtcnt >= 0)
-                    c = *fmt++;
-                if (c == '*') {
-                    v = getnextarg(args, arglen, &argidx);
-                    if (v == NULL)
-                        goto error;
-                    if (!PyLong_Check(v)) {
-                        PyErr_SetString(
-                            PyExc_TypeError,
-                            "* wants int");
-                        goto error;
-                    }
-                    prec = _PyLong_AsInt(v);
-                    if (prec == -1 && PyErr_Occurred())
-                        goto error;
-                    if (prec < 0)
-                        prec = 0;
-                    if (--fmtcnt >= 0)
-                        c = *fmt++;
-                }
-                else if (c >= 0 && isdigit(c)) {
-                    prec = c - '0';
-                    while (--fmtcnt >= 0) {
-                        c = Py_CHARMASK(*fmt++);
-                        if (!isdigit(c))
-                            break;
-                        if (prec > (INT_MAX - ((int)c - '0')) / 10) {
-                            PyErr_SetString(
-                                PyExc_ValueError,
-                                "prec too big");
-                            goto error;
-                        }
-                        prec = prec*10 + (c - '0');
-                    }
-                }
-            } /* prec */
-            if (fmtcnt >= 0) {
-                if (c == 'h' || c == 'l' || c == 'L') {
-                    if (--fmtcnt >= 0)
-                        c = *fmt++;
-                }
-            }
-            if (fmtcnt < 0) {
-                PyErr_SetString(PyExc_ValueError,
-                                "incomplete format");
-                goto error;
-            }
-            if (c != '%') {
-                v = getnextarg(args, arglen, &argidx);
-                if (v == NULL)
-                    goto error;
-            }
-            sign = 0;
-            fill = ' ';
-            switch (c) {
-            case '%':
-                pbuf = "%";
-                len = 1;
-                break;
-            case 'r':
-                // %r is only for 2/3 code; 3 only code should use %a
-            case 'a':
-                temp = PyObject_ASCII(v);
-                if (temp == NULL)
-                    goto error;
-                assert(PyUnicode_IS_ASCII(temp));
-                pbuf = (const char *)PyUnicode_1BYTE_DATA(temp);
-                len = PyUnicode_GET_LENGTH(temp);
-                if (prec >= 0 && len > prec)
-                    len = prec;
-                break;
-            case 's':
-                // %s is only for 2/3 code; 3 only code should use %b
-            case 'b':
-                temp = format_obj(v, &pbuf, &len);
-                if (temp == NULL)
-                    goto error;
-                if (prec >= 0 && len > prec)
-                    len = prec;
-                break;
-            case 'i':
-            case 'd':
-            case 'u':
-            case 'o':
-            case 'x':
-            case 'X':
-                temp = formatlong(v, flags, prec, c);
-                if (!temp)
-                    goto error;
-                assert(PyUnicode_IS_ASCII(temp));
-                pbuf = (const char *)PyUnicode_1BYTE_DATA(temp);
-                len = PyUnicode_GET_LENGTH(temp);
-                sign = 1;
-                if (flags & F_ZERO)
-                    fill = '0';
-                break;
-            case 'e':
-            case 'E':
-            case 'f':
-            case 'F':
-            case 'g':
-            case 'G':
-                temp = formatfloat(v, flags, prec, c);
-                if (temp == NULL)
-                    goto error;
-                pbuf = PyBytes_AS_STRING(temp);
-                len = PyBytes_GET_SIZE(temp);
-                sign = 1;
-                if (flags & F_ZERO)
-                    fill = '0';
-                break;
-            case 'c':
-                pbuf = &onechar;
-                len = byte_converter(v, &onechar);
-                if (!len)
-                    goto error;
-                break;
-            default:
-                PyErr_Format(PyExc_ValueError,
-                  "unsupported format character '%c' (0x%x) "
-                  "at index %zd",
-                  c, c,
-                  (Py_ssize_t)(fmt - 1 -
-                               PyBytes_AsString(format)));
-                goto error;
-            }
-            if (sign) {
-                if (*pbuf == '-' || *pbuf == '+') {
-                    sign = *pbuf++;
-                    len--;
-                }
-                else if (flags & F_SIGN)
-                    sign = '+';
-                else if (flags & F_BLANK)
-                    sign = ' ';
-                else
-                    sign = 0;
-            }
-            if (width < len)
-                width = len;
-            if (rescnt - (sign != 0) < width) {
-                reslen -= rescnt;
-                rescnt = width + fmtcnt + 100;
-                reslen += rescnt;
-                if (reslen < 0) {
-                    Py_DECREF(result);
-                    Py_XDECREF(temp);
-                    return PyErr_NoMemory();
-                }
-                if (_PyBytes_Resize(&result, reslen)) {
-                    Py_XDECREF(temp);
-                    return NULL;
-                }
-                res = PyBytes_AS_STRING(result)
-                    + reslen - rescnt;
-            }
-            if (sign) {
-                if (fill != ' ')
-                    *res++ = sign;
-                rescnt--;
-                if (width > len)
-                    width--;
-            }
-            if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
-                assert(pbuf[0] == '0');
-                assert(pbuf[1] == c);
-                if (fill != ' ') {
-                    *res++ = *pbuf++;
-                    *res++ = *pbuf++;
-                }
-                rescnt -= 2;
-                width -= 2;
-                if (width < 0)
-                    width = 0;
-                len -= 2;
-            }
-            if (width > len && !(flags & F_LJUST)) {
-                do {
-                    --rescnt;
-                    *res++ = fill;
-                } while (--width > len);
-            }
-            if (fill == ' ') {
-                if (sign)
-                    *res++ = sign;
-                if ((flags & F_ALT) &&
-                    (c == 'x' || c == 'X')) {
-                    assert(pbuf[0] == '0');
-                    assert(pbuf[1] == c);
-                    *res++ = *pbuf++;
-                    *res++ = *pbuf++;
-                }
-            }
-            Py_MEMCPY(res, pbuf, len);
-            res += len;
-            rescnt -= len;
-            while (--width >= len) {
-                --rescnt;
-                *res++ = ' ';
-            }
-            if (dict && (argidx < arglen) && c != '%') {
-                PyErr_SetString(PyExc_TypeError,
-                           "not all arguments converted during bytes formatting");
-                Py_XDECREF(temp);
-                goto error;
-            }
-            Py_XDECREF(temp);
-        } /* '%' */
-    } /* until end */
-    if (argidx < arglen && !dict) {
-        PyErr_SetString(PyExc_TypeError,
-                        "not all arguments converted during bytes formatting");
-        goto error;
-    }
-    if (args_owned) {
-        Py_DECREF(args);
-    }
-    if (_PyBytes_Resize(&result, reslen - rescnt))
-        return NULL;
-    return result;
-
- error:
-    Py_DECREF(result);
-    if (args_owned) {
-        Py_DECREF(args);
-    }
-    return NULL;
-}
-
-/* =-= */
-
-static void
-bytes_dealloc(PyObject *op)
-{
-    Py_TYPE(op)->tp_free(op);
-}
-
-/* Unescape a backslash-escaped string. If unicode is non-zero,
-   the string is a u-literal. If recode_encoding is non-zero,
-   the string is UTF-8 encoded and should be re-encoded in the
-   specified encoding.  */
-
-PyObject *PyBytes_DecodeEscape(const char *s,
-                                Py_ssize_t len,
-                                const char *errors,
-                                Py_ssize_t unicode,
-                                const char *recode_encoding)
-{
-    int c;
-    char *p, *buf;
-    const char *end;
-    PyObject *v;
-    Py_ssize_t newlen = recode_encoding ? 4*len:len;
-    v = PyBytes_FromStringAndSize((char *)NULL, newlen);
-    if (v == NULL)
-        return NULL;
-    p = buf = PyBytes_AsString(v);
-    end = s + len;
-    while (s < end) {
-        if (*s != '\\') {
-          non_esc:
-            if (recode_encoding && (*s & 0x80)) {
-                PyObject *u, *w;
-                char *r;
-                const char* t;
-                Py_ssize_t rn;
-                t = s;
-                /* Decode non-ASCII bytes as UTF-8. */
-                while (t < end && (*t & 0x80)) t++;
-                u = PyUnicode_DecodeUTF8(s, t - s, errors);
-                if(!u) goto failed;
-
-                /* Recode them in target encoding. */
-                w = PyUnicode_AsEncodedString(
-                    u, recode_encoding, errors);
-                Py_DECREF(u);
-                if (!w)                 goto failed;
-
-                /* Append bytes to output buffer. */
-                assert(PyBytes_Check(w));
-                r = PyBytes_AS_STRING(w);
-                rn = PyBytes_GET_SIZE(w);
-                Py_MEMCPY(p, r, rn);
-                p += rn;
-                Py_DECREF(w);
-                s = t;
-            } else {
-                *p++ = *s++;
-            }
-            continue;
-        }
-        s++;
-        if (s==end) {
-            PyErr_SetString(PyExc_ValueError,
-                            "Trailing \\ in string");
-            goto failed;
-        }
-        switch (*s++) {
-        /* XXX This assumes ASCII! */
-        case '\n': break;
-        case '\\': *p++ = '\\'; break;
-        case '\'': *p++ = '\''; break;
-        case '\"': *p++ = '\"'; break;
-        case 'b': *p++ = '\b'; break;
-        case 'f': *p++ = '\014'; break; /* FF */
-        case 't': *p++ = '\t'; break;
-        case 'n': *p++ = '\n'; break;
-        case 'r': *p++ = '\r'; break;
-        case 'v': *p++ = '\013'; break; /* VT */
-        case 'a': *p++ = '\007'; break; /* BEL, not classic C */
-        case '0': case '1': case '2': case '3':
-        case '4': case '5': case '6': case '7':
-            c = s[-1] - '0';
-            if (s < end && '0' <= *s && *s <= '7') {
-                c = (c<<3) + *s++ - '0';
-                if (s < end && '0' <= *s && *s <= '7')
-                    c = (c<<3) + *s++ - '0';
-            }
-            *p++ = c;
-            break;
-        case 'x':
-            if (s+1 < end && Py_ISXDIGIT(s[0]) && Py_ISXDIGIT(s[1])) {
-                unsigned int x = 0;
-                c = Py_CHARMASK(*s);
-                s++;
-                if (Py_ISDIGIT(c))
-                    x = c - '0';
-                else if (Py_ISLOWER(c))
-                    x = 10 + c - 'a';
-                else
-                    x = 10 + c - 'A';
-                x = x << 4;
-                c = Py_CHARMASK(*s);
-                s++;
-                if (Py_ISDIGIT(c))
-                    x += c - '0';
-                else if (Py_ISLOWER(c))
-                    x += 10 + c - 'a';
-                else
-                    x += 10 + c - 'A';
-                *p++ = x;
-                break;
-            }
-            if (!errors || strcmp(errors, "strict") == 0) {
-                PyErr_Format(PyExc_ValueError,
-                             "invalid \\x escape at position %d",
-                             s - 2 - (end - len));
-                goto failed;
-            }
-            if (strcmp(errors, "replace") == 0) {
-                *p++ = '?';
-            } else if (strcmp(errors, "ignore") == 0)
-                /* do nothing */;
-            else {
-                PyErr_Format(PyExc_ValueError,
-                             "decoding error; unknown "
-                             "error handling code: %.400s",
-                             errors);
-                goto failed;
-            }
-            /* skip \x */
-            if (s < end && Py_ISXDIGIT(s[0]))
-                s++; /* and a hexdigit */
-            break;
-        default:
-            *p++ = '\\';
-            s--;
-            goto non_esc; /* an arbitrary number of unescaped
-                             UTF-8 bytes may follow. */
-        }
-    }
-    if (p-buf < newlen)
-        _PyBytes_Resize(&v, p - buf);
-    return v;
-  failed:
-    Py_DECREF(v);
-    return NULL;
-}
-
-/* -------------------------------------------------------------------- */
-/* object api */
-
-Py_ssize_t
-PyBytes_Size(PyObject *op)
-{
-    if (!PyBytes_Check(op)) {
-        PyErr_Format(PyExc_TypeError,
-             "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
-        return -1;
-    }
-    return Py_SIZE(op);
-}
-
-char *
-PyBytes_AsString(PyObject *op)
-{
-    if (!PyBytes_Check(op)) {
-        PyErr_Format(PyExc_TypeError,
-             "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
-        return NULL;
-    }
-    return ((PyBytesObject *)op)->ob_sval;
-}
-
-int
-PyBytes_AsStringAndSize(PyObject *obj,
-                         char **s,
-                         Py_ssize_t *len)
-{
-    if (s == NULL) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-
-    if (!PyBytes_Check(obj)) {
-        PyErr_Format(PyExc_TypeError,
-             "expected bytes, %.200s found", Py_TYPE(obj)->tp_name);
-        return -1;
-    }
-
-    *s = PyBytes_AS_STRING(obj);
-    if (len != NULL)
-        *len = PyBytes_GET_SIZE(obj);
-    else if (strlen(*s) != (size_t)PyBytes_GET_SIZE(obj)) {
-        PyErr_SetString(PyExc_ValueError,
-                        "embedded null byte");
-        return -1;
-    }
-    return 0;
-}
-
-/* -------------------------------------------------------------------- */
-/* Methods */
-
-#include "stringlib/stringdefs.h"
-
-#include "stringlib/fastsearch.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/join.h"
-#include "stringlib/partition.h"
-#include "stringlib/split.h"
-#include "stringlib/ctype.h"
-
-#include "stringlib/transmogrify.h"
-
-PyObject *
-PyBytes_Repr(PyObject *obj, int smartquotes)
-{
-    PyBytesObject* op = (PyBytesObject*) obj;
-    Py_ssize_t i, length = Py_SIZE(op);
-    Py_ssize_t newsize, squotes, dquotes;
-    PyObject *v;
-    unsigned char quote, *s, *p;
-
-    /* Compute size of output string */
-    squotes = dquotes = 0;
-    newsize = 3; /* b'' */
-    s = (unsigned char*)op->ob_sval;
-    for (i = 0; i < length; i++) {
-        Py_ssize_t incr = 1;
-        switch(s[i]) {
-        case '\'': squotes++; break;
-        case '"':  dquotes++; break;
-        case '\\': case '\t': case '\n': case '\r':
-            incr = 2; break; /* \C */
-        default:
-            if (s[i] < ' ' || s[i] >= 0x7f)
-                incr = 4; /* \xHH */
-        }
-        if (newsize > PY_SSIZE_T_MAX - incr)
-            goto overflow;
-        newsize += incr;
-    }
-    quote = '\'';
-    if (smartquotes && squotes && !dquotes)
-        quote = '"';
-    if (squotes && quote == '\'') {
-        if (newsize > PY_SSIZE_T_MAX - squotes)
-            goto overflow;
-        newsize += squotes;
-    }
-
-    v = PyUnicode_New(newsize, 127);
-    if (v == NULL) {
-        return NULL;
-    }
-    p = PyUnicode_1BYTE_DATA(v);
-
-    *p++ = 'b', *p++ = quote;
-    for (i = 0; i < length; i++) {
-        unsigned char c = op->ob_sval[i];
-        if (c == quote || c == '\\')
-            *p++ = '\\', *p++ = c;
-        else if (c == '\t')
-            *p++ = '\\', *p++ = 't';
-        else if (c == '\n')
-            *p++ = '\\', *p++ = 'n';
-        else if (c == '\r')
-            *p++ = '\\', *p++ = 'r';
-        else if (c < ' ' || c >= 0x7f) {
-            *p++ = '\\';
-            *p++ = 'x';
-            *p++ = Py_hexdigits[(c & 0xf0) >> 4];
-            *p++ = Py_hexdigits[c & 0xf];
-        }
-        else
-            *p++ = c;
-    }
-    *p++ = quote;
-    assert(_PyUnicode_CheckConsistency(v, 1));
-    return v;
-
-  overflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "bytes object is too large to make repr");
-    return NULL;
-}
-
-static PyObject *
-bytes_repr(PyObject *op)
-{
-    return PyBytes_Repr(op, 1);
-}
-
-static PyObject *
-bytes_str(PyObject *op)
-{
-    if (Py_BytesWarningFlag) {
-        if (PyErr_WarnEx(PyExc_BytesWarning,
-                         "str() on a bytes instance", 1))
-            return NULL;
-    }
-    return bytes_repr(op);
-}
-
-static Py_ssize_t
-bytes_length(PyBytesObject *a)
-{
-    return Py_SIZE(a);
-}
-
-/* This is also used by PyBytes_Concat() */
-static PyObject *
-bytes_concat(PyObject *a, PyObject *b)
-{
-    Py_ssize_t size;
-    Py_buffer va, vb;
-    PyObject *result = NULL;
-
-    va.len = -1;
-    vb.len = -1;
-    if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
-        PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
-        PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
-                     Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
-        goto done;
-    }
-
-    /* Optimize end cases */
-    if (va.len == 0 && PyBytes_CheckExact(b)) {
-        result = b;
-        Py_INCREF(result);
-        goto done;
-    }
-    if (vb.len == 0 && PyBytes_CheckExact(a)) {
-        result = a;
-        Py_INCREF(result);
-        goto done;
-    }
-
-    size = va.len + vb.len;
-    if (size < 0) {
-        PyErr_NoMemory();
-        goto done;
-    }
-
-    result = PyBytes_FromStringAndSize(NULL, size);
-    if (result != NULL) {
-        memcpy(PyBytes_AS_STRING(result), va.buf, va.len);
-        memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len);
-    }
-
-  done:
-    if (va.len != -1)
-        PyBuffer_Release(&va);
-    if (vb.len != -1)
-        PyBuffer_Release(&vb);
-    return result;
-}
-
-static PyObject *
-bytes_repeat(PyBytesObject *a, Py_ssize_t n)
-{
-    Py_ssize_t i;
-    Py_ssize_t j;
-    Py_ssize_t size;
-    PyBytesObject *op;
-    size_t nbytes;
-    if (n < 0)
-        n = 0;
-    /* watch out for overflows:  the size can overflow int,
-     * and the # of bytes needed can overflow size_t
-     */
-    if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) {
-        PyErr_SetString(PyExc_OverflowError,
-            "repeated bytes are too long");
-        return NULL;
-    }
-    size = Py_SIZE(a) * n;
-    if (size == Py_SIZE(a) && PyBytes_CheckExact(a)) {
-        Py_INCREF(a);
-        return (PyObject *)a;
-    }
-    nbytes = (size_t)size;
-    if (nbytes + PyBytesObject_SIZE <= nbytes) {
-        PyErr_SetString(PyExc_OverflowError,
-            "repeated bytes are too long");
-        return NULL;
-    }
-    op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + nbytes);
-    if (op == NULL)
-        return PyErr_NoMemory();
-    (void)PyObject_INIT_VAR(op, &PyBytes_Type, size);
-    op->ob_shash = -1;
-    op->ob_sval[size] = '\0';
-    if (Py_SIZE(a) == 1 && n > 0) {
-        memset(op->ob_sval, a->ob_sval[0] , n);
-        return (PyObject *) op;
-    }
-    i = 0;
-    if (i < size) {
-        Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
-        i = Py_SIZE(a);
-    }
-    while (i < size) {
-        j = (i <= size-i)  ?  i  :  size-i;
-        Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
-        i += j;
-    }
-    return (PyObject *) op;
-}
-
-static int
-bytes_contains(PyObject *self, PyObject *arg)
-{
-    Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
-    if (ival == -1 && PyErr_Occurred()) {
-        Py_buffer varg;
-        Py_ssize_t pos;
-        PyErr_Clear();
-        if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
-            return -1;
-        pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self),
-                             varg.buf, varg.len, 0);
-        PyBuffer_Release(&varg);
-        return pos >= 0;
-    }
-    if (ival < 0 || ival >= 256) {
-        PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
-        return -1;
-    }
-
-    return memchr(PyBytes_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
-}
-
-static PyObject *
-bytes_item(PyBytesObject *a, Py_ssize_t i)
-{
-    if (i < 0 || i >= Py_SIZE(a)) {
-        PyErr_SetString(PyExc_IndexError, "index out of range");
-        return NULL;
-    }
-    return PyLong_FromLong((unsigned char)a->ob_sval[i]);
-}
-
-Py_LOCAL(int)
-bytes_compare_eq(PyBytesObject *a, PyBytesObject *b)
-{
-    int cmp;
-    Py_ssize_t len;
-
-    len = Py_SIZE(a);
-    if (Py_SIZE(b) != len)
-        return 0;
-
-    if (a->ob_sval[0] != b->ob_sval[0])
-        return 0;
-
-    cmp = memcmp(a->ob_sval, b->ob_sval, len);
-    return (cmp == 0);
-}
-
-static PyObject*
-bytes_richcompare(PyBytesObject *a, PyBytesObject *b, int op)
-{
-    int c;
-    Py_ssize_t len_a, len_b;
-    Py_ssize_t min_len;
-    PyObject *result;
-
-    /* Make sure both arguments are strings. */
-    if (!(PyBytes_Check(a) && PyBytes_Check(b))) {
-        if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
-            if (PyObject_IsInstance((PyObject*)a,
-                                    (PyObject*)&PyUnicode_Type) ||
-                PyObject_IsInstance((PyObject*)b,
-                                    (PyObject*)&PyUnicode_Type)) {
-                if (PyErr_WarnEx(PyExc_BytesWarning,
-                            "Comparison between bytes and string", 1))
-                    return NULL;
-            }
-            else if (PyObject_IsInstance((PyObject*)a,
-                                    (PyObject*)&PyLong_Type) ||
-                PyObject_IsInstance((PyObject*)b,
-                                    (PyObject*)&PyLong_Type)) {
-                if (PyErr_WarnEx(PyExc_BytesWarning,
-                            "Comparison between bytes and int", 1))
-                    return NULL;
-            }
-        }
-        result = Py_NotImplemented;
-    }
-    else if (a == b) {
-        switch (op) {
-        case Py_EQ:
-        case Py_LE:
-        case Py_GE:
-            /* a string is equal to itself */
-            result = Py_True;
-            break;
-        case Py_NE:
-        case Py_LT:
-        case Py_GT:
-            result = Py_False;
-            break;
-        default:
-            PyErr_BadArgument();
-            return NULL;
-        }
-    }
-    else if (op == Py_EQ || op == Py_NE) {
-        int eq = bytes_compare_eq(a, b);
-        eq ^= (op == Py_NE);
-        result = eq ? Py_True : Py_False;
-    }
-    else {
-        len_a = Py_SIZE(a);
-        len_b = Py_SIZE(b);
-        min_len = Py_MIN(len_a, len_b);
-        if (min_len > 0) {
-            c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
-            if (c == 0)
-                c = memcmp(a->ob_sval, b->ob_sval, min_len);
-        }
-        else
-            c = 0;
-        if (c == 0)
-            c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
-        switch (op) {
-        case Py_LT: c = c <  0; break;
-        case Py_LE: c = c <= 0; break;
-        case Py_GT: c = c >  0; break;
-        case Py_GE: c = c >= 0; break;
-        default:
-            PyErr_BadArgument();
-            return NULL;
-        }
-        result = c ? Py_True : Py_False;
-    }
-
-    Py_INCREF(result);
-    return result;
-}
-
-static Py_hash_t
-bytes_hash(PyBytesObject *a)
-{
-    if (a->ob_shash == -1) {
-        /* Can't fail */
-        a->ob_shash = _Py_HashBytes(a->ob_sval, Py_SIZE(a));
-    }
-    return a->ob_shash;
-}
-
-static PyObject*
-bytes_subscript(PyBytesObject* self, PyObject* item)
-{
-    if (PyIndex_Check(item)) {
-        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-        if (i == -1 && PyErr_Occurred())
-            return NULL;
-        if (i < 0)
-            i += PyBytes_GET_SIZE(self);
-        if (i < 0 || i >= PyBytes_GET_SIZE(self)) {
-            PyErr_SetString(PyExc_IndexError,
-                            "index out of range");
-            return NULL;
-        }
-        return PyLong_FromLong((unsigned char)self->ob_sval[i]);
-    }
-    else if (PySlice_Check(item)) {
-        Py_ssize_t start, stop, step, slicelength, cur, i;
-        char* source_buf;
-        char* result_buf;
-        PyObject* result;
-
-        if (PySlice_GetIndicesEx(item,
-                         PyBytes_GET_SIZE(self),
-                         &start, &stop, &step, &slicelength) < 0) {
-            return NULL;
-        }
-
-        if (slicelength <= 0) {
-            return PyBytes_FromStringAndSize("", 0);
-        }
-        else if (start == 0 && step == 1 &&
-                 slicelength == PyBytes_GET_SIZE(self) &&
-                 PyBytes_CheckExact(self)) {
-            Py_INCREF(self);
-            return (PyObject *)self;
-        }
-        else if (step == 1) {
-            return PyBytes_FromStringAndSize(
-                PyBytes_AS_STRING(self) + start,
-                slicelength);
-        }
-        else {
-            source_buf = PyBytes_AS_STRING(self);
-            result = PyBytes_FromStringAndSize(NULL, slicelength);
-            if (result == NULL)
-                return NULL;
-
-            result_buf = PyBytes_AS_STRING(result);
-            for (cur = start, i = 0; i < slicelength;
-                 cur += step, i++) {
-                result_buf[i] = source_buf[cur];
-            }
-
-            return result;
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "byte indices must be integers or slices, not %.200s",
-                     Py_TYPE(item)->tp_name);
-        return NULL;
-    }
-}
-
-static int
-bytes_buffer_getbuffer(PyBytesObject *self, Py_buffer *view, int flags)
-{
-    return PyBuffer_FillInfo(view, (PyObject*)self, (void *)self->ob_sval, Py_SIZE(self),
-                             1, flags);
-}
-
-static PySequenceMethods bytes_as_sequence = {
-    (lenfunc)bytes_length, /*sq_length*/
-    (binaryfunc)bytes_concat, /*sq_concat*/
-    (ssizeargfunc)bytes_repeat, /*sq_repeat*/
-    (ssizeargfunc)bytes_item, /*sq_item*/
-    0,                  /*sq_slice*/
-    0,                  /*sq_ass_item*/
-    0,                  /*sq_ass_slice*/
-    (objobjproc)bytes_contains /*sq_contains*/
-};
-
-static PyMappingMethods bytes_as_mapping = {
-    (lenfunc)bytes_length,
-    (binaryfunc)bytes_subscript,
-    0,
-};
-
-static PyBufferProcs bytes_as_buffer = {
-    (getbufferproc)bytes_buffer_getbuffer,
-    NULL,
-};
-
-
-#define LEFTSTRIP 0
-#define RIGHTSTRIP 1
-#define BOTHSTRIP 2
-
-/*[clinic input]
-bytes.split
-
-    sep: object = None
-        The delimiter according which to split the bytes.
-        None (the default value) means split on ASCII whitespace characters
-        (space, tab, return, newline, formfeed, vertical tab).
-    maxsplit: Py_ssize_t = -1
-        Maximum number of splits to do.
-        -1 (the default value) means no limit.
-
-Return a list of the sections in the bytes, using sep as the delimiter.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(bytes_split__doc__,
@@ -1652,46 +40,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_split_impl(PyBytesObject*self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=c80a47afdd505975 input=8b809b39074abbfa]*/
-{
-    Py_ssize_t len = PyBytes_GET_SIZE(self), n;
-    const char *s = PyBytes_AS_STRING(self), *sub;
-    Py_buffer vsub;
-    PyObject *list;
-
-    if (maxsplit < 0)
-        maxsplit = PY_SSIZE_T_MAX;
-    if (sep == Py_None)
-        return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
-    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
-        return NULL;
-    sub = vsub.buf;
-    n = vsub.len;
-
-    list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
-    PyBuffer_Release(&vsub);
-    return list;
-}
-
-/*[clinic input]
-bytes.partition
-
-    self: self(type="PyBytesObject *")
-    sep: Py_buffer
-    /
-
-Partition the bytes into three parts using the given separator.
-
-This will search for the separator sep in the bytes. If the separator is found,
-returns a 3-tuple containing the part before the separator, the separator
-itself, and the part after it.
-
-If the separator is not found, returns a 3-tuple containing the original bytes
-object and two empty bytes objects.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_partition__doc__,
 "partition($self, sep, /)\n"
 "--\n"
@@ -1731,34 +79,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_partition_impl(PyBytesObject *self, Py_buffer *sep)
-/*[clinic end generated code: output=3006727cfbf83aa4 input=bc855dc63ca949de]*/
-{
-    return stringlib_partition(
-        (PyObject*) self,
-        PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
-        sep->obj, (const char *)sep->buf, sep->len
-        );
-}
-
-/*[clinic input]
-bytes.rpartition
-
-    self: self(type="PyBytesObject *")
-    sep: Py_buffer
-    /
-
-Partition the bytes into three parts using the given separator.
-
-This will search for the separator sep in the bytes, starting and the end. If
-the separator is found, returns a 3-tuple containing the part before the
-separator, the separator itself, and the part after it.
-
-If the separator is not found, returns a 3-tuple containing two empty bytes
-objects and the original bytes object.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_rpartition__doc__,
 "rpartition($self, sep, /)\n"
 "--\n"
@@ -1798,25 +118,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep)
-/*[clinic end generated code: output=57b169dc47fa90e8 input=6588fff262a9170e]*/
-{
-    return stringlib_rpartition(
-        (PyObject*) self,
-        PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
-        sep->obj, (const char *)sep->buf, sep->len
-        );
-}
-
-/*[clinic input]
-bytes.rsplit = bytes.split
-
-Return a list of the sections in the bytes, using sep as the delimiter.
-
-Splitting is done starting at the end of the bytes and working to the front.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_rsplit__doc__,
 "rsplit($self, /, sep=None, maxsplit=-1)\n"
 "--\n"
@@ -1857,45 +158,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_rsplit_impl(PyBytesObject*self, PyObject *sep, Py_ssize_t maxsplit)
-/*[clinic end generated code: output=f86feddedbd7b26d input=0f86c9f28f7d7b7b]*/
-{
-    Py_ssize_t len = PyBytes_GET_SIZE(self), n;
-    const char *s = PyBytes_AS_STRING(self), *sub;
-    Py_buffer vsub;
-    PyObject *list;
-
-    if (maxsplit < 0)
-        maxsplit = PY_SSIZE_T_MAX;
-    if (sep == Py_None)
-        return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
-    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
-        return NULL;
-    sub = vsub.buf;
-    n = vsub.len;
-
-    list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
-    PyBuffer_Release(&vsub);
-    return list;
-}
-
-
-/*[clinic input]
-bytes.join
-
-    iterable_of_bytes: object
-    /
-
-Concatenate any number of bytes objects.
-
-The bytes whose method is called is inserted in between each pair.
-
-The result is returned as a new bytes object.
-
-Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_join__doc__,
 "join($self, iterable_of_bytes, /)\n"
 "--\n"
@@ -1911,265 +173,6 @@
 #define BYTES_JOIN_METHODDEF    \
     {"join", (PyCFunction)bytes_join, METH_O, bytes_join__doc__},
 
-static PyObject *
-bytes_join(PyBytesObject*self, PyObject *iterable_of_bytes)
-/*[clinic end generated code: output=e541a14a8da97908 input=7fe377b95bd549d2]*/
-{
-    return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
-}
-
-PyObject *
-_PyBytes_Join(PyObject *sep, PyObject *x)
-{
-    assert(sep != NULL && PyBytes_Check(sep));
-    assert(x != NULL);
-    return bytes_join((PyBytesObject*)sep, x);
-}
-
-/* helper macro to fixup start/end slice values */
-#define ADJUST_INDICES(start, end, len)         \
-    if (end > len)                          \
-        end = len;                          \
-    else if (end < 0) {                     \
-        end += len;                         \
-        if (end < 0)                        \
-        end = 0;                        \
-    }                                       \
-    if (start < 0) {                        \
-        start += len;                       \
-        if (start < 0)                      \
-        start = 0;                      \
-    }
-
-Py_LOCAL_INLINE(Py_ssize_t)
-bytes_find_internal(PyBytesObject *self, PyObject *args, int dir)
-{
-    PyObject *subobj;
-    char byte;
-    Py_buffer subbuf;
-    const char *sub;
-    Py_ssize_t len, sub_len;
-    Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
-    Py_ssize_t res;
-
-    if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
-                                         args, &subobj, &byte, &start, &end))
-        return -2;
-
-    if (subobj) {
-        if (PyObject_GetBuffer(subobj, &subbuf, PyBUF_SIMPLE) != 0)
-            return -2;
-
-        sub = subbuf.buf;
-        sub_len = subbuf.len;
-    }
-    else {
-        sub = &byte;
-        sub_len = 1;
-    }
-    len = PyBytes_GET_SIZE(self);
-
-    ADJUST_INDICES(start, end, len);
-    if (end - start < sub_len)
-        res = -1;
-    /* Issue #23573: FIXME, windows has no memrchr() */
-    else if (sub_len == 1 && dir > 0) {
-        unsigned char needle = *sub;
-        int mode = (dir > 0) ? FAST_SEARCH : FAST_RSEARCH;
-        res = stringlib_fastsearch_memchr_1char(
-            PyBytes_AS_STRING(self) + start, end - start,
-            needle, needle, mode);
-        if (res >= 0)
-            res += start;
-    }
-    else {
-        if (dir > 0)
-            res = stringlib_find_slice(
-                PyBytes_AS_STRING(self), len,
-                sub, sub_len, start, end);
-        else
-            res = stringlib_rfind_slice(
-                PyBytes_AS_STRING(self), len,
-                sub, sub_len, start, end);
-    }
-
-    if (subobj)
-        PyBuffer_Release(&subbuf);
-
-    return res;
-}
-
-
-PyDoc_STRVAR(find__doc__,
-"B.find(sub[, start[, end]]) -> int\n\
-\n\
-Return the lowest index in B where substring sub is found,\n\
-such that sub is contained within B[start:end].  Optional\n\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-bytes_find(PyBytesObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytes_find_internal(self, args, +1);
-    if (result == -2)
-        return NULL;
-    return PyLong_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(index__doc__,
-"B.index(sub[, start[, end]]) -> int\n\
-\n\
-Like B.find() but raise ValueError when the substring is not found.");
-
-static PyObject *
-bytes_index(PyBytesObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytes_find_internal(self, args, +1);
-    if (result == -2)
-        return NULL;
-    if (result == -1) {
-        PyErr_SetString(PyExc_ValueError,
-                        "substring not found");
-        return NULL;
-    }
-    return PyLong_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(rfind__doc__,
-"B.rfind(sub[, start[, end]]) -> int\n\
-\n\
-Return the highest index in B where substring sub is found,\n\
-such that sub is contained within B[start:end].  Optional\n\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-bytes_rfind(PyBytesObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytes_find_internal(self, args, -1);
-    if (result == -2)
-        return NULL;
-    return PyLong_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(rindex__doc__,
-"B.rindex(sub[, start[, end]]) -> int\n\
-\n\
-Like B.rfind() but raise ValueError when the substring is not found.");
-
-static PyObject *
-bytes_rindex(PyBytesObject *self, PyObject *args)
-{
-    Py_ssize_t result = bytes_find_internal(self, args, -1);
-    if (result == -2)
-        return NULL;
-    if (result == -1) {
-        PyErr_SetString(PyExc_ValueError,
-                        "substring not found");
-        return NULL;
-    }
-    return PyLong_FromSsize_t(result);
-}
-
-
-Py_LOCAL_INLINE(PyObject *)
-do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj)
-{
-    Py_buffer vsep;
-    char *s = PyBytes_AS_STRING(self);
-    Py_ssize_t len = PyBytes_GET_SIZE(self);
-    char *sep;
-    Py_ssize_t seplen;
-    Py_ssize_t i, j;
-
-    if (PyObject_GetBuffer(sepobj, &vsep, PyBUF_SIMPLE) != 0)
-        return NULL;
-    sep = vsep.buf;
-    seplen = vsep.len;
-
-    i = 0;
-    if (striptype != RIGHTSTRIP) {
-        while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
-            i++;
-        }
-    }
-
-    j = len;
-    if (striptype != LEFTSTRIP) {
-        do {
-            j--;
-        } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
-        j++;
-    }
-
-    PyBuffer_Release(&vsep);
-
-    if (i == 0 && j == len && PyBytes_CheckExact(self)) {
-        Py_INCREF(self);
-        return (PyObject*)self;
-    }
-    else
-        return PyBytes_FromStringAndSize(s+i, j-i);
-}
-
-
-Py_LOCAL_INLINE(PyObject *)
-do_strip(PyBytesObject *self, int striptype)
-{
-    char *s = PyBytes_AS_STRING(self);
-    Py_ssize_t len = PyBytes_GET_SIZE(self), i, j;
-
-    i = 0;
-    if (striptype != RIGHTSTRIP) {
-        while (i < len && Py_ISSPACE(s[i])) {
-            i++;
-        }
-    }
-
-    j = len;
-    if (striptype != LEFTSTRIP) {
-        do {
-            j--;
-        } while (j >= i && Py_ISSPACE(s[j]));
-        j++;
-    }
-
-    if (i == 0 && j == len && PyBytes_CheckExact(self)) {
-        Py_INCREF(self);
-        return (PyObject*)self;
-    }
-    else
-        return PyBytes_FromStringAndSize(s+i, j-i);
-}
-
-
-Py_LOCAL_INLINE(PyObject *)
-do_argstrip(PyBytesObject *self, int striptype, PyObject *bytes)
-{
-    if (bytes != NULL && bytes != Py_None) {
-        return do_xstrip(self, striptype, bytes);
-    }
-    return do_strip(self, striptype);
-}
-
-/*[clinic input]
-bytes.strip
-
-    self: self(type="PyBytesObject *")
-    bytes: object = None
-    /
-
-Strip leading and trailing bytes contained in the argument.
-
-If the argument is omitted or None, strip leading and trailing ASCII whitespace.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_strip__doc__,
 "strip($self, bytes=None, /)\n"
 "--\n"
@@ -2200,25 +203,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_strip_impl(PyBytesObject *self, PyObject *bytes)
-/*[clinic end generated code: output=c8234a599ba5ec35 input=37daa5fad1395d95]*/
-{
-    return do_argstrip(self, BOTHSTRIP, bytes);
-}
-
-/*[clinic input]
-bytes.lstrip
-
-    self: self(type="PyBytesObject *")
-    bytes: object = None
-    /
-
-Strip leading bytes contained in the argument.
-
-If the argument is omitted or None, strip leading  ASCII whitespace.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_lstrip__doc__,
 "lstrip($self, bytes=None, /)\n"
 "--\n"
@@ -2249,25 +233,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes)
-/*[clinic end generated code: output=529e8511ab6f1115 input=88811b09dfbc2988]*/
-{
-    return do_argstrip(self, LEFTSTRIP, bytes);
-}
-
-/*[clinic input]
-bytes.rstrip
-
-    self: self(type="PyBytesObject *")
-    bytes: object = None
-    /
-
-Strip trailing bytes contained in the argument.
-
-If the argument is omitted or None, strip trailing ASCII whitespace.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_rstrip__doc__,
 "rstrip($self, bytes=None, /)\n"
 "--\n"
@@ -2298,79 +263,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes)
-/*[clinic end generated code: output=e98730bd133e6593 input=8f93c9cd361f0140]*/
-{
-    return do_argstrip(self, RIGHTSTRIP, bytes);
-}
-
-
-PyDoc_STRVAR(count__doc__,
-"B.count(sub[, start[, end]]) -> int\n\
-\n\
-Return the number of non-overlapping occurrences of substring sub in\n\
-string B[start:end].  Optional arguments start and end are interpreted\n\
-as in slice notation.");
-
-static PyObject *
-bytes_count(PyBytesObject *self, PyObject *args)
-{
-    PyObject *sub_obj;
-    const char *str = PyBytes_AS_STRING(self), *sub;
-    Py_ssize_t sub_len;
-    char byte;
-    Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
-
-    Py_buffer vsub;
-    PyObject *count_obj;
-
-    if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
-                                         &start, &end))
-        return NULL;
-
-    if (sub_obj) {
-        if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0)
-            return NULL;
-
-        sub = vsub.buf;
-        sub_len = vsub.len;
-    }
-    else {
-        sub = &byte;
-        sub_len = 1;
-    }
-
-    ADJUST_INDICES(start, end, PyBytes_GET_SIZE(self));
-
-    count_obj = PyLong_FromSsize_t(
-        stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
-        );
-
-    if (sub_obj)
-        PyBuffer_Release(&vsub);
-
-    return count_obj;
-}
-
-
-/*[clinic input]
-bytes.translate
-
-    self: self(type="PyBytesObject *")
-    table: object
-        Translation table, which must be a bytes object of length 256.
-    [
-    deletechars: object
-    ]
-    /
-
-Return a copy with each character mapped by the given translation table.
-
-All characters occurring in the optional argument deletechars are removed.
-The remaining characters are mapped through the given translation table.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_translate__doc__,
 "translate(table, [deletechars])\n"
 "Return a copy with each character mapped by the given translation table.\n"
@@ -2415,138 +307,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_translate_impl(PyBytesObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
-/*[clinic end generated code: output=f0f29a57f41df5d8 input=d8fa5519d7cc4be7]*/
-{
-    char *input, *output;
-    Py_buffer table_view = {NULL, NULL};
-    Py_buffer del_table_view = {NULL, NULL};
-    const char *table_chars;
-    Py_ssize_t i, c, changed = 0;
-    PyObject *input_obj = (PyObject*)self;
-    const char *output_start, *del_table_chars=NULL;
-    Py_ssize_t inlen, tablen, dellen = 0;
-    PyObject *result;
-    int trans_table[256];
-
-    if (PyBytes_Check(table)) {
-        table_chars = PyBytes_AS_STRING(table);
-        tablen = PyBytes_GET_SIZE(table);
-    }
-    else if (table == Py_None) {
-        table_chars = NULL;
-        tablen = 256;
-    }
-    else {
-        if (PyObject_GetBuffer(table, &table_view, PyBUF_SIMPLE) != 0)
-            return NULL;
-        table_chars = table_view.buf;
-        tablen = table_view.len;
-    }
-
-    if (tablen != 256) {
-        PyErr_SetString(PyExc_ValueError,
-          "translation table must be 256 characters long");
-        PyBuffer_Release(&table_view);
-        return NULL;
-    }
-
-    if (deletechars != NULL) {
-        if (PyBytes_Check(deletechars)) {
-            del_table_chars = PyBytes_AS_STRING(deletechars);
-            dellen = PyBytes_GET_SIZE(deletechars);
-        }
-        else {
-            if (PyObject_GetBuffer(deletechars, &del_table_view, PyBUF_SIMPLE) != 0) {
-                PyBuffer_Release(&table_view);
-                return NULL;
-            }
-            del_table_chars = del_table_view.buf;
-            dellen = del_table_view.len;
-        }
-    }
-    else {
-        del_table_chars = NULL;
-        dellen = 0;
-    }
-
-    inlen = PyBytes_GET_SIZE(input_obj);
-    result = PyBytes_FromStringAndSize((char *)NULL, inlen);
-    if (result == NULL) {
-        PyBuffer_Release(&del_table_view);
-        PyBuffer_Release(&table_view);
-        return NULL;
-    }
-    output_start = output = PyBytes_AsString(result);
-    input = PyBytes_AS_STRING(input_obj);
-
-    if (dellen == 0 && table_chars != NULL) {
-        /* If no deletions are required, use faster code */
-        for (i = inlen; --i >= 0; ) {
-            c = Py_CHARMASK(*input++);
-            if (Py_CHARMASK((*output++ = table_chars[c])) != c)
-                changed = 1;
-        }
-        if (!changed && PyBytes_CheckExact(input_obj)) {
-            Py_INCREF(input_obj);
-            Py_DECREF(result);
-            result = input_obj;
-        }
-        PyBuffer_Release(&del_table_view);
-        PyBuffer_Release(&table_view);
-        return result;
-    }
-
-    if (table_chars == NULL) {
-        for (i = 0; i < 256; i++)
-            trans_table[i] = Py_CHARMASK(i);
-    } else {
-        for (i = 0; i < 256; i++)
-            trans_table[i] = Py_CHARMASK(table_chars[i]);
-    }
-    PyBuffer_Release(&table_view);
-
-    for (i = 0; i < dellen; i++)
-        trans_table[(int) Py_CHARMASK(del_table_chars[i])] = -1;
-    PyBuffer_Release(&del_table_view);
-
-    for (i = inlen; --i >= 0; ) {
-        c = Py_CHARMASK(*input++);
-        if (trans_table[c] != -1)
-            if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
-                continue;
-        changed = 1;
-    }
-    if (!changed && PyBytes_CheckExact(input_obj)) {
-        Py_DECREF(result);
-        Py_INCREF(input_obj);
-        return input_obj;
-    }
-    /* Fix the size of the resulting string */
-    if (inlen > 0)
-        _PyBytes_Resize(&result, output - output_start);
-    return result;
-}
-
-
-/*[clinic input]
-
- at staticmethod
-bytes.maketrans
-
-    frm: Py_buffer
-    to: Py_buffer
-    /
-
-Return a translation table useable for the bytes or bytearray translate method.
-
-The returned table will be one where each byte in frm is mapped to the byte at
-the same position in to.
-
-The bytes objects frm and to must be of the same length.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_maketrans__doc__,
 "maketrans(frm, to, /)\n"
 "--\n"
@@ -2588,522 +348,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to)
-/*[clinic end generated code: output=7df47390c476ac60 input=de7a8fc5632bb8f1]*/
-{
-    return _Py_bytes_maketrans(frm, to);
-}
-
-/* find and count characters and substrings */
-
-#define findchar(target, target_len, c)                         \
-  ((char *)memchr((const void *)(target), c, target_len))
-
-/* String ops must return a string.  */
-/* If the object is subclass of string, create a copy */
-Py_LOCAL(PyBytesObject *)
-return_self(PyBytesObject *self)
-{
-    if (PyBytes_CheckExact(self)) {
-        Py_INCREF(self);
-        return self;
-    }
-    return (PyBytesObject *)PyBytes_FromStringAndSize(
-        PyBytes_AS_STRING(self),
-        PyBytes_GET_SIZE(self));
-}
-
-Py_LOCAL_INLINE(Py_ssize_t)
-countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
-{
-    Py_ssize_t count=0;
-    const char *start=target;
-    const char *end=target+target_len;
-
-    while ( (start=findchar(start, end-start, c)) != NULL ) {
-        count++;
-        if (count >= maxcount)
-            break;
-        start += 1;
-    }
-    return count;
-}
-
-
-/* Algorithms for different cases of string replacement */
-
-/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
-Py_LOCAL(PyBytesObject *)
-replace_interleave(PyBytesObject *self,
-                   const char *to_s, Py_ssize_t to_len,
-                   Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count, i;
-    PyBytesObject *result;
-
-    self_len = PyBytes_GET_SIZE(self);
-
-    /* 1 at the end plus 1 after every character;
-       count = min(maxcount, self_len + 1) */
-    if (maxcount <= self_len)
-        count = maxcount;
-    else
-        /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
-        count = self_len + 1;
-
-    /* Check for overflow */
-    /*   result_len = count * to_len + self_len; */
-    assert(count > 0);
-    if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replacement bytes are too long");
-        return NULL;
-    }
-    result_len = count * to_len + self_len;
-
-    if (! (result = (PyBytesObject *)
-                     PyBytes_FromStringAndSize(NULL, result_len)) )
-        return NULL;
-
-    self_s = PyBytes_AS_STRING(self);
-    result_s = PyBytes_AS_STRING(result);
-
-    /* TODO: special case single character, which doesn't need memcpy */
-
-    /* Lay the first one down (guaranteed this will occur) */
-    Py_MEMCPY(result_s, to_s, to_len);
-    result_s += to_len;
-    count -= 1;
-
-    for (i=0; i<count; i++) {
-        *result_s++ = *self_s++;
-        Py_MEMCPY(result_s, to_s, to_len);
-        result_s += to_len;
-    }
-
-    /* Copy the rest of the original string */
-    Py_MEMCPY(result_s, self_s, self_len-i);
-
-    return result;
-}
-
-/* Special case for deleting a single character */
-/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
-Py_LOCAL(PyBytesObject *)
-replace_delete_single_character(PyBytesObject *self,
-                                char from_c, Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count;
-    PyBytesObject *result;
-
-    self_len = PyBytes_GET_SIZE(self);
-    self_s = PyBytes_AS_STRING(self);
-
-    count = countchar(self_s, self_len, from_c, maxcount);
-    if (count == 0) {
-        return return_self(self);
-    }
-
-    result_len = self_len - count;  /* from_len == 1 */
-    assert(result_len>=0);
-
-    if ( (result = (PyBytesObject *)
-                    PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
-        return NULL;
-    result_s = PyBytes_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        next = findchar(start, end-start, from_c);
-        if (next == NULL)
-            break;
-        Py_MEMCPY(result_s, start, next-start);
-        result_s += (next-start);
-        start = next+1;
-    }
-    Py_MEMCPY(result_s, start, end-start);
-
-    return result;
-}
-
-/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
-
-Py_LOCAL(PyBytesObject *)
-replace_delete_substring(PyBytesObject *self,
-                         const char *from_s, Py_ssize_t from_len,
-                         Py_ssize_t maxcount) {
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count, offset;
-    PyBytesObject *result;
-
-    self_len = PyBytes_GET_SIZE(self);
-    self_s = PyBytes_AS_STRING(self);
-
-    count = stringlib_count(self_s, self_len,
-                            from_s, from_len,
-                            maxcount);
-
-    if (count == 0) {
-        /* no matches */
-        return return_self(self);
-    }
-
-    result_len = self_len - (count * from_len);
-    assert (result_len>=0);
-
-    if ( (result = (PyBytesObject *)
-          PyBytes_FromStringAndSize(NULL, result_len)) == NULL )
-        return NULL;
-
-    result_s = PyBytes_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        offset = stringlib_find(start, end-start,
-                                from_s, from_len,
-                                0);
-        if (offset == -1)
-            break;
-        next = start + offset;
-
-        Py_MEMCPY(result_s, start, next-start);
-
-        result_s += (next-start);
-        start = next+from_len;
-    }
-    Py_MEMCPY(result_s, start, end-start);
-    return result;
-}
-
-/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
-Py_LOCAL(PyBytesObject *)
-replace_single_character_in_place(PyBytesObject *self,
-                                  char from_c, char to_c,
-                                  Py_ssize_t maxcount)
-{
-    char *self_s, *result_s, *start, *end, *next;
-    Py_ssize_t self_len;
-    PyBytesObject *result;
-
-    /* The result string will be the same size */
-    self_s = PyBytes_AS_STRING(self);
-    self_len = PyBytes_GET_SIZE(self);
-
-    next = findchar(self_s, self_len, from_c);
-
-    if (next == NULL) {
-        /* No matches; return the original string */
-        return return_self(self);
-    }
-
-    /* Need to make a new string */
-    result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len);
-    if (result == NULL)
-        return NULL;
-    result_s = PyBytes_AS_STRING(result);
-    Py_MEMCPY(result_s, self_s, self_len);
-
-    /* change everything in-place, starting with this one */
-    start =  result_s + (next-self_s);
-    *start = to_c;
-    start++;
-    end = result_s + self_len;
-
-    while (--maxcount > 0) {
-        next = findchar(start, end-start, from_c);
-        if (next == NULL)
-            break;
-        *next = to_c;
-        start = next+1;
-    }
-
-    return result;
-}
-
-/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyBytesObject *)
-replace_substring_in_place(PyBytesObject *self,
-                           const char *from_s, Py_ssize_t from_len,
-                           const char *to_s, Py_ssize_t to_len,
-                           Py_ssize_t maxcount)
-{
-    char *result_s, *start, *end;
-    char *self_s;
-    Py_ssize_t self_len, offset;
-    PyBytesObject *result;
-
-    /* The result string will be the same size */
-
-    self_s = PyBytes_AS_STRING(self);
-    self_len = PyBytes_GET_SIZE(self);
-
-    offset = stringlib_find(self_s, self_len,
-                            from_s, from_len,
-                            0);
-    if (offset == -1) {
-        /* No matches; return the original string */
-        return return_self(self);
-    }
-
-    /* Need to make a new string */
-    result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len);
-    if (result == NULL)
-        return NULL;
-    result_s = PyBytes_AS_STRING(result);
-    Py_MEMCPY(result_s, self_s, self_len);
-
-    /* change everything in-place, starting with this one */
-    start =  result_s + offset;
-    Py_MEMCPY(start, to_s, from_len);
-    start += from_len;
-    end = result_s + self_len;
-
-    while ( --maxcount > 0) {
-        offset = stringlib_find(start, end-start,
-                                from_s, from_len,
-                                0);
-        if (offset==-1)
-            break;
-        Py_MEMCPY(start+offset, to_s, from_len);
-        start += offset+from_len;
-    }
-
-    return result;
-}
-
-/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyBytesObject *)
-replace_single_character(PyBytesObject *self,
-                         char from_c,
-                         const char *to_s, Py_ssize_t to_len,
-                         Py_ssize_t maxcount)
-{
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count;
-    PyBytesObject *result;
-
-    self_s = PyBytes_AS_STRING(self);
-    self_len = PyBytes_GET_SIZE(self);
-
-    count = countchar(self_s, self_len, from_c, maxcount);
-    if (count == 0) {
-        /* no matches, return unchanged */
-        return return_self(self);
-    }
-
-    /* use the difference between current and new, hence the "-1" */
-    /*   result_len = self_len + count * (to_len-1)  */
-    assert(count > 0);
-    if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replacement bytes are too long");
-        return NULL;
-    }
-    result_len = self_len + count * (to_len - 1);
-
-    if ( (result = (PyBytesObject *)
-          PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
-        return NULL;
-    result_s = PyBytes_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        next = findchar(start, end-start, from_c);
-        if (next == NULL)
-            break;
-
-        if (next == start) {
-            /* replace with the 'to' */
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start += 1;
-        } else {
-            /* copy the unchanged old then the 'to' */
-            Py_MEMCPY(result_s, start, next-start);
-            result_s += (next-start);
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start = next+1;
-        }
-    }
-    /* Copy the remainder of the remaining string */
-    Py_MEMCPY(result_s, start, end-start);
-
-    return result;
-}
-
-/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyBytesObject *)
-replace_substring(PyBytesObject *self,
-                  const char *from_s, Py_ssize_t from_len,
-                  const char *to_s, Py_ssize_t to_len,
-                  Py_ssize_t maxcount) {
-    char *self_s, *result_s;
-    char *start, *next, *end;
-    Py_ssize_t self_len, result_len;
-    Py_ssize_t count, offset;
-    PyBytesObject *result;
-
-    self_s = PyBytes_AS_STRING(self);
-    self_len = PyBytes_GET_SIZE(self);
-
-    count = stringlib_count(self_s, self_len,
-                            from_s, from_len,
-                            maxcount);
-
-    if (count == 0) {
-        /* no matches, return unchanged */
-        return return_self(self);
-    }
-
-    /* Check for overflow */
-    /*    result_len = self_len + count * (to_len-from_len) */
-    assert(count > 0);
-    if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replacement bytes are too long");
-        return NULL;
-    }
-    result_len = self_len + count * (to_len-from_len);
-
-    if ( (result = (PyBytesObject *)
-          PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
-        return NULL;
-    result_s = PyBytes_AS_STRING(result);
-
-    start = self_s;
-    end = self_s + self_len;
-    while (count-- > 0) {
-        offset = stringlib_find(start, end-start,
-                                from_s, from_len,
-                                0);
-        if (offset == -1)
-            break;
-        next = start+offset;
-        if (next == start) {
-            /* replace with the 'to' */
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start += from_len;
-        } else {
-            /* copy the unchanged old then the 'to' */
-            Py_MEMCPY(result_s, start, next-start);
-            result_s += (next-start);
-            Py_MEMCPY(result_s, to_s, to_len);
-            result_s += to_len;
-            start = next+from_len;
-        }
-    }
-    /* Copy the remainder of the remaining string */
-    Py_MEMCPY(result_s, start, end-start);
-
-    return result;
-}
-
-
-Py_LOCAL(PyBytesObject *)
-replace(PyBytesObject *self,
-    const char *from_s, Py_ssize_t from_len,
-    const char *to_s, Py_ssize_t to_len,
-    Py_ssize_t maxcount)
-{
-    if (maxcount < 0) {
-        maxcount = PY_SSIZE_T_MAX;
-    } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) {
-        /* nothing to do; return the original string */
-        return return_self(self);
-    }
-
-    if (maxcount == 0 ||
-        (from_len == 0 && to_len == 0)) {
-        /* nothing to do; return the original string */
-        return return_self(self);
-    }
-
-    /* Handle zero-length special cases */
-
-    if (from_len == 0) {
-        /* insert the 'to' string everywhere.   */
-        /*    >>> "Python".replace("", ".")     */
-        /*    '.P.y.t.h.o.n.'                   */
-        return replace_interleave(self, to_s, to_len, maxcount);
-    }
-
-    /* Except for "".replace("", "A") == "A" there is no way beyond this */
-    /* point for an empty self string to generate a non-empty string */
-    /* Special case so the remaining code always gets a non-empty string */
-    if (PyBytes_GET_SIZE(self) == 0) {
-        return return_self(self);
-    }
-
-    if (to_len == 0) {
-        /* delete all occurrences of 'from' string */
-        if (from_len == 1) {
-            return replace_delete_single_character(
-                self, from_s[0], maxcount);
-        } else {
-            return replace_delete_substring(self, from_s,
-                                            from_len, maxcount);
-        }
-    }
-
-    /* Handle special case where both strings have the same length */
-
-    if (from_len == to_len) {
-        if (from_len == 1) {
-            return replace_single_character_in_place(
-                self,
-                from_s[0],
-                to_s[0],
-                maxcount);
-        } else {
-            return replace_substring_in_place(
-                self, from_s, from_len, to_s, to_len,
-                maxcount);
-        }
-    }
-
-    /* Otherwise use the more generic algorithms */
-    if (from_len == 1) {
-        return replace_single_character(self, from_s[0],
-                                        to_s, to_len, maxcount);
-    } else {
-        /* len('from')>=2, len('to')>=1 */
-        return replace_substring(self, from_s, from_len, to_s, to_len,
-                                 maxcount);
-    }
-}
-
-
-/*[clinic input]
-bytes.replace
-
-    old: Py_buffer
-    new: Py_buffer
-    count: Py_ssize_t = -1
-        Maximum number of occurrences to replace.
-        -1 (the default value) means replace all occurrences.
-    /
-
-Return a copy with all occurrences of substring old replaced by new.
-
-If the optional argument count is given, only the first count occurrences are
-replaced.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_replace__doc__,
 "replace($self, old, new, count=-1, /)\n"
 "--\n"
@@ -3148,174 +392,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_replace_impl(PyBytesObject*self, Py_buffer *old, Py_buffer *new, Py_ssize_t count)
-/*[clinic end generated code: output=f07bd9ecf29ee8d8 input=b2fbbf0bf04de8e5]*/
-{
-    return (PyObject *)replace((PyBytesObject *) self,
-                               (const char *)old->buf, old->len,
-                               (const char *)new->buf, new->len, count);
-}
-
-/** End DALKE **/
-
-/* Matches the end (direction >= 0) or start (direction < 0) of self
- * against substr, using the start and end arguments. Returns
- * -1 on error, 0 if not found and 1 if found.
- */
-Py_LOCAL(int)
-_bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start,
-                  Py_ssize_t end, int direction)
-{
-    Py_ssize_t len = PyBytes_GET_SIZE(self);
-    Py_ssize_t slen;
-    Py_buffer sub_view = {NULL, NULL};
-    const char* sub;
-    const char* str;
-
-    if (PyBytes_Check(substr)) {
-        sub = PyBytes_AS_STRING(substr);
-        slen = PyBytes_GET_SIZE(substr);
-    }
-    else {
-        if (PyObject_GetBuffer(substr, &sub_view, PyBUF_SIMPLE) != 0)
-            return -1;
-        sub = sub_view.buf;
-        slen = sub_view.len;
-    }
-    str = PyBytes_AS_STRING(self);
-
-    ADJUST_INDICES(start, end, len);
-
-    if (direction < 0) {
-        /* startswith */
-        if (start+slen > len)
-            goto notfound;
-    } else {
-        /* endswith */
-        if (end-start < slen || start > len)
-            goto notfound;
-
-        if (end-slen > start)
-            start = end - slen;
-    }
-    if (end-start < slen)
-        goto notfound;
-    if (memcmp(str+start, sub, slen) != 0)
-        goto notfound;
-
-    PyBuffer_Release(&sub_view);
-    return 1;
-
-notfound:
-    PyBuffer_Release(&sub_view);
-    return 0;
-}
-
-
-PyDoc_STRVAR(startswith__doc__,
-"B.startswith(prefix[, start[, end]]) -> bool\n\
-\n\
-Return True if B starts with the specified prefix, False otherwise.\n\
-With optional start, test B beginning at that position.\n\
-With optional end, stop comparing B at that position.\n\
-prefix can also be a tuple of bytes to try.");
-
-static PyObject *
-bytes_startswith(PyBytesObject *self, PyObject *args)
-{
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    PyObject *subobj;
-    int result;
-
-    if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
-        return NULL;
-    if (PyTuple_Check(subobj)) {
-        Py_ssize_t i;
-        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-            result = _bytes_tailmatch(self,
-                            PyTuple_GET_ITEM(subobj, i),
-                            start, end, -1);
-            if (result == -1)
-                return NULL;
-            else if (result) {
-                Py_RETURN_TRUE;
-            }
-        }
-        Py_RETURN_FALSE;
-    }
-    result = _bytes_tailmatch(self, subobj, start, end, -1);
-    if (result == -1) {
-        if (PyErr_ExceptionMatches(PyExc_TypeError))
-            PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
-                         "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
-        return NULL;
-    }
-    else
-        return PyBool_FromLong(result);
-}
-
-
-PyDoc_STRVAR(endswith__doc__,
-"B.endswith(suffix[, start[, end]]) -> bool\n\
-\n\
-Return True if B ends with the specified suffix, False otherwise.\n\
-With optional start, test B beginning at that position.\n\
-With optional end, stop comparing B at that position.\n\
-suffix can also be a tuple of bytes to try.");
-
-static PyObject *
-bytes_endswith(PyBytesObject *self, PyObject *args)
-{
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    PyObject *subobj;
-    int result;
-
-    if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
-        return NULL;
-    if (PyTuple_Check(subobj)) {
-        Py_ssize_t i;
-        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-            result = _bytes_tailmatch(self,
-                            PyTuple_GET_ITEM(subobj, i),
-                            start, end, +1);
-            if (result == -1)
-                return NULL;
-            else if (result) {
-                Py_RETURN_TRUE;
-            }
-        }
-        Py_RETURN_FALSE;
-    }
-    result = _bytes_tailmatch(self, subobj, start, end, +1);
-    if (result == -1) {
-        if (PyErr_ExceptionMatches(PyExc_TypeError))
-            PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
-                         "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
-        return NULL;
-    }
-    else
-        return PyBool_FromLong(result);
-}
-
-
-/*[clinic input]
-bytes.decode
-
-    encoding: str(c_default="NULL") = 'utf-8'
-        The encoding with which to decode the bytes.
-    errors: str(c_default="NULL") = 'strict'
-        The error handling scheme to use for the handling of decoding errors.
-        The default is 'strict' meaning that decoding errors raise a
-        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
-        as well as any other name registered with codecs.register_error that
-        can handle UnicodeDecodeErrors.
-
-Decode the bytes using the codec registered for encoding.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_decode__doc__,
 "decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
 "--\n"
@@ -3355,25 +431,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_decode_impl(PyBytesObject*self, const char *encoding, const char *errors)
-/*[clinic end generated code: output=61a80290bbfce696 input=958174769d2a40ca]*/
-{
-    return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
-}
-
-
-/*[clinic input]
-bytes.splitlines
-
-    keepends: int(py_default="False") = 0
-
-Return a list of the lines in the bytes, breaking at line boundaries.
-
-Line breaks are not included in the resulting list unless keepends is given and
-true.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_splitlines__doc__,
 "splitlines($self, /, keepends=False)\n"
 "--\n"
@@ -3406,45 +463,6 @@
     return return_value;
 }
 
-static PyObject *
-bytes_splitlines_impl(PyBytesObject*self, int keepends)
-/*[clinic end generated code: output=79da057d05d126de input=ddb93e3351080c8c]*/
-{
-    return stringlib_splitlines(
-        (PyObject*) self, PyBytes_AS_STRING(self),
-        PyBytes_GET_SIZE(self), keepends
-        );
-}
-
-static int
-hex_digit_to_int(Py_UCS4 c)
-{
-    if (c >= 128)
-        return -1;
-    if (Py_ISDIGIT(c))
-        return c - '0';
-    else {
-        if (Py_ISUPPER(c))
-            c = Py_TOLOWER(c);
-        if (c >= 'a' && c <= 'f')
-            return c - 'a' + 10;
-    }
-    return -1;
-}
-
-/*[clinic input]
- at classmethod
-bytes.fromhex
-
-    string: unicode
-    /
-
-Create a bytes object from a string of hexadecimal numbers.
-
-Spaces between two numbers are accepted.
-Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(bytes_fromhex__doc__,
 "fromhex($type, string, /)\n"
 "--\n"
@@ -3475,720 +493,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-bytes_fromhex_impl(PyTypeObject *type, PyObject *string)
-/*[clinic end generated code: output=09e6cbef56cbbb65 input=bf4d1c361670acd3]*/
-{
-    PyObject *newstring;
-    char *buf;
-    Py_ssize_t hexlen, byteslen, i, j;
-    int top, bot;
-    void *data;
-    unsigned int kind;
-
-    assert(PyUnicode_Check(string));
-    if (PyUnicode_READY(string))
-        return NULL;
-    kind = PyUnicode_KIND(string);
-    data = PyUnicode_DATA(string);
-    hexlen = PyUnicode_GET_LENGTH(string);
-
-    byteslen = hexlen/2; /* This overestimates if there are spaces */
-    newstring = PyBytes_FromStringAndSize(NULL, byteslen);
-    if (!newstring)
-        return NULL;
-    buf = PyBytes_AS_STRING(newstring);
-    for (i = j = 0; i < hexlen; i += 2) {
-        /* skip over spaces in the input */
-        while (PyUnicode_READ(kind, data, i) == ' ')
-            i++;
-        if (i >= hexlen)
-            break;
-        top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
-        bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
-        if (top == -1 || bot == -1) {
-            PyErr_Format(PyExc_ValueError,
-                         "non-hexadecimal number found in "
-                         "fromhex() arg at position %zd", i);
-            goto error;
-        }
-        buf[j++] = (top << 4) + bot;
-    }
-    if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0)
-        goto error;
-    return newstring;
-
-  error:
-    Py_XDECREF(newstring);
-    return NULL;
-}
-
-static PyObject *
-bytes_getnewargs(PyBytesObject *v)
-{
-    return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(v));
-}
-
-
-static PyMethodDef
-bytes_methods[] = {
-    {"__getnewargs__",          (PyCFunction)bytes_getnewargs,  METH_NOARGS},
-    {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
-     _Py_capitalize__doc__},
-    {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
-    {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__},
-    BYTES_DECODE_METHODDEF
-    {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS,
-     endswith__doc__},
-    {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
-     expandtabs__doc__},
-    {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__},
-    BYTES_FROMHEX_METHODDEF
-    {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__},
-    {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
-     _Py_isalnum__doc__},
-    {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
-     _Py_isalpha__doc__},
-    {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
-     _Py_isdigit__doc__},
-    {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
-     _Py_islower__doc__},
-    {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
-     _Py_isspace__doc__},
-    {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
-     _Py_istitle__doc__},
-    {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
-     _Py_isupper__doc__},
-    BYTES_JOIN_METHODDEF
-    {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
-    {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
-    BYTES_LSTRIP_METHODDEF
-    BYTES_MAKETRANS_METHODDEF
-    BYTES_PARTITION_METHODDEF
-    BYTES_REPLACE_METHODDEF
-    {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__},
-    {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__},
-    {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
-    BYTES_RPARTITION_METHODDEF
-    BYTES_RSPLIT_METHODDEF
-    BYTES_RSTRIP_METHODDEF
-    BYTES_SPLIT_METHODDEF
-    BYTES_SPLITLINES_METHODDEF
-    {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS,
-     startswith__doc__},
-    BYTES_STRIP_METHODDEF
-    {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
-     _Py_swapcase__doc__},
-    {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
-    BYTES_TRANSLATE_METHODDEF
-    {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
-    {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
-    {NULL,     NULL}                         /* sentinel */
-};
-
-static PyObject *
-bytes_mod(PyObject *v, PyObject *w)
-{
-    if (!PyBytes_Check(v))
-        Py_RETURN_NOTIMPLEMENTED;
-    return _PyBytes_Format(v, w);
-}
-
-static PyNumberMethods bytes_as_number = {
-    0,              /*nb_add*/
-    0,              /*nb_subtract*/
-    0,              /*nb_multiply*/
-    bytes_mod,      /*nb_remainder*/
-};
-
-static PyObject *
-str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
-
-static PyObject *
-bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *x = NULL;
-    const char *encoding = NULL;
-    const char *errors = NULL;
-    PyObject *new = NULL;
-    PyObject *func;
-    Py_ssize_t size;
-    static char *kwlist[] = {"source", "encoding", "errors", 0};
-    _Py_IDENTIFIER(__bytes__);
-
-    if (type != &PyBytes_Type)
-        return str_subtype_new(type, args, kwds);
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytes", kwlist, &x,
-                                     &encoding, &errors))
-        return NULL;
-    if (x == NULL) {
-        if (encoding != NULL || errors != NULL) {
-            PyErr_SetString(PyExc_TypeError,
-                            "encoding or errors without sequence "
-                            "argument");
-            return NULL;
-        }
-        return PyBytes_FromStringAndSize(NULL, 0);
-    }
-
-    if (PyUnicode_Check(x)) {
-        /* Encode via the codec registry */
-        if (encoding == NULL) {
-            PyErr_SetString(PyExc_TypeError,
-                            "string argument without an encoding");
-            return NULL;
-        }
-        new = PyUnicode_AsEncodedString(x, encoding, errors);
-        if (new == NULL)
-            return NULL;
-        assert(PyBytes_Check(new));
-        return new;
-    }
-
-    /* If it's not unicode, there can't be encoding or errors */
-    if (encoding != NULL || errors != NULL) {
-        PyErr_SetString(PyExc_TypeError,
-            "encoding or errors without a string argument");
-        return NULL;
-    }
-
-    /* We'd like to call PyObject_Bytes here, but we need to check for an
-       integer argument before deferring to PyBytes_FromObject, something
-       PyObject_Bytes doesn't do. */
-    func = _PyObject_LookupSpecial(x, &PyId___bytes__);
-    if (func != NULL) {
-        new = PyObject_CallFunctionObjArgs(func, NULL);
-        Py_DECREF(func);
-        if (new == NULL)
-            return NULL;
-        if (!PyBytes_Check(new)) {
-            PyErr_Format(PyExc_TypeError,
-                         "__bytes__ returned non-bytes (type %.200s)",
-                         Py_TYPE(new)->tp_name);
-            Py_DECREF(new);
-            return NULL;
-        }
-        return new;
-    }
-    else if (PyErr_Occurred())
-        return NULL;
-
-    /* Is it an integer? */
-    size = PyNumber_AsSsize_t(x, PyExc_OverflowError);
-    if (size == -1 && PyErr_Occurred()) {
-        if (PyErr_ExceptionMatches(PyExc_OverflowError))
-            return NULL;
-        PyErr_Clear();
-    }
-    else if (size < 0) {
-        PyErr_SetString(PyExc_ValueError, "negative count");
-        return NULL;
-    }
-    else {
-        new = _PyBytes_FromSize(size, 1);
-        if (new == NULL)
-            return NULL;
-        return new;
-    }
-
-    return PyBytes_FromObject(x);
-}
-
-PyObject *
-PyBytes_FromObject(PyObject *x)
-{
-    PyObject *new, *it;
-    Py_ssize_t i, size;
-
-    if (x == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-
-    if (PyBytes_CheckExact(x)) {
-        Py_INCREF(x);
-        return x;
-    }
-
-    /* Use the modern buffer interface */
-    if (PyObject_CheckBuffer(x)) {
-        Py_buffer view;
-        if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0)
-            return NULL;
-        new = PyBytes_FromStringAndSize(NULL, view.len);
-        if (!new)
-            goto fail;
-        if (PyBuffer_ToContiguous(((PyBytesObject *)new)->ob_sval,
-                                  &view, view.len, 'C') < 0)
-            goto fail;
-        PyBuffer_Release(&view);
-        return new;
-      fail:
-        Py_XDECREF(new);
-        PyBuffer_Release(&view);
-        return NULL;
-    }
-    if (PyUnicode_Check(x)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "cannot convert unicode object to bytes");
-        return NULL;
-    }
-
-    if (PyList_CheckExact(x)) {
-        new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x));
-        if (new == NULL)
-            return NULL;
-        for (i = 0; i < Py_SIZE(x); i++) {
-            Py_ssize_t value = PyNumber_AsSsize_t(
-                PyList_GET_ITEM(x, i), PyExc_ValueError);
-            if (value == -1 && PyErr_Occurred()) {
-                Py_DECREF(new);
-                return NULL;
-            }
-            if (value < 0 || value >= 256) {
-                PyErr_SetString(PyExc_ValueError,
-                                "bytes must be in range(0, 256)");
-                Py_DECREF(new);
-                return NULL;
-            }
-            ((PyBytesObject *)new)->ob_sval[i] = (char) value;
-        }
-        return new;
-    }
-    if (PyTuple_CheckExact(x)) {
-        new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x));
-        if (new == NULL)
-            return NULL;
-        for (i = 0; i < Py_SIZE(x); i++) {
-            Py_ssize_t value = PyNumber_AsSsize_t(
-                PyTuple_GET_ITEM(x, i), PyExc_ValueError);
-            if (value == -1 && PyErr_Occurred()) {
-                Py_DECREF(new);
-                return NULL;
-            }
-            if (value < 0 || value >= 256) {
-                PyErr_SetString(PyExc_ValueError,
-                                "bytes must be in range(0, 256)");
-                Py_DECREF(new);
-                return NULL;
-            }
-            ((PyBytesObject *)new)->ob_sval[i] = (char) value;
-        }
-        return new;
-    }
-
-    /* For iterator version, create a string object and resize as needed */
-    size = PyObject_LengthHint(x, 64);
-    if (size == -1 && PyErr_Occurred())
-        return NULL;
-    /* Allocate an extra byte to prevent PyBytes_FromStringAndSize() from
-       returning a shared empty bytes string. This required because we
-       want to call _PyBytes_Resize() the returned object, which we can
-       only do on bytes objects with refcount == 1. */
-    if (size == 0)
-        size = 1;
-    new = PyBytes_FromStringAndSize(NULL, size);
-    if (new == NULL)
-        return NULL;
-    assert(Py_REFCNT(new) == 1);
-
-    /* Get the iterator */
-    it = PyObject_GetIter(x);
-    if (it == NULL)
-        goto error;
-
-    /* Run the iterator to exhaustion */
-    for (i = 0; ; i++) {
-        PyObject *item;
-        Py_ssize_t value;
-
-        /* Get the next item */
-        item = PyIter_Next(it);
-        if (item == NULL) {
-            if (PyErr_Occurred())
-                goto error;
-            break;
-        }
-
-        /* Interpret it as an int (__index__) */
-        value = PyNumber_AsSsize_t(item, PyExc_ValueError);
-        Py_DECREF(item);
-        if (value == -1 && PyErr_Occurred())
-            goto error;
-
-        /* Range check */
-        if (value < 0 || value >= 256) {
-            PyErr_SetString(PyExc_ValueError,
-                            "bytes must be in range(0, 256)");
-            goto error;
-        }
-
-        /* Append the byte */
-        if (i >= size) {
-            size = 2 * size + 1;
-            if (_PyBytes_Resize(&new, size) < 0)
-                goto error;
-        }
-        ((PyBytesObject *)new)->ob_sval[i] = (char) value;
-    }
-    _PyBytes_Resize(&new, i);
-
-    /* Clean up and return success */
-    Py_DECREF(it);
-    return new;
-
-  error:
-    Py_XDECREF(it);
-    Py_XDECREF(new);
-    return NULL;
-}
-
-static PyObject *
-str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *tmp, *pnew;
-    Py_ssize_t n;
-
-    assert(PyType_IsSubtype(type, &PyBytes_Type));
-    tmp = bytes_new(&PyBytes_Type, args, kwds);
-    if (tmp == NULL)
-        return NULL;
-    assert(PyBytes_CheckExact(tmp));
-    n = PyBytes_GET_SIZE(tmp);
-    pnew = type->tp_alloc(type, n);
-    if (pnew != NULL) {
-        Py_MEMCPY(PyBytes_AS_STRING(pnew),
-                  PyBytes_AS_STRING(tmp), n+1);
-        ((PyBytesObject *)pnew)->ob_shash =
-            ((PyBytesObject *)tmp)->ob_shash;
-    }
-    Py_DECREF(tmp);
-    return pnew;
-}
-
-PyDoc_STRVAR(bytes_doc,
-"bytes(iterable_of_ints) -> bytes\n\
-bytes(string, encoding[, errors]) -> bytes\n\
-bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\
-bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\
-bytes() -> empty bytes object\n\
-\n\
-Construct an immutable array of bytes from:\n\
-  - an iterable yielding integers in range(256)\n\
-  - a text string encoded using the specified encoding\n\
-  - any object implementing the buffer API.\n\
-  - an integer");
-
-static PyObject *bytes_iter(PyObject *seq);
-
-PyTypeObject PyBytes_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "bytes",
-    PyBytesObject_SIZE,
-    sizeof(char),
-    bytes_dealloc,                      /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)bytes_repr,                       /* tp_repr */
-    &bytes_as_number,                           /* tp_as_number */
-    &bytes_as_sequence,                         /* tp_as_sequence */
-    &bytes_as_mapping,                          /* tp_as_mapping */
-    (hashfunc)bytes_hash,                       /* tp_hash */
-    0,                                          /* tp_call */
-    bytes_str,                                  /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    &bytes_as_buffer,                           /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
-        Py_TPFLAGS_BYTES_SUBCLASS,              /* tp_flags */
-    bytes_doc,                                  /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    (richcmpfunc)bytes_richcompare,             /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    bytes_iter,                                 /* tp_iter */
-    0,                                          /* tp_iternext */
-    bytes_methods,                              /* tp_methods */
-    0,                                          /* tp_members */
-    0,                                          /* tp_getset */
-    &PyBaseObject_Type,                         /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    0,                                          /* tp_alloc */
-    bytes_new,                                  /* tp_new */
-    PyObject_Del,                               /* tp_free */
-};
-
-void
-PyBytes_Concat(PyObject **pv, PyObject *w)
-{
-    assert(pv != NULL);
-    if (*pv == NULL)
-        return;
-    if (w == NULL) {
-        Py_CLEAR(*pv);
-        return;
-    }
-
-    if (Py_REFCNT(*pv) == 1 && PyBytes_CheckExact(*pv)) {
-        /* Only one reference, so we can resize in place */
-        Py_ssize_t oldsize;
-        Py_buffer wb;
-
-        wb.len = -1;
-        if (PyObject_GetBuffer(w, &wb, PyBUF_SIMPLE) != 0) {
-            PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
-                         Py_TYPE(w)->tp_name, Py_TYPE(*pv)->tp_name);
-            Py_CLEAR(*pv);
-            return;
-        }
-
-        oldsize = PyBytes_GET_SIZE(*pv);
-        if (oldsize > PY_SSIZE_T_MAX - wb.len) {
-            PyErr_NoMemory();
-            goto error;
-        }
-        if (_PyBytes_Resize(pv, oldsize + wb.len) < 0)
-            goto error;
-
-        memcpy(PyBytes_AS_STRING(*pv) + oldsize, wb.buf, wb.len);
-        PyBuffer_Release(&wb);
-        return;
-
-      error:
-        PyBuffer_Release(&wb);
-        Py_CLEAR(*pv);
-        return;
-    }
-
-    else {
-        /* Multiple references, need to create new object */
-        PyObject *v;
-        v = bytes_concat(*pv, w);
-        Py_DECREF(*pv);
-        *pv = v;
-    }
-}
-
-void
-PyBytes_ConcatAndDel(PyObject **pv, PyObject *w)
-{
-    PyBytes_Concat(pv, w);
-    Py_XDECREF(w);
-}
-
-
-/* The following function breaks the notion that bytes are immutable:
-   it changes the size of a bytes object.  We get away with this only if there
-   is only one module referencing the object.  You can also think of it
-   as creating a new bytes object and destroying the old one, only
-   more efficiently.  In any case, don't use this if the bytes object may
-   already be known to some other part of the code...
-   Note that if there's not enough memory to resize the bytes object, the
-   original bytes object at *pv is deallocated, *pv is set to NULL, an "out of
-   memory" exception is set, and -1 is returned.  Else (on success) 0 is
-   returned, and the value in *pv may or may not be the same as on input.
-   As always, an extra byte is allocated for a trailing \0 byte (newsize
-   does *not* include that), and a trailing \0 byte is stored.
-*/
-
-int
-_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
-{
-    PyObject *v;
-    PyBytesObject *sv;
-    v = *pv;
-    if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
-        *pv = 0;
-        Py_DECREF(v);
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    /* XXX UNREF/NEWREF interface should be more symmetrical */
-    _Py_DEC_REFTOTAL;
-    _Py_ForgetReference(v);
-    *pv = (PyObject *)
-        PyObject_REALLOC(v, PyBytesObject_SIZE + newsize);
-    if (*pv == NULL) {
-        PyObject_Del(v);
-        PyErr_NoMemory();
-        return -1;
-    }
-    _Py_NewReference(*pv);
-    sv = (PyBytesObject *) *pv;
-    Py_SIZE(sv) = newsize;
-    sv->ob_sval[newsize] = '\0';
-    sv->ob_shash = -1;          /* invalidate cached hash value */
-    return 0;
-}
-
-void
-PyBytes_Fini(void)
-{
-    int i;
-    for (i = 0; i < UCHAR_MAX + 1; i++)
-        Py_CLEAR(characters[i]);
-    Py_CLEAR(nullstring);
-}
-
-/*********************** Bytes Iterator ****************************/
-
-typedef struct {
-    PyObject_HEAD
-    Py_ssize_t it_index;
-    PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */
-} striterobject;
-
-static void
-striter_dealloc(striterobject *it)
-{
-    _PyObject_GC_UNTRACK(it);
-    Py_XDECREF(it->it_seq);
-    PyObject_GC_Del(it);
-}
-
-static int
-striter_traverse(striterobject *it, visitproc visit, void *arg)
-{
-    Py_VISIT(it->it_seq);
-    return 0;
-}
-
-static PyObject *
-striter_next(striterobject *it)
-{
-    PyBytesObject *seq;
-    PyObject *item;
-
-    assert(it != NULL);
-    seq = it->it_seq;
-    if (seq == NULL)
-        return NULL;
-    assert(PyBytes_Check(seq));
-
-    if (it->it_index < PyBytes_GET_SIZE(seq)) {
-        item = PyLong_FromLong(
-            (unsigned char)seq->ob_sval[it->it_index]);
-        if (item != NULL)
-            ++it->it_index;
-        return item;
-    }
-
-    Py_DECREF(seq);
-    it->it_seq = NULL;
-    return NULL;
-}
-
-static PyObject *
-striter_len(striterobject *it)
-{
-    Py_ssize_t len = 0;
-    if (it->it_seq)
-        len = PyBytes_GET_SIZE(it->it_seq) - it->it_index;
-    return PyLong_FromSsize_t(len);
-}
-
-PyDoc_STRVAR(length_hint_doc,
-             "Private method returning an estimate of len(list(it)).");
-
-static PyObject *
-striter_reduce(striterobject *it)
-{
-    if (it->it_seq != NULL) {
-        return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
-                             it->it_seq, it->it_index);
-    } else {
-        PyObject *u = PyUnicode_FromUnicode(NULL, 0);
-        if (u == NULL)
-            return NULL;
-        return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
-    }
-}
-
-PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
-
-static PyObject *
-striter_setstate(striterobject *it, PyObject *state)
-{
-    Py_ssize_t index = PyLong_AsSsize_t(state);
-    if (index == -1 && PyErr_Occurred())
-        return NULL;
-    if (it->it_seq != NULL) {
-        if (index < 0)
-            index = 0;
-        else if (index > PyBytes_GET_SIZE(it->it_seq))
-            index = PyBytes_GET_SIZE(it->it_seq); /* iterator exhausted */
-        it->it_index = index;
-    }
-    Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
-
-static PyMethodDef striter_methods[] = {
-    {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS,
-     length_hint_doc},
-    {"__reduce__",      (PyCFunction)striter_reduce, METH_NOARGS,
-     reduce_doc},
-    {"__setstate__",    (PyCFunction)striter_setstate, METH_O,
-     setstate_doc},
-    {NULL,              NULL}           /* sentinel */
-};
-
-PyTypeObject PyBytesIter_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "bytes_iterator",                           /* tp_name */
-    sizeof(striterobject),                      /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)striter_dealloc,                /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)striter_traverse,     /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    PyObject_SelfIter,                          /* tp_iter */
-    (iternextfunc)striter_next,                 /* tp_iternext */
-    striter_methods,                            /* tp_methods */
-    0,
-};
-
-static PyObject *
-bytes_iter(PyObject *seq)
-{
-    striterobject *it;
-
-    if (!PyBytes_Check(seq)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    it = PyObject_GC_New(striterobject, &PyBytesIter_Type);
-    if (it == NULL)
-        return NULL;
-    it->it_index = 0;
-    Py_INCREF(seq);
-    it->it_seq = (PyBytesObject *)seq;
-    _PyObject_GC_TRACK(it);
-    return (PyObject *)it;
-}
+/*[clinic end generated code: output=dfe5c9a317b99f49 input=a9049054013a1b77]*/
diff --git a/Objects/dictobject.c b/Objects/clinic/dictobject.c.h
copy from Objects/dictobject.c
copy to Objects/clinic/dictobject.c.h
--- a/Objects/dictobject.c
+++ b/Objects/clinic/dictobject.c.h
@@ -1,1760 +1,5 @@
-
-/* Dictionary object implementation using a hash table */
-
-/* The distribution includes a separate file, Objects/dictnotes.txt,
-   describing explorations into dictionary design and optimization.
-   It covers typical dictionary use patterns, the parameters for
-   tuning dictionaries, and several ideas for possible optimizations.
-*/
-
-
-/*
-There are four kinds of slots in the table:
-
-1. Unused.  me_key == me_value == NULL
-   Does not hold an active (key, value) pair now and never did.  Unused can
-   transition to Active upon key insertion.  This is the only case in which
-   me_key is NULL, and is each slot's initial state.
-
-2. Active.  me_key != NULL and me_key != dummy and me_value != NULL
-   Holds an active (key, value) pair.  Active can transition to Dummy or
-   Pending upon key deletion (for combined and split tables respectively).
-   This is the only case in which me_value != NULL.
-
-3. Dummy.  me_key == dummy and me_value == NULL
-   Previously held an active (key, value) pair, but that was deleted and an
-   active pair has not yet overwritten the slot.  Dummy can transition to
-   Active upon key insertion.  Dummy slots cannot be made Unused again
-   (cannot have me_key set to NULL), else the probe sequence in case of
-   collision would have no way to know they were once active.
-
-4. Pending. Not yet inserted or deleted from a split-table.
-   key != NULL, key != dummy and value == NULL
-
-The DictObject can be in one of two forms.
-Either:
-  A combined table:
-    ma_values == NULL, dk_refcnt == 1.
-    Values are stored in the me_value field of the PyDictKeysObject.
-    Slot kind 4 is not allowed i.e.
-        key != NULL, key != dummy and value == NULL is illegal.
-Or:
-  A split table:
-    ma_values != NULL, dk_refcnt >= 1
-    Values are stored in the ma_values array.
-    Only string (unicode) keys are allowed, no <dummy> keys are present.
-
-Note: .popitem() abuses the me_hash field of an Unused or Dummy slot to
-hold a search finger.  The me_hash field of Unused or Dummy slots has no
-meaning otherwise. As a consequence of this popitem always converts the dict
-to the combined-table form.
-*/
-
-/* PyDict_MINSIZE_SPLIT is the minimum size of a split dictionary.
- * It must be a power of 2, and at least 4.
- * Resizing of split dictionaries is very rare, so the saving memory is more
- * important than the cost of resizing.
- */
-#define PyDict_MINSIZE_SPLIT 4
-
-/* PyDict_MINSIZE_COMBINED is the starting size for any new, non-split dict.
- * 8 allows dicts with no more than 5 active entries; experiments suggested
- * this suffices for the majority of dicts (consisting mostly of usually-small
- * dicts created to pass keyword arguments).
- * Making this 8, rather than 4 reduces the number of resizes for most
- * dictionaries, without any significant extra memory use.
- */
-#define PyDict_MINSIZE_COMBINED 8
-
-#include "Python.h"
-#include "stringlib/eq.h"
-
 /*[clinic input]
-class dict "PyDictObject *" "&PyDict_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
-
-typedef struct {
-    /* Cached hash code of me_key. */
-    Py_hash_t me_hash;
-    PyObject *me_key;
-    PyObject *me_value; /* This field is only meaningful for combined tables */
-} PyDictKeyEntry;
-
-typedef PyDictKeyEntry *(*dict_lookup_func)
-(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr);
-
-struct _dictkeysobject {
-    Py_ssize_t dk_refcnt;
-    Py_ssize_t dk_size;
-    dict_lookup_func dk_lookup;
-    Py_ssize_t dk_usable;
-    PyDictKeyEntry dk_entries[1];
-};
-
-
-/*
-To ensure the lookup algorithm terminates, there must be at least one Unused
-slot (NULL key) in the table.
-To avoid slowing down lookups on a near-full table, we resize the table when
-it's USABLE_FRACTION (currently two-thirds) full.
-*/
-
-#define PERTURB_SHIFT 5
-
-/*
-Major subtleties ahead:  Most hash schemes depend on having a "good" hash
-function, in the sense of simulating randomness.  Python doesn't:  its most
-important hash functions (for strings and ints) are very regular in common
-cases:
-
-  >>> map(hash, (0, 1, 2, 3))
-  [0, 1, 2, 3]
-  >>> map(hash, ("namea", "nameb", "namec", "named"))
-  [-1658398457, -1658398460, -1658398459, -1658398462]
-  >>>
-
-This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
-the low-order i bits as the initial table index is extremely fast, and there
-are no collisions at all for dicts indexed by a contiguous range of ints.
-The same is approximately true when keys are "consecutive" strings.  So this
-gives better-than-random behavior in common cases, and that's very desirable.
-
-OTOH, when collisions occur, the tendency to fill contiguous slices of the
-hash table makes a good collision resolution strategy crucial.  Taking only
-the last i bits of the hash code is also vulnerable:  for example, consider
-the list [i << 16 for i in range(20000)] as a set of keys.  Since ints are
-their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
- of every hash code are all 0:  they *all* map to the same table index.
-
-But catering to unusual cases should not slow the usual ones, so we just take
-the last i bits anyway.  It's up to collision resolution to do the rest.  If
-we *usually* find the key we're looking for on the first try (and, it turns
-out, we usually do -- the table load factor is kept under 2/3, so the odds
-are solidly in our favor), then it makes best sense to keep the initial index
-computation dirt cheap.
-
-The first half of collision resolution is to visit table indices via this
-recurrence:
-
-    j = ((5*j) + 1) mod 2**i
-
-For any initial j in range(2**i), repeating that 2**i times generates each
-int in range(2**i) exactly once (see any text on random-number generation for
-proof).  By itself, this doesn't help much:  like linear probing (setting
-j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
-order.  This would be bad, except that's not the only thing we do, and it's
-actually *good* in the common cases where hash keys are consecutive.  In an
-example that's really too small to make this entirely clear, for a table of
-size 2**3 the order of indices is:
-
-    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
-
-If two things come in at index 5, the first place we look after is index 2,
-not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
-Linear probing is deadly in this case because there the fixed probe order
-is the *same* as the order consecutive keys are likely to arrive.  But it's
-extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
-and certain that consecutive hash codes do not.
-
-The other half of the strategy is to get the other bits of the hash code
-into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
-full hash code, and changing the recurrence to:
-
-    j = (5*j) + 1 + perturb;
-    perturb >>= PERTURB_SHIFT;
-    use j % 2**i as the next table index;
-
-Now the probe sequence depends (eventually) on every bit in the hash code,
-and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
-because it quickly magnifies small differences in the bits that didn't affect
-the initial index.  Note that because perturb is unsigned, if the recurrence
-is executed often enough perturb eventually becomes and remains 0.  At that
-point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
-that's certain to find an empty slot eventually (since it generates every int
-in range(2**i), and we make sure there's always at least one empty slot).
-
-Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
-small so that the high bits of the hash code continue to affect the probe
-sequence across iterations; but you want it large so that in really bad cases
-the high-order hash bits have an effect on early iterations.  5 was "the
-best" in minimizing total collisions across experiments Tim Peters ran (on
-both normal and pathological cases), but 4 and 6 weren't significantly worse.
-
-Historical: Reimer Behrends contributed the idea of using a polynomial-based
-approach, using repeated multiplication by x in GF(2**n) where an irreducible
-polynomial for each table size was chosen such that x was a primitive root.
-Christian Tismer later extended that to use division by x instead, as an
-efficient way to get the high bits of the hash code into play.  This scheme
-also gave excellent collision statistics, but was more expensive:  two
-if-tests were required inside the loop; computing "the next" index took about
-the same number of operations but without as much potential parallelism
-(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
-above, and then shifting perturb can be done while the table index is being
-masked); and the PyDictObject struct required a member to hold the table's
-polynomial.  In Tim's experiments the current scheme ran faster, produced
-equally good collision statistics, needed less code & used less memory.
-
-*/
-
-/* Object used as dummy key to fill deleted entries
- * This could be any unique object,
- * use a custom type in order to minimise coupling.
-*/
-static PyObject _dummy_struct;
-
-#define dummy (&_dummy_struct)
-
-#ifdef Py_REF_DEBUG
-PyObject *
-_PyDict_Dummy(void)
-{
-    return dummy;
-}
-#endif
-
-/* forward declarations */
-static PyDictKeyEntry *lookdict(PyDictObject *mp, PyObject *key,
-                                Py_hash_t hash, PyObject ***value_addr);
-static PyDictKeyEntry *lookdict_unicode(PyDictObject *mp, PyObject *key,
-                                        Py_hash_t hash, PyObject ***value_addr);
-static PyDictKeyEntry *
-lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
-                         Py_hash_t hash, PyObject ***value_addr);
-static PyDictKeyEntry *lookdict_split(PyDictObject *mp, PyObject *key,
-                                      Py_hash_t hash, PyObject ***value_addr);
-
-static int dictresize(PyDictObject *mp, Py_ssize_t minused);
-
-/* Dictionary reuse scheme to save calls to malloc, free, and memset */
-#ifndef PyDict_MAXFREELIST
-#define PyDict_MAXFREELIST 80
-#endif
-static PyDictObject *free_list[PyDict_MAXFREELIST];
-static int numfree = 0;
-
-int
-PyDict_ClearFreeList(void)
-{
-    PyDictObject *op;
-    int ret = numfree;
-    while (numfree) {
-        op = free_list[--numfree];
-        assert(PyDict_CheckExact(op));
-        PyObject_GC_Del(op);
-    }
-    return ret;
-}
-
-/* Print summary info about the state of the optimized allocator */
-void
-_PyDict_DebugMallocStats(FILE *out)
-{
-    _PyDebugAllocatorStats(out,
-                           "free PyDictObject", numfree, sizeof(PyDictObject));
-}
-
-
-void
-PyDict_Fini(void)
-{
-    PyDict_ClearFreeList();
-}
-
-#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
-#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
-
-#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
-#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
-#define DK_SIZE(dk) ((dk)->dk_size)
-#define DK_MASK(dk) (((dk)->dk_size)-1)
-#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
-
-/* USABLE_FRACTION is the maximum dictionary load.
- * Currently set to (2n+1)/3. Increasing this ratio makes dictionaries more
- * dense resulting in more collisions.  Decreasing it improves sparseness
- * at the expense of spreading entries over more cache lines and at the
- * cost of total memory consumed.
- *
- * USABLE_FRACTION must obey the following:
- *     (0 < USABLE_FRACTION(n) < n) for all n >= 2
- *
- * USABLE_FRACTION should be very quick to calculate.
- * Fractions around 5/8 to 2/3 seem to work well in practice.
- */
-
-/* Use (2n+1)/3 rather than 2n+3 because: it makes no difference for
- * combined tables (the two fractions round to the same number n < ),
- * but 2*4/3 is 2 whereas (2*4+1)/3 is 3 which potentially saves quite
- * a lot of space for small, split tables */
-#define USABLE_FRACTION(n) ((((n) << 1)+1)/3)
-
-/* Alternative fraction that is otherwise close enough to (2n+1)/3 to make
- * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
- * 32 * 2/3 = 21, 32 * 5/8 = 20.
- * Its advantage is that it is faster to compute on machines with slow division.
- * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
-*/
-
-/* GROWTH_RATE. Growth rate upon hitting maximum load.
- * Currently set to used*2 + capacity/2.
- * This means that dicts double in size when growing without deletions,
- * but have more head room when the number of deletions is on a par with the
- * number of insertions.
- * Raising this to used*4 doubles memory consumption depending on the size of
- * the dictionary, but results in half the number of resizes, less effort to
- * resize.
- * GROWTH_RATE was set to used*4 up to version 3.2.
- * GROWTH_RATE was set to used*2 in version 3.3.0
- */
-#define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
-
-#define ENSURE_ALLOWS_DELETIONS(d) \
-    if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
-        (d)->ma_keys->dk_lookup = lookdict_unicode; \
-    }
-
-/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
- * (which cannot fail and thus can do no allocation).
- */
-static PyDictKeysObject empty_keys_struct = {
-        2, /* dk_refcnt 1 for this struct, 1 for dummy_struct */
-        1, /* dk_size */
-        lookdict_split, /* dk_lookup */
-        0, /* dk_usable (immutable) */
-        {
-            { 0, 0, 0 } /* dk_entries (empty) */
-        }
-};
-
-static PyObject *empty_values[1] = { NULL };
-
-#define Py_EMPTY_KEYS &empty_keys_struct
-
-static PyDictKeysObject *new_keys_object(Py_ssize_t size)
-{
-    PyDictKeysObject *dk;
-    Py_ssize_t i;
-    PyDictKeyEntry *ep0;
-
-    assert(size >= PyDict_MINSIZE_SPLIT);
-    assert(IS_POWER_OF_2(size));
-    dk = PyMem_MALLOC(sizeof(PyDictKeysObject) +
-                      sizeof(PyDictKeyEntry) * (size-1));
-    if (dk == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    DK_DEBUG_INCREF dk->dk_refcnt = 1;
-    dk->dk_size = size;
-    dk->dk_usable = USABLE_FRACTION(size);
-    ep0 = &dk->dk_entries[0];
-    /* Hash value of slot 0 is used by popitem, so it must be initialized */
-    ep0->me_hash = 0;
-    for (i = 0; i < size; i++) {
-        ep0[i].me_key = NULL;
-        ep0[i].me_value = NULL;
-    }
-    dk->dk_lookup = lookdict_unicode_nodummy;
-    return dk;
-}
-
-static void
-free_keys_object(PyDictKeysObject *keys)
-{
-    PyDictKeyEntry *entries = &keys->dk_entries[0];
-    Py_ssize_t i, n;
-    for (i = 0, n = DK_SIZE(keys); i < n; i++) {
-        Py_XDECREF(entries[i].me_key);
-        Py_XDECREF(entries[i].me_value);
-    }
-    PyMem_FREE(keys);
-}
-
-#define new_values(size) PyMem_NEW(PyObject *, size)
-
-#define free_values(values) PyMem_FREE(values)
-
-/* Consumes a reference to the keys object */
-static PyObject *
-new_dict(PyDictKeysObject *keys, PyObject **values)
-{
-    PyDictObject *mp;
-    assert(keys != NULL);
-    if (numfree) {
-        mp = free_list[--numfree];
-        assert (mp != NULL);
-        assert (Py_TYPE(mp) == &PyDict_Type);
-        _Py_NewReference((PyObject *)mp);
-    }
-    else {
-        mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
-        if (mp == NULL) {
-            DK_DECREF(keys);
-            free_values(values);
-            return NULL;
-        }
-    }
-    mp->ma_keys = keys;
-    mp->ma_values = values;
-    mp->ma_used = 0;
-    return (PyObject *)mp;
-}
-
-/* Consumes a reference to the keys object */
-static PyObject *
-new_dict_with_shared_keys(PyDictKeysObject *keys)
-{
-    PyObject **values;
-    Py_ssize_t i, size;
-
-    size = DK_SIZE(keys);
-    values = new_values(size);
-    if (values == NULL) {
-        DK_DECREF(keys);
-        return PyErr_NoMemory();
-    }
-    for (i = 0; i < size; i++) {
-        values[i] = NULL;
-    }
-    return new_dict(keys, values);
-}
-
-PyObject *
-PyDict_New(void)
-{
-    PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE_COMBINED);
-    if (keys == NULL)
-        return NULL;
-    return new_dict(keys, NULL);
-}
-
-/*
-The basic lookup function used by all operations.
-This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
-Open addressing is preferred over chaining since the link overhead for
-chaining would be substantial (100% with typical malloc overhead).
-
-The initial probe index is computed as hash mod the table size. Subsequent
-probe indices are computed as explained earlier.
-
-All arithmetic on hash should ignore overflow.
-
-The details in this version are due to Tim Peters, building on many past
-contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
-Christian Tismer.
-
-lookdict() is general-purpose, and may return NULL if (and only if) a
-comparison raises an exception (this was new in Python 2.5).
-lookdict_unicode() below is specialized to string keys, comparison of which can
-never raise an exception; that function can never return NULL.
-lookdict_unicode_nodummy is further specialized for string keys that cannot be
-the <dummy> value.
-For both, when the key isn't found a PyDictEntry* is returned
-where the key would have been found, *value_addr points to the matching value
-slot.
-*/
-static PyDictKeyEntry *
-lookdict(PyDictObject *mp, PyObject *key,
-         Py_hash_t hash, PyObject ***value_addr)
-{
-    size_t i;
-    size_t perturb;
-    PyDictKeyEntry *freeslot;
-    size_t mask;
-    PyDictKeyEntry *ep0;
-    PyDictKeyEntry *ep;
-    int cmp;
-    PyObject *startkey;
-
-top:
-    mask = DK_MASK(mp->ma_keys);
-    ep0 = &mp->ma_keys->dk_entries[0];
-    i = (size_t)hash & mask;
-    ep = &ep0[i];
-    if (ep->me_key == NULL || ep->me_key == key) {
-        *value_addr = &ep->me_value;
-        return ep;
-    }
-    if (ep->me_key == dummy)
-        freeslot = ep;
-    else {
-        if (ep->me_hash == hash) {
-            startkey = ep->me_key;
-            Py_INCREF(startkey);
-            cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
-            Py_DECREF(startkey);
-            if (cmp < 0)
-                return NULL;
-            if (ep0 == mp->ma_keys->dk_entries && ep->me_key == startkey) {
-                if (cmp > 0) {
-                    *value_addr = &ep->me_value;
-                    return ep;
-                }
-            }
-            else {
-                /* The dict was mutated, restart */
-                goto top;
-            }
-        }
-        freeslot = NULL;
-    }
-
-    /* In the loop, me_key == dummy is by far (factor of 100s) the
-       least likely outcome, so test for that last. */
-    for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
-        i = (i << 2) + i + perturb + 1;
-        ep = &ep0[i & mask];
-        if (ep->me_key == NULL) {
-            if (freeslot == NULL) {
-                *value_addr = &ep->me_value;
-                return ep;
-            } else {
-                *value_addr = &freeslot->me_value;
-                return freeslot;
-            }
-        }
-        if (ep->me_key == key) {
-            *value_addr = &ep->me_value;
-            return ep;
-        }
-        if (ep->me_hash == hash && ep->me_key != dummy) {
-            startkey = ep->me_key;
-            Py_INCREF(startkey);
-            cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
-            Py_DECREF(startkey);
-            if (cmp < 0) {
-                *value_addr = NULL;
-                return NULL;
-            }
-            if (ep0 == mp->ma_keys->dk_entries && ep->me_key == startkey) {
-                if (cmp > 0) {
-                    *value_addr = &ep->me_value;
-                    return ep;
-                }
-            }
-            else {
-                /* The dict was mutated, restart */
-                goto top;
-            }
-        }
-        else if (ep->me_key == dummy && freeslot == NULL)
-            freeslot = ep;
-    }
-    assert(0);          /* NOT REACHED */
-    return 0;
-}
-
-/* Specialized version for string-only keys */
-static PyDictKeyEntry *
-lookdict_unicode(PyDictObject *mp, PyObject *key,
-                 Py_hash_t hash, PyObject ***value_addr)
-{
-    size_t i;
-    size_t perturb;
-    PyDictKeyEntry *freeslot;
-    size_t mask = DK_MASK(mp->ma_keys);
-    PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
-    PyDictKeyEntry *ep;
-
-    /* Make sure this function doesn't have to handle non-unicode keys,
-       including subclasses of str; e.g., one reason to subclass
-       unicodes is to override __eq__, and for speed we don't cater to
-       that here. */
-    if (!PyUnicode_CheckExact(key)) {
-        mp->ma_keys->dk_lookup = lookdict;
-        return lookdict(mp, key, hash, value_addr);
-    }
-    i = (size_t)hash & mask;
-    ep = &ep0[i];
-    if (ep->me_key == NULL || ep->me_key == key) {
-        *value_addr = &ep->me_value;
-        return ep;
-    }
-    if (ep->me_key == dummy)
-        freeslot = ep;
-    else {
-        if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) {
-            *value_addr = &ep->me_value;
-            return ep;
-        }
-        freeslot = NULL;
-    }
-
-    /* In the loop, me_key == dummy is by far (factor of 100s) the
-       least likely outcome, so test for that last. */
-    for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
-        i = (i << 2) + i + perturb + 1;
-        ep = &ep0[i & mask];
-        if (ep->me_key == NULL) {
-            if (freeslot == NULL) {
-                *value_addr = &ep->me_value;
-                return ep;
-            } else {
-                *value_addr = &freeslot->me_value;
-                return freeslot;
-            }
-        }
-        if (ep->me_key == key
-            || (ep->me_hash == hash
-            && ep->me_key != dummy
-            && unicode_eq(ep->me_key, key))) {
-            *value_addr = &ep->me_value;
-            return ep;
-        }
-        if (ep->me_key == dummy && freeslot == NULL)
-            freeslot = ep;
-    }
-    assert(0);          /* NOT REACHED */
-    return 0;
-}
-
-/* Faster version of lookdict_unicode when it is known that no <dummy> keys
- * will be present. */
-static PyDictKeyEntry *
-lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
-                         Py_hash_t hash, PyObject ***value_addr)
-{
-    size_t i;
-    size_t perturb;
-    size_t mask = DK_MASK(mp->ma_keys);
-    PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
-    PyDictKeyEntry *ep;
-
-    /* Make sure this function doesn't have to handle non-unicode keys,
-       including subclasses of str; e.g., one reason to subclass
-       unicodes is to override __eq__, and for speed we don't cater to
-       that here. */
-    if (!PyUnicode_CheckExact(key)) {
-        mp->ma_keys->dk_lookup = lookdict;
-        return lookdict(mp, key, hash, value_addr);
-    }
-    i = (size_t)hash & mask;
-    ep = &ep0[i];
-    assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
-    if (ep->me_key == NULL || ep->me_key == key ||
-        (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
-        *value_addr = &ep->me_value;
-        return ep;
-    }
-    for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
-        i = (i << 2) + i + perturb + 1;
-        ep = &ep0[i & mask];
-        assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
-        if (ep->me_key == NULL || ep->me_key == key ||
-            (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
-            *value_addr = &ep->me_value;
-            return ep;
-        }
-    }
-    assert(0);          /* NOT REACHED */
-    return 0;
-}
-
-/* Version of lookdict for split tables.
- * All split tables and only split tables use this lookup function.
- * Split tables only contain unicode keys and no dummy keys,
- * so algorithm is the same as lookdict_unicode_nodummy.
- */
-static PyDictKeyEntry *
-lookdict_split(PyDictObject *mp, PyObject *key,
-               Py_hash_t hash, PyObject ***value_addr)
-{
-    size_t i;
-    size_t perturb;
-    size_t mask = DK_MASK(mp->ma_keys);
-    PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
-    PyDictKeyEntry *ep;
-
-    if (!PyUnicode_CheckExact(key)) {
-        ep = lookdict(mp, key, hash, value_addr);
-        /* lookdict expects a combined-table, so fix value_addr */
-        i = ep - ep0;
-        *value_addr = &mp->ma_values[i];
-        return ep;
-    }
-    i = (size_t)hash & mask;
-    ep = &ep0[i];
-    assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
-    if (ep->me_key == NULL || ep->me_key == key ||
-        (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
-        *value_addr = &mp->ma_values[i];
-        return ep;
-    }
-    for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
-        i = (i << 2) + i + perturb + 1;
-        ep = &ep0[i & mask];
-        assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
-        if (ep->me_key == NULL || ep->me_key == key ||
-            (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
-            *value_addr = &mp->ma_values[i & mask];
-            return ep;
-        }
-    }
-    assert(0);          /* NOT REACHED */
-    return 0;
-}
-
-int
-_PyDict_HasOnlyStringKeys(PyObject *dict)
-{
-    Py_ssize_t pos = 0;
-    PyObject *key, *value;
-    assert(PyDict_Check(dict));
-    /* Shortcut */
-    if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
-        return 1;
-    while (PyDict_Next(dict, &pos, &key, &value))
-        if (!PyUnicode_Check(key))
-            return 0;
-    return 1;
-}
-
-#define MAINTAIN_TRACKING(mp, key, value) \
-    do { \
-        if (!_PyObject_GC_IS_TRACKED(mp)) { \
-            if (_PyObject_GC_MAY_BE_TRACKED(key) || \
-                _PyObject_GC_MAY_BE_TRACKED(value)) { \
-                _PyObject_GC_TRACK(mp); \
-            } \
-        } \
-    } while(0)
-
-void
-_PyDict_MaybeUntrack(PyObject *op)
-{
-    PyDictObject *mp;
-    PyObject *value;
-    Py_ssize_t i, size;
-
-    if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
-        return;
-
-    mp = (PyDictObject *) op;
-    size = DK_SIZE(mp->ma_keys);
-    if (_PyDict_HasSplitTable(mp)) {
-        for (i = 0; i < size; i++) {
-            if ((value = mp->ma_values[i]) == NULL)
-                continue;
-            if (_PyObject_GC_MAY_BE_TRACKED(value)) {
-                assert(!_PyObject_GC_MAY_BE_TRACKED(
-                    mp->ma_keys->dk_entries[i].me_key));
-                return;
-            }
-        }
-    }
-    else {
-        PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
-        for (i = 0; i < size; i++) {
-            if ((value = ep0[i].me_value) == NULL)
-                continue;
-            if (_PyObject_GC_MAY_BE_TRACKED(value) ||
-                _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
-                return;
-        }
-    }
-    _PyObject_GC_UNTRACK(op);
-}
-
-/* Internal function to find slot for an item from its hash
- * when it is known that the key is not present in the dict.
- */
-static PyDictKeyEntry *
-find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
-                PyObject ***value_addr)
-{
-    size_t i;
-    size_t perturb;
-    size_t mask = DK_MASK(mp->ma_keys);
-    PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
-    PyDictKeyEntry *ep;
-
-    assert(key != NULL);
-    if (!PyUnicode_CheckExact(key))
-        mp->ma_keys->dk_lookup = lookdict;
-    i = hash & mask;
-    ep = &ep0[i];
-    for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
-        i = (i << 2) + i + perturb + 1;
-        ep = &ep0[i & mask];
-    }
-    assert(ep->me_value == NULL);
-    if (mp->ma_values)
-        *value_addr = &mp->ma_values[i & mask];
-    else
-        *value_addr = &ep->me_value;
-    return ep;
-}
-
-static int
-insertion_resize(PyDictObject *mp)
-{
-    return dictresize(mp, GROWTH_RATE(mp));
-}
-
-/*
-Internal routine to insert a new item into the table.
-Used both by the internal resize routine and by the public insert routine.
-Returns -1 if an error occurred, or 0 on success.
-*/
-static int
-insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
-{
-    PyObject *old_value;
-    PyObject **value_addr;
-    PyDictKeyEntry *ep;
-    assert(key != dummy);
-
-    if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
-        if (insertion_resize(mp) < 0)
-            return -1;
-    }
-
-    ep = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr);
-    if (ep == NULL) {
-        return -1;
-    }
-    assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
-    Py_INCREF(value);
-    MAINTAIN_TRACKING(mp, key, value);
-    old_value = *value_addr;
-    if (old_value != NULL) {
-        assert(ep->me_key != NULL && ep->me_key != dummy);
-        *value_addr = value;
-        Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
-    }
-    else {
-        if (ep->me_key == NULL) {
-            Py_INCREF(key);
-            if (mp->ma_keys->dk_usable <= 0) {
-                /* Need to resize. */
-                if (insertion_resize(mp) < 0) {
-                    Py_DECREF(key);
-                    Py_DECREF(value);
-                    return -1;
-                }
-                ep = find_empty_slot(mp, key, hash, &value_addr);
-            }
-            mp->ma_keys->dk_usable--;
-            assert(mp->ma_keys->dk_usable >= 0);
-            ep->me_key = key;
-            ep->me_hash = hash;
-        }
-        else {
-            if (ep->me_key == dummy) {
-                Py_INCREF(key);
-                ep->me_key = key;
-                ep->me_hash = hash;
-                Py_DECREF(dummy);
-            } else {
-                assert(_PyDict_HasSplitTable(mp));
-            }
-        }
-        mp->ma_used++;
-        *value_addr = value;
-        assert(ep->me_key != NULL && ep->me_key != dummy);
-    }
-    return 0;
-}
-
-/*
-Internal routine used by dictresize() to insert an item which is
-known to be absent from the dict.  This routine also assumes that
-the dict contains no deleted entries.  Besides the performance benefit,
-using insertdict() in dictresize() is dangerous (SF bug #1456209).
-Note that no refcounts are changed by this routine; if needed, the caller
-is responsible for incref'ing `key` and `value`.
-Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
-must set them correctly
-*/
-static void
-insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
-                 PyObject *value)
-{
-    size_t i;
-    size_t perturb;
-    PyDictKeysObject *k = mp->ma_keys;
-    size_t mask = (size_t)DK_SIZE(k)-1;
-    PyDictKeyEntry *ep0 = &k->dk_entries[0];
-    PyDictKeyEntry *ep;
-
-    assert(k->dk_lookup != NULL);
-    assert(value != NULL);
-    assert(key != NULL);
-    assert(key != dummy);
-    assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
-    i = hash & mask;
-    ep = &ep0[i];
-    for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
-        i = (i << 2) + i + perturb + 1;
-        ep = &ep0[i & mask];
-    }
-    assert(ep->me_value == NULL);
-    ep->me_key = key;
-    ep->me_hash = hash;
-    ep->me_value = value;
-}
-
-/*
-Restructure the table by allocating a new table and reinserting all
-items again.  When entries have been deleted, the new table may
-actually be smaller than the old one.
-If a table is split (its keys and hashes are shared, its values are not),
-then the values are temporarily copied into the table, it is resized as
-a combined table, then the me_value slots in the old table are NULLed out.
-After resizing a table is always combined,
-but can be resplit by make_keys_shared().
-*/
-static int
-dictresize(PyDictObject *mp, Py_ssize_t minused)
-{
-    Py_ssize_t newsize;
-    PyDictKeysObject *oldkeys;
-    PyObject **oldvalues;
-    Py_ssize_t i, oldsize;
-
-/* Find the smallest table size > minused. */
-    for (newsize = PyDict_MINSIZE_COMBINED;
-         newsize <= minused && newsize > 0;
-         newsize <<= 1)
-        ;
-    if (newsize <= 0) {
-        PyErr_NoMemory();
-        return -1;
-    }
-    oldkeys = mp->ma_keys;
-    oldvalues = mp->ma_values;
-    /* Allocate a new table. */
-    mp->ma_keys = new_keys_object(newsize);
-    if (mp->ma_keys == NULL) {
-        mp->ma_keys = oldkeys;
-        return -1;
-    }
-    if (oldkeys->dk_lookup == lookdict)
-        mp->ma_keys->dk_lookup = lookdict;
-    oldsize = DK_SIZE(oldkeys);
-    mp->ma_values = NULL;
-    /* If empty then nothing to copy so just return */
-    if (oldsize == 1) {
-        assert(oldkeys == Py_EMPTY_KEYS);
-        DK_DECREF(oldkeys);
-        return 0;
-    }
-    /* Main loop below assumes we can transfer refcount to new keys
-     * and that value is stored in me_value.
-     * Increment ref-counts and copy values here to compensate
-     * This (resizing a split table) should be relatively rare */
-    if (oldvalues != NULL) {
-        for (i = 0; i < oldsize; i++) {
-            if (oldvalues[i] != NULL) {
-                Py_INCREF(oldkeys->dk_entries[i].me_key);
-                oldkeys->dk_entries[i].me_value = oldvalues[i];
-            }
-        }
-    }
-    /* Main loop */
-    for (i = 0; i < oldsize; i++) {
-        PyDictKeyEntry *ep = &oldkeys->dk_entries[i];
-        if (ep->me_value != NULL) {
-            assert(ep->me_key != dummy);
-            insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
-        }
-    }
-    mp->ma_keys->dk_usable -= mp->ma_used;
-    if (oldvalues != NULL) {
-        /* NULL out me_value slot in oldkeys, in case it was shared */
-        for (i = 0; i < oldsize; i++)
-            oldkeys->dk_entries[i].me_value = NULL;
-        assert(oldvalues != empty_values);
-        free_values(oldvalues);
-        DK_DECREF(oldkeys);
-    }
-    else {
-        assert(oldkeys->dk_lookup != lookdict_split);
-        if (oldkeys->dk_lookup != lookdict_unicode_nodummy) {
-            PyDictKeyEntry *ep0 = &oldkeys->dk_entries[0];
-            for (i = 0; i < oldsize; i++) {
-                if (ep0[i].me_key == dummy)
-                    Py_DECREF(dummy);
-            }
-        }
-        assert(oldkeys->dk_refcnt == 1);
-        DK_DEBUG_DECREF PyMem_FREE(oldkeys);
-    }
-    return 0;
-}
-
-/* Returns NULL if unable to split table.
- * A NULL return does not necessarily indicate an error */
-static PyDictKeysObject *
-make_keys_shared(PyObject *op)
-{
-    Py_ssize_t i;
-    Py_ssize_t size;
-    PyDictObject *mp = (PyDictObject *)op;
-
-    if (!PyDict_CheckExact(op))
-        return NULL;
-    if (!_PyDict_HasSplitTable(mp)) {
-        PyDictKeyEntry *ep0;
-        PyObject **values;
-        assert(mp->ma_keys->dk_refcnt == 1);
-        if (mp->ma_keys->dk_lookup == lookdict) {
-            return NULL;
-        }
-        else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
-            /* Remove dummy keys */
-            if (dictresize(mp, DK_SIZE(mp->ma_keys)))
-                return NULL;
-        }
-        assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
-        /* Copy values into a new array */
-        ep0 = &mp->ma_keys->dk_entries[0];
-        size = DK_SIZE(mp->ma_keys);
-        values = new_values(size);
-        if (values == NULL) {
-            PyErr_SetString(PyExc_MemoryError,
-                "Not enough memory to allocate new values array");
-            return NULL;
-        }
-        for (i = 0; i < size; i++) {
-            values[i] = ep0[i].me_value;
-            ep0[i].me_value = NULL;
-        }
-        mp->ma_keys->dk_lookup = lookdict_split;
-        mp->ma_values = values;
-    }
-    DK_INCREF(mp->ma_keys);
-    return mp->ma_keys;
-}
-
-PyObject *
-_PyDict_NewPresized(Py_ssize_t minused)
-{
-    Py_ssize_t newsize;
-    PyDictKeysObject *new_keys;
-    for (newsize = PyDict_MINSIZE_COMBINED;
-         newsize <= minused && newsize > 0;
-         newsize <<= 1)
-        ;
-    new_keys = new_keys_object(newsize);
-    if (new_keys == NULL)
-        return NULL;
-    return new_dict(new_keys, NULL);
-}
-
-/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
- * that may occur (originally dicts supported only string keys, and exceptions
- * weren't possible).  So, while the original intent was that a NULL return
- * meant the key wasn't present, in reality it can mean that, or that an error
- * (suppressed) occurred while computing the key's hash, or that some error
- * (suppressed) occurred when comparing keys in the dict's internal probe
- * sequence.  A nasty example of the latter is when a Python-coded comparison
- * function hits a stack-depth error, which can cause this to return NULL
- * even if the key is present.
- */
-PyObject *
-PyDict_GetItem(PyObject *op, PyObject *key)
-{
-    Py_hash_t hash;
-    PyDictObject *mp = (PyDictObject *)op;
-    PyDictKeyEntry *ep;
-    PyThreadState *tstate;
-    PyObject **value_addr;
-
-    if (!PyDict_Check(op))
-        return NULL;
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1)
-    {
-        hash = PyObject_Hash(key);
-        if (hash == -1) {
-            PyErr_Clear();
-            return NULL;
-        }
-    }
-
-    /* We can arrive here with a NULL tstate during initialization: try
-       running "python -Wi" for an example related to string interning.
-       Let's just hope that no exception occurs then...  This must be
-       _PyThreadState_Current and not PyThreadState_GET() because in debug
-       mode, the latter complains if tstate is NULL. */
-    tstate = (PyThreadState*)_Py_atomic_load_relaxed(
-        &_PyThreadState_Current);
-    if (tstate != NULL && tstate->curexc_type != NULL) {
-        /* preserve the existing exception */
-        PyObject *err_type, *err_value, *err_tb;
-        PyErr_Fetch(&err_type, &err_value, &err_tb);
-        ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-        /* ignore errors */
-        PyErr_Restore(err_type, err_value, err_tb);
-        if (ep == NULL)
-            return NULL;
-    }
-    else {
-        ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-        if (ep == NULL) {
-            PyErr_Clear();
-            return NULL;
-        }
-    }
-    return *value_addr;
-}
-
-PyObject *
-_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
-{
-    PyDictObject *mp = (PyDictObject *)op;
-    PyDictKeyEntry *ep;
-    PyThreadState *tstate;
-    PyObject **value_addr;
-
-    if (!PyDict_Check(op))
-        return NULL;
-
-    /* We can arrive here with a NULL tstate during initialization: try
-       running "python -Wi" for an example related to string interning.
-       Let's just hope that no exception occurs then...  This must be
-       _PyThreadState_Current and not PyThreadState_GET() because in debug
-       mode, the latter complains if tstate is NULL. */
-    tstate = (PyThreadState*)_Py_atomic_load_relaxed(
-        &_PyThreadState_Current);
-    if (tstate != NULL && tstate->curexc_type != NULL) {
-        /* preserve the existing exception */
-        PyObject *err_type, *err_value, *err_tb;
-        PyErr_Fetch(&err_type, &err_value, &err_tb);
-        ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-        /* ignore errors */
-        PyErr_Restore(err_type, err_value, err_tb);
-        if (ep == NULL)
-            return NULL;
-    }
-    else {
-        ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-        if (ep == NULL) {
-            PyErr_Clear();
-            return NULL;
-        }
-    }
-    return *value_addr;
-}
-
-/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
-   This returns NULL *with* an exception set if an exception occurred.
-   It returns NULL *without* an exception set if the key wasn't present.
-*/
-PyObject *
-PyDict_GetItemWithError(PyObject *op, PyObject *key)
-{
-    Py_hash_t hash;
-    PyDictObject*mp = (PyDictObject *)op;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if (!PyDict_Check(op)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1)
-    {
-        hash = PyObject_Hash(key);
-        if (hash == -1) {
-            return NULL;
-        }
-    }
-
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return NULL;
-    return *value_addr;
-}
-
-PyObject *
-_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
-{
-    PyObject *kv;
-    kv = _PyUnicode_FromId(key); /* borrowed */
-    if (kv == NULL)
-        return NULL;
-    return PyDict_GetItemWithError(dp, kv);
-}
-
-/* Fast version of global value lookup.
- * Lookup in globals, then builtins.
- */
-PyObject *
-_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
-{
-    PyObject *x;
-    if (PyUnicode_CheckExact(key)) {
-        PyObject **value_addr;
-        Py_hash_t hash = ((PyASCIIObject *)key)->hash;
-        if (hash != -1) {
-            PyDictKeyEntry *e;
-            e = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr);
-            if (e == NULL) {
-                return NULL;
-            }
-            x = *value_addr;
-            if (x != NULL)
-                return x;
-            e = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr);
-            if (e == NULL) {
-                return NULL;
-            }
-            x = *value_addr;
-            return x;
-        }
-    }
-    x = PyDict_GetItemWithError((PyObject *)globals, key);
-    if (x != NULL)
-        return x;
-    if (PyErr_Occurred())
-        return NULL;
-    return PyDict_GetItemWithError((PyObject *)builtins, key);
-}
-
-/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
- * dictionary if it's merely replacing the value for an existing key.
- * This means that it's safe to loop over a dictionary with PyDict_Next()
- * and occasionally replace a value -- but you can't insert new keys or
- * remove them.
- */
-int
-PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
-{
-    PyDictObject *mp;
-    Py_hash_t hash;
-    if (!PyDict_Check(op)) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    assert(key);
-    assert(value);
-    mp = (PyDictObject *)op;
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1)
-    {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return -1;
-    }
-
-    /* insertdict() handles any resizing that might be necessary */
-    return insertdict(mp, key, hash, value);
-}
-
-int
-_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
-                         Py_hash_t hash)
-{
-    PyDictObject *mp;
-
-    if (!PyDict_Check(op)) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    assert(key);
-    assert(value);
-    mp = (PyDictObject *)op;
-
-    /* insertdict() handles any resizing that might be necessary */
-    return insertdict(mp, key, hash, value);
-}
-
-int
-PyDict_DelItem(PyObject *op, PyObject *key)
-{
-    PyDictObject *mp;
-    Py_hash_t hash;
-    PyDictKeyEntry *ep;
-    PyObject *old_key, *old_value;
-    PyObject **value_addr;
-
-    if (!PyDict_Check(op)) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    assert(key);
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return -1;
-    }
-    mp = (PyDictObject *)op;
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return -1;
-    if (*value_addr == NULL) {
-        _PyErr_SetKeyError(key);
-        return -1;
-    }
-    old_value = *value_addr;
-    *value_addr = NULL;
-    mp->ma_used--;
-    if (!_PyDict_HasSplitTable(mp)) {
-        ENSURE_ALLOWS_DELETIONS(mp);
-        old_key = ep->me_key;
-        Py_INCREF(dummy);
-        ep->me_key = dummy;
-        Py_DECREF(old_key);
-    }
-    Py_DECREF(old_value);
-    return 0;
-}
-
-void
-PyDict_Clear(PyObject *op)
-{
-    PyDictObject *mp;
-    PyDictKeysObject *oldkeys;
-    PyObject **oldvalues;
-    Py_ssize_t i, n;
-
-    if (!PyDict_Check(op))
-        return;
-    mp = ((PyDictObject *)op);
-    oldkeys = mp->ma_keys;
-    oldvalues = mp->ma_values;
-    if (oldvalues == empty_values)
-        return;
-    /* Empty the dict... */
-    DK_INCREF(Py_EMPTY_KEYS);
-    mp->ma_keys = Py_EMPTY_KEYS;
-    mp->ma_values = empty_values;
-    mp->ma_used = 0;
-    /* ...then clear the keys and values */
-    if (oldvalues != NULL) {
-        n = DK_SIZE(oldkeys);
-        for (i = 0; i < n; i++)
-            Py_CLEAR(oldvalues[i]);
-        free_values(oldvalues);
-        DK_DECREF(oldkeys);
-    }
-    else {
-       assert(oldkeys->dk_refcnt == 1);
-       DK_DECREF(oldkeys);
-    }
-}
-
-/* Returns -1 if no more items (or op is not a dict),
- * index of item otherwise. Stores value in pvalue
- */
-Py_LOCAL_INLINE(Py_ssize_t)
-dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
-{
-    Py_ssize_t mask, offset;
-    PyDictObject *mp;
-    PyObject **value_ptr;
-
-
-    if (!PyDict_Check(op))
-        return -1;
-    mp = (PyDictObject *)op;
-    if (i < 0)
-        return -1;
-    if (mp->ma_values) {
-        value_ptr = &mp->ma_values[i];
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &mp->ma_keys->dk_entries[i].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    mask = DK_MASK(mp->ma_keys);
-    while (i <= mask && *value_ptr == NULL) {
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-        i++;
-    }
-    if (i > mask)
-        return -1;
-    if (pvalue)
-        *pvalue = *value_ptr;
-    return i;
-}
-
-/*
- * Iterate over a dict.  Use like so:
- *
- *     Py_ssize_t i;
- *     PyObject *key, *value;
- *     i = 0;   # important!  i should not otherwise be changed by you
- *     while (PyDict_Next(yourdict, &i, &key, &value)) {
- *              Refer to borrowed references in key and value.
- *     }
- *
- * CAUTION:  In general, it isn't safe to use PyDict_Next in a loop that
- * mutates the dict.  One exception:  it is safe if the loop merely changes
- * the values associated with the keys (but doesn't insert new keys or
- * delete keys), via PyDict_SetItem().
- */
-int
-PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
-{
-    PyDictObject *mp;
-    Py_ssize_t i = dict_next(op, *ppos, pvalue);
-    if (i < 0)
-        return 0;
-    mp = (PyDictObject *)op;
-    *ppos = i+1;
-    if (pkey)
-        *pkey = mp->ma_keys->dk_entries[i].me_key;
-    return 1;
-}
-
-/* Internal version of PyDict_Next that returns a hash value in addition
- * to the key and value.
- */
-int
-_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
-             PyObject **pvalue, Py_hash_t *phash)
-{
-    PyDictObject *mp;
-    Py_ssize_t i = dict_next(op, *ppos, pvalue);
-    if (i < 0)
-        return 0;
-    mp = (PyDictObject *)op;
-    *ppos = i+1;
-    *phash = mp->ma_keys->dk_entries[i].me_hash;
-    if (pkey)
-        *pkey = mp->ma_keys->dk_entries[i].me_key;
-    return 1;
-}
-
-/* Methods */
-
-static void
-dict_dealloc(PyDictObject *mp)
-{
-    PyObject **values = mp->ma_values;
-    PyDictKeysObject *keys = mp->ma_keys;
-    Py_ssize_t i, n;
-    PyObject_GC_UnTrack(mp);
-    Py_TRASHCAN_SAFE_BEGIN(mp)
-    if (values != NULL) {
-        if (values != empty_values) {
-            for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
-                Py_XDECREF(values[i]);
-            }
-            free_values(values);
-        }
-        DK_DECREF(keys);
-    }
-    else if (keys != NULL) {
-        assert(keys->dk_refcnt == 1);
-        DK_DECREF(keys);
-    }
-    if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
-        free_list[numfree++] = mp;
-    else
-        Py_TYPE(mp)->tp_free((PyObject *)mp);
-    Py_TRASHCAN_SAFE_END(mp)
-}
-
-
-static PyObject *
-dict_repr(PyDictObject *mp)
-{
-    Py_ssize_t i;
-    PyObject *key = NULL, *value = NULL;
-    _PyUnicodeWriter writer;
-    int first;
-
-    i = Py_ReprEnter((PyObject *)mp);
-    if (i != 0) {
-        return i > 0 ? PyUnicode_FromString("{...}") : NULL;
-    }
-
-    if (mp->ma_used == 0) {
-        Py_ReprLeave((PyObject *)mp);
-        return PyUnicode_FromString("{}");
-    }
-
-    _PyUnicodeWriter_Init(&writer);
-    writer.overallocate = 1;
-    /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
-    writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
-
-    if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
-        goto error;
-
-    /* Do repr() on each key+value pair, and insert ": " between them.
-       Note that repr may mutate the dict. */
-    i = 0;
-    first = 1;
-    while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
-        PyObject *s;
-        int res;
-
-        /* Prevent repr from deleting key or value during key format. */
-        Py_INCREF(key);
-        Py_INCREF(value);
-
-        if (!first) {
-            if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
-                goto error;
-        }
-        first = 0;
-
-        s = PyObject_Repr(key);
-        if (s == NULL)
-            goto error;
-        res = _PyUnicodeWriter_WriteStr(&writer, s);
-        Py_DECREF(s);
-        if (res < 0)
-            goto error;
-
-        if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
-            goto error;
-
-        s = PyObject_Repr(value);
-        if (s == NULL)
-            goto error;
-        res = _PyUnicodeWriter_WriteStr(&writer, s);
-        Py_DECREF(s);
-        if (res < 0)
-            goto error;
-
-        Py_CLEAR(key);
-        Py_CLEAR(value);
-    }
-
-    writer.overallocate = 0;
-    if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
-        goto error;
-
-    Py_ReprLeave((PyObject *)mp);
-
-    return _PyUnicodeWriter_Finish(&writer);
-
-error:
-    Py_ReprLeave((PyObject *)mp);
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(key);
-    Py_XDECREF(value);
-    return NULL;
-}
-
-static Py_ssize_t
-dict_length(PyDictObject *mp)
-{
-    return mp->ma_used;
-}
-
-static PyObject *
-dict_subscript(PyDictObject *mp, PyObject *key)
-{
-    PyObject *v;
-    Py_hash_t hash;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return NULL;
-    }
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return NULL;
-    v = *value_addr;
-    if (v == NULL) {
-        if (!PyDict_CheckExact(mp)) {
-            /* Look up __missing__ method if we're a subclass. */
-            PyObject *missing, *res;
-            _Py_IDENTIFIER(__missing__);
-            missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
-            if (missing != NULL) {
-                res = PyObject_CallFunctionObjArgs(missing,
-                                                   key, NULL);
-                Py_DECREF(missing);
-                return res;
-            }
-            else if (PyErr_Occurred())
-                return NULL;
-        }
-        _PyErr_SetKeyError(key);
-        return NULL;
-    }
-    else
-        Py_INCREF(v);
-    return v;
-}
-
-static int
-dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
-{
-    if (w == NULL)
-        return PyDict_DelItem((PyObject *)mp, v);
-    else
-        return PyDict_SetItem((PyObject *)mp, v, w);
-}
-
-static PyMappingMethods dict_as_mapping = {
-    (lenfunc)dict_length, /*mp_length*/
-    (binaryfunc)dict_subscript, /*mp_subscript*/
-    (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
-};
-
-static PyObject *
-dict_keys(PyDictObject *mp)
-{
-    PyObject *v;
-    Py_ssize_t i, j;
-    PyDictKeyEntry *ep;
-    Py_ssize_t size, n, offset;
-    PyObject **value_ptr;
-
-  again:
-    n = mp->ma_used;
-    v = PyList_New(n);
-    if (v == NULL)
-        return NULL;
-    if (n != mp->ma_used) {
-        /* Durnit.  The allocations caused the dict to resize.
-         * Just start over, this shouldn't normally happen.
-         */
-        Py_DECREF(v);
-        goto again;
-    }
-    ep = &mp->ma_keys->dk_entries[0];
-    size = DK_SIZE(mp->ma_keys);
-    if (mp->ma_values) {
-        value_ptr = mp->ma_values;
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &ep[0].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    for (i = 0, j = 0; i < size; i++) {
-        if (*value_ptr != NULL) {
-            PyObject *key = ep[i].me_key;
-            Py_INCREF(key);
-            PyList_SET_ITEM(v, j, key);
-            j++;
-        }
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-    }
-    assert(j == n);
-    return v;
-}
-
-static PyObject *
-dict_values(PyDictObject *mp)
-{
-    PyObject *v;
-    Py_ssize_t i, j;
-    Py_ssize_t size, n, offset;
-    PyObject **value_ptr;
-
-  again:
-    n = mp->ma_used;
-    v = PyList_New(n);
-    if (v == NULL)
-        return NULL;
-    if (n != mp->ma_used) {
-        /* Durnit.  The allocations caused the dict to resize.
-         * Just start over, this shouldn't normally happen.
-         */
-        Py_DECREF(v);
-        goto again;
-    }
-    size = DK_SIZE(mp->ma_keys);
-    if (mp->ma_values) {
-        value_ptr = mp->ma_values;
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &mp->ma_keys->dk_entries[0].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    for (i = 0, j = 0; i < size; i++) {
-        PyObject *value = *value_ptr;
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-        if (value != NULL) {
-            Py_INCREF(value);
-            PyList_SET_ITEM(v, j, value);
-            j++;
-        }
-    }
-    assert(j == n);
-    return v;
-}
-
-static PyObject *
-dict_items(PyDictObject *mp)
-{
-    PyObject *v;
-    Py_ssize_t i, j, n;
-    Py_ssize_t size, offset;
-    PyObject *item, *key;
-    PyDictKeyEntry *ep;
-    PyObject **value_ptr;
-
-    /* Preallocate the list of tuples, to avoid allocations during
-     * the loop over the items, which could trigger GC, which
-     * could resize the dict. :-(
-     */
-  again:
-    n = mp->ma_used;
-    v = PyList_New(n);
-    if (v == NULL)
-        return NULL;
-    for (i = 0; i < n; i++) {
-        item = PyTuple_New(2);
-        if (item == NULL) {
-            Py_DECREF(v);
-            return NULL;
-        }
-        PyList_SET_ITEM(v, i, item);
-    }
-    if (n != mp->ma_used) {
-        /* Durnit.  The allocations caused the dict to resize.
-         * Just start over, this shouldn't normally happen.
-         */
-        Py_DECREF(v);
-        goto again;
-    }
-    /* Nothing we do below makes any function calls. */
-    ep = mp->ma_keys->dk_entries;
-    size = DK_SIZE(mp->ma_keys);
-    if (mp->ma_values) {
-        value_ptr = mp->ma_values;
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &ep[0].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    for (i = 0, j = 0; i < size; i++) {
-        PyObject *value = *value_ptr;
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-        if (value != NULL) {
-            key = ep[i].me_key;
-            item = PyList_GET_ITEM(v, j);
-            Py_INCREF(key);
-            PyTuple_SET_ITEM(item, 0, key);
-            Py_INCREF(value);
-            PyTuple_SET_ITEM(item, 1, value);
-            j++;
-        }
-    }
-    assert(j == n);
-    return v;
-}
-
-/*[clinic input]
- at classmethod
-dict.fromkeys
-    iterable: object
-    value: object=None
-    /
-
-Returns a new dict with keys from iterable and values equal to value.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(dict_fromkeys__doc__,
@@ -1786,486 +31,6 @@
     return return_value;
 }
 
-static PyObject *
-dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
-/*[clinic end generated code: output=55f8dc0ffa87406f input=b85a667f9bf4669d]*/
-{
-    PyObject *it;       /* iter(seq) */
-    PyObject *key;
-    PyObject *d;
-    int status;
-
-    d = PyObject_CallObject((PyObject *)type, NULL);
-    if (d == NULL)
-        return NULL;
-
-    if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
-        if (PyDict_CheckExact(iterable)) {
-            PyDictObject *mp = (PyDictObject *)d;
-            PyObject *oldvalue;
-            Py_ssize_t pos = 0;
-            PyObject *key;
-            Py_hash_t hash;
-
-            if (dictresize(mp, Py_SIZE(iterable))) {
-                Py_DECREF(d);
-                return NULL;
-            }
-
-            while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
-                if (insertdict(mp, key, hash, value)) {
-                    Py_DECREF(d);
-                    return NULL;
-                }
-            }
-            return d;
-        }
-        if (PyAnySet_CheckExact(iterable)) {
-            PyDictObject *mp = (PyDictObject *)d;
-            Py_ssize_t pos = 0;
-            PyObject *key;
-            Py_hash_t hash;
-
-            if (dictresize(mp, PySet_GET_SIZE(iterable))) {
-                Py_DECREF(d);
-                return NULL;
-            }
-
-            while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
-                if (insertdict(mp, key, hash, value)) {
-                    Py_DECREF(d);
-                    return NULL;
-                }
-            }
-            return d;
-        }
-    }
-
-    it = PyObject_GetIter(iterable);
-    if (it == NULL){
-        Py_DECREF(d);
-        return NULL;
-    }
-
-    if (PyDict_CheckExact(d)) {
-        while ((key = PyIter_Next(it)) != NULL) {
-            status = PyDict_SetItem(d, key, value);
-            Py_DECREF(key);
-            if (status < 0)
-                goto Fail;
-        }
-    } else {
-        while ((key = PyIter_Next(it)) != NULL) {
-            status = PyObject_SetItem(d, key, value);
-            Py_DECREF(key);
-            if (status < 0)
-                goto Fail;
-        }
-    }
-
-    if (PyErr_Occurred())
-        goto Fail;
-    Py_DECREF(it);
-    return d;
-
-Fail:
-    Py_DECREF(it);
-    Py_DECREF(d);
-    return NULL;
-}
-
-static int
-dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
-{
-    PyObject *arg = NULL;
-    int result = 0;
-
-    if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
-        result = -1;
-
-    else if (arg != NULL) {
-        _Py_IDENTIFIER(keys);
-        if (_PyObject_HasAttrId(arg, &PyId_keys))
-            result = PyDict_Merge(self, arg, 1);
-        else
-            result = PyDict_MergeFromSeq2(self, arg, 1);
-    }
-    if (result == 0 && kwds != NULL) {
-        if (PyArg_ValidateKeywordArguments(kwds))
-            result = PyDict_Merge(self, kwds, 1);
-        else
-            result = -1;
-    }
-    return result;
-}
-
-static PyObject *
-dict_update(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    if (dict_update_common(self, args, kwds, "update") != -1)
-        Py_RETURN_NONE;
-    return NULL;
-}
-
-/* Update unconditionally replaces existing items.
-   Merge has a 3rd argument 'override'; if set, it acts like Update,
-   otherwise it leaves existing items unchanged.
-
-   PyDict_{Update,Merge} update/merge from a mapping object.
-
-   PyDict_MergeFromSeq2 updates/merges from any iterable object
-   producing iterable objects of length 2.
-*/
-
-int
-PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
-{
-    PyObject *it;       /* iter(seq2) */
-    Py_ssize_t i;       /* index into seq2 of current element */
-    PyObject *item;     /* seq2[i] */
-    PyObject *fast;     /* item as a 2-tuple or 2-list */
-
-    assert(d != NULL);
-    assert(PyDict_Check(d));
-    assert(seq2 != NULL);
-
-    it = PyObject_GetIter(seq2);
-    if (it == NULL)
-        return -1;
-
-    for (i = 0; ; ++i) {
-        PyObject *key, *value;
-        Py_ssize_t n;
-
-        fast = NULL;
-        item = PyIter_Next(it);
-        if (item == NULL) {
-            if (PyErr_Occurred())
-                goto Fail;
-            break;
-        }
-
-        /* Convert item to sequence, and verify length 2. */
-        fast = PySequence_Fast(item, "");
-        if (fast == NULL) {
-            if (PyErr_ExceptionMatches(PyExc_TypeError))
-                PyErr_Format(PyExc_TypeError,
-                    "cannot convert dictionary update "
-                    "sequence element #%zd to a sequence",
-                    i);
-            goto Fail;
-        }
-        n = PySequence_Fast_GET_SIZE(fast);
-        if (n != 2) {
-            PyErr_Format(PyExc_ValueError,
-                         "dictionary update sequence element #%zd "
-                         "has length %zd; 2 is required",
-                         i, n);
-            goto Fail;
-        }
-
-        /* Update/merge with this (key, value) pair. */
-        key = PySequence_Fast_GET_ITEM(fast, 0);
-        value = PySequence_Fast_GET_ITEM(fast, 1);
-        if (override || PyDict_GetItem(d, key) == NULL) {
-            int status = PyDict_SetItem(d, key, value);
-            if (status < 0)
-                goto Fail;
-        }
-        Py_DECREF(fast);
-        Py_DECREF(item);
-    }
-
-    i = 0;
-    goto Return;
-Fail:
-    Py_XDECREF(item);
-    Py_XDECREF(fast);
-    i = -1;
-Return:
-    Py_DECREF(it);
-    return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
-}
-
-int
-PyDict_Update(PyObject *a, PyObject *b)
-{
-    return PyDict_Merge(a, b, 1);
-}
-
-int
-PyDict_Merge(PyObject *a, PyObject *b, int override)
-{
-    PyDictObject *mp, *other;
-    Py_ssize_t i, n;
-    PyDictKeyEntry *entry;
-
-    /* We accept for the argument either a concrete dictionary object,
-     * or an abstract "mapping" object.  For the former, we can do
-     * things quite efficiently.  For the latter, we only require that
-     * PyMapping_Keys() and PyObject_GetItem() be supported.
-     */
-    if (a == NULL || !PyDict_Check(a) || b == NULL) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    mp = (PyDictObject*)a;
-    if (PyDict_Check(b)) {
-        other = (PyDictObject*)b;
-        if (other == mp || other->ma_used == 0)
-            /* a.update(a) or a.update({}); nothing to do */
-            return 0;
-        if (mp->ma_used == 0)
-            /* Since the target dict is empty, PyDict_GetItem()
-             * always returns NULL.  Setting override to 1
-             * skips the unnecessary test.
-             */
-            override = 1;
-        /* Do one big resize at the start, rather than
-         * incrementally resizing as we insert new items.  Expect
-         * that there will be no (or few) overlapping keys.
-         */
-        if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
-            if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
-               return -1;
-        for (i = 0, n = DK_SIZE(other->ma_keys); i < n; i++) {
-            PyObject *value;
-            entry = &other->ma_keys->dk_entries[i];
-            if (other->ma_values)
-                value = other->ma_values[i];
-            else
-                value = entry->me_value;
-
-            if (value != NULL &&
-                (override ||
-                 PyDict_GetItem(a, entry->me_key) == NULL)) {
-                if (insertdict(mp, entry->me_key,
-                               entry->me_hash,
-                               value) != 0)
-                    return -1;
-            }
-        }
-    }
-    else {
-        /* Do it the generic, slower way */
-        PyObject *keys = PyMapping_Keys(b);
-        PyObject *iter;
-        PyObject *key, *value;
-        int status;
-
-        if (keys == NULL)
-            /* Docstring says this is equivalent to E.keys() so
-             * if E doesn't have a .keys() method we want
-             * AttributeError to percolate up.  Might as well
-             * do the same for any other error.
-             */
-            return -1;
-
-        iter = PyObject_GetIter(keys);
-        Py_DECREF(keys);
-        if (iter == NULL)
-            return -1;
-
-        for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
-            if (!override && PyDict_GetItem(a, key) != NULL) {
-                Py_DECREF(key);
-                continue;
-            }
-            value = PyObject_GetItem(b, key);
-            if (value == NULL) {
-                Py_DECREF(iter);
-                Py_DECREF(key);
-                return -1;
-            }
-            status = PyDict_SetItem(a, key, value);
-            Py_DECREF(key);
-            Py_DECREF(value);
-            if (status < 0) {
-                Py_DECREF(iter);
-                return -1;
-            }
-        }
-        Py_DECREF(iter);
-        if (PyErr_Occurred())
-            /* Iterator completed, via error */
-            return -1;
-    }
-    return 0;
-}
-
-static PyObject *
-dict_copy(PyDictObject *mp)
-{
-    return PyDict_Copy((PyObject*)mp);
-}
-
-PyObject *
-PyDict_Copy(PyObject *o)
-{
-    PyObject *copy;
-    PyDictObject *mp;
-    Py_ssize_t i, n;
-
-    if (o == NULL || !PyDict_Check(o)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    mp = (PyDictObject *)o;
-    if (_PyDict_HasSplitTable(mp)) {
-        PyDictObject *split_copy;
-        PyObject **newvalues = new_values(DK_SIZE(mp->ma_keys));
-        if (newvalues == NULL)
-            return PyErr_NoMemory();
-        split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
-        if (split_copy == NULL) {
-            free_values(newvalues);
-            return NULL;
-        }
-        split_copy->ma_values = newvalues;
-        split_copy->ma_keys = mp->ma_keys;
-        split_copy->ma_used = mp->ma_used;
-        DK_INCREF(mp->ma_keys);
-        for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
-            PyObject *value = mp->ma_values[i];
-            Py_XINCREF(value);
-            split_copy->ma_values[i] = value;
-        }
-        if (_PyObject_GC_IS_TRACKED(mp))
-            _PyObject_GC_TRACK(split_copy);
-        return (PyObject *)split_copy;
-    }
-    copy = PyDict_New();
-    if (copy == NULL)
-        return NULL;
-    if (PyDict_Merge(copy, o, 1) == 0)
-        return copy;
-    Py_DECREF(copy);
-    return NULL;
-}
-
-Py_ssize_t
-PyDict_Size(PyObject *mp)
-{
-    if (mp == NULL || !PyDict_Check(mp)) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    return ((PyDictObject *)mp)->ma_used;
-}
-
-PyObject *
-PyDict_Keys(PyObject *mp)
-{
-    if (mp == NULL || !PyDict_Check(mp)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    return dict_keys((PyDictObject *)mp);
-}
-
-PyObject *
-PyDict_Values(PyObject *mp)
-{
-    if (mp == NULL || !PyDict_Check(mp)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    return dict_values((PyDictObject *)mp);
-}
-
-PyObject *
-PyDict_Items(PyObject *mp)
-{
-    if (mp == NULL || !PyDict_Check(mp)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    return dict_items((PyDictObject *)mp);
-}
-
-/* Return 1 if dicts equal, 0 if not, -1 if error.
- * Gets out as soon as any difference is detected.
- * Uses only Py_EQ comparison.
- */
-static int
-dict_equal(PyDictObject *a, PyDictObject *b)
-{
-    Py_ssize_t i;
-
-    if (a->ma_used != b->ma_used)
-        /* can't be equal if # of entries differ */
-        return 0;
-    /* Same # of entries -- check all of 'em.  Exit early on any diff. */
-    for (i = 0; i < DK_SIZE(a->ma_keys); i++) {
-        PyDictKeyEntry *ep = &a->ma_keys->dk_entries[i];
-        PyObject *aval;
-        if (a->ma_values)
-            aval = a->ma_values[i];
-        else
-            aval = ep->me_value;
-        if (aval != NULL) {
-            int cmp;
-            PyObject *bval;
-            PyObject **vaddr;
-            PyObject *key = ep->me_key;
-            /* temporarily bump aval's refcount to ensure it stays
-               alive until we're done with it */
-            Py_INCREF(aval);
-            /* ditto for key */
-            Py_INCREF(key);
-            /* reuse the known hash value */
-            if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr) == NULL)
-                bval = NULL;
-            else
-                bval = *vaddr;
-            Py_DECREF(key);
-            if (bval == NULL) {
-                Py_DECREF(aval);
-                if (PyErr_Occurred())
-                    return -1;
-                return 0;
-            }
-            cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
-            Py_DECREF(aval);
-            if (cmp <= 0)  /* error or not equal */
-                return cmp;
-        }
-    }
-    return 1;
-}
-
-static PyObject *
-dict_richcompare(PyObject *v, PyObject *w, int op)
-{
-    int cmp;
-    PyObject *res;
-
-    if (!PyDict_Check(v) || !PyDict_Check(w)) {
-        res = Py_NotImplemented;
-    }
-    else if (op == Py_EQ || op == Py_NE) {
-        cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
-        if (cmp < 0)
-            return NULL;
-        res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
-    }
-    else
-        res = Py_NotImplemented;
-    Py_INCREF(res);
-    return res;
-}
-
-/*[clinic input]
-
- at coexist
-dict.__contains__
-
-  key: object
-  /
-
-True if D has a key k, else False.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(dict___contains____doc__,
 "__contains__($self, key, /)\n"
 "--\n"
@@ -2274,1654 +39,4 @@
 
 #define DICT___CONTAINS___METHODDEF    \
     {"__contains__", (PyCFunction)dict___contains__, METH_O|METH_COEXIST, dict___contains____doc__},
-
-static PyObject *
-dict___contains__(PyDictObject *self, PyObject *key)
-/*[clinic end generated code: output=3cf3f8aaf2cc5cc3 input=b852b2a19b51ab24]*/
-{
-    register PyDictObject *mp = self;
-    Py_hash_t hash;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return NULL;
-    }
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return NULL;
-    return PyBool_FromLong(*value_addr != NULL);
-}
-
-static PyObject *
-dict_get(PyDictObject *mp, PyObject *args)
-{
-    PyObject *key;
-    PyObject *failobj = Py_None;
-    PyObject *val = NULL;
-    Py_hash_t hash;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
-        return NULL;
-
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return NULL;
-    }
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return NULL;
-    val = *value_addr;
-    if (val == NULL)
-        val = failobj;
-    Py_INCREF(val);
-    return val;
-}
-
-PyObject *
-PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
-{
-    PyDictObject *mp = (PyDictObject *)d;
-    PyObject *val = NULL;
-    Py_hash_t hash;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if (!PyDict_Check(d)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return NULL;
-    }
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return NULL;
-    val = *value_addr;
-    if (val == NULL) {
-        if (mp->ma_keys->dk_usable <= 0) {
-            /* Need to resize. */
-            if (insertion_resize(mp) < 0)
-                return NULL;
-            ep = find_empty_slot(mp, key, hash, &value_addr);
-        }
-        Py_INCREF(defaultobj);
-        Py_INCREF(key);
-        MAINTAIN_TRACKING(mp, key, defaultobj);
-        ep->me_key = key;
-        ep->me_hash = hash;
-        *value_addr = defaultobj;
-        val = defaultobj;
-        mp->ma_keys->dk_usable--;
-        mp->ma_used++;
-    }
-    return val;
-}
-
-static PyObject *
-dict_setdefault(PyDictObject *mp, PyObject *args)
-{
-    PyObject *key, *val;
-    PyObject *defaultobj = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
-        return NULL;
-
-    val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
-    Py_XINCREF(val);
-    return val;
-}
-
-static PyObject *
-dict_clear(PyDictObject *mp)
-{
-    PyDict_Clear((PyObject *)mp);
-    Py_RETURN_NONE;
-}
-
-static PyObject *
-dict_pop(PyDictObject *mp, PyObject *args)
-{
-    Py_hash_t hash;
-    PyObject *old_value, *old_key;
-    PyObject *key, *deflt = NULL;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
-        return NULL;
-    if (mp->ma_used == 0) {
-        if (deflt) {
-            Py_INCREF(deflt);
-            return deflt;
-        }
-        _PyErr_SetKeyError(key);
-        return NULL;
-    }
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return NULL;
-    }
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    if (ep == NULL)
-        return NULL;
-    old_value = *value_addr;
-    if (old_value == NULL) {
-        if (deflt) {
-            Py_INCREF(deflt);
-            return deflt;
-        }
-        _PyErr_SetKeyError(key);
-        return NULL;
-    }
-    *value_addr = NULL;
-    mp->ma_used--;
-    if (!_PyDict_HasSplitTable(mp)) {
-        ENSURE_ALLOWS_DELETIONS(mp);
-        old_key = ep->me_key;
-        Py_INCREF(dummy);
-        ep->me_key = dummy;
-        Py_DECREF(old_key);
-    }
-    return old_value;
-}
-
-static PyObject *
-dict_popitem(PyDictObject *mp)
-{
-    Py_hash_t i = 0;
-    PyDictKeyEntry *ep;
-    PyObject *res;
-
-
-    /* Allocate the result tuple before checking the size.  Believe it
-     * or not, this allocation could trigger a garbage collection which
-     * could empty the dict, so if we checked the size first and that
-     * happened, the result would be an infinite loop (searching for an
-     * entry that no longer exists).  Note that the usual popitem()
-     * idiom is "while d: k, v = d.popitem()". so needing to throw the
-     * tuple away if the dict *is* empty isn't a significant
-     * inefficiency -- possible, but unlikely in practice.
-     */
-    res = PyTuple_New(2);
-    if (res == NULL)
-        return NULL;
-    if (mp->ma_used == 0) {
-        Py_DECREF(res);
-        PyErr_SetString(PyExc_KeyError,
-                        "popitem(): dictionary is empty");
-        return NULL;
-    }
-    /* Convert split table to combined table */
-    if (mp->ma_keys->dk_lookup == lookdict_split) {
-        if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
-            Py_DECREF(res);
-            return NULL;
-        }
-    }
-    ENSURE_ALLOWS_DELETIONS(mp);
-    /* Set ep to "the first" dict entry with a value.  We abuse the hash
-     * field of slot 0 to hold a search finger:
-     * If slot 0 has a value, use slot 0.
-     * Else slot 0 is being used to hold a search finger,
-     * and we use its hash value as the first index to look.
-     */
-    ep = &mp->ma_keys->dk_entries[0];
-    if (ep->me_value == NULL) {
-        Py_ssize_t mask = DK_MASK(mp->ma_keys);
-        i = ep->me_hash;
-        /* The hash field may be a real hash value, or it may be a
-         * legit search finger, or it may be a once-legit search
-         * finger that's out of bounds now because it wrapped around
-         * or the table shrunk -- simply make sure it's in bounds now.
-         */
-        if (i > mask || i < 1)
-            i = 1;              /* skip slot 0 */
-        while ((ep = &mp->ma_keys->dk_entries[i])->me_value == NULL) {
-            i++;
-            if (i > mask)
-                i = 1;
-        }
-    }
-    PyTuple_SET_ITEM(res, 0, ep->me_key);
-    PyTuple_SET_ITEM(res, 1, ep->me_value);
-    Py_INCREF(dummy);
-    ep->me_key = dummy;
-    ep->me_value = NULL;
-    mp->ma_used--;
-    assert(mp->ma_keys->dk_entries[0].me_value == NULL);
-    mp->ma_keys->dk_entries[0].me_hash = i + 1;  /* next place to start */
-    return res;
-}
-
-static int
-dict_traverse(PyObject *op, visitproc visit, void *arg)
-{
-    Py_ssize_t i, n;
-    PyDictObject *mp = (PyDictObject *)op;
-    if (mp->ma_keys->dk_lookup == lookdict) {
-        for (i = 0; i < DK_SIZE(mp->ma_keys); i++) {
-            if (mp->ma_keys->dk_entries[i].me_value != NULL) {
-                Py_VISIT(mp->ma_keys->dk_entries[i].me_value);
-                Py_VISIT(mp->ma_keys->dk_entries[i].me_key);
-            }
-        }
-    } else {
-        if (mp->ma_values != NULL) {
-            for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
-                Py_VISIT(mp->ma_values[i]);
-            }
-        }
-        else {
-            for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
-                Py_VISIT(mp->ma_keys->dk_entries[i].me_value);
-            }
-        }
-    }
-    return 0;
-}
-
-static int
-dict_tp_clear(PyObject *op)
-{
-    PyDict_Clear(op);
-    return 0;
-}
-
-static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
-
-static PyObject *
-dict_sizeof(PyDictObject *mp)
-{
-    Py_ssize_t size, res;
-
-    size = DK_SIZE(mp->ma_keys);
-    res = sizeof(PyDictObject);
-    if (mp->ma_values)
-        res += size * sizeof(PyObject*);
-    /* If the dictionary is split, the keys portion is accounted-for
-       in the type object. */
-    if (mp->ma_keys->dk_refcnt == 1)
-        res += sizeof(PyDictKeysObject) + (size-1) * sizeof(PyDictKeyEntry);
-    return PyLong_FromSsize_t(res);
-}
-
-Py_ssize_t
-_PyDict_KeysSize(PyDictKeysObject *keys)
-{
-    return sizeof(PyDictKeysObject) + (DK_SIZE(keys)-1) * sizeof(PyDictKeyEntry);
-}
-
-PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
-
-PyDoc_STRVAR(sizeof__doc__,
-"D.__sizeof__() -> size of D in memory, in bytes");
-
-PyDoc_STRVAR(get__doc__,
-"D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.");
-
-PyDoc_STRVAR(setdefault_doc__,
-"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D");
-
-PyDoc_STRVAR(pop__doc__,
-"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
-If key is not found, d is returned if given, otherwise KeyError is raised");
-
-PyDoc_STRVAR(popitem__doc__,
-"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
-2-tuple; but raise KeyError if D is empty.");
-
-PyDoc_STRVAR(update__doc__,
-"D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.\n\
-If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\n\
-If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\n\
-In either case, this is followed by: for k in F:  D[k] = F[k]");
-
-PyDoc_STRVAR(clear__doc__,
-"D.clear() -> None.  Remove all items from D.");
-
-PyDoc_STRVAR(copy__doc__,
-"D.copy() -> a shallow copy of D");
-
-/* Forward */
-static PyObject *dictkeys_new(PyObject *);
-static PyObject *dictitems_new(PyObject *);
-static PyObject *dictvalues_new(PyObject *);
-
-PyDoc_STRVAR(keys__doc__,
-             "D.keys() -> a set-like object providing a view on D's keys");
-PyDoc_STRVAR(items__doc__,
-             "D.items() -> a set-like object providing a view on D's items");
-PyDoc_STRVAR(values__doc__,
-             "D.values() -> an object providing a view on D's values");
-
-static PyMethodDef mapp_methods[] = {
-    DICT___CONTAINS___METHODDEF
-    {"__getitem__", (PyCFunction)dict_subscript,        METH_O | METH_COEXIST,
-     getitem__doc__},
-    {"__sizeof__",      (PyCFunction)dict_sizeof,       METH_NOARGS,
-     sizeof__doc__},
-    {"get",         (PyCFunction)dict_get,          METH_VARARGS,
-     get__doc__},
-    {"setdefault",  (PyCFunction)dict_setdefault,   METH_VARARGS,
-     setdefault_doc__},
-    {"pop",         (PyCFunction)dict_pop,          METH_VARARGS,
-     pop__doc__},
-    {"popitem",         (PyCFunction)dict_popitem,      METH_NOARGS,
-     popitem__doc__},
-    {"keys",            (PyCFunction)dictkeys_new,      METH_NOARGS,
-    keys__doc__},
-    {"items",           (PyCFunction)dictitems_new,     METH_NOARGS,
-    items__doc__},
-    {"values",          (PyCFunction)dictvalues_new,    METH_NOARGS,
-    values__doc__},
-    {"update",          (PyCFunction)dict_update,       METH_VARARGS | METH_KEYWORDS,
-     update__doc__},
-    DICT_FROMKEYS_METHODDEF
-    {"clear",           (PyCFunction)dict_clear,        METH_NOARGS,
-     clear__doc__},
-    {"copy",            (PyCFunction)dict_copy,         METH_NOARGS,
-     copy__doc__},
-    {NULL,              NULL}   /* sentinel */
-};
-
-/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
-int
-PyDict_Contains(PyObject *op, PyObject *key)
-{
-    Py_hash_t hash;
-    PyDictObject *mp = (PyDictObject *)op;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    if (!PyUnicode_CheckExact(key) ||
-        (hash = ((PyASCIIObject *) key)->hash) == -1) {
-        hash = PyObject_Hash(key);
-        if (hash == -1)
-            return -1;
-    }
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    return (ep == NULL) ? -1 : (*value_addr != NULL);
-}
-
-/* Internal version of PyDict_Contains used when the hash value is already known */
-int
-_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
-{
-    PyDictObject *mp = (PyDictObject *)op;
-    PyDictKeyEntry *ep;
-    PyObject **value_addr;
-
-    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
-    return (ep == NULL) ? -1 : (*value_addr != NULL);
-}
-
-/* Hack to implement "key in dict" */
-static PySequenceMethods dict_as_sequence = {
-    0,                          /* sq_length */
-    0,                          /* sq_concat */
-    0,                          /* sq_repeat */
-    0,                          /* sq_item */
-    0,                          /* sq_slice */
-    0,                          /* sq_ass_item */
-    0,                          /* sq_ass_slice */
-    PyDict_Contains,            /* sq_contains */
-    0,                          /* sq_inplace_concat */
-    0,                          /* sq_inplace_repeat */
-};
-
-static PyObject *
-dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *self;
-    PyDictObject *d;
-
-    assert(type != NULL && type->tp_alloc != NULL);
-    self = type->tp_alloc(type, 0);
-    if (self == NULL)
-        return NULL;
-    d = (PyDictObject *)self;
-
-    /* The object has been implicitly tracked by tp_alloc */
-    if (type == &PyDict_Type)
-        _PyObject_GC_UNTRACK(d);
-
-    d->ma_used = 0;
-    d->ma_keys = new_keys_object(PyDict_MINSIZE_COMBINED);
-    if (d->ma_keys == NULL) {
-        Py_DECREF(self);
-        return NULL;
-    }
-    return self;
-}
-
-static int
-dict_init(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    return dict_update_common(self, args, kwds, "dict");
-}
-
-static PyObject *
-dict_iter(PyDictObject *dict)
-{
-    return dictiter_new(dict, &PyDictIterKey_Type);
-}
-
-PyDoc_STRVAR(dictionary_doc,
-"dict() -> new empty dictionary\n"
-"dict(mapping) -> new dictionary initialized from a mapping object's\n"
-"    (key, value) pairs\n"
-"dict(iterable) -> new dictionary initialized as if via:\n"
-"    d = {}\n"
-"    for k, v in iterable:\n"
-"        d[k] = v\n"
-"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
-"    in the keyword argument list.  For example:  dict(one=1, two=2)");
-
-PyTypeObject PyDict_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict",
-    sizeof(PyDictObject),
-    0,
-    (destructor)dict_dealloc,                   /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)dict_repr,                        /* tp_repr */
-    0,                                          /* tp_as_number */
-    &dict_as_sequence,                          /* tp_as_sequence */
-    &dict_as_mapping,                           /* tp_as_mapping */
-    PyObject_HashNotImplemented,                /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS,         /* tp_flags */
-    dictionary_doc,                             /* tp_doc */
-    dict_traverse,                              /* tp_traverse */
-    dict_tp_clear,                              /* tp_clear */
-    dict_richcompare,                           /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    (getiterfunc)dict_iter,                     /* tp_iter */
-    0,                                          /* tp_iternext */
-    mapp_methods,                               /* tp_methods */
-    0,                                          /* tp_members */
-    0,                                          /* tp_getset */
-    0,                                          /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    dict_init,                                  /* tp_init */
-    PyType_GenericAlloc,                        /* tp_alloc */
-    dict_new,                                   /* tp_new */
-    PyObject_GC_Del,                            /* tp_free */
-};
-
-PyObject *
-_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
-{
-    PyObject *kv;
-    kv = _PyUnicode_FromId(key); /* borrowed */
-    if (kv == NULL) {
-        PyErr_Clear();
-        return NULL;
-    }
-    return PyDict_GetItem(dp, kv);
-}
-
-/* For backward compatibility with old dictionary interface */
-
-PyObject *
-PyDict_GetItemString(PyObject *v, const char *key)
-{
-    PyObject *kv, *rv;
-    kv = PyUnicode_FromString(key);
-    if (kv == NULL) {
-        PyErr_Clear();
-        return NULL;
-    }
-    rv = PyDict_GetItem(v, kv);
-    Py_DECREF(kv);
-    return rv;
-}
-
-int
-_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
-{
-    PyObject *kv;
-    kv = _PyUnicode_FromId(key); /* borrowed */
-    if (kv == NULL)
-        return -1;
-    return PyDict_SetItem(v, kv, item);
-}
-
-int
-PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
-{
-    PyObject *kv;
-    int err;
-    kv = PyUnicode_FromString(key);
-    if (kv == NULL)
-        return -1;
-    PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
-    err = PyDict_SetItem(v, kv, item);
-    Py_DECREF(kv);
-    return err;
-}
-
-int
-_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
-{
-    PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
-    if (kv == NULL)
-        return -1;
-    return PyDict_DelItem(v, kv);
-}
-
-int
-PyDict_DelItemString(PyObject *v, const char *key)
-{
-    PyObject *kv;
-    int err;
-    kv = PyUnicode_FromString(key);
-    if (kv == NULL)
-        return -1;
-    err = PyDict_DelItem(v, kv);
-    Py_DECREF(kv);
-    return err;
-}
-
-/* Dictionary iterator types */
-
-typedef struct {
-    PyObject_HEAD
-    PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
-    Py_ssize_t di_used;
-    Py_ssize_t di_pos;
-    PyObject* di_result; /* reusable result tuple for iteritems */
-    Py_ssize_t len;
-} dictiterobject;
-
-static PyObject *
-dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
-{
-    dictiterobject *di;
-    di = PyObject_GC_New(dictiterobject, itertype);
-    if (di == NULL)
-        return NULL;
-    Py_INCREF(dict);
-    di->di_dict = dict;
-    di->di_used = dict->ma_used;
-    di->di_pos = 0;
-    di->len = dict->ma_used;
-    if (itertype == &PyDictIterItem_Type) {
-        di->di_result = PyTuple_Pack(2, Py_None, Py_None);
-        if (di->di_result == NULL) {
-            Py_DECREF(di);
-            return NULL;
-        }
-    }
-    else
-        di->di_result = NULL;
-    _PyObject_GC_TRACK(di);
-    return (PyObject *)di;
-}
-
-static void
-dictiter_dealloc(dictiterobject *di)
-{
-    Py_XDECREF(di->di_dict);
-    Py_XDECREF(di->di_result);
-    PyObject_GC_Del(di);
-}
-
-static int
-dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
-{
-    Py_VISIT(di->di_dict);
-    Py_VISIT(di->di_result);
-    return 0;
-}
-
-static PyObject *
-dictiter_len(dictiterobject *di)
-{
-    Py_ssize_t len = 0;
-    if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
-        len = di->len;
-    return PyLong_FromSize_t(len);
-}
-
-PyDoc_STRVAR(length_hint_doc,
-             "Private method returning an estimate of len(list(it)).");
-
-static PyObject *
-dictiter_reduce(dictiterobject *di);
-
-PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
-
-static PyMethodDef dictiter_methods[] = {
-    {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
-     length_hint_doc},
-     {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
-     reduce_doc},
-    {NULL,              NULL}           /* sentinel */
-};
-
-static PyObject *dictiter_iternextkey(dictiterobject *di)
-{
-    PyObject *key;
-    Py_ssize_t i, mask, offset;
-    PyDictKeysObject *k;
-    PyDictObject *d = di->di_dict;
-    PyObject **value_ptr;
-
-    if (d == NULL)
-        return NULL;
-    assert (PyDict_Check(d));
-
-    if (di->di_used != d->ma_used) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "dictionary changed size during iteration");
-        di->di_used = -1; /* Make this state sticky */
-        return NULL;
-    }
-
-    i = di->di_pos;
-    if (i < 0)
-        goto fail;
-    k = d->ma_keys;
-    if (d->ma_values) {
-        value_ptr = &d->ma_values[i];
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &k->dk_entries[i].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    mask = DK_SIZE(k)-1;
-    while (i <= mask && *value_ptr == NULL) {
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-        i++;
-    }
-    di->di_pos = i+1;
-    if (i > mask)
-        goto fail;
-    di->len--;
-    key = k->dk_entries[i].me_key;
-    Py_INCREF(key);
-    return key;
-
-fail:
-    Py_DECREF(d);
-    di->di_dict = NULL;
-    return NULL;
-}
-
-PyTypeObject PyDictIterKey_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict_keyiterator",                         /* tp_name */
-    sizeof(dictiterobject),                     /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)dictiter_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)dictiter_traverse,            /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    PyObject_SelfIter,                          /* tp_iter */
-    (iternextfunc)dictiter_iternextkey,         /* tp_iternext */
-    dictiter_methods,                           /* tp_methods */
-    0,
-};
-
-static PyObject *dictiter_iternextvalue(dictiterobject *di)
-{
-    PyObject *value;
-    Py_ssize_t i, mask, offset;
-    PyDictObject *d = di->di_dict;
-    PyObject **value_ptr;
-
-    if (d == NULL)
-        return NULL;
-    assert (PyDict_Check(d));
-
-    if (di->di_used != d->ma_used) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "dictionary changed size during iteration");
-        di->di_used = -1; /* Make this state sticky */
-        return NULL;
-    }
-
-    i = di->di_pos;
-    mask = DK_SIZE(d->ma_keys)-1;
-    if (i < 0 || i > mask)
-        goto fail;
-    if (d->ma_values) {
-        value_ptr = &d->ma_values[i];
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &d->ma_keys->dk_entries[i].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    while (i <= mask && *value_ptr == NULL) {
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-        i++;
-        if (i > mask)
-            goto fail;
-    }
-    di->di_pos = i+1;
-    di->len--;
-    value = *value_ptr;
-    Py_INCREF(value);
-    return value;
-
-fail:
-    Py_DECREF(d);
-    di->di_dict = NULL;
-    return NULL;
-}
-
-PyTypeObject PyDictIterValue_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict_valueiterator",                       /* tp_name */
-    sizeof(dictiterobject),                     /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)dictiter_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)dictiter_traverse,            /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    PyObject_SelfIter,                          /* tp_iter */
-    (iternextfunc)dictiter_iternextvalue,       /* tp_iternext */
-    dictiter_methods,                           /* tp_methods */
-    0,
-};
-
-static PyObject *dictiter_iternextitem(dictiterobject *di)
-{
-    PyObject *key, *value, *result = di->di_result;
-    Py_ssize_t i, mask, offset;
-    PyDictObject *d = di->di_dict;
-    PyObject **value_ptr;
-
-    if (d == NULL)
-        return NULL;
-    assert (PyDict_Check(d));
-
-    if (di->di_used != d->ma_used) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "dictionary changed size during iteration");
-        di->di_used = -1; /* Make this state sticky */
-        return NULL;
-    }
-
-    i = di->di_pos;
-    if (i < 0)
-        goto fail;
-    mask = DK_SIZE(d->ma_keys)-1;
-    if (d->ma_values) {
-        value_ptr = &d->ma_values[i];
-        offset = sizeof(PyObject *);
-    }
-    else {
-        value_ptr = &d->ma_keys->dk_entries[i].me_value;
-        offset = sizeof(PyDictKeyEntry);
-    }
-    while (i <= mask && *value_ptr == NULL) {
-        value_ptr = (PyObject **)(((char *)value_ptr) + offset);
-        i++;
-    }
-    di->di_pos = i+1;
-    if (i > mask)
-        goto fail;
-
-    if (result->ob_refcnt == 1) {
-        Py_INCREF(result);
-        Py_DECREF(PyTuple_GET_ITEM(result, 0));
-        Py_DECREF(PyTuple_GET_ITEM(result, 1));
-    } else {
-        result = PyTuple_New(2);
-        if (result == NULL)
-            return NULL;
-    }
-    di->len--;
-    key = d->ma_keys->dk_entries[i].me_key;
-    value = *value_ptr;
-    Py_INCREF(key);
-    Py_INCREF(value);
-    PyTuple_SET_ITEM(result, 0, key);
-    PyTuple_SET_ITEM(result, 1, value);
-    return result;
-
-fail:
-    Py_DECREF(d);
-    di->di_dict = NULL;
-    return NULL;
-}
-
-PyTypeObject PyDictIterItem_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict_itemiterator",                        /* tp_name */
-    sizeof(dictiterobject),                     /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)dictiter_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)dictiter_traverse,            /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    PyObject_SelfIter,                          /* tp_iter */
-    (iternextfunc)dictiter_iternextitem,        /* tp_iternext */
-    dictiter_methods,                           /* tp_methods */
-    0,
-};
-
-
-static PyObject *
-dictiter_reduce(dictiterobject *di)
-{
-    PyObject *list;
-    dictiterobject tmp;
-
-    list = PyList_New(0);
-    if (!list)
-        return NULL;
-
-    /* copy the itertor state */
-    tmp = *di;
-    Py_XINCREF(tmp.di_dict);
-
-    /* iterate the temporary into a list */
-    for(;;) {
-        PyObject *element = 0;
-        if (Py_TYPE(di) == &PyDictIterItem_Type)
-            element = dictiter_iternextitem(&tmp);
-        else if (Py_TYPE(di) == &PyDictIterKey_Type)
-            element = dictiter_iternextkey(&tmp);
-        else if (Py_TYPE(di) == &PyDictIterValue_Type)
-            element = dictiter_iternextvalue(&tmp);
-        else
-            assert(0);
-        if (element) {
-            if (PyList_Append(list, element)) {
-                Py_DECREF(element);
-                Py_DECREF(list);
-                Py_XDECREF(tmp.di_dict);
-                return NULL;
-            }
-            Py_DECREF(element);
-        } else
-            break;
-    }
-    Py_XDECREF(tmp.di_dict);
-    /* check for error */
-    if (tmp.di_dict != NULL) {
-        /* we have an error */
-        Py_DECREF(list);
-        return NULL;
-    }
-    return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
-}
-
-/***********************************************/
-/* View objects for keys(), items(), values(). */
-/***********************************************/
-
-/* The instance lay-out is the same for all three; but the type differs. */
-
-typedef struct {
-    PyObject_HEAD
-    PyDictObject *dv_dict;
-} dictviewobject;
-
-
-static void
-dictview_dealloc(dictviewobject *dv)
-{
-    Py_XDECREF(dv->dv_dict);
-    PyObject_GC_Del(dv);
-}
-
-static int
-dictview_traverse(dictviewobject *dv, visitproc visit, void *arg)
-{
-    Py_VISIT(dv->dv_dict);
-    return 0;
-}
-
-static Py_ssize_t
-dictview_len(dictviewobject *dv)
-{
-    Py_ssize_t len = 0;
-    if (dv->dv_dict != NULL)
-        len = dv->dv_dict->ma_used;
-    return len;
-}
-
-static PyObject *
-dictview_new(PyObject *dict, PyTypeObject *type)
-{
-    dictviewobject *dv;
-    if (dict == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    if (!PyDict_Check(dict)) {
-        /* XXX Get rid of this restriction later */
-        PyErr_Format(PyExc_TypeError,
-                     "%s() requires a dict argument, not '%s'",
-                     type->tp_name, dict->ob_type->tp_name);
-        return NULL;
-    }
-    dv = PyObject_GC_New(dictviewobject, type);
-    if (dv == NULL)
-        return NULL;
-    Py_INCREF(dict);
-    dv->dv_dict = (PyDictObject *)dict;
-    _PyObject_GC_TRACK(dv);
-    return (PyObject *)dv;
-}
-
-/* TODO(guido): The views objects are not complete:
-
- * support more set operations
- * support arbitrary mappings?
-   - either these should be static or exported in dictobject.h
-   - if public then they should probably be in builtins
-*/
-
-/* Return 1 if self is a subset of other, iterating over self;
-   0 if not; -1 if an error occurred. */
-static int
-all_contained_in(PyObject *self, PyObject *other)
-{
-    PyObject *iter = PyObject_GetIter(self);
-    int ok = 1;
-
-    if (iter == NULL)
-        return -1;
-    for (;;) {
-        PyObject *next = PyIter_Next(iter);
-        if (next == NULL) {
-            if (PyErr_Occurred())
-                ok = -1;
-            break;
-        }
-        ok = PySequence_Contains(other, next);
-        Py_DECREF(next);
-        if (ok <= 0)
-            break;
-    }
-    Py_DECREF(iter);
-    return ok;
-}
-
-static PyObject *
-dictview_richcompare(PyObject *self, PyObject *other, int op)
-{
-    Py_ssize_t len_self, len_other;
-    int ok;
-    PyObject *result;
-
-    assert(self != NULL);
-    assert(PyDictViewSet_Check(self));
-    assert(other != NULL);
-
-    if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    len_self = PyObject_Size(self);
-    if (len_self < 0)
-        return NULL;
-    len_other = PyObject_Size(other);
-    if (len_other < 0)
-        return NULL;
-
-    ok = 0;
-    switch(op) {
-
-    case Py_NE:
-    case Py_EQ:
-        if (len_self == len_other)
-            ok = all_contained_in(self, other);
-        if (op == Py_NE && ok >= 0)
-            ok = !ok;
-        break;
-
-    case Py_LT:
-        if (len_self < len_other)
-            ok = all_contained_in(self, other);
-        break;
-
-      case Py_LE:
-          if (len_self <= len_other)
-              ok = all_contained_in(self, other);
-          break;
-
-    case Py_GT:
-        if (len_self > len_other)
-            ok = all_contained_in(other, self);
-        break;
-
-    case Py_GE:
-        if (len_self >= len_other)
-            ok = all_contained_in(other, self);
-        break;
-
-    }
-    if (ok < 0)
-        return NULL;
-    result = ok ? Py_True : Py_False;
-    Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-dictview_repr(dictviewobject *dv)
-{
-    PyObject *seq;
-    PyObject *result;
-
-    seq = PySequence_List((PyObject *)dv);
-    if (seq == NULL)
-        return NULL;
-
-    result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
-    Py_DECREF(seq);
-    return result;
-}
-
-/*** dict_keys ***/
-
-static PyObject *
-dictkeys_iter(dictviewobject *dv)
-{
-    if (dv->dv_dict == NULL) {
-        Py_RETURN_NONE;
-    }
-    return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
-}
-
-static int
-dictkeys_contains(dictviewobject *dv, PyObject *obj)
-{
-    if (dv->dv_dict == NULL)
-        return 0;
-    return PyDict_Contains((PyObject *)dv->dv_dict, obj);
-}
-
-static PySequenceMethods dictkeys_as_sequence = {
-    (lenfunc)dictview_len,              /* sq_length */
-    0,                                  /* sq_concat */
-    0,                                  /* sq_repeat */
-    0,                                  /* sq_item */
-    0,                                  /* sq_slice */
-    0,                                  /* sq_ass_item */
-    0,                                  /* sq_ass_slice */
-    (objobjproc)dictkeys_contains,      /* sq_contains */
-};
-
-static PyObject*
-dictviews_sub(PyObject* self, PyObject *other)
-{
-    PyObject *result = PySet_New(self);
-    PyObject *tmp;
-    _Py_IDENTIFIER(difference_update);
-
-    if (result == NULL)
-        return NULL;
-
-    tmp = _PyObject_CallMethodId(result, &PyId_difference_update, "O", other);
-    if (tmp == NULL) {
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    Py_DECREF(tmp);
-    return result;
-}
-
-static PyObject*
-dictviews_and(PyObject* self, PyObject *other)
-{
-    PyObject *result = PySet_New(self);
-    PyObject *tmp;
-    _Py_IDENTIFIER(intersection_update);
-
-    if (result == NULL)
-        return NULL;
-
-    tmp = _PyObject_CallMethodId(result, &PyId_intersection_update, "O", other);
-    if (tmp == NULL) {
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    Py_DECREF(tmp);
-    return result;
-}
-
-static PyObject*
-dictviews_or(PyObject* self, PyObject *other)
-{
-    PyObject *result = PySet_New(self);
-    PyObject *tmp;
-    _Py_IDENTIFIER(update);
-
-    if (result == NULL)
-        return NULL;
-
-    tmp = _PyObject_CallMethodId(result, &PyId_update, "O", other);
-    if (tmp == NULL) {
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    Py_DECREF(tmp);
-    return result;
-}
-
-static PyObject*
-dictviews_xor(PyObject* self, PyObject *other)
-{
-    PyObject *result = PySet_New(self);
-    PyObject *tmp;
-    _Py_IDENTIFIER(symmetric_difference_update);
-
-    if (result == NULL)
-        return NULL;
-
-    tmp = _PyObject_CallMethodId(result, &PyId_symmetric_difference_update, "O",
-                              other);
-    if (tmp == NULL) {
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    Py_DECREF(tmp);
-    return result;
-}
-
-static PyNumberMethods dictviews_as_number = {
-    0,                                  /*nb_add*/
-    (binaryfunc)dictviews_sub,          /*nb_subtract*/
-    0,                                  /*nb_multiply*/
-    0,                                  /*nb_remainder*/
-    0,                                  /*nb_divmod*/
-    0,                                  /*nb_power*/
-    0,                                  /*nb_negative*/
-    0,                                  /*nb_positive*/
-    0,                                  /*nb_absolute*/
-    0,                                  /*nb_bool*/
-    0,                                  /*nb_invert*/
-    0,                                  /*nb_lshift*/
-    0,                                  /*nb_rshift*/
-    (binaryfunc)dictviews_and,          /*nb_and*/
-    (binaryfunc)dictviews_xor,          /*nb_xor*/
-    (binaryfunc)dictviews_or,           /*nb_or*/
-};
-
-static PyObject*
-dictviews_isdisjoint(PyObject *self, PyObject *other)
-{
-    PyObject *it;
-    PyObject *item = NULL;
-
-    if (self == other) {
-        if (dictview_len((dictviewobject *)self) == 0)
-            Py_RETURN_TRUE;
-        else
-            Py_RETURN_FALSE;
-    }
-
-    /* Iterate over the shorter object (only if other is a set,
-     * because PySequence_Contains may be expensive otherwise): */
-    if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
-        Py_ssize_t len_self = dictview_len((dictviewobject *)self);
-        Py_ssize_t len_other = PyObject_Size(other);
-        if (len_other == -1)
-            return NULL;
-
-        if ((len_other > len_self)) {
-            PyObject *tmp = other;
-            other = self;
-            self = tmp;
-        }
-    }
-
-    it = PyObject_GetIter(other);
-    if (it == NULL)
-        return NULL;
-
-    while ((item = PyIter_Next(it)) != NULL) {
-        int contains = PySequence_Contains(self, item);
-        Py_DECREF(item);
-        if (contains == -1) {
-            Py_DECREF(it);
-            return NULL;
-        }
-
-        if (contains) {
-            Py_DECREF(it);
-            Py_RETURN_FALSE;
-        }
-    }
-    Py_DECREF(it);
-    if (PyErr_Occurred())
-        return NULL; /* PyIter_Next raised an exception. */
-    Py_RETURN_TRUE;
-}
-
-PyDoc_STRVAR(isdisjoint_doc,
-"Return True if the view and the given iterable have a null intersection.");
-
-static PyMethodDef dictkeys_methods[] = {
-    {"isdisjoint",      (PyCFunction)dictviews_isdisjoint,  METH_O,
-     isdisjoint_doc},
-    {NULL,              NULL}           /* sentinel */
-};
-
-PyTypeObject PyDictKeys_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict_keys",                                /* tp_name */
-    sizeof(dictviewobject),                     /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)dictview_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)dictview_repr,                    /* tp_repr */
-    &dictviews_as_number,                       /* tp_as_number */
-    &dictkeys_as_sequence,                      /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)dictview_traverse,            /* tp_traverse */
-    0,                                          /* tp_clear */
-    dictview_richcompare,                       /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    (getiterfunc)dictkeys_iter,                 /* tp_iter */
-    0,                                          /* tp_iternext */
-    dictkeys_methods,                           /* tp_methods */
-    0,
-};
-
-static PyObject *
-dictkeys_new(PyObject *dict)
-{
-    return dictview_new(dict, &PyDictKeys_Type);
-}
-
-/*** dict_items ***/
-
-static PyObject *
-dictitems_iter(dictviewobject *dv)
-{
-    if (dv->dv_dict == NULL) {
-        Py_RETURN_NONE;
-    }
-    return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
-}
-
-static int
-dictitems_contains(dictviewobject *dv, PyObject *obj)
-{
-    PyObject *key, *value, *found;
-    if (dv->dv_dict == NULL)
-        return 0;
-    if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
-        return 0;
-    key = PyTuple_GET_ITEM(obj, 0);
-    value = PyTuple_GET_ITEM(obj, 1);
-    found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
-    if (found == NULL) {
-        if (PyErr_Occurred())
-            return -1;
-        return 0;
-    }
-    return PyObject_RichCompareBool(value, found, Py_EQ);
-}
-
-static PySequenceMethods dictitems_as_sequence = {
-    (lenfunc)dictview_len,              /* sq_length */
-    0,                                  /* sq_concat */
-    0,                                  /* sq_repeat */
-    0,                                  /* sq_item */
-    0,                                  /* sq_slice */
-    0,                                  /* sq_ass_item */
-    0,                                  /* sq_ass_slice */
-    (objobjproc)dictitems_contains,     /* sq_contains */
-};
-
-static PyMethodDef dictitems_methods[] = {
-    {"isdisjoint",      (PyCFunction)dictviews_isdisjoint,  METH_O,
-     isdisjoint_doc},
-    {NULL,              NULL}           /* sentinel */
-};
-
-PyTypeObject PyDictItems_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict_items",                               /* tp_name */
-    sizeof(dictviewobject),                     /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)dictview_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)dictview_repr,                    /* tp_repr */
-    &dictviews_as_number,                       /* tp_as_number */
-    &dictitems_as_sequence,                     /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)dictview_traverse,            /* tp_traverse */
-    0,                                          /* tp_clear */
-    dictview_richcompare,                       /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    (getiterfunc)dictitems_iter,                /* tp_iter */
-    0,                                          /* tp_iternext */
-    dictitems_methods,                          /* tp_methods */
-    0,
-};
-
-static PyObject *
-dictitems_new(PyObject *dict)
-{
-    return dictview_new(dict, &PyDictItems_Type);
-}
-
-/*** dict_values ***/
-
-static PyObject *
-dictvalues_iter(dictviewobject *dv)
-{
-    if (dv->dv_dict == NULL) {
-        Py_RETURN_NONE;
-    }
-    return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
-}
-
-static PySequenceMethods dictvalues_as_sequence = {
-    (lenfunc)dictview_len,              /* sq_length */
-    0,                                  /* sq_concat */
-    0,                                  /* sq_repeat */
-    0,                                  /* sq_item */
-    0,                                  /* sq_slice */
-    0,                                  /* sq_ass_item */
-    0,                                  /* sq_ass_slice */
-    (objobjproc)0,                      /* sq_contains */
-};
-
-static PyMethodDef dictvalues_methods[] = {
-    {NULL,              NULL}           /* sentinel */
-};
-
-PyTypeObject PyDictValues_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "dict_values",                              /* tp_name */
-    sizeof(dictviewobject),                     /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)dictview_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)dictview_repr,                    /* tp_repr */
-    0,                                          /* tp_as_number */
-    &dictvalues_as_sequence,                    /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                                          /* tp_doc */
-    (traverseproc)dictview_traverse,            /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    (getiterfunc)dictvalues_iter,               /* tp_iter */
-    0,                                          /* tp_iternext */
-    dictvalues_methods,                         /* tp_methods */
-    0,
-};
-
-static PyObject *
-dictvalues_new(PyObject *dict)
-{
-    return dictview_new(dict, &PyDictValues_Type);
-}
-
-/* Returns NULL if cannot allocate a new PyDictKeysObject,
-   but does not set an error */
-PyDictKeysObject *
-_PyDict_NewKeysForClass(void)
-{
-    PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE_SPLIT);
-    if (keys == NULL)
-        PyErr_Clear();
-    else
-        keys->dk_lookup = lookdict_split;
-    return keys;
-}
-
-#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
-
-PyObject *
-PyObject_GenericGetDict(PyObject *obj, void *context)
-{
-    PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
-    if (dictptr == NULL) {
-        PyErr_SetString(PyExc_AttributeError,
-                        "This object has no __dict__");
-        return NULL;
-    }
-    dict = *dictptr;
-    if (dict == NULL) {
-        PyTypeObject *tp = Py_TYPE(obj);
-        if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
-            DK_INCREF(CACHED_KEYS(tp));
-            *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
-        }
-        else {
-            *dictptr = dict = PyDict_New();
-        }
-    }
-    Py_XINCREF(dict);
-    return dict;
-}
-
-int
-_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
-                     PyObject *key, PyObject *value)
-{
-    PyObject *dict;
-    int res;
-    PyDictKeysObject *cached;
-
-    assert(dictptr != NULL);
-    if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
-        assert(dictptr != NULL);
-        dict = *dictptr;
-        if (dict == NULL) {
-            DK_INCREF(cached);
-            dict = new_dict_with_shared_keys(cached);
-            if (dict == NULL)
-                return -1;
-            *dictptr = dict;
-        }
-        if (value == NULL) {
-            res = PyDict_DelItem(dict, key);
-            if (cached != ((PyDictObject *)dict)->ma_keys) {
-                CACHED_KEYS(tp) = NULL;
-                DK_DECREF(cached);
-            }
-        } else {
-            res = PyDict_SetItem(dict, key, value);
-            if (cached != ((PyDictObject *)dict)->ma_keys) {
-                /* Either update tp->ht_cached_keys or delete it */
-                if (cached->dk_refcnt == 1) {
-                    CACHED_KEYS(tp) = make_keys_shared(dict);
-                } else {
-                    CACHED_KEYS(tp) = NULL;
-                }
-                DK_DECREF(cached);
-                if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
-                    return -1;
-            }
-        }
-    } else {
-        dict = *dictptr;
-        if (dict == NULL) {
-            dict = PyDict_New();
-            if (dict == NULL)
-                return -1;
-            *dictptr = dict;
-        }
-        if (value == NULL) {
-            res = PyDict_DelItem(dict, key);
-        } else {
-            res = PyDict_SetItem(dict, key, value);
-        }
-    }
-    return res;
-}
-
-void
-_PyDictKeys_DecRef(PyDictKeysObject *keys)
-{
-    DK_DECREF(keys);
-}
-
-
-/* ARGSUSED */
-static PyObject *
-dummy_repr(PyObject *op)
-{
-    return PyUnicode_FromString("<dummy key>");
-}
-
-/* ARGUSED */
-static void
-dummy_dealloc(PyObject* ignore)
-{
-    /* This should never get called, but we also don't want to SEGV if
-     * we accidentally decref dummy-key out of existence.
-     */
-    Py_FatalError("deallocating <dummy key>");
-}
-
-static PyTypeObject PyDictDummy_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "<dummy key> type",
-    0,
-    0,
-    dummy_dealloc,      /*tp_dealloc*/ /*never called*/
-    0,                  /*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_reserved*/
-    dummy_repr,         /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash */
-    0,                  /*tp_call */
-    0,                  /*tp_str */
-    0,                  /*tp_getattro */
-    0,                  /*tp_setattro */
-    0,                  /*tp_as_buffer */
-    Py_TPFLAGS_DEFAULT, /*tp_flags */
-};
-
-static PyObject _dummy_struct = {
-  _PyObject_EXTRA_INIT
-  2, &PyDictDummy_Type
-};
-
+/*[clinic end generated code: output=fe74d676332fdba6 input=a9049054013a1b77]*/
diff --git a/Objects/unicodeobject.c b/Objects/clinic/unicodeobject.c.h
copy from Objects/unicodeobject.c
copy to Objects/clinic/unicodeobject.c.h
--- a/Objects/unicodeobject.c
+++ b/Objects/clinic/unicodeobject.c.h
@@ -1,12958 +1,5 @@
-/*
-
-Unicode implementation based on original code by Fredrik Lundh,
-modified by Marc-Andre Lemburg <mal at lemburg.com>.
-
-Major speed upgrades to the method implementations at the Reykjavik
-NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
-
-Copyright (c) Corporation for National Research Initiatives.
-
---------------------------------------------------------------------
-The original string type implementation is:
-
-  Copyright (c) 1999 by Secret Labs AB
-  Copyright (c) 1999 by Fredrik Lundh
-
-By obtaining, using, and/or copying this software and/or its
-associated documentation, you agree that you have read, understood,
-and will comply with the following terms and conditions:
-
-Permission to use, copy, modify, and distribute this software and its
-associated documentation for any purpose and without fee is hereby
-granted, provided that the above copyright notice appears in all
-copies, and that both that copyright notice and this permission notice
-appear in supporting documentation, and that the name of Secret Labs
-AB or the author not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
-THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
-OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------
-
-*/
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-#include "ucnhash.h"
-#include "bytes_methods.h"
-
-#ifdef MS_WINDOWS
-#include <windows.h>
-#endif
-
 /*[clinic input]
-class str "PyUnicodeObject *" "&PyUnicode_Type"
-[clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
-
-/* --- Globals ------------------------------------------------------------
-
-NOTE: In the interpreter's initialization phase, some globals are currently
-      initialized dynamically as needed. In the process Unicode objects may
-      be created before the Unicode type is ready.
-
-*/
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
-#define MAX_UNICODE 0x10ffff
-
-#ifdef Py_DEBUG
-#  define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
-#else
-#  define _PyUnicode_CHECK(op) PyUnicode_Check(op)
-#endif
-
-#define _PyUnicode_UTF8(op)                             \
-    (((PyCompactUnicodeObject*)(op))->utf8)
-#define PyUnicode_UTF8(op)                              \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     assert(PyUnicode_IS_READY(op)),                    \
-     PyUnicode_IS_COMPACT_ASCII(op) ?                   \
-         ((char*)((PyASCIIObject*)(op) + 1)) :          \
-         _PyUnicode_UTF8(op))
-#define _PyUnicode_UTF8_LENGTH(op)                      \
-    (((PyCompactUnicodeObject*)(op))->utf8_length)
-#define PyUnicode_UTF8_LENGTH(op)                       \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     assert(PyUnicode_IS_READY(op)),                    \
-     PyUnicode_IS_COMPACT_ASCII(op) ?                   \
-         ((PyASCIIObject*)(op))->length :               \
-         _PyUnicode_UTF8_LENGTH(op))
-#define _PyUnicode_WSTR(op)                             \
-    (((PyASCIIObject*)(op))->wstr)
-#define _PyUnicode_WSTR_LENGTH(op)                      \
-    (((PyCompactUnicodeObject*)(op))->wstr_length)
-#define _PyUnicode_LENGTH(op)                           \
-    (((PyASCIIObject *)(op))->length)
-#define _PyUnicode_STATE(op)                            \
-    (((PyASCIIObject *)(op))->state)
-#define _PyUnicode_HASH(op)                             \
-    (((PyASCIIObject *)(op))->hash)
-#define _PyUnicode_KIND(op)                             \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     ((PyASCIIObject *)(op))->state.kind)
-#define _PyUnicode_GET_LENGTH(op)                       \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     ((PyASCIIObject *)(op))->length)
-#define _PyUnicode_DATA_ANY(op)                         \
-    (((PyUnicodeObject*)(op))->data.any)
-
-#undef PyUnicode_READY
-#define PyUnicode_READY(op)                             \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     (PyUnicode_IS_READY(op) ?                          \
-      0 :                                               \
-      _PyUnicode_Ready(op)))
-
-#define _PyUnicode_SHARE_UTF8(op)                       \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     assert(!PyUnicode_IS_COMPACT_ASCII(op)),           \
-     (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
-#define _PyUnicode_SHARE_WSTR(op)                       \
-    (assert(_PyUnicode_CHECK(op)),                      \
-     (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
-
-/* true if the Unicode object has an allocated UTF-8 memory block
-   (not shared with other data) */
-#define _PyUnicode_HAS_UTF8_MEMORY(op)                  \
-    ((!PyUnicode_IS_COMPACT_ASCII(op)                   \
-      && _PyUnicode_UTF8(op)                            \
-      && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
-
-/* true if the Unicode object has an allocated wstr memory block
-   (not shared with other data) */
-#define _PyUnicode_HAS_WSTR_MEMORY(op)                  \
-    ((_PyUnicode_WSTR(op) &&                            \
-      (!PyUnicode_IS_READY(op) ||                       \
-       _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
-
-/* Generic helper macro to convert characters of different types.
-   from_type and to_type have to be valid type names, begin and end
-   are pointers to the source characters which should be of type
-   "from_type *".  to is a pointer of type "to_type *" and points to the
-   buffer where the result characters are written to. */
-#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
-    do {                                                \
-        to_type *_to = (to_type *)(to);                \
-        const from_type *_iter = (from_type *)(begin);  \
-        const from_type *_end = (from_type *)(end);     \
-        Py_ssize_t n = (_end) - (_iter);                \
-        const from_type *_unrolled_end =                \
-            _iter + _Py_SIZE_ROUND_DOWN(n, 4);          \
-        while (_iter < (_unrolled_end)) {               \
-            _to[0] = (to_type) _iter[0];                \
-            _to[1] = (to_type) _iter[1];                \
-            _to[2] = (to_type) _iter[2];                \
-            _to[3] = (to_type) _iter[3];                \
-            _iter += 4; _to += 4;                       \
-        }                                               \
-        while (_iter < (_end))                          \
-            *_to++ = (to_type) *_iter++;                \
-    } while (0)
-
-/* This dictionary holds all interned unicode strings.  Note that references
-   to strings in this dictionary are *not* counted in the string's ob_refcnt.
-   When the interned string reaches a refcnt of 0 the string deallocation
-   function will delete the reference from this dictionary.
-
-   Another way to look at this is that to say that the actual reference
-   count of a string is:  s->ob_refcnt + (s->state ? 2 : 0)
-*/
-static PyObject *interned = NULL;
-
-/* The empty Unicode object is shared to improve performance. */
-static PyObject *unicode_empty = NULL;
-
-#define _Py_INCREF_UNICODE_EMPTY()                      \
-    do {                                                \
-        if (unicode_empty != NULL)                      \
-            Py_INCREF(unicode_empty);                   \
-        else {                                          \
-            unicode_empty = PyUnicode_New(0, 0);        \
-            if (unicode_empty != NULL) {                \
-                Py_INCREF(unicode_empty);               \
-                assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
-            }                                           \
-        }                                               \
-    } while (0)
-
-#define _Py_RETURN_UNICODE_EMPTY()                      \
-    do {                                                \
-        _Py_INCREF_UNICODE_EMPTY();                     \
-        return unicode_empty;                           \
-    } while (0)
-
-/* Forward declaration */
-Py_LOCAL_INLINE(int)
-_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
-
-/* List of static strings. */
-static _Py_Identifier *static_strings = NULL;
-
-/* Single character Unicode strings in the Latin-1 range are being
-   shared as well. */
-static PyObject *unicode_latin1[256] = {NULL};
-
-/* Fast detection of the most frequent whitespace characters */
-const unsigned char _Py_ascii_whitespace[] = {
-    0, 0, 0, 0, 0, 0, 0, 0,
-/*     case 0x0009: * CHARACTER TABULATION */
-/*     case 0x000A: * LINE FEED */
-/*     case 0x000B: * LINE TABULATION */
-/*     case 0x000C: * FORM FEED */
-/*     case 0x000D: * CARRIAGE RETURN */
-    0, 1, 1, 1, 1, 1, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-/*     case 0x001C: * FILE SEPARATOR */
-/*     case 0x001D: * GROUP SEPARATOR */
-/*     case 0x001E: * RECORD SEPARATOR */
-/*     case 0x001F: * UNIT SEPARATOR */
-    0, 0, 0, 0, 1, 1, 1, 1,
-/*     case 0x0020: * SPACE */
-    1, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0
-};
-
-/* forward */
-static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
-static PyObject* get_latin1_char(unsigned char ch);
-static int unicode_modifiable(PyObject *unicode);
-
-
-static PyObject *
-_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
-static PyObject *
-_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
-static PyObject *
-_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
-
-static PyObject *
-unicode_encode_call_errorhandler(const char *errors,
-       PyObject **errorHandler,const char *encoding, const char *reason,
-       PyObject *unicode, PyObject **exceptionObject,
-       Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
-
-static void
-raise_encode_exception(PyObject **exceptionObject,
-                       const char *encoding,
-                       PyObject *unicode,
-                       Py_ssize_t startpos, Py_ssize_t endpos,
-                       const char *reason);
-
-/* Same for linebreaks */
-static unsigned char ascii_linebreak[] = {
-    0, 0, 0, 0, 0, 0, 0, 0,
-/*         0x000A, * LINE FEED */
-/*         0x000B, * LINE TABULATION */
-/*         0x000C, * FORM FEED */
-/*         0x000D, * CARRIAGE RETURN */
-    0, 0, 1, 1, 1, 1, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-/*         0x001C, * FILE SEPARATOR */
-/*         0x001D, * GROUP SEPARATOR */
-/*         0x001E, * RECORD SEPARATOR */
-    0, 0, 0, 0, 1, 1, 1, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0
-};
-
-/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
-   This function is kept for backward compatibility with the old API. */
-Py_UNICODE
-PyUnicode_GetMax(void)
-{
-#ifdef Py_UNICODE_WIDE
-    return 0x10FFFF;
-#else
-    /* This is actually an illegal character, so it should
-       not be passed to unichr. */
-    return 0xFFFF;
-#endif
-}
-
-#ifdef Py_DEBUG
-int
-_PyUnicode_CheckConsistency(PyObject *op, int check_content)
-{
-    PyASCIIObject *ascii;
-    unsigned int kind;
-
-    assert(PyUnicode_Check(op));
-
-    ascii = (PyASCIIObject *)op;
-    kind = ascii->state.kind;
-
-    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
-        assert(kind == PyUnicode_1BYTE_KIND);
-        assert(ascii->state.ready == 1);
-    }
-    else {
-        PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
-        void *data;
-
-        if (ascii->state.compact == 1) {
-            data = compact + 1;
-            assert(kind == PyUnicode_1BYTE_KIND
-                   || kind == PyUnicode_2BYTE_KIND
-                   || kind == PyUnicode_4BYTE_KIND);
-            assert(ascii->state.ascii == 0);
-            assert(ascii->state.ready == 1);
-            assert (compact->utf8 != data);
-        }
-        else {
-            PyUnicodeObject *unicode = (PyUnicodeObject *)op;
-
-            data = unicode->data.any;
-            if (kind == PyUnicode_WCHAR_KIND) {
-                assert(ascii->length == 0);
-                assert(ascii->hash == -1);
-                assert(ascii->state.compact == 0);
-                assert(ascii->state.ascii == 0);
-                assert(ascii->state.ready == 0);
-                assert(ascii->state.interned == SSTATE_NOT_INTERNED);
-                assert(ascii->wstr != NULL);
-                assert(data == NULL);
-                assert(compact->utf8 == NULL);
-            }
-            else {
-                assert(kind == PyUnicode_1BYTE_KIND
-                       || kind == PyUnicode_2BYTE_KIND
-                       || kind == PyUnicode_4BYTE_KIND);
-                assert(ascii->state.compact == 0);
-                assert(ascii->state.ready == 1);
-                assert(data != NULL);
-                if (ascii->state.ascii) {
-                    assert (compact->utf8 == data);
-                    assert (compact->utf8_length == ascii->length);
-                }
-                else
-                    assert (compact->utf8 != data);
-            }
-        }
-        if (kind != PyUnicode_WCHAR_KIND) {
-            if (
-#if SIZEOF_WCHAR_T == 2
-                kind == PyUnicode_2BYTE_KIND
-#else
-                kind == PyUnicode_4BYTE_KIND
-#endif
-               )
-            {
-                assert(ascii->wstr == data);
-                assert(compact->wstr_length == ascii->length);
-            } else
-                assert(ascii->wstr != data);
-        }
-
-        if (compact->utf8 == NULL)
-            assert(compact->utf8_length == 0);
-        if (ascii->wstr == NULL)
-            assert(compact->wstr_length == 0);
-    }
-    /* check that the best kind is used */
-    if (check_content && kind != PyUnicode_WCHAR_KIND)
-    {
-        Py_ssize_t i;
-        Py_UCS4 maxchar = 0;
-        void *data;
-        Py_UCS4 ch;
-
-        data = PyUnicode_DATA(ascii);
-        for (i=0; i < ascii->length; i++)
-        {
-            ch = PyUnicode_READ(kind, data, i);
-            if (ch > maxchar)
-                maxchar = ch;
-        }
-        if (kind == PyUnicode_1BYTE_KIND) {
-            if (ascii->state.ascii == 0) {
-                assert(maxchar >= 128);
-                assert(maxchar <= 255);
-            }
-            else
-                assert(maxchar < 128);
-        }
-        else if (kind == PyUnicode_2BYTE_KIND) {
-            assert(maxchar >= 0x100);
-            assert(maxchar <= 0xFFFF);
-        }
-        else {
-            assert(maxchar >= 0x10000);
-            assert(maxchar <= MAX_UNICODE);
-        }
-        assert(PyUnicode_READ(kind, data, ascii->length) == 0);
-    }
-    return 1;
-}
-#endif
-
-static PyObject*
-unicode_result_wchar(PyObject *unicode)
-{
-#ifndef Py_DEBUG
-    Py_ssize_t len;
-
-    len = _PyUnicode_WSTR_LENGTH(unicode);
-    if (len == 0) {
-        Py_DECREF(unicode);
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-    if (len == 1) {
-        wchar_t ch = _PyUnicode_WSTR(unicode)[0];
-        if ((Py_UCS4)ch < 256) {
-            PyObject *latin1_char = get_latin1_char((unsigned char)ch);
-            Py_DECREF(unicode);
-            return latin1_char;
-        }
-    }
-
-    if (_PyUnicode_Ready(unicode) < 0) {
-        Py_DECREF(unicode);
-        return NULL;
-    }
-#else
-    assert(Py_REFCNT(unicode) == 1);
-
-    /* don't make the result ready in debug mode to ensure that the caller
-       makes the string ready before using it */
-    assert(_PyUnicode_CheckConsistency(unicode, 1));
-#endif
-    return unicode;
-}
-
-static PyObject*
-unicode_result_ready(PyObject *unicode)
-{
-    Py_ssize_t length;
-
-    length = PyUnicode_GET_LENGTH(unicode);
-    if (length == 0) {
-        if (unicode != unicode_empty) {
-            Py_DECREF(unicode);
-            _Py_RETURN_UNICODE_EMPTY();
-        }
-        return unicode_empty;
-    }
-
-    if (length == 1) {
-        void *data = PyUnicode_DATA(unicode);
-        int kind = PyUnicode_KIND(unicode);
-        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
-        if (ch < 256) {
-            PyObject *latin1_char = unicode_latin1[ch];
-            if (latin1_char != NULL) {
-                if (unicode != latin1_char) {
-                    Py_INCREF(latin1_char);
-                    Py_DECREF(unicode);
-                }
-                return latin1_char;
-            }
-            else {
-                assert(_PyUnicode_CheckConsistency(unicode, 1));
-                Py_INCREF(unicode);
-                unicode_latin1[ch] = unicode;
-                return unicode;
-            }
-        }
-    }
-
-    assert(_PyUnicode_CheckConsistency(unicode, 1));
-    return unicode;
-}
-
-static PyObject*
-unicode_result(PyObject *unicode)
-{
-    assert(_PyUnicode_CHECK(unicode));
-    if (PyUnicode_IS_READY(unicode))
-        return unicode_result_ready(unicode);
-    else
-        return unicode_result_wchar(unicode);
-}
-
-static PyObject*
-unicode_result_unchanged(PyObject *unicode)
-{
-    if (PyUnicode_CheckExact(unicode)) {
-        if (PyUnicode_READY(unicode) == -1)
-            return NULL;
-        Py_INCREF(unicode);
-        return unicode;
-    }
-    else
-        /* Subtype -- return genuine unicode string with the same value. */
-        return _PyUnicode_Copy(unicode);
-}
-
-/* --- Bloom Filters ----------------------------------------------------- */
-
-/* stuff to implement simple "bloom filters" for Unicode characters.
-   to keep things simple, we use a single bitmask, using the least 5
-   bits from each unicode characters as the bit index. */
-
-/* the linebreak mask is set up by Unicode_Init below */
-
-#if LONG_BIT >= 128
-#define BLOOM_WIDTH 128
-#elif LONG_BIT >= 64
-#define BLOOM_WIDTH 64
-#elif LONG_BIT >= 32
-#define BLOOM_WIDTH 32
-#else
-#error "LONG_BIT is smaller than 32"
-#endif
-
-#define BLOOM_MASK unsigned long
-
-static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
-
-#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
-
-#define BLOOM_LINEBREAK(ch)                                             \
-    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
-     (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
-
-Py_LOCAL_INLINE(BLOOM_MASK)
-make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
-{
-#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
-    do {                                               \
-        TYPE *data = (TYPE *)PTR;                      \
-        TYPE *end = data + LEN;                        \
-        Py_UCS4 ch;                                    \
-        for (; data != end; data++) {                  \
-            ch = *data;                                \
-            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
-        }                                              \
-        break;                                         \
-    } while (0)
-
-    /* calculate simple bloom-style bitmask for a given unicode string */
-
-    BLOOM_MASK mask;
-
-    mask = 0;
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
-        break;
-    default:
-        assert(0);
-    }
-    return mask;
-
-#undef BLOOM_UPDATE
-}
-
-/* Compilation of templated routines */
-
-#include "stringlib/asciilib.h"
-#include "stringlib/fastsearch.h"
-#include "stringlib/partition.h"
-#include "stringlib/split.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/find_max_char.h"
-#include "stringlib/localeutil.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/ucs1lib.h"
-#include "stringlib/fastsearch.h"
-#include "stringlib/partition.h"
-#include "stringlib/split.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/replace.h"
-#include "stringlib/find_max_char.h"
-#include "stringlib/localeutil.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/ucs2lib.h"
-#include "stringlib/fastsearch.h"
-#include "stringlib/partition.h"
-#include "stringlib/split.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/replace.h"
-#include "stringlib/find_max_char.h"
-#include "stringlib/localeutil.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/ucs4lib.h"
-#include "stringlib/fastsearch.h"
-#include "stringlib/partition.h"
-#include "stringlib/split.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/replace.h"
-#include "stringlib/find_max_char.h"
-#include "stringlib/localeutil.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/unicodedefs.h"
-#include "stringlib/fastsearch.h"
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/undef.h"
-
-/* --- Unicode Object ----------------------------------------------------- */
-
-static PyObject *
-fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
-
-Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
-                                     Py_ssize_t size, Py_UCS4 ch,
-                                     int direction)
-{
-    int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
-
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        {
-            Py_UCS1 ch1 = (Py_UCS1) ch;
-            if (ch1 == ch)
-                return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
-            else
-                return -1;
-        }
-    case PyUnicode_2BYTE_KIND:
-        {
-            Py_UCS2 ch2 = (Py_UCS2) ch;
-            if (ch2 == ch)
-                return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
-            else
-                return -1;
-        }
-    case PyUnicode_4BYTE_KIND:
-        return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
-    default:
-        assert(0);
-        return -1;
-    }
-}
-
-#ifdef Py_DEBUG
-/* Fill the data of an Unicode string with invalid characters to detect bugs
-   earlier.
-
-   _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
-   ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
-   invalid character in Unicode 6.0. */
-static void
-unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
-{
-    int kind = PyUnicode_KIND(unicode);
-    Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
-    Py_ssize_t length = _PyUnicode_LENGTH(unicode);
-    if (length <= old_length)
-        return;
-    memset(data + old_length * kind, 0xff, (length - old_length) * kind);
-}
-#endif
-
-static PyObject*
-resize_compact(PyObject *unicode, Py_ssize_t length)
-{
-    Py_ssize_t char_size;
-    Py_ssize_t struct_size;
-    Py_ssize_t new_size;
-    int share_wstr;
-    PyObject *new_unicode;
-#ifdef Py_DEBUG
-    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
-#endif
-
-    assert(unicode_modifiable(unicode));
-    assert(PyUnicode_IS_READY(unicode));
-    assert(PyUnicode_IS_COMPACT(unicode));
-
-    char_size = PyUnicode_KIND(unicode);
-    if (PyUnicode_IS_ASCII(unicode))
-        struct_size = sizeof(PyASCIIObject);
-    else
-        struct_size = sizeof(PyCompactUnicodeObject);
-    share_wstr = _PyUnicode_SHARE_WSTR(unicode);
-
-    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    new_size = (struct_size + (length + 1) * char_size);
-
-    _Py_DEC_REFTOTAL;
-    _Py_ForgetReference(unicode);
-
-    new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
-    if (new_unicode == NULL) {
-        _Py_NewReference(unicode);
-        PyErr_NoMemory();
-        return NULL;
-    }
-    unicode = new_unicode;
-    _Py_NewReference(unicode);
-
-    _PyUnicode_LENGTH(unicode) = length;
-    if (share_wstr) {
-        _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
-        if (!PyUnicode_IS_ASCII(unicode))
-            _PyUnicode_WSTR_LENGTH(unicode) = length;
-    }
-    else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
-        PyObject_DEL(_PyUnicode_WSTR(unicode));
-        _PyUnicode_WSTR(unicode) = NULL;
-    }
-#ifdef Py_DEBUG
-    unicode_fill_invalid(unicode, old_length);
-#endif
-    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
-                    length, 0);
-    assert(_PyUnicode_CheckConsistency(unicode, 0));
-    return unicode;
-}
-
-static int
-resize_inplace(PyObject *unicode, Py_ssize_t length)
-{
-    wchar_t *wstr;
-    Py_ssize_t new_size;
-    assert(!PyUnicode_IS_COMPACT(unicode));
-    assert(Py_REFCNT(unicode) == 1);
-
-    if (PyUnicode_IS_READY(unicode)) {
-        Py_ssize_t char_size;
-        int share_wstr, share_utf8;
-        void *data;
-#ifdef Py_DEBUG
-        Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
-#endif
-
-        data = _PyUnicode_DATA_ANY(unicode);
-        char_size = PyUnicode_KIND(unicode);
-        share_wstr = _PyUnicode_SHARE_WSTR(unicode);
-        share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
-
-        if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        new_size = (length + 1) * char_size;
-
-        if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
-        {
-            PyObject_DEL(_PyUnicode_UTF8(unicode));
-            _PyUnicode_UTF8(unicode) = NULL;
-            _PyUnicode_UTF8_LENGTH(unicode) = 0;
-        }
-
-        data = (PyObject *)PyObject_REALLOC(data, new_size);
-        if (data == NULL) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        _PyUnicode_DATA_ANY(unicode) = data;
-        if (share_wstr) {
-            _PyUnicode_WSTR(unicode) = data;
-            _PyUnicode_WSTR_LENGTH(unicode) = length;
-        }
-        if (share_utf8) {
-            _PyUnicode_UTF8(unicode) = data;
-            _PyUnicode_UTF8_LENGTH(unicode) = length;
-        }
-        _PyUnicode_LENGTH(unicode) = length;
-        PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
-#ifdef Py_DEBUG
-        unicode_fill_invalid(unicode, old_length);
-#endif
-        if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
-            assert(_PyUnicode_CheckConsistency(unicode, 0));
-            return 0;
-        }
-    }
-    assert(_PyUnicode_WSTR(unicode) != NULL);
-
-    /* check for integer overflow */
-    if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
-        PyErr_NoMemory();
-        return -1;
-    }
-    new_size = sizeof(wchar_t) * (length + 1);
-    wstr =  _PyUnicode_WSTR(unicode);
-    wstr = PyObject_REALLOC(wstr, new_size);
-    if (!wstr) {
-        PyErr_NoMemory();
-        return -1;
-    }
-    _PyUnicode_WSTR(unicode) = wstr;
-    _PyUnicode_WSTR(unicode)[length] = 0;
-    _PyUnicode_WSTR_LENGTH(unicode) = length;
-    assert(_PyUnicode_CheckConsistency(unicode, 0));
-    return 0;
-}
-
-static PyObject*
-resize_copy(PyObject *unicode, Py_ssize_t length)
-{
-    Py_ssize_t copy_length;
-    if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
-        PyObject *copy;
-
-        if (PyUnicode_READY(unicode) == -1)
-            return NULL;
-
-        copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
-        if (copy == NULL)
-            return NULL;
-
-        copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
-        _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
-        return copy;
-    }
-    else {
-        PyObject *w;
-
-        w = (PyObject*)_PyUnicode_New(length);
-        if (w == NULL)
-            return NULL;
-        copy_length = _PyUnicode_WSTR_LENGTH(unicode);
-        copy_length = Py_MIN(copy_length, length);
-        Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
-                  copy_length * sizeof(wchar_t));
-        return w;
-    }
-}
-
-/* We allocate one more byte to make sure the string is
-   Ux0000 terminated; some code (e.g. new_identifier)
-   relies on that.
-
-   XXX This allocator could further be enhanced by assuring that the
-   free list never reduces its size below 1.
-
-*/
-
-static PyUnicodeObject *
-_PyUnicode_New(Py_ssize_t length)
-{
-    PyUnicodeObject *unicode;
-    size_t new_size;
-
-    /* Optimization for empty strings */
-    if (length == 0 && unicode_empty != NULL) {
-        Py_INCREF(unicode_empty);
-        return (PyUnicodeObject*)unicode_empty;
-    }
-
-    /* Ensure we won't overflow the size. */
-    if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
-        return (PyUnicodeObject *)PyErr_NoMemory();
-    }
-    if (length < 0) {
-        PyErr_SetString(PyExc_SystemError,
-                        "Negative size passed to _PyUnicode_New");
-        return NULL;
-    }
-
-    unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
-    if (unicode == NULL)
-        return NULL;
-    new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
-
-    _PyUnicode_WSTR_LENGTH(unicode) = length;
-    _PyUnicode_HASH(unicode) = -1;
-    _PyUnicode_STATE(unicode).interned = 0;
-    _PyUnicode_STATE(unicode).kind = 0;
-    _PyUnicode_STATE(unicode).compact = 0;
-    _PyUnicode_STATE(unicode).ready = 0;
-    _PyUnicode_STATE(unicode).ascii = 0;
-    _PyUnicode_DATA_ANY(unicode) = NULL;
-    _PyUnicode_LENGTH(unicode) = 0;
-    _PyUnicode_UTF8(unicode) = NULL;
-    _PyUnicode_UTF8_LENGTH(unicode) = 0;
-
-    _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
-    if (!_PyUnicode_WSTR(unicode)) {
-        Py_DECREF(unicode);
-        PyErr_NoMemory();
-        return NULL;
-    }
-
-    /* Initialize the first element to guard against cases where
-     * the caller fails before initializing str -- unicode_resize()
-     * reads str[0], and the Keep-Alive optimization can keep memory
-     * allocated for str alive across a call to unicode_dealloc(unicode).
-     * We don't want unicode_resize to read uninitialized memory in
-     * that case.
-     */
-    _PyUnicode_WSTR(unicode)[0] = 0;
-    _PyUnicode_WSTR(unicode)[length] = 0;
-
-    assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
-    return unicode;
-}
-
-static const char*
-unicode_kind_name(PyObject *unicode)
-{
-    /* don't check consistency: unicode_kind_name() is called from
-       _PyUnicode_Dump() */
-    if (!PyUnicode_IS_COMPACT(unicode))
-    {
-        if (!PyUnicode_IS_READY(unicode))
-            return "wstr";
-        switch (PyUnicode_KIND(unicode))
-        {
-        case PyUnicode_1BYTE_KIND:
-            if (PyUnicode_IS_ASCII(unicode))
-                return "legacy ascii";
-            else
-                return "legacy latin1";
-        case PyUnicode_2BYTE_KIND:
-            return "legacy UCS2";
-        case PyUnicode_4BYTE_KIND:
-            return "legacy UCS4";
-        default:
-            return "<legacy invalid kind>";
-        }
-    }
-    assert(PyUnicode_IS_READY(unicode));
-    switch (PyUnicode_KIND(unicode)) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(unicode))
-            return "ascii";
-        else
-            return "latin1";
-    case PyUnicode_2BYTE_KIND:
-        return "UCS2";
-    case PyUnicode_4BYTE_KIND:
-        return "UCS4";
-    default:
-        return "<invalid compact kind>";
-    }
-}
-
-#ifdef Py_DEBUG
-/* Functions wrapping macros for use in debugger */
-char *_PyUnicode_utf8(void *unicode){
-    return PyUnicode_UTF8(unicode);
-}
-
-void *_PyUnicode_compact_data(void *unicode) {
-    return _PyUnicode_COMPACT_DATA(unicode);
-}
-void *_PyUnicode_data(void *unicode){
-    printf("obj %p\n", unicode);
-    printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
-    printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
-    printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
-    printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
-    printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
-    return PyUnicode_DATA(unicode);
-}
-
-void
-_PyUnicode_Dump(PyObject *op)
-{
-    PyASCIIObject *ascii = (PyASCIIObject *)op;
-    PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
-    PyUnicodeObject *unicode = (PyUnicodeObject *)op;
-    void *data;
-
-    if (ascii->state.compact)
-    {
-        if (ascii->state.ascii)
-            data = (ascii + 1);
-        else
-            data = (compact + 1);
-    }
-    else
-        data = unicode->data.any;
-    printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
-           unicode_kind_name(op), ascii->length);
-
-    if (ascii->wstr == data)
-        printf("shared ");
-    printf("wstr=%p", ascii->wstr);
-
-    if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
-        printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
-        if (!ascii->state.compact && compact->utf8 == unicode->data.any)
-            printf("shared ");
-        printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
-               compact->utf8, compact->utf8_length);
-    }
-    printf(", data=%p\n", data);
-}
-#endif
-
-PyObject *
-PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
-{
-    PyObject *obj;
-    PyCompactUnicodeObject *unicode;
-    void *data;
-    enum PyUnicode_Kind kind;
-    int is_sharing, is_ascii;
-    Py_ssize_t char_size;
-    Py_ssize_t struct_size;
-
-    /* Optimization for empty strings */
-    if (size == 0 && unicode_empty != NULL) {
-        Py_INCREF(unicode_empty);
-        return unicode_empty;
-    }
-
-    is_ascii = 0;
-    is_sharing = 0;
-    struct_size = sizeof(PyCompactUnicodeObject);
-    if (maxchar < 128) {
-        kind = PyUnicode_1BYTE_KIND;
-        char_size = 1;
-        is_ascii = 1;
-        struct_size = sizeof(PyASCIIObject);
-    }
-    else if (maxchar < 256) {
-        kind = PyUnicode_1BYTE_KIND;
-        char_size = 1;
-    }
-    else if (maxchar < 65536) {
-        kind = PyUnicode_2BYTE_KIND;
-        char_size = 2;
-        if (sizeof(wchar_t) == 2)
-            is_sharing = 1;
-    }
-    else {
-        if (maxchar > MAX_UNICODE) {
-            PyErr_SetString(PyExc_SystemError,
-                            "invalid maximum character passed to PyUnicode_New");
-            return NULL;
-        }
-        kind = PyUnicode_4BYTE_KIND;
-        char_size = 4;
-        if (sizeof(wchar_t) == 4)
-            is_sharing = 1;
-    }
-
-    /* Ensure we won't overflow the size. */
-    if (size < 0) {
-        PyErr_SetString(PyExc_SystemError,
-                        "Negative size passed to PyUnicode_New");
-        return NULL;
-    }
-    if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
-        return PyErr_NoMemory();
-
-    /* Duplicated allocation code from _PyObject_New() instead of a call to
-     * PyObject_New() so we are able to allocate space for the object and
-     * it's data buffer.
-     */
-    obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
-    if (obj == NULL)
-        return PyErr_NoMemory();
-    obj = PyObject_INIT(obj, &PyUnicode_Type);
-    if (obj == NULL)
-        return NULL;
-
-    unicode = (PyCompactUnicodeObject *)obj;
-    if (is_ascii)
-        data = ((PyASCIIObject*)obj) + 1;
-    else
-        data = unicode + 1;
-    _PyUnicode_LENGTH(unicode) = size;
-    _PyUnicode_HASH(unicode) = -1;
-    _PyUnicode_STATE(unicode).interned = 0;
-    _PyUnicode_STATE(unicode).kind = kind;
-    _PyUnicode_STATE(unicode).compact = 1;
-    _PyUnicode_STATE(unicode).ready = 1;
-    _PyUnicode_STATE(unicode).ascii = is_ascii;
-    if (is_ascii) {
-        ((char*)data)[size] = 0;
-        _PyUnicode_WSTR(unicode) = NULL;
-    }
-    else if (kind == PyUnicode_1BYTE_KIND) {
-        ((char*)data)[size] = 0;
-        _PyUnicode_WSTR(unicode) = NULL;
-        _PyUnicode_WSTR_LENGTH(unicode) = 0;
-        unicode->utf8 = NULL;
-        unicode->utf8_length = 0;
-    }
-    else {
-        unicode->utf8 = NULL;
-        unicode->utf8_length = 0;
-        if (kind == PyUnicode_2BYTE_KIND)
-            ((Py_UCS2*)data)[size] = 0;
-        else /* kind == PyUnicode_4BYTE_KIND */
-            ((Py_UCS4*)data)[size] = 0;
-        if (is_sharing) {
-            _PyUnicode_WSTR_LENGTH(unicode) = size;
-            _PyUnicode_WSTR(unicode) = (wchar_t *)data;
-        }
-        else {
-            _PyUnicode_WSTR_LENGTH(unicode) = 0;
-            _PyUnicode_WSTR(unicode) = NULL;
-        }
-    }
-#ifdef Py_DEBUG
-    unicode_fill_invalid((PyObject*)unicode, 0);
-#endif
-    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
-    return obj;
-}
-
-#if SIZEOF_WCHAR_T == 2
-/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
-   will decode surrogate pairs, the other conversions are implemented as macros
-   for efficiency.
-
-   This function assumes that unicode can hold one more code point than wstr
-   characters for a terminating null character. */
-static void
-unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
-                              PyObject *unicode)
-{
-    const wchar_t *iter;
-    Py_UCS4 *ucs4_out;
-
-    assert(unicode != NULL);
-    assert(_PyUnicode_CHECK(unicode));
-    assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
-    ucs4_out = PyUnicode_4BYTE_DATA(unicode);
-
-    for (iter = begin; iter < end; ) {
-        assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
-                           _PyUnicode_GET_LENGTH(unicode)));
-        if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
-            && (iter+1) < end
-            && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
-        {
-            *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
-            iter += 2;
-        }
-        else {
-            *ucs4_out++ = *iter;
-            iter++;
-        }
-    }
-    assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
-                        _PyUnicode_GET_LENGTH(unicode)));
-
-}
-#endif
-
-static int
-unicode_check_modifiable(PyObject *unicode)
-{
-    if (!unicode_modifiable(unicode)) {
-        PyErr_SetString(PyExc_SystemError,
-                        "Cannot modify a string currently used");
-        return -1;
-    }
-    return 0;
-}
-
-static int
-_copy_characters(PyObject *to, Py_ssize_t to_start,
-                 PyObject *from, Py_ssize_t from_start,
-                 Py_ssize_t how_many, int check_maxchar)
-{
-    unsigned int from_kind, to_kind;
-    void *from_data, *to_data;
-
-    assert(0 <= how_many);
-    assert(0 <= from_start);
-    assert(0 <= to_start);
-    assert(PyUnicode_Check(from));
-    assert(PyUnicode_IS_READY(from));
-    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
-
-    assert(PyUnicode_Check(to));
-    assert(PyUnicode_IS_READY(to));
-    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
-
-    if (how_many == 0)
-        return 0;
-
-    from_kind = PyUnicode_KIND(from);
-    from_data = PyUnicode_DATA(from);
-    to_kind = PyUnicode_KIND(to);
-    to_data = PyUnicode_DATA(to);
-
-#ifdef Py_DEBUG
-    if (!check_maxchar
-        && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
-    {
-        const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
-        Py_UCS4 ch;
-        Py_ssize_t i;
-        for (i=0; i < how_many; i++) {
-            ch = PyUnicode_READ(from_kind, from_data, from_start + i);
-            assert(ch <= to_maxchar);
-        }
-    }
-#endif
-
-    if (from_kind == to_kind) {
-        if (check_maxchar
-            && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
-        {
-            /* Writing Latin-1 characters into an ASCII string requires to
-               check that all written characters are pure ASCII */
-            Py_UCS4 max_char;
-            max_char = ucs1lib_find_max_char(from_data,
-                                             (Py_UCS1*)from_data + how_many);
-            if (max_char >= 128)
-                return -1;
-        }
-        Py_MEMCPY((char*)to_data + to_kind * to_start,
-                  (char*)from_data + from_kind * from_start,
-                  to_kind * how_many);
-    }
-    else if (from_kind == PyUnicode_1BYTE_KIND
-             && to_kind == PyUnicode_2BYTE_KIND)
-    {
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS1, Py_UCS2,
-            PyUnicode_1BYTE_DATA(from) + from_start,
-            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
-            PyUnicode_2BYTE_DATA(to) + to_start
-            );
-    }
-    else if (from_kind == PyUnicode_1BYTE_KIND
-             && to_kind == PyUnicode_4BYTE_KIND)
-    {
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS1, Py_UCS4,
-            PyUnicode_1BYTE_DATA(from) + from_start,
-            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
-            PyUnicode_4BYTE_DATA(to) + to_start
-            );
-    }
-    else if (from_kind == PyUnicode_2BYTE_KIND
-             && to_kind == PyUnicode_4BYTE_KIND)
-    {
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS2, Py_UCS4,
-            PyUnicode_2BYTE_DATA(from) + from_start,
-            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
-            PyUnicode_4BYTE_DATA(to) + to_start
-            );
-    }
-    else {
-        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
-
-        if (!check_maxchar) {
-            if (from_kind == PyUnicode_2BYTE_KIND
-                && to_kind == PyUnicode_1BYTE_KIND)
-            {
-                _PyUnicode_CONVERT_BYTES(
-                    Py_UCS2, Py_UCS1,
-                    PyUnicode_2BYTE_DATA(from) + from_start,
-                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
-                    PyUnicode_1BYTE_DATA(to) + to_start
-                    );
-            }
-            else if (from_kind == PyUnicode_4BYTE_KIND
-                     && to_kind == PyUnicode_1BYTE_KIND)
-            {
-                _PyUnicode_CONVERT_BYTES(
-                    Py_UCS4, Py_UCS1,
-                    PyUnicode_4BYTE_DATA(from) + from_start,
-                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
-                    PyUnicode_1BYTE_DATA(to) + to_start
-                    );
-            }
-            else if (from_kind == PyUnicode_4BYTE_KIND
-                     && to_kind == PyUnicode_2BYTE_KIND)
-            {
-                _PyUnicode_CONVERT_BYTES(
-                    Py_UCS4, Py_UCS2,
-                    PyUnicode_4BYTE_DATA(from) + from_start,
-                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
-                    PyUnicode_2BYTE_DATA(to) + to_start
-                    );
-            }
-            else {
-                assert(0);
-                return -1;
-            }
-        }
-        else {
-            const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
-            Py_UCS4 ch;
-            Py_ssize_t i;
-
-            for (i=0; i < how_many; i++) {
-                ch = PyUnicode_READ(from_kind, from_data, from_start + i);
-                if (ch > to_maxchar)
-                    return -1;
-                PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
-            }
-        }
-    }
-    return 0;
-}
-
-void
-_PyUnicode_FastCopyCharacters(
-    PyObject *to, Py_ssize_t to_start,
-    PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
-{
-    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
-}
-
-Py_ssize_t
-PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
-                         PyObject *from, Py_ssize_t from_start,
-                         Py_ssize_t how_many)
-{
-    int err;
-
-    if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-
-    if (PyUnicode_READY(from) == -1)
-        return -1;
-    if (PyUnicode_READY(to) == -1)
-        return -1;
-
-    if (from_start < 0) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return -1;
-    }
-    if (to_start < 0) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return -1;
-    }
-    how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
-    if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
-        PyErr_Format(PyExc_SystemError,
-                     "Cannot write %zi characters at %zi "
-                     "in a string of %zi characters",
-                     how_many, to_start, PyUnicode_GET_LENGTH(to));
-        return -1;
-    }
-
-    if (how_many == 0)
-        return 0;
-
-    if (unicode_check_modifiable(to))
-        return -1;
-
-    err = _copy_characters(to, to_start, from, from_start, how_many, 1);
-    if (err) {
-        PyErr_Format(PyExc_SystemError,
-                     "Cannot copy %s characters "
-                     "into a string of %s characters",
-                     unicode_kind_name(from),
-                     unicode_kind_name(to));
-        return -1;
-    }
-    return how_many;
-}
-
-/* Find the maximum code point and count the number of surrogate pairs so a
-   correct string length can be computed before converting a string to UCS4.
-   This function counts single surrogates as a character and not as a pair.
-
-   Return 0 on success, or -1 on error. */
-static int
-find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
-                        Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
-{
-    const wchar_t *iter;
-    Py_UCS4 ch;
-
-    assert(num_surrogates != NULL && maxchar != NULL);
-    *num_surrogates = 0;
-    *maxchar = 0;
-
-    for (iter = begin; iter < end; ) {
-#if SIZEOF_WCHAR_T == 2
-        if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
-            && (iter+1) < end
-            && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
-        {
-            ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
-            ++(*num_surrogates);
-            iter += 2;
-        }
-        else
-#endif
-        {
-            ch = *iter;
-            iter++;
-        }
-        if (ch > *maxchar) {
-            *maxchar = ch;
-            if (*maxchar > MAX_UNICODE) {
-                PyErr_Format(PyExc_ValueError,
-                             "character U+%x is not in range [U+0000; U+10ffff]",
-                             ch);
-                return -1;
-            }
-        }
-    }
-    return 0;
-}
-
-int
-_PyUnicode_Ready(PyObject *unicode)
-{
-    wchar_t *end;
-    Py_UCS4 maxchar = 0;
-    Py_ssize_t num_surrogates;
-#if SIZEOF_WCHAR_T == 2
-    Py_ssize_t length_wo_surrogates;
-#endif
-
-    /* _PyUnicode_Ready() is only intended for old-style API usage where
-       strings were created using _PyObject_New() and where no canonical
-       representation (the str field) has been set yet aka strings
-       which are not yet ready. */
-    assert(_PyUnicode_CHECK(unicode));
-    assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
-    assert(_PyUnicode_WSTR(unicode) != NULL);
-    assert(_PyUnicode_DATA_ANY(unicode) == NULL);
-    assert(_PyUnicode_UTF8(unicode) == NULL);
-    /* Actually, it should neither be interned nor be anything else: */
-    assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
-
-    end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
-    if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
-                                &maxchar, &num_surrogates) == -1)
-        return -1;
-
-    if (maxchar < 256) {
-        _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
-        if (!_PyUnicode_DATA_ANY(unicode)) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
-                                _PyUnicode_WSTR(unicode), end,
-                                PyUnicode_1BYTE_DATA(unicode));
-        PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
-        _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
-        _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
-        if (maxchar < 128) {
-            _PyUnicode_STATE(unicode).ascii = 1;
-            _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
-            _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
-        }
-        else {
-            _PyUnicode_STATE(unicode).ascii = 0;
-            _PyUnicode_UTF8(unicode) = NULL;
-            _PyUnicode_UTF8_LENGTH(unicode) = 0;
-        }
-        PyObject_FREE(_PyUnicode_WSTR(unicode));
-        _PyUnicode_WSTR(unicode) = NULL;
-        _PyUnicode_WSTR_LENGTH(unicode) = 0;
-    }
-    /* In this case we might have to convert down from 4-byte native
-       wchar_t to 2-byte unicode. */
-    else if (maxchar < 65536) {
-        assert(num_surrogates == 0 &&
-               "FindMaxCharAndNumSurrogatePairs() messed up");
-
-#if SIZEOF_WCHAR_T == 2
-        /* We can share representations and are done. */
-        _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
-        PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
-        _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
-        _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
-        _PyUnicode_UTF8(unicode) = NULL;
-        _PyUnicode_UTF8_LENGTH(unicode) = 0;
-#else
-        /* sizeof(wchar_t) == 4 */
-        _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
-            2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
-        if (!_PyUnicode_DATA_ANY(unicode)) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
-                                _PyUnicode_WSTR(unicode), end,
-                                PyUnicode_2BYTE_DATA(unicode));
-        PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
-        _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
-        _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
-        _PyUnicode_UTF8(unicode) = NULL;
-        _PyUnicode_UTF8_LENGTH(unicode) = 0;
-        PyObject_FREE(_PyUnicode_WSTR(unicode));
-        _PyUnicode_WSTR(unicode) = NULL;
-        _PyUnicode_WSTR_LENGTH(unicode) = 0;
-#endif
-    }
-    /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
-    else {
-#if SIZEOF_WCHAR_T == 2
-        /* in case the native representation is 2-bytes, we need to allocate a
-           new normalized 4-byte version. */
-        length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
-        if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
-        if (!_PyUnicode_DATA_ANY(unicode)) {
-            PyErr_NoMemory();
-            return -1;
-        }
-        _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
-        _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
-        _PyUnicode_UTF8(unicode) = NULL;
-        _PyUnicode_UTF8_LENGTH(unicode) = 0;
-        /* unicode_convert_wchar_to_ucs4() requires a ready string */
-        _PyUnicode_STATE(unicode).ready = 1;
-        unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
-        PyObject_FREE(_PyUnicode_WSTR(unicode));
-        _PyUnicode_WSTR(unicode) = NULL;
-        _PyUnicode_WSTR_LENGTH(unicode) = 0;
-#else
-        assert(num_surrogates == 0);
-
-        _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
-        _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
-        _PyUnicode_UTF8(unicode) = NULL;
-        _PyUnicode_UTF8_LENGTH(unicode) = 0;
-        _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
-#endif
-        PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
-    }
-    _PyUnicode_STATE(unicode).ready = 1;
-    assert(_PyUnicode_CheckConsistency(unicode, 1));
-    return 0;
-}
-
-static void
-unicode_dealloc(PyObject *unicode)
-{
-    switch (PyUnicode_CHECK_INTERNED(unicode)) {
-    case SSTATE_NOT_INTERNED:
-        break;
-
-    case SSTATE_INTERNED_MORTAL:
-        /* revive dead object temporarily for DelItem */
-        Py_REFCNT(unicode) = 3;
-        if (PyDict_DelItem(interned, unicode) != 0)
-            Py_FatalError(
-                "deletion of interned string failed");
-        break;
-
-    case SSTATE_INTERNED_IMMORTAL:
-        Py_FatalError("Immortal interned string died.");
-
-    default:
-        Py_FatalError("Inconsistent interned string state.");
-    }
-
-    if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
-        PyObject_DEL(_PyUnicode_WSTR(unicode));
-    if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
-        PyObject_DEL(_PyUnicode_UTF8(unicode));
-    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
-        PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
-
-    Py_TYPE(unicode)->tp_free(unicode);
-}
-
-#ifdef Py_DEBUG
-static int
-unicode_is_singleton(PyObject *unicode)
-{
-    PyASCIIObject *ascii = (PyASCIIObject *)unicode;
-    if (unicode == unicode_empty)
-        return 1;
-    if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
-    {
-        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
-        if (ch < 256 && unicode_latin1[ch] == unicode)
-            return 1;
-    }
-    return 0;
-}
-#endif
-
-static int
-unicode_modifiable(PyObject *unicode)
-{
-    assert(_PyUnicode_CHECK(unicode));
-    if (Py_REFCNT(unicode) != 1)
-        return 0;
-    if (_PyUnicode_HASH(unicode) != -1)
-        return 0;
-    if (PyUnicode_CHECK_INTERNED(unicode))
-        return 0;
-    if (!PyUnicode_CheckExact(unicode))
-        return 0;
-#ifdef Py_DEBUG
-    /* singleton refcount is greater than 1 */
-    assert(!unicode_is_singleton(unicode));
-#endif
-    return 1;
-}
-
-static int
-unicode_resize(PyObject **p_unicode, Py_ssize_t length)
-{
-    PyObject *unicode;
-    Py_ssize_t old_length;
-
-    assert(p_unicode != NULL);
-    unicode = *p_unicode;
-
-    assert(unicode != NULL);
-    assert(PyUnicode_Check(unicode));
-    assert(0 <= length);
-
-    if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
-        old_length = PyUnicode_WSTR_LENGTH(unicode);
-    else
-        old_length = PyUnicode_GET_LENGTH(unicode);
-    if (old_length == length)
-        return 0;
-
-    if (length == 0) {
-        _Py_INCREF_UNICODE_EMPTY();
-        if (!unicode_empty)
-            return -1;
-        Py_DECREF(*p_unicode);
-        *p_unicode = unicode_empty;
-        return 0;
-    }
-
-    if (!unicode_modifiable(unicode)) {
-        PyObject *copy = resize_copy(unicode, length);
-        if (copy == NULL)
-            return -1;
-        Py_DECREF(*p_unicode);
-        *p_unicode = copy;
-        return 0;
-    }
-
-    if (PyUnicode_IS_COMPACT(unicode)) {
-        PyObject *new_unicode = resize_compact(unicode, length);
-        if (new_unicode == NULL)
-            return -1;
-        *p_unicode = new_unicode;
-        return 0;
-    }
-    return resize_inplace(unicode, length);
-}
-
-int
-PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
-{
-    PyObject *unicode;
-    if (p_unicode == NULL) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    unicode = *p_unicode;
-    if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
-    {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    return unicode_resize(p_unicode, length);
-}
-
-/* Copy a ASCII or latin1 char* string into a Python Unicode string.
-
-   WARNING: The function doesn't copy the terminating null character and
-   doesn't check the maximum character (may write a latin1 character in an
-   ASCII string). */
-static void
-unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
-                   const char *str, Py_ssize_t len)
-{
-    enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
-    void *data = PyUnicode_DATA(unicode);
-    const char *end = str + len;
-
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND: {
-        assert(index + len <= PyUnicode_GET_LENGTH(unicode));
-#ifdef Py_DEBUG
-        if (PyUnicode_IS_ASCII(unicode)) {
-            Py_UCS4 maxchar = ucs1lib_find_max_char(
-                (const Py_UCS1*)str,
-                (const Py_UCS1*)str + len);
-            assert(maxchar < 128);
-        }
-#endif
-        memcpy((char *) data + index, str, len);
-        break;
-    }
-    case PyUnicode_2BYTE_KIND: {
-        Py_UCS2 *start = (Py_UCS2 *)data + index;
-        Py_UCS2 *ucs2 = start;
-        assert(index <= PyUnicode_GET_LENGTH(unicode));
-
-        for (; str < end; ++ucs2, ++str)
-            *ucs2 = (Py_UCS2)*str;
-
-        assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
-        break;
-    }
-    default: {
-        Py_UCS4 *start = (Py_UCS4 *)data + index;
-        Py_UCS4 *ucs4 = start;
-        assert(kind == PyUnicode_4BYTE_KIND);
-        assert(index <= PyUnicode_GET_LENGTH(unicode));
-
-        for (; str < end; ++ucs4, ++str)
-            *ucs4 = (Py_UCS4)*str;
-
-        assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
-    }
-    }
-}
-
-static PyObject*
-get_latin1_char(unsigned char ch)
-{
-    PyObject *unicode = unicode_latin1[ch];
-    if (!unicode) {
-        unicode = PyUnicode_New(1, ch);
-        if (!unicode)
-            return NULL;
-        PyUnicode_1BYTE_DATA(unicode)[0] = ch;
-        assert(_PyUnicode_CheckConsistency(unicode, 1));
-        unicode_latin1[ch] = unicode;
-    }
-    Py_INCREF(unicode);
-    return unicode;
-}
-
-static PyObject*
-unicode_char(Py_UCS4 ch)
-{
-    PyObject *unicode;
-
-    assert(ch <= MAX_UNICODE);
-
-    if (ch < 256)
-        return get_latin1_char(ch);
-
-    unicode = PyUnicode_New(1, ch);
-    if (unicode == NULL)
-        return NULL;
-    switch (PyUnicode_KIND(unicode)) {
-    case PyUnicode_1BYTE_KIND:
-        PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
-        break;
-    case PyUnicode_2BYTE_KIND:
-        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
-        break;
-    default:
-        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
-        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
-    }
-    assert(_PyUnicode_CheckConsistency(unicode, 1));
-    return unicode;
-}
-
-PyObject *
-PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
-{
-    PyObject *unicode;
-    Py_UCS4 maxchar = 0;
-    Py_ssize_t num_surrogates;
-
-    if (u == NULL)
-        return (PyObject*)_PyUnicode_New(size);
-
-    /* If the Unicode data is known at construction time, we can apply
-       some optimizations which share commonly used objects. */
-
-    /* Optimization for empty strings */
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    /* Single character Unicode objects in the Latin-1 range are
-       shared when using this constructor */
-    if (size == 1 && (Py_UCS4)*u < 256)
-        return get_latin1_char((unsigned char)*u);
-
-    /* If not empty and not single character, copy the Unicode data
-       into the new object */
-    if (find_maxchar_surrogates(u, u + size,
-                                &maxchar, &num_surrogates) == -1)
-        return NULL;
-
-    unicode = PyUnicode_New(size - num_surrogates, maxchar);
-    if (!unicode)
-        return NULL;
-
-    switch (PyUnicode_KIND(unicode)) {
-    case PyUnicode_1BYTE_KIND:
-        _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
-                                u, u + size, PyUnicode_1BYTE_DATA(unicode));
-        break;
-    case PyUnicode_2BYTE_KIND:
-#if Py_UNICODE_SIZE == 2
-        Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
-#else
-        _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
-                                u, u + size, PyUnicode_2BYTE_DATA(unicode));
-#endif
-        break;
-    case PyUnicode_4BYTE_KIND:
-#if SIZEOF_WCHAR_T == 2
-        /* This is the only case which has to process surrogates, thus
-           a simple copy loop is not enough and we need a function. */
-        unicode_convert_wchar_to_ucs4(u, u + size, unicode);
-#else
-        assert(num_surrogates == 0);
-        Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
-#endif
-        break;
-    default:
-        assert(0 && "Impossible state");
-    }
-
-    return unicode_result(unicode);
-}
-
-PyObject *
-PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
-{
-    if (size < 0) {
-        PyErr_SetString(PyExc_SystemError,
-                        "Negative size passed to PyUnicode_FromStringAndSize");
-        return NULL;
-    }
-    if (u != NULL)
-        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
-    else
-        return (PyObject *)_PyUnicode_New(size);
-}
-
-PyObject *
-PyUnicode_FromString(const char *u)
-{
-    size_t size = strlen(u);
-    if (size > PY_SSIZE_T_MAX) {
-        PyErr_SetString(PyExc_OverflowError, "input too long");
-        return NULL;
-    }
-    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
-}
-
-PyObject *
-_PyUnicode_FromId(_Py_Identifier *id)
-{
-    if (!id->object) {
-        id->object = PyUnicode_DecodeUTF8Stateful(id->string,
-                                                  strlen(id->string),
-                                                  NULL, NULL);
-        if (!id->object)
-            return NULL;
-        PyUnicode_InternInPlace(&id->object);
-        assert(!id->next);
-        id->next = static_strings;
-        static_strings = id;
-    }
-    return id->object;
-}
-
-void
-_PyUnicode_ClearStaticStrings()
-{
-    _Py_Identifier *tmp, *s = static_strings;
-    while (s) {
-        Py_CLEAR(s->object);
-        tmp = s->next;
-        s->next = NULL;
-        s = tmp;
-    }
-    static_strings = NULL;
-}
-
-/* Internal function, doesn't check maximum character */
-
-PyObject*
-_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
-{
-    const unsigned char *s = (const unsigned char *)buffer;
-    PyObject *unicode;
-    if (size == 1) {
-#ifdef Py_DEBUG
-        assert((unsigned char)s[0] < 128);
-#endif
-        return get_latin1_char(s[0]);
-    }
-    unicode = PyUnicode_New(size, 127);
-    if (!unicode)
-        return NULL;
-    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
-    assert(_PyUnicode_CheckConsistency(unicode, 1));
-    return unicode;
-}
-
-static Py_UCS4
-kind_maxchar_limit(unsigned int kind)
-{
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        return 0x80;
-    case PyUnicode_2BYTE_KIND:
-        return 0x100;
-    case PyUnicode_4BYTE_KIND:
-        return 0x10000;
-    default:
-        assert(0 && "invalid kind");
-        return MAX_UNICODE;
-    }
-}
-
-Py_LOCAL_INLINE(Py_UCS4)
-align_maxchar(Py_UCS4 maxchar)
-{
-    if (maxchar <= 127)
-        return 127;
-    else if (maxchar <= 255)
-        return 255;
-    else if (maxchar <= 65535)
-        return 65535;
-    else
-        return MAX_UNICODE;
-}
-
-static PyObject*
-_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
-{
-    PyObject *res;
-    unsigned char max_char;
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-    assert(size > 0);
-    if (size == 1)
-        return get_latin1_char(u[0]);
-
-    max_char = ucs1lib_find_max_char(u, u + size);
-    res = PyUnicode_New(size, max_char);
-    if (!res)
-        return NULL;
-    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
-    assert(_PyUnicode_CheckConsistency(res, 1));
-    return res;
-}
-
-static PyObject*
-_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
-{
-    PyObject *res;
-    Py_UCS2 max_char;
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-    assert(size > 0);
-    if (size == 1)
-        return unicode_char(u[0]);
-
-    max_char = ucs2lib_find_max_char(u, u + size);
-    res = PyUnicode_New(size, max_char);
-    if (!res)
-        return NULL;
-    if (max_char >= 256)
-        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
-    else {
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
-    }
-    assert(_PyUnicode_CheckConsistency(res, 1));
-    return res;
-}
-
-static PyObject*
-_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
-{
-    PyObject *res;
-    Py_UCS4 max_char;
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-    assert(size > 0);
-    if (size == 1)
-        return unicode_char(u[0]);
-
-    max_char = ucs4lib_find_max_char(u, u + size);
-    res = PyUnicode_New(size, max_char);
-    if (!res)
-        return NULL;
-    if (max_char < 256)
-        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
-                                 PyUnicode_1BYTE_DATA(res));
-    else if (max_char < 0x10000)
-        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
-                                 PyUnicode_2BYTE_DATA(res));
-    else
-        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
-    assert(_PyUnicode_CheckConsistency(res, 1));
-    return res;
-}
-
-PyObject*
-PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
-{
-    if (size < 0) {
-        PyErr_SetString(PyExc_ValueError, "size must be positive");
-        return NULL;
-    }
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        return _PyUnicode_FromUCS1(buffer, size);
-    case PyUnicode_2BYTE_KIND:
-        return _PyUnicode_FromUCS2(buffer, size);
-    case PyUnicode_4BYTE_KIND:
-        return _PyUnicode_FromUCS4(buffer, size);
-    default:
-        PyErr_SetString(PyExc_SystemError, "invalid kind");
-        return NULL;
-    }
-}
-
-Py_UCS4
-_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
-{
-    enum PyUnicode_Kind kind;
-    void *startptr, *endptr;
-
-    assert(PyUnicode_IS_READY(unicode));
-    assert(0 <= start);
-    assert(end <= PyUnicode_GET_LENGTH(unicode));
-    assert(start <= end);
-
-    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
-        return PyUnicode_MAX_CHAR_VALUE(unicode);
-
-    if (start == end)
-        return 127;
-
-    if (PyUnicode_IS_ASCII(unicode))
-        return 127;
-
-    kind = PyUnicode_KIND(unicode);
-    startptr = PyUnicode_DATA(unicode);
-    endptr = (char *)startptr + end * kind;
-    startptr = (char *)startptr + start * kind;
-    switch(kind) {
-    case PyUnicode_1BYTE_KIND:
-        return ucs1lib_find_max_char(startptr, endptr);
-    case PyUnicode_2BYTE_KIND:
-        return ucs2lib_find_max_char(startptr, endptr);
-    case PyUnicode_4BYTE_KIND:
-        return ucs4lib_find_max_char(startptr, endptr);
-    default:
-        assert(0);
-        return 0;
-    }
-}
-
-/* Ensure that a string uses the most efficient storage, if it is not the
-   case: create a new string with of the right kind. Write NULL into *p_unicode
-   on error. */
-static void
-unicode_adjust_maxchar(PyObject **p_unicode)
-{
-    PyObject *unicode, *copy;
-    Py_UCS4 max_char;
-    Py_ssize_t len;
-    unsigned int kind;
-
-    assert(p_unicode != NULL);
-    unicode = *p_unicode;
-    assert(PyUnicode_IS_READY(unicode));
-    if (PyUnicode_IS_ASCII(unicode))
-        return;
-
-    len = PyUnicode_GET_LENGTH(unicode);
-    kind = PyUnicode_KIND(unicode);
-    if (kind == PyUnicode_1BYTE_KIND) {
-        const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
-        max_char = ucs1lib_find_max_char(u, u + len);
-        if (max_char >= 128)
-            return;
-    }
-    else if (kind == PyUnicode_2BYTE_KIND) {
-        const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
-        max_char = ucs2lib_find_max_char(u, u + len);
-        if (max_char >= 256)
-            return;
-    }
-    else {
-        const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
-        assert(kind == PyUnicode_4BYTE_KIND);
-        max_char = ucs4lib_find_max_char(u, u + len);
-        if (max_char >= 0x10000)
-            return;
-    }
-    copy = PyUnicode_New(len, max_char);
-    if (copy != NULL)
-        _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
-    Py_DECREF(unicode);
-    *p_unicode = copy;
-}
-
-PyObject*
-_PyUnicode_Copy(PyObject *unicode)
-{
-    Py_ssize_t length;
-    PyObject *copy;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-
-    length = PyUnicode_GET_LENGTH(unicode);
-    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
-    if (!copy)
-        return NULL;
-    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
-
-    Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
-              length * PyUnicode_KIND(unicode));
-    assert(_PyUnicode_CheckConsistency(copy, 1));
-    return copy;
-}
-
-
-/* Widen Unicode objects to larger buffers. Don't write terminating null
-   character. Return NULL on error. */
-
-void*
-_PyUnicode_AsKind(PyObject *s, unsigned int kind)
-{
-    Py_ssize_t len;
-    void *result;
-    unsigned int skind;
-
-    if (PyUnicode_READY(s) == -1)
-        return NULL;
-
-    len = PyUnicode_GET_LENGTH(s);
-    skind = PyUnicode_KIND(s);
-    if (skind >= kind) {
-        PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
-        return NULL;
-    }
-    switch (kind) {
-    case PyUnicode_2BYTE_KIND:
-        result = PyMem_New(Py_UCS2, len);
-        if (!result)
-            return PyErr_NoMemory();
-        assert(skind == PyUnicode_1BYTE_KIND);
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS1, Py_UCS2,
-            PyUnicode_1BYTE_DATA(s),
-            PyUnicode_1BYTE_DATA(s) + len,
-            result);
-        return result;
-    case PyUnicode_4BYTE_KIND:
-        result = PyMem_New(Py_UCS4, len);
-        if (!result)
-            return PyErr_NoMemory();
-        if (skind == PyUnicode_2BYTE_KIND) {
-            _PyUnicode_CONVERT_BYTES(
-                Py_UCS2, Py_UCS4,
-                PyUnicode_2BYTE_DATA(s),
-                PyUnicode_2BYTE_DATA(s) + len,
-                result);
-        }
-        else {
-            assert(skind == PyUnicode_1BYTE_KIND);
-            _PyUnicode_CONVERT_BYTES(
-                Py_UCS1, Py_UCS4,
-                PyUnicode_1BYTE_DATA(s),
-                PyUnicode_1BYTE_DATA(s) + len,
-                result);
-        }
-        return result;
-    default:
-        break;
-    }
-    PyErr_SetString(PyExc_SystemError, "invalid kind");
-    return NULL;
-}
-
-static Py_UCS4*
-as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
-        int copy_null)
-{
-    int kind;
-    void *data;
-    Py_ssize_t len, targetlen;
-    if (PyUnicode_READY(string) == -1)
-        return NULL;
-    kind = PyUnicode_KIND(string);
-    data = PyUnicode_DATA(string);
-    len = PyUnicode_GET_LENGTH(string);
-    targetlen = len;
-    if (copy_null)
-        targetlen++;
-    if (!target) {
-        target = PyMem_New(Py_UCS4, targetlen);
-        if (!target) {
-            PyErr_NoMemory();
-            return NULL;
-        }
-    }
-    else {
-        if (targetsize < targetlen) {
-            PyErr_Format(PyExc_SystemError,
-                         "string is longer than the buffer");
-            if (copy_null && 0 < targetsize)
-                target[0] = 0;
-            return NULL;
-        }
-    }
-    if (kind == PyUnicode_1BYTE_KIND) {
-        Py_UCS1 *start = (Py_UCS1 *) data;
-        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
-    }
-    else if (kind == PyUnicode_2BYTE_KIND) {
-        Py_UCS2 *start = (Py_UCS2 *) data;
-        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
-    }
-    else {
-        assert(kind == PyUnicode_4BYTE_KIND);
-        Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
-    }
-    if (copy_null)
-        target[len] = 0;
-    return target;
-}
-
-Py_UCS4*
-PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
-                 int copy_null)
-{
-    if (target == NULL || targetsize < 0) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    return as_ucs4(string, target, targetsize, copy_null);
-}
-
-Py_UCS4*
-PyUnicode_AsUCS4Copy(PyObject *string)
-{
-    return as_ucs4(string, NULL, 0, 1);
-}
-
-#ifdef HAVE_WCHAR_H
-
-PyObject *
-PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
-{
-    if (w == NULL) {
-        if (size == 0)
-            _Py_RETURN_UNICODE_EMPTY();
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-
-    if (size == -1) {
-        size = wcslen(w);
-    }
-
-    return PyUnicode_FromUnicode(w, size);
-}
-
-#endif /* HAVE_WCHAR_H */
-
-/* maximum number of characters required for output of %lld or %p.
-   We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
-   plus 1 for the sign.  53/22 is an upper bound for log10(256). */
-#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
-
-static int
-unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
-                             Py_ssize_t width, Py_ssize_t precision)
-{
-    Py_ssize_t length, fill, arglen;
-    Py_UCS4 maxchar;
-
-    if (PyUnicode_READY(str) == -1)
-        return -1;
-
-    length = PyUnicode_GET_LENGTH(str);
-    if ((precision == -1 || precision >= length)
-        && width <= length)
-        return _PyUnicodeWriter_WriteStr(writer, str);
-
-    if (precision != -1)
-        length = Py_MIN(precision, length);
-
-    arglen = Py_MAX(length, width);
-    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
-        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
-    else
-        maxchar = writer->maxchar;
-
-    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
-        return -1;
-
-    if (width > length) {
-        fill = width - length;
-        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
-            return -1;
-        writer->pos += fill;
-    }
-
-    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
-                                  str, 0, length);
-    writer->pos += length;
-    return 0;
-}
-
-static int
-unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
-                              Py_ssize_t width, Py_ssize_t precision)
-{
-    /* UTF-8 */
-    Py_ssize_t length;
-    PyObject *unicode;
-    int res;
-
-    length = strlen(str);
-    if (precision != -1)
-        length = Py_MIN(length, precision);
-    unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
-    if (unicode == NULL)
-        return -1;
-
-    res = unicode_fromformat_write_str(writer, unicode, width, -1);
-    Py_DECREF(unicode);
-    return res;
-}
-
-static const char*
-unicode_fromformat_arg(_PyUnicodeWriter *writer,
-                       const char *f, va_list *vargs)
-{
-    const char *p;
-    Py_ssize_t len;
-    int zeropad;
-    Py_ssize_t width;
-    Py_ssize_t precision;
-    int longflag;
-    int longlongflag;
-    int size_tflag;
-    Py_ssize_t fill;
-
-    p = f;
-    f++;
-    zeropad = 0;
-    if (*f == '0') {
-        zeropad = 1;
-        f++;
-    }
-
-    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
-    width = -1;
-    if (Py_ISDIGIT((unsigned)*f)) {
-        width = *f - '0';
-        f++;
-        while (Py_ISDIGIT((unsigned)*f)) {
-            if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
-                PyErr_SetString(PyExc_ValueError,
-                                "width too big");
-                return NULL;
-            }
-            width = (width * 10) + (*f - '0');
-            f++;
-        }
-    }
-    precision = -1;
-    if (*f == '.') {
-        f++;
-        if (Py_ISDIGIT((unsigned)*f)) {
-            precision = (*f - '0');
-            f++;
-            while (Py_ISDIGIT((unsigned)*f)) {
-                if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
-                    PyErr_SetString(PyExc_ValueError,
-                                    "precision too big");
-                    return NULL;
-                }
-                precision = (precision * 10) + (*f - '0');
-                f++;
-            }
-        }
-        if (*f == '%') {
-            /* "%.3%s" => f points to "3" */
-            f--;
-        }
-    }
-    if (*f == '\0') {
-        /* bogus format "%.123" => go backward, f points to "3" */
-        f--;
-    }
-
-    /* Handle %ld, %lu, %lld and %llu. */
-    longflag = 0;
-    longlongflag = 0;
-    size_tflag = 0;
-    if (*f == 'l') {
-        if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
-            longflag = 1;
-            ++f;
-        }
-#ifdef HAVE_LONG_LONG
-        else if (f[1] == 'l' &&
-                 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
-            longlongflag = 1;
-            f += 2;
-        }
-#endif
-    }
-    /* handle the size_t flag. */
-    else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
-        size_tflag = 1;
-        ++f;
-    }
-
-    if (f[1] == '\0')
-        writer->overallocate = 0;
-
-    switch (*f) {
-    case 'c':
-    {
-        int ordinal = va_arg(*vargs, int);
-        if (ordinal < 0 || ordinal > MAX_UNICODE) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "character argument not in range(0x110000)");
-            return NULL;
-        }
-        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
-            return NULL;
-        break;
-    }
-
-    case 'i':
-    case 'd':
-    case 'u':
-    case 'x':
-    {
-        /* used by sprintf */
-        char buffer[MAX_LONG_LONG_CHARS];
-        Py_ssize_t arglen;
-
-        if (*f == 'u') {
-            if (longflag)
-                len = sprintf(buffer, "%lu",
-                        va_arg(*vargs, unsigned long));
-#ifdef HAVE_LONG_LONG
-            else if (longlongflag)
-                len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
-                        va_arg(*vargs, unsigned PY_LONG_LONG));
-#endif
-            else if (size_tflag)
-                len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
-                        va_arg(*vargs, size_t));
-            else
-                len = sprintf(buffer, "%u",
-                        va_arg(*vargs, unsigned int));
-        }
-        else if (*f == 'x') {
-            len = sprintf(buffer, "%x", va_arg(*vargs, int));
-        }
-        else {
-            if (longflag)
-                len = sprintf(buffer, "%li",
-                        va_arg(*vargs, long));
-#ifdef HAVE_LONG_LONG
-            else if (longlongflag)
-                len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
-                        va_arg(*vargs, PY_LONG_LONG));
-#endif
-            else if (size_tflag)
-                len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
-                        va_arg(*vargs, Py_ssize_t));
-            else
-                len = sprintf(buffer, "%i",
-                        va_arg(*vargs, int));
-        }
-        assert(len >= 0);
-
-        if (precision < len)
-            precision = len;
-
-        arglen = Py_MAX(precision, width);
-        if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
-            return NULL;
-
-        if (width > precision) {
-            Py_UCS4 fillchar;
-            fill = width - precision;
-            fillchar = zeropad?'0':' ';
-            if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
-                return NULL;
-            writer->pos += fill;
-        }
-        if (precision > len) {
-            fill = precision - len;
-            if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
-                return NULL;
-            writer->pos += fill;
-        }
-
-        if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
-            return NULL;
-        break;
-    }
-
-    case 'p':
-    {
-        char number[MAX_LONG_LONG_CHARS];
-
-        len = sprintf(number, "%p", va_arg(*vargs, void*));
-        assert(len >= 0);
-
-        /* %p is ill-defined:  ensure leading 0x. */
-        if (number[1] == 'X')
-            number[1] = 'x';
-        else if (number[1] != 'x') {
-            memmove(number + 2, number,
-                    strlen(number) + 1);
-            number[0] = '0';
-            number[1] = 'x';
-            len += 2;
-        }
-
-        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
-            return NULL;
-        break;
-    }
-
-    case 's':
-    {
-        /* UTF-8 */
-        const char *s = va_arg(*vargs, const char*);
-        if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
-            return NULL;
-        break;
-    }
-
-    case 'U':
-    {
-        PyObject *obj = va_arg(*vargs, PyObject *);
-        assert(obj && _PyUnicode_CHECK(obj));
-
-        if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
-            return NULL;
-        break;
-    }
-
-    case 'V':
-    {
-        PyObject *obj = va_arg(*vargs, PyObject *);
-        const char *str = va_arg(*vargs, const char *);
-        if (obj) {
-            assert(_PyUnicode_CHECK(obj));
-            if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
-                return NULL;
-        }
-        else {
-            assert(str != NULL);
-            if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
-                return NULL;
-        }
-        break;
-    }
-
-    case 'S':
-    {
-        PyObject *obj = va_arg(*vargs, PyObject *);
-        PyObject *str;
-        assert(obj);
-        str = PyObject_Str(obj);
-        if (!str)
-            return NULL;
-        if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
-            Py_DECREF(str);
-            return NULL;
-        }
-        Py_DECREF(str);
-        break;
-    }
-
-    case 'R':
-    {
-        PyObject *obj = va_arg(*vargs, PyObject *);
-        PyObject *repr;
-        assert(obj);
-        repr = PyObject_Repr(obj);
-        if (!repr)
-            return NULL;
-        if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
-            Py_DECREF(repr);
-            return NULL;
-        }
-        Py_DECREF(repr);
-        break;
-    }
-
-    case 'A':
-    {
-        PyObject *obj = va_arg(*vargs, PyObject *);
-        PyObject *ascii;
-        assert(obj);
-        ascii = PyObject_ASCII(obj);
-        if (!ascii)
-            return NULL;
-        if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
-            Py_DECREF(ascii);
-            return NULL;
-        }
-        Py_DECREF(ascii);
-        break;
-    }
-
-    case '%':
-        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
-            return NULL;
-        break;
-
-    default:
-        /* if we stumble upon an unknown formatting code, copy the rest
-           of the format string to the output string. (we cannot just
-           skip the code, since there's no way to know what's in the
-           argument list) */
-        len = strlen(p);
-        if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
-            return NULL;
-        f = p+len;
-        return f;
-    }
-
-    f++;
-    return f;
-}
-
-PyObject *
-PyUnicode_FromFormatV(const char *format, va_list vargs)
-{
-    va_list vargs2;
-    const char *f;
-    _PyUnicodeWriter writer;
-
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = strlen(format) + 100;
-    writer.overallocate = 1;
-
-    /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
-       Copy it to be able to pass a reference to a subfunction. */
-    Py_VA_COPY(vargs2, vargs);
-
-    for (f = format; *f; ) {
-        if (*f == '%') {
-            f = unicode_fromformat_arg(&writer, f, &vargs2);
-            if (f == NULL)
-                goto fail;
-        }
-        else {
-            const char *p;
-            Py_ssize_t len;
-
-            p = f;
-            do
-            {
-                if ((unsigned char)*p > 127) {
-                    PyErr_Format(PyExc_ValueError,
-                        "PyUnicode_FromFormatV() expects an ASCII-encoded format "
-                        "string, got a non-ASCII byte: 0x%02x",
-                        (unsigned char)*p);
-                    return NULL;
-                }
-                p++;
-            }
-            while (*p != '\0' && *p != '%');
-            len = p - f;
-
-            if (*p == '\0')
-                writer.overallocate = 0;
-
-            if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
-                goto fail;
-
-            f = p;
-        }
-    }
-    return _PyUnicodeWriter_Finish(&writer);
-
-  fail:
-    _PyUnicodeWriter_Dealloc(&writer);
-    return NULL;
-}
-
-PyObject *
-PyUnicode_FromFormat(const char *format, ...)
-{
-    PyObject* ret;
-    va_list vargs;
-
-#ifdef HAVE_STDARG_PROTOTYPES
-    va_start(vargs, format);
-#else
-    va_start(vargs);
-#endif
-    ret = PyUnicode_FromFormatV(format, vargs);
-    va_end(vargs);
-    return ret;
-}
-
-#ifdef HAVE_WCHAR_H
-
-/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
-   convert a Unicode object to a wide character string.
-
-   - If w is NULL: return the number of wide characters (including the null
-     character) required to convert the unicode object. Ignore size argument.
-
-   - Otherwise: return the number of wide characters (excluding the null
-     character) written into w. Write at most size wide characters (including
-     the null character). */
-static Py_ssize_t
-unicode_aswidechar(PyObject *unicode,
-                   wchar_t *w,
-                   Py_ssize_t size)
-{
-    Py_ssize_t res;
-    const wchar_t *wstr;
-
-    wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
-    if (wstr == NULL)
-        return -1;
-
-    if (w != NULL) {
-        if (size > res)
-            size = res + 1;
-        else
-            res = size;
-        Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
-        return res;
-    }
-    else
-        return res + 1;
-}
-
-Py_ssize_t
-PyUnicode_AsWideChar(PyObject *unicode,
-                     wchar_t *w,
-                     Py_ssize_t size)
-{
-    if (unicode == NULL) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    return unicode_aswidechar(unicode, w, size);
-}
-
-wchar_t*
-PyUnicode_AsWideCharString(PyObject *unicode,
-                           Py_ssize_t *size)
-{
-    wchar_t* buffer;
-    Py_ssize_t buflen;
-
-    if (unicode == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-
-    buflen = unicode_aswidechar(unicode, NULL, 0);
-    if (buflen == -1)
-        return NULL;
-    buffer = PyMem_NEW(wchar_t, buflen);
-    if (buffer == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    buflen = unicode_aswidechar(unicode, buffer, buflen);
-    if (buflen == -1) {
-        PyMem_FREE(buffer);
-        return NULL;
-    }
-    if (size != NULL)
-        *size = buflen;
-    return buffer;
-}
-
-#endif /* HAVE_WCHAR_H */
-
-PyObject *
-PyUnicode_FromOrdinal(int ordinal)
-{
-    if (ordinal < 0 || ordinal > MAX_UNICODE) {
-        PyErr_SetString(PyExc_ValueError,
-                        "chr() arg not in range(0x110000)");
-        return NULL;
-    }
-
-    return unicode_char((Py_UCS4)ordinal);
-}
-
-PyObject *
-PyUnicode_FromObject(PyObject *obj)
-{
-    /* XXX Perhaps we should make this API an alias of
-       PyObject_Str() instead ?! */
-    if (PyUnicode_CheckExact(obj)) {
-        if (PyUnicode_READY(obj) == -1)
-            return NULL;
-        Py_INCREF(obj);
-        return obj;
-    }
-    if (PyUnicode_Check(obj)) {
-        /* For a Unicode subtype that's not a Unicode object,
-           return a true Unicode object with the same data. */
-        return _PyUnicode_Copy(obj);
-    }
-    PyErr_Format(PyExc_TypeError,
-                 "Can't convert '%.100s' object to str implicitly",
-                 Py_TYPE(obj)->tp_name);
-    return NULL;
-}
-
-PyObject *
-PyUnicode_FromEncodedObject(PyObject *obj,
-                            const char *encoding,
-                            const char *errors)
-{
-    Py_buffer buffer;
-    PyObject *v;
-
-    if (obj == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-
-    /* Decoding bytes objects is the most common case and should be fast */
-    if (PyBytes_Check(obj)) {
-        if (PyBytes_GET_SIZE(obj) == 0)
-            _Py_RETURN_UNICODE_EMPTY();
-        v = PyUnicode_Decode(
-                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
-                encoding, errors);
-        return v;
-    }
-
-    if (PyUnicode_Check(obj)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "decoding str is not supported");
-        return NULL;
-    }
-
-    /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
-    if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
-        PyErr_Format(PyExc_TypeError,
-                     "coercing to str: need a bytes-like object, %.80s found",
-                     Py_TYPE(obj)->tp_name);
-        return NULL;
-    }
-
-    if (buffer.len == 0) {
-        PyBuffer_Release(&buffer);
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-    v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
-    PyBuffer_Release(&buffer);
-    return v;
-}
-
-/* Convert encoding to lower case and replace '_' with '-' in order to
-   catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
-   1 on success. */
-int
-_Py_normalize_encoding(const char *encoding,
-                       char *lower,
-                       size_t lower_len)
-{
-    const char *e;
-    char *l;
-    char *l_end;
-
-    if (encoding == NULL) {
-        /* 6 == strlen("utf-8") + 1 */
-        if (lower_len < 6)
-            return 0;
-        strcpy(lower, "utf-8");
-        return 1;
-    }
-    e = encoding;
-    l = lower;
-    l_end = &lower[lower_len - 1];
-    while (*e) {
-        if (l == l_end)
-            return 0;
-        if (Py_ISUPPER(*e)) {
-            *l++ = Py_TOLOWER(*e++);
-        }
-        else if (*e == '_') {
-            *l++ = '-';
-            e++;
-        }
-        else {
-            *l++ = *e++;
-        }
-    }
-    *l = '\0';
-    return 1;
-}
-
-PyObject *
-PyUnicode_Decode(const char *s,
-                 Py_ssize_t size,
-                 const char *encoding,
-                 const char *errors)
-{
-    PyObject *buffer = NULL, *unicode;
-    Py_buffer info;
-    char lower[11];  /* Enough for any encoding shortcut */
-
-    /* Shortcuts for common default encodings */
-    if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
-        if ((strcmp(lower, "utf-8") == 0) ||
-            (strcmp(lower, "utf8") == 0))
-            return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
-        else if ((strcmp(lower, "latin-1") == 0) ||
-                 (strcmp(lower, "latin1") == 0) ||
-                 (strcmp(lower, "iso-8859-1") == 0) ||
-                 (strcmp(lower, "iso8859-1") == 0))
-            return PyUnicode_DecodeLatin1(s, size, errors);
-#ifdef HAVE_MBCS
-        else if (strcmp(lower, "mbcs") == 0)
-            return PyUnicode_DecodeMBCS(s, size, errors);
-#endif
-        else if (strcmp(lower, "ascii") == 0)
-            return PyUnicode_DecodeASCII(s, size, errors);
-        else if (strcmp(lower, "utf-16") == 0)
-            return PyUnicode_DecodeUTF16(s, size, errors, 0);
-        else if (strcmp(lower, "utf-32") == 0)
-            return PyUnicode_DecodeUTF32(s, size, errors, 0);
-    }
-
-    /* Decode via the codec registry */
-    buffer = NULL;
-    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
-        goto onError;
-    buffer = PyMemoryView_FromBuffer(&info);
-    if (buffer == NULL)
-        goto onError;
-    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
-    if (unicode == NULL)
-        goto onError;
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_Format(PyExc_TypeError,
-                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
-                     "use codecs.decode() to decode to arbitrary types",
-                     encoding,
-                     Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
-        Py_DECREF(unicode);
-        goto onError;
-    }
-    Py_DECREF(buffer);
-    return unicode_result(unicode);
-
-  onError:
-    Py_XDECREF(buffer);
-    return NULL;
-}
-
-PyObject *
-PyUnicode_AsDecodedObject(PyObject *unicode,
-                          const char *encoding,
-                          const char *errors)
-{
-    PyObject *v;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-
-    /* Decode via the codec registry */
-    v = PyCodec_Decode(unicode, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    return unicode_result(v);
-
-  onError:
-    return NULL;
-}
-
-PyObject *
-PyUnicode_AsDecodedUnicode(PyObject *unicode,
-                           const char *encoding,
-                           const char *errors)
-{
-    PyObject *v;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-
-    /* Decode via the codec registry */
-    v = PyCodec_Decode(unicode, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    if (!PyUnicode_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
-                     "use codecs.decode() to decode to arbitrary types",
-                     encoding,
-                     Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
-        Py_DECREF(v);
-        goto onError;
-    }
-    return unicode_result(v);
-
-  onError:
-    return NULL;
-}
-
-PyObject *
-PyUnicode_Encode(const Py_UNICODE *s,
-                 Py_ssize_t size,
-                 const char *encoding,
-                 const char *errors)
-{
-    PyObject *v, *unicode;
-
-    unicode = PyUnicode_FromUnicode(s, size);
-    if (unicode == NULL)
-        return NULL;
-    v = PyUnicode_AsEncodedString(unicode, encoding, errors);
-    Py_DECREF(unicode);
-    return v;
-}
-
-PyObject *
-PyUnicode_AsEncodedObject(PyObject *unicode,
-                          const char *encoding,
-                          const char *errors)
-{
-    PyObject *v;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-
-    /* Encode via the codec registry */
-    v = PyCodec_Encode(unicode, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    return v;
-
-  onError:
-    return NULL;
-}
-
-static size_t
-wcstombs_errorpos(const wchar_t *wstr)
-{
-    size_t len;
-#if SIZEOF_WCHAR_T == 2
-    wchar_t buf[3];
-#else
-    wchar_t buf[2];
-#endif
-    char outbuf[MB_LEN_MAX];
-    const wchar_t *start, *previous;
-
-#if SIZEOF_WCHAR_T == 2
-    buf[2] = 0;
-#else
-    buf[1] = 0;
-#endif
-    start = wstr;
-    while (*wstr != L'\0')
-    {
-        previous = wstr;
-#if SIZEOF_WCHAR_T == 2
-        if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
-            && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
-        {
-            buf[0] = wstr[0];
-            buf[1] = wstr[1];
-            wstr += 2;
-        }
-        else {
-            buf[0] = *wstr;
-            buf[1] = 0;
-            wstr++;
-        }
-#else
-        buf[0] = *wstr;
-        wstr++;
-#endif
-        len = wcstombs(outbuf, buf, sizeof(outbuf));
-        if (len == (size_t)-1)
-            return previous - start;
-    }
-
-    /* failed to find the unencodable character */
-    return 0;
-}
-
-static int
-locale_error_handler(const char *errors, int *surrogateescape)
-{
-    if (errors == NULL) {
-        *surrogateescape = 0;
-        return 0;
-    }
-
-    if (strcmp(errors, "strict") == 0) {
-        *surrogateescape = 0;
-        return 0;
-    }
-    if (strcmp(errors, "surrogateescape") == 0) {
-        *surrogateescape = 1;
-        return 0;
-    }
-    PyErr_Format(PyExc_ValueError,
-                 "only 'strict' and 'surrogateescape' error handlers "
-                 "are supported, not '%s'",
-                 errors);
-    return -1;
-}
-
-PyObject *
-PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
-{
-    Py_ssize_t wlen, wlen2;
-    wchar_t *wstr;
-    PyObject *bytes = NULL;
-    char *errmsg;
-    PyObject *reason = NULL;
-    PyObject *exc;
-    size_t error_pos;
-    int surrogateescape;
-
-    if (locale_error_handler(errors, &surrogateescape) < 0)
-        return NULL;
-
-    wstr = PyUnicode_AsWideCharString(unicode, &wlen);
-    if (wstr == NULL)
-        return NULL;
-
-    wlen2 = wcslen(wstr);
-    if (wlen2 != wlen) {
-        PyMem_Free(wstr);
-        PyErr_SetString(PyExc_ValueError, "embedded null character");
-        return NULL;
-    }
-
-    if (surrogateescape) {
-        /* "surrogateescape" error handler */
-        char *str;
-
-        str = Py_EncodeLocale(wstr, &error_pos);
-        if (str == NULL) {
-            if (error_pos == (size_t)-1) {
-                PyErr_NoMemory();
-                PyMem_Free(wstr);
-                return NULL;
-            }
-            else {
-                goto encode_error;
-            }
-        }
-        PyMem_Free(wstr);
-
-        bytes = PyBytes_FromString(str);
-        PyMem_Free(str);
-    }
-    else {
-        /* strict mode */
-        size_t len, len2;
-
-        len = wcstombs(NULL, wstr, 0);
-        if (len == (size_t)-1) {
-            error_pos = (size_t)-1;
-            goto encode_error;
-        }
-
-        bytes = PyBytes_FromStringAndSize(NULL, len);
-        if (bytes == NULL) {
-            PyMem_Free(wstr);
-            return NULL;
-        }
-
-        len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
-        if (len2 == (size_t)-1 || len2 > len) {
-            error_pos = (size_t)-1;
-            goto encode_error;
-        }
-        PyMem_Free(wstr);
-    }
-    return bytes;
-
-encode_error:
-    errmsg = strerror(errno);
-    assert(errmsg != NULL);
-
-    if (error_pos == (size_t)-1)
-        error_pos = wcstombs_errorpos(wstr);
-
-    PyMem_Free(wstr);
-    Py_XDECREF(bytes);
-
-    if (errmsg != NULL) {
-        size_t errlen;
-        wstr = Py_DecodeLocale(errmsg, &errlen);
-        if (wstr != NULL) {
-            reason = PyUnicode_FromWideChar(wstr, errlen);
-            PyMem_RawFree(wstr);
-        } else
-            errmsg = NULL;
-    }
-    if (errmsg == NULL)
-        reason = PyUnicode_FromString(
-            "wcstombs() encountered an unencodable "
-            "wide character");
-    if (reason == NULL)
-        return NULL;
-
-    exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
-                                "locale", unicode,
-                                (Py_ssize_t)error_pos,
-                                (Py_ssize_t)(error_pos+1),
-                                reason);
-    Py_DECREF(reason);
-    if (exc != NULL) {
-        PyCodec_StrictErrors(exc);
-        Py_XDECREF(exc);
-    }
-    return NULL;
-}
-
-PyObject *
-PyUnicode_EncodeFSDefault(PyObject *unicode)
-{
-#ifdef HAVE_MBCS
-    return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
-#elif defined(__APPLE__)
-    return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
-#else
-    PyInterpreterState *interp = PyThreadState_GET()->interp;
-    /* Bootstrap check: if the filesystem codec is implemented in Python, we
-       cannot use it to encode and decode filenames before it is loaded. Load
-       the Python codec requires to encode at least its own filename. Use the C
-       version of the locale codec until the codec registry is initialized and
-       the Python codec is loaded.
-
-       Py_FileSystemDefaultEncoding is shared between all interpreters, we
-       cannot only rely on it: check also interp->fscodec_initialized for
-       subinterpreters. */
-    if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
-        return PyUnicode_AsEncodedString(unicode,
-                                         Py_FileSystemDefaultEncoding,
-                                         "surrogateescape");
-    }
-    else {
-        return PyUnicode_EncodeLocale(unicode, "surrogateescape");
-    }
-#endif
-}
-
-PyObject *
-PyUnicode_AsEncodedString(PyObject *unicode,
-                          const char *encoding,
-                          const char *errors)
-{
-    PyObject *v;
-    char lower[11];  /* Enough for any encoding shortcut */
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-
-    /* Shortcuts for common default encodings */
-    if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
-        if ((strcmp(lower, "utf-8") == 0) ||
-            (strcmp(lower, "utf8") == 0))
-        {
-            if (errors == NULL || strcmp(errors, "strict") == 0)
-                return _PyUnicode_AsUTF8String(unicode, NULL);
-            else
-                return _PyUnicode_AsUTF8String(unicode, errors);
-        }
-        else if ((strcmp(lower, "latin-1") == 0) ||
-                 (strcmp(lower, "latin1") == 0) ||
-                 (strcmp(lower, "iso-8859-1") == 0) ||
-                 (strcmp(lower, "iso8859-1") == 0))
-            return _PyUnicode_AsLatin1String(unicode, errors);
-#ifdef HAVE_MBCS
-        else if (strcmp(lower, "mbcs") == 0)
-            return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
-#endif
-        else if (strcmp(lower, "ascii") == 0)
-            return _PyUnicode_AsASCIIString(unicode, errors);
-    }
-
-    /* Encode via the codec registry */
-    v = _PyCodec_EncodeText(unicode, encoding, errors);
-    if (v == NULL)
-        return NULL;
-
-    /* The normal path */
-    if (PyBytes_Check(v))
-        return v;
-
-    /* If the codec returns a buffer, raise a warning and convert to bytes */
-    if (PyByteArray_Check(v)) {
-        int error;
-        PyObject *b;
-
-        error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
-            "encoder %s returned bytearray instead of bytes; "
-            "use codecs.encode() to encode to arbitrary types",
-            encoding);
-        if (error) {
-            Py_DECREF(v);
-            return NULL;
-        }
-
-        b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
-        Py_DECREF(v);
-        return b;
-    }
-
-    PyErr_Format(PyExc_TypeError,
-                 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
-                 "use codecs.encode() to encode to arbitrary types",
-                 encoding,
-                 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
-    Py_DECREF(v);
-    return NULL;
-}
-
-PyObject *
-PyUnicode_AsEncodedUnicode(PyObject *unicode,
-                           const char *encoding,
-                           const char *errors)
-{
-    PyObject *v;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-
-    if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-
-    /* Encode via the codec registry */
-    v = PyCodec_Encode(unicode, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    if (!PyUnicode_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "'%.400s' encoder returned '%.400s' instead of 'str'; "
-                     "use codecs.encode() to encode to arbitrary types",
-                     encoding,
-                     Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
-        Py_DECREF(v);
-        goto onError;
-    }
-    return v;
-
-  onError:
-    return NULL;
-}
-
-static size_t
-mbstowcs_errorpos(const char *str, size_t len)
-{
-#ifdef HAVE_MBRTOWC
-    const char *start = str;
-    mbstate_t mbs;
-    size_t converted;
-    wchar_t ch;
-
-    memset(&mbs, 0, sizeof mbs);
-    while (len)
-    {
-        converted = mbrtowc(&ch, str, len, &mbs);
-        if (converted == 0)
-            /* Reached end of string */
-            break;
-        if (converted == (size_t)-1 || converted == (size_t)-2) {
-            /* Conversion error or incomplete character */
-            return str - start;
-        }
-        else {
-            str += converted;
-            len -= converted;
-        }
-    }
-    /* failed to find the undecodable byte sequence */
-    return 0;
-#endif
-    return 0;
-}
-
-PyObject*
-PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
-                              const char *errors)
-{
-    wchar_t smallbuf[256];
-    size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
-    wchar_t *wstr;
-    size_t wlen, wlen2;
-    PyObject *unicode;
-    int surrogateescape;
-    size_t error_pos;
-    char *errmsg;
-    PyObject *reason = NULL;   /* initialize to prevent gcc warning */
-    PyObject *exc;
-
-    if (locale_error_handler(errors, &surrogateescape) < 0)
-        return NULL;
-
-    if (str[len] != '\0' || (size_t)len != strlen(str))  {
-        PyErr_SetString(PyExc_ValueError, "embedded null byte");
-        return NULL;
-    }
-
-    if (surrogateescape) {
-        /* "surrogateescape" error handler */
-        wstr = Py_DecodeLocale(str, &wlen);
-        if (wstr == NULL) {
-            if (wlen == (size_t)-1)
-                PyErr_NoMemory();
-            else
-                PyErr_SetFromErrno(PyExc_OSError);
-            return NULL;
-        }
-
-        unicode = PyUnicode_FromWideChar(wstr, wlen);
-        PyMem_RawFree(wstr);
-    }
-    else {
-        /* strict mode */
-#ifndef HAVE_BROKEN_MBSTOWCS
-        wlen = mbstowcs(NULL, str, 0);
-#else
-        wlen = len;
-#endif
-        if (wlen == (size_t)-1)
-            goto decode_error;
-        if (wlen+1 <= smallbuf_len) {
-            wstr = smallbuf;
-        }
-        else {
-            wstr = PyMem_New(wchar_t, wlen+1);
-            if (!wstr)
-                return PyErr_NoMemory();
-        }
-
-        wlen2 = mbstowcs(wstr, str, wlen+1);
-        if (wlen2 == (size_t)-1) {
-            if (wstr != smallbuf)
-                PyMem_Free(wstr);
-            goto decode_error;
-        }
-#ifdef HAVE_BROKEN_MBSTOWCS
-        assert(wlen2 == wlen);
-#endif
-        unicode = PyUnicode_FromWideChar(wstr, wlen2);
-        if (wstr != smallbuf)
-            PyMem_Free(wstr);
-    }
-    return unicode;
-
-decode_error:
-    errmsg = strerror(errno);
-    assert(errmsg != NULL);
-
-    error_pos = mbstowcs_errorpos(str, len);
-    if (errmsg != NULL) {
-        size_t errlen;
-        wstr = Py_DecodeLocale(errmsg, &errlen);
-        if (wstr != NULL) {
-            reason = PyUnicode_FromWideChar(wstr, errlen);
-            PyMem_RawFree(wstr);
-        } else
-            errmsg = NULL;
-    }
-    if (errmsg == NULL)
-        reason = PyUnicode_FromString(
-            "mbstowcs() encountered an invalid multibyte sequence");
-    if (reason == NULL)
-        return NULL;
-
-    exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
-                                "locale", str, len,
-                                (Py_ssize_t)error_pos,
-                                (Py_ssize_t)(error_pos+1),
-                                reason);
-    Py_DECREF(reason);
-    if (exc != NULL) {
-        PyCodec_StrictErrors(exc);
-        Py_XDECREF(exc);
-    }
-    return NULL;
-}
-
-PyObject*
-PyUnicode_DecodeLocale(const char *str, const char *errors)
-{
-    Py_ssize_t size = (Py_ssize_t)strlen(str);
-    return PyUnicode_DecodeLocaleAndSize(str, size, errors);
-}
-
-
-PyObject*
-PyUnicode_DecodeFSDefault(const char *s) {
-    Py_ssize_t size = (Py_ssize_t)strlen(s);
-    return PyUnicode_DecodeFSDefaultAndSize(s, size);
-}
-
-PyObject*
-PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
-{
-#ifdef HAVE_MBCS
-    return PyUnicode_DecodeMBCS(s, size, NULL);
-#elif defined(__APPLE__)
-    return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
-#else
-    PyInterpreterState *interp = PyThreadState_GET()->interp;
-    /* Bootstrap check: if the filesystem codec is implemented in Python, we
-       cannot use it to encode and decode filenames before it is loaded. Load
-       the Python codec requires to encode at least its own filename. Use the C
-       version of the locale codec until the codec registry is initialized and
-       the Python codec is loaded.
-
-       Py_FileSystemDefaultEncoding is shared between all interpreters, we
-       cannot only rely on it: check also interp->fscodec_initialized for
-       subinterpreters. */
-    if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
-        return PyUnicode_Decode(s, size,
-                                Py_FileSystemDefaultEncoding,
-                                "surrogateescape");
-    }
-    else {
-        return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
-    }
-#endif
-}
-
-
-int
-_PyUnicode_HasNULChars(PyObject* str)
-{
-    Py_ssize_t pos;
-
-    if (PyUnicode_READY(str) == -1)
-        return -1;
-    pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
-                   PyUnicode_GET_LENGTH(str), '\0', 1);
-    if (pos == -1)
-        return 0;
-    else
-        return 1;
-}
-
-int
-PyUnicode_FSConverter(PyObject* arg, void* addr)
-{
-    PyObject *output = NULL;
-    Py_ssize_t size;
-    void *data;
-    if (arg == NULL) {
-        Py_DECREF(*(PyObject**)addr);
-        return 1;
-    }
-    if (PyBytes_Check(arg)) {
-        output = arg;
-        Py_INCREF(output);
-    }
-    else {
-        arg = PyUnicode_FromObject(arg);
-        if (!arg)
-            return 0;
-        output = PyUnicode_EncodeFSDefault(arg);
-        Py_DECREF(arg);
-        if (!output)
-            return 0;
-        if (!PyBytes_Check(output)) {
-            Py_DECREF(output);
-            PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
-            return 0;
-        }
-    }
-    size = PyBytes_GET_SIZE(output);
-    data = PyBytes_AS_STRING(output);
-    if ((size_t)size != strlen(data)) {
-        PyErr_SetString(PyExc_ValueError, "embedded null byte");
-        Py_DECREF(output);
-        return 0;
-    }
-    *(PyObject**)addr = output;
-    return Py_CLEANUP_SUPPORTED;
-}
-
-
-int
-PyUnicode_FSDecoder(PyObject* arg, void* addr)
-{
-    PyObject *output = NULL;
-    if (arg == NULL) {
-        Py_DECREF(*(PyObject**)addr);
-        return 1;
-    }
-    if (PyUnicode_Check(arg)) {
-        if (PyUnicode_READY(arg) == -1)
-            return 0;
-        output = arg;
-        Py_INCREF(output);
-    }
-    else {
-        arg = PyBytes_FromObject(arg);
-        if (!arg)
-            return 0;
-        output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
-                                                  PyBytes_GET_SIZE(arg));
-        Py_DECREF(arg);
-        if (!output)
-            return 0;
-        if (!PyUnicode_Check(output)) {
-            Py_DECREF(output);
-            PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
-            return 0;
-        }
-    }
-    if (PyUnicode_READY(output) == -1) {
-        Py_DECREF(output);
-        return 0;
-    }
-    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
-                 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
-        PyErr_SetString(PyExc_ValueError, "embedded null character");
-        Py_DECREF(output);
-        return 0;
-    }
-    *(PyObject**)addr = output;
-    return Py_CLEANUP_SUPPORTED;
-}
-
-
-char*
-PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
-{
-    PyObject *bytes;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-
-    if (PyUnicode_UTF8(unicode) == NULL) {
-        assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
-        bytes = _PyUnicode_AsUTF8String(unicode, "strict");
-        if (bytes == NULL)
-            return NULL;
-        _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
-        if (_PyUnicode_UTF8(unicode) == NULL) {
-            PyErr_NoMemory();
-            Py_DECREF(bytes);
-            return NULL;
-        }
-        _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
-        Py_MEMCPY(_PyUnicode_UTF8(unicode),
-                  PyBytes_AS_STRING(bytes),
-                  _PyUnicode_UTF8_LENGTH(unicode) + 1);
-        Py_DECREF(bytes);
-    }
-
-    if (psize)
-        *psize = PyUnicode_UTF8_LENGTH(unicode);
-    return PyUnicode_UTF8(unicode);
-}
-
-char*
-PyUnicode_AsUTF8(PyObject *unicode)
-{
-    return PyUnicode_AsUTF8AndSize(unicode, NULL);
-}
-
-Py_UNICODE *
-PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
-{
-    const unsigned char *one_byte;
-#if SIZEOF_WCHAR_T == 4
-    const Py_UCS2 *two_bytes;
-#else
-    const Py_UCS4 *four_bytes;
-    const Py_UCS4 *ucs4_end;
-    Py_ssize_t num_surrogates;
-#endif
-    wchar_t *w;
-    wchar_t *wchar_end;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (_PyUnicode_WSTR(unicode) == NULL) {
-        /* Non-ASCII compact unicode object */
-        assert(_PyUnicode_KIND(unicode) != 0);
-        assert(PyUnicode_IS_READY(unicode));
-
-        if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
-#if SIZEOF_WCHAR_T == 2
-            four_bytes = PyUnicode_4BYTE_DATA(unicode);
-            ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
-            num_surrogates = 0;
-
-            for (; four_bytes < ucs4_end; ++four_bytes) {
-                if (*four_bytes > 0xFFFF)
-                    ++num_surrogates;
-            }
-
-            _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
-                    sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
-            if (!_PyUnicode_WSTR(unicode)) {
-                PyErr_NoMemory();
-                return NULL;
-            }
-            _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
-
-            w = _PyUnicode_WSTR(unicode);
-            wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
-            four_bytes = PyUnicode_4BYTE_DATA(unicode);
-            for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
-                if (*four_bytes > 0xFFFF) {
-                    assert(*four_bytes <= MAX_UNICODE);
-                    /* encode surrogate pair in this case */
-                    *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
-                    *w   = Py_UNICODE_LOW_SURROGATE(*four_bytes);
-                }
-                else
-                    *w = *four_bytes;
-
-                if (w > wchar_end) {
-                    assert(0 && "Miscalculated string end");
-                }
-            }
-            *w = 0;
-#else
-            /* sizeof(wchar_t) == 4 */
-            Py_FatalError("Impossible unicode object state, wstr and str "
-                          "should share memory already.");
-            return NULL;
-#endif
-        }
-        else {
-            if ((size_t)_PyUnicode_LENGTH(unicode) >
-                    PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
-                PyErr_NoMemory();
-                return NULL;
-            }
-            _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
-                                                  (_PyUnicode_LENGTH(unicode) + 1));
-            if (!_PyUnicode_WSTR(unicode)) {
-                PyErr_NoMemory();
-                return NULL;
-            }
-            if (!PyUnicode_IS_COMPACT_ASCII(unicode))
-                _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
-            w = _PyUnicode_WSTR(unicode);
-            wchar_end = w + _PyUnicode_LENGTH(unicode);
-
-            if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
-                one_byte = PyUnicode_1BYTE_DATA(unicode);
-                for (; w < wchar_end; ++one_byte, ++w)
-                    *w = *one_byte;
-                /* null-terminate the wstr */
-                *w = 0;
-            }
-            else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
-#if SIZEOF_WCHAR_T == 4
-                two_bytes = PyUnicode_2BYTE_DATA(unicode);
-                for (; w < wchar_end; ++two_bytes, ++w)
-                    *w = *two_bytes;
-                /* null-terminate the wstr */
-                *w = 0;
-#else
-                /* sizeof(wchar_t) == 2 */
-                PyObject_FREE(_PyUnicode_WSTR(unicode));
-                _PyUnicode_WSTR(unicode) = NULL;
-                Py_FatalError("Impossible unicode object state, wstr "
-                              "and str should share memory already.");
-                return NULL;
-#endif
-            }
-            else {
-                assert(0 && "This should never happen.");
-            }
-        }
-    }
-    if (size != NULL)
-        *size = PyUnicode_WSTR_LENGTH(unicode);
-    return _PyUnicode_WSTR(unicode);
-}
-
-Py_UNICODE *
-PyUnicode_AsUnicode(PyObject *unicode)
-{
-    return PyUnicode_AsUnicodeAndSize(unicode, NULL);
-}
-
-
-Py_ssize_t
-PyUnicode_GetSize(PyObject *unicode)
-{
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-    return PyUnicode_GET_SIZE(unicode);
-
-  onError:
-    return -1;
-}
-
-Py_ssize_t
-PyUnicode_GetLength(PyObject *unicode)
-{
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return -1;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return -1;
-    return PyUnicode_GET_LENGTH(unicode);
-}
-
-Py_UCS4
-PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
-{
-    void *data;
-    int kind;
-
-    if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
-        PyErr_BadArgument();
-        return (Py_UCS4)-1;
-    }
-    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return (Py_UCS4)-1;
-    }
-    data = PyUnicode_DATA(unicode);
-    kind = PyUnicode_KIND(unicode);
-    return PyUnicode_READ(kind, data, index);
-}
-
-int
-PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
-{
-    if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
-        PyErr_BadArgument();
-        return -1;
-    }
-    assert(PyUnicode_IS_READY(unicode));
-    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return -1;
-    }
-    if (unicode_check_modifiable(unicode))
-        return -1;
-    if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
-        PyErr_SetString(PyExc_ValueError, "character out of range");
-        return -1;
-    }
-    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
-                    index, ch);
-    return 0;
-}
-
-const char *
-PyUnicode_GetDefaultEncoding(void)
-{
-    return "utf-8";
-}
-
-/* create or adjust a UnicodeDecodeError */
-static void
-make_decode_exception(PyObject **exceptionObject,
-                      const char *encoding,
-                      const char *input, Py_ssize_t length,
-                      Py_ssize_t startpos, Py_ssize_t endpos,
-                      const char *reason)
-{
-    if (*exceptionObject == NULL) {
-        *exceptionObject = PyUnicodeDecodeError_Create(
-            encoding, input, length, startpos, endpos, reason);
-    }
-    else {
-        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
-            goto onError;
-        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
-            goto onError;
-        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
-            goto onError;
-    }
-    return;
-
-onError:
-    Py_CLEAR(*exceptionObject);
-}
-
-#ifdef HAVE_MBCS
-/* error handling callback helper:
-   build arguments, call the callback and check the arguments,
-   if no exception occurred, copy the replacement to the output
-   and adjust various state variables.
-   return 0 on success, -1 on error
-*/
-
-static int
-unicode_decode_call_errorhandler_wchar(
-    const char *errors, PyObject **errorHandler,
-    const char *encoding, const char *reason,
-    const char **input, const char **inend, Py_ssize_t *startinpos,
-    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
-    PyObject **output, Py_ssize_t *outpos)
-{
-    static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
-
-    PyObject *restuple = NULL;
-    PyObject *repunicode = NULL;
-    Py_ssize_t outsize;
-    Py_ssize_t insize;
-    Py_ssize_t requiredsize;
-    Py_ssize_t newpos;
-    PyObject *inputobj = NULL;
-    wchar_t *repwstr;
-    Py_ssize_t repwlen;
-
-    assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
-    outsize = _PyUnicode_WSTR_LENGTH(*output);
-
-    if (*errorHandler == NULL) {
-        *errorHandler = PyCodec_LookupError(errors);
-        if (*errorHandler == NULL)
-            goto onError;
-    }
-
-    make_decode_exception(exceptionObject,
-        encoding,
-        *input, *inend - *input,
-        *startinpos, *endinpos,
-        reason);
-    if (*exceptionObject == NULL)
-        goto onError;
-
-    restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
-    if (restuple == NULL)
-        goto onError;
-    if (!PyTuple_Check(restuple)) {
-        PyErr_SetString(PyExc_TypeError, &argparse[4]);
-        goto onError;
-    }
-    if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
-        goto onError;
-
-    /* Copy back the bytes variables, which might have been modified by the
-       callback */
-    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
-    if (!inputobj)
-        goto onError;
-    if (!PyBytes_Check(inputobj)) {
-        PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
-    }
-    *input = PyBytes_AS_STRING(inputobj);
-    insize = PyBytes_GET_SIZE(inputobj);
-    *inend = *input + insize;
-    /* we can DECREF safely, as the exception has another reference,
-       so the object won't go away. */
-    Py_DECREF(inputobj);
-
-    if (newpos<0)
-        newpos = insize+newpos;
-    if (newpos<0 || newpos>insize) {
-        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
-        goto onError;
-    }
-
-    repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
-    if (repwstr == NULL)
-        goto onError;
-    /* need more space? (at least enough for what we
-       have+the replacement+the rest of the string (starting
-       at the new input position), so we won't have to check space
-       when there are no errors in the rest of the string) */
-    requiredsize = *outpos;
-    if (requiredsize > PY_SSIZE_T_MAX - repwlen)
-        goto overflow;
-    requiredsize += repwlen;
-    if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
-        goto overflow;
-    requiredsize += insize - newpos;
-    if (requiredsize > outsize) {
-        if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
-            requiredsize = 2*outsize;
-        if (unicode_resize(output, requiredsize) < 0)
-            goto onError;
-    }
-    wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
-    *outpos += repwlen;
-    *endinpos = newpos;
-    *inptr = *input + newpos;
-
-    /* we made it! */
-    Py_XDECREF(restuple);
-    return 0;
-
-  overflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "decoded result is too long for a Python string");
-
-  onError:
-    Py_XDECREF(restuple);
-    return -1;
-}
-#endif   /* HAVE_MBCS */
-
-static int
-unicode_decode_call_errorhandler_writer(
-    const char *errors, PyObject **errorHandler,
-    const char *encoding, const char *reason,
-    const char **input, const char **inend, Py_ssize_t *startinpos,
-    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
-    _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
-{
-    static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
-
-    PyObject *restuple = NULL;
-    PyObject *repunicode = NULL;
-    Py_ssize_t insize;
-    Py_ssize_t newpos;
-    Py_ssize_t replen;
-    PyObject *inputobj = NULL;
-
-    if (*errorHandler == NULL) {
-        *errorHandler = PyCodec_LookupError(errors);
-        if (*errorHandler == NULL)
-            goto onError;
-    }
-
-    make_decode_exception(exceptionObject,
-        encoding,
-        *input, *inend - *input,
-        *startinpos, *endinpos,
-        reason);
-    if (*exceptionObject == NULL)
-        goto onError;
-
-    restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
-    if (restuple == NULL)
-        goto onError;
-    if (!PyTuple_Check(restuple)) {
-        PyErr_SetString(PyExc_TypeError, &argparse[4]);
-        goto onError;
-    }
-    if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
-        goto onError;
-
-    /* Copy back the bytes variables, which might have been modified by the
-       callback */
-    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
-    if (!inputobj)
-        goto onError;
-    if (!PyBytes_Check(inputobj)) {
-        PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
-    }
-    *input = PyBytes_AS_STRING(inputobj);
-    insize = PyBytes_GET_SIZE(inputobj);
-    *inend = *input + insize;
-    /* we can DECREF safely, as the exception has another reference,
-       so the object won't go away. */
-    Py_DECREF(inputobj);
-
-    if (newpos<0)
-        newpos = insize+newpos;
-    if (newpos<0 || newpos>insize) {
-        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
-        goto onError;
-    }
-
-    if (PyUnicode_READY(repunicode) < 0)
-        goto onError;
-    replen = PyUnicode_GET_LENGTH(repunicode);
-    if (replen > 1) {
-        writer->min_length += replen - 1;
-        writer->overallocate = 1;
-        if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
-                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
-            goto onError;
-    }
-    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
-        goto onError;
-
-    *endinpos = newpos;
-    *inptr = *input + newpos;
-
-    /* we made it! */
-    Py_XDECREF(restuple);
-    return 0;
-
-  onError:
-    Py_XDECREF(restuple);
-    return -1;
-}
-
-/* --- UTF-7 Codec -------------------------------------------------------- */
-
-/* See RFC2152 for details.  We encode conservatively and decode liberally. */
-
-/* Three simple macros defining base-64. */
-
-/* Is c a base-64 character? */
-
-#define IS_BASE64(c) \
-    (((c) >= 'A' && (c) <= 'Z') ||     \
-     ((c) >= 'a' && (c) <= 'z') ||     \
-     ((c) >= '0' && (c) <= '9') ||     \
-     (c) == '+' || (c) == '/')
-
-/* given that c is a base-64 character, what is its base-64 value? */
-
-#define FROM_BASE64(c)                                                  \
-    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
-     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
-     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
-     (c) == '+' ? 62 : 63)
-
-/* What is the base-64 character of the bottom 6 bits of n? */
-
-#define TO_BASE64(n)  \
-    ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
-
-/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
- * decoded as itself.  We are permissive on decoding; the only ASCII
- * byte not decoding to itself is the + which begins a base64
- * string. */
-
-#define DECODE_DIRECT(c)                                \
-    ((c) <= 127 && (c) != '+')
-
-/* The UTF-7 encoder treats ASCII characters differently according to
- * whether they are Set D, Set O, Whitespace, or special (i.e. none of
- * the above).  See RFC2152.  This array identifies these different
- * sets:
- * 0 : "Set D"
- *     alphanumeric and '(),-./:?
- * 1 : "Set O"
- *     !"#$%&*;<=>@[]^_`{|}
- * 2 : "whitespace"
- *     ht nl cr sp
- * 3 : special (must be base64 encoded)
- *     everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
- */
-
-static
-char utf7_category[128] = {
-/* nul soh stx etx eot enq ack bel bs  ht  nl  vt  np  cr  so  si  */
-    3,  3,  3,  3,  3,  3,  3,  3,  3,  2,  2,  3,  3,  2,  3,  3,
-/* dle dc1 dc2 dc3 dc4 nak syn etb can em  sub esc fs  gs  rs  us  */
-    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
-/* sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /  */
-    2,  1,  1,  1,  1,  1,  1,  0,  0,  0,  1,  3,  0,  0,  0,  0,
-/*  0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?  */
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0,
-/*  @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O  */
-    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-/*  P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _  */
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  3,  1,  1,  1,
-/*  `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o  */
-    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-/*  p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~  del */
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  3,  3,
-};
-
-/* ENCODE_DIRECT: this character should be encoded as itself.  The
- * answer depends on whether we are encoding set O as itself, and also
- * on whether we are encoding whitespace as itself.  RFC2152 makes it
- * clear that the answers to these questions vary between
- * applications, so this code needs to be flexible.  */
-
-#define ENCODE_DIRECT(c, directO, directWS)             \
-    ((c) < 128 && (c) > 0 &&                            \
-     ((utf7_category[(c)] == 0) ||                      \
-      (directWS && (utf7_category[(c)] == 2)) ||        \
-      (directO && (utf7_category[(c)] == 1))))
-
-PyObject *
-PyUnicode_DecodeUTF7(const char *s,
-                     Py_ssize_t size,
-                     const char *errors)
-{
-    return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
-}
-
-/* The decoder.  The only state we preserve is our read position,
- * i.e. how many characters we have consumed.  So if we end in the
- * middle of a shift sequence we have to back off the read position
- * and the output to the beginning of the sequence, otherwise we lose
- * all the shift state (seen bits, number of bits seen, high
- * surrogate). */
-
-PyObject *
-PyUnicode_DecodeUTF7Stateful(const char *s,
-                             Py_ssize_t size,
-                             const char *errors,
-                             Py_ssize_t *consumed)
-{
-    const char *starts = s;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    const char *e;
-    _PyUnicodeWriter writer;
-    const char *errmsg = "";
-    int inShift = 0;
-    Py_ssize_t shiftOutStart;
-    unsigned int base64bits = 0;
-    unsigned long base64buffer = 0;
-    Py_UCS4 surrogate = 0;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-
-    if (size == 0) {
-        if (consumed)
-            *consumed = 0;
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-    /* Start off assuming it's all ASCII. Widen later as necessary. */
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = size;
-
-    shiftOutStart = 0;
-    e = s + size;
-
-    while (s < e) {
-        Py_UCS4 ch;
-      restart:
-        ch = (unsigned char) *s;
-
-        if (inShift) { /* in a base-64 section */
-            if (IS_BASE64(ch)) { /* consume a base-64 character */
-                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
-                base64bits += 6;
-                s++;
-                if (base64bits >= 16) {
-                    /* we have enough bits for a UTF-16 value */
-                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
-                    base64bits -= 16;
-                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
-                    assert(outCh <= 0xffff);
-                    if (surrogate) {
-                        /* expecting a second surrogate */
-                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
-                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
-                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
-                                goto onError;
-                            surrogate = 0;
-                            continue;
-                        }
-                        else {
-                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
-                                goto onError;
-                            surrogate = 0;
-                        }
-                    }
-                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
-                        /* first surrogate */
-                        surrogate = outCh;
-                    }
-                    else {
-                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
-                            goto onError;
-                    }
-                }
-            }
-            else { /* now leaving a base-64 section */
-                inShift = 0;
-                s++;
-                if (surrogate) {
-                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
-                        goto onError;
-                    surrogate = 0;
-                }
-                if (base64bits > 0) { /* left-over bits */
-                    if (base64bits >= 6) {
-                        /* We've seen at least one base-64 character */
-                        errmsg = "partial character in shift sequence";
-                        goto utf7Error;
-                    }
-                    else {
-                        /* Some bits remain; they should be zero */
-                        if (base64buffer != 0) {
-                            errmsg = "non-zero padding bits in shift sequence";
-                            goto utf7Error;
-                        }
-                    }
-                }
-                if (ch != '-') {
-                    /* '-' is absorbed; other terminating
-                       characters are preserved */
-                    if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
-                        goto onError;
-                }
-            }
-        }
-        else if ( ch == '+' ) {
-            startinpos = s-starts;
-            s++; /* consume '+' */
-            if (s < e && *s == '-') { /* '+-' encodes '+' */
-                s++;
-                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
-                    goto onError;
-            }
-            else { /* begin base64-encoded section */
-                inShift = 1;
-                shiftOutStart = writer.pos;
-                base64bits = 0;
-                base64buffer = 0;
-            }
-        }
-        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
-            s++;
-            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
-                goto onError;
-        }
-        else {
-            startinpos = s-starts;
-            s++;
-            errmsg = "unexpected special character";
-            goto utf7Error;
-        }
-        continue;
-utf7Error:
-        endinpos = s-starts;
-        if (unicode_decode_call_errorhandler_writer(
-                errors, &errorHandler,
-                "utf7", errmsg,
-                &starts, &e, &startinpos, &endinpos, &exc, &s,
-                &writer))
-            goto onError;
-    }
-
-    /* end of string */
-
-    if (inShift && !consumed) { /* in shift sequence, no more to follow */
-        /* if we're in an inconsistent state, that's an error */
-        if (surrogate ||
-                (base64bits >= 6) ||
-                (base64bits > 0 && base64buffer != 0)) {
-            endinpos = size;
-            if (unicode_decode_call_errorhandler_writer(
-                    errors, &errorHandler,
-                    "utf7", "unterminated shift sequence",
-                    &starts, &e, &startinpos, &endinpos, &exc, &s,
-                    &writer))
-                goto onError;
-            if (s < e)
-                goto restart;
-        }
-    }
-
-    /* return state */
-    if (consumed) {
-        if (inShift) {
-            *consumed = startinpos;
-            if (writer.pos != shiftOutStart && writer.maxchar > 127) {
-                PyObject *result = PyUnicode_FromKindAndData(
-                        writer.kind, writer.data, shiftOutStart);
-                Py_XDECREF(errorHandler);
-                Py_XDECREF(exc);
-                _PyUnicodeWriter_Dealloc(&writer);
-                return result;
-            }
-            writer.pos = shiftOutStart; /* back off output */
-        }
-        else {
-            *consumed = s-starts;
-        }
-    }
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    _PyUnicodeWriter_Dealloc(&writer);
-    return NULL;
-}
-
-
-PyObject *
-_PyUnicode_EncodeUTF7(PyObject *str,
-                      int base64SetO,
-                      int base64WhiteSpace,
-                      const char *errors)
-{
-    int kind;
-    void *data;
-    Py_ssize_t len;
-    PyObject *v;
-    int inShift = 0;
-    Py_ssize_t i;
-    unsigned int base64bits = 0;
-    unsigned long base64buffer = 0;
-    char * out;
-    char * start;
-
-    if (PyUnicode_READY(str) == -1)
-        return NULL;
-    kind = PyUnicode_KIND(str);
-    data = PyUnicode_DATA(str);
-    len = PyUnicode_GET_LENGTH(str);
-
-    if (len == 0)
-        return PyBytes_FromStringAndSize(NULL, 0);
-
-    /* It might be possible to tighten this worst case */
-    if (len > PY_SSIZE_T_MAX / 8)
-        return PyErr_NoMemory();
-    v = PyBytes_FromStringAndSize(NULL, len * 8);
-    if (v == NULL)
-        return NULL;
-
-    start = out = PyBytes_AS_STRING(v);
-    for (i = 0; i < len; ++i) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-
-        if (inShift) {
-            if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
-                /* shifting out */
-                if (base64bits) { /* output remaining bits */
-                    *out++ = TO_BASE64(base64buffer << (6-base64bits));
-                    base64buffer = 0;
-                    base64bits = 0;
-                }
-                inShift = 0;
-                /* Characters not in the BASE64 set implicitly unshift the sequence
-                   so no '-' is required, except if the character is itself a '-' */
-                if (IS_BASE64(ch) || ch == '-') {
-                    *out++ = '-';
-                }
-                *out++ = (char) ch;
-            }
-            else {
-                goto encode_char;
-            }
-        }
-        else { /* not in a shift sequence */
-            if (ch == '+') {
-                *out++ = '+';
-                        *out++ = '-';
-            }
-            else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
-                *out++ = (char) ch;
-            }
-            else {
-                *out++ = '+';
-                inShift = 1;
-                goto encode_char;
-            }
-        }
-        continue;
-encode_char:
-        if (ch >= 0x10000) {
-            assert(ch <= MAX_UNICODE);
-
-            /* code first surrogate */
-            base64bits += 16;
-            base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
-            while (base64bits >= 6) {
-                *out++ = TO_BASE64(base64buffer >> (base64bits-6));
-                base64bits -= 6;
-            }
-            /* prepare second surrogate */
-            ch = Py_UNICODE_LOW_SURROGATE(ch);
-        }
-        base64bits += 16;
-        base64buffer = (base64buffer << 16) | ch;
-        while (base64bits >= 6) {
-            *out++ = TO_BASE64(base64buffer >> (base64bits-6));
-            base64bits -= 6;
-        }
-    }
-    if (base64bits)
-        *out++= TO_BASE64(base64buffer << (6-base64bits) );
-    if (inShift)
-        *out++ = '-';
-    if (_PyBytes_Resize(&v, out - start) < 0)
-        return NULL;
-    return v;
-}
-PyObject *
-PyUnicode_EncodeUTF7(const Py_UNICODE *s,
-                     Py_ssize_t size,
-                     int base64SetO,
-                     int base64WhiteSpace,
-                     const char *errors)
-{
-    PyObject *result;
-    PyObject *tmp = PyUnicode_FromUnicode(s, size);
-    if (tmp == NULL)
-        return NULL;
-    result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
-                                   base64WhiteSpace, errors);
-    Py_DECREF(tmp);
-    return result;
-}
-
-#undef IS_BASE64
-#undef FROM_BASE64
-#undef TO_BASE64
-#undef DECODE_DIRECT
-#undef ENCODE_DIRECT
-
-/* --- UTF-8 Codec -------------------------------------------------------- */
-
-PyObject *
-PyUnicode_DecodeUTF8(const char *s,
-                     Py_ssize_t size,
-                     const char *errors)
-{
-    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
-}
-
-#include "stringlib/asciilib.h"
-#include "stringlib/codecs.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/ucs1lib.h"
-#include "stringlib/codecs.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/ucs2lib.h"
-#include "stringlib/codecs.h"
-#include "stringlib/undef.h"
-
-#include "stringlib/ucs4lib.h"
-#include "stringlib/codecs.h"
-#include "stringlib/undef.h"
-
-/* Mask to quickly check whether a C 'long' contains a
-   non-ASCII, UTF8-encoded char. */
-#if (SIZEOF_LONG == 8)
-# define ASCII_CHAR_MASK 0x8080808080808080UL
-#elif (SIZEOF_LONG == 4)
-# define ASCII_CHAR_MASK 0x80808080UL
-#else
-# error C 'long' size should be either 4 or 8!
-#endif
-
-static Py_ssize_t
-ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
-{
-    const char *p = start;
-    const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
-
-    /*
-     * Issue #17237: m68k is a bit different from most architectures in
-     * that objects do not use "natural alignment" - for example, int and
-     * long are only aligned at 2-byte boundaries.  Therefore the assert()
-     * won't work; also, tests have shown that skipping the "optimised
-     * version" will even speed up m68k.
-     */
-#if !defined(__m68k__)
-#if SIZEOF_LONG <= SIZEOF_VOID_P
-    assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
-    if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
-        /* Fast path, see in STRINGLIB(utf8_decode) for
-           an explanation. */
-        /* Help allocation */
-        const char *_p = p;
-        Py_UCS1 * q = dest;
-        while (_p < aligned_end) {
-            unsigned long value = *(const unsigned long *) _p;
-            if (value & ASCII_CHAR_MASK)
-                break;
-            *((unsigned long *)q) = value;
-            _p += SIZEOF_LONG;
-            q += SIZEOF_LONG;
-        }
-        p = _p;
-        while (p < end) {
-            if ((unsigned char)*p & 0x80)
-                break;
-            *q++ = *p++;
-        }
-        return p - start;
-    }
-#endif
-#endif
-    while (p < end) {
-        /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
-           for an explanation. */
-        if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
-            /* Help allocation */
-            const char *_p = p;
-            while (_p < aligned_end) {
-                unsigned long value = *(unsigned long *) _p;
-                if (value & ASCII_CHAR_MASK)
-                    break;
-                _p += SIZEOF_LONG;
-            }
-            p = _p;
-            if (_p == end)
-                break;
-        }
-        if ((unsigned char)*p & 0x80)
-            break;
-        ++p;
-    }
-    memcpy(dest, start, p - start);
-    return p - start;
-}
-
-PyObject *
-PyUnicode_DecodeUTF8Stateful(const char *s,
-                             Py_ssize_t size,
-                             const char *errors,
-                             Py_ssize_t *consumed)
-{
-    _PyUnicodeWriter writer;
-    const char *starts = s;
-    const char *end = s + size;
-
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    const char *errmsg = "";
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-
-    if (size == 0) {
-        if (consumed)
-            *consumed = 0;
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
-    if (size == 1 && (unsigned char)s[0] < 128) {
-        if (consumed)
-            *consumed = 1;
-        return get_latin1_char((unsigned char)s[0]);
-    }
-
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = size;
-    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
-        goto onError;
-
-    writer.pos = ascii_decode(s, end, writer.data);
-    s += writer.pos;
-    while (s < end) {
-        Py_UCS4 ch;
-        int kind = writer.kind;
-        if (kind == PyUnicode_1BYTE_KIND) {
-            if (PyUnicode_IS_ASCII(writer.buffer))
-                ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
-            else
-                ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
-        } else if (kind == PyUnicode_2BYTE_KIND) {
-            ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
-        } else {
-            assert(kind == PyUnicode_4BYTE_KIND);
-            ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
-        }
-
-        switch (ch) {
-        case 0:
-            if (s == end || consumed)
-                goto End;
-            errmsg = "unexpected end of data";
-            startinpos = s - starts;
-            endinpos = end - starts;
-            break;
-        case 1:
-            errmsg = "invalid start byte";
-            startinpos = s - starts;
-            endinpos = startinpos + 1;
-            break;
-        case 2:
-        case 3:
-        case 4:
-            errmsg = "invalid continuation byte";
-            startinpos = s - starts;
-            endinpos = startinpos + ch - 1;
-            break;
-        default:
-            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
-                goto onError;
-            continue;
-        }
-
-        if (unicode_decode_call_errorhandler_writer(
-                errors, &errorHandler,
-                "utf-8", errmsg,
-                &starts, &end, &startinpos, &endinpos, &exc, &s,
-                &writer))
-            goto onError;
-    }
-
-End:
-    if (consumed)
-        *consumed = s - starts;
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-onError:
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    _PyUnicodeWriter_Dealloc(&writer);
-    return NULL;
-}
-
-#ifdef __APPLE__
-
-/* Simplified UTF-8 decoder using surrogateescape error handler,
-   used to decode the command line arguments on Mac OS X.
-
-   Return a pointer to a newly allocated wide character string (use
-   PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
-
-wchar_t*
-_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
-{
-    const char *e;
-    wchar_t *unicode;
-    Py_ssize_t outpos;
-
-    /* Note: size will always be longer than the resulting Unicode
-       character count */
-    if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
-        return NULL;
-    unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
-    if (!unicode)
-        return NULL;
-
-    /* Unpack UTF-8 encoded data */
-    e = s + size;
-    outpos = 0;
-    while (s < e) {
-        Py_UCS4 ch;
-#if SIZEOF_WCHAR_T == 4
-        ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
-#else
-        ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
-#endif
-        if (ch > 0xFF) {
-#if SIZEOF_WCHAR_T == 4
-            assert(0);
-#else
-            assert(Py_UNICODE_IS_SURROGATE(ch));
-            /*  compute and append the two surrogates: */
-            unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
-            unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
-#endif
-        }
-        else {
-            if (!ch && s == e)
-                break;
-            /* surrogateescape */
-            unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
-        }
-    }
-    unicode[outpos] = L'\0';
-    return unicode;
-}
-
-#endif /* __APPLE__ */
-
-/* Primary internal function which creates utf8 encoded bytes objects.
-
-   Allocation strategy:  if the string is short, convert into a stack buffer
-   and allocate exactly as much space needed at the end.  Else allocate the
-   maximum possible needed (4 result bytes per Unicode character), and return
-   the excess memory at the end.
-*/
-PyObject *
-_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
-{
-    enum PyUnicode_Kind kind;
-    void *data;
-    Py_ssize_t size;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-
-    if (PyUnicode_UTF8(unicode))
-        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
-                                         PyUnicode_UTF8_LENGTH(unicode));
-
-    kind = PyUnicode_KIND(unicode);
-    data = PyUnicode_DATA(unicode);
-    size = PyUnicode_GET_LENGTH(unicode);
-
-    switch (kind) {
-    default:
-        assert(0);
-    case PyUnicode_1BYTE_KIND:
-        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
-        assert(!PyUnicode_IS_ASCII(unicode));
-        return ucs1lib_utf8_encoder(unicode, data, size, errors);
-    case PyUnicode_2BYTE_KIND:
-        return ucs2lib_utf8_encoder(unicode, data, size, errors);
-    case PyUnicode_4BYTE_KIND:
-        return ucs4lib_utf8_encoder(unicode, data, size, errors);
-    }
-}
-
-PyObject *
-PyUnicode_EncodeUTF8(const Py_UNICODE *s,
-                     Py_ssize_t size,
-                     const char *errors)
-{
-    PyObject *v, *unicode;
-
-    unicode = PyUnicode_FromUnicode(s, size);
-    if (unicode == NULL)
-        return NULL;
-    v = _PyUnicode_AsUTF8String(unicode, errors);
-    Py_DECREF(unicode);
-    return v;
-}
-
-PyObject *
-PyUnicode_AsUTF8String(PyObject *unicode)
-{
-    return _PyUnicode_AsUTF8String(unicode, NULL);
-}
-
-/* --- UTF-32 Codec ------------------------------------------------------- */
-
-PyObject *
-PyUnicode_DecodeUTF32(const char *s,
-                      Py_ssize_t size,
-                      const char *errors,
-                      int *byteorder)
-{
-    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
-}
-
-PyObject *
-PyUnicode_DecodeUTF32Stateful(const char *s,
-                              Py_ssize_t size,
-                              const char *errors,
-                              int *byteorder,
-                              Py_ssize_t *consumed)
-{
-    const char *starts = s;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    _PyUnicodeWriter writer;
-    const unsigned char *q, *e;
-    int le, bo = 0;       /* assume native ordering by default */
-    const char *encoding;
-    const char *errmsg = "";
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-
-    q = (unsigned char *)s;
-    e = q + size;
-
-    if (byteorder)
-        bo = *byteorder;
-
-    /* Check for BOM marks (U+FEFF) in the input and adjust current
-       byte order setting accordingly. In native mode, the leading BOM
-       mark is skipped, in all other modes, it is copied to the output
-       stream as-is (giving a ZWNBSP character). */
-    if (bo == 0 && size >= 4) {
-        Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
-        if (bom == 0x0000FEFF) {
-            bo = -1;
-            q += 4;
-        }
-        else if (bom == 0xFFFE0000) {
-            bo = 1;
-            q += 4;
-        }
-        if (byteorder)
-            *byteorder = bo;
-    }
-
-    if (q == e) {
-        if (consumed)
-            *consumed = size;
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-#ifdef WORDS_BIGENDIAN
-    le = bo < 0;
-#else
-    le = bo <= 0;
-#endif
-    encoding = le ? "utf-32-le" : "utf-32-be";
-
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = (e - q + 3) / 4;
-    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
-        goto onError;
-
-    while (1) {
-        Py_UCS4 ch = 0;
-        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
-
-        if (e - q >= 4) {
-            enum PyUnicode_Kind kind = writer.kind;
-            void *data = writer.data;
-            const unsigned char *last = e - 4;
-            Py_ssize_t pos = writer.pos;
-            if (le) {
-                do {
-                    ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
-                    if (ch > maxch)
-                        break;
-                    if (kind != PyUnicode_1BYTE_KIND &&
-                        Py_UNICODE_IS_SURROGATE(ch))
-                        break;
-                    PyUnicode_WRITE(kind, data, pos++, ch);
-                    q += 4;
-                } while (q <= last);
-            }
-            else {
-                do {
-                    ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
-                    if (ch > maxch)
-                        break;
-                    if (kind != PyUnicode_1BYTE_KIND &&
-                        Py_UNICODE_IS_SURROGATE(ch))
-                        break;
-                    PyUnicode_WRITE(kind, data, pos++, ch);
-                    q += 4;
-                } while (q <= last);
-            }
-            writer.pos = pos;
-        }
-
-        if (Py_UNICODE_IS_SURROGATE(ch)) {
-            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
-            startinpos = ((const char *)q) - starts;
-            endinpos = startinpos + 4;
-        }
-        else if (ch <= maxch) {
-            if (q == e || consumed)
-                break;
-            /* remaining bytes at the end? (size should be divisible by 4) */
-            errmsg = "truncated data";
-            startinpos = ((const char *)q) - starts;
-            endinpos = ((const char *)e) - starts;
-        }
-        else {
-            if (ch < 0x110000) {
-                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
-                    goto onError;
-                q += 4;
-                continue;
-            }
-            errmsg = "code point not in range(0x110000)";
-            startinpos = ((const char *)q) - starts;
-            endinpos = startinpos + 4;
-        }
-
-        /* The remaining input chars are ignored if the callback
-           chooses to skip the input */
-        if (unicode_decode_call_errorhandler_writer(
-                errors, &errorHandler,
-                encoding, errmsg,
-                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
-                &writer))
-            goto onError;
-    }
-
-    if (consumed)
-        *consumed = (const char *)q-starts;
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-PyObject *
-_PyUnicode_EncodeUTF32(PyObject *str,
-                       const char *errors,
-                       int byteorder)
-{
-    int kind;
-    void *data;
-    Py_ssize_t len;
-    PyObject *v;
-    unsigned char *p;
-    Py_ssize_t nsize, i;
-    /* Offsets from p for storing byte pairs in the right order. */
-#if PY_LITTLE_ENDIAN
-    int iorder[] = {0, 1, 2, 3};
-#else
-    int iorder[] = {3, 2, 1, 0};
-#endif
-    const char *encoding;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    PyObject *rep = NULL;
-
-#define STORECHAR(CH)                           \
-    do {                                        \
-        p[iorder[3]] = ((CH) >> 24) & 0xff;     \
-        p[iorder[2]] = ((CH) >> 16) & 0xff;     \
-        p[iorder[1]] = ((CH) >> 8) & 0xff;      \
-        p[iorder[0]] = (CH) & 0xff;             \
-        p += 4;                                 \
-    } while(0)
-
-    if (!PyUnicode_Check(str)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(str) == -1)
-        return NULL;
-    kind = PyUnicode_KIND(str);
-    data = PyUnicode_DATA(str);
-    len = PyUnicode_GET_LENGTH(str);
-
-    nsize = len + (byteorder == 0);
-    if (nsize > PY_SSIZE_T_MAX / 4)
-        return PyErr_NoMemory();
-    v = PyBytes_FromStringAndSize(NULL, nsize * 4);
-    if (v == NULL)
-        return NULL;
-
-    p = (unsigned char *)PyBytes_AS_STRING(v);
-    if (byteorder == 0)
-        STORECHAR(0xFEFF);
-    if (len == 0)
-        return v;
-
-    if (byteorder == -1) {
-        /* force LE */
-        iorder[0] = 0;
-        iorder[1] = 1;
-        iorder[2] = 2;
-        iorder[3] = 3;
-        encoding = "utf-32-le";
-    }
-    else if (byteorder == 1) {
-        /* force BE */
-        iorder[0] = 3;
-        iorder[1] = 2;
-        iorder[2] = 1;
-        iorder[3] = 0;
-        encoding = "utf-32-be";
-    }
-    else
-        encoding = "utf-32";
-
-    if (kind == PyUnicode_1BYTE_KIND) {
-        for (i = 0; i < len; i++)
-            STORECHAR(PyUnicode_READ(kind, data, i));
-        return v;
-    }
-
-    for (i = 0; i < len;) {
-        Py_ssize_t repsize, moreunits;
-        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-        i++;
-        assert(ch <= MAX_UNICODE);
-        if (!Py_UNICODE_IS_SURROGATE(ch)) {
-            STORECHAR(ch);
-            continue;
-        }
-
-        rep = unicode_encode_call_errorhandler(
-                errors, &errorHandler,
-                encoding, "surrogates not allowed",
-                str, &exc, i-1, i, &i);
-
-        if (!rep)
-            goto error;
-
-        if (PyBytes_Check(rep)) {
-            repsize = PyBytes_GET_SIZE(rep);
-            if (repsize & 3) {
-                raise_encode_exception(&exc, encoding,
-                                       str, i - 1, i,
-                                       "surrogates not allowed");
-                goto error;
-            }
-            moreunits = repsize / 4;
-        }
-        else {
-            assert(PyUnicode_Check(rep));
-            if (PyUnicode_READY(rep) < 0)
-                goto error;
-            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
-            if (!PyUnicode_IS_ASCII(rep)) {
-                raise_encode_exception(&exc, encoding,
-                                       str, i - 1, i,
-                                       "surrogates not allowed");
-                goto error;
-            }
-        }
-
-        /* four bytes are reserved for each surrogate */
-        if (moreunits > 1) {
-            Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
-            Py_ssize_t morebytes = 4 * (moreunits - 1);
-            if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
-                /* integer overflow */
-                PyErr_NoMemory();
-                goto error;
-            }
-            if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
-                goto error;
-            p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
-        }
-
-        if (PyBytes_Check(rep)) {
-            Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
-            p += repsize;
-        } else /* rep is unicode */ {
-            const Py_UCS1 *repdata;
-            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
-            repdata = PyUnicode_1BYTE_DATA(rep);
-            while (repsize--) {
-                Py_UCS4 ch = *repdata++;
-                STORECHAR(ch);
-            }
-        }
-
-        Py_CLEAR(rep);
-    }
-
-    /* Cut back to size actually needed. This is necessary for, for example,
-       encoding of a string containing isolated surrogates and the 'ignore'
-       handler is used. */
-    nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
-    if (nsize != PyBytes_GET_SIZE(v))
-      _PyBytes_Resize(&v, nsize);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return v;
-  error:
-    Py_XDECREF(rep);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    Py_XDECREF(v);
-    return NULL;
-#undef STORECHAR
-}
-
-PyObject *
-PyUnicode_EncodeUTF32(const Py_UNICODE *s,
-                      Py_ssize_t size,
-                      const char *errors,
-                      int byteorder)
-{
-    PyObject *result;
-    PyObject *tmp = PyUnicode_FromUnicode(s, size);
-    if (tmp == NULL)
-        return NULL;
-    result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
-    Py_DECREF(tmp);
-    return result;
-}
-
-PyObject *
-PyUnicode_AsUTF32String(PyObject *unicode)
-{
-    return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
-}
-
-/* --- UTF-16 Codec ------------------------------------------------------- */
-
-PyObject *
-PyUnicode_DecodeUTF16(const char *s,
-                      Py_ssize_t size,
-                      const char *errors,
-                      int *byteorder)
-{
-    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
-}
-
-PyObject *
-PyUnicode_DecodeUTF16Stateful(const char *s,
-                              Py_ssize_t size,
-                              const char *errors,
-                              int *byteorder,
-                              Py_ssize_t *consumed)
-{
-    const char *starts = s;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    _PyUnicodeWriter writer;
-    const unsigned char *q, *e;
-    int bo = 0;       /* assume native ordering by default */
-    int native_ordering;
-    const char *errmsg = "";
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    const char *encoding;
-
-    q = (unsigned char *)s;
-    e = q + size;
-
-    if (byteorder)
-        bo = *byteorder;
-
-    /* Check for BOM marks (U+FEFF) in the input and adjust current
-       byte order setting accordingly. In native mode, the leading BOM
-       mark is skipped, in all other modes, it is copied to the output
-       stream as-is (giving a ZWNBSP character). */
-    if (bo == 0 && size >= 2) {
-        const Py_UCS4 bom = (q[1] << 8) | q[0];
-        if (bom == 0xFEFF) {
-            q += 2;
-            bo = -1;
-        }
-        else if (bom == 0xFFFE) {
-            q += 2;
-            bo = 1;
-        }
-        if (byteorder)
-            *byteorder = bo;
-    }
-
-    if (q == e) {
-        if (consumed)
-            *consumed = size;
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-#if PY_LITTLE_ENDIAN
-    native_ordering = bo <= 0;
-    encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
-#else
-    native_ordering = bo >= 0;
-    encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
-#endif
-
-    /* Note: size will always be longer than the resulting Unicode
-       character count */
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = (e - q + 1) / 2;
-    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
-        goto onError;
-
-    while (1) {
-        Py_UCS4 ch = 0;
-        if (e - q >= 2) {
-            int kind = writer.kind;
-            if (kind == PyUnicode_1BYTE_KIND) {
-                if (PyUnicode_IS_ASCII(writer.buffer))
-                    ch = asciilib_utf16_decode(&q, e,
-                            (Py_UCS1*)writer.data, &writer.pos,
-                            native_ordering);
-                else
-                    ch = ucs1lib_utf16_decode(&q, e,
-                            (Py_UCS1*)writer.data, &writer.pos,
-                            native_ordering);
-            } else if (kind == PyUnicode_2BYTE_KIND) {
-                ch = ucs2lib_utf16_decode(&q, e,
-                        (Py_UCS2*)writer.data, &writer.pos,
-                        native_ordering);
-            } else {
-                assert(kind == PyUnicode_4BYTE_KIND);
-                ch = ucs4lib_utf16_decode(&q, e,
-                        (Py_UCS4*)writer.data, &writer.pos,
-                        native_ordering);
-            }
-        }
-
-        switch (ch)
-        {
-        case 0:
-            /* remaining byte at the end? (size should be even) */
-            if (q == e || consumed)
-                goto End;
-            errmsg = "truncated data";
-            startinpos = ((const char *)q) - starts;
-            endinpos = ((const char *)e) - starts;
-            break;
-            /* The remaining input chars are ignored if the callback
-               chooses to skip the input */
-        case 1:
-            q -= 2;
-            if (consumed)
-                goto End;
-            errmsg = "unexpected end of data";
-            startinpos = ((const char *)q) - starts;
-            endinpos = ((const char *)e) - starts;
-            break;
-        case 2:
-            errmsg = "illegal encoding";
-            startinpos = ((const char *)q) - 2 - starts;
-            endinpos = startinpos + 2;
-            break;
-        case 3:
-            errmsg = "illegal UTF-16 surrogate";
-            startinpos = ((const char *)q) - 4 - starts;
-            endinpos = startinpos + 2;
-            break;
-        default:
-            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
-                goto onError;
-            continue;
-        }
-
-        if (unicode_decode_call_errorhandler_writer(
-                errors,
-                &errorHandler,
-                encoding, errmsg,
-                &starts,
-                (const char **)&e,
-                &startinpos,
-                &endinpos,
-                &exc,
-                (const char **)&q,
-                &writer))
-            goto onError;
-    }
-
-End:
-    if (consumed)
-        *consumed = (const char *)q-starts;
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-PyObject *
-_PyUnicode_EncodeUTF16(PyObject *str,
-                       const char *errors,
-                       int byteorder)
-{
-    enum PyUnicode_Kind kind;
-    const void *data;
-    Py_ssize_t len;
-    PyObject *v;
-    unsigned short *out;
-    Py_ssize_t pairs;
-#if PY_BIG_ENDIAN
-    int native_ordering = byteorder >= 0;
-#else
-    int native_ordering = byteorder <= 0;
-#endif
-    const char *encoding;
-    Py_ssize_t nsize, pos;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    PyObject *rep = NULL;
-
-    if (!PyUnicode_Check(str)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(str) == -1)
-        return NULL;
-    kind = PyUnicode_KIND(str);
-    data = PyUnicode_DATA(str);
-    len = PyUnicode_GET_LENGTH(str);
-
-    pairs = 0;
-    if (kind == PyUnicode_4BYTE_KIND) {
-        const Py_UCS4 *in = (const Py_UCS4 *)data;
-        const Py_UCS4 *end = in + len;
-        while (in < end)
-            if (*in++ >= 0x10000)
-                pairs++;
-    }
-    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
-        return PyErr_NoMemory();
-    nsize = len + pairs + (byteorder == 0);
-    v = PyBytes_FromStringAndSize(NULL, nsize * 2);
-    if (v == NULL)
-        return NULL;
-
-    /* output buffer is 2-bytes aligned */
-    assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
-    out = (unsigned short *)PyBytes_AS_STRING(v);
-    if (byteorder == 0)
-        *out++ = 0xFEFF;
-    if (len == 0)
-        goto done;
-
-    if (kind == PyUnicode_1BYTE_KIND) {
-        ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
-        goto done;
-    }
-
-    if (byteorder < 0)
-        encoding = "utf-16-le";
-    else if (byteorder > 0)
-        encoding = "utf-16-be";
-    else
-        encoding = "utf-16";
-
-    pos = 0;
-    while (pos < len) {
-        Py_ssize_t repsize, moreunits;
-
-        if (kind == PyUnicode_2BYTE_KIND) {
-            pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
-                                        &out, native_ordering);
-        }
-        else {
-            assert(kind == PyUnicode_4BYTE_KIND);
-            pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
-                                        &out, native_ordering);
-        }
-        if (pos == len)
-            break;
-
-        rep = unicode_encode_call_errorhandler(
-                errors, &errorHandler,
-                encoding, "surrogates not allowed",
-                str, &exc, pos, pos + 1, &pos);
-        if (!rep)
-            goto error;
-
-        if (PyBytes_Check(rep)) {
-            repsize = PyBytes_GET_SIZE(rep);
-            if (repsize & 1) {
-                raise_encode_exception(&exc, encoding,
-                                       str, pos - 1, pos,
-                                       "surrogates not allowed");
-                goto error;
-            }
-            moreunits = repsize / 2;
-        }
-        else {
-            assert(PyUnicode_Check(rep));
-            if (PyUnicode_READY(rep) < 0)
-                goto error;
-            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
-            if (!PyUnicode_IS_ASCII(rep)) {
-                raise_encode_exception(&exc, encoding,
-                                       str, pos - 1, pos,
-                                       "surrogates not allowed");
-                goto error;
-            }
-        }
-
-        /* two bytes are reserved for each surrogate */
-        if (moreunits > 1) {
-            Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
-            Py_ssize_t morebytes = 2 * (moreunits - 1);
-            if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
-                /* integer overflow */
-                PyErr_NoMemory();
-                goto error;
-            }
-            if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
-                goto error;
-            out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
-        }
-
-        if (PyBytes_Check(rep)) {
-            Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
-            out += moreunits;
-        } else /* rep is unicode */ {
-            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
-            ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
-                                 &out, native_ordering);
-        }
-
-        Py_CLEAR(rep);
-    }
-
-    /* Cut back to size actually needed. This is necessary for, for example,
-    encoding of a string containing isolated surrogates and the 'ignore' handler
-    is used. */
-    nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
-    if (nsize != PyBytes_GET_SIZE(v))
-      _PyBytes_Resize(&v, nsize);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-  done:
-    return v;
-  error:
-    Py_XDECREF(rep);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    Py_XDECREF(v);
-    return NULL;
-#undef STORECHAR
-}
-
-PyObject *
-PyUnicode_EncodeUTF16(const Py_UNICODE *s,
-                      Py_ssize_t size,
-                      const char *errors,
-                      int byteorder)
-{
-    PyObject *result;
-    PyObject *tmp = PyUnicode_FromUnicode(s, size);
-    if (tmp == NULL)
-        return NULL;
-    result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
-    Py_DECREF(tmp);
-    return result;
-}
-
-PyObject *
-PyUnicode_AsUTF16String(PyObject *unicode)
-{
-    return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
-}
-
-/* --- Unicode Escape Codec ----------------------------------------------- */
-
-/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
-   if all the escapes in the string make it still a valid ASCII string.
-   Returns -1 if any escapes were found which cause the string to
-   pop out of ASCII range.  Otherwise returns the length of the
-   required buffer to hold the string.
-   */
-static Py_ssize_t
-length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
-{
-    const unsigned char *p = (const unsigned char *)s;
-    const unsigned char *end = p + size;
-    Py_ssize_t length = 0;
-
-    if (size < 0)
-        return -1;
-
-    for (; p < end; ++p) {
-        if (*p > 127) {
-            /* Non-ASCII */
-            return -1;
-        }
-        else if (*p != '\\') {
-            /* Normal character */
-            ++length;
-        }
-        else {
-            /* Backslash-escape, check next char */
-            ++p;
-            /* Escape sequence reaches till end of string or
-               non-ASCII follow-up. */
-            if (p >= end || *p > 127)
-                return -1;
-            switch (*p) {
-            case '\n':
-                /* backslash + \n result in zero characters */
-                break;
-            case '\\': case '\'': case '\"':
-            case 'b': case 'f': case 't':
-            case 'n': case 'r': case 'v': case 'a':
-                ++length;
-                break;
-            case '0': case '1': case '2': case '3':
-            case '4': case '5': case '6': case '7':
-            case 'x': case 'u': case 'U': case 'N':
-                /* these do not guarantee ASCII characters */
-                return -1;
-            default:
-                /* count the backslash + the other character */
-                length += 2;
-            }
-        }
-    }
-    return length;
-}
-
-static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
-
-PyObject *
-PyUnicode_DecodeUnicodeEscape(const char *s,
-                              Py_ssize_t size,
-                              const char *errors)
-{
-    const char *starts = s;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    _PyUnicodeWriter writer;
-    const char *end;
-    char* message;
-    Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    Py_ssize_t len;
-
-    len = length_of_escaped_ascii_string(s, size);
-    if (len == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    /* After length_of_escaped_ascii_string() there are two alternatives,
-       either the string is pure ASCII with named escapes like \n, etc.
-       and we determined it's exact size (common case)
-       or it contains \x, \u, ... escape sequences.  then we create a
-       legacy wchar string and resize it at the end of this function. */
-    _PyUnicodeWriter_Init(&writer);
-    if (len > 0) {
-        writer.min_length = len;
-    }
-    else {
-        /* Escaped strings will always be longer than the resulting
-           Unicode string, so we start with size here and then reduce the
-           length after conversion to the true value.
-           (but if the error callback returns a long replacement string
-           we'll have to allocate more space) */
-        writer.min_length = size;
-    }
-
-    if (size == 0)
-        return _PyUnicodeWriter_Finish(&writer);
-    end = s + size;
-
-    while (s < end) {
-        unsigned char c;
-        Py_UCS4 x;
-        int digits;
-
-        /* Non-escape characters are interpreted as Unicode ordinals */
-        if (*s != '\\') {
-            x = (unsigned char)*s;
-            s++;
-            if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
-                goto onError;
-            continue;
-        }
-
-        startinpos = s-starts;
-        /* \ - Escapes */
-        s++;
-        c = *s++;
-        if (s > end)
-            c = '\0'; /* Invalid after \ */
-
-        switch (c) {
-
-            /* \x escapes */
-#define WRITECHAR(ch)                                                      \
-            do {                                                           \
-                if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0)    \
-                    goto onError;                                          \
-            } while(0)
-
-        case '\n': break;
-        case '\\': WRITECHAR('\\'); break;
-        case '\'': WRITECHAR('\''); break;
-        case '\"': WRITECHAR('\"'); break;
-        case 'b': WRITECHAR('\b'); break;
-        /* FF */
-        case 'f': WRITECHAR('\014'); break;
-        case 't': WRITECHAR('\t'); break;
-        case 'n': WRITECHAR('\n'); break;
-        case 'r': WRITECHAR('\r'); break;
-        /* VT */
-        case 'v': WRITECHAR('\013'); break;
-        /* BEL, not classic C */
-        case 'a': WRITECHAR('\007'); break;
-
-            /* \OOO (octal) escapes */
-        case '0': case '1': case '2': case '3':
-        case '4': case '5': case '6': case '7':
-            x = s[-1] - '0';
-            if (s < end && '0' <= *s && *s <= '7') {
-                x = (x<<3) + *s++ - '0';
-                if (s < end && '0' <= *s && *s <= '7')
-                    x = (x<<3) + *s++ - '0';
-            }
-            WRITECHAR(x);
-            break;
-
-            /* hex escapes */
-            /* \xXX */
-        case 'x':
-            digits = 2;
-            message = "truncated \\xXX escape";
-            goto hexescape;
-
-            /* \uXXXX */
-        case 'u':
-            digits = 4;
-            message = "truncated \\uXXXX escape";
-            goto hexescape;
-
-            /* \UXXXXXXXX */
-        case 'U':
-            digits = 8;
-            message = "truncated \\UXXXXXXXX escape";
-        hexescape:
-            chr = 0;
-            if (end - s < digits) {
-                /* count only hex digits */
-                for (; s < end; ++s) {
-                    c = (unsigned char)*s;
-                    if (!Py_ISXDIGIT(c))
-                        goto error;
-                }
-                goto error;
-            }
-            for (; digits--; ++s) {
-                c = (unsigned char)*s;
-                if (!Py_ISXDIGIT(c))
-                    goto error;
-                chr = (chr<<4) & ~0xF;
-                if (c >= '0' && c <= '9')
-                    chr += c - '0';
-                else if (c >= 'a' && c <= 'f')
-                    chr += 10 + c - 'a';
-                else
-                    chr += 10 + c - 'A';
-            }
-            if (chr == 0xffffffff && PyErr_Occurred())
-                /* _decoding_error will have already written into the
-                   target buffer. */
-                break;
-        store:
-            /* when we get here, chr is a 32-bit unicode character */
-            message = "illegal Unicode character";
-            if (chr > MAX_UNICODE)
-                goto error;
-            WRITECHAR(chr);
-            break;
-
-            /* \N{name} */
-        case 'N':
-            message = "malformed \\N character escape";
-            if (ucnhash_CAPI == NULL) {
-                /* load the unicode data module */
-                ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
-                                                PyUnicodeData_CAPSULE_NAME, 1);
-                if (ucnhash_CAPI == NULL)
-                    goto ucnhashError;
-            }
-            if (*s == '{') {
-                const char *start = s+1;
-                /* look for the closing brace */
-                while (*s != '}' && s < end)
-                    s++;
-                if (s > start && s < end && *s == '}') {
-                    /* found a name.  look it up in the unicode database */
-                    message = "unknown Unicode character name";
-                    s++;
-                    if (s - start - 1 <= INT_MAX &&
-                        ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
-                                              &chr, 0))
-                        goto store;
-                }
-            }
-            goto error;
-
-        default:
-            if (s > end) {
-                message = "\\ at end of string";
-                s--;
-                goto error;
-            }
-            else {
-                WRITECHAR('\\');
-                WRITECHAR((unsigned char)s[-1]);
-            }
-            break;
-        }
-        continue;
-
-      error:
-        endinpos = s-starts;
-        if (unicode_decode_call_errorhandler_writer(
-                errors, &errorHandler,
-                "unicodeescape", message,
-                &starts, &end, &startinpos, &endinpos, &exc, &s,
-                &writer))
-            goto onError;
-        continue;
-    }
-#undef WRITECHAR
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  ucnhashError:
-    PyErr_SetString(
-        PyExc_UnicodeError,
-        "\\N escapes not supported (can't load unicodedata module)"
-        );
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-/* Return a Unicode-Escape string version of the Unicode object.
-
-   If quotes is true, the string is enclosed in u"" or u'' quotes as
-   appropriate.
-
-*/
-
-PyObject *
-PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
-{
-    Py_ssize_t i, len;
-    PyObject *repr;
-    char *p;
-    int kind;
-    void *data;
-    Py_ssize_t expandsize = 0;
-
-    /* Initial allocation is based on the longest-possible character
-       escape.
-
-       For UCS1 strings it's '\xxx', 4 bytes per source character.
-       For UCS2 strings it's '\uxxxx', 6 bytes per source character.
-       For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
-    */
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    len = PyUnicode_GET_LENGTH(unicode);
-    kind = PyUnicode_KIND(unicode);
-    data = PyUnicode_DATA(unicode);
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND: expandsize = 4; break;
-    case PyUnicode_2BYTE_KIND: expandsize = 6; break;
-    case PyUnicode_4BYTE_KIND: expandsize = 10; break;
-    }
-
-    if (len == 0)
-        return PyBytes_FromStringAndSize(NULL, 0);
-
-    if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
-        return PyErr_NoMemory();
-
-    repr = PyBytes_FromStringAndSize(NULL,
-                                     2
-                                     + expandsize*len
-                                     + 1);
-    if (repr == NULL)
-        return NULL;
-
-    p = PyBytes_AS_STRING(repr);
-
-    for (i = 0; i < len; i++) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-
-        /* Escape backslashes */
-        if (ch == '\\') {
-            *p++ = '\\';
-            *p++ = (char) ch;
-            continue;
-        }
-
-        /* Map 21-bit characters to '\U00xxxxxx' */
-        else if (ch >= 0x10000) {
-            assert(ch <= MAX_UNICODE);
-            *p++ = '\\';
-            *p++ = 'U';
-            *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
-            *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
-            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
-            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
-            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
-            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
-            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
-            *p++ = Py_hexdigits[ch & 0x0000000F];
-            continue;
-        }
-
-        /* Map 16-bit characters to '\uxxxx' */
-        if (ch >= 256) {
-            *p++ = '\\';
-            *p++ = 'u';
-            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
-            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
-            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
-            *p++ = Py_hexdigits[ch & 0x000F];
-        }
-
-        /* Map special whitespace to '\t', \n', '\r' */
-        else if (ch == '\t') {
-            *p++ = '\\';
-            *p++ = 't';
-        }
-        else if (ch == '\n') {
-            *p++ = '\\';
-            *p++ = 'n';
-        }
-        else if (ch == '\r') {
-            *p++ = '\\';
-            *p++ = 'r';
-        }
-
-        /* Map non-printable US ASCII to '\xhh' */
-        else if (ch < ' ' || ch >= 0x7F) {
-            *p++ = '\\';
-            *p++ = 'x';
-            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
-            *p++ = Py_hexdigits[ch & 0x000F];
-        }
-
-        /* Copy everything else as-is */
-        else
-            *p++ = (char) ch;
-    }
-
-    assert(p - PyBytes_AS_STRING(repr) > 0);
-    if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
-        return NULL;
-    return repr;
-}
-
-PyObject *
-PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
-                              Py_ssize_t size)
-{
-    PyObject *result;
-    PyObject *tmp = PyUnicode_FromUnicode(s, size);
-    if (tmp == NULL)
-        return NULL;
-    result = PyUnicode_AsUnicodeEscapeString(tmp);
-    Py_DECREF(tmp);
-    return result;
-}
-
-/* --- Raw Unicode Escape Codec ------------------------------------------- */
-
-PyObject *
-PyUnicode_DecodeRawUnicodeEscape(const char *s,
-                                 Py_ssize_t size,
-                                 const char *errors)
-{
-    const char *starts = s;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    _PyUnicodeWriter writer;
-    const char *end;
-    const char *bs;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    /* Escaped strings will always be longer than the resulting
-       Unicode string, so we start with size here and then reduce the
-       length after conversion to the true value. (But decoding error
-       handler might have to resize the string) */
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = size;
-
-    end = s + size;
-    while (s < end) {
-        unsigned char c;
-        Py_UCS4 x;
-        int i;
-        int count;
-
-        /* Non-escape characters are interpreted as Unicode ordinals */
-        if (*s != '\\') {
-            x = (unsigned char)*s++;
-            if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
-                goto onError;
-            continue;
-        }
-        startinpos = s-starts;
-
-        /* \u-escapes are only interpreted iff the number of leading
-           backslashes if odd */
-        bs = s;
-        for (;s < end;) {
-            if (*s != '\\')
-                break;
-            x = (unsigned char)*s++;
-            if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
-                goto onError;
-        }
-        if (((s - bs) & 1) == 0 ||
-            s >= end ||
-            (*s != 'u' && *s != 'U')) {
-            continue;
-        }
-        writer.pos--;
-        count = *s=='u' ? 4 : 8;
-        s++;
-
-        /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
-        for (x = 0, i = 0; i < count; ++i, ++s) {
-            c = (unsigned char)*s;
-            if (!Py_ISXDIGIT(c)) {
-                endinpos = s-starts;
-                if (unicode_decode_call_errorhandler_writer(
-                        errors, &errorHandler,
-                        "rawunicodeescape", "truncated \\uXXXX",
-                        &starts, &end, &startinpos, &endinpos, &exc, &s,
-                        &writer))
-                    goto onError;
-                goto nextByte;
-            }
-            x = (x<<4) & ~0xF;
-            if (c >= '0' && c <= '9')
-                x += c - '0';
-            else if (c >= 'a' && c <= 'f')
-                x += 10 + c - 'a';
-            else
-                x += 10 + c - 'A';
-        }
-        if (x <= MAX_UNICODE) {
-            if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
-                goto onError;
-        }
-        else {
-            endinpos = s-starts;
-            if (unicode_decode_call_errorhandler_writer(
-                    errors, &errorHandler,
-                    "rawunicodeescape", "\\Uxxxxxxxx out of range",
-                    &starts, &end, &startinpos, &endinpos, &exc, &s,
-                    &writer))
-                goto onError;
-        }
-      nextByte:
-        ;
-    }
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-
-PyObject *
-PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
-{
-    PyObject *repr;
-    char *p;
-    char *q;
-    Py_ssize_t expandsize, pos;
-    int kind;
-    void *data;
-    Py_ssize_t len;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    kind = PyUnicode_KIND(unicode);
-    data = PyUnicode_DATA(unicode);
-    len = PyUnicode_GET_LENGTH(unicode);
-    /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
-       bytes, and 1 byte characters 4. */
-    expandsize = kind * 2 + 2;
-
-    if (len > PY_SSIZE_T_MAX / expandsize)
-        return PyErr_NoMemory();
-
-    repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
-    if (repr == NULL)
-        return NULL;
-    if (len == 0)
-        return repr;
-
-    p = q = PyBytes_AS_STRING(repr);
-    for (pos = 0; pos < len; pos++) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
-        /* Map 32-bit characters to '\Uxxxxxxxx' */
-        if (ch >= 0x10000) {
-            assert(ch <= MAX_UNICODE);
-            *p++ = '\\';
-            *p++ = 'U';
-            *p++ = Py_hexdigits[(ch >> 28) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 24) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
-            *p++ = Py_hexdigits[ch & 15];
-        }
-        /* Map 16-bit characters to '\uxxxx' */
-        else if (ch >= 256) {
-            *p++ = '\\';
-            *p++ = 'u';
-            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
-            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
-            *p++ = Py_hexdigits[ch & 15];
-        }
-        /* Copy everything else as-is */
-        else
-            *p++ = (char) ch;
-    }
-
-    assert(p > q);
-    if (_PyBytes_Resize(&repr, p - q) < 0)
-        return NULL;
-    return repr;
-}
-
-PyObject *
-PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
-                                 Py_ssize_t size)
-{
-    PyObject *result;
-    PyObject *tmp = PyUnicode_FromUnicode(s, size);
-    if (tmp == NULL)
-        return NULL;
-    result = PyUnicode_AsRawUnicodeEscapeString(tmp);
-    Py_DECREF(tmp);
-    return result;
-}
-
-/* --- Unicode Internal Codec ------------------------------------------- */
-
-PyObject *
-_PyUnicode_DecodeUnicodeInternal(const char *s,
-                                 Py_ssize_t size,
-                                 const char *errors)
-{
-    const char *starts = s;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    _PyUnicodeWriter writer;
-    const char *end;
-    const char *reason;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-
-    if (PyErr_WarnEx(PyExc_DeprecationWarning,
-                     "unicode_internal codec has been deprecated",
-                     1))
-        return NULL;
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    _PyUnicodeWriter_Init(&writer);
-    if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
-        PyErr_NoMemory();
-        goto onError;
-    }
-    writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
-
-    end = s + size;
-    while (s < end) {
-        Py_UNICODE uch;
-        Py_UCS4 ch;
-        if (end - s < Py_UNICODE_SIZE) {
-            endinpos = end-starts;
-            reason = "truncated input";
-            goto error;
-        }
-        /* We copy the raw representation one byte at a time because the
-           pointer may be unaligned (see test_codeccallbacks). */
-        ((char *) &uch)[0] = s[0];
-        ((char *) &uch)[1] = s[1];
-#ifdef Py_UNICODE_WIDE
-        ((char *) &uch)[2] = s[2];
-        ((char *) &uch)[3] = s[3];
-#endif
-        ch = uch;
-#ifdef Py_UNICODE_WIDE
-        /* We have to sanity check the raw data, otherwise doom looms for
-           some malformed UCS-4 data. */
-        if (ch > 0x10ffff) {
-            endinpos = s - starts + Py_UNICODE_SIZE;
-            reason = "illegal code point (> 0x10FFFF)";
-            goto error;
-        }
-#endif
-        s += Py_UNICODE_SIZE;
-#ifndef Py_UNICODE_WIDE
-        if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
-        {
-            Py_UNICODE uch2;
-            ((char *) &uch2)[0] = s[0];
-            ((char *) &uch2)[1] = s[1];
-            if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
-            {
-                ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
-                s += Py_UNICODE_SIZE;
-            }
-        }
-#endif
-
-        if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
-            goto onError;
-        continue;
-
-  error:
-        startinpos = s - starts;
-        if (unicode_decode_call_errorhandler_writer(
-                errors, &errorHandler,
-                "unicode_internal", reason,
-                &starts, &end, &startinpos, &endinpos, &exc, &s,
-                &writer))
-            goto onError;
-    }
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-/* --- Latin-1 Codec ------------------------------------------------------ */
-
-PyObject *
-PyUnicode_DecodeLatin1(const char *s,
-                       Py_ssize_t size,
-                       const char *errors)
-{
-    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
-    return _PyUnicode_FromUCS1((unsigned char*)s, size);
-}
-
-/* create or adjust a UnicodeEncodeError */
-static void
-make_encode_exception(PyObject **exceptionObject,
-                      const char *encoding,
-                      PyObject *unicode,
-                      Py_ssize_t startpos, Py_ssize_t endpos,
-                      const char *reason)
-{
-    if (*exceptionObject == NULL) {
-        *exceptionObject = PyObject_CallFunction(
-            PyExc_UnicodeEncodeError, "sOnns",
-            encoding, unicode, startpos, endpos, reason);
-    }
-    else {
-        if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
-            goto onError;
-        if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
-            goto onError;
-        if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
-            goto onError;
-        return;
-      onError:
-        Py_CLEAR(*exceptionObject);
-    }
-}
-
-/* raises a UnicodeEncodeError */
-static void
-raise_encode_exception(PyObject **exceptionObject,
-                       const char *encoding,
-                       PyObject *unicode,
-                       Py_ssize_t startpos, Py_ssize_t endpos,
-                       const char *reason)
-{
-    make_encode_exception(exceptionObject,
-                          encoding, unicode, startpos, endpos, reason);
-    if (*exceptionObject != NULL)
-        PyCodec_StrictErrors(*exceptionObject);
-}
-
-/* error handling callback helper:
-   build arguments, call the callback and check the arguments,
-   put the result into newpos and return the replacement string, which
-   has to be freed by the caller */
-static PyObject *
-unicode_encode_call_errorhandler(const char *errors,
-                                 PyObject **errorHandler,
-                                 const char *encoding, const char *reason,
-                                 PyObject *unicode, PyObject **exceptionObject,
-                                 Py_ssize_t startpos, Py_ssize_t endpos,
-                                 Py_ssize_t *newpos)
-{
-    static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
-    Py_ssize_t len;
-    PyObject *restuple;
-    PyObject *resunicode;
-
-    if (*errorHandler == NULL) {
-        *errorHandler = PyCodec_LookupError(errors);
-        if (*errorHandler == NULL)
-            return NULL;
-    }
-
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    len = PyUnicode_GET_LENGTH(unicode);
-
-    make_encode_exception(exceptionObject,
-                          encoding, unicode, startpos, endpos, reason);
-    if (*exceptionObject == NULL)
-        return NULL;
-
-    restuple = PyObject_CallFunctionObjArgs(
-        *errorHandler, *exceptionObject, NULL);
-    if (restuple == NULL)
-        return NULL;
-    if (!PyTuple_Check(restuple)) {
-        PyErr_SetString(PyExc_TypeError, &argparse[3]);
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    if (!PyArg_ParseTuple(restuple, argparse,
-                          &resunicode, newpos)) {
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
-        PyErr_SetString(PyExc_TypeError, &argparse[3]);
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    if (*newpos<0)
-        *newpos = len + *newpos;
-    if (*newpos<0 || *newpos>len) {
-        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    Py_INCREF(resunicode);
-    Py_DECREF(restuple);
-    return resunicode;
-}
-
-static PyObject *
-unicode_encode_ucs1(PyObject *unicode,
-                    const char *errors,
-                    unsigned int limit)
-{
-    /* input state */
-    Py_ssize_t pos=0, size;
-    int kind;
-    void *data;
-    /* output object */
-    PyObject *res;
-    /* pointer into the output */
-    char *str;
-    /* current output position */
-    Py_ssize_t ressize;
-    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
-    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    /* the following variable is used for caching string comparisons
-     * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
-    int known_errorHandler = -1;
-
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    size = PyUnicode_GET_LENGTH(unicode);
-    kind = PyUnicode_KIND(unicode);
-    data = PyUnicode_DATA(unicode);
-    /* allocate enough for a simple encoding without
-       replacements, if we need more, we'll resize */
-    if (size == 0)
-        return PyBytes_FromStringAndSize(NULL, 0);
-    res = PyBytes_FromStringAndSize(NULL, size);
-    if (res == NULL)
-        return NULL;
-    str = PyBytes_AS_STRING(res);
-    ressize = size;
-
-    while (pos < size) {
-        Py_UCS4 c = PyUnicode_READ(kind, data, pos);
-
-        /* can we encode this? */
-        if (c<limit) {
-            /* no overflow check, because we know that the space is enough */
-            *str++ = (char)c;
-            ++pos;
-        }
-        else {
-            Py_ssize_t requiredsize;
-            PyObject *repunicode;
-            Py_ssize_t repsize, newpos, respos, i;
-            /* startpos for collecting unencodable chars */
-            Py_ssize_t collstart = pos;
-            Py_ssize_t collend = pos;
-            /* find all unecodable characters */
-            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
-                ++collend;
-            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
-            if (known_errorHandler==-1) {
-                if ((errors==NULL) || (!strcmp(errors, "strict")))
-                    known_errorHandler = 1;
-                else if (!strcmp(errors, "replace"))
-                    known_errorHandler = 2;
-                else if (!strcmp(errors, "ignore"))
-                    known_errorHandler = 3;
-                else if (!strcmp(errors, "xmlcharrefreplace"))
-                    known_errorHandler = 4;
-                else
-                    known_errorHandler = 0;
-            }
-            switch (known_errorHandler) {
-            case 1: /* strict */
-                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
-                goto onError;
-            case 2: /* replace */
-                while (collstart++ < collend)
-                    *str++ = '?'; /* fall through */
-            case 3: /* ignore */
-                pos = collend;
-                break;
-            case 4: /* xmlcharrefreplace */
-                respos = str - PyBytes_AS_STRING(res);
-                requiredsize = respos;
-                /* determine replacement size */
-                for (i = collstart; i < collend; ++i) {
-                    Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-                    Py_ssize_t incr;
-                    if (ch < 10)
-                        incr = 2+1+1;
-                    else if (ch < 100)
-                        incr = 2+2+1;
-                    else if (ch < 1000)
-                        incr = 2+3+1;
-                    else if (ch < 10000)
-                        incr = 2+4+1;
-                    else if (ch < 100000)
-                        incr = 2+5+1;
-                    else if (ch < 1000000)
-                        incr = 2+6+1;
-                    else {
-                        assert(ch <= MAX_UNICODE);
-                        incr = 2+7+1;
-                    }
-                    if (requiredsize > PY_SSIZE_T_MAX - incr)
-                        goto overflow;
-                    requiredsize += incr;
-                }
-                if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
-                    goto overflow;
-                requiredsize += size - collend;
-                if (requiredsize > ressize) {
-                    if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
-                        requiredsize = 2*ressize;
-                    if (_PyBytes_Resize(&res, requiredsize))
-                        goto onError;
-                    str = PyBytes_AS_STRING(res) + respos;
-                    ressize = requiredsize;
-                }
-                /* generate replacement */
-                for (i = collstart; i < collend; ++i) {
-                    str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
-                }
-                pos = collend;
-                break;
-            default:
-                repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
-                                                              encoding, reason, unicode, &exc,
-                                                              collstart, collend, &newpos);
-                if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
-                                           PyUnicode_READY(repunicode) == -1))
-                    goto onError;
-                if (PyBytes_Check(repunicode)) {
-                    /* Directly copy bytes result to output. */
-                    repsize = PyBytes_Size(repunicode);
-                    if (repsize > 1) {
-                        /* Make room for all additional bytes. */
-                        respos = str - PyBytes_AS_STRING(res);
-                        if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
-                            Py_DECREF(repunicode);
-                            goto overflow;
-                        }
-                        if (_PyBytes_Resize(&res, ressize+repsize-1)) {
-                            Py_DECREF(repunicode);
-                            goto onError;
-                        }
-                        str = PyBytes_AS_STRING(res) + respos;
-                        ressize += repsize-1;
-                    }
-                    memcpy(str, PyBytes_AsString(repunicode), repsize);
-                    str += repsize;
-                    pos = newpos;
-                    Py_DECREF(repunicode);
-                    break;
-                }
-                /* need more space? (at least enough for what we
-                   have+the replacement+the rest of the string, so
-                   we won't have to check space for encodable characters) */
-                respos = str - PyBytes_AS_STRING(res);
-                repsize = PyUnicode_GET_LENGTH(repunicode);
-                requiredsize = respos;
-                if (requiredsize > PY_SSIZE_T_MAX - repsize)
-                    goto overflow;
-                requiredsize += repsize;
-                if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
-                    goto overflow;
-                requiredsize += size - collend;
-                if (requiredsize > ressize) {
-                    if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
-                        requiredsize = 2*ressize;
-                    if (_PyBytes_Resize(&res, requiredsize)) {
-                        Py_DECREF(repunicode);
-                        goto onError;
-                    }
-                    str = PyBytes_AS_STRING(res) + respos;
-                    ressize = requiredsize;
-                }
-                /* check if there is anything unencodable in the replacement
-                   and copy it to the output */
-                for (i = 0; repsize-->0; ++i, ++str) {
-                    c = PyUnicode_READ_CHAR(repunicode, i);
-                    if (c >= limit) {
-                        raise_encode_exception(&exc, encoding, unicode,
-                                               pos, pos+1, reason);
-                        Py_DECREF(repunicode);
-                        goto onError;
-                    }
-                    *str = (char)c;
-                }
-                pos = newpos;
-                Py_DECREF(repunicode);
-            }
-        }
-    }
-    /* Resize if we allocated to much */
-    size = str - PyBytes_AS_STRING(res);
-    if (size < ressize) { /* If this falls res will be NULL */
-        assert(size >= 0);
-        if (_PyBytes_Resize(&res, size) < 0)
-            goto onError;
-    }
-
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return res;
-
-  overflow:
-    PyErr_SetString(PyExc_OverflowError,
-                    "encoded result is too long for a Python string");
-
-  onError:
-    Py_XDECREF(res);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-/* Deprecated */
-PyObject *
-PyUnicode_EncodeLatin1(const Py_UNICODE *p,
-                       Py_ssize_t size,
-                       const char *errors)
-{
-    PyObject *result;
-    PyObject *unicode = PyUnicode_FromUnicode(p, size);
-    if (unicode == NULL)
-        return NULL;
-    result = unicode_encode_ucs1(unicode, errors, 256);
-    Py_DECREF(unicode);
-    return result;
-}
-
-PyObject *
-_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
-{
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    /* Fast path: if it is a one-byte string, construct
-       bytes object directly. */
-    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
-        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
-                                         PyUnicode_GET_LENGTH(unicode));
-    /* Non-Latin-1 characters present. Defer to above function to
-       raise the exception. */
-    return unicode_encode_ucs1(unicode, errors, 256);
-}
-
-PyObject*
-PyUnicode_AsLatin1String(PyObject *unicode)
-{
-    return _PyUnicode_AsLatin1String(unicode, NULL);
-}
-
-/* --- 7-bit ASCII Codec -------------------------------------------------- */
-
-PyObject *
-PyUnicode_DecodeASCII(const char *s,
-                      Py_ssize_t size,
-                      const char *errors)
-{
-    const char *starts = s;
-    _PyUnicodeWriter writer;
-    int kind;
-    void *data;
-    Py_ssize_t startinpos;
-    Py_ssize_t endinpos;
-    Py_ssize_t outpos;
-    const char *e;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
-    if (size == 1 && (unsigned char)s[0] < 128)
-        return get_latin1_char((unsigned char)s[0]);
-
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = size;
-    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
-        return NULL;
-
-    e = s + size;
-    data = writer.data;
-    outpos = ascii_decode(s, e, (Py_UCS1 *)data);
-    writer.pos = outpos;
-    if (writer.pos == size)
-        return _PyUnicodeWriter_Finish(&writer);
-
-    s += writer.pos;
-    kind = writer.kind;
-    while (s < e) {
-        unsigned char c = (unsigned char)*s;
-        if (c < 128) {
-            PyUnicode_WRITE(kind, data, writer.pos, c);
-            writer.pos++;
-            ++s;
-        }
-        else {
-            startinpos = s-starts;
-            endinpos = startinpos + 1;
-            if (unicode_decode_call_errorhandler_writer(
-                    errors, &errorHandler,
-                    "ascii", "ordinal not in range(128)",
-                    &starts, &e, &startinpos, &endinpos, &exc, &s,
-                    &writer))
-                goto onError;
-            kind = writer.kind;
-            data = writer.data;
-        }
-    }
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return NULL;
-}
-
-/* Deprecated */
-PyObject *
-PyUnicode_EncodeASCII(const Py_UNICODE *p,
-                      Py_ssize_t size,
-                      const char *errors)
-{
-    PyObject *result;
-    PyObject *unicode = PyUnicode_FromUnicode(p, size);
-    if (unicode == NULL)
-        return NULL;
-    result = unicode_encode_ucs1(unicode, errors, 128);
-    Py_DECREF(unicode);
-    return result;
-}
-
-PyObject *
-_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
-{
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    /* Fast path: if it is an ASCII-only string, construct bytes object
-       directly. Else defer to above function to raise the exception. */
-    if (PyUnicode_IS_ASCII(unicode))
-        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
-                                         PyUnicode_GET_LENGTH(unicode));
-    return unicode_encode_ucs1(unicode, errors, 128);
-}
-
-PyObject *
-PyUnicode_AsASCIIString(PyObject *unicode)
-{
-    return _PyUnicode_AsASCIIString(unicode, NULL);
-}
-
-#ifdef HAVE_MBCS
-
-/* --- MBCS codecs for Windows -------------------------------------------- */
-
-#if SIZEOF_INT < SIZEOF_SIZE_T
-#define NEED_RETRY
-#endif
-
-#ifndef WC_ERR_INVALID_CHARS
-#  define WC_ERR_INVALID_CHARS 0x0080
-#endif
-
-static char*
-code_page_name(UINT code_page, PyObject **obj)
-{
-    *obj = NULL;
-    if (code_page == CP_ACP)
-        return "mbcs";
-    if (code_page == CP_UTF7)
-        return "CP_UTF7";
-    if (code_page == CP_UTF8)
-        return "CP_UTF8";
-
-    *obj = PyBytes_FromFormat("cp%u", code_page);
-    if (*obj == NULL)
-        return NULL;
-    return PyBytes_AS_STRING(*obj);
-}
-
-static DWORD
-decode_code_page_flags(UINT code_page)
-{
-    if (code_page == CP_UTF7) {
-        /* The CP_UTF7 decoder only supports flags=0 */
-        return 0;
-    }
-    else
-        return MB_ERR_INVALID_CHARS;
-}
-
-/*
- * Decode a byte string from a Windows code page into unicode object in strict
- * mode.
- *
- * Returns consumed size if succeed, returns -2 on decode error, or raise an
- * OSError and returns -1 on other error.
- */
-static int
-decode_code_page_strict(UINT code_page,
-                        PyObject **v,
-                        const char *in,
-                        int insize)
-{
-    const DWORD flags = decode_code_page_flags(code_page);
-    wchar_t *out;
-    DWORD outsize;
-
-    /* First get the size of the result */
-    assert(insize > 0);
-    outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
-    if (outsize <= 0)
-        goto error;
-
-    if (*v == NULL) {
-        /* Create unicode object */
-        /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
-        *v = (PyObject*)_PyUnicode_New(outsize);
-        if (*v == NULL)
-            return -1;
-        out = PyUnicode_AS_UNICODE(*v);
-    }
-    else {
-        /* Extend unicode object */
-        Py_ssize_t n = PyUnicode_GET_SIZE(*v);
-        if (unicode_resize(v, n + outsize) < 0)
-            return -1;
-        out = PyUnicode_AS_UNICODE(*v) + n;
-    }
-
-    /* Do the conversion */
-    outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
-    if (outsize <= 0)
-        goto error;
-    return insize;
-
-error:
-    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
-        return -2;
-    PyErr_SetFromWindowsErr(0);
-    return -1;
-}
-
-/*
- * Decode a byte string from a code page into unicode object with an error
- * handler.
- *
- * Returns consumed size if succeed, or raise an OSError or
- * UnicodeDecodeError exception and returns -1 on error.
- */
-static int
-decode_code_page_errors(UINT code_page,
-                        PyObject **v,
-                        const char *in, const int size,
-                        const char *errors, int final)
-{
-    const char *startin = in;
-    const char *endin = in + size;
-    const DWORD flags = decode_code_page_flags(code_page);
-    /* Ideally, we should get reason from FormatMessage. This is the Windows
-       2000 English version of the message. */
-    const char *reason = "No mapping for the Unicode character exists "
-                         "in the target code page.";
-    /* each step cannot decode more than 1 character, but a character can be
-       represented as a surrogate pair */
-    wchar_t buffer[2], *startout, *out;
-    int insize;
-    Py_ssize_t outsize;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    PyObject *encoding_obj = NULL;
-    char *encoding;
-    DWORD err;
-    int ret = -1;
-
-    assert(size > 0);
-
-    encoding = code_page_name(code_page, &encoding_obj);
-    if (encoding == NULL)
-        return -1;
-
-    if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
-        /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
-           UnicodeDecodeError. */
-        make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
-        if (exc != NULL) {
-            PyCodec_StrictErrors(exc);
-            Py_CLEAR(exc);
-        }
-        goto error;
-    }
-
-    if (*v == NULL) {
-        /* Create unicode object */
-        if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
-            PyErr_NoMemory();
-            goto error;
-        }
-        /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
-        *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
-        if (*v == NULL)
-            goto error;
-        startout = PyUnicode_AS_UNICODE(*v);
-    }
-    else {
-        /* Extend unicode object */
-        Py_ssize_t n = PyUnicode_GET_SIZE(*v);
-        if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
-            PyErr_NoMemory();
-            goto error;
-        }
-        if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
-            goto error;
-        startout = PyUnicode_AS_UNICODE(*v) + n;
-    }
-
-    /* Decode the byte string character per character */
-    out = startout;
-    while (in < endin)
-    {
-        /* Decode a character */
-        insize = 1;
-        do
-        {
-            outsize = MultiByteToWideChar(code_page, flags,
-                                          in, insize,
-                                          buffer, Py_ARRAY_LENGTH(buffer));
-            if (outsize > 0)
-                break;
-            err = GetLastError();
-            if (err != ERROR_NO_UNICODE_TRANSLATION
-                && err != ERROR_INSUFFICIENT_BUFFER)
-            {
-                PyErr_SetFromWindowsErr(0);
-                goto error;
-            }
-            insize++;
-        }
-        /* 4=maximum length of a UTF-8 sequence */
-        while (insize <= 4 && (in + insize) <= endin);
-
-        if (outsize <= 0) {
-            Py_ssize_t startinpos, endinpos, outpos;
-
-            /* last character in partial decode? */
-            if (in + insize >= endin && !final)
-                break;
-
-            startinpos = in - startin;
-            endinpos = startinpos + 1;
-            outpos = out - PyUnicode_AS_UNICODE(*v);
-            if (unicode_decode_call_errorhandler_wchar(
-                    errors, &errorHandler,
-                    encoding, reason,
-                    &startin, &endin, &startinpos, &endinpos, &exc, &in,
-                    v, &outpos))
-            {
-                goto error;
-            }
-            out = PyUnicode_AS_UNICODE(*v) + outpos;
-        }
-        else {
-            in += insize;
-            memcpy(out, buffer, outsize * sizeof(wchar_t));
-            out += outsize;
-        }
-    }
-
-    /* write a NUL character at the end */
-    *out = 0;
-
-    /* Extend unicode object */
-    outsize = out - startout;
-    assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
-    if (unicode_resize(v, outsize) < 0)
-        goto error;
-    /* (in - startin) <= size and size is an int */
-    ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
-
-error:
-    Py_XDECREF(encoding_obj);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return ret;
-}
-
-static PyObject *
-decode_code_page_stateful(int code_page,
-                          const char *s, Py_ssize_t size,
-                          const char *errors, Py_ssize_t *consumed)
-{
-    PyObject *v = NULL;
-    int chunk_size, final, converted, done;
-
-    if (code_page < 0) {
-        PyErr_SetString(PyExc_ValueError, "invalid code page number");
-        return NULL;
-    }
-
-    if (consumed)
-        *consumed = 0;
-
-    do
-    {
-#ifdef NEED_RETRY
-        if (size > INT_MAX) {
-            chunk_size = INT_MAX;
-            final = 0;
-            done = 0;
-        }
-        else
-#endif
-        {
-            chunk_size = (int)size;
-            final = (consumed == NULL);
-            done = 1;
-        }
-
-        if (chunk_size == 0 && done) {
-            if (v != NULL)
-                break;
-            _Py_RETURN_UNICODE_EMPTY();
-        }
-
-        converted = decode_code_page_strict(code_page, &v,
-                                            s, chunk_size);
-        if (converted == -2)
-            converted = decode_code_page_errors(code_page, &v,
-                                                s, chunk_size,
-                                                errors, final);
-        assert(converted != 0 || done);
-
-        if (converted < 0) {
-            Py_XDECREF(v);
-            return NULL;
-        }
-
-        if (consumed)
-            *consumed += converted;
-
-        s += converted;
-        size -= converted;
-    } while (!done);
-
-    return unicode_result(v);
-}
-
-PyObject *
-PyUnicode_DecodeCodePageStateful(int code_page,
-                                 const char *s,
-                                 Py_ssize_t size,
-                                 const char *errors,
-                                 Py_ssize_t *consumed)
-{
-    return decode_code_page_stateful(code_page, s, size, errors, consumed);
-}
-
-PyObject *
-PyUnicode_DecodeMBCSStateful(const char *s,
-                             Py_ssize_t size,
-                             const char *errors,
-                             Py_ssize_t *consumed)
-{
-    return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
-}
-
-PyObject *
-PyUnicode_DecodeMBCS(const char *s,
-                     Py_ssize_t size,
-                     const char *errors)
-{
-    return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
-}
-
-static DWORD
-encode_code_page_flags(UINT code_page, const char *errors)
-{
-    if (code_page == CP_UTF8) {
-        return WC_ERR_INVALID_CHARS;
-    }
-    else if (code_page == CP_UTF7) {
-        /* CP_UTF7 only supports flags=0 */
-        return 0;
-    }
-    else {
-        if (errors != NULL && strcmp(errors, "replace") == 0)
-            return 0;
-        else
-            return WC_NO_BEST_FIT_CHARS;
-    }
-}
-
-/*
- * Encode a Unicode string to a Windows code page into a byte string in strict
- * mode.
- *
- * Returns consumed characters if succeed, returns -2 on encode error, or raise
- * an OSError and returns -1 on other error.
- */
-static int
-encode_code_page_strict(UINT code_page, PyObject **outbytes,
-                        PyObject *unicode, Py_ssize_t offset, int len,
-                        const char* errors)
-{
-    BOOL usedDefaultChar = FALSE;
-    BOOL *pusedDefaultChar = &usedDefaultChar;
-    int outsize;
-    PyObject *exc = NULL;
-    wchar_t *p;
-    Py_ssize_t size;
-    const DWORD flags = encode_code_page_flags(code_page, NULL);
-    char *out;
-    /* Create a substring so that we can get the UTF-16 representation
-       of just the slice under consideration. */
-    PyObject *substring;
-
-    assert(len > 0);
-
-    if (code_page != CP_UTF8 && code_page != CP_UTF7)
-        pusedDefaultChar = &usedDefaultChar;
-    else
-        pusedDefaultChar = NULL;
-
-    substring = PyUnicode_Substring(unicode, offset, offset+len);
-    if (substring == NULL)
-        return -1;
-    p = PyUnicode_AsUnicodeAndSize(substring, &size);
-    if (p == NULL) {
-        Py_DECREF(substring);
-        return -1;
-    }
-    assert(size <= INT_MAX);
-
-    /* First get the size of the result */
-    outsize = WideCharToMultiByte(code_page, flags,
-                                  p, (int)size,
-                                  NULL, 0,
-                                  NULL, pusedDefaultChar);
-    if (outsize <= 0)
-        goto error;
-    /* If we used a default char, then we failed! */
-    if (pusedDefaultChar && *pusedDefaultChar) {
-        Py_DECREF(substring);
-        return -2;
-    }
-
-    if (*outbytes == NULL) {
-        /* Create string object */
-        *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
-        if (*outbytes == NULL) {
-            Py_DECREF(substring);
-            return -1;
-        }
-        out = PyBytes_AS_STRING(*outbytes);
-    }
-    else {
-        /* Extend string object */
-        const Py_ssize_t n = PyBytes_Size(*outbytes);
-        if (outsize > PY_SSIZE_T_MAX - n) {
-            PyErr_NoMemory();
-            Py_DECREF(substring);
-            return -1;
-        }
-        if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
-            Py_DECREF(substring);
-            return -1;
-        }
-        out = PyBytes_AS_STRING(*outbytes) + n;
-    }
-
-    /* Do the conversion */
-    outsize = WideCharToMultiByte(code_page, flags,
-                                  p, (int)size,
-                                  out, outsize,
-                                  NULL, pusedDefaultChar);
-    Py_CLEAR(substring);
-    if (outsize <= 0)
-        goto error;
-    if (pusedDefaultChar && *pusedDefaultChar)
-        return -2;
-    return 0;
-
-error:
-    Py_XDECREF(substring);
-    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
-        return -2;
-    PyErr_SetFromWindowsErr(0);
-    return -1;
-}
-
-/*
- * Encode a Unicode string to a Windows code page into a byte string using a
- * error handler.
- *
- * Returns consumed characters if succeed, or raise an OSError and returns
- * -1 on other error.
- */
-static int
-encode_code_page_errors(UINT code_page, PyObject **outbytes,
-                        PyObject *unicode, Py_ssize_t unicode_offset,
-                        Py_ssize_t insize, const char* errors)
-{
-    const DWORD flags = encode_code_page_flags(code_page, errors);
-    Py_ssize_t pos = unicode_offset;
-    Py_ssize_t endin = unicode_offset + insize;
-    /* Ideally, we should get reason from FormatMessage. This is the Windows
-       2000 English version of the message. */
-    const char *reason = "invalid character";
-    /* 4=maximum length of a UTF-8 sequence */
-    char buffer[4];
-    BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
-    Py_ssize_t outsize;
-    char *out;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    PyObject *encoding_obj = NULL;
-    char *encoding;
-    Py_ssize_t newpos, newoutsize;
-    PyObject *rep;
-    int ret = -1;
-
-    assert(insize > 0);
-
-    encoding = code_page_name(code_page, &encoding_obj);
-    if (encoding == NULL)
-        return -1;
-
-    if (errors == NULL || strcmp(errors, "strict") == 0) {
-        /* The last error was ERROR_NO_UNICODE_TRANSLATION,
-           then we raise a UnicodeEncodeError. */
-        make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
-        if (exc != NULL) {
-            PyCodec_StrictErrors(exc);
-            Py_DECREF(exc);
-        }
-        Py_XDECREF(encoding_obj);
-        return -1;
-    }
-
-    if (code_page != CP_UTF8 && code_page != CP_UTF7)
-        pusedDefaultChar = &usedDefaultChar;
-    else
-        pusedDefaultChar = NULL;
-
-    if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
-        PyErr_NoMemory();
-        goto error;
-    }
-    outsize = insize * Py_ARRAY_LENGTH(buffer);
-
-    if (*outbytes == NULL) {
-        /* Create string object */
-        *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
-        if (*outbytes == NULL)
-            goto error;
-        out = PyBytes_AS_STRING(*outbytes);
-    }
-    else {
-        /* Extend string object */
-        Py_ssize_t n = PyBytes_Size(*outbytes);
-        if (n > PY_SSIZE_T_MAX - outsize) {
-            PyErr_NoMemory();
-            goto error;
-        }
-        if (_PyBytes_Resize(outbytes, n + outsize) < 0)
-            goto error;
-        out = PyBytes_AS_STRING(*outbytes) + n;
-    }
-
-    /* Encode the string character per character */
-    while (pos < endin)
-    {
-        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
-        wchar_t chars[2];
-        int charsize;
-        if (ch < 0x10000) {
-            chars[0] = (wchar_t)ch;
-            charsize = 1;
-        }
-        else {
-            chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
-            chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
-            charsize = 2;
-        }
-
-        outsize = WideCharToMultiByte(code_page, flags,
-                                      chars, charsize,
-                                      buffer, Py_ARRAY_LENGTH(buffer),
-                                      NULL, pusedDefaultChar);
-        if (outsize > 0) {
-            if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
-            {
-                pos++;
-                memcpy(out, buffer, outsize);
-                out += outsize;
-                continue;
-            }
-        }
-        else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
-            PyErr_SetFromWindowsErr(0);
-            goto error;
-        }
-
-        rep = unicode_encode_call_errorhandler(
-                  errors, &errorHandler, encoding, reason,
-                  unicode, &exc,
-                  pos, pos + 1, &newpos);
-        if (rep == NULL)
-            goto error;
-        pos = newpos;
-
-        if (PyBytes_Check(rep)) {
-            outsize = PyBytes_GET_SIZE(rep);
-            if (outsize != 1) {
-                Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
-                newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
-                if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
-                    Py_DECREF(rep);
-                    goto error;
-                }
-                out = PyBytes_AS_STRING(*outbytes) + offset;
-            }
-            memcpy(out, PyBytes_AS_STRING(rep), outsize);
-            out += outsize;
-        }
-        else {
-            Py_ssize_t i;
-            enum PyUnicode_Kind kind;
-            void *data;
-
-            if (PyUnicode_READY(rep) == -1) {
-                Py_DECREF(rep);
-                goto error;
-            }
-
-            outsize = PyUnicode_GET_LENGTH(rep);
-            if (outsize != 1) {
-                Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
-                newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
-                if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
-                    Py_DECREF(rep);
-                    goto error;
-                }
-                out = PyBytes_AS_STRING(*outbytes) + offset;
-            }
-            kind = PyUnicode_KIND(rep);
-            data = PyUnicode_DATA(rep);
-            for (i=0; i < outsize; i++) {
-                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-                if (ch > 127) {
-                    raise_encode_exception(&exc,
-                        encoding, unicode,
-                        pos, pos + 1,
-                        "unable to encode error handler result to ASCII");
-                    Py_DECREF(rep);
-                    goto error;
-                }
-                *out = (unsigned char)ch;
-                out++;
-            }
-        }
-        Py_DECREF(rep);
-    }
-    /* write a NUL byte */
-    *out = 0;
-    outsize = out - PyBytes_AS_STRING(*outbytes);
-    assert(outsize <= PyBytes_GET_SIZE(*outbytes));
-    if (_PyBytes_Resize(outbytes, outsize) < 0)
-        goto error;
-    ret = 0;
-
-error:
-    Py_XDECREF(encoding_obj);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return ret;
-}
-
-static PyObject *
-encode_code_page(int code_page,
-                 PyObject *unicode,
-                 const char *errors)
-{
-    Py_ssize_t len;
-    PyObject *outbytes = NULL;
-    Py_ssize_t offset;
-    int chunk_len, ret, done;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    len = PyUnicode_GET_LENGTH(unicode);
-
-    if (code_page < 0) {
-        PyErr_SetString(PyExc_ValueError, "invalid code page number");
-        return NULL;
-    }
-
-    if (len == 0)
-        return PyBytes_FromStringAndSize(NULL, 0);
-
-    offset = 0;
-    do
-    {
-#ifdef NEED_RETRY
-        /* UTF-16 encoding may double the size, so use only INT_MAX/2
-           chunks. */
-        if (len > INT_MAX/2) {
-            chunk_len = INT_MAX/2;
-            done = 0;
-        }
-        else
-#endif
-        {
-            chunk_len = (int)len;
-            done = 1;
-        }
-
-        ret = encode_code_page_strict(code_page, &outbytes,
-                                      unicode, offset, chunk_len,
-                                      errors);
-        if (ret == -2)
-            ret = encode_code_page_errors(code_page, &outbytes,
-                                          unicode, offset,
-                                          chunk_len, errors);
-        if (ret < 0) {
-            Py_XDECREF(outbytes);
-            return NULL;
-        }
-
-        offset += chunk_len;
-        len -= chunk_len;
-    } while (!done);
-
-    return outbytes;
-}
-
-PyObject *
-PyUnicode_EncodeMBCS(const Py_UNICODE *p,
-                     Py_ssize_t size,
-                     const char *errors)
-{
-    PyObject *unicode, *res;
-    unicode = PyUnicode_FromUnicode(p, size);
-    if (unicode == NULL)
-        return NULL;
-    res = encode_code_page(CP_ACP, unicode, errors);
-    Py_DECREF(unicode);
-    return res;
-}
-
-PyObject *
-PyUnicode_EncodeCodePage(int code_page,
-                         PyObject *unicode,
-                         const char *errors)
-{
-    return encode_code_page(code_page, unicode, errors);
-}
-
-PyObject *
-PyUnicode_AsMBCSString(PyObject *unicode)
-{
-    return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
-}
-
-#undef NEED_RETRY
-
-#endif /* HAVE_MBCS */
-
-/* --- Character Mapping Codec -------------------------------------------- */
-
-static int
-charmap_decode_string(const char *s,
-                      Py_ssize_t size,
-                      PyObject *mapping,
-                      const char *errors,
-                      _PyUnicodeWriter *writer)
-{
-    const char *starts = s;
-    const char *e;
-    Py_ssize_t startinpos, endinpos;
-    PyObject *errorHandler = NULL, *exc = NULL;
-    Py_ssize_t maplen;
-    enum PyUnicode_Kind mapkind;
-    void *mapdata;
-    Py_UCS4 x;
-    unsigned char ch;
-
-    if (PyUnicode_READY(mapping) == -1)
-        return -1;
-
-    maplen = PyUnicode_GET_LENGTH(mapping);
-    mapdata = PyUnicode_DATA(mapping);
-    mapkind = PyUnicode_KIND(mapping);
-
-    e = s + size;
-
-    if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
-        /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
-         * is disabled in encoding aliases, latin1 is preferred because
-         * its implementation is faster. */
-        Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
-        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
-        Py_UCS4 maxchar = writer->maxchar;
-
-        assert (writer->kind == PyUnicode_1BYTE_KIND);
-        while (s < e) {
-            ch = *s;
-            x = mapdata_ucs1[ch];
-            if (x > maxchar) {
-                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
-                    goto onError;
-                maxchar = writer->maxchar;
-                outdata = (Py_UCS1 *)writer->data;
-            }
-            outdata[writer->pos] = x;
-            writer->pos++;
-            ++s;
-        }
-        return 0;
-    }
-
-    while (s < e) {
-        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
-            enum PyUnicode_Kind outkind = writer->kind;
-            Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
-            if (outkind == PyUnicode_1BYTE_KIND) {
-                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
-                Py_UCS4 maxchar = writer->maxchar;
-                while (s < e) {
-                    ch = *s;
-                    x = mapdata_ucs2[ch];
-                    if (x > maxchar)
-                        goto Error;
-                    outdata[writer->pos] = x;
-                    writer->pos++;
-                    ++s;
-                }
-                break;
-            }
-            else if (outkind == PyUnicode_2BYTE_KIND) {
-                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
-                while (s < e) {
-                    ch = *s;
-                    x = mapdata_ucs2[ch];
-                    if (x == 0xFFFE)
-                        goto Error;
-                    outdata[writer->pos] = x;
-                    writer->pos++;
-                    ++s;
-                }
-                break;
-            }
-        }
-        ch = *s;
-
-        if (ch < maplen)
-            x = PyUnicode_READ(mapkind, mapdata, ch);
-        else
-            x = 0xfffe; /* invalid value */
-Error:
-        if (x == 0xfffe)
-        {
-            /* undefined mapping */
-            startinpos = s-starts;
-            endinpos = startinpos+1;
-            if (unicode_decode_call_errorhandler_writer(
-                    errors, &errorHandler,
-                    "charmap", "character maps to <undefined>",
-                    &starts, &e, &startinpos, &endinpos, &exc, &s,
-                    writer)) {
-                goto onError;
-            }
-            continue;
-        }
-
-        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
-            goto onError;
-        ++s;
-    }
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return 0;
-
-onError:
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return -1;
-}
-
-static int
-charmap_decode_mapping(const char *s,
-                       Py_ssize_t size,
-                       PyObject *mapping,
-                       const char *errors,
-                       _PyUnicodeWriter *writer)
-{
-    const char *starts = s;
-    const char *e;
-    Py_ssize_t startinpos, endinpos;
-    PyObject *errorHandler = NULL, *exc = NULL;
-    unsigned char ch;
-    PyObject *key, *item = NULL;
-
-    e = s + size;
-
-    while (s < e) {
-        ch = *s;
-
-        /* Get mapping (char ordinal -> integer, Unicode char or None) */
-        key = PyLong_FromLong((long)ch);
-        if (key == NULL)
-            goto onError;
-
-        item = PyObject_GetItem(mapping, key);
-        Py_DECREF(key);
-        if (item == NULL) {
-            if (PyErr_ExceptionMatches(PyExc_LookupError)) {
-                /* No mapping found means: mapping is undefined. */
-                PyErr_Clear();
-                goto Undefined;
-            } else
-                goto onError;
-        }
-
-        /* Apply mapping */
-        if (item == Py_None)
-            goto Undefined;
-        if (PyLong_Check(item)) {
-            long value = PyLong_AS_LONG(item);
-            if (value == 0xFFFE)
-                goto Undefined;
-            if (value < 0 || value > MAX_UNICODE) {
-                PyErr_Format(PyExc_TypeError,
-                             "character mapping must be in range(0x%lx)",
-                             (unsigned long)MAX_UNICODE + 1);
-                goto onError;
-            }
-
-            if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
-                goto onError;
-        }
-        else if (PyUnicode_Check(item)) {
-            if (PyUnicode_READY(item) == -1)
-                goto onError;
-            if (PyUnicode_GET_LENGTH(item) == 1) {
-                Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
-                if (value == 0xFFFE)
-                    goto Undefined;
-                if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
-                    goto onError;
-            }
-            else {
-                writer->overallocate = 1;
-                if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
-                    goto onError;
-            }
-        }
-        else {
-            /* wrong return value */
-            PyErr_SetString(PyExc_TypeError,
-                            "character mapping must return integer, None or str");
-            goto onError;
-        }
-        Py_CLEAR(item);
-        ++s;
-        continue;
-
-Undefined:
-        /* undefined mapping */
-        Py_CLEAR(item);
-        startinpos = s-starts;
-        endinpos = startinpos+1;
-        if (unicode_decode_call_errorhandler_writer(
-                errors, &errorHandler,
-                "charmap", "character maps to <undefined>",
-                &starts, &e, &startinpos, &endinpos, &exc, &s,
-                writer)) {
-            goto onError;
-        }
-    }
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return 0;
-
-onError:
-    Py_XDECREF(item);
-    Py_XDECREF(errorHandler);
-    Py_XDECREF(exc);
-    return -1;
-}
-
-PyObject *
-PyUnicode_DecodeCharmap(const char *s,
-                        Py_ssize_t size,
-                        PyObject *mapping,
-                        const char *errors)
-{
-    _PyUnicodeWriter writer;
-
-    /* Default to Latin-1 */
-    if (mapping == NULL)
-        return PyUnicode_DecodeLatin1(s, size, errors);
-
-    if (size == 0)
-        _Py_RETURN_UNICODE_EMPTY();
-    _PyUnicodeWriter_Init(&writer);
-    writer.min_length = size;
-    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
-        goto onError;
-
-    if (PyUnicode_CheckExact(mapping)) {
-        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
-            goto onError;
-    }
-    else {
-        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
-            goto onError;
-    }
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    return NULL;
-}
-
-/* Charmap encoding: the lookup table */
-
-struct encoding_map {
-    PyObject_HEAD
-    unsigned char level1[32];
-    int count2, count3;
-    unsigned char level23[1];
-};
-
-static PyObject*
-encoding_map_size(PyObject *obj, PyObject* args)
-{
-    struct encoding_map *map = (struct encoding_map*)obj;
-    return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
-                           128*map->count3);
-}
-
-static PyMethodDef encoding_map_methods[] = {
-    {"size", encoding_map_size, METH_NOARGS,
-     PyDoc_STR("Return the size (in bytes) of this object") },
-    { 0 }
-};
-
-static void
-encoding_map_dealloc(PyObject* o)
-{
-    PyObject_FREE(o);
-}
-
-static PyTypeObject EncodingMapType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "EncodingMap",          /*tp_name*/
-    sizeof(struct encoding_map),   /*tp_basicsize*/
-    0,                      /*tp_itemsize*/
-    /* methods */
-    encoding_map_dealloc,   /*tp_dealloc*/
-    0,                      /*tp_print*/
-    0,                      /*tp_getattr*/
-    0,                      /*tp_setattr*/
-    0,                      /*tp_reserved*/
-    0,                      /*tp_repr*/
-    0,                      /*tp_as_number*/
-    0,                      /*tp_as_sequence*/
-    0,                      /*tp_as_mapping*/
-    0,                      /*tp_hash*/
-    0,                      /*tp_call*/
-    0,                      /*tp_str*/
-    0,                      /*tp_getattro*/
-    0,                      /*tp_setattro*/
-    0,                      /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT,     /*tp_flags*/
-    0,                      /*tp_doc*/
-    0,                      /*tp_traverse*/
-    0,                      /*tp_clear*/
-    0,                      /*tp_richcompare*/
-    0,                      /*tp_weaklistoffset*/
-    0,                      /*tp_iter*/
-    0,                      /*tp_iternext*/
-    encoding_map_methods,   /*tp_methods*/
-    0,                      /*tp_members*/
-    0,                      /*tp_getset*/
-    0,                      /*tp_base*/
-    0,                      /*tp_dict*/
-    0,                      /*tp_descr_get*/
-    0,                      /*tp_descr_set*/
-    0,                      /*tp_dictoffset*/
-    0,                      /*tp_init*/
-    0,                      /*tp_alloc*/
-    0,                      /*tp_new*/
-    0,                      /*tp_free*/
-    0,                      /*tp_is_gc*/
-};
-
-PyObject*
-PyUnicode_BuildEncodingMap(PyObject* string)
-{
-    PyObject *result;
-    struct encoding_map *mresult;
-    int i;
-    int need_dict = 0;
-    unsigned char level1[32];
-    unsigned char level2[512];
-    unsigned char *mlevel1, *mlevel2, *mlevel3;
-    int count2 = 0, count3 = 0;
-    int kind;
-    void *data;
-    Py_ssize_t length;
-    Py_UCS4 ch;
-
-    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    kind = PyUnicode_KIND(string);
-    data = PyUnicode_DATA(string);
-    length = PyUnicode_GET_LENGTH(string);
-    length = Py_MIN(length, 256);
-    memset(level1, 0xFF, sizeof level1);
-    memset(level2, 0xFF, sizeof level2);
-
-    /* If there isn't a one-to-one mapping of NULL to \0,
-       or if there are non-BMP characters, we need to use
-       a mapping dictionary. */
-    if (PyUnicode_READ(kind, data, 0) != 0)
-        need_dict = 1;
-    for (i = 1; i < length; i++) {
-        int l1, l2;
-        ch = PyUnicode_READ(kind, data, i);
-        if (ch == 0 || ch > 0xFFFF) {
-            need_dict = 1;
-            break;
-        }
-        if (ch == 0xFFFE)
-            /* unmapped character */
-            continue;
-        l1 = ch >> 11;
-        l2 = ch >> 7;
-        if (level1[l1] == 0xFF)
-            level1[l1] = count2++;
-        if (level2[l2] == 0xFF)
-            level2[l2] = count3++;
-    }
-
-    if (count2 >= 0xFF || count3 >= 0xFF)
-        need_dict = 1;
-
-    if (need_dict) {
-        PyObject *result = PyDict_New();
-        PyObject *key, *value;
-        if (!result)
-            return NULL;
-        for (i = 0; i < length; i++) {
-            key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
-            value = PyLong_FromLong(i);
-            if (!key || !value)
-                goto failed1;
-            if (PyDict_SetItem(result, key, value) == -1)
-                goto failed1;
-            Py_DECREF(key);
-            Py_DECREF(value);
-        }
-        return result;
-      failed1:
-        Py_XDECREF(key);
-        Py_XDECREF(value);
-        Py_DECREF(result);
-        return NULL;
-    }
-
-    /* Create a three-level trie */
-    result = PyObject_MALLOC(sizeof(struct encoding_map) +
-                             16*count2 + 128*count3 - 1);
-    if (!result)
-        return PyErr_NoMemory();
-    PyObject_Init(result, &EncodingMapType);
-    mresult = (struct encoding_map*)result;
-    mresult->count2 = count2;
-    mresult->count3 = count3;
-    mlevel1 = mresult->level1;
-    mlevel2 = mresult->level23;
-    mlevel3 = mresult->level23 + 16*count2;
-    memcpy(mlevel1, level1, 32);
-    memset(mlevel2, 0xFF, 16*count2);
-    memset(mlevel3, 0, 128*count3);
-    count3 = 0;
-    for (i = 1; i < length; i++) {
-        int o1, o2, o3, i2, i3;
-        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-        if (ch == 0xFFFE)
-            /* unmapped character */
-            continue;
-        o1 = ch>>11;
-        o2 = (ch>>7) & 0xF;
-        i2 = 16*mlevel1[o1] + o2;
-        if (mlevel2[i2] == 0xFF)
-            mlevel2[i2] = count3++;
-        o3 = ch & 0x7F;
-        i3 = 128*mlevel2[i2] + o3;
-        mlevel3[i3] = i;
-    }
-    return result;
-}
-
-static int
-encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
-{
-    struct encoding_map *map = (struct encoding_map*)mapping;
-    int l1 = c>>11;
-    int l2 = (c>>7) & 0xF;
-    int l3 = c & 0x7F;
-    int i;
-
-    if (c > 0xFFFF)
-        return -1;
-    if (c == 0)
-        return 0;
-    /* level 1*/
-    i = map->level1[l1];
-    if (i == 0xFF) {
-        return -1;
-    }
-    /* level 2*/
-    i = map->level23[16*i+l2];
-    if (i == 0xFF) {
-        return -1;
-    }
-    /* level 3 */
-    i = map->level23[16*map->count2 + 128*i + l3];
-    if (i == 0) {
-        return -1;
-    }
-    return i;
-}
-
-/* Lookup the character ch in the mapping. If the character
-   can't be found, Py_None is returned (or NULL, if another
-   error occurred). */
-static PyObject *
-charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
-{
-    PyObject *w = PyLong_FromLong((long)c);
-    PyObject *x;
-
-    if (w == NULL)
-        return NULL;
-    x = PyObject_GetItem(mapping, w);
-    Py_DECREF(w);
-    if (x == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
-            /* No mapping found means: mapping is undefined. */
-            PyErr_Clear();
-            x = Py_None;
-            Py_INCREF(x);
-            return x;
-        } else
-            return NULL;
-    }
-    else if (x == Py_None)
-        return x;
-    else if (PyLong_Check(x)) {
-        long value = PyLong_AS_LONG(x);
-        if (value < 0 || value > 255) {
-            PyErr_SetString(PyExc_TypeError,
-                            "character mapping must be in range(256)");
-            Py_DECREF(x);
-            return NULL;
-        }
-        return x;
-    }
-    else if (PyBytes_Check(x))
-        return x;
-    else {
-        /* wrong return value */
-        PyErr_Format(PyExc_TypeError,
-                     "character mapping must return integer, bytes or None, not %.400s",
-                     x->ob_type->tp_name);
-        Py_DECREF(x);
-        return NULL;
-    }
-}
-
-static int
-charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
-{
-    Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
-    /* exponentially overallocate to minimize reallocations */
-    if (requiredsize < 2*outsize)
-        requiredsize = 2*outsize;
-    if (_PyBytes_Resize(outobj, requiredsize))
-        return -1;
-    return 0;
-}
-
-typedef enum charmapencode_result {
-    enc_SUCCESS, enc_FAILED, enc_EXCEPTION
-} charmapencode_result;
-/* lookup the character, put the result in the output string and adjust
-   various state variables. Resize the output bytes object if not enough
-   space is available. Return a new reference to the object that
-   was put in the output buffer, or Py_None, if the mapping was undefined
-   (in which case no character was written) or NULL, if a
-   reallocation error occurred. The caller must decref the result */
-static charmapencode_result
-charmapencode_output(Py_UCS4 c, PyObject *mapping,
-                     PyObject **outobj, Py_ssize_t *outpos)
-{
-    PyObject *rep;
-    char *outstart;
-    Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
-
-    if (Py_TYPE(mapping) == &EncodingMapType) {
-        int res = encoding_map_lookup(c, mapping);
-        Py_ssize_t requiredsize = *outpos+1;
-        if (res == -1)
-            return enc_FAILED;
-        if (outsize<requiredsize)
-            if (charmapencode_resize(outobj, outpos, requiredsize))
-                return enc_EXCEPTION;
-        outstart = PyBytes_AS_STRING(*outobj);
-        outstart[(*outpos)++] = (char)res;
-        return enc_SUCCESS;
-    }
-
-    rep = charmapencode_lookup(c, mapping);
-    if (rep==NULL)
-        return enc_EXCEPTION;
-    else if (rep==Py_None) {
-        Py_DECREF(rep);
-        return enc_FAILED;
-    } else {
-        if (PyLong_Check(rep)) {
-            Py_ssize_t requiredsize = *outpos+1;
-            if (outsize<requiredsize)
-                if (charmapencode_resize(outobj, outpos, requiredsize)) {
-                    Py_DECREF(rep);
-                    return enc_EXCEPTION;
-                }
-            outstart = PyBytes_AS_STRING(*outobj);
-            outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
-        }
-        else {
-            const char *repchars = PyBytes_AS_STRING(rep);
-            Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
-            Py_ssize_t requiredsize = *outpos+repsize;
-            if (outsize<requiredsize)
-                if (charmapencode_resize(outobj, outpos, requiredsize)) {
-                    Py_DECREF(rep);
-                    return enc_EXCEPTION;
-                }
-            outstart = PyBytes_AS_STRING(*outobj);
-            memcpy(outstart + *outpos, repchars, repsize);
-            *outpos += repsize;
-        }
-    }
-    Py_DECREF(rep);
-    return enc_SUCCESS;
-}
-
-/* handle an error in PyUnicode_EncodeCharmap
-   Return 0 on success, -1 on error */
-static int
-charmap_encoding_error(
-    PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
-    PyObject **exceptionObject,
-    int *known_errorHandler, PyObject **errorHandler, const char *errors,
-    PyObject **res, Py_ssize_t *respos)
-{
-    PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
-    Py_ssize_t size, repsize;
-    Py_ssize_t newpos;
-    enum PyUnicode_Kind kind;
-    void *data;
-    Py_ssize_t index;
-    /* startpos for collecting unencodable chars */
-    Py_ssize_t collstartpos = *inpos;
-    Py_ssize_t collendpos = *inpos+1;
-    Py_ssize_t collpos;
-    char *encoding = "charmap";
-    char *reason = "character maps to <undefined>";
-    charmapencode_result x;
-    Py_UCS4 ch;
-    int val;
-
-    if (PyUnicode_READY(unicode) == -1)
-        return -1;
-    size = PyUnicode_GET_LENGTH(unicode);
-    /* find all unencodable characters */
-    while (collendpos < size) {
-        PyObject *rep;
-        if (Py_TYPE(mapping) == &EncodingMapType) {
-            ch = PyUnicode_READ_CHAR(unicode, collendpos);
-            val = encoding_map_lookup(ch, mapping);
-            if (val != -1)
-                break;
-            ++collendpos;
-            continue;
-        }
-
-        ch = PyUnicode_READ_CHAR(unicode, collendpos);
-        rep = charmapencode_lookup(ch, mapping);
-        if (rep==NULL)
-            return -1;
-        else if (rep!=Py_None) {
-            Py_DECREF(rep);
-            break;
-        }
-        Py_DECREF(rep);
-        ++collendpos;
-    }
-    /* cache callback name lookup
-     * (if not done yet, i.e. it's the first error) */
-    if (*known_errorHandler==-1) {
-        if ((errors==NULL) || (!strcmp(errors, "strict")))
-            *known_errorHandler = 1;
-        else if (!strcmp(errors, "replace"))
-            *known_errorHandler = 2;
-        else if (!strcmp(errors, "ignore"))
-            *known_errorHandler = 3;
-        else if (!strcmp(errors, "xmlcharrefreplace"))
-            *known_errorHandler = 4;
-        else
-            *known_errorHandler = 0;
-    }
-    switch (*known_errorHandler) {
-    case 1: /* strict */
-        raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
-        return -1;
-    case 2: /* replace */
-        for (collpos = collstartpos; collpos<collendpos; ++collpos) {
-            x = charmapencode_output('?', mapping, res, respos);
-            if (x==enc_EXCEPTION) {
-                return -1;
-            }
-            else if (x==enc_FAILED) {
-                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
-                return -1;
-            }
-        }
-        /* fall through */
-    case 3: /* ignore */
-        *inpos = collendpos;
-        break;
-    case 4: /* xmlcharrefreplace */
-        /* generate replacement (temporarily (mis)uses p) */
-        for (collpos = collstartpos; collpos < collendpos; ++collpos) {
-            char buffer[2+29+1+1];
-            char *cp;
-            sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
-            for (cp = buffer; *cp; ++cp) {
-                x = charmapencode_output(*cp, mapping, res, respos);
-                if (x==enc_EXCEPTION)
-                    return -1;
-                else if (x==enc_FAILED) {
-                    raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
-                    return -1;
-                }
-            }
-        }
-        *inpos = collendpos;
-        break;
-    default:
-        repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
-                                                      encoding, reason, unicode, exceptionObject,
-                                                      collstartpos, collendpos, &newpos);
-        if (repunicode == NULL)
-            return -1;
-        if (PyBytes_Check(repunicode)) {
-            /* Directly copy bytes result to output. */
-            Py_ssize_t outsize = PyBytes_Size(*res);
-            Py_ssize_t requiredsize;
-            repsize = PyBytes_Size(repunicode);
-            requiredsize = *respos + repsize;
-            if (requiredsize > outsize)
-                /* Make room for all additional bytes. */
-                if (charmapencode_resize(res, respos, requiredsize)) {
-                    Py_DECREF(repunicode);
-                    return -1;
-                }
-            memcpy(PyBytes_AsString(*res) + *respos,
-                   PyBytes_AsString(repunicode),  repsize);
-            *respos += repsize;
-            *inpos = newpos;
-            Py_DECREF(repunicode);
-            break;
-        }
-        /* generate replacement  */
-        if (PyUnicode_READY(repunicode) == -1) {
-            Py_DECREF(repunicode);
-            return -1;
-        }
-        repsize = PyUnicode_GET_LENGTH(repunicode);
-        data = PyUnicode_DATA(repunicode);
-        kind = PyUnicode_KIND(repunicode);
-        for (index = 0; index < repsize; index++) {
-            Py_UCS4 repch = PyUnicode_READ(kind, data, index);
-            x = charmapencode_output(repch, mapping, res, respos);
-            if (x==enc_EXCEPTION) {
-                Py_DECREF(repunicode);
-                return -1;
-            }
-            else if (x==enc_FAILED) {
-                Py_DECREF(repunicode);
-                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
-                return -1;
-            }
-        }
-        *inpos = newpos;
-        Py_DECREF(repunicode);
-    }
-    return 0;
-}
-
-PyObject *
-_PyUnicode_EncodeCharmap(PyObject *unicode,
-                         PyObject *mapping,
-                         const char *errors)
-{
-    /* output object */
-    PyObject *res = NULL;
-    /* current input position */
-    Py_ssize_t inpos = 0;
-    Py_ssize_t size;
-    /* current output position */
-    Py_ssize_t respos = 0;
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    /* the following variable is used for caching string comparisons
-     * -1=not initialized, 0=unknown, 1=strict, 2=replace,
-     * 3=ignore, 4=xmlcharrefreplace */
-    int known_errorHandler = -1;
-    void *data;
-    int kind;
-
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    size = PyUnicode_GET_LENGTH(unicode);
-    data = PyUnicode_DATA(unicode);
-    kind = PyUnicode_KIND(unicode);
-
-    /* Default to Latin-1 */
-    if (mapping == NULL)
-        return unicode_encode_ucs1(unicode, errors, 256);
-
-    /* allocate enough for a simple encoding without
-       replacements, if we need more, we'll resize */
-    res = PyBytes_FromStringAndSize(NULL, size);
-    if (res == NULL)
-        goto onError;
-    if (size == 0)
-        return res;
-
-    while (inpos<size) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
-        /* try to encode it */
-        charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
-        if (x==enc_EXCEPTION) /* error */
-            goto onError;
-        if (x==enc_FAILED) { /* unencodable character */
-            if (charmap_encoding_error(unicode, &inpos, mapping,
-                                       &exc,
-                                       &known_errorHandler, &errorHandler, errors,
-                                       &res, &respos)) {
-                goto onError;
-            }
-        }
-        else
-            /* done with this character => adjust input position */
-            ++inpos;
-    }
-
-    /* Resize if we allocated to much */
-    if (respos<PyBytes_GET_SIZE(res))
-        if (_PyBytes_Resize(&res, respos) < 0)
-            goto onError;
-
-    Py_XDECREF(exc);
-    Py_XDECREF(errorHandler);
-    return res;
-
-  onError:
-    Py_XDECREF(res);
-    Py_XDECREF(exc);
-    Py_XDECREF(errorHandler);
-    return NULL;
-}
-
-/* Deprecated */
-PyObject *
-PyUnicode_EncodeCharmap(const Py_UNICODE *p,
-                        Py_ssize_t size,
-                        PyObject *mapping,
-                        const char *errors)
-{
-    PyObject *result;
-    PyObject *unicode = PyUnicode_FromUnicode(p, size);
-    if (unicode == NULL)
-        return NULL;
-    result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
-    Py_DECREF(unicode);
-    return result;
-}
-
-PyObject *
-PyUnicode_AsCharmapString(PyObject *unicode,
-                          PyObject *mapping)
-{
-    if (!PyUnicode_Check(unicode) || mapping == NULL) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
-}
-
-/* create or adjust a UnicodeTranslateError */
-static void
-make_translate_exception(PyObject **exceptionObject,
-                         PyObject *unicode,
-                         Py_ssize_t startpos, Py_ssize_t endpos,
-                         const char *reason)
-{
-    if (*exceptionObject == NULL) {
-        *exceptionObject = _PyUnicodeTranslateError_Create(
-            unicode, startpos, endpos, reason);
-    }
-    else {
-        if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
-            goto onError;
-        if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
-            goto onError;
-        if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
-            goto onError;
-        return;
-      onError:
-        Py_CLEAR(*exceptionObject);
-    }
-}
-
-/* error handling callback helper:
-   build arguments, call the callback and check the arguments,
-   put the result into newpos and return the replacement string, which
-   has to be freed by the caller */
-static PyObject *
-unicode_translate_call_errorhandler(const char *errors,
-                                    PyObject **errorHandler,
-                                    const char *reason,
-                                    PyObject *unicode, PyObject **exceptionObject,
-                                    Py_ssize_t startpos, Py_ssize_t endpos,
-                                    Py_ssize_t *newpos)
-{
-    static char *argparse = "O!n;translating error handler must return (str, int) tuple";
-
-    Py_ssize_t i_newpos;
-    PyObject *restuple;
-    PyObject *resunicode;
-
-    if (*errorHandler == NULL) {
-        *errorHandler = PyCodec_LookupError(errors);
-        if (*errorHandler == NULL)
-            return NULL;
-    }
-
-    make_translate_exception(exceptionObject,
-                             unicode, startpos, endpos, reason);
-    if (*exceptionObject == NULL)
-        return NULL;
-
-    restuple = PyObject_CallFunctionObjArgs(
-        *errorHandler, *exceptionObject, NULL);
-    if (restuple == NULL)
-        return NULL;
-    if (!PyTuple_Check(restuple)) {
-        PyErr_SetString(PyExc_TypeError, &argparse[4]);
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
-                          &resunicode, &i_newpos)) {
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    if (i_newpos<0)
-        *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
-    else
-        *newpos = i_newpos;
-    if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
-        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
-        Py_DECREF(restuple);
-        return NULL;
-    }
-    Py_INCREF(resunicode);
-    Py_DECREF(restuple);
-    return resunicode;
-}
-
-/* Lookup the character ch in the mapping and put the result in result,
-   which must be decrefed by the caller.
-   Return 0 on success, -1 on error */
-static int
-charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
-{
-    PyObject *w = PyLong_FromLong((long)c);
-    PyObject *x;
-
-    if (w == NULL)
-        return -1;
-    x = PyObject_GetItem(mapping, w);
-    Py_DECREF(w);
-    if (x == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
-            /* No mapping found means: use 1:1 mapping. */
-            PyErr_Clear();
-            *result = NULL;
-            return 0;
-        } else
-            return -1;
-    }
-    else if (x == Py_None) {
-        *result = x;
-        return 0;
-    }
-    else if (PyLong_Check(x)) {
-        long value = PyLong_AS_LONG(x);
-        if (value < 0 || value > MAX_UNICODE) {
-            PyErr_Format(PyExc_ValueError,
-                         "character mapping must be in range(0x%x)",
-                         MAX_UNICODE+1);
-            Py_DECREF(x);
-            return -1;
-        }
-        *result = x;
-        return 0;
-    }
-    else if (PyUnicode_Check(x)) {
-        *result = x;
-        return 0;
-    }
-    else {
-        /* wrong return value */
-        PyErr_SetString(PyExc_TypeError,
-                        "character mapping must return integer, None or str");
-        Py_DECREF(x);
-        return -1;
-    }
-}
-
-/* lookup the character, write the result into the writer.
-   Return 1 if the result was written into the writer, return 0 if the mapping
-   was undefined, raise an exception return -1 on error. */
-static int
-charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
-                        _PyUnicodeWriter *writer)
-{
-    PyObject *item;
-
-    if (charmaptranslate_lookup(ch, mapping, &item))
-        return -1;
-
-    if (item == NULL) {
-        /* not found => default to 1:1 mapping */
-        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
-            return -1;
-        }
-        return 1;
-    }
-
-    if (item == Py_None) {
-        Py_DECREF(item);
-        return 0;
-    }
-
-    if (PyLong_Check(item)) {
-        long ch = (Py_UCS4)PyLong_AS_LONG(item);
-        /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
-           used it */
-        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
-            Py_DECREF(item);
-            return -1;
-        }
-        Py_DECREF(item);
-        return 1;
-    }
-
-    if (!PyUnicode_Check(item)) {
-        Py_DECREF(item);
-        return -1;
-    }
-
-    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
-        Py_DECREF(item);
-        return -1;
-    }
-
-    Py_DECREF(item);
-    return 1;
-}
-
-static int
-unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
-                              Py_UCS1 *translate)
-{
-    PyObject *item = NULL;
-    int ret = 0;
-
-    if (charmaptranslate_lookup(ch, mapping, &item)) {
-        return -1;
-    }
-
-    if (item == Py_None) {
-        /* deletion */
-        translate[ch] = 0xfe;
-    }
-    else if (item == NULL) {
-        /* not found => default to 1:1 mapping */
-        translate[ch] = ch;
-        return 1;
-    }
-    else if (PyLong_Check(item)) {
-        long replace = PyLong_AS_LONG(item);
-        /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
-           used it */
-        if (127 < replace) {
-            /* invalid character or character outside ASCII:
-               skip the fast translate */
-            goto exit;
-        }
-        translate[ch] = (Py_UCS1)replace;
-    }
-    else if (PyUnicode_Check(item)) {
-        Py_UCS4 replace;
-
-        if (PyUnicode_READY(item) == -1) {
-            Py_DECREF(item);
-            return -1;
-        }
-        if (PyUnicode_GET_LENGTH(item) != 1)
-            goto exit;
-
-        replace = PyUnicode_READ_CHAR(item, 0);
-        if (replace > 127)
-            goto exit;
-        translate[ch] = (Py_UCS1)replace;
-    }
-    else {
-        /* not None, NULL, long or unicode */
-        goto exit;
-    }
-    ret = 1;
-
-  exit:
-    Py_DECREF(item);
-    return ret;
-}
-
-/* Fast path for ascii => ascii translation. Return 1 if the whole string
-   was translated into writer, return 0 if the input string was partially
-   translated into writer, raise an exception and return -1 on error. */
-static int
-unicode_fast_translate(PyObject *input, PyObject *mapping,
-                       _PyUnicodeWriter *writer, int ignore)
-{
-    Py_UCS1 ascii_table[128], ch, ch2;
-    Py_ssize_t len;
-    Py_UCS1 *in, *end, *out;
-    int res = 0;
-
-    if (PyUnicode_READY(input) == -1)
-        return -1;
-    if (!PyUnicode_IS_ASCII(input))
-        return 0;
-    len = PyUnicode_GET_LENGTH(input);
-
-    memset(ascii_table, 0xff, 128);
-
-    in = PyUnicode_1BYTE_DATA(input);
-    end = in + len;
-
-    assert(PyUnicode_IS_ASCII(writer->buffer));
-    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
-    out = PyUnicode_1BYTE_DATA(writer->buffer);
-
-    for (; in < end; in++) {
-        ch = *in;
-        ch2 = ascii_table[ch];
-        if (ch2 == 0xff) {
-            int translate = unicode_fast_translate_lookup(mapping, ch,
-                                                          ascii_table);
-            if (translate < 0)
-                return -1;
-            if (translate == 0)
-                goto exit;
-            ch2 = ascii_table[ch];
-        }
-        if (ch2 == 0xfe) {
-            if (ignore)
-                continue;
-            goto exit;
-        }
-        assert(ch2 < 128);
-        *out = ch2;
-        out++;
-    }
-    res = 1;
-
-exit:
-    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
-    return res;
-}
-
-PyObject *
-_PyUnicode_TranslateCharmap(PyObject *input,
-                            PyObject *mapping,
-                            const char *errors)
-{
-    /* input object */
-    char *data;
-    Py_ssize_t size, i;
-    int kind;
-    /* output buffer */
-    _PyUnicodeWriter writer;
-    /* error handler */
-    char *reason = "character maps to <undefined>";
-    PyObject *errorHandler = NULL;
-    PyObject *exc = NULL;
-    int ignore;
-    int res;
-
-    if (mapping == NULL) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-
-    if (PyUnicode_READY(input) == -1)
-        return NULL;
-    data = (char*)PyUnicode_DATA(input);
-    kind = PyUnicode_KIND(input);
-    size = PyUnicode_GET_LENGTH(input);
-
-    if (size == 0) {
-        Py_INCREF(input);
-        return input;
-    }
-
-    /* allocate enough for a simple 1:1 translation without
-       replacements, if we need more, we'll resize */
-    _PyUnicodeWriter_Init(&writer);
-    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
-        goto onError;
-
-    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
-
-    res = unicode_fast_translate(input, mapping, &writer, ignore);
-    if (res < 0) {
-        _PyUnicodeWriter_Dealloc(&writer);
-        return NULL;
-    }
-    if (res == 1)
-        return _PyUnicodeWriter_Finish(&writer);
-
-    i = writer.pos;
-    while (i<size) {
-        /* try to encode it */
-        int translate;
-        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
-        Py_ssize_t newpos;
-        /* startpos for collecting untranslatable chars */
-        Py_ssize_t collstart;
-        Py_ssize_t collend;
-        Py_UCS4 ch;
-
-        ch = PyUnicode_READ(kind, data, i);
-        translate = charmaptranslate_output(ch, mapping, &writer);
-        if (translate < 0)
-            goto onError;
-
-        if (translate != 0) {
-            /* it worked => adjust input pointer */
-            ++i;
-            continue;
-        }
-
-        /* untranslatable character */
-        collstart = i;
-        collend = i+1;
-
-        /* find all untranslatable characters */
-        while (collend < size) {
-            PyObject *x;
-            ch = PyUnicode_READ(kind, data, collend);
-            if (charmaptranslate_lookup(ch, mapping, &x))
-                goto onError;
-            Py_XDECREF(x);
-            if (x != Py_None)
-                break;
-            ++collend;
-        }
-
-        if (ignore) {
-            i = collend;
-        }
-        else {
-            repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
-                                                             reason, input, &exc,
-                                                             collstart, collend, &newpos);
-            if (repunicode == NULL)
-                goto onError;
-            if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
-                Py_DECREF(repunicode);
-                goto onError;
-            }
-            Py_DECREF(repunicode);
-            i = newpos;
-        }
-    }
-    Py_XDECREF(exc);
-    Py_XDECREF(errorHandler);
-    return _PyUnicodeWriter_Finish(&writer);
-
-  onError:
-    _PyUnicodeWriter_Dealloc(&writer);
-    Py_XDECREF(exc);
-    Py_XDECREF(errorHandler);
-    return NULL;
-}
-
-/* Deprecated. Use PyUnicode_Translate instead. */
-PyObject *
-PyUnicode_TranslateCharmap(const Py_UNICODE *p,
-                           Py_ssize_t size,
-                           PyObject *mapping,
-                           const char *errors)
-{
-    PyObject *result;
-    PyObject *unicode = PyUnicode_FromUnicode(p, size);
-    if (!unicode)
-        return NULL;
-    result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
-    Py_DECREF(unicode);
-    return result;
-}
-
-PyObject *
-PyUnicode_Translate(PyObject *str,
-                    PyObject *mapping,
-                    const char *errors)
-{
-    PyObject *result;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL)
-        return NULL;
-    result = _PyUnicode_TranslateCharmap(str, mapping, errors);
-    Py_DECREF(str);
-    return result;
-}
-
-static Py_UCS4
-fix_decimal_and_space_to_ascii(PyObject *self)
-{
-    /* No need to call PyUnicode_READY(self) because this function is only
-       called as a callback from fixup() which does it already. */
-    const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
-    const int kind = PyUnicode_KIND(self);
-    void *data = PyUnicode_DATA(self);
-    Py_UCS4 maxchar = 127, ch, fixed;
-    int modified = 0;
-    Py_ssize_t i;
-
-    for (i = 0; i < len; ++i) {
-        ch = PyUnicode_READ(kind, data, i);
-        fixed = 0;
-        if (ch > 127) {
-            if (Py_UNICODE_ISSPACE(ch))
-                fixed = ' ';
-            else {
-                const int decimal = Py_UNICODE_TODECIMAL(ch);
-                if (decimal >= 0)
-                    fixed = '0' + decimal;
-            }
-            if (fixed != 0) {
-                modified = 1;
-                maxchar = Py_MAX(maxchar, fixed);
-                PyUnicode_WRITE(kind, data, i, fixed);
-            }
-            else
-                maxchar = Py_MAX(maxchar, ch);
-        }
-    }
-
-    return (modified) ? maxchar : 0;
-}
-
-PyObject *
-_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
-{
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-    if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
-        /* If the string is already ASCII, just return the same string */
-        Py_INCREF(unicode);
-        return unicode;
-    }
-    return fixup(unicode, fix_decimal_and_space_to_ascii);
-}
-
-PyObject *
-PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
-                                  Py_ssize_t length)
-{
-    PyObject *decimal;
-    Py_ssize_t i;
-    Py_UCS4 maxchar;
-    enum PyUnicode_Kind kind;
-    void *data;
-
-    maxchar = 127;
-    for (i = 0; i < length; i++) {
-        Py_UCS4 ch = s[i];
-        if (ch > 127) {
-            int decimal = Py_UNICODE_TODECIMAL(ch);
-            if (decimal >= 0)
-                ch = '0' + decimal;
-            maxchar = Py_MAX(maxchar, ch);
-        }
-    }
-
-    /* Copy to a new string */
-    decimal = PyUnicode_New(length, maxchar);
-    if (decimal == NULL)
-        return decimal;
-    kind = PyUnicode_KIND(decimal);
-    data = PyUnicode_DATA(decimal);
-    /* Iterate over code points */
-    for (i = 0; i < length; i++) {
-        Py_UCS4 ch = s[i];
-        if (ch > 127) {
-            int decimal = Py_UNICODE_TODECIMAL(ch);
-            if (decimal >= 0)
-                ch = '0' + decimal;
-        }
-        PyUnicode_WRITE(kind, data, i, ch);
-    }
-    return unicode_result(decimal);
-}
-/* --- Decimal Encoder ---------------------------------------------------- */
-
-int
-PyUnicode_EncodeDecimal(Py_UNICODE *s,
-                        Py_ssize_t length,
-                        char *output,
-                        const char *errors)
-{
-    PyObject *unicode;
-    Py_ssize_t i;
-    enum PyUnicode_Kind kind;
-    void *data;
-
-    if (output == NULL) {
-        PyErr_BadArgument();
-        return -1;
-    }
-
-    unicode = PyUnicode_FromUnicode(s, length);
-    if (unicode == NULL)
-        return -1;
-
-    if (PyUnicode_READY(unicode) == -1) {
-        Py_DECREF(unicode);
-        return -1;
-    }
-    kind = PyUnicode_KIND(unicode);
-    data = PyUnicode_DATA(unicode);
-
-    for (i=0; i < length; ) {
-        PyObject *exc;
-        Py_UCS4 ch;
-        int decimal;
-        Py_ssize_t startpos;
-
-        ch = PyUnicode_READ(kind, data, i);
-
-        if (Py_UNICODE_ISSPACE(ch)) {
-            *output++ = ' ';
-            i++;
-            continue;
-        }
-        decimal = Py_UNICODE_TODECIMAL(ch);
-        if (decimal >= 0) {
-            *output++ = '0' + decimal;
-            i++;
-            continue;
-        }
-        if (0 < ch && ch < 256) {
-            *output++ = (char)ch;
-            i++;
-            continue;
-        }
-
-        startpos = i;
-        exc = NULL;
-        raise_encode_exception(&exc, "decimal", unicode,
-                               startpos, startpos+1,
-                               "invalid decimal Unicode string");
-        Py_XDECREF(exc);
-        Py_DECREF(unicode);
-        return -1;
-    }
-    /* 0-terminate the output string */
-    *output++ = '\0';
-    Py_DECREF(unicode);
-    return 0;
-}
-
-/* --- Helpers ------------------------------------------------------------ */
-
-/* helper macro to fixup start/end slice values */
-#define ADJUST_INDICES(start, end, len)         \
-    if (end > len)                              \
-        end = len;                              \
-    else if (end < 0) {                         \
-        end += len;                             \
-        if (end < 0)                            \
-            end = 0;                            \
-    }                                           \
-    if (start < 0) {                            \
-        start += len;                           \
-        if (start < 0)                          \
-            start = 0;                          \
-    }
-
-static Py_ssize_t
-any_find_slice(int direction, PyObject* s1, PyObject* s2,
-               Py_ssize_t start,
-               Py_ssize_t end)
-{
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2, result;
-
-    kind1 = PyUnicode_KIND(s1);
-    kind2 = PyUnicode_KIND(s2);
-    if (kind1 < kind2)
-        return -1;
-
-    len1 = PyUnicode_GET_LENGTH(s1);
-    len2 = PyUnicode_GET_LENGTH(s2);
-    ADJUST_INDICES(start, end, len1);
-    if (end - start < len2)
-        return -1;
-
-    buf1 = PyUnicode_DATA(s1);
-    buf2 = PyUnicode_DATA(s2);
-    if (len2 == 1) {
-        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
-        result = findchar((const char *)buf1 + kind1*start,
-                          kind1, end - start, ch, direction);
-        if (result == -1)
-            return -1;
-        else
-            return start + result;
-    }
-
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(s2, kind1);
-        if (!buf2)
-            return -2;
-    }
-
-    if (direction > 0) {
-        switch (kind1) {
-        case PyUnicode_1BYTE_KIND:
-            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
-                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
-            else
-                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
-            break;
-        case PyUnicode_2BYTE_KIND:
-            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
-            break;
-        case PyUnicode_4BYTE_KIND:
-            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
-            break;
-        default:
-            assert(0); result = -2;
-        }
-    }
-    else {
-        switch (kind1) {
-        case PyUnicode_1BYTE_KIND:
-            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
-                result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
-            else
-                result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
-            break;
-        case PyUnicode_2BYTE_KIND:
-            result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
-            break;
-        case PyUnicode_4BYTE_KIND:
-            result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
-            break;
-        default:
-            assert(0); result = -2;
-        }
-    }
-
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-
-    return result;
-}
-
-Py_ssize_t
-_PyUnicode_InsertThousandsGrouping(
-    PyObject *unicode, Py_ssize_t index,
-    Py_ssize_t n_buffer,
-    void *digits, Py_ssize_t n_digits,
-    Py_ssize_t min_width,
-    const char *grouping, PyObject *thousands_sep,
-    Py_UCS4 *maxchar)
-{
-    unsigned int kind, thousands_sep_kind;
-    char *data, *thousands_sep_data;
-    Py_ssize_t thousands_sep_len;
-    Py_ssize_t len;
-
-    if (unicode != NULL) {
-        kind = PyUnicode_KIND(unicode);
-        data = (char *) PyUnicode_DATA(unicode) + index * kind;
-    }
-    else {
-        kind = PyUnicode_1BYTE_KIND;
-        data = NULL;
-    }
-    thousands_sep_kind = PyUnicode_KIND(thousands_sep);
-    thousands_sep_data = PyUnicode_DATA(thousands_sep);
-    thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
-    if (unicode != NULL && thousands_sep_kind != kind) {
-        if (thousands_sep_kind < kind) {
-            thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
-            if (!thousands_sep_data)
-                return -1;
-        }
-        else {
-            data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
-            if (!data)
-                return -1;
-        }
-    }
-
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
-            len = asciilib_InsertThousandsGrouping(
-                (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
-                min_width, grouping,
-                (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
-        else
-            len = ucs1lib_InsertThousandsGrouping(
-                (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
-                min_width, grouping,
-                (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        len = ucs2lib_InsertThousandsGrouping(
-            (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
-            min_width, grouping,
-            (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        len = ucs4lib_InsertThousandsGrouping(
-            (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
-            min_width, grouping,
-            (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
-        break;
-    default:
-        assert(0);
-        return -1;
-    }
-    if (unicode != NULL && thousands_sep_kind != kind) {
-        if (thousands_sep_kind < kind)
-            PyMem_Free(thousands_sep_data);
-        else
-            PyMem_Free(data);
-    }
-    if (unicode == NULL) {
-        *maxchar = 127;
-        if (len != n_digits) {
-            *maxchar = Py_MAX(*maxchar,
-                                   PyUnicode_MAX_CHAR_VALUE(thousands_sep));
-        }
-    }
-    return len;
-}
-
-
-Py_ssize_t
-PyUnicode_Count(PyObject *str,
-                PyObject *substr,
-                Py_ssize_t start,
-                Py_ssize_t end)
-{
-    Py_ssize_t result;
-    PyObject* str_obj;
-    PyObject* sub_obj;
-    int kind1, kind2;
-    void *buf1 = NULL, *buf2 = NULL;
-    Py_ssize_t len1, len2;
-
-    str_obj = PyUnicode_FromObject(str);
-    if (!str_obj)
-        return -1;
-    sub_obj = PyUnicode_FromObject(substr);
-    if (!sub_obj) {
-        Py_DECREF(str_obj);
-        return -1;
-    }
-    if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
-        Py_DECREF(sub_obj);
-        Py_DECREF(str_obj);
-        return -1;
-    }
-
-    kind1 = PyUnicode_KIND(str_obj);
-    kind2 = PyUnicode_KIND(sub_obj);
-    if (kind1 < kind2) {
-        Py_DECREF(sub_obj);
-        Py_DECREF(str_obj);
-        return 0;
-    }
-
-    len1 = PyUnicode_GET_LENGTH(str_obj);
-    len2 = PyUnicode_GET_LENGTH(sub_obj);
-    ADJUST_INDICES(start, end, len1);
-    if (end - start < len2) {
-        Py_DECREF(sub_obj);
-        Py_DECREF(str_obj);
-        return 0;
-    }
-
-    buf1 = PyUnicode_DATA(str_obj);
-    buf2 = PyUnicode_DATA(sub_obj);
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(sub_obj, kind1);
-        if (!buf2)
-            goto onError;
-    }
-
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
-            result = asciilib_count(
-                ((Py_UCS1*)buf1) + start, end - start,
-                buf2, len2, PY_SSIZE_T_MAX
-                );
-        else
-            result = ucs1lib_count(
-                ((Py_UCS1*)buf1) + start, end - start,
-                buf2, len2, PY_SSIZE_T_MAX
-                );
-        break;
-    case PyUnicode_2BYTE_KIND:
-        result = ucs2lib_count(
-            ((Py_UCS2*)buf1) + start, end - start,
-            buf2, len2, PY_SSIZE_T_MAX
-            );
-        break;
-    case PyUnicode_4BYTE_KIND:
-        result = ucs4lib_count(
-            ((Py_UCS4*)buf1) + start, end - start,
-            buf2, len2, PY_SSIZE_T_MAX
-            );
-        break;
-    default:
-        assert(0); result = 0;
-    }
-
-    Py_DECREF(sub_obj);
-    Py_DECREF(str_obj);
-
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-
-    return result;
-  onError:
-    Py_DECREF(sub_obj);
-    Py_DECREF(str_obj);
-    if (kind2 != kind1 && buf2)
-        PyMem_Free(buf2);
-    return -1;
-}
-
-Py_ssize_t
-PyUnicode_Find(PyObject *str,
-               PyObject *sub,
-               Py_ssize_t start,
-               Py_ssize_t end,
-               int direction)
-{
-    Py_ssize_t result;
-
-    str = PyUnicode_FromObject(str);
-    if (!str)
-        return -2;
-    sub = PyUnicode_FromObject(sub);
-    if (!sub) {
-        Py_DECREF(str);
-        return -2;
-    }
-    if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
-        Py_DECREF(sub);
-        Py_DECREF(str);
-        return -2;
-    }
-
-    result = any_find_slice(direction,
-        str, sub, start, end
-        );
-
-    Py_DECREF(str);
-    Py_DECREF(sub);
-
-    return result;
-}
-
-Py_ssize_t
-PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
-                   Py_ssize_t start, Py_ssize_t end,
-                   int direction)
-{
-    int kind;
-    Py_ssize_t result;
-    if (PyUnicode_READY(str) == -1)
-        return -2;
-    if (start < 0 || end < 0) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return -2;
-    }
-    if (end > PyUnicode_GET_LENGTH(str))
-        end = PyUnicode_GET_LENGTH(str);
-    if (start >= end)
-        return -1;
-    kind = PyUnicode_KIND(str);
-    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
-                      kind, end-start, ch, direction);
-    if (result == -1)
-        return -1;
-    else
-        return start + result;
-}
-
-static int
-tailmatch(PyObject *self,
-          PyObject *substring,
-          Py_ssize_t start,
-          Py_ssize_t end,
-          int direction)
-{
-    int kind_self;
-    int kind_sub;
-    void *data_self;
-    void *data_sub;
-    Py_ssize_t offset;
-    Py_ssize_t i;
-    Py_ssize_t end_sub;
-
-    if (PyUnicode_READY(self) == -1 ||
-        PyUnicode_READY(substring) == -1)
-        return -1;
-
-    if (PyUnicode_GET_LENGTH(substring) == 0)
-        return 1;
-
-    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
-    end -= PyUnicode_GET_LENGTH(substring);
-    if (end < start)
-        return 0;
-
-    kind_self = PyUnicode_KIND(self);
-    data_self = PyUnicode_DATA(self);
-    kind_sub = PyUnicode_KIND(substring);
-    data_sub = PyUnicode_DATA(substring);
-    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
-
-    if (direction > 0)
-        offset = end;
-    else
-        offset = start;
-
-    if (PyUnicode_READ(kind_self, data_self, offset) ==
-        PyUnicode_READ(kind_sub, data_sub, 0) &&
-        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
-        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
-        /* If both are of the same kind, memcmp is sufficient */
-        if (kind_self == kind_sub) {
-            return ! memcmp((char *)data_self +
-                                (offset * PyUnicode_KIND(substring)),
-                            data_sub,
-                            PyUnicode_GET_LENGTH(substring) *
-                                PyUnicode_KIND(substring));
-        }
-        /* otherwise we have to compare each character by first accesing it */
-        else {
-            /* We do not need to compare 0 and len(substring)-1 because
-               the if statement above ensured already that they are equal
-               when we end up here. */
-            for (i = 1; i < end_sub; ++i) {
-                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
-                    PyUnicode_READ(kind_sub, data_sub, i))
-                    return 0;
-            }
-            return 1;
-        }
-    }
-
-    return 0;
-}
-
-Py_ssize_t
-PyUnicode_Tailmatch(PyObject *str,
-                    PyObject *substr,
-                    Py_ssize_t start,
-                    Py_ssize_t end,
-                    int direction)
-{
-    Py_ssize_t result;
-
-    str = PyUnicode_FromObject(str);
-    if (str == NULL)
-        return -1;
-    substr = PyUnicode_FromObject(substr);
-    if (substr == NULL) {
-        Py_DECREF(str);
-        return -1;
-    }
-
-    result = tailmatch(str, substr,
-                       start, end, direction);
-    Py_DECREF(str);
-    Py_DECREF(substr);
-    return result;
-}
-
-/* Apply fixfct filter to the Unicode object self and return a
-   reference to the modified object */
-
-static PyObject *
-fixup(PyObject *self,
-      Py_UCS4 (*fixfct)(PyObject *s))
-{
-    PyObject *u;
-    Py_UCS4 maxchar_old, maxchar_new = 0;
-    PyObject *v;
-
-    u = _PyUnicode_Copy(self);
-    if (u == NULL)
-        return NULL;
-    maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
-
-    /* fix functions return the new maximum character in a string,
-       if the kind of the resulting unicode object does not change,
-       everything is fine.  Otherwise we need to change the string kind
-       and re-run the fix function. */
-    maxchar_new = fixfct(u);
-
-    if (maxchar_new == 0) {
-        /* no changes */;
-        if (PyUnicode_CheckExact(self)) {
-            Py_DECREF(u);
-            Py_INCREF(self);
-            return self;
-        }
-        else
-            return u;
-    }
-
-    maxchar_new = align_maxchar(maxchar_new);
-
-    if (maxchar_new == maxchar_old)
-        return u;
-
-    /* In case the maximum character changed, we need to
-       convert the string to the new category. */
-    v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
-    if (v == NULL) {
-        Py_DECREF(u);
-        return NULL;
-    }
-    if (maxchar_new > maxchar_old) {
-        /* If the maxchar increased so that the kind changed, not all
-           characters are representable anymore and we need to fix the
-           string again. This only happens in very few cases. */
-        _PyUnicode_FastCopyCharacters(v, 0,
-                                      self, 0, PyUnicode_GET_LENGTH(self));
-        maxchar_old = fixfct(v);
-        assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
-    }
-    else {
-        _PyUnicode_FastCopyCharacters(v, 0,
-                                      u, 0, PyUnicode_GET_LENGTH(self));
-    }
-    Py_DECREF(u);
-    assert(_PyUnicode_CheckConsistency(v, 1));
-    return v;
-}
-
-static PyObject *
-ascii_upper_or_lower(PyObject *self, int lower)
-{
-    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
-    char *resdata, *data = PyUnicode_DATA(self);
-    PyObject *res;
-
-    res = PyUnicode_New(len, 127);
-    if (res == NULL)
-        return NULL;
-    resdata = PyUnicode_DATA(res);
-    if (lower)
-        _Py_bytes_lower(resdata, data, len);
-    else
-        _Py_bytes_upper(resdata, data, len);
-    return res;
-}
-
-static Py_UCS4
-handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
-{
-    Py_ssize_t j;
-    int final_sigma;
-    Py_UCS4 c = 0;   /* initialize to prevent gcc warning */
-    /* U+03A3 is in the Final_Sigma context when, it is found like this:
-
-     \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
-
-    where ! is a negation and \p{xxx} is a character with property xxx.
-    */
-    for (j = i - 1; j >= 0; j--) {
-        c = PyUnicode_READ(kind, data, j);
-        if (!_PyUnicode_IsCaseIgnorable(c))
-            break;
-    }
-    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
-    if (final_sigma) {
-        for (j = i + 1; j < length; j++) {
-            c = PyUnicode_READ(kind, data, j);
-            if (!_PyUnicode_IsCaseIgnorable(c))
-                break;
-        }
-        final_sigma = j == length || !_PyUnicode_IsCased(c);
-    }
-    return (final_sigma) ? 0x3C2 : 0x3C3;
-}
-
-static int
-lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
-           Py_UCS4 c, Py_UCS4 *mapped)
-{
-    /* Obscure special case. */
-    if (c == 0x3A3) {
-        mapped[0] = handle_capital_sigma(kind, data, length, i);
-        return 1;
-    }
-    return _PyUnicode_ToLowerFull(c, mapped);
-}
-
-static Py_ssize_t
-do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
-{
-    Py_ssize_t i, k = 0;
-    int n_res, j;
-    Py_UCS4 c, mapped[3];
-
-    c = PyUnicode_READ(kind, data, 0);
-    n_res = _PyUnicode_ToUpperFull(c, mapped);
-    for (j = 0; j < n_res; j++) {
-        *maxchar = Py_MAX(*maxchar, mapped[j]);
-        res[k++] = mapped[j];
-    }
-    for (i = 1; i < length; i++) {
-        c = PyUnicode_READ(kind, data, i);
-        n_res = lower_ucs4(kind, data, length, i, c, mapped);
-        for (j = 0; j < n_res; j++) {
-            *maxchar = Py_MAX(*maxchar, mapped[j]);
-            res[k++] = mapped[j];
-        }
-    }
-    return k;
-}
-
-static Py_ssize_t
-do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
-    Py_ssize_t i, k = 0;
-
-    for (i = 0; i < length; i++) {
-        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
-        int n_res, j;
-        if (Py_UNICODE_ISUPPER(c)) {
-            n_res = lower_ucs4(kind, data, length, i, c, mapped);
-        }
-        else if (Py_UNICODE_ISLOWER(c)) {
-            n_res = _PyUnicode_ToUpperFull(c, mapped);
-        }
-        else {
-            n_res = 1;
-            mapped[0] = c;
-        }
-        for (j = 0; j < n_res; j++) {
-            *maxchar = Py_MAX(*maxchar, mapped[j]);
-            res[k++] = mapped[j];
-        }
-    }
-    return k;
-}
-
-static Py_ssize_t
-do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
-                  Py_UCS4 *maxchar, int lower)
-{
-    Py_ssize_t i, k = 0;
-
-    for (i = 0; i < length; i++) {
-        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
-        int n_res, j;
-        if (lower)
-            n_res = lower_ucs4(kind, data, length, i, c, mapped);
-        else
-            n_res = _PyUnicode_ToUpperFull(c, mapped);
-        for (j = 0; j < n_res; j++) {
-            *maxchar = Py_MAX(*maxchar, mapped[j]);
-            res[k++] = mapped[j];
-        }
-    }
-    return k;
-}
-
-static Py_ssize_t
-do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
-{
-    return do_upper_or_lower(kind, data, length, res, maxchar, 0);
-}
-
-static Py_ssize_t
-do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
-{
-    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
-}
-
-static Py_ssize_t
-do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
-{
-    Py_ssize_t i, k = 0;
-
-    for (i = 0; i < length; i++) {
-        Py_UCS4 c = PyUnicode_READ(kind, data, i);
-        Py_UCS4 mapped[3];
-        int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
-        for (j = 0; j < n_res; j++) {
-            *maxchar = Py_MAX(*maxchar, mapped[j]);
-            res[k++] = mapped[j];
-        }
-    }
-    return k;
-}
-
-static Py_ssize_t
-do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
-{
-    Py_ssize_t i, k = 0;
-    int previous_is_cased;
-
-    previous_is_cased = 0;
-    for (i = 0; i < length; i++) {
-        const Py_UCS4 c = PyUnicode_READ(kind, data, i);
-        Py_UCS4 mapped[3];
-        int n_res, j;
-
-        if (previous_is_cased)
-            n_res = lower_ucs4(kind, data, length, i, c, mapped);
-        else
-            n_res = _PyUnicode_ToTitleFull(c, mapped);
-
-        for (j = 0; j < n_res; j++) {
-            *maxchar = Py_MAX(*maxchar, mapped[j]);
-            res[k++] = mapped[j];
-        }
-
-        previous_is_cased = _PyUnicode_IsCased(c);
-    }
-    return k;
-}
-
-static PyObject *
-case_operation(PyObject *self,
-               Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
-{
-    PyObject *res = NULL;
-    Py_ssize_t length, newlength = 0;
-    int kind, outkind;
-    void *data, *outdata;
-    Py_UCS4 maxchar = 0, *tmp, *tmpend;
-
-    assert(PyUnicode_IS_READY(self));
-
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-    length = PyUnicode_GET_LENGTH(self);
-    if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
-        PyErr_SetString(PyExc_OverflowError, "string is too long");
-        return NULL;
-    }
-    tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
-    if (tmp == NULL)
-        return PyErr_NoMemory();
-    newlength = perform(kind, data, length, tmp, &maxchar);
-    res = PyUnicode_New(newlength, maxchar);
-    if (res == NULL)
-        goto leave;
-    tmpend = tmp + newlength;
-    outdata = PyUnicode_DATA(res);
-    outkind = PyUnicode_KIND(res);
-    switch (outkind) {
-    case PyUnicode_1BYTE_KIND:
-        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
-        break;
-    default:
-        assert(0);
-        break;
-    }
-  leave:
-    PyMem_FREE(tmp);
-    return res;
-}
-
-PyObject *
-PyUnicode_Join(PyObject *separator, PyObject *seq)
-{
-    PyObject *sep = NULL;
-    Py_ssize_t seplen;
-    PyObject *res = NULL; /* the result */
-    PyObject *fseq;          /* PySequence_Fast(seq) */
-    Py_ssize_t seqlen;       /* len(fseq) -- number of items in sequence */
-    PyObject **items;
-    PyObject *item;
-    Py_ssize_t sz, i, res_offset;
-    Py_UCS4 maxchar;
-    Py_UCS4 item_maxchar;
-    int use_memcpy;
-    unsigned char *res_data = NULL, *sep_data = NULL;
-    PyObject *last_obj;
-    unsigned int kind = 0;
-
-    fseq = PySequence_Fast(seq, "can only join an iterable");
-    if (fseq == NULL) {
-        return NULL;
-    }
-
-    /* NOTE: the following code can't call back into Python code,
-     * so we are sure that fseq won't be mutated.
-     */
-
-    seqlen = PySequence_Fast_GET_SIZE(fseq);
-    /* If empty sequence, return u"". */
-    if (seqlen == 0) {
-        Py_DECREF(fseq);
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-
-    /* If singleton sequence with an exact Unicode, return that. */
-    last_obj = NULL;
-    items = PySequence_Fast_ITEMS(fseq);
-    if (seqlen == 1) {
-        if (PyUnicode_CheckExact(items[0])) {
-            res = items[0];
-            Py_INCREF(res);
-            Py_DECREF(fseq);
-            return res;
-        }
-        seplen = 0;
-        maxchar = 0;
-    }
-    else {
-        /* Set up sep and seplen */
-        if (separator == NULL) {
-            /* fall back to a blank space separator */
-            sep = PyUnicode_FromOrdinal(' ');
-            if (!sep)
-                goto onError;
-            seplen = 1;
-            maxchar = 32;
-        }
-        else {
-            if (!PyUnicode_Check(separator)) {
-                PyErr_Format(PyExc_TypeError,
-                             "separator: expected str instance,"
-                             " %.80s found",
-                             Py_TYPE(separator)->tp_name);
-                goto onError;
-            }
-            if (PyUnicode_READY(separator))
-                goto onError;
-            sep = separator;
-            seplen = PyUnicode_GET_LENGTH(separator);
-            maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
-            /* inc refcount to keep this code path symmetric with the
-               above case of a blank separator */
-            Py_INCREF(sep);
-        }
-        last_obj = sep;
-    }
-
-    /* There are at least two things to join, or else we have a subclass
-     * of str in the sequence.
-     * Do a pre-pass to figure out the total amount of space we'll
-     * need (sz), and see whether all argument are strings.
-     */
-    sz = 0;
-#ifdef Py_DEBUG
-    use_memcpy = 0;
-#else
-    use_memcpy = 1;
-#endif
-    for (i = 0; i < seqlen; i++) {
-        const Py_ssize_t old_sz = sz;
-        item = items[i];
-        if (!PyUnicode_Check(item)) {
-            PyErr_Format(PyExc_TypeError,
-                         "sequence item %zd: expected str instance,"
-                         " %.80s found",
-                         i, Py_TYPE(item)->tp_name);
-            goto onError;
-        }
-        if (PyUnicode_READY(item) == -1)
-            goto onError;
-        sz += PyUnicode_GET_LENGTH(item);
-        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
-        maxchar = Py_MAX(maxchar, item_maxchar);
-        if (i != 0)
-            sz += seplen;
-        if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "join() result is too long for a Python string");
-            goto onError;
-        }
-        if (use_memcpy && last_obj != NULL) {
-            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
-                use_memcpy = 0;
-        }
-        last_obj = item;
-    }
-
-    res = PyUnicode_New(sz, maxchar);
-    if (res == NULL)
-        goto onError;
-
-    /* Catenate everything. */
-#ifdef Py_DEBUG
-    use_memcpy = 0;
-#else
-    if (use_memcpy) {
-        res_data = PyUnicode_1BYTE_DATA(res);
-        kind = PyUnicode_KIND(res);
-        if (seplen != 0)
-            sep_data = PyUnicode_1BYTE_DATA(sep);
-    }
-#endif
-    if (use_memcpy) {
-        for (i = 0; i < seqlen; ++i) {
-            Py_ssize_t itemlen;
-            item = items[i];
-
-            /* Copy item, and maybe the separator. */
-            if (i && seplen != 0) {
-                Py_MEMCPY(res_data,
-                          sep_data,
-                          kind * seplen);
-                res_data += kind * seplen;
-            }
-
-            itemlen = PyUnicode_GET_LENGTH(item);
-            if (itemlen != 0) {
-                Py_MEMCPY(res_data,
-                          PyUnicode_DATA(item),
-                          kind * itemlen);
-                res_data += kind * itemlen;
-            }
-        }
-        assert(res_data == PyUnicode_1BYTE_DATA(res)
-                           + kind * PyUnicode_GET_LENGTH(res));
-    }
-    else {
-        for (i = 0, res_offset = 0; i < seqlen; ++i) {
-            Py_ssize_t itemlen;
-            item = items[i];
-
-            /* Copy item, and maybe the separator. */
-            if (i && seplen != 0) {
-                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
-                res_offset += seplen;
-            }
-
-            itemlen = PyUnicode_GET_LENGTH(item);
-            if (itemlen != 0) {
-                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
-                res_offset += itemlen;
-            }
-        }
-        assert(res_offset == PyUnicode_GET_LENGTH(res));
-    }
-
-    Py_DECREF(fseq);
-    Py_XDECREF(sep);
-    assert(_PyUnicode_CheckConsistency(res, 1));
-    return res;
-
-  onError:
-    Py_DECREF(fseq);
-    Py_XDECREF(sep);
-    Py_XDECREF(res);
-    return NULL;
-}
-
-#define FILL(kind, data, value, start, length) \
-    do { \
-        Py_ssize_t i_ = 0; \
-        assert(kind != PyUnicode_WCHAR_KIND); \
-        switch ((kind)) { \
-        case PyUnicode_1BYTE_KIND: { \
-            unsigned char * to_ = (unsigned char *)((data)) + (start); \
-            memset(to_, (unsigned char)value, (length)); \
-            break; \
-        } \
-        case PyUnicode_2BYTE_KIND: { \
-            Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
-            for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
-            break; \
-        } \
-        case PyUnicode_4BYTE_KIND: { \
-            Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
-            for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
-            break; \
-        } \
-        default: assert(0); \
-        } \
-    } while (0)
-
-void
-_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
-                    Py_UCS4 fill_char)
-{
-    const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
-    const void *data = PyUnicode_DATA(unicode);
-    assert(PyUnicode_IS_READY(unicode));
-    assert(unicode_modifiable(unicode));
-    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
-    assert(start >= 0);
-    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
-    FILL(kind, data, fill_char, start, length);
-}
-
-Py_ssize_t
-PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
-               Py_UCS4 fill_char)
-{
-    Py_ssize_t maxlen;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadInternalCall();
-        return -1;
-    }
-    if (PyUnicode_READY(unicode) == -1)
-        return -1;
-    if (unicode_check_modifiable(unicode))
-        return -1;
-
-    if (start < 0) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return -1;
-    }
-    if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
-        PyErr_SetString(PyExc_ValueError,
-                         "fill character is bigger than "
-                         "the string maximum character");
-        return -1;
-    }
-
-    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
-    length = Py_MIN(maxlen, length);
-    if (length <= 0)
-        return 0;
-
-    _PyUnicode_FastFill(unicode, start, length, fill_char);
-    return length;
-}
-
-static PyObject *
-pad(PyObject *self,
-    Py_ssize_t left,
-    Py_ssize_t right,
-    Py_UCS4 fill)
-{
-    PyObject *u;
-    Py_UCS4 maxchar;
-    int kind;
-    void *data;
-
-    if (left < 0)
-        left = 0;
-    if (right < 0)
-        right = 0;
-
-    if (left == 0 && right == 0)
-        return unicode_result_unchanged(self);
-
-    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
-        right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
-        PyErr_SetString(PyExc_OverflowError, "padded string is too long");
-        return NULL;
-    }
-    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
-    maxchar = Py_MAX(maxchar, fill);
-    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
-    if (!u)
-        return NULL;
-
-    kind = PyUnicode_KIND(u);
-    data = PyUnicode_DATA(u);
-    if (left)
-        FILL(kind, data, fill, 0, left);
-    if (right)
-        FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
-    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
-    assert(_PyUnicode_CheckConsistency(u, 1));
-    return u;
-}
-
-PyObject *
-PyUnicode_Splitlines(PyObject *string, int keepends)
-{
-    PyObject *list;
-
-    string = PyUnicode_FromObject(string);
-    if (string == NULL)
-        return NULL;
-    if (PyUnicode_READY(string) == -1) {
-        Py_DECREF(string);
-        return NULL;
-    }
-
-    switch (PyUnicode_KIND(string)) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(string))
-            list = asciilib_splitlines(
-                string, PyUnicode_1BYTE_DATA(string),
-                PyUnicode_GET_LENGTH(string), keepends);
-        else
-            list = ucs1lib_splitlines(
-                string, PyUnicode_1BYTE_DATA(string),
-                PyUnicode_GET_LENGTH(string), keepends);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        list = ucs2lib_splitlines(
-            string, PyUnicode_2BYTE_DATA(string),
-            PyUnicode_GET_LENGTH(string), keepends);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        list = ucs4lib_splitlines(
-            string, PyUnicode_4BYTE_DATA(string),
-            PyUnicode_GET_LENGTH(string), keepends);
-        break;
-    default:
-        assert(0);
-        list = 0;
-    }
-    Py_DECREF(string);
-    return list;
-}
-
-static PyObject *
-split(PyObject *self,
-      PyObject *substring,
-      Py_ssize_t maxcount)
-{
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2;
-    PyObject* out;
-
-    if (maxcount < 0)
-        maxcount = PY_SSIZE_T_MAX;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (substring == NULL)
-        switch (PyUnicode_KIND(self)) {
-        case PyUnicode_1BYTE_KIND:
-            if (PyUnicode_IS_ASCII(self))
-                return asciilib_split_whitespace(
-                    self,  PyUnicode_1BYTE_DATA(self),
-                    PyUnicode_GET_LENGTH(self), maxcount
-                    );
-            else
-                return ucs1lib_split_whitespace(
-                    self,  PyUnicode_1BYTE_DATA(self),
-                    PyUnicode_GET_LENGTH(self), maxcount
-                    );
-        case PyUnicode_2BYTE_KIND:
-            return ucs2lib_split_whitespace(
-                self,  PyUnicode_2BYTE_DATA(self),
-                PyUnicode_GET_LENGTH(self), maxcount
-                );
-        case PyUnicode_4BYTE_KIND:
-            return ucs4lib_split_whitespace(
-                self,  PyUnicode_4BYTE_DATA(self),
-                PyUnicode_GET_LENGTH(self), maxcount
-                );
-        default:
-            assert(0);
-            return NULL;
-        }
-
-    if (PyUnicode_READY(substring) == -1)
-        return NULL;
-
-    kind1 = PyUnicode_KIND(self);
-    kind2 = PyUnicode_KIND(substring);
-    len1 = PyUnicode_GET_LENGTH(self);
-    len2 = PyUnicode_GET_LENGTH(substring);
-    if (kind1 < kind2 || len1 < len2) {
-        out = PyList_New(1);
-        if (out == NULL)
-            return NULL;
-        Py_INCREF(self);
-        PyList_SET_ITEM(out, 0, self);
-        return out;
-    }
-    buf1 = PyUnicode_DATA(self);
-    buf2 = PyUnicode_DATA(substring);
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(substring, kind1);
-        if (!buf2)
-            return NULL;
-    }
-
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
-            out = asciilib_split(
-                self,  buf1, len1, buf2, len2, maxcount);
-        else
-            out = ucs1lib_split(
-                self,  buf1, len1, buf2, len2, maxcount);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        out = ucs2lib_split(
-            self,  buf1, len1, buf2, len2, maxcount);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        out = ucs4lib_split(
-            self,  buf1, len1, buf2, len2, maxcount);
-        break;
-    default:
-        out = NULL;
-    }
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-    return out;
-}
-
-static PyObject *
-rsplit(PyObject *self,
-       PyObject *substring,
-       Py_ssize_t maxcount)
-{
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2;
-    PyObject* out;
-
-    if (maxcount < 0)
-        maxcount = PY_SSIZE_T_MAX;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (substring == NULL)
-        switch (PyUnicode_KIND(self)) {
-        case PyUnicode_1BYTE_KIND:
-            if (PyUnicode_IS_ASCII(self))
-                return asciilib_rsplit_whitespace(
-                    self,  PyUnicode_1BYTE_DATA(self),
-                    PyUnicode_GET_LENGTH(self), maxcount
-                    );
-            else
-                return ucs1lib_rsplit_whitespace(
-                    self,  PyUnicode_1BYTE_DATA(self),
-                    PyUnicode_GET_LENGTH(self), maxcount
-                    );
-        case PyUnicode_2BYTE_KIND:
-            return ucs2lib_rsplit_whitespace(
-                self,  PyUnicode_2BYTE_DATA(self),
-                PyUnicode_GET_LENGTH(self), maxcount
-                );
-        case PyUnicode_4BYTE_KIND:
-            return ucs4lib_rsplit_whitespace(
-                self,  PyUnicode_4BYTE_DATA(self),
-                PyUnicode_GET_LENGTH(self), maxcount
-                );
-        default:
-            assert(0);
-            return NULL;
-        }
-
-    if (PyUnicode_READY(substring) == -1)
-        return NULL;
-
-    kind1 = PyUnicode_KIND(self);
-    kind2 = PyUnicode_KIND(substring);
-    len1 = PyUnicode_GET_LENGTH(self);
-    len2 = PyUnicode_GET_LENGTH(substring);
-    if (kind1 < kind2 || len1 < len2) {
-        out = PyList_New(1);
-        if (out == NULL)
-            return NULL;
-        Py_INCREF(self);
-        PyList_SET_ITEM(out, 0, self);
-        return out;
-    }
-    buf1 = PyUnicode_DATA(self);
-    buf2 = PyUnicode_DATA(substring);
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(substring, kind1);
-        if (!buf2)
-            return NULL;
-    }
-
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
-            out = asciilib_rsplit(
-                self,  buf1, len1, buf2, len2, maxcount);
-        else
-            out = ucs1lib_rsplit(
-                self,  buf1, len1, buf2, len2, maxcount);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        out = ucs2lib_rsplit(
-            self,  buf1, len1, buf2, len2, maxcount);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        out = ucs4lib_rsplit(
-            self,  buf1, len1, buf2, len2, maxcount);
-        break;
-    default:
-        out = NULL;
-    }
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-    return out;
-}
-
-static Py_ssize_t
-anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
-            PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
-{
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
-            return asciilib_find(buf1, len1, buf2, len2, offset);
-        else
-            return ucs1lib_find(buf1, len1, buf2, len2, offset);
-    case PyUnicode_2BYTE_KIND:
-        return ucs2lib_find(buf1, len1, buf2, len2, offset);
-    case PyUnicode_4BYTE_KIND:
-        return ucs4lib_find(buf1, len1, buf2, len2, offset);
-    }
-    assert(0);
-    return -1;
-}
-
-static Py_ssize_t
-anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
-             PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
-{
-    switch (kind) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
-            return asciilib_count(sbuf, slen, buf1, len1, maxcount);
-        else
-            return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
-    case PyUnicode_2BYTE_KIND:
-        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
-    case PyUnicode_4BYTE_KIND:
-        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
-    }
-    assert(0);
-    return 0;
-}
-
-static void
-replace_1char_inplace(PyObject *u, Py_ssize_t pos,
-                      Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
-{
-    int kind = PyUnicode_KIND(u);
-    void *data = PyUnicode_DATA(u);
-    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
-    if (kind == PyUnicode_1BYTE_KIND) {
-        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
-                                      (Py_UCS1 *)data + len,
-                                      u1, u2, maxcount);
-    }
-    else if (kind == PyUnicode_2BYTE_KIND) {
-        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
-                                      (Py_UCS2 *)data + len,
-                                      u1, u2, maxcount);
-    }
-    else {
-        assert(kind == PyUnicode_4BYTE_KIND);
-        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
-                                      (Py_UCS4 *)data + len,
-                                      u1, u2, maxcount);
-    }
-}
-
-static PyObject *
-replace(PyObject *self, PyObject *str1,
-        PyObject *str2, Py_ssize_t maxcount)
-{
-    PyObject *u;
-    char *sbuf = PyUnicode_DATA(self);
-    char *buf1 = PyUnicode_DATA(str1);
-    char *buf2 = PyUnicode_DATA(str2);
-    int srelease = 0, release1 = 0, release2 = 0;
-    int skind = PyUnicode_KIND(self);
-    int kind1 = PyUnicode_KIND(str1);
-    int kind2 = PyUnicode_KIND(str2);
-    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
-    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
-    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
-    int mayshrink;
-    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
-
-    if (maxcount < 0)
-        maxcount = PY_SSIZE_T_MAX;
-    else if (maxcount == 0 || slen == 0)
-        goto nothing;
-
-    if (str1 == str2)
-        goto nothing;
-
-    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
-    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
-    if (maxchar < maxchar_str1)
-        /* substring too wide to be present */
-        goto nothing;
-    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
-    /* Replacing str1 with str2 may cause a maxchar reduction in the
-       result string. */
-    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
-    maxchar = Py_MAX(maxchar, maxchar_str2);
-
-    if (len1 == len2) {
-        /* same length */
-        if (len1 == 0)
-            goto nothing;
-        if (len1 == 1) {
-            /* replace characters */
-            Py_UCS4 u1, u2;
-            Py_ssize_t pos;
-
-            u1 = PyUnicode_READ(kind1, buf1, 0);
-            pos = findchar(sbuf, skind, slen, u1, 1);
-            if (pos < 0)
-                goto nothing;
-            u2 = PyUnicode_READ(kind2, buf2, 0);
-            u = PyUnicode_New(slen, maxchar);
-            if (!u)
-                goto error;
-
-            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
-            replace_1char_inplace(u, pos, u1, u2, maxcount);
-        }
-        else {
-            int rkind = skind;
-            char *res;
-            Py_ssize_t i;
-
-            if (kind1 < rkind) {
-                /* widen substring */
-                buf1 = _PyUnicode_AsKind(str1, rkind);
-                if (!buf1) goto error;
-                release1 = 1;
-            }
-            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
-            if (i < 0)
-                goto nothing;
-            if (rkind > kind2) {
-                /* widen replacement */
-                buf2 = _PyUnicode_AsKind(str2, rkind);
-                if (!buf2) goto error;
-                release2 = 1;
-            }
-            else if (rkind < kind2) {
-                /* widen self and buf1 */
-                rkind = kind2;
-                if (release1) PyMem_Free(buf1);
-                release1 = 0;
-                sbuf = _PyUnicode_AsKind(self, rkind);
-                if (!sbuf) goto error;
-                srelease = 1;
-                buf1 = _PyUnicode_AsKind(str1, rkind);
-                if (!buf1) goto error;
-                release1 = 1;
-            }
-            u = PyUnicode_New(slen, maxchar);
-            if (!u)
-                goto error;
-            assert(PyUnicode_KIND(u) == rkind);
-            res = PyUnicode_DATA(u);
-
-            memcpy(res, sbuf, rkind * slen);
-            /* change everything in-place, starting with this one */
-            memcpy(res + rkind * i,
-                   buf2,
-                   rkind * len2);
-            i += len1;
-
-            while ( --maxcount > 0) {
-                i = anylib_find(rkind, self,
-                                sbuf+rkind*i, slen-i,
-                                str1, buf1, len1, i);
-                if (i == -1)
-                    break;
-                memcpy(res + rkind * i,
-                       buf2,
-                       rkind * len2);
-                i += len1;
-            }
-        }
-    }
-    else {
-        Py_ssize_t n, i, j, ires;
-        Py_ssize_t new_size;
-        int rkind = skind;
-        char *res;
-
-        if (kind1 < rkind) {
-            /* widen substring */
-            buf1 = _PyUnicode_AsKind(str1, rkind);
-            if (!buf1) goto error;
-            release1 = 1;
-        }
-        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
-        if (n == 0)
-            goto nothing;
-        if (kind2 < rkind) {
-            /* widen replacement */
-            buf2 = _PyUnicode_AsKind(str2, rkind);
-            if (!buf2) goto error;
-            release2 = 1;
-        }
-        else if (kind2 > rkind) {
-            /* widen self and buf1 */
-            rkind = kind2;
-            sbuf = _PyUnicode_AsKind(self, rkind);
-            if (!sbuf) goto error;
-            srelease = 1;
-            if (release1) PyMem_Free(buf1);
-            release1 = 0;
-            buf1 = _PyUnicode_AsKind(str1, rkind);
-            if (!buf1) goto error;
-            release1 = 1;
-        }
-        /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
-           PyUnicode_GET_LENGTH(str1))); */
-        if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
-                PyErr_SetString(PyExc_OverflowError,
-                                "replace string is too long");
-                goto error;
-        }
-        new_size = slen + n * (len2 - len1);
-        if (new_size == 0) {
-            _Py_INCREF_UNICODE_EMPTY();
-            if (!unicode_empty)
-                goto error;
-            u = unicode_empty;
-            goto done;
-        }
-        if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "replace string is too long");
-            goto error;
-        }
-        u = PyUnicode_New(new_size, maxchar);
-        if (!u)
-            goto error;
-        assert(PyUnicode_KIND(u) == rkind);
-        res = PyUnicode_DATA(u);
-        ires = i = 0;
-        if (len1 > 0) {
-            while (n-- > 0) {
-                /* look for next match */
-                j = anylib_find(rkind, self,
-                                sbuf + rkind * i, slen-i,
-                                str1, buf1, len1, i);
-                if (j == -1)
-                    break;
-                else if (j > i) {
-                    /* copy unchanged part [i:j] */
-                    memcpy(res + rkind * ires,
-                           sbuf + rkind * i,
-                           rkind * (j-i));
-                    ires += j - i;
-                }
-                /* copy substitution string */
-                if (len2 > 0) {
-                    memcpy(res + rkind * ires,
-                           buf2,
-                           rkind * len2);
-                    ires += len2;
-                }
-                i = j + len1;
-            }
-            if (i < slen)
-                /* copy tail [i:] */
-                memcpy(res + rkind * ires,
-                       sbuf + rkind * i,
-                       rkind * (slen-i));
-        }
-        else {
-            /* interleave */
-            while (n > 0) {
-                memcpy(res + rkind * ires,
-                       buf2,
-                       rkind * len2);
-                ires += len2;
-                if (--n <= 0)
-                    break;
-                memcpy(res + rkind * ires,
-                       sbuf + rkind * i,
-                       rkind);
-                ires++;
-                i++;
-            }
-            memcpy(res + rkind * ires,
-                   sbuf + rkind * i,
-                   rkind * (slen-i));
-        }
-    }
-
-    if (mayshrink) {
-        unicode_adjust_maxchar(&u);
-        if (u == NULL)
-            goto error;
-    }
-
-  done:
-    if (srelease)
-        PyMem_FREE(sbuf);
-    if (release1)
-        PyMem_FREE(buf1);
-    if (release2)
-        PyMem_FREE(buf2);
-    assert(_PyUnicode_CheckConsistency(u, 1));
-    return u;
-
-  nothing:
-    /* nothing to replace; return original string (when possible) */
-    if (srelease)
-        PyMem_FREE(sbuf);
-    if (release1)
-        PyMem_FREE(buf1);
-    if (release2)
-        PyMem_FREE(buf2);
-    return unicode_result_unchanged(self);
-
-  error:
-    if (srelease && sbuf)
-        PyMem_FREE(sbuf);
-    if (release1 && buf1)
-        PyMem_FREE(buf1);
-    if (release2 && buf2)
-        PyMem_FREE(buf2);
-    return NULL;
-}
-
-/* --- Unicode Object Methods --------------------------------------------- */
-
-PyDoc_STRVAR(title__doc__,
-             "S.title() -> str\n\
-\n\
-Return a titlecased version of S, i.e. words start with title case\n\
-characters, all remaining cased characters have lower case.");
-
-static PyObject*
-unicode_title(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    return case_operation(self, do_title);
-}
-
-PyDoc_STRVAR(capitalize__doc__,
-             "S.capitalize() -> str\n\
-\n\
-Return a capitalized version of S, i.e. make the first character\n\
-have upper case and the rest lower case.");
-
-static PyObject*
-unicode_capitalize(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    if (PyUnicode_GET_LENGTH(self) == 0)
-        return unicode_result_unchanged(self);
-    return case_operation(self, do_capitalize);
-}
-
-PyDoc_STRVAR(casefold__doc__,
-             "S.casefold() -> str\n\
-\n\
-Return a version of S suitable for caseless comparisons.");
-
-static PyObject *
-unicode_casefold(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    if (PyUnicode_IS_ASCII(self))
-        return ascii_upper_or_lower(self, 1);
-    return case_operation(self, do_casefold);
-}
-
-
-/* Argument converter.  Coerces to a single unicode character */
-
-static int
-convert_uc(PyObject *obj, void *addr)
-{
-    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
-    PyObject *uniobj;
-
-    uniobj = PyUnicode_FromObject(obj);
-    if (uniobj == NULL) {
-        PyErr_SetString(PyExc_TypeError,
-                        "The fill character cannot be converted to Unicode");
-        return 0;
-    }
-    if (PyUnicode_GET_LENGTH(uniobj) != 1) {
-        PyErr_SetString(PyExc_TypeError,
-                        "The fill character must be exactly one character long");
-        Py_DECREF(uniobj);
-        return 0;
-    }
-    *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
-    Py_DECREF(uniobj);
-    return 1;
-}
-
-PyDoc_STRVAR(center__doc__,
-             "S.center(width[, fillchar]) -> str\n\
-\n\
-Return S centered in a string of length width. Padding is\n\
-done using the specified fill character (default is a space)");
-
-static PyObject *
-unicode_center(PyObject *self, PyObject *args)
-{
-    Py_ssize_t marg, left;
-    Py_ssize_t width;
-    Py_UCS4 fillchar = ' ';
-
-    if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (PyUnicode_GET_LENGTH(self) >= width)
-        return unicode_result_unchanged(self);
-
-    marg = width - PyUnicode_GET_LENGTH(self);
-    left = marg / 2 + (marg & width & 1);
-
-    return pad(self, left, marg - left, fillchar);
-}
-
-/* This function assumes that str1 and str2 are readied by the caller. */
-
-static int
-unicode_compare(PyObject *str1, PyObject *str2)
-{
-#define COMPARE(TYPE1, TYPE2) \
-    do { \
-        TYPE1* p1 = (TYPE1 *)data1; \
-        TYPE2* p2 = (TYPE2 *)data2; \
-        TYPE1* end = p1 + len; \
-        Py_UCS4 c1, c2; \
-        for (; p1 != end; p1++, p2++) { \
-            c1 = *p1; \
-            c2 = *p2; \
-            if (c1 != c2) \
-                return (c1 < c2) ? -1 : 1; \
-        } \
-    } \
-    while (0)
-
-    int kind1, kind2;
-    void *data1, *data2;
-    Py_ssize_t len1, len2, len;
-
-    kind1 = PyUnicode_KIND(str1);
-    kind2 = PyUnicode_KIND(str2);
-    data1 = PyUnicode_DATA(str1);
-    data2 = PyUnicode_DATA(str2);
-    len1 = PyUnicode_GET_LENGTH(str1);
-    len2 = PyUnicode_GET_LENGTH(str2);
-    len = Py_MIN(len1, len2);
-
-    switch(kind1) {
-    case PyUnicode_1BYTE_KIND:
-    {
-        switch(kind2) {
-        case PyUnicode_1BYTE_KIND:
-        {
-            int cmp = memcmp(data1, data2, len);
-            /* normalize result of memcmp() into the range [-1; 1] */
-            if (cmp < 0)
-                return -1;
-            if (cmp > 0)
-                return 1;
-            break;
-        }
-        case PyUnicode_2BYTE_KIND:
-            COMPARE(Py_UCS1, Py_UCS2);
-            break;
-        case PyUnicode_4BYTE_KIND:
-            COMPARE(Py_UCS1, Py_UCS4);
-            break;
-        default:
-            assert(0);
-        }
-        break;
-    }
-    case PyUnicode_2BYTE_KIND:
-    {
-        switch(kind2) {
-        case PyUnicode_1BYTE_KIND:
-            COMPARE(Py_UCS2, Py_UCS1);
-            break;
-        case PyUnicode_2BYTE_KIND:
-        {
-            COMPARE(Py_UCS2, Py_UCS2);
-            break;
-        }
-        case PyUnicode_4BYTE_KIND:
-            COMPARE(Py_UCS2, Py_UCS4);
-            break;
-        default:
-            assert(0);
-        }
-        break;
-    }
-    case PyUnicode_4BYTE_KIND:
-    {
-        switch(kind2) {
-        case PyUnicode_1BYTE_KIND:
-            COMPARE(Py_UCS4, Py_UCS1);
-            break;
-        case PyUnicode_2BYTE_KIND:
-            COMPARE(Py_UCS4, Py_UCS2);
-            break;
-        case PyUnicode_4BYTE_KIND:
-        {
-#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
-            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
-            /* normalize result of wmemcmp() into the range [-1; 1] */
-            if (cmp < 0)
-                return -1;
-            if (cmp > 0)
-                return 1;
-#else
-            COMPARE(Py_UCS4, Py_UCS4);
-#endif
-            break;
-        }
-        default:
-            assert(0);
-        }
-        break;
-    }
-    default:
-        assert(0);
-    }
-
-    if (len1 == len2)
-        return 0;
-    if (len1 < len2)
-        return -1;
-    else
-        return 1;
-
-#undef COMPARE
-}
-
-Py_LOCAL(int)
-unicode_compare_eq(PyObject *str1, PyObject *str2)
-{
-    int kind;
-    void *data1, *data2;
-    Py_ssize_t len;
-    int cmp;
-
-    len = PyUnicode_GET_LENGTH(str1);
-    if (PyUnicode_GET_LENGTH(str2) != len)
-        return 0;
-    kind = PyUnicode_KIND(str1);
-    if (PyUnicode_KIND(str2) != kind)
-        return 0;
-    data1 = PyUnicode_DATA(str1);
-    data2 = PyUnicode_DATA(str2);
-
-    cmp = memcmp(data1, data2, len * kind);
-    return (cmp == 0);
-}
-
-
-int
-PyUnicode_Compare(PyObject *left, PyObject *right)
-{
-    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
-        if (PyUnicode_READY(left) == -1 ||
-            PyUnicode_READY(right) == -1)
-            return -1;
-
-        /* a string is equal to itself */
-        if (left == right)
-            return 0;
-
-        return unicode_compare(left, right);
-    }
-    PyErr_Format(PyExc_TypeError,
-                 "Can't compare %.100s and %.100s",
-                 left->ob_type->tp_name,
-                 right->ob_type->tp_name);
-    return -1;
-}
-
-int
-_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
-{
-    PyObject *right_str = _PyUnicode_FromId(right);   /* borrowed */
-    if (right_str == NULL)
-        return -1;
-    return PyUnicode_Compare(left, right_str);
-}
-
-int
-PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
-{
-    Py_ssize_t i;
-    int kind;
-    Py_UCS4 chr;
-
-    assert(_PyUnicode_CHECK(uni));
-    if (PyUnicode_READY(uni) == -1)
-        return -1;
-    kind = PyUnicode_KIND(uni);
-    if (kind == PyUnicode_1BYTE_KIND) {
-        const void *data = PyUnicode_1BYTE_DATA(uni);
-        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
-        size_t len, len2 = strlen(str);
-        int cmp;
-
-        len = Py_MIN(len1, len2);
-        cmp = memcmp(data, str, len);
-        if (cmp != 0) {
-            if (cmp < 0)
-                return -1;
-            else
-                return 1;
-        }
-        if (len1 > len2)
-            return 1; /* uni is longer */
-        if (len1 < len2)
-            return -1; /* str is longer */
-        return 0;
-    }
-    else {
-        void *data = PyUnicode_DATA(uni);
-        /* Compare Unicode string and source character set string */
-        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
-            if (chr != (unsigned char)str[i])
-                return (chr < (unsigned char)(str[i])) ? -1 : 1;
-        /* This check keeps Python strings that end in '\0' from comparing equal
-         to C strings identical up to that point. */
-        if (PyUnicode_GET_LENGTH(uni) != i || chr)
-            return 1; /* uni is longer */
-        if (str[i])
-            return -1; /* str is longer */
-        return 0;
-    }
-}
-
-
-#define TEST_COND(cond)                         \
-    ((cond) ? Py_True : Py_False)
-
-PyObject *
-PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
-{
-    int result;
-    PyObject *v;
-
-    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
-        Py_RETURN_NOTIMPLEMENTED;
-
-    if (PyUnicode_READY(left) == -1 ||
-        PyUnicode_READY(right) == -1)
-        return NULL;
-
-    if (left == right) {
-        switch (op) {
-        case Py_EQ:
-        case Py_LE:
-        case Py_GE:
-            /* a string is equal to itself */
-            v = Py_True;
-            break;
-        case Py_NE:
-        case Py_LT:
-        case Py_GT:
-            v = Py_False;
-            break;
-        default:
-            PyErr_BadArgument();
-            return NULL;
-        }
-    }
-    else if (op == Py_EQ || op == Py_NE) {
-        result = unicode_compare_eq(left, right);
-        result ^= (op == Py_NE);
-        v = TEST_COND(result);
-    }
-    else {
-        result = unicode_compare(left, right);
-
-        /* Convert the return value to a Boolean */
-        switch (op) {
-        case Py_LE:
-            v = TEST_COND(result <= 0);
-            break;
-        case Py_GE:
-            v = TEST_COND(result >= 0);
-            break;
-        case Py_LT:
-            v = TEST_COND(result == -1);
-            break;
-        case Py_GT:
-            v = TEST_COND(result == 1);
-            break;
-        default:
-            PyErr_BadArgument();
-            return NULL;
-        }
-    }
-    Py_INCREF(v);
-    return v;
-}
-
-int
-PyUnicode_Contains(PyObject *container, PyObject *element)
-{
-    PyObject *str, *sub;
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2;
-    int result;
-
-    /* Coerce the two arguments */
-    sub = PyUnicode_FromObject(element);
-    if (!sub) {
-        PyErr_Format(PyExc_TypeError,
-                     "'in <string>' requires string as left operand, not %s",
-                     element->ob_type->tp_name);
-        return -1;
-    }
-
-    str = PyUnicode_FromObject(container);
-    if (!str) {
-        Py_DECREF(sub);
-        return -1;
-    }
-
-    kind1 = PyUnicode_KIND(str);
-    kind2 = PyUnicode_KIND(sub);
-    if (kind1 < kind2) {
-        Py_DECREF(sub);
-        Py_DECREF(str);
-        return 0;
-    }
-    len1 = PyUnicode_GET_LENGTH(str);
-    len2 = PyUnicode_GET_LENGTH(sub);
-    if (len1 < len2) {
-        Py_DECREF(sub);
-        Py_DECREF(str);
-        return 0;
-    }
-    buf1 = PyUnicode_DATA(str);
-    buf2 = PyUnicode_DATA(sub);
-    if (len2 == 1) {
-        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
-        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
-        Py_DECREF(sub);
-        Py_DECREF(str);
-        return result;
-    }
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(sub, kind1);
-        if (!buf2) {
-            Py_DECREF(sub);
-            Py_DECREF(str);
-            return -1;
-        }
-    }
-
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
-        break;
-    case PyUnicode_2BYTE_KIND:
-        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
-        break;
-    case PyUnicode_4BYTE_KIND:
-        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
-        break;
-    default:
-        result = -1;
-        assert(0);
-    }
-
-    Py_DECREF(str);
-    Py_DECREF(sub);
-
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-
-    return result;
-}
-
-/* Concat to string or Unicode object giving a new Unicode object. */
-
-PyObject *
-PyUnicode_Concat(PyObject *left, PyObject *right)
-{
-    PyObject *u = NULL, *v = NULL, *w;
-    Py_UCS4 maxchar, maxchar2;
-    Py_ssize_t u_len, v_len, new_len;
-
-    /* Coerce the two arguments */
-    u = PyUnicode_FromObject(left);
-    if (u == NULL)
-        goto onError;
-    v = PyUnicode_FromObject(right);
-    if (v == NULL)
-        goto onError;
-
-    /* Shortcuts */
-    if (v == unicode_empty) {
-        Py_DECREF(v);
-        return u;
-    }
-    if (u == unicode_empty) {
-        Py_DECREF(u);
-        return v;
-    }
-
-    u_len = PyUnicode_GET_LENGTH(u);
-    v_len = PyUnicode_GET_LENGTH(v);
-    if (u_len > PY_SSIZE_T_MAX - v_len) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "strings are too large to concat");
-        goto onError;
-    }
-    new_len = u_len + v_len;
-
-    maxchar = PyUnicode_MAX_CHAR_VALUE(u);
-    maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
-    maxchar = Py_MAX(maxchar, maxchar2);
-
-    /* Concat the two Unicode strings */
-    w = PyUnicode_New(new_len, maxchar);
-    if (w == NULL)
-        goto onError;
-    _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
-    _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
-    Py_DECREF(u);
-    Py_DECREF(v);
-    assert(_PyUnicode_CheckConsistency(w, 1));
-    return w;
-
-  onError:
-    Py_XDECREF(u);
-    Py_XDECREF(v);
-    return NULL;
-}
-
-void
-PyUnicode_Append(PyObject **p_left, PyObject *right)
-{
-    PyObject *left, *res;
-    Py_UCS4 maxchar, maxchar2;
-    Py_ssize_t left_len, right_len, new_len;
-
-    if (p_left == NULL) {
-        if (!PyErr_Occurred())
-            PyErr_BadInternalCall();
-        return;
-    }
-    left = *p_left;
-    if (right == NULL || left == NULL
-        || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
-        if (!PyErr_Occurred())
-            PyErr_BadInternalCall();
-        goto error;
-    }
-
-    if (PyUnicode_READY(left) == -1)
-        goto error;
-    if (PyUnicode_READY(right) == -1)
-        goto error;
-
-    /* Shortcuts */
-    if (left == unicode_empty) {
-        Py_DECREF(left);
-        Py_INCREF(right);
-        *p_left = right;
-        return;
-    }
-    if (right == unicode_empty)
-        return;
-
-    left_len = PyUnicode_GET_LENGTH(left);
-    right_len = PyUnicode_GET_LENGTH(right);
-    if (left_len > PY_SSIZE_T_MAX - right_len) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "strings are too large to concat");
-        goto error;
-    }
-    new_len = left_len + right_len;
-
-    if (unicode_modifiable(left)
-        && PyUnicode_CheckExact(right)
-        && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
-        /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
-           to change the structure size, but characters are stored just after
-           the structure, and so it requires to move all characters which is
-           not so different than duplicating the string. */
-        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
-    {
-        /* append inplace */
-        if (unicode_resize(p_left, new_len) != 0)
-            goto error;
-
-        /* copy 'right' into the newly allocated area of 'left' */
-        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
-    }
-    else {
-        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
-        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
-        maxchar = Py_MAX(maxchar, maxchar2);
-
-        /* Concat the two Unicode strings */
-        res = PyUnicode_New(new_len, maxchar);
-        if (res == NULL)
-            goto error;
-        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
-        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
-        Py_DECREF(left);
-        *p_left = res;
-    }
-    assert(_PyUnicode_CheckConsistency(*p_left, 1));
-    return;
-
-error:
-    Py_CLEAR(*p_left);
-}
-
-void
-PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
-{
-    PyUnicode_Append(pleft, right);
-    Py_XDECREF(right);
-}
-
-PyDoc_STRVAR(count__doc__,
-             "S.count(sub[, start[, end]]) -> int\n\
-\n\
-Return the number of non-overlapping occurrences of substring sub in\n\
-string S[start:end].  Optional arguments start and end are\n\
-interpreted as in slice notation.");
-
-static PyObject *
-unicode_count(PyObject *self, PyObject *args)
-{
-    PyObject *substring = NULL;   /* initialize to fix a compiler warning */
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    PyObject *result;
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2, iresult;
-
-    if (!stringlib_parse_args_finds_unicode("count", args, &substring,
-                                            &start, &end))
-        return NULL;
-
-    kind1 = PyUnicode_KIND(self);
-    kind2 = PyUnicode_KIND(substring);
-    if (kind1 < kind2) {
-        Py_DECREF(substring);
-        return PyLong_FromLong(0);
-    }
-    len1 = PyUnicode_GET_LENGTH(self);
-    len2 = PyUnicode_GET_LENGTH(substring);
-    ADJUST_INDICES(start, end, len1);
-    if (end - start < len2) {
-        Py_DECREF(substring);
-        return PyLong_FromLong(0);
-    }
-    buf1 = PyUnicode_DATA(self);
-    buf2 = PyUnicode_DATA(substring);
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(substring, kind1);
-        if (!buf2) {
-            Py_DECREF(substring);
-            return NULL;
-        }
-    }
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        iresult = ucs1lib_count(
-            ((Py_UCS1*)buf1) + start, end - start,
-            buf2, len2, PY_SSIZE_T_MAX
-            );
-        break;
-    case PyUnicode_2BYTE_KIND:
-        iresult = ucs2lib_count(
-            ((Py_UCS2*)buf1) + start, end - start,
-            buf2, len2, PY_SSIZE_T_MAX
-            );
-        break;
-    case PyUnicode_4BYTE_KIND:
-        iresult = ucs4lib_count(
-            ((Py_UCS4*)buf1) + start, end - start,
-            buf2, len2, PY_SSIZE_T_MAX
-            );
-        break;
-    default:
-        assert(0); iresult = 0;
-    }
-
-    result = PyLong_FromSsize_t(iresult);
-
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-
-    Py_DECREF(substring);
-
-    return result;
-}
-
-PyDoc_STRVAR(encode__doc__,
-             "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
-\n\
-Encode S using the codec registered for encoding. Default encoding\n\
-is 'utf-8'. errors may be given to set a different error\n\
-handling scheme. Default is 'strict' meaning that encoding errors raise\n\
-a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
-'xmlcharrefreplace' as well as any other name registered with\n\
-codecs.register_error that can handle UnicodeEncodeErrors.");
-
-static PyObject *
-unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
-{
-    static char *kwlist[] = {"encoding", "errors", 0};
-    char *encoding = NULL;
-    char *errors = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
-                                     kwlist, &encoding, &errors))
-        return NULL;
-    return PyUnicode_AsEncodedString(self, encoding, errors);
-}
-
-PyDoc_STRVAR(expandtabs__doc__,
-             "S.expandtabs(tabsize=8) -> str\n\
-\n\
-Return a copy of S where all tab characters are expanded using spaces.\n\
-If tabsize is not given, a tab size of 8 characters is assumed.");
-
-static PyObject*
-unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    Py_ssize_t i, j, line_pos, src_len, incr;
-    Py_UCS4 ch;
-    PyObject *u;
-    void *src_data, *dest_data;
-    static char *kwlist[] = {"tabsize", 0};
-    int tabsize = 8;
-    int kind;
-    int found;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
-                                     kwlist, &tabsize))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    /* First pass: determine size of output string */
-    src_len = PyUnicode_GET_LENGTH(self);
-    i = j = line_pos = 0;
-    kind = PyUnicode_KIND(self);
-    src_data = PyUnicode_DATA(self);
-    found = 0;
-    for (; i < src_len; i++) {
-        ch = PyUnicode_READ(kind, src_data, i);
-        if (ch == '\t') {
-            found = 1;
-            if (tabsize > 0) {
-                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
-                if (j > PY_SSIZE_T_MAX - incr)
-                    goto overflow;
-                line_pos += incr;
-                j += incr;
-            }
-        }
-        else {
-            if (j > PY_SSIZE_T_MAX - 1)
-                goto overflow;
-            line_pos++;
-            j++;
-            if (ch == '\n' || ch == '\r')
-                line_pos = 0;
-        }
-    }
-    if (!found)
-        return unicode_result_unchanged(self);
-
-    /* Second pass: create output string and fill it */
-    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
-    if (!u)
-        return NULL;
-    dest_data = PyUnicode_DATA(u);
-
-    i = j = line_pos = 0;
-
-    for (; i < src_len; i++) {
-        ch = PyUnicode_READ(kind, src_data, i);
-        if (ch == '\t') {
-            if (tabsize > 0) {
-                incr = tabsize - (line_pos % tabsize);
-                line_pos += incr;
-                FILL(kind, dest_data, ' ', j, incr);
-                j += incr;
-            }
-        }
-        else {
-            line_pos++;
-            PyUnicode_WRITE(kind, dest_data, j, ch);
-            j++;
-            if (ch == '\n' || ch == '\r')
-                line_pos = 0;
-        }
-    }
-    assert (j == PyUnicode_GET_LENGTH(u));
-    return unicode_result(u);
-
-  overflow:
-    PyErr_SetString(PyExc_OverflowError, "new string is too long");
-    return NULL;
-}
-
-PyDoc_STRVAR(find__doc__,
-             "S.find(sub[, start[, end]]) -> int\n\
-\n\
-Return the lowest index in S where substring sub is found,\n\
-such that sub is contained within S[start:end].  Optional\n\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-unicode_find(PyObject *self, PyObject *args)
-{
-    /* initialize variables to prevent gcc warning */
-    PyObject *substring = NULL;
-    Py_ssize_t start = 0;
-    Py_ssize_t end = 0;
-    Py_ssize_t result;
-
-    if (!stringlib_parse_args_finds_unicode("find", args, &substring,
-                                            &start, &end))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-    if (PyUnicode_READY(substring) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-
-    result = any_find_slice(1, self, substring, start, end);
-
-    Py_DECREF(substring);
-
-    if (result == -2)
-        return NULL;
-
-    return PyLong_FromSsize_t(result);
-}
-
-static PyObject *
-unicode_getitem(PyObject *self, Py_ssize_t index)
-{
-    void *data;
-    enum PyUnicode_Kind kind;
-    Py_UCS4 ch;
-
-    if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return NULL;
-    }
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-    ch = PyUnicode_READ(kind, data, index);
-    return unicode_char(ch);
-}
-
-/* Believe it or not, this produces the same value for ASCII strings
-   as bytes_hash(). */
-static Py_hash_t
-unicode_hash(PyObject *self)
-{
-    Py_ssize_t len;
-    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
-
-#ifdef Py_DEBUG
-    assert(_Py_HashSecret_Initialized);
-#endif
-    if (_PyUnicode_HASH(self) != -1)
-        return _PyUnicode_HASH(self);
-    if (PyUnicode_READY(self) == -1)
-        return -1;
-    len = PyUnicode_GET_LENGTH(self);
-    /*
-      We make the hash of the empty string be 0, rather than using
-      (prefix ^ suffix), since this slightly obfuscates the hash secret
-    */
-    if (len == 0) {
-        _PyUnicode_HASH(self) = 0;
-        return 0;
-    }
-    x = _Py_HashBytes(PyUnicode_DATA(self),
-                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
-    _PyUnicode_HASH(self) = x;
-    return x;
-}
-
-PyDoc_STRVAR(index__doc__,
-             "S.index(sub[, start[, end]]) -> int\n\
-\n\
-Like S.find() but raise ValueError when the substring is not found.");
-
-static PyObject *
-unicode_index(PyObject *self, PyObject *args)
-{
-    /* initialize variables to prevent gcc warning */
-    Py_ssize_t result;
-    PyObject *substring = NULL;
-    Py_ssize_t start = 0;
-    Py_ssize_t end = 0;
-
-    if (!stringlib_parse_args_finds_unicode("index", args, &substring,
-                                            &start, &end))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-    if (PyUnicode_READY(substring) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-
-    result = any_find_slice(1, self, substring, start, end);
-
-    Py_DECREF(substring);
-
-    if (result == -2)
-        return NULL;
-
-    if (result < 0) {
-        PyErr_SetString(PyExc_ValueError, "substring not found");
-        return NULL;
-    }
-
-    return PyLong_FromSsize_t(result);
-}
-
-PyDoc_STRVAR(islower__doc__,
-             "S.islower() -> bool\n\
-\n\
-Return True if all cased characters in S are lowercase and there is\n\
-at least one cased character in S, False otherwise.");
-
-static PyObject*
-unicode_islower(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-    int cased;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    cased = 0;
-    for (i = 0; i < length; i++) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-
-        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
-            return PyBool_FromLong(0);
-        else if (!cased && Py_UNICODE_ISLOWER(ch))
-            cased = 1;
-    }
-    return PyBool_FromLong(cased);
-}
-
-PyDoc_STRVAR(isupper__doc__,
-             "S.isupper() -> bool\n\
-\n\
-Return True if all cased characters in S are uppercase and there is\n\
-at least one cased character in S, False otherwise.");
-
-static PyObject*
-unicode_isupper(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-    int cased;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    cased = 0;
-    for (i = 0; i < length; i++) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-
-        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
-            return PyBool_FromLong(0);
-        else if (!cased && Py_UNICODE_ISUPPER(ch))
-            cased = 1;
-    }
-    return PyBool_FromLong(cased);
-}
-
-PyDoc_STRVAR(istitle__doc__,
-             "S.istitle() -> bool\n\
-\n\
-Return True if S is a titlecased string and there is at least one\n\
-character in S, i.e. upper- and titlecase characters may only\n\
-follow uncased characters and lowercase characters only cased ones.\n\
-Return False otherwise.");
-
-static PyObject*
-unicode_istitle(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-    int cased, previous_is_cased;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1) {
-        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
-        return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
-                               (Py_UNICODE_ISUPPER(ch) != 0));
-    }
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    cased = 0;
-    previous_is_cased = 0;
-    for (i = 0; i < length; i++) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-
-        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
-            if (previous_is_cased)
-                return PyBool_FromLong(0);
-            previous_is_cased = 1;
-            cased = 1;
-        }
-        else if (Py_UNICODE_ISLOWER(ch)) {
-            if (!previous_is_cased)
-                return PyBool_FromLong(0);
-            previous_is_cased = 1;
-            cased = 1;
-        }
-        else
-            previous_is_cased = 0;
-    }
-    return PyBool_FromLong(cased);
-}
-
-PyDoc_STRVAR(isspace__doc__,
-             "S.isspace() -> bool\n\
-\n\
-Return True if all characters in S are whitespace\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-unicode_isspace(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    for (i = 0; i < length; i++) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-        if (!Py_UNICODE_ISSPACE(ch))
-            return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-PyDoc_STRVAR(isalpha__doc__,
-             "S.isalpha() -> bool\n\
-\n\
-Return True if all characters in S are alphabetic\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-unicode_isalpha(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    for (i = 0; i < length; i++) {
-        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
-            return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-PyDoc_STRVAR(isalnum__doc__,
-             "S.isalnum() -> bool\n\
-\n\
-Return True if all characters in S are alphanumeric\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-unicode_isalnum(PyObject *self)
-{
-    int kind;
-    void *data;
-    Py_ssize_t len, i;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-    len = PyUnicode_GET_LENGTH(self);
-
-    /* Shortcut for single character strings */
-    if (len == 1) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
-        return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
-    }
-
-    /* Special case for empty strings */
-    if (len == 0)
-        return PyBool_FromLong(0);
-
-    for (i = 0; i < len; i++) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-        if (!Py_UNICODE_ISALNUM(ch))
-            return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-PyDoc_STRVAR(isdecimal__doc__,
-             "S.isdecimal() -> bool\n\
-\n\
-Return True if there are only decimal characters in S,\n\
-False otherwise.");
-
-static PyObject*
-unicode_isdecimal(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    for (i = 0; i < length; i++) {
-        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
-            return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-PyDoc_STRVAR(isdigit__doc__,
-             "S.isdigit() -> bool\n\
-\n\
-Return True if all characters in S are digits\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-unicode_isdigit(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1) {
-        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
-        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
-    }
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    for (i = 0; i < length; i++) {
-        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
-            return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-PyDoc_STRVAR(isnumeric__doc__,
-             "S.isnumeric() -> bool\n\
-\n\
-Return True if there are only numeric characters in S,\n\
-False otherwise.");
-
-static PyObject*
-unicode_isnumeric(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
-
-    /* Special case for empty strings */
-    if (length == 0)
-        return PyBool_FromLong(0);
-
-    for (i = 0; i < length; i++) {
-        if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
-            return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-int
-PyUnicode_IsIdentifier(PyObject *self)
-{
-    int kind;
-    void *data;
-    Py_ssize_t i;
-    Py_UCS4 first;
-
-    if (PyUnicode_READY(self) == -1) {
-        Py_FatalError("identifier not ready");
-        return 0;
-    }
-
-    /* Special case for empty strings */
-    if (PyUnicode_GET_LENGTH(self) == 0)
-        return 0;
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* PEP 3131 says that the first character must be in
-       XID_Start and subsequent characters in XID_Continue,
-       and for the ASCII range, the 2.x rules apply (i.e
-       start with letters and underscore, continue with
-       letters, digits, underscore). However, given the current
-       definition of XID_Start and XID_Continue, it is sufficient
-       to check just for these, except that _ must be allowed
-       as starting an identifier.  */
-    first = PyUnicode_READ(kind, data, 0);
-    if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
-        return 0;
-
-    for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
-        if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
-            return 0;
-    return 1;
-}
-
-PyDoc_STRVAR(isidentifier__doc__,
-             "S.isidentifier() -> bool\n\
-\n\
-Return True if S is a valid identifier according\n\
-to the language definition.\n\
-\n\
-Use keyword.iskeyword() to test for reserved identifiers\n\
-such as \"def\" and \"class\".\n");
-
-static PyObject*
-unicode_isidentifier(PyObject *self)
-{
-    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
-}
-
-PyDoc_STRVAR(isprintable__doc__,
-             "S.isprintable() -> bool\n\
-\n\
-Return True if all characters in S are considered\n\
-printable in repr() or S is empty, False otherwise.");
-
-static PyObject*
-unicode_isprintable(PyObject *self)
-{
-    Py_ssize_t i, length;
-    int kind;
-    void *data;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    length = PyUnicode_GET_LENGTH(self);
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-
-    /* Shortcut for single character strings */
-    if (length == 1)
-        return PyBool_FromLong(
-            Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
-
-    for (i = 0; i < length; i++) {
-        if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
-            Py_RETURN_FALSE;
-        }
-    }
-    Py_RETURN_TRUE;
-}
-
-PyDoc_STRVAR(join__doc__,
-             "S.join(iterable) -> str\n\
-\n\
-Return a string which is the concatenation of the strings in the\n\
-iterable.  The separator between elements is S.");
-
-static PyObject*
-unicode_join(PyObject *self, PyObject *data)
-{
-    return PyUnicode_Join(self, data);
-}
-
-static Py_ssize_t
-unicode_length(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return -1;
-    return PyUnicode_GET_LENGTH(self);
-}
-
-PyDoc_STRVAR(ljust__doc__,
-             "S.ljust(width[, fillchar]) -> str\n\
-\n\
-Return S left-justified in a Unicode string of length width. Padding is\n\
-done using the specified fill character (default is a space).");
-
-static PyObject *
-unicode_ljust(PyObject *self, PyObject *args)
-{
-    Py_ssize_t width;
-    Py_UCS4 fillchar = ' ';
-
-    if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (PyUnicode_GET_LENGTH(self) >= width)
-        return unicode_result_unchanged(self);
-
-    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
-}
-
-PyDoc_STRVAR(lower__doc__,
-             "S.lower() -> str\n\
-\n\
-Return a copy of the string S converted to lowercase.");
-
-static PyObject*
-unicode_lower(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    if (PyUnicode_IS_ASCII(self))
-        return ascii_upper_or_lower(self, 1);
-    return case_operation(self, do_lower);
-}
-
-#define LEFTSTRIP 0
-#define RIGHTSTRIP 1
-#define BOTHSTRIP 2
-
-/* Arrays indexed by above */
-static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
-
-#define STRIPNAME(i) (stripformat[i]+3)
-
-/* externally visible for str.strip(unicode) */
-PyObject *
-_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
-{
-    void *data;
-    int kind;
-    Py_ssize_t i, j, len;
-    BLOOM_MASK sepmask;
-    Py_ssize_t seplen;
-
-    if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
-        return NULL;
-
-    kind = PyUnicode_KIND(self);
-    data = PyUnicode_DATA(self);
-    len = PyUnicode_GET_LENGTH(self);
-    seplen = PyUnicode_GET_LENGTH(sepobj);
-    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
-                              PyUnicode_DATA(sepobj),
-                              seplen);
-
-    i = 0;
-    if (striptype != RIGHTSTRIP) {
-        while (i < len) {
-            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-            if (!BLOOM(sepmask, ch))
-                break;
-            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
-                break;
-            i++;
-        }
-    }
-
-    j = len;
-    if (striptype != LEFTSTRIP) {
-        j--;
-        while (j >= i) {
-            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
-            if (!BLOOM(sepmask, ch))
-                break;
-            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
-                break;
-            j--;
-        }
-
-        j++;
-    }
-
-    return PyUnicode_Substring(self, i, j);
-}
-
-PyObject*
-PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
-{
-    unsigned char *data;
-    int kind;
-    Py_ssize_t length;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    length = PyUnicode_GET_LENGTH(self);
-    end = Py_MIN(end, length);
-
-    if (start == 0 && end == length)
-        return unicode_result_unchanged(self);
-
-    if (start < 0 || end < 0) {
-        PyErr_SetString(PyExc_IndexError, "string index out of range");
-        return NULL;
-    }
-    if (start >= length || end < start)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    length = end - start;
-    if (PyUnicode_IS_ASCII(self)) {
-        data = PyUnicode_1BYTE_DATA(self);
-        return _PyUnicode_FromASCII((char*)(data + start), length);
-    }
-    else {
-        kind = PyUnicode_KIND(self);
-        data = PyUnicode_1BYTE_DATA(self);
-        return PyUnicode_FromKindAndData(kind,
-                                         data + kind * start,
-                                         length);
-    }
-}
-
-static PyObject *
-do_strip(PyObject *self, int striptype)
-{
-    Py_ssize_t len, i, j;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    len = PyUnicode_GET_LENGTH(self);
-
-    if (PyUnicode_IS_ASCII(self)) {
-        Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
-
-        i = 0;
-        if (striptype != RIGHTSTRIP) {
-            while (i < len) {
-                Py_UCS1 ch = data[i];
-                if (!_Py_ascii_whitespace[ch])
-                    break;
-                i++;
-            }
-        }
-
-        j = len;
-        if (striptype != LEFTSTRIP) {
-            j--;
-            while (j >= i) {
-                Py_UCS1 ch = data[j];
-                if (!_Py_ascii_whitespace[ch])
-                    break;
-                j--;
-            }
-            j++;
-        }
-    }
-    else {
-        int kind = PyUnicode_KIND(self);
-        void *data = PyUnicode_DATA(self);
-
-        i = 0;
-        if (striptype != RIGHTSTRIP) {
-            while (i < len) {
-                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
-                if (!Py_UNICODE_ISSPACE(ch))
-                    break;
-                i++;
-            }
-        }
-
-        j = len;
-        if (striptype != LEFTSTRIP) {
-            j--;
-            while (j >= i) {
-                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
-                if (!Py_UNICODE_ISSPACE(ch))
-                    break;
-                j--;
-            }
-            j++;
-        }
-    }
-
-    return PyUnicode_Substring(self, i, j);
-}
-
-
-static PyObject *
-do_argstrip(PyObject *self, int striptype, PyObject *args)
-{
-    PyObject *sep = NULL;
-
-    if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
-        return NULL;
-
-    if (sep != NULL && sep != Py_None) {
-        if (PyUnicode_Check(sep))
-            return _PyUnicode_XStrip(self, striptype, sep);
-        else {
-            PyErr_Format(PyExc_TypeError,
-                         "%s arg must be None or str",
-                         STRIPNAME(striptype));
-            return NULL;
-        }
-    }
-
-    return do_strip(self, striptype);
-}
-
-
-PyDoc_STRVAR(strip__doc__,
-             "S.strip([chars]) -> str\n\
-\n\
-Return a copy of the string S with leading and trailing\n\
-whitespace removed.\n\
-If chars is given and not None, remove characters in chars instead.");
-
-static PyObject *
-unicode_strip(PyObject *self, PyObject *args)
-{
-    if (PyTuple_GET_SIZE(args) == 0)
-        return do_strip(self, BOTHSTRIP); /* Common case */
-    else
-        return do_argstrip(self, BOTHSTRIP, args);
-}
-
-
-PyDoc_STRVAR(lstrip__doc__,
-             "S.lstrip([chars]) -> str\n\
-\n\
-Return a copy of the string S with leading whitespace removed.\n\
-If chars is given and not None, remove characters in chars instead.");
-
-static PyObject *
-unicode_lstrip(PyObject *self, PyObject *args)
-{
-    if (PyTuple_GET_SIZE(args) == 0)
-        return do_strip(self, LEFTSTRIP); /* Common case */
-    else
-        return do_argstrip(self, LEFTSTRIP, args);
-}
-
-
-PyDoc_STRVAR(rstrip__doc__,
-             "S.rstrip([chars]) -> str\n\
-\n\
-Return a copy of the string S with trailing whitespace removed.\n\
-If chars is given and not None, remove characters in chars instead.");
-
-static PyObject *
-unicode_rstrip(PyObject *self, PyObject *args)
-{
-    if (PyTuple_GET_SIZE(args) == 0)
-        return do_strip(self, RIGHTSTRIP); /* Common case */
-    else
-        return do_argstrip(self, RIGHTSTRIP, args);
-}
-
-
-static PyObject*
-unicode_repeat(PyObject *str, Py_ssize_t len)
-{
-    PyObject *u;
-    Py_ssize_t nchars, n;
-
-    if (len < 1)
-        _Py_RETURN_UNICODE_EMPTY();
-
-    /* no repeat, return original string */
-    if (len == 1)
-        return unicode_result_unchanged(str);
-
-    if (PyUnicode_READY(str) == -1)
-        return NULL;
-
-    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "repeated string is too long");
-        return NULL;
-    }
-    nchars = len * PyUnicode_GET_LENGTH(str);
-
-    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
-    if (!u)
-        return NULL;
-    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
-
-    if (PyUnicode_GET_LENGTH(str) == 1) {
-        const int kind = PyUnicode_KIND(str);
-        const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
-        if (kind == PyUnicode_1BYTE_KIND) {
-            void *to = PyUnicode_DATA(u);
-            memset(to, (unsigned char)fill_char, len);
-        }
-        else if (kind == PyUnicode_2BYTE_KIND) {
-            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
-            for (n = 0; n < len; ++n)
-                ucs2[n] = fill_char;
-        } else {
-            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
-            assert(kind == PyUnicode_4BYTE_KIND);
-            for (n = 0; n < len; ++n)
-                ucs4[n] = fill_char;
-        }
-    }
-    else {
-        /* number of characters copied this far */
-        Py_ssize_t done = PyUnicode_GET_LENGTH(str);
-        const Py_ssize_t char_size = PyUnicode_KIND(str);
-        char *to = (char *) PyUnicode_DATA(u);
-        Py_MEMCPY(to, PyUnicode_DATA(str),
-                  PyUnicode_GET_LENGTH(str) * char_size);
-        while (done < nchars) {
-            n = (done <= nchars-done) ? done : nchars-done;
-            Py_MEMCPY(to + (done * char_size), to, n * char_size);
-            done += n;
-        }
-    }
-
-    assert(_PyUnicode_CheckConsistency(u, 1));
-    return u;
-}
-
-PyObject *
-PyUnicode_Replace(PyObject *obj,
-                  PyObject *subobj,
-                  PyObject *replobj,
-                  Py_ssize_t maxcount)
-{
-    PyObject *self;
-    PyObject *str1;
-    PyObject *str2;
-    PyObject *result;
-
-    self = PyUnicode_FromObject(obj);
-    if (self == NULL)
-        return NULL;
-    str1 = PyUnicode_FromObject(subobj);
-    if (str1 == NULL) {
-        Py_DECREF(self);
-        return NULL;
-    }
-    str2 = PyUnicode_FromObject(replobj);
-    if (str2 == NULL) {
-        Py_DECREF(self);
-        Py_DECREF(str1);
-        return NULL;
-    }
-    if (PyUnicode_READY(self) == -1 ||
-        PyUnicode_READY(str1) == -1 ||
-        PyUnicode_READY(str2) == -1)
-        result = NULL;
-    else
-        result = replace(self, str1, str2, maxcount);
-    Py_DECREF(self);
-    Py_DECREF(str1);
-    Py_DECREF(str2);
-    return result;
-}
-
-PyDoc_STRVAR(replace__doc__,
-             "S.replace(old, new[, count]) -> str\n\
-\n\
-Return a copy of S with all occurrences of substring\n\
-old replaced by new.  If the optional argument count is\n\
-given, only the first count occurrences are replaced.");
-
-static PyObject*
-unicode_replace(PyObject *self, PyObject *args)
-{
-    PyObject *str1;
-    PyObject *str2;
-    Py_ssize_t maxcount = -1;
-    PyObject *result;
-
-    if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
-        return NULL;
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    str1 = PyUnicode_FromObject(str1);
-    if (str1 == NULL)
-        return NULL;
-    str2 = PyUnicode_FromObject(str2);
-    if (str2 == NULL) {
-        Py_DECREF(str1);
-        return NULL;
-    }
-    if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
-        result = NULL;
-    else
-        result = replace(self, str1, str2, maxcount);
-
-    Py_DECREF(str1);
-    Py_DECREF(str2);
-    return result;
-}
-
-static PyObject *
-unicode_repr(PyObject *unicode)
-{
-    PyObject *repr;
-    Py_ssize_t isize;
-    Py_ssize_t osize, squote, dquote, i, o;
-    Py_UCS4 max, quote;
-    int ikind, okind, unchanged;
-    void *idata, *odata;
-
-    if (PyUnicode_READY(unicode) == -1)
-        return NULL;
-
-    isize = PyUnicode_GET_LENGTH(unicode);
-    idata = PyUnicode_DATA(unicode);
-
-    /* Compute length of output, quote characters, and
-       maximum character */
-    osize = 0;
-    max = 127;
-    squote = dquote = 0;
-    ikind = PyUnicode_KIND(unicode);
-    for (i = 0; i < isize; i++) {
-        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
-        Py_ssize_t incr = 1;
-        switch (ch) {
-        case '\'': squote++; break;
-        case '"':  dquote++; break;
-        case '\\': case '\t': case '\r': case '\n':
-            incr = 2;
-            break;
-        default:
-            /* Fast-path ASCII */
-            if (ch < ' ' || ch == 0x7f)
-                incr = 4; /* \xHH */
-            else if (ch < 0x7f)
-                ;
-            else if (Py_UNICODE_ISPRINTABLE(ch))
-                max = ch > max ? ch : max;
-            else if (ch < 0x100)
-                incr = 4; /* \xHH */
-            else if (ch < 0x10000)
-                incr = 6; /* \uHHHH */
-            else
-                incr = 10; /* \uHHHHHHHH */
-        }
-        if (osize > PY_SSIZE_T_MAX - incr) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "string is too long to generate repr");
-            return NULL;
-        }
-        osize += incr;
-    }
-
-    quote = '\'';
-    unchanged = (osize == isize);
-    if (squote) {
-        unchanged = 0;
-        if (dquote)
-            /* Both squote and dquote present. Use squote,
-               and escape them */
-            osize += squote;
-        else
-            quote = '"';
-    }
-    osize += 2;   /* quotes */
-
-    repr = PyUnicode_New(osize, max);
-    if (repr == NULL)
-        return NULL;
-    okind = PyUnicode_KIND(repr);
-    odata = PyUnicode_DATA(repr);
-
-    PyUnicode_WRITE(okind, odata, 0, quote);
-    PyUnicode_WRITE(okind, odata, osize-1, quote);
-    if (unchanged) {
-        _PyUnicode_FastCopyCharacters(repr, 1,
-                                      unicode, 0,
-                                      isize);
-    }
-    else {
-        for (i = 0, o = 1; i < isize; i++) {
-            Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
-
-            /* Escape quotes and backslashes */
-            if ((ch == quote) || (ch == '\\')) {
-                PyUnicode_WRITE(okind, odata, o++, '\\');
-                PyUnicode_WRITE(okind, odata, o++, ch);
-                continue;
-            }
-
-            /* Map special whitespace to '\t', \n', '\r' */
-            if (ch == '\t') {
-                PyUnicode_WRITE(okind, odata, o++, '\\');
-                PyUnicode_WRITE(okind, odata, o++, 't');
-            }
-            else if (ch == '\n') {
-                PyUnicode_WRITE(okind, odata, o++, '\\');
-                PyUnicode_WRITE(okind, odata, o++, 'n');
-            }
-            else if (ch == '\r') {
-                PyUnicode_WRITE(okind, odata, o++, '\\');
-                PyUnicode_WRITE(okind, odata, o++, 'r');
-            }
-
-            /* Map non-printable US ASCII to '\xhh' */
-            else if (ch < ' ' || ch == 0x7F) {
-                PyUnicode_WRITE(okind, odata, o++, '\\');
-                PyUnicode_WRITE(okind, odata, o++, 'x');
-                PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
-                PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
-            }
-
-            /* Copy ASCII characters as-is */
-            else if (ch < 0x7F) {
-                PyUnicode_WRITE(okind, odata, o++, ch);
-            }
-
-            /* Non-ASCII characters */
-            else {
-                /* Map Unicode whitespace and control characters
-                   (categories Z* and C* except ASCII space)
-                */
-                if (!Py_UNICODE_ISPRINTABLE(ch)) {
-                    PyUnicode_WRITE(okind, odata, o++, '\\');
-                    /* Map 8-bit characters to '\xhh' */
-                    if (ch <= 0xff) {
-                        PyUnicode_WRITE(okind, odata, o++, 'x');
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
-                    }
-                    /* Map 16-bit characters to '\uxxxx' */
-                    else if (ch <= 0xffff) {
-                        PyUnicode_WRITE(okind, odata, o++, 'u');
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
-                    }
-                    /* Map 21-bit characters to '\U00xxxxxx' */
-                    else {
-                        PyUnicode_WRITE(okind, odata, o++, 'U');
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
-                        PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
-                    }
-                }
-                /* Copy characters as-is */
-                else {
-                    PyUnicode_WRITE(okind, odata, o++, ch);
-                }
-            }
-        }
-    }
-    /* Closing quote already added at the beginning */
-    assert(_PyUnicode_CheckConsistency(repr, 1));
-    return repr;
-}
-
-PyDoc_STRVAR(rfind__doc__,
-             "S.rfind(sub[, start[, end]]) -> int\n\
-\n\
-Return the highest index in S where substring sub is found,\n\
-such that sub is contained within S[start:end].  Optional\n\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-unicode_rfind(PyObject *self, PyObject *args)
-{
-    /* initialize variables to prevent gcc warning */
-    PyObject *substring = NULL;
-    Py_ssize_t start = 0;
-    Py_ssize_t end = 0;
-    Py_ssize_t result;
-
-    if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
-                                            &start, &end))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-    if (PyUnicode_READY(substring) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-
-    result = any_find_slice(-1, self, substring, start, end);
-
-    Py_DECREF(substring);
-
-    if (result == -2)
-        return NULL;
-
-    return PyLong_FromSsize_t(result);
-}
-
-PyDoc_STRVAR(rindex__doc__,
-             "S.rindex(sub[, start[, end]]) -> int\n\
-\n\
-Like S.rfind() but raise ValueError when the substring is not found.");
-
-static PyObject *
-unicode_rindex(PyObject *self, PyObject *args)
-{
-    /* initialize variables to prevent gcc warning */
-    PyObject *substring = NULL;
-    Py_ssize_t start = 0;
-    Py_ssize_t end = 0;
-    Py_ssize_t result;
-
-    if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
-                                            &start, &end))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-    if (PyUnicode_READY(substring) == -1) {
-        Py_DECREF(substring);
-        return NULL;
-    }
-
-    result = any_find_slice(-1, self, substring, start, end);
-
-    Py_DECREF(substring);
-
-    if (result == -2)
-        return NULL;
-
-    if (result < 0) {
-        PyErr_SetString(PyExc_ValueError, "substring not found");
-        return NULL;
-    }
-
-    return PyLong_FromSsize_t(result);
-}
-
-PyDoc_STRVAR(rjust__doc__,
-             "S.rjust(width[, fillchar]) -> str\n\
-\n\
-Return S right-justified in a string of length width. Padding is\n\
-done using the specified fill character (default is a space).");
-
-static PyObject *
-unicode_rjust(PyObject *self, PyObject *args)
-{
-    Py_ssize_t width;
-    Py_UCS4 fillchar = ' ';
-
-    if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (PyUnicode_GET_LENGTH(self) >= width)
-        return unicode_result_unchanged(self);
-
-    return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
-}
-
-PyObject *
-PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
-{
-    PyObject *result;
-
-    s = PyUnicode_FromObject(s);
-    if (s == NULL)
-        return NULL;
-    if (sep != NULL) {
-        sep = PyUnicode_FromObject(sep);
-        if (sep == NULL) {
-            Py_DECREF(s);
-            return NULL;
-        }
-    }
-
-    result = split(s, sep, maxsplit);
-
-    Py_DECREF(s);
-    Py_XDECREF(sep);
-    return result;
-}
-
-PyDoc_STRVAR(split__doc__,
-             "S.split(sep=None, maxsplit=-1) -> list of strings\n\
-\n\
-Return a list of the words in S, using sep as the\n\
-delimiter string.  If maxsplit is given, at most maxsplit\n\
-splits are done. If sep is not specified or is None, any\n\
-whitespace string is a separator and empty strings are\n\
-removed from the result.");
-
-static PyObject*
-unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    static char *kwlist[] = {"sep", "maxsplit", 0};
-    PyObject *substring = Py_None;
-    Py_ssize_t maxcount = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
-                                     kwlist, &substring, &maxcount))
-        return NULL;
-
-    if (substring == Py_None)
-        return split(self, NULL, maxcount);
-    else if (PyUnicode_Check(substring))
-        return split(self, substring, maxcount);
-    else
-        return PyUnicode_Split(self, substring, maxcount);
-}
-
-PyObject *
-PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
-{
-    PyObject* str_obj;
-    PyObject* sep_obj;
-    PyObject* out;
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2;
-
-    str_obj = PyUnicode_FromObject(str_in);
-    if (!str_obj)
-        return NULL;
-    sep_obj = PyUnicode_FromObject(sep_in);
-    if (!sep_obj) {
-        Py_DECREF(str_obj);
-        return NULL;
-    }
-    if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
-        Py_DECREF(sep_obj);
-        Py_DECREF(str_obj);
-        return NULL;
-    }
-
-    kind1 = PyUnicode_KIND(str_obj);
-    kind2 = PyUnicode_KIND(sep_obj);
-    len1 = PyUnicode_GET_LENGTH(str_obj);
-    len2 = PyUnicode_GET_LENGTH(sep_obj);
-    if (kind1 < kind2 || len1 < len2) {
-        _Py_INCREF_UNICODE_EMPTY();
-        if (!unicode_empty)
-            out = NULL;
-        else {
-            out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
-            Py_DECREF(unicode_empty);
-        }
-        Py_DECREF(sep_obj);
-        Py_DECREF(str_obj);
-        return out;
-    }
-    buf1 = PyUnicode_DATA(str_obj);
-    buf2 = PyUnicode_DATA(sep_obj);
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(sep_obj, kind1);
-        if (!buf2)
-            goto onError;
-    }
-
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
-            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        else
-            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        break;
-    default:
-        assert(0);
-        out = 0;
-    }
-
-    Py_DECREF(sep_obj);
-    Py_DECREF(str_obj);
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-
-    return out;
-  onError:
-    Py_DECREF(sep_obj);
-    Py_DECREF(str_obj);
-    if (kind2 != kind1 && buf2)
-        PyMem_Free(buf2);
-    return NULL;
-}
-
-
-PyObject *
-PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
-{
-    PyObject* str_obj;
-    PyObject* sep_obj;
-    PyObject* out;
-    int kind1, kind2;
-    void *buf1, *buf2;
-    Py_ssize_t len1, len2;
-
-    str_obj = PyUnicode_FromObject(str_in);
-    if (!str_obj)
-        return NULL;
-    sep_obj = PyUnicode_FromObject(sep_in);
-    if (!sep_obj) {
-        Py_DECREF(str_obj);
-        return NULL;
-    }
-
-    kind1 = PyUnicode_KIND(str_obj);
-    kind2 = PyUnicode_KIND(sep_obj);
-    len1 = PyUnicode_GET_LENGTH(str_obj);
-    len2 = PyUnicode_GET_LENGTH(sep_obj);
-    if (kind1 < kind2 || len1 < len2) {
-        _Py_INCREF_UNICODE_EMPTY();
-        if (!unicode_empty)
-            out = NULL;
-        else {
-            out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
-            Py_DECREF(unicode_empty);
-        }
-        Py_DECREF(sep_obj);
-        Py_DECREF(str_obj);
-        return out;
-    }
-    buf1 = PyUnicode_DATA(str_obj);
-    buf2 = PyUnicode_DATA(sep_obj);
-    if (kind2 != kind1) {
-        buf2 = _PyUnicode_AsKind(sep_obj, kind1);
-        if (!buf2)
-            goto onError;
-    }
-
-    switch (kind1) {
-    case PyUnicode_1BYTE_KIND:
-        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
-            out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        else
-            out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        break;
-    case PyUnicode_2BYTE_KIND:
-        out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        break;
-    case PyUnicode_4BYTE_KIND:
-        out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
-        break;
-    default:
-        assert(0);
-        out = 0;
-    }
-
-    Py_DECREF(sep_obj);
-    Py_DECREF(str_obj);
-    if (kind2 != kind1)
-        PyMem_Free(buf2);
-
-    return out;
-  onError:
-    Py_DECREF(sep_obj);
-    Py_DECREF(str_obj);
-    if (kind2 != kind1 && buf2)
-        PyMem_Free(buf2);
-    return NULL;
-}
-
-PyDoc_STRVAR(partition__doc__,
-             "S.partition(sep) -> (head, sep, tail)\n\
-\n\
-Search for the separator sep in S, and return the part before it,\n\
-the separator itself, and the part after it.  If the separator is not\n\
-found, return S and two empty strings.");
-
-static PyObject*
-unicode_partition(PyObject *self, PyObject *separator)
-{
-    return PyUnicode_Partition(self, separator);
-}
-
-PyDoc_STRVAR(rpartition__doc__,
-             "S.rpartition(sep) -> (head, sep, tail)\n\
-\n\
-Search for the separator sep in S, starting at the end of S, and return\n\
-the part before it, the separator itself, and the part after it.  If the\n\
-separator is not found, return two empty strings and S.");
-
-static PyObject*
-unicode_rpartition(PyObject *self, PyObject *separator)
-{
-    return PyUnicode_RPartition(self, separator);
-}
-
-PyObject *
-PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
-{
-    PyObject *result;
-
-    s = PyUnicode_FromObject(s);
-    if (s == NULL)
-        return NULL;
-    if (sep != NULL) {
-        sep = PyUnicode_FromObject(sep);
-        if (sep == NULL) {
-            Py_DECREF(s);
-            return NULL;
-        }
-    }
-
-    result = rsplit(s, sep, maxsplit);
-
-    Py_DECREF(s);
-    Py_XDECREF(sep);
-    return result;
-}
-
-PyDoc_STRVAR(rsplit__doc__,
-             "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
-\n\
-Return a list of the words in S, using sep as the\n\
-delimiter string, starting at the end of the string and\n\
-working to the front.  If maxsplit is given, at most maxsplit\n\
-splits are done. If sep is not specified, any whitespace string\n\
-is a separator.");
-
-static PyObject*
-unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    static char *kwlist[] = {"sep", "maxsplit", 0};
-    PyObject *substring = Py_None;
-    Py_ssize_t maxcount = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
-                                     kwlist, &substring, &maxcount))
-        return NULL;
-
-    if (substring == Py_None)
-        return rsplit(self, NULL, maxcount);
-    else if (PyUnicode_Check(substring))
-        return rsplit(self, substring, maxcount);
-    else
-        return PyUnicode_RSplit(self, substring, maxcount);
-}
-
-PyDoc_STRVAR(splitlines__doc__,
-             "S.splitlines([keepends]) -> list of strings\n\
-\n\
-Return a list of the lines in S, breaking at line boundaries.\n\
-Line breaks are not included in the resulting list unless keepends\n\
-is given and true.");
-
-static PyObject*
-unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    static char *kwlist[] = {"keepends", 0};
-    int keepends = 0;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
-                                     kwlist, &keepends))
-        return NULL;
-
-    return PyUnicode_Splitlines(self, keepends);
-}
-
-static
-PyObject *unicode_str(PyObject *self)
-{
-    return unicode_result_unchanged(self);
-}
-
-PyDoc_STRVAR(swapcase__doc__,
-             "S.swapcase() -> str\n\
-\n\
-Return a copy of S with uppercase characters converted to lowercase\n\
-and vice versa.");
-
-static PyObject*
-unicode_swapcase(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    return case_operation(self, do_swapcase);
-}
-
-/*[clinic input]
-
- at staticmethod
-str.maketrans as unicode_maketrans
-
-  x: object
-
-  y: unicode=NULL
-
-  z: unicode=NULL
-
-  /
-
-Return a translation table usable for str.translate().
-
-If there is only one argument, it must be a dictionary mapping Unicode
-ordinals (integers) or characters to Unicode ordinals, strings or None.
-Character keys will be then converted to ordinals.
-If there are two arguments, they must be strings of equal length, and
-in the resulting dictionary, each character in x will be mapped to the
-character at the same position in y. If there is a third argument, it
-must be a string, whose characters will be mapped to None in the result.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(unicode_maketrans__doc__,
@@ -12992,2486 +39,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
-/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
-{
-    PyObject *new = NULL, *key, *value;
-    Py_ssize_t i = 0;
-    int res;
-
-    new = PyDict_New();
-    if (!new)
-        return NULL;
-    if (y != NULL) {
-        int x_kind, y_kind, z_kind;
-        void *x_data, *y_data, *z_data;
-
-        /* x must be a string too, of equal length */
-        if (!PyUnicode_Check(x)) {
-            PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
-                            "be a string if there is a second argument");
-            goto err;
-        }
-        if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
-            PyErr_SetString(PyExc_ValueError, "the first two maketrans "
-                            "arguments must have equal length");
-            goto err;
-        }
-        /* create entries for translating chars in x to those in y */
-        x_kind = PyUnicode_KIND(x);
-        y_kind = PyUnicode_KIND(y);
-        x_data = PyUnicode_DATA(x);
-        y_data = PyUnicode_DATA(y);
-        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
-            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
-            if (!key)
-                goto err;
-            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
-            if (!value) {
-                Py_DECREF(key);
-                goto err;
-            }
-            res = PyDict_SetItem(new, key, value);
-            Py_DECREF(key);
-            Py_DECREF(value);
-            if (res < 0)
-                goto err;
-        }
-        /* create entries for deleting chars in z */
-        if (z != NULL) {
-            z_kind = PyUnicode_KIND(z);
-            z_data = PyUnicode_DATA(z);
-            for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
-                key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
-                if (!key)
-                    goto err;
-                res = PyDict_SetItem(new, key, Py_None);
-                Py_DECREF(key);
-                if (res < 0)
-                    goto err;
-            }
-        }
-    } else {
-        int kind;
-        void *data;
-
-        /* x must be a dict */
-        if (!PyDict_CheckExact(x)) {
-            PyErr_SetString(PyExc_TypeError, "if you give only one argument "
-                            "to maketrans it must be a dict");
-            goto err;
-        }
-        /* copy entries into the new dict, converting string keys to int keys */
-        while (PyDict_Next(x, &i, &key, &value)) {
-            if (PyUnicode_Check(key)) {
-                /* convert string keys to integer keys */
-                PyObject *newkey;
-                if (PyUnicode_GET_LENGTH(key) != 1) {
-                    PyErr_SetString(PyExc_ValueError, "string keys in translate "
-                                    "table must be of length 1");
-                    goto err;
-                }
-                kind = PyUnicode_KIND(key);
-                data = PyUnicode_DATA(key);
-                newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
-                if (!newkey)
-                    goto err;
-                res = PyDict_SetItem(new, newkey, value);
-                Py_DECREF(newkey);
-                if (res < 0)
-                    goto err;
-            } else if (PyLong_Check(key)) {
-                /* just keep integer keys */
-                if (PyDict_SetItem(new, key, value) < 0)
-                    goto err;
-            } else {
-                PyErr_SetString(PyExc_TypeError, "keys in translate table must "
-                                "be strings or integers");
-                goto err;
-            }
-        }
-    }
-    return new;
-  err:
-    Py_DECREF(new);
-    return NULL;
-}
-
-PyDoc_STRVAR(translate__doc__,
-             "S.translate(table) -> str\n\
-\n\
-Return a copy of the string S, where all characters have been mapped\n\
-through the given translation table, which must be a mapping of\n\
-Unicode ordinals to Unicode ordinals, strings, or None.\n\
-Unmapped characters are left untouched. Characters mapped to None\n\
-are deleted.");
-
-static PyObject*
-unicode_translate(PyObject *self, PyObject *table)
-{
-    return _PyUnicode_TranslateCharmap(self, table, "ignore");
-}
-
-PyDoc_STRVAR(upper__doc__,
-             "S.upper() -> str\n\
-\n\
-Return a copy of S converted to uppercase.");
-
-static PyObject*
-unicode_upper(PyObject *self)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    if (PyUnicode_IS_ASCII(self))
-        return ascii_upper_or_lower(self, 0);
-    return case_operation(self, do_upper);
-}
-
-PyDoc_STRVAR(zfill__doc__,
-             "S.zfill(width) -> str\n\
-\n\
-Pad a numeric string S with zeros on the left, to fill a field\n\
-of the specified width. The string S is never truncated.");
-
-static PyObject *
-unicode_zfill(PyObject *self, PyObject *args)
-{
-    Py_ssize_t fill;
-    PyObject *u;
-    Py_ssize_t width;
-    int kind;
-    void *data;
-    Py_UCS4 chr;
-
-    if (!PyArg_ParseTuple(args, "n:zfill", &width))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (PyUnicode_GET_LENGTH(self) >= width)
-        return unicode_result_unchanged(self);
-
-    fill = width - PyUnicode_GET_LENGTH(self);
-
-    u = pad(self, fill, 0, '0');
-
-    if (u == NULL)
-        return NULL;
-
-    kind = PyUnicode_KIND(u);
-    data = PyUnicode_DATA(u);
-    chr = PyUnicode_READ(kind, data, fill);
-
-    if (chr == '+' || chr == '-') {
-        /* move sign to beginning of string */
-        PyUnicode_WRITE(kind, data, 0, chr);
-        PyUnicode_WRITE(kind, data, fill, '0');
-    }
-
-    assert(_PyUnicode_CheckConsistency(u, 1));
-    return u;
-}
-
-#if 0
-static PyObject *
-unicode__decimal2ascii(PyObject *self)
-{
-    return PyUnicode_TransformDecimalAndSpaceToASCII(self);
-}
-#endif
-
-PyDoc_STRVAR(startswith__doc__,
-             "S.startswith(prefix[, start[, end]]) -> bool\n\
-\n\
-Return True if S starts with the specified prefix, False otherwise.\n\
-With optional start, test S beginning at that position.\n\
-With optional end, stop comparing S at that position.\n\
-prefix can also be a tuple of strings to try.");
-
-static PyObject *
-unicode_startswith(PyObject *self,
-                   PyObject *args)
-{
-    PyObject *subobj;
-    PyObject *substring;
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    int result;
-
-    if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
-        return NULL;
-    if (PyTuple_Check(subobj)) {
-        Py_ssize_t i;
-        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-            substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
-            if (substring == NULL)
-                return NULL;
-            result = tailmatch(self, substring, start, end, -1);
-            Py_DECREF(substring);
-            if (result == -1)
-                return NULL;
-            if (result) {
-                Py_RETURN_TRUE;
-            }
-        }
-        /* nothing matched */
-        Py_RETURN_FALSE;
-    }
-    substring = PyUnicode_FromObject(subobj);
-    if (substring == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_TypeError))
-            PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
-                         "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
-        return NULL;
-    }
-    result = tailmatch(self, substring, start, end, -1);
-    Py_DECREF(substring);
-    if (result == -1)
-        return NULL;
-    return PyBool_FromLong(result);
-}
-
-
-PyDoc_STRVAR(endswith__doc__,
-             "S.endswith(suffix[, start[, end]]) -> bool\n\
-\n\
-Return True if S ends with the specified suffix, False otherwise.\n\
-With optional start, test S beginning at that position.\n\
-With optional end, stop comparing S at that position.\n\
-suffix can also be a tuple of strings to try.");
-
-static PyObject *
-unicode_endswith(PyObject *self,
-                 PyObject *args)
-{
-    PyObject *subobj;
-    PyObject *substring;
-    Py_ssize_t start = 0;
-    Py_ssize_t end = PY_SSIZE_T_MAX;
-    int result;
-
-    if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
-        return NULL;
-    if (PyTuple_Check(subobj)) {
-        Py_ssize_t i;
-        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-            substring = PyUnicode_FromObject(
-                PyTuple_GET_ITEM(subobj, i));
-            if (substring == NULL)
-                return NULL;
-            result = tailmatch(self, substring, start, end, +1);
-            Py_DECREF(substring);
-            if (result == -1)
-                return NULL;
-            if (result) {
-                Py_RETURN_TRUE;
-            }
-        }
-        Py_RETURN_FALSE;
-    }
-    substring = PyUnicode_FromObject(subobj);
-    if (substring == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_TypeError))
-            PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
-                         "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
-        return NULL;
-    }
-    result = tailmatch(self, substring, start, end, +1);
-    Py_DECREF(substring);
-    if (result == -1)
-        return NULL;
-    return PyBool_FromLong(result);
-}
-
-Py_LOCAL_INLINE(void)
-_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
-{
-    if (!writer->readonly)
-        writer->size = PyUnicode_GET_LENGTH(writer->buffer);
-    else {
-        /* Copy-on-write mode: set buffer size to 0 so
-         * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
-         * next write. */
-        writer->size = 0;
-    }
-    writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
-    writer->data = PyUnicode_DATA(writer->buffer);
-    writer->kind = PyUnicode_KIND(writer->buffer);
-}
-
-void
-_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
-{
-    memset(writer, 0, sizeof(*writer));
-#ifdef Py_DEBUG
-    writer->kind = 5;    /* invalid kind */
-#endif
-    writer->min_char = 127;
-}
-
-int
-_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
-                                 Py_ssize_t length, Py_UCS4 maxchar)
-{
-#ifdef MS_WINDOWS
-   /* On Windows, overallocate by 50% is the best factor */
-#  define OVERALLOCATE_FACTOR 2
-#else
-   /* On Linux, overallocate by 25% is the best factor */
-#  define OVERALLOCATE_FACTOR 4
-#endif
-    Py_ssize_t newlen;
-    PyObject *newbuffer;
-
-    assert(length > 0);
-
-    if (length > PY_SSIZE_T_MAX - writer->pos) {
-        PyErr_NoMemory();
-        return -1;
-    }
-    newlen = writer->pos + length;
-
-    maxchar = Py_MAX(maxchar, writer->min_char);
-
-    if (writer->buffer == NULL) {
-        assert(!writer->readonly);
-        if (writer->overallocate
-            && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
-            /* overallocate to limit the number of realloc() */
-            newlen += newlen / OVERALLOCATE_FACTOR;
-        }
-        if (newlen < writer->min_length)
-            newlen = writer->min_length;
-
-        writer->buffer = PyUnicode_New(newlen, maxchar);
-        if (writer->buffer == NULL)
-            return -1;
-    }
-    else if (newlen > writer->size) {
-        if (writer->overallocate
-            && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
-            /* overallocate to limit the number of realloc() */
-            newlen += newlen / OVERALLOCATE_FACTOR;
-        }
-        if (newlen < writer->min_length)
-            newlen = writer->min_length;
-
-        if (maxchar > writer->maxchar || writer->readonly) {
-            /* resize + widen */
-            newbuffer = PyUnicode_New(newlen, maxchar);
-            if (newbuffer == NULL)
-                return -1;
-            _PyUnicode_FastCopyCharacters(newbuffer, 0,
-                                          writer->buffer, 0, writer->pos);
-            Py_DECREF(writer->buffer);
-            writer->readonly = 0;
-        }
-        else {
-            newbuffer = resize_compact(writer->buffer, newlen);
-            if (newbuffer == NULL)
-                return -1;
-        }
-        writer->buffer = newbuffer;
-    }
-    else if (maxchar > writer->maxchar) {
-        assert(!writer->readonly);
-        newbuffer = PyUnicode_New(writer->size, maxchar);
-        if (newbuffer == NULL)
-            return -1;
-        _PyUnicode_FastCopyCharacters(newbuffer, 0,
-                                      writer->buffer, 0, writer->pos);
-        Py_DECREF(writer->buffer);
-        writer->buffer = newbuffer;
-    }
-    _PyUnicodeWriter_Update(writer);
-    return 0;
-
-#undef OVERALLOCATE_FACTOR
-}
-
-Py_LOCAL_INLINE(int)
-_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
-{
-    if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
-        return -1;
-    PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
-    writer->pos++;
-    return 0;
-}
-
-int
-_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
-{
-    return _PyUnicodeWriter_WriteCharInline(writer, ch);
-}
-
-int
-_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
-{
-    Py_UCS4 maxchar;
-    Py_ssize_t len;
-
-    if (PyUnicode_READY(str) == -1)
-        return -1;
-    len = PyUnicode_GET_LENGTH(str);
-    if (len == 0)
-        return 0;
-    maxchar = PyUnicode_MAX_CHAR_VALUE(str);
-    if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
-        if (writer->buffer == NULL && !writer->overallocate) {
-            assert(_PyUnicode_CheckConsistency(str, 1));
-            writer->readonly = 1;
-            Py_INCREF(str);
-            writer->buffer = str;
-            _PyUnicodeWriter_Update(writer);
-            writer->pos += len;
-            return 0;
-        }
-        if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
-            return -1;
-    }
-    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
-                                  str, 0, len);
-    writer->pos += len;
-    return 0;
-}
-
-int
-_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
-                                Py_ssize_t start, Py_ssize_t end)
-{
-    Py_UCS4 maxchar;
-    Py_ssize_t len;
-
-    if (PyUnicode_READY(str) == -1)
-        return -1;
-
-    assert(0 <= start);
-    assert(end <= PyUnicode_GET_LENGTH(str));
-    assert(start <= end);
-
-    if (end == 0)
-        return 0;
-
-    if (start == 0 && end == PyUnicode_GET_LENGTH(str))
-        return _PyUnicodeWriter_WriteStr(writer, str);
-
-    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
-        maxchar = _PyUnicode_FindMaxChar(str, start, end);
-    else
-        maxchar = writer->maxchar;
-    len = end - start;
-
-    if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
-        return -1;
-
-    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
-                                  str, start, len);
-    writer->pos += len;
-    return 0;
-}
-
-int
-_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
-                                  const char *ascii, Py_ssize_t len)
-{
-    if (len == -1)
-        len = strlen(ascii);
-
-    assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
-
-    if (writer->buffer == NULL && !writer->overallocate) {
-        PyObject *str;
-
-        str = _PyUnicode_FromASCII(ascii, len);
-        if (str == NULL)
-            return -1;
-
-        writer->readonly = 1;
-        writer->buffer = str;
-        _PyUnicodeWriter_Update(writer);
-        writer->pos += len;
-        return 0;
-    }
-
-    if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
-        return -1;
-
-    switch (writer->kind)
-    {
-    case PyUnicode_1BYTE_KIND:
-    {
-        const Py_UCS1 *str = (const Py_UCS1 *)ascii;
-        Py_UCS1 *data = writer->data;
-
-        Py_MEMCPY(data + writer->pos, str, len);
-        break;
-    }
-    case PyUnicode_2BYTE_KIND:
-    {
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS1, Py_UCS2,
-            ascii, ascii + len,
-            (Py_UCS2 *)writer->data + writer->pos);
-        break;
-    }
-    case PyUnicode_4BYTE_KIND:
-    {
-        _PyUnicode_CONVERT_BYTES(
-            Py_UCS1, Py_UCS4,
-            ascii, ascii + len,
-            (Py_UCS4 *)writer->data + writer->pos);
-        break;
-    }
-    default:
-        assert(0);
-    }
-
-    writer->pos += len;
-    return 0;
-}
-
-int
-_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
-                                   const char *str, Py_ssize_t len)
-{
-    Py_UCS4 maxchar;
-
-    maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
-    if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
-        return -1;
-    unicode_write_cstr(writer->buffer, writer->pos, str, len);
-    writer->pos += len;
-    return 0;
-}
-
-PyObject *
-_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
-{
-    PyObject *str;
-    if (writer->pos == 0) {
-        Py_CLEAR(writer->buffer);
-        _Py_RETURN_UNICODE_EMPTY();
-    }
-    if (writer->readonly) {
-        str = writer->buffer;
-        writer->buffer = NULL;
-        assert(PyUnicode_GET_LENGTH(str) == writer->pos);
-        return str;
-    }
-    if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
-        PyObject *newbuffer;
-        newbuffer = resize_compact(writer->buffer, writer->pos);
-        if (newbuffer == NULL) {
-            Py_CLEAR(writer->buffer);
-            return NULL;
-        }
-        writer->buffer = newbuffer;
-    }
-    str = writer->buffer;
-    writer->buffer = NULL;
-    assert(_PyUnicode_CheckConsistency(str, 1));
-    return unicode_result_ready(str);
-}
-
-void
-_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
-{
-    Py_CLEAR(writer->buffer);
-}
-
-#include "stringlib/unicode_format.h"
-
-PyDoc_STRVAR(format__doc__,
-             "S.format(*args, **kwargs) -> str\n\
-\n\
-Return a formatted version of S, using substitutions from args and kwargs.\n\
-The substitutions are identified by braces ('{' and '}').");
-
-PyDoc_STRVAR(format_map__doc__,
-             "S.format_map(mapping) -> str\n\
-\n\
-Return a formatted version of S, using substitutions from mapping.\n\
-The substitutions are identified by braces ('{' and '}').");
-
-static PyObject *
-unicode__format__(PyObject* self, PyObject* args)
-{
-    PyObject *format_spec;
-    _PyUnicodeWriter writer;
-    int ret;
-
-    if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
-        return NULL;
-
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-    _PyUnicodeWriter_Init(&writer);
-    ret = _PyUnicode_FormatAdvancedWriter(&writer,
-                                          self, format_spec, 0,
-                                          PyUnicode_GET_LENGTH(format_spec));
-    if (ret == -1) {
-        _PyUnicodeWriter_Dealloc(&writer);
-        return NULL;
-    }
-    return _PyUnicodeWriter_Finish(&writer);
-}
-
-PyDoc_STRVAR(p_format__doc__,
-             "S.__format__(format_spec) -> str\n\
-\n\
-Return a formatted version of S as described by format_spec.");
-
-static PyObject *
-unicode__sizeof__(PyObject *v)
-{
-    Py_ssize_t size;
-
-    /* If it's a compact object, account for base structure +
-       character data. */
-    if (PyUnicode_IS_COMPACT_ASCII(v))
-        size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
-    else if (PyUnicode_IS_COMPACT(v))
-        size = sizeof(PyCompactUnicodeObject) +
-            (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
-    else {
-        /* If it is a two-block object, account for base object, and
-           for character block if present. */
-        size = sizeof(PyUnicodeObject);
-        if (_PyUnicode_DATA_ANY(v))
-            size += (PyUnicode_GET_LENGTH(v) + 1) *
-                PyUnicode_KIND(v);
-    }
-    /* If the wstr pointer is present, account for it unless it is shared
-       with the data pointer. Check if the data is not shared. */
-    if (_PyUnicode_HAS_WSTR_MEMORY(v))
-        size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
-    if (_PyUnicode_HAS_UTF8_MEMORY(v))
-        size += PyUnicode_UTF8_LENGTH(v) + 1;
-
-    return PyLong_FromSsize_t(size);
-}
-
-PyDoc_STRVAR(sizeof__doc__,
-             "S.__sizeof__() -> size of S in memory, in bytes");
-
-static PyObject *
-unicode_getnewargs(PyObject *v)
-{
-    PyObject *copy = _PyUnicode_Copy(v);
-    if (!copy)
-        return NULL;
-    return Py_BuildValue("(N)", copy);
-}
-
-static PyMethodDef unicode_methods[] = {
-    {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
-    {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
-    {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
-    {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
-    {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
-    {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
-    {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
-    {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
-    {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
-    {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
-    {"expandtabs", (PyCFunction) unicode_expandtabs,
-     METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
-    {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
-    {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
-    {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
-    {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
-    {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
-    {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
-    {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
-    {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
-    {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
-    {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
-    {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
-    {"splitlines", (PyCFunction) unicode_splitlines,
-     METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
-    {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
-    {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
-    {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
-    {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
-    {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
-    {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
-    {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
-    {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
-    {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
-    {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
-    {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
-    {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
-    {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
-    {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
-    {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
-    {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
-    {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
-    {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
-    {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
-    {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
-    {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
-    UNICODE_MAKETRANS_METHODDEF
-    {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
-#if 0
-    /* These methods are just used for debugging the implementation. */
-    {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
-#endif
-
-    {"__getnewargs__",  (PyCFunction)unicode_getnewargs, METH_NOARGS},
-    {NULL, NULL}
-};
-
-static PyObject *
-unicode_mod(PyObject *v, PyObject *w)
-{
-    if (!PyUnicode_Check(v))
-        Py_RETURN_NOTIMPLEMENTED;
-    return PyUnicode_Format(v, w);
-}
-
-static PyNumberMethods unicode_as_number = {
-    0,              /*nb_add*/
-    0,              /*nb_subtract*/
-    0,              /*nb_multiply*/
-    unicode_mod,            /*nb_remainder*/
-};
-
-static PySequenceMethods unicode_as_sequence = {
-    (lenfunc) unicode_length,       /* sq_length */
-    PyUnicode_Concat,           /* sq_concat */
-    (ssizeargfunc) unicode_repeat,  /* sq_repeat */
-    (ssizeargfunc) unicode_getitem,     /* sq_item */
-    0,                  /* sq_slice */
-    0,                  /* sq_ass_item */
-    0,                  /* sq_ass_slice */
-    PyUnicode_Contains,         /* sq_contains */
-};
-
-static PyObject*
-unicode_subscript(PyObject* self, PyObject* item)
-{
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
-
-    if (PyIndex_Check(item)) {
-        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-        if (i == -1 && PyErr_Occurred())
-            return NULL;
-        if (i < 0)
-            i += PyUnicode_GET_LENGTH(self);
-        return unicode_getitem(self, i);
-    } else if (PySlice_Check(item)) {
-        Py_ssize_t start, stop, step, slicelength, cur, i;
-        PyObject *result;
-        void *src_data, *dest_data;
-        int src_kind, dest_kind;
-        Py_UCS4 ch, max_char, kind_limit;
-
-        if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
-                                 &start, &stop, &step, &slicelength) < 0) {
-            return NULL;
-        }
-
-        if (slicelength <= 0) {
-            _Py_RETURN_UNICODE_EMPTY();
-        } else if (start == 0 && step == 1 &&
-                   slicelength == PyUnicode_GET_LENGTH(self)) {
-            return unicode_result_unchanged(self);
-        } else if (step == 1) {
-            return PyUnicode_Substring(self,
-                                       start, start + slicelength);
-        }
-        /* General case */
-        src_kind = PyUnicode_KIND(self);
-        src_data = PyUnicode_DATA(self);
-        if (!PyUnicode_IS_ASCII(self)) {
-            kind_limit = kind_maxchar_limit(src_kind);
-            max_char = 0;
-            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
-                ch = PyUnicode_READ(src_kind, src_data, cur);
-                if (ch > max_char) {
-                    max_char = ch;
-                    if (max_char >= kind_limit)
-                        break;
-                }
-            }
-        }
-        else
-            max_char = 127;
-        result = PyUnicode_New(slicelength, max_char);
-        if (result == NULL)
-            return NULL;
-        dest_kind = PyUnicode_KIND(result);
-        dest_data = PyUnicode_DATA(result);
-
-        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
-            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
-            PyUnicode_WRITE(dest_kind, dest_data, i, ch);
-        }
-        assert(_PyUnicode_CheckConsistency(result, 1));
-        return result;
-    } else {
-        PyErr_SetString(PyExc_TypeError, "string indices must be integers");
-        return NULL;
-    }
-}
-
-static PyMappingMethods unicode_as_mapping = {
-    (lenfunc)unicode_length,        /* mp_length */
-    (binaryfunc)unicode_subscript,  /* mp_subscript */
-    (objobjargproc)0,           /* mp_ass_subscript */
-};
-
-
-/* Helpers for PyUnicode_Format() */
-
-struct unicode_formatter_t {
-    PyObject *args;
-    int args_owned;
-    Py_ssize_t arglen, argidx;
-    PyObject *dict;
-
-    enum PyUnicode_Kind fmtkind;
-    Py_ssize_t fmtcnt, fmtpos;
-    void *fmtdata;
-    PyObject *fmtstr;
-
-    _PyUnicodeWriter writer;
-};
-
-struct unicode_format_arg_t {
-    Py_UCS4 ch;
-    int flags;
-    Py_ssize_t width;
-    int prec;
-    int sign;
-};
-
-static PyObject *
-unicode_format_getnextarg(struct unicode_formatter_t *ctx)
-{
-    Py_ssize_t argidx = ctx->argidx;
-
-    if (argidx < ctx->arglen) {
-        ctx->argidx++;
-        if (ctx->arglen < 0)
-            return ctx->args;
-        else
-            return PyTuple_GetItem(ctx->args, argidx);
-    }
-    PyErr_SetString(PyExc_TypeError,
-                    "not enough arguments for format string");
-    return NULL;
-}
-
-/* Returns a new reference to a PyUnicode object, or NULL on failure. */
-
-/* Format a float into the writer if the writer is not NULL, or into *p_output
-   otherwise.
-
-   Return 0 on success, raise an exception and return -1 on error. */
-static int
-formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
-            PyObject **p_output,
-            _PyUnicodeWriter *writer)
-{
-    char *p;
-    double x;
-    Py_ssize_t len;
-    int prec;
-    int dtoa_flags;
-
-    x = PyFloat_AsDouble(v);
-    if (x == -1.0 && PyErr_Occurred())
-        return -1;
-
-    prec = arg->prec;
-    if (prec < 0)
-        prec = 6;
-
-    if (arg->flags & F_ALT)
-        dtoa_flags = Py_DTSF_ALT;
-    else
-        dtoa_flags = 0;
-    p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
-    if (p == NULL)
-        return -1;
-    len = strlen(p);
-    if (writer) {
-        if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
-            PyMem_Free(p);
-            return -1;
-        }
-    }
-    else
-        *p_output = _PyUnicode_FromASCII(p, len);
-    PyMem_Free(p);
-    return 0;
-}
-
-/* formatlong() emulates the format codes d, u, o, x and X, and
- * the F_ALT flag, for Python's long (unbounded) ints.  It's not used for
- * Python's regular ints.
- * Return value:  a new PyUnicodeObject*, or NULL if error.
- *     The output string is of the form
- *         "-"? ("0x" | "0X")? digit+
- *     "0x"/"0X" are present only for x and X conversions, with F_ALT
- *         set in flags.  The case of hex digits will be correct,
- *     There will be at least prec digits, zero-filled on the left if
- *         necessary to get that many.
- * val          object to be converted
- * flags        bitmask of format flags; only F_ALT is looked at
- * prec         minimum number of digits; 0-fill on left if needed
- * type         a character in [duoxX]; u acts the same as d
- *
- * CAUTION:  o, x and X conversions on regular ints can never
- * produce a '-' sign, but can for Python's unbounded ints.
- */
-PyObject *
-_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
-{
-    PyObject *result = NULL;
-    char *buf;
-    Py_ssize_t i;
-    int sign;           /* 1 if '-', else 0 */
-    int len;            /* number of characters */
-    Py_ssize_t llen;
-    int numdigits;      /* len == numnondigits + numdigits */
-    int numnondigits = 0;
-
-    /* Avoid exceeding SSIZE_T_MAX */
-    if (prec > INT_MAX-3) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "precision too large");
-        return NULL;
-    }
-
-    assert(PyLong_Check(val));
-
-    switch (type) {
-    default:
-        assert(!"'type' not in [diuoxX]");
-    case 'd':
-    case 'i':
-    case 'u':
-        /* int and int subclasses should print numerically when a numeric */
-        /* format code is used (see issue18780) */
-        result = PyNumber_ToBase(val, 10);
-        break;
-    case 'o':
-        numnondigits = 2;
-        result = PyNumber_ToBase(val, 8);
-        break;
-    case 'x':
-    case 'X':
-        numnondigits = 2;
-        result = PyNumber_ToBase(val, 16);
-        break;
-    }
-    if (!result)
-        return NULL;
-
-    assert(unicode_modifiable(result));
-    assert(PyUnicode_IS_READY(result));
-    assert(PyUnicode_IS_ASCII(result));
-
-    /* To modify the string in-place, there can only be one reference. */
-    if (Py_REFCNT(result) != 1) {
-        Py_DECREF(result);
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    buf = PyUnicode_DATA(result);
-    llen = PyUnicode_GET_LENGTH(result);
-    if (llen > INT_MAX) {
-        Py_DECREF(result);
-        PyErr_SetString(PyExc_ValueError,
-                        "string too large in _PyUnicode_FormatLong");
-        return NULL;
-    }
-    len = (int)llen;
-    sign = buf[0] == '-';
-    numnondigits += sign;
-    numdigits = len - numnondigits;
-    assert(numdigits > 0);
-
-    /* Get rid of base marker unless F_ALT */
-    if (((alt) == 0 &&
-        (type == 'o' || type == 'x' || type == 'X'))) {
-        assert(buf[sign] == '0');
-        assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
-               buf[sign+1] == 'o');
-        numnondigits -= 2;
-        buf += 2;
-        len -= 2;
-        if (sign)
-            buf[0] = '-';
-        assert(len == numnondigits + numdigits);
-        assert(numdigits > 0);
-    }
-
-    /* Fill with leading zeroes to meet minimum width. */
-    if (prec > numdigits) {
-        PyObject *r1 = PyBytes_FromStringAndSize(NULL,
-                                numnondigits + prec);
-        char *b1;
-        if (!r1) {
-            Py_DECREF(result);
-            return NULL;
-        }
-        b1 = PyBytes_AS_STRING(r1);
-        for (i = 0; i < numnondigits; ++i)
-            *b1++ = *buf++;
-        for (i = 0; i < prec - numdigits; i++)
-            *b1++ = '0';
-        for (i = 0; i < numdigits; i++)
-            *b1++ = *buf++;
-        *b1 = '\0';
-        Py_DECREF(result);
-        result = r1;
-        buf = PyBytes_AS_STRING(result);
-        len = numnondigits + prec;
-    }
-
-    /* Fix up case for hex conversions. */
-    if (type == 'X') {
-        /* Need to convert all lower case letters to upper case.
-           and need to convert 0x to 0X (and -0x to -0X). */
-        for (i = 0; i < len; i++)
-            if (buf[i] >= 'a' && buf[i] <= 'x')
-                buf[i] -= 'a'-'A';
-    }
-    if (!PyUnicode_Check(result)
-        || buf != PyUnicode_DATA(result)) {
-        PyObject *unicode;
-        unicode = _PyUnicode_FromASCII(buf, len);
-        Py_DECREF(result);
-        result = unicode;
-    }
-    else if (len != PyUnicode_GET_LENGTH(result)) {
-        if (PyUnicode_Resize(&result, len) < 0)
-            Py_CLEAR(result);
-    }
-    return result;
-}
-
-/* Format an integer or a float as an integer.
- * Return 1 if the number has been formatted into the writer,
- *        0 if the number has been formatted into *p_output
- *       -1 and raise an exception on error */
-static int
-mainformatlong(PyObject *v,
-               struct unicode_format_arg_t *arg,
-               PyObject **p_output,
-               _PyUnicodeWriter *writer)
-{
-    PyObject *iobj, *res;
-    char type = (char)arg->ch;
-
-    if (!PyNumber_Check(v))
-        goto wrongtype;
-
-    /* make sure number is a type of integer for o, x, and X */
-    if (!PyLong_Check(v)) {
-        if (type == 'o' || type == 'x' || type == 'X') {
-            iobj = PyNumber_Index(v);
-            if (iobj == NULL) {
-                if (PyErr_ExceptionMatches(PyExc_TypeError))
-                    goto wrongtype;
-                return -1;
-            }
-        }
-        else {
-            iobj = PyNumber_Long(v);
-            if (iobj == NULL ) {
-                if (PyErr_ExceptionMatches(PyExc_TypeError))
-                    goto wrongtype;
-                return -1;
-            }
-        }
-        assert(PyLong_Check(iobj));
-    }
-    else {
-        iobj = v;
-        Py_INCREF(iobj);
-    }
-
-    if (PyLong_CheckExact(v)
-        && arg->width == -1 && arg->prec == -1
-        && !(arg->flags & (F_SIGN | F_BLANK))
-        && type != 'X')
-    {
-        /* Fast path */
-        int alternate = arg->flags & F_ALT;
-        int base;
-
-        switch(type)
-        {
-            default:
-                assert(0 && "'type' not in [diuoxX]");
-            case 'd':
-            case 'i':
-            case 'u':
-                base = 10;
-                break;
-            case 'o':
-                base = 8;
-                break;
-            case 'x':
-            case 'X':
-                base = 16;
-                break;
-        }
-
-        if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
-            Py_DECREF(iobj);
-            return -1;
-        }
-        Py_DECREF(iobj);
-        return 1;
-    }
-
-    res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
-    Py_DECREF(iobj);
-    if (res == NULL)
-        return -1;
-    *p_output = res;
-    return 0;
-
-wrongtype:
-    switch(type)
-    {
-        case 'o':
-        case 'x':
-        case 'X':
-            PyErr_Format(PyExc_TypeError,
-                    "%%%c format: an integer is required, "
-                    "not %.200s",
-                    type, Py_TYPE(v)->tp_name);
-            break;
-        default:
-            PyErr_Format(PyExc_TypeError,
-                    "%%%c format: a number is required, "
-                    "not %.200s",
-                    type, Py_TYPE(v)->tp_name);
-            break;
-    }
-    return -1;
-}
-
-static Py_UCS4
-formatchar(PyObject *v)
-{
-    /* presume that the buffer is at least 3 characters long */
-    if (PyUnicode_Check(v)) {
-        if (PyUnicode_GET_LENGTH(v) == 1) {
-            return PyUnicode_READ_CHAR(v, 0);
-        }
-        goto onError;
-    }
-    else {
-        PyObject *iobj;
-        long x;
-        /* make sure number is a type of integer */
-        if (!PyLong_Check(v)) {
-            iobj = PyNumber_Index(v);
-            if (iobj == NULL) {
-                goto onError;
-            }
-            v = iobj;
-            Py_DECREF(iobj);
-        }
-        /* Integer input truncated to a character */
-        x = PyLong_AsLong(v);
-        if (x == -1 && PyErr_Occurred())
-            goto onError;
-
-        if (x < 0 || x > MAX_UNICODE) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "%c arg not in range(0x110000)");
-            return (Py_UCS4) -1;
-        }
-
-        return (Py_UCS4) x;
-    }
-
-  onError:
-    PyErr_SetString(PyExc_TypeError,
-                    "%c requires int or char");
-    return (Py_UCS4) -1;
-}
-
-/* Parse options of an argument: flags, width, precision.
-   Handle also "%(name)" syntax.
-
-   Return 0 if the argument has been formatted into arg->str.
-   Return 1 if the argument has been written into ctx->writer,
-   Raise an exception and return -1 on error. */
-static int
-unicode_format_arg_parse(struct unicode_formatter_t *ctx,
-                         struct unicode_format_arg_t *arg)
-{
-#define FORMAT_READ(ctx) \
-        PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
-
-    PyObject *v;
-
-    if (arg->ch == '(') {
-        /* Get argument value from a dictionary. Example: "%(name)s". */
-        Py_ssize_t keystart;
-        Py_ssize_t keylen;
-        PyObject *key;
-        int pcount = 1;
-
-        if (ctx->dict == NULL) {
-            PyErr_SetString(PyExc_TypeError,
-                            "format requires a mapping");
-            return -1;
-        }
-        ++ctx->fmtpos;
-        --ctx->fmtcnt;
-        keystart = ctx->fmtpos;
-        /* Skip over balanced parentheses */
-        while (pcount > 0 && --ctx->fmtcnt >= 0) {
-            arg->ch = FORMAT_READ(ctx);
-            if (arg->ch == ')')
-                --pcount;
-            else if (arg->ch == '(')
-                ++pcount;
-            ctx->fmtpos++;
-        }
-        keylen = ctx->fmtpos - keystart - 1;
-        if (ctx->fmtcnt < 0 || pcount > 0) {
-            PyErr_SetString(PyExc_ValueError,
-                            "incomplete format key");
-            return -1;
-        }
-        key = PyUnicode_Substring(ctx->fmtstr,
-                                  keystart, keystart + keylen);
-        if (key == NULL)
-            return -1;
-        if (ctx->args_owned) {
-            Py_DECREF(ctx->args);
-            ctx->args_owned = 0;
-        }
-        ctx->args = PyObject_GetItem(ctx->dict, key);
-        Py_DECREF(key);
-        if (ctx->args == NULL)
-            return -1;
-        ctx->args_owned = 1;
-        ctx->arglen = -1;
-        ctx->argidx = -2;
-    }
-
-    /* Parse flags. Example: "%+i" => flags=F_SIGN. */
-    while (--ctx->fmtcnt >= 0) {
-        arg->ch = FORMAT_READ(ctx);
-        ctx->fmtpos++;
-        switch (arg->ch) {
-        case '-': arg->flags |= F_LJUST; continue;
-        case '+': arg->flags |= F_SIGN; continue;
-        case ' ': arg->flags |= F_BLANK; continue;
-        case '#': arg->flags |= F_ALT; continue;
-        case '0': arg->flags |= F_ZERO; continue;
-        }
-        break;
-    }
-
-    /* Parse width. Example: "%10s" => width=10 */
-    if (arg->ch == '*') {
-        v = unicode_format_getnextarg(ctx);
-        if (v == NULL)
-            return -1;
-        if (!PyLong_Check(v)) {
-            PyErr_SetString(PyExc_TypeError,
-                            "* wants int");
-            return -1;
-        }
-        arg->width = PyLong_AsSsize_t(v);
-        if (arg->width == -1 && PyErr_Occurred())
-            return -1;
-        if (arg->width < 0) {
-            arg->flags |= F_LJUST;
-            arg->width = -arg->width;
-        }
-        if (--ctx->fmtcnt >= 0) {
-            arg->ch = FORMAT_READ(ctx);
-            ctx->fmtpos++;
-        }
-    }
-    else if (arg->ch >= '0' && arg->ch <= '9') {
-        arg->width = arg->ch - '0';
-        while (--ctx->fmtcnt >= 0) {
-            arg->ch = FORMAT_READ(ctx);
-            ctx->fmtpos++;
-            if (arg->ch < '0' || arg->ch > '9')
-                break;
-            /* Since arg->ch is unsigned, the RHS would end up as unsigned,
-               mixing signed and unsigned comparison. Since arg->ch is between
-               '0' and '9', casting to int is safe. */
-            if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
-                PyErr_SetString(PyExc_ValueError,
-                                "width too big");
-                return -1;
-            }
-            arg->width = arg->width*10 + (arg->ch - '0');
-        }
-    }
-
-    /* Parse precision. Example: "%.3f" => prec=3 */
-    if (arg->ch == '.') {
-        arg->prec = 0;
-        if (--ctx->fmtcnt >= 0) {
-            arg->ch = FORMAT_READ(ctx);
-            ctx->fmtpos++;
-        }
-        if (arg->ch == '*') {
-            v = unicode_format_getnextarg(ctx);
-            if (v == NULL)
-                return -1;
-            if (!PyLong_Check(v)) {
-                PyErr_SetString(PyExc_TypeError,
-                                "* wants int");
-                return -1;
-            }
-            arg->prec = _PyLong_AsInt(v);
-            if (arg->prec == -1 && PyErr_Occurred())
-                return -1;
-            if (arg->prec < 0)
-                arg->prec = 0;
-            if (--ctx->fmtcnt >= 0) {
-                arg->ch = FORMAT_READ(ctx);
-                ctx->fmtpos++;
-            }
-        }
-        else if (arg->ch >= '0' && arg->ch <= '9') {
-            arg->prec = arg->ch - '0';
-            while (--ctx->fmtcnt >= 0) {
-                arg->ch = FORMAT_READ(ctx);
-                ctx->fmtpos++;
-                if (arg->ch < '0' || arg->ch > '9')
-                    break;
-                if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
-                    PyErr_SetString(PyExc_ValueError,
-                                    "precision too big");
-                    return -1;
-                }
-                arg->prec = arg->prec*10 + (arg->ch - '0');
-            }
-        }
-    }
-
-    /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
-    if (ctx->fmtcnt >= 0) {
-        if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
-            if (--ctx->fmtcnt >= 0) {
-                arg->ch = FORMAT_READ(ctx);
-                ctx->fmtpos++;
-            }
-        }
-    }
-    if (ctx->fmtcnt < 0) {
-        PyErr_SetString(PyExc_ValueError,
-                        "incomplete format");
-        return -1;
-    }
-    return 0;
-
-#undef FORMAT_READ
-}
-
-/* Format one argument. Supported conversion specifiers:
-
-   - "s", "r", "a": any type
-   - "i", "d", "u": int or float
-   - "o", "x", "X": int
-   - "e", "E", "f", "F", "g", "G": float
-   - "c": int or str (1 character)
-
-   When possible, the output is written directly into the Unicode writer
-   (ctx->writer). A string is created when padding is required.
-
-   Return 0 if the argument has been formatted into *p_str,
-          1 if the argument has been written into ctx->writer,
-         -1 on error. */
-static int
-unicode_format_arg_format(struct unicode_formatter_t *ctx,
-                          struct unicode_format_arg_t *arg,
-                          PyObject **p_str)
-{
-    PyObject *v;
-    _PyUnicodeWriter *writer = &ctx->writer;
-
-    if (ctx->fmtcnt == 0)
-        ctx->writer.overallocate = 0;
-
-    if (arg->ch == '%') {
-        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
-            return -1;
-        return 1;
-    }
-
-    v = unicode_format_getnextarg(ctx);
-    if (v == NULL)
-        return -1;
-
-
-    switch (arg->ch) {
-    case 's':
-    case 'r':
-    case 'a':
-        if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
-            /* Fast path */
-            if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
-                return -1;
-            return 1;
-        }
-
-        if (PyUnicode_CheckExact(v) && arg->ch == 's') {
-            *p_str = v;
-            Py_INCREF(*p_str);
-        }
-        else {
-            if (arg->ch == 's')
-                *p_str = PyObject_Str(v);
-            else if (arg->ch == 'r')
-                *p_str = PyObject_Repr(v);
-            else
-                *p_str = PyObject_ASCII(v);
-        }
-        break;
-
-    case 'i':
-    case 'd':
-    case 'u':
-    case 'o':
-    case 'x':
-    case 'X':
-    {
-        int ret = mainformatlong(v, arg, p_str, writer);
-        if (ret != 0)
-            return ret;
-        arg->sign = 1;
-        break;
-    }
-
-    case 'e':
-    case 'E':
-    case 'f':
-    case 'F':
-    case 'g':
-    case 'G':
-        if (arg->width == -1 && arg->prec == -1
-            && !(arg->flags & (F_SIGN | F_BLANK)))
-        {
-            /* Fast path */
-            if (formatfloat(v, arg, NULL, writer) == -1)
-                return -1;
-            return 1;
-        }
-
-        arg->sign = 1;
-        if (formatfloat(v, arg, p_str, NULL) == -1)
-            return -1;
-        break;
-
-    case 'c':
-    {
-        Py_UCS4 ch = formatchar(v);
-        if (ch == (Py_UCS4) -1)
-            return -1;
-        if (arg->width == -1 && arg->prec == -1) {
-            /* Fast path */
-            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
-                return -1;
-            return 1;
-        }
-        *p_str = PyUnicode_FromOrdinal(ch);
-        break;
-    }
-
-    default:
-        PyErr_Format(PyExc_ValueError,
-                     "unsupported format character '%c' (0x%x) "
-                     "at index %zd",
-                     (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
-                     (int)arg->ch,
-                     ctx->fmtpos - 1);
-        return -1;
-    }
-    if (*p_str == NULL)
-        return -1;
-    assert (PyUnicode_Check(*p_str));
-    return 0;
-}
-
-static int
-unicode_format_arg_output(struct unicode_formatter_t *ctx,
-                          struct unicode_format_arg_t *arg,
-                          PyObject *str)
-{
-    Py_ssize_t len;
-    enum PyUnicode_Kind kind;
-    void *pbuf;
-    Py_ssize_t pindex;
-    Py_UCS4 signchar;
-    Py_ssize_t buflen;
-    Py_UCS4 maxchar;
-    Py_ssize_t sublen;
-    _PyUnicodeWriter *writer = &ctx->writer;
-    Py_UCS4 fill;
-
-    fill = ' ';
-    if (arg->sign && arg->flags & F_ZERO)
-        fill = '0';
-
-    if (PyUnicode_READY(str) == -1)
-        return -1;
-
-    len = PyUnicode_GET_LENGTH(str);
-    if ((arg->width == -1 || arg->width <= len)
-        && (arg->prec == -1 || arg->prec >= len)
-        && !(arg->flags & (F_SIGN | F_BLANK)))
-    {
-        /* Fast path */
-        if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
-            return -1;
-        return 0;
-    }
-
-    /* Truncate the string for "s", "r" and "a" formats
-       if the precision is set */
-    if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
-        if (arg->prec >= 0 && len > arg->prec)
-            len = arg->prec;
-    }
-
-    /* Adjust sign and width */
-    kind = PyUnicode_KIND(str);
-    pbuf = PyUnicode_DATA(str);
-    pindex = 0;
-    signchar = '\0';
-    if (arg->sign) {
-        Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
-        if (ch == '-' || ch == '+') {
-            signchar = ch;
-            len--;
-            pindex++;
-        }
-        else if (arg->flags & F_SIGN)
-            signchar = '+';
-        else if (arg->flags & F_BLANK)
-            signchar = ' ';
-        else
-            arg->sign = 0;
-    }
-    if (arg->width < len)
-        arg->width = len;
-
-    /* Prepare the writer */
-    maxchar = writer->maxchar;
-    if (!(arg->flags & F_LJUST)) {
-        if (arg->sign) {
-            if ((arg->width-1) > len)
-                maxchar = Py_MAX(maxchar, fill);
-        }
-        else {
-            if (arg->width > len)
-                maxchar = Py_MAX(maxchar, fill);
-        }
-    }
-    if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
-        Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
-        maxchar = Py_MAX(maxchar, strmaxchar);
-    }
-
-    buflen = arg->width;
-    if (arg->sign && len == arg->width)
-        buflen++;
-    if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
-        return -1;
-
-    /* Write the sign if needed */
-    if (arg->sign) {
-        if (fill != ' ') {
-            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
-            writer->pos += 1;
-        }
-        if (arg->width > len)
-            arg->width--;
-    }
-
-    /* Write the numeric prefix for "x", "X" and "o" formats
-       if the alternate form is used.
-       For example, write "0x" for the "%#x" format. */
-    if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
-        assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
-        assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
-        if (fill != ' ') {
-            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
-            PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
-            writer->pos += 2;
-            pindex += 2;
-        }
-        arg->width -= 2;
-        if (arg->width < 0)
-            arg->width = 0;
-        len -= 2;
-    }
-
-    /* Pad left with the fill character if needed */
-    if (arg->width > len && !(arg->flags & F_LJUST)) {
-        sublen = arg->width - len;
-        FILL(writer->kind, writer->data, fill, writer->pos, sublen);
-        writer->pos += sublen;
-        arg->width = len;
-    }
-
-    /* If padding with spaces: write sign if needed and/or numeric prefix if
-       the alternate form is used */
-    if (fill == ' ') {
-        if (arg->sign) {
-            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
-            writer->pos += 1;
-        }
-        if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
-            assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
-            assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
-            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
-            PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
-            writer->pos += 2;
-            pindex += 2;
-        }
-    }
-
-    /* Write characters */
-    if (len) {
-        _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
-                                      str, pindex, len);
-        writer->pos += len;
-    }
-
-    /* Pad right with the fill character if needed */
-    if (arg->width > len) {
-        sublen = arg->width - len;
-        FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
-        writer->pos += sublen;
-    }
-    return 0;
-}
-
-/* Helper of PyUnicode_Format(): format one arg.
-   Return 0 on success, raise an exception and return -1 on error. */
-static int
-unicode_format_arg(struct unicode_formatter_t *ctx)
-{
-    struct unicode_format_arg_t arg;
-    PyObject *str;
-    int ret;
-
-    arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
-    arg.flags = 0;
-    arg.width = -1;
-    arg.prec = -1;
-    arg.sign = 0;
-    str = NULL;
-
-    ret = unicode_format_arg_parse(ctx, &arg);
-    if (ret == -1)
-        return -1;
-
-    ret = unicode_format_arg_format(ctx, &arg, &str);
-    if (ret == -1)
-        return -1;
-
-    if (ret != 1) {
-        ret = unicode_format_arg_output(ctx, &arg, str);
-        Py_DECREF(str);
-        if (ret == -1)
-            return -1;
-    }
-
-    if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
-        PyErr_SetString(PyExc_TypeError,
-                        "not all arguments converted during string formatting");
-        return -1;
-    }
-    return 0;
-}
-
-PyObject *
-PyUnicode_Format(PyObject *format, PyObject *args)
-{
-    struct unicode_formatter_t ctx;
-
-    if (format == NULL || args == NULL) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-
-    ctx.fmtstr = PyUnicode_FromObject(format);
-    if (ctx.fmtstr == NULL)
-        return NULL;
-    if (PyUnicode_READY(ctx.fmtstr) == -1) {
-        Py_DECREF(ctx.fmtstr);
-        return NULL;
-    }
-    ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
-    ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
-    ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
-    ctx.fmtpos = 0;
-
-    _PyUnicodeWriter_Init(&ctx.writer);
-    ctx.writer.min_length = ctx.fmtcnt + 100;
-    ctx.writer.overallocate = 1;
-
-    if (PyTuple_Check(args)) {
-        ctx.arglen = PyTuple_Size(args);
-        ctx.argidx = 0;
-    }
-    else {
-        ctx.arglen = -1;
-        ctx.argidx = -2;
-    }
-    ctx.args_owned = 0;
-    if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
-        ctx.dict = args;
-    else
-        ctx.dict = NULL;
-    ctx.args = args;
-
-    while (--ctx.fmtcnt >= 0) {
-        if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
-            Py_ssize_t nonfmtpos;
-
-            nonfmtpos = ctx.fmtpos++;
-            while (ctx.fmtcnt >= 0 &&
-                   PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
-                ctx.fmtpos++;
-                ctx.fmtcnt--;
-            }
-            if (ctx.fmtcnt < 0) {
-                ctx.fmtpos--;
-                ctx.writer.overallocate = 0;
-            }
-
-            if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
-                                                nonfmtpos, ctx.fmtpos) < 0)
-                goto onError;
-        }
-        else {
-            ctx.fmtpos++;
-            if (unicode_format_arg(&ctx) == -1)
-                goto onError;
-        }
-    }
-
-    if (ctx.argidx < ctx.arglen && !ctx.dict) {
-        PyErr_SetString(PyExc_TypeError,
-                        "not all arguments converted during string formatting");
-        goto onError;
-    }
-
-    if (ctx.args_owned) {
-        Py_DECREF(ctx.args);
-    }
-    Py_DECREF(ctx.fmtstr);
-    return _PyUnicodeWriter_Finish(&ctx.writer);
-
-  onError:
-    Py_DECREF(ctx.fmtstr);
-    _PyUnicodeWriter_Dealloc(&ctx.writer);
-    if (ctx.args_owned) {
-        Py_DECREF(ctx.args);
-    }
-    return NULL;
-}
-
-static PyObject *
-unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
-
-static PyObject *
-unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *x = NULL;
-    static char *kwlist[] = {"object", "encoding", "errors", 0};
-    char *encoding = NULL;
-    char *errors = NULL;
-
-    if (type != &PyUnicode_Type)
-        return unicode_subtype_new(type, args, kwds);
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
-                                     kwlist, &x, &encoding, &errors))
-        return NULL;
-    if (x == NULL)
-        _Py_RETURN_UNICODE_EMPTY();
-    if (encoding == NULL && errors == NULL)
-        return PyObject_Str(x);
-    else
-        return PyUnicode_FromEncodedObject(x, encoding, errors);
-}
-
-static PyObject *
-unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *unicode, *self;
-    Py_ssize_t length, char_size;
-    int share_wstr, share_utf8;
-    unsigned int kind;
-    void *data;
-
-    assert(PyType_IsSubtype(type, &PyUnicode_Type));
-
-    unicode = unicode_new(&PyUnicode_Type, args, kwds);
-    if (unicode == NULL)
-        return NULL;
-    assert(_PyUnicode_CHECK(unicode));
-    if (PyUnicode_READY(unicode) == -1) {
-        Py_DECREF(unicode);
-        return NULL;
-    }
-
-    self = type->tp_alloc(type, 0);
-    if (self == NULL) {
-        Py_DECREF(unicode);
-        return NULL;
-    }
-    kind = PyUnicode_KIND(unicode);
-    length = PyUnicode_GET_LENGTH(unicode);
-
-    _PyUnicode_LENGTH(self) = length;
-#ifdef Py_DEBUG
-    _PyUnicode_HASH(self) = -1;
-#else
-    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
-#endif
-    _PyUnicode_STATE(self).interned = 0;
-    _PyUnicode_STATE(self).kind = kind;
-    _PyUnicode_STATE(self).compact = 0;
-    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
-    _PyUnicode_STATE(self).ready = 1;
-    _PyUnicode_WSTR(self) = NULL;
-    _PyUnicode_UTF8_LENGTH(self) = 0;
-    _PyUnicode_UTF8(self) = NULL;
-    _PyUnicode_WSTR_LENGTH(self) = 0;
-    _PyUnicode_DATA_ANY(self) = NULL;
-
-    share_utf8 = 0;
-    share_wstr = 0;
-    if (kind == PyUnicode_1BYTE_KIND) {
-        char_size = 1;
-        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
-            share_utf8 = 1;
-    }
-    else if (kind == PyUnicode_2BYTE_KIND) {
-        char_size = 2;
-        if (sizeof(wchar_t) == 2)
-            share_wstr = 1;
-    }
-    else {
-        assert(kind == PyUnicode_4BYTE_KIND);
-        char_size = 4;
-        if (sizeof(wchar_t) == 4)
-            share_wstr = 1;
-    }
-
-    /* Ensure we won't overflow the length. */
-    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
-        PyErr_NoMemory();
-        goto onError;
-    }
-    data = PyObject_MALLOC((length + 1) * char_size);
-    if (data == NULL) {
-        PyErr_NoMemory();
-        goto onError;
-    }
-
-    _PyUnicode_DATA_ANY(self) = data;
-    if (share_utf8) {
-        _PyUnicode_UTF8_LENGTH(self) = length;
-        _PyUnicode_UTF8(self) = data;
-    }
-    if (share_wstr) {
-        _PyUnicode_WSTR_LENGTH(self) = length;
-        _PyUnicode_WSTR(self) = (wchar_t *)data;
-    }
-
-    Py_MEMCPY(data, PyUnicode_DATA(unicode),
-              kind * (length + 1));
-    assert(_PyUnicode_CheckConsistency(self, 1));
-#ifdef Py_DEBUG
-    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
-#endif
-    Py_DECREF(unicode);
-    return self;
-
-onError:
-    Py_DECREF(unicode);
-    Py_DECREF(self);
-    return NULL;
-}
-
-PyDoc_STRVAR(unicode_doc,
-"str(object='') -> str\n\
-str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
-\n\
-Create a new string object from the given object. If encoding or\n\
-errors is specified, then the object must expose a data buffer\n\
-that will be decoded using the given encoding and error handler.\n\
-Otherwise, returns the result of object.__str__() (if defined)\n\
-or repr(object).\n\
-encoding defaults to sys.getdefaultencoding().\n\
-errors defaults to 'strict'.");
-
-static PyObject *unicode_iter(PyObject *seq);
-
-PyTypeObject PyUnicode_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "str",              /* tp_name */
-    sizeof(PyUnicodeObject),        /* tp_size */
-    0,                  /* tp_itemsize */
-    /* Slots */
-    (destructor)unicode_dealloc,    /* tp_dealloc */
-    0,                  /* tp_print */
-    0,                  /* tp_getattr */
-    0,                  /* tp_setattr */
-    0,                  /* tp_reserved */
-    unicode_repr,           /* tp_repr */
-    &unicode_as_number,         /* tp_as_number */
-    &unicode_as_sequence,       /* tp_as_sequence */
-    &unicode_as_mapping,        /* tp_as_mapping */
-    (hashfunc) unicode_hash,        /* tp_hash*/
-    0,                  /* tp_call*/
-    (reprfunc) unicode_str,     /* tp_str */
-    PyObject_GenericGetAttr,        /* tp_getattro */
-    0,                  /* tp_setattro */
-    0,                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
-    Py_TPFLAGS_UNICODE_SUBCLASS,    /* tp_flags */
-    unicode_doc,            /* tp_doc */
-    0,                  /* tp_traverse */
-    0,                  /* tp_clear */
-    PyUnicode_RichCompare,      /* tp_richcompare */
-    0,                  /* tp_weaklistoffset */
-    unicode_iter,           /* tp_iter */
-    0,                  /* tp_iternext */
-    unicode_methods,            /* tp_methods */
-    0,                  /* tp_members */
-    0,                  /* tp_getset */
-    &PyBaseObject_Type,         /* tp_base */
-    0,                  /* tp_dict */
-    0,                  /* tp_descr_get */
-    0,                  /* tp_descr_set */
-    0,                  /* tp_dictoffset */
-    0,                  /* tp_init */
-    0,                  /* tp_alloc */
-    unicode_new,            /* tp_new */
-    PyObject_Del,           /* tp_free */
-};
-
-/* Initialize the Unicode implementation */
-
-int _PyUnicode_Init(void)
-{
-    /* XXX - move this array to unicodectype.c ? */
-    Py_UCS2 linebreak[] = {
-        0x000A, /* LINE FEED */
-        0x000D, /* CARRIAGE RETURN */
-        0x001C, /* FILE SEPARATOR */
-        0x001D, /* GROUP SEPARATOR */
-        0x001E, /* RECORD SEPARATOR */
-        0x0085, /* NEXT LINE */
-        0x2028, /* LINE SEPARATOR */
-        0x2029, /* PARAGRAPH SEPARATOR */
-    };
-
-    /* Init the implementation */
-    _Py_INCREF_UNICODE_EMPTY();
-    if (!unicode_empty)
-        Py_FatalError("Can't create empty string");
-    Py_DECREF(unicode_empty);
-
-    if (PyType_Ready(&PyUnicode_Type) < 0)
-        Py_FatalError("Can't initialize 'unicode'");
-
-    /* initialize the linebreak bloom filter */
-    bloom_linebreak = make_bloom_mask(
-        PyUnicode_2BYTE_KIND, linebreak,
-        Py_ARRAY_LENGTH(linebreak));
-
-    if (PyType_Ready(&EncodingMapType) < 0)
-         Py_FatalError("Can't initialize encoding map type");
-
-    if (PyType_Ready(&PyFieldNameIter_Type) < 0)
-        Py_FatalError("Can't initialize field name iterator type");
-
-    if (PyType_Ready(&PyFormatterIter_Type) < 0)
-        Py_FatalError("Can't initialize formatter iter type");
-
-    return 0;
-}
-
-/* Finalize the Unicode implementation */
-
-int
-PyUnicode_ClearFreeList(void)
-{
-    return 0;
-}
-
-void
-_PyUnicode_Fini(void)
-{
-    int i;
-
-    Py_CLEAR(unicode_empty);
-
-    for (i = 0; i < 256; i++)
-        Py_CLEAR(unicode_latin1[i]);
-    _PyUnicode_ClearStaticStrings();
-    (void)PyUnicode_ClearFreeList();
-}
-
-void
-PyUnicode_InternInPlace(PyObject **p)
-{
-    PyObject *s = *p;
-    PyObject *t;
-#ifdef Py_DEBUG
-    assert(s != NULL);
-    assert(_PyUnicode_CHECK(s));
-#else
-    if (s == NULL || !PyUnicode_Check(s))
-        return;
-#endif
-    /* If it's a subclass, we don't really know what putting
-       it in the interned dict might do. */
-    if (!PyUnicode_CheckExact(s))
-        return;
-    if (PyUnicode_CHECK_INTERNED(s))
-        return;
-    if (interned == NULL) {
-        interned = PyDict_New();
-        if (interned == NULL) {
-            PyErr_Clear(); /* Don't leave an exception */
-            return;
-        }
-    }
-    /* It might be that the GetItem call fails even
-       though the key is present in the dictionary,
-       namely when this happens during a stack overflow. */
-    Py_ALLOW_RECURSION
-    t = PyDict_GetItem(interned, s);
-    Py_END_ALLOW_RECURSION
-
-    if (t) {
-        Py_INCREF(t);
-        Py_DECREF(*p);
-        *p = t;
-        return;
-    }
-
-    PyThreadState_GET()->recursion_critical = 1;
-    if (PyDict_SetItem(interned, s, s) < 0) {
-        PyErr_Clear();
-        PyThreadState_GET()->recursion_critical = 0;
-        return;
-    }
-    PyThreadState_GET()->recursion_critical = 0;
-    /* The two references in interned are not counted by refcnt.
-       The deallocator will take care of this */
-    Py_REFCNT(s) -= 2;
-    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
-}
-
-void
-PyUnicode_InternImmortal(PyObject **p)
-{
-    PyUnicode_InternInPlace(p);
-    if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
-        _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
-        Py_INCREF(*p);
-    }
-}
-
-PyObject *
-PyUnicode_InternFromString(const char *cp)
-{
-    PyObject *s = PyUnicode_FromString(cp);
-    if (s == NULL)
-        return NULL;
-    PyUnicode_InternInPlace(&s);
-    return s;
-}
-
-void
-_Py_ReleaseInternedUnicodeStrings(void)
-{
-    PyObject *keys;
-    PyObject *s;
-    Py_ssize_t i, n;
-    Py_ssize_t immortal_size = 0, mortal_size = 0;
-
-    if (interned == NULL || !PyDict_Check(interned))
-        return;
-    keys = PyDict_Keys(interned);
-    if (keys == NULL || !PyList_Check(keys)) {
-        PyErr_Clear();
-        return;
-    }
-
-    /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
-       detector, interned unicode strings are not forcibly deallocated;
-       rather, we give them their stolen references back, and then clear
-       and DECREF the interned dict. */
-
-    n = PyList_GET_SIZE(keys);
-    fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
-            n);
-    for (i = 0; i < n; i++) {
-        s = PyList_GET_ITEM(keys, i);
-        if (PyUnicode_READY(s) == -1) {
-            assert(0 && "could not ready string");
-            fprintf(stderr, "could not ready string\n");
-        }
-        switch (PyUnicode_CHECK_INTERNED(s)) {
-        case SSTATE_NOT_INTERNED:
-            /* XXX Shouldn't happen */
-            break;
-        case SSTATE_INTERNED_IMMORTAL:
-            Py_REFCNT(s) += 1;
-            immortal_size += PyUnicode_GET_LENGTH(s);
-            break;
-        case SSTATE_INTERNED_MORTAL:
-            Py_REFCNT(s) += 2;
-            mortal_size += PyUnicode_GET_LENGTH(s);
-            break;
-        default:
-            Py_FatalError("Inconsistent interned string state.");
-        }
-        _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
-    }
-    fprintf(stderr, "total size of all interned strings: "
-            "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
-            "mortal/immortal\n", mortal_size, immortal_size);
-    Py_DECREF(keys);
-    PyDict_Clear(interned);
-    Py_CLEAR(interned);
-}
-
-
-/********************* Unicode Iterator **************************/
-
-typedef struct {
-    PyObject_HEAD
-    Py_ssize_t it_index;
-    PyObject *it_seq;    /* Set to NULL when iterator is exhausted */
-} unicodeiterobject;
-
-static void
-unicodeiter_dealloc(unicodeiterobject *it)
-{
-    _PyObject_GC_UNTRACK(it);
-    Py_XDECREF(it->it_seq);
-    PyObject_GC_Del(it);
-}
-
-static int
-unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
-{
-    Py_VISIT(it->it_seq);
-    return 0;
-}
-
-static PyObject *
-unicodeiter_next(unicodeiterobject *it)
-{
-    PyObject *seq, *item;
-
-    assert(it != NULL);
-    seq = it->it_seq;
-    if (seq == NULL)
-        return NULL;
-    assert(_PyUnicode_CHECK(seq));
-
-    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
-        int kind = PyUnicode_KIND(seq);
-        void *data = PyUnicode_DATA(seq);
-        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
-        item = PyUnicode_FromOrdinal(chr);
-        if (item != NULL)
-            ++it->it_index;
-        return item;
-    }
-
-    Py_DECREF(seq);
-    it->it_seq = NULL;
-    return NULL;
-}
-
-static PyObject *
-unicodeiter_len(unicodeiterobject *it)
-{
-    Py_ssize_t len = 0;
-    if (it->it_seq)
-        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
-    return PyLong_FromSsize_t(len);
-}
-
-PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
-
-static PyObject *
-unicodeiter_reduce(unicodeiterobject *it)
-{
-    if (it->it_seq != NULL) {
-        return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
-                             it->it_seq, it->it_index);
-    } else {
-        PyObject *u = PyUnicode_FromUnicode(NULL, 0);
-        if (u == NULL)
-            return NULL;
-        return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
-    }
-}
-
-PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
-
-static PyObject *
-unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
-{
-    Py_ssize_t index = PyLong_AsSsize_t(state);
-    if (index == -1 && PyErr_Occurred())
-        return NULL;
-    if (it->it_seq != NULL) {
-        if (index < 0)
-            index = 0;
-        else if (index > PyUnicode_GET_LENGTH(it->it_seq))
-            index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
-        it->it_index = index;
-    }
-    Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
-
-static PyMethodDef unicodeiter_methods[] = {
-    {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
-     length_hint_doc},
-    {"__reduce__",      (PyCFunction)unicodeiter_reduce, METH_NOARGS,
-     reduce_doc},
-    {"__setstate__",    (PyCFunction)unicodeiter_setstate, METH_O,
-     setstate_doc},
-    {NULL,      NULL}       /* sentinel */
-};
-
-PyTypeObject PyUnicodeIter_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "str_iterator",         /* tp_name */
-    sizeof(unicodeiterobject),      /* tp_basicsize */
-    0,                  /* tp_itemsize */
-    /* methods */
-    (destructor)unicodeiter_dealloc,    /* tp_dealloc */
-    0,                  /* tp_print */
-    0,                  /* tp_getattr */
-    0,                  /* tp_setattr */
-    0,                  /* tp_reserved */
-    0,                  /* tp_repr */
-    0,                  /* tp_as_number */
-    0,                  /* tp_as_sequence */
-    0,                  /* tp_as_mapping */
-    0,                  /* tp_hash */
-    0,                  /* tp_call */
-    0,                  /* tp_str */
-    PyObject_GenericGetAttr,        /* tp_getattro */
-    0,                  /* tp_setattro */
-    0,                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-    0,                  /* tp_doc */
-    (traverseproc)unicodeiter_traverse, /* tp_traverse */
-    0,                  /* tp_clear */
-    0,                  /* tp_richcompare */
-    0,                  /* tp_weaklistoffset */
-    PyObject_SelfIter,          /* tp_iter */
-    (iternextfunc)unicodeiter_next,     /* tp_iternext */
-    unicodeiter_methods,            /* tp_methods */
-    0,
-};
-
-static PyObject *
-unicode_iter(PyObject *seq)
-{
-    unicodeiterobject *it;
-
-    if (!PyUnicode_Check(seq)) {
-        PyErr_BadInternalCall();
-        return NULL;
-    }
-    if (PyUnicode_READY(seq) == -1)
-        return NULL;
-    it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
-    if (it == NULL)
-        return NULL;
-    it->it_index = 0;
-    Py_INCREF(seq);
-    it->it_seq = seq;
-    _PyObject_GC_TRACK(it);
-    return (PyObject *)it;
-}
-
-
-size_t
-Py_UNICODE_strlen(const Py_UNICODE *u)
-{
-    int res = 0;
-    while(*u++)
-        res++;
-    return res;
-}
-
-Py_UNICODE*
-Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
-{
-    Py_UNICODE *u = s1;
-    while ((*u++ = *s2++));
-    return s1;
-}
-
-Py_UNICODE*
-Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
-{
-    Py_UNICODE *u = s1;
-    while ((*u++ = *s2++))
-        if (n-- == 0)
-            break;
-    return s1;
-}
-
-Py_UNICODE*
-Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
-{
-    Py_UNICODE *u1 = s1;
-    u1 += Py_UNICODE_strlen(u1);
-    Py_UNICODE_strcpy(u1, s2);
-    return s1;
-}
-
-int
-Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
-{
-    while (*s1 && *s2 && *s1 == *s2)
-        s1++, s2++;
-    if (*s1 && *s2)
-        return (*s1 < *s2) ? -1 : +1;
-    if (*s1)
-        return 1;
-    if (*s2)
-        return -1;
-    return 0;
-}
-
-int
-Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
-{
-    Py_UNICODE u1, u2;
-    for (; n != 0; n--) {
-        u1 = *s1;
-        u2 = *s2;
-        if (u1 != u2)
-            return (u1 < u2) ? -1 : +1;
-        if (u1 == '\0')
-            return 0;
-        s1++;
-        s2++;
-    }
-    return 0;
-}
-
-Py_UNICODE*
-Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
-{
-    const Py_UNICODE *p;
-    for (p = s; *p; p++)
-        if (*p == c)
-            return (Py_UNICODE*)p;
-    return NULL;
-}
-
-Py_UNICODE*
-Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
-{
-    const Py_UNICODE *p;
-    p = s + Py_UNICODE_strlen(s);
-    while (p != s) {
-        p--;
-        if (*p == c)
-            return (Py_UNICODE*)p;
-    }
-    return NULL;
-}
-
-Py_UNICODE*
-PyUnicode_AsUnicodeCopy(PyObject *unicode)
-{
-    Py_UNICODE *u, *copy;
-    Py_ssize_t len, size;
-
-    if (!PyUnicode_Check(unicode)) {
-        PyErr_BadArgument();
-        return NULL;
-    }
-    u = PyUnicode_AsUnicodeAndSize(unicode, &len);
-    if (u == NULL)
-        return NULL;
-    /* Ensure we won't overflow the size. */
-    if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    size = len + 1; /* copy the null character */
-    size *= sizeof(Py_UNICODE);
-    copy = PyMem_Malloc(size);
-    if (copy == NULL) {
-        PyErr_NoMemory();
-        return NULL;
-    }
-    memcpy(copy, u, size);
-    return copy;
-}
-
-/* A _string module, to export formatter_parser and formatter_field_name_split
-   to the string.Formatter class implemented in Python. */
-
-static PyMethodDef _string_methods[] = {
-    {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
-     METH_O, PyDoc_STR("split the argument as a field name")},
-    {"formatter_parser", (PyCFunction) formatter_parser,
-     METH_O, PyDoc_STR("parse the argument as a format string")},
-    {NULL, NULL}
-};
-
-static struct PyModuleDef _string_module = {
-    PyModuleDef_HEAD_INIT,
-    "_string",
-    PyDoc_STR("string helper module"),
-    0,
-    _string_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit__string(void)
-{
-    return PyModule_Create(&_string_module);
-}
-
-
-#ifdef __cplusplus
-}
-#endif
+/*[clinic end generated code: output=4670413843c53055 input=a9049054013a1b77]*/
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -233,6 +233,8 @@
 static PyDictObject *free_list[PyDict_MAXFREELIST];
 static int numfree = 0;
 
+#include "clinic/dictobject.c.h"
+
 int
 PyDict_ClearFreeList(void)
 {
@@ -1757,38 +1759,9 @@
 Returns a new dict with keys from iterable and values equal to value.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(dict_fromkeys__doc__,
-"fromkeys($type, iterable, value=None, /)\n"
-"--\n"
-"\n"
-"Returns a new dict with keys from iterable and values equal to value.");
-
-#define DICT_FROMKEYS_METHODDEF    \
-    {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS|METH_CLASS, dict_fromkeys__doc__},
-
-static PyObject *
-dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value);
-
-static PyObject *
-dict_fromkeys(PyTypeObject *type, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *iterable;
-    PyObject *value = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "fromkeys",
-        1, 2,
-        &iterable, &value))
-        goto exit;
-    return_value = dict_fromkeys_impl(type, iterable, value);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
-/*[clinic end generated code: output=55f8dc0ffa87406f input=b85a667f9bf4669d]*/
+/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
 {
     PyObject *it;       /* iter(seq) */
     PyObject *key;
@@ -2266,18 +2239,9 @@
 True if D has a key k, else False.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(dict___contains____doc__,
-"__contains__($self, key, /)\n"
-"--\n"
-"\n"
-"True if D has a key k, else False.");
-
-#define DICT___CONTAINS___METHODDEF    \
-    {"__contains__", (PyCFunction)dict___contains__, METH_O|METH_COEXIST, dict___contains____doc__},
-
 static PyObject *
 dict___contains__(PyDictObject *self, PyObject *key)
-/*[clinic end generated code: output=3cf3f8aaf2cc5cc3 input=b852b2a19b51ab24]*/
+/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
 {
     register PyDictObject *mp = self;
     Py_hash_t hash;
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -290,6 +290,8 @@
     0, 0, 0, 0, 0, 0, 0, 0
 };
 
+#include "clinic/unicodeobject.c.h"
+
 /* The max unicode value is always 0x10FFFF while using the PEP-393 API.
    This function is kept for backward compatibility with the old API. */
 Py_UNICODE
@@ -12955,47 +12957,9 @@
 must be a string, whose characters will be mapped to None in the result.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(unicode_maketrans__doc__,
-"maketrans(x, y=None, z=None, /)\n"
-"--\n"
-"\n"
-"Return a translation table usable for str.translate().\n"
-"\n"
-"If there is only one argument, it must be a dictionary mapping Unicode\n"
-"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
-"Character keys will be then converted to ordinals.\n"
-"If there are two arguments, they must be strings of equal length, and\n"
-"in the resulting dictionary, each character in x will be mapped to the\n"
-"character at the same position in y. If there is a third argument, it\n"
-"must be a string, whose characters will be mapped to None in the result.");
-
-#define UNICODE_MAKETRANS_METHODDEF    \
-    {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
-
-static PyObject *
-unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
-
-static PyObject *
-unicode_maketrans(void *null, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *x;
-    PyObject *y = NULL;
-    PyObject *z = NULL;
-
-    if (!PyArg_ParseTuple(args,
-        "O|UU:maketrans",
-        &x, &y, &z))
-        goto exit;
-    return_value = unicode_maketrans_impl(x, y, z);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
-/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
+/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
 {
     PyObject *new = NULL, *key, *value;
     Py_ssize_t i = 0;
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c
--- a/Python/bltinmodule.c
+++ b/Python/bltinmodule.c
@@ -46,6 +46,8 @@
 _Py_IDENTIFIER(stdout);
 _Py_IDENTIFIER(stderr);
 
+#include "clinic/bltinmodule.c.h"
+
 /* AC: cannot convert yet, waiting for *args support */
 static PyObject *
 builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
@@ -239,18 +241,9 @@
 Return the absolute value of the argument.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_abs__doc__,
-"abs($module, x, /)\n"
-"--\n"
-"\n"
-"Return the absolute value of the argument.");
-
-#define BUILTIN_ABS_METHODDEF    \
-    {"abs", (PyCFunction)builtin_abs, METH_O, builtin_abs__doc__},
-
 static PyObject *
 builtin_abs(PyModuleDef *module, PyObject *x)
-/*[clinic end generated code: output=f85095528ce7e2e5 input=aa29cc07869b4732]*/
+/*[clinic end generated code: output=6833047c493ecea2 input=aa29cc07869b4732]*/
 {
     return PyNumber_Absolute(x);
 }
@@ -266,20 +259,9 @@
 If the iterable is empty, return True.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_all__doc__,
-"all($module, iterable, /)\n"
-"--\n"
-"\n"
-"Return True if bool(x) is True for all values x in the iterable.\n"
-"\n"
-"If the iterable is empty, return True.");
-
-#define BUILTIN_ALL_METHODDEF    \
-    {"all", (PyCFunction)builtin_all, METH_O, builtin_all__doc__},
-
 static PyObject *
 builtin_all(PyModuleDef *module, PyObject *iterable)
-/*[clinic end generated code: output=d001db739ba83b46 input=dd506dc9998d42bd]*/
+/*[clinic end generated code: output=089e6d1b7bde27b1 input=dd506dc9998d42bd]*/
 {
     PyObject *it, *item;
     PyObject *(*iternext)(PyObject *);
@@ -326,20 +308,9 @@
 If the iterable is empty, return False.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_any__doc__,
-"any($module, iterable, /)\n"
-"--\n"
-"\n"
-"Return True if bool(x) is True for any x in the iterable.\n"
-"\n"
-"If the iterable is empty, return False.");
-
-#define BUILTIN_ANY_METHODDEF    \
-    {"any", (PyCFunction)builtin_any, METH_O, builtin_any__doc__},
-
 static PyObject *
 builtin_any(PyModuleDef *module, PyObject *iterable)
-/*[clinic end generated code: output=3a4b6dbe6a0d6f61 input=8fe8460f3fbbced8]*/
+/*[clinic end generated code: output=1be994b2c2307492 input=8fe8460f3fbbced8]*/
 {
     PyObject *it, *item;
     PyObject *(*iternext)(PyObject *);
@@ -389,23 +360,9 @@
 to that returned by repr() in Python 2.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_ascii__doc__,
-"ascii($module, obj, /)\n"
-"--\n"
-"\n"
-"Return an ASCII-only representation of an object.\n"
-"\n"
-"As repr(), return a string containing a printable representation of an\n"
-"object, but escape the non-ASCII characters in the string returned by\n"
-"repr() using \\\\x, \\\\u or \\\\U escapes. This generates a string similar\n"
-"to that returned by repr() in Python 2.");
-
-#define BUILTIN_ASCII_METHODDEF    \
-    {"ascii", (PyCFunction)builtin_ascii, METH_O, builtin_ascii__doc__},
-
 static PyObject *
 builtin_ascii(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=f0e6754154c2d30b input=0cbdc1420a306325]*/
+/*[clinic end generated code: output=d4e862c48af2a933 input=0cbdc1420a306325]*/
 {
     return PyObject_ASCII(obj);
 }
@@ -423,21 +380,9 @@
    '0b1010101010101010101010'
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_bin__doc__,
-"bin($module, number, /)\n"
-"--\n"
-"\n"
-"Return the binary representation of an integer.\n"
-"\n"
-"   >>> bin(2796202)\n"
-"   \'0b1010101010101010101010\'");
-
-#define BUILTIN_BIN_METHODDEF    \
-    {"bin", (PyCFunction)builtin_bin, METH_O, builtin_bin__doc__},
-
 static PyObject *
 builtin_bin(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=18fed0e943650da1 input=2a6362ae9a9c9203]*/
+/*[clinic end generated code: output=25ee26c6cf3bbb54 input=2a6362ae9a9c9203]*/
 {
     return PyNumber_ToBase(number, 2);
 }
@@ -455,21 +400,9 @@
 __call__() method.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_callable__doc__,
-"callable($module, obj, /)\n"
-"--\n"
-"\n"
-"Return whether the object is callable (i.e., some kind of function).\n"
-"\n"
-"Note that classes are callable, as are instances of classes with a\n"
-"__call__() method.");
-
-#define BUILTIN_CALLABLE_METHODDEF    \
-    {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__},
-
 static PyObject *
 builtin_callable(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=b3a92cbe635f32af input=bb3bb528fffdade4]*/
+/*[clinic end generated code: output=f4df2ce92364b656 input=bb3bb528fffdade4]*/
 {
     return PyBool_FromLong((long)PyCallable_Check(obj));
 }
@@ -640,40 +573,9 @@
 format_spec defaults to the empty string
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_format__doc__,
-"format($module, value, format_spec=\'\', /)\n"
-"--\n"
-"\n"
-"Return value.__format__(format_spec)\n"
-"\n"
-"format_spec defaults to the empty string");
-
-#define BUILTIN_FORMAT_METHODDEF    \
-    {"format", (PyCFunction)builtin_format, METH_VARARGS, builtin_format__doc__},
-
-static PyObject *
-builtin_format_impl(PyModuleDef *module, PyObject *value, PyObject *format_spec);
-
-static PyObject *
-builtin_format(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *value;
-    PyObject *format_spec = NULL;
-
-    if (!PyArg_ParseTuple(args,
-        "O|U:format",
-        &value, &format_spec))
-        goto exit;
-    return_value = builtin_format_impl(module, value, format_spec);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_format_impl(PyModuleDef *module, PyObject *value, PyObject *format_spec)
-/*[clinic end generated code: output=39723a58c72e8871 input=e23f2f11e0098c64]*/
+/*[clinic end generated code: output=fae3e927cc715466 input=e23f2f11e0098c64]*/
 {
     return PyObject_Format(value, format_spec);
 }
@@ -687,37 +589,9 @@
 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_chr__doc__,
-"chr($module, i, /)\n"
-"--\n"
-"\n"
-"Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
-
-#define BUILTIN_CHR_METHODDEF    \
-    {"chr", (PyCFunction)builtin_chr, METH_VARARGS, builtin_chr__doc__},
-
-static PyObject *
-builtin_chr_impl(PyModuleDef *module, int i);
-
-static PyObject *
-builtin_chr(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    int i;
-
-    if (!PyArg_ParseTuple(args,
-        "i:chr",
-        &i))
-        goto exit;
-    return_value = builtin_chr_impl(module, i);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_chr_impl(PyModuleDef *module, int i)
-/*[clinic end generated code: output=4d6bbe948f56e2ae input=9b1ced29615adf66]*/
+/*[clinic end generated code: output=67fe4d87e690f373 input=9b1ced29615adf66]*/
 {
     return PyUnicode_FromOrdinal(i);
 }
@@ -779,55 +653,9 @@
 in addition to any features explicitly specified.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_compile__doc__,
-"compile($module, /, source, filename, mode, flags=0, dont_inherit=0,\n"
-"        optimize=-1)\n"
-"--\n"
-"\n"
-"Compile source into a code object that can be executed by exec() or eval().\n"
-"\n"
-"The source code may represent a Python module, statement or expression.\n"
-"The filename will be used for run-time error messages.\n"
-"The mode must be \'exec\' to compile a module, \'single\' to compile a\n"
-"single (interactive) statement, or \'eval\' to compile an expression.\n"
-"The flags argument, if present, controls which future statements influence\n"
-"the compilation of the code.\n"
-"The dont_inherit argument, if non-zero, stops the compilation inheriting\n"
-"the effects of any future statements in effect in the code calling\n"
-"compile; if absent or zero these statements do influence the compilation,\n"
-"in addition to any features explicitly specified.");
-
-#define BUILTIN_COMPILE_METHODDEF    \
-    {"compile", (PyCFunction)builtin_compile, METH_VARARGS|METH_KEYWORDS, builtin_compile__doc__},
-
-static PyObject *
-builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize);
-
-static PyObject *
-builtin_compile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
-{
-    PyObject *return_value = NULL;
-    static char *_keywords[] = {"source", "filename", "mode", "flags", "dont_inherit", "optimize", NULL};
-    PyObject *source;
-    PyObject *filename;
-    const char *mode;
-    int flags = 0;
-    int dont_inherit = 0;
-    int optimize = -1;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
-        "OO&s|iii:compile", _keywords,
-        &source, PyUnicode_FSDecoder, &filename, &mode, &flags, &dont_inherit, &optimize))
-        goto exit;
-    return_value = builtin_compile_impl(module, source, filename, mode, flags, dont_inherit, optimize);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize)
-/*[clinic end generated code: output=c72d197809d178fc input=c6212a9d21472f7e]*/
+/*[clinic end generated code: output=4f41a315386bab9f input=c6212a9d21472f7e]*/
 {
     Py_buffer view = {NULL, NULL};
     const char *str;
@@ -951,38 +779,9 @@
 Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_divmod__doc__,
-"divmod($module, x, y, /)\n"
-"--\n"
-"\n"
-"Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.");
-
-#define BUILTIN_DIVMOD_METHODDEF    \
-    {"divmod", (PyCFunction)builtin_divmod, METH_VARARGS, builtin_divmod__doc__},
-
-static PyObject *
-builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y);
-
-static PyObject *
-builtin_divmod(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *x;
-    PyObject *y;
-
-    if (!PyArg_UnpackTuple(args, "divmod",
-        2, 2,
-        &x, &y))
-        goto exit;
-    return_value = builtin_divmod_impl(module, x, y);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
-/*[clinic end generated code: output=77e8d408b1338886 input=c9c617b7bb74c615]*/
+/*[clinic end generated code: output=9ad0076120ebf9ac input=c9c617b7bb74c615]*/
 {
     return PyNumber_Divmod(x, y);
 }
@@ -1005,45 +804,9 @@
 If only globals is given, locals defaults to it.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_eval__doc__,
-"eval($module, source, globals=None, locals=None, /)\n"
-"--\n"
-"\n"
-"Evaluate the given source in the context of globals and locals.\n"
-"\n"
-"The source may be a string representing a Python expression\n"
-"or a code object as returned by compile().\n"
-"The globals must be a dictionary and locals can be any mapping,\n"
-"defaulting to the current globals and locals.\n"
-"If only globals is given, locals defaults to it.");
-
-#define BUILTIN_EVAL_METHODDEF    \
-    {"eval", (PyCFunction)builtin_eval, METH_VARARGS, builtin_eval__doc__},
-
-static PyObject *
-builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals);
-
-static PyObject *
-builtin_eval(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *source;
-    PyObject *globals = Py_None;
-    PyObject *locals = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "eval",
-        1, 3,
-        &source, &globals, &locals))
-        goto exit;
-    return_value = builtin_eval_impl(module, source, globals, locals);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
-/*[clinic end generated code: output=644fd59012538ce6 input=31e42c1d2125b50b]*/
+/*[clinic end generated code: output=90642b79dd8b08d6 input=31e42c1d2125b50b]*/
 {
     PyObject *result, *tmp = NULL;
     Py_buffer view = {NULL, NULL};
@@ -1125,45 +888,9 @@
 If only globals is given, locals defaults to it.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_exec__doc__,
-"exec($module, source, globals=None, locals=None, /)\n"
-"--\n"
-"\n"
-"Execute the given source in the context of globals and locals.\n"
-"\n"
-"The source may be a string representing one or more Python statements\n"
-"or a code object as returned by compile().\n"
-"The globals must be a dictionary and locals can be any mapping,\n"
-"defaulting to the current globals and locals.\n"
-"If only globals is given, locals defaults to it.");
-
-#define BUILTIN_EXEC_METHODDEF    \
-    {"exec", (PyCFunction)builtin_exec, METH_VARARGS, builtin_exec__doc__},
-
-static PyObject *
-builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals);
-
-static PyObject *
-builtin_exec(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *source;
-    PyObject *globals = Py_None;
-    PyObject *locals = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "exec",
-        1, 3,
-        &source, &globals, &locals))
-        goto exit;
-    return_value = builtin_exec_impl(module, source, globals, locals);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
-/*[clinic end generated code: output=0281b48bfa8e3c87 input=536e057b5e00d89e]*/
+/*[clinic end generated code: output=e8e0bbcde826a048 input=536e057b5e00d89e]*/
 {
     PyObject *v;
 
@@ -1275,30 +1002,9 @@
 global scope and vice-versa.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_globals__doc__,
-"globals($module, /)\n"
-"--\n"
-"\n"
-"Return the dictionary containing the current scope\'s global variables.\n"
-"\n"
-"NOTE: Updates to this dictionary *will* affect name lookups in the current\n"
-"global scope and vice-versa.");
-
-#define BUILTIN_GLOBALS_METHODDEF    \
-    {"globals", (PyCFunction)builtin_globals, METH_NOARGS, builtin_globals__doc__},
-
-static PyObject *
-builtin_globals_impl(PyModuleDef *module);
-
-static PyObject *
-builtin_globals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return builtin_globals_impl(module);
-}
-
 static PyObject *
 builtin_globals_impl(PyModuleDef *module)
-/*[clinic end generated code: output=048640f58b1f20ad input=9327576f92bb48ba]*/
+/*[clinic end generated code: output=4958645e96dd8138 input=9327576f92bb48ba]*/
 {
     PyObject *d;
 
@@ -1320,40 +1026,9 @@
 This is done by calling getattr(obj, name) and catching AttributeError.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_hasattr__doc__,
-"hasattr($module, obj, name, /)\n"
-"--\n"
-"\n"
-"Return whether the object has an attribute with the given name.\n"
-"\n"
-"This is done by calling getattr(obj, name) and catching AttributeError.");
-
-#define BUILTIN_HASATTR_METHODDEF    \
-    {"hasattr", (PyCFunction)builtin_hasattr, METH_VARARGS, builtin_hasattr__doc__},
-
-static PyObject *
-builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
-
-static PyObject *
-builtin_hasattr(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *obj;
-    PyObject *name;
-
-    if (!PyArg_UnpackTuple(args, "hasattr",
-        2, 2,
-        &obj, &name))
-        goto exit;
-    return_value = builtin_hasattr_impl(module, obj, name);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
-/*[clinic end generated code: output=e0bd996ef73d1217 input=b50bad5f739ea10d]*/
+/*[clinic end generated code: output=81154fdd63634696 input=b50bad5f739ea10d]*/
 {
     PyObject *v;
 
@@ -1392,21 +1067,9 @@
 (CPython uses the object's memory address.)
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_id__doc__,
-"id($module, obj, /)\n"
-"--\n"
-"\n"
-"Return the identity of an object.\n"
-"\n"
-"This is guaranteed to be unique among simultaneously existing objects.\n"
-"(CPython uses the object\'s memory address.)");
-
-#define BUILTIN_ID_METHODDEF    \
-    {"id", (PyCFunction)builtin_id, METH_O, builtin_id__doc__},
-
 static PyObject *
 builtin_id(PyModuleDef *self, PyObject *v)
-/*[clinic end generated code: output=f54da09c91992e63 input=a1f988d98357341d]*/
+/*[clinic end generated code: output=0aa640785f697f65 input=a1f988d98357341d]*/
 {
     return PyLong_FromVoidPtr(v);
 }
@@ -1639,41 +1302,9 @@
 setattr(x, 'y', v) is equivalent to ``x.y = v''
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_setattr__doc__,
-"setattr($module, obj, name, value, /)\n"
-"--\n"
-"\n"
-"Sets the named attribute on the given object to the specified value.\n"
-"\n"
-"setattr(x, \'y\', v) is equivalent to ``x.y = v\'\'");
-
-#define BUILTIN_SETATTR_METHODDEF    \
-    {"setattr", (PyCFunction)builtin_setattr, METH_VARARGS, builtin_setattr__doc__},
-
-static PyObject *
-builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value);
-
-static PyObject *
-builtin_setattr(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *obj;
-    PyObject *name;
-    PyObject *value;
-
-    if (!PyArg_UnpackTuple(args, "setattr",
-        3, 3,
-        &obj, &name, &value))
-        goto exit;
-    return_value = builtin_setattr_impl(module, obj, name, value);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=4336dcbbf7691d2d input=fbe7e53403116b93]*/
+/*[clinic end generated code: output=c5e0a3a3971333ed input=fbe7e53403116b93]*/
 {
     if (PyObject_SetAttr(obj, name, value) != 0)
         return NULL;
@@ -1694,40 +1325,9 @@
 delattr(x, 'y') is equivalent to ``del x.y''
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_delattr__doc__,
-"delattr($module, obj, name, /)\n"
-"--\n"
-"\n"
-"Deletes the named attribute from the given object.\n"
-"\n"
-"delattr(x, \'y\') is equivalent to ``del x.y\'\'");
-
-#define BUILTIN_DELATTR_METHODDEF    \
-    {"delattr", (PyCFunction)builtin_delattr, METH_VARARGS, builtin_delattr__doc__},
-
-static PyObject *
-builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
-
-static PyObject *
-builtin_delattr(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *obj;
-    PyObject *name;
-
-    if (!PyArg_UnpackTuple(args, "delattr",
-        2, 2,
-        &obj, &name))
-        goto exit;
-    return_value = builtin_delattr_impl(module, obj, name);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
-/*[clinic end generated code: output=319c2d884aa769cf input=647af2ce9183a823]*/
+/*[clinic end generated code: output=ef653e698a0b4187 input=647af2ce9183a823]*/
 {
     if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
         return NULL;
@@ -1748,21 +1348,9 @@
 reverse is not necessarily true.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_hash__doc__,
-"hash($module, obj, /)\n"
-"--\n"
-"\n"
-"Return the hash value for the given object.\n"
-"\n"
-"Two objects that compare equal must also have the same hash value, but the\n"
-"reverse is not necessarily true.");
-
-#define BUILTIN_HASH_METHODDEF    \
-    {"hash", (PyCFunction)builtin_hash, METH_O, builtin_hash__doc__},
-
 static PyObject *
 builtin_hash(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=1ec467611c13468b input=ccc4d2b9a351df4e]*/
+/*[clinic end generated code: output=1f32ff154c1f751a input=ccc4d2b9a351df4e]*/
 {
     Py_hash_t x;
 
@@ -1785,21 +1373,9 @@
    '0xc0ffee'
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_hex__doc__,
-"hex($module, number, /)\n"
-"--\n"
-"\n"
-"Return the hexadecimal representation of an integer.\n"
-"\n"
-"   >>> hex(12648430)\n"
-"   \'0xc0ffee\'");
-
-#define BUILTIN_HEX_METHODDEF    \
-    {"hex", (PyCFunction)builtin_hex, METH_O, builtin_hex__doc__},
-
 static PyObject *
 builtin_hex(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=f18e9439aeaa2c6c input=e816200b0a728ebe]*/
+/*[clinic end generated code: output=618489ce3cbc5858 input=e816200b0a728ebe]*/
 {
     return PyNumber_ToBase(number, 16);
 }
@@ -1841,18 +1417,9 @@
 Return the number of items in a container.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_len__doc__,
-"len($module, obj, /)\n"
-"--\n"
-"\n"
-"Return the number of items in a container.");
-
-#define BUILTIN_LEN_METHODDEF    \
-    {"len", (PyCFunction)builtin_len, METH_O, builtin_len__doc__},
-
 static PyObject *
 builtin_len(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=5a38b0db40761705 input=2e5ff15db9a2de22]*/
+/*[clinic end generated code: output=8e5837b6f81d915b input=2e5ff15db9a2de22]*/
 {
     Py_ssize_t res;
 
@@ -1873,31 +1440,9 @@
 covered by any backwards compatibility guarantees.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_locals__doc__,
-"locals($module, /)\n"
-"--\n"
-"\n"
-"Return a dictionary containing the current scope\'s local variables.\n"
-"\n"
-"NOTE: Whether or not updates to this dictionary will affect name lookups in\n"
-"the local scope and vice-versa is *implementation dependent* and not\n"
-"covered by any backwards compatibility guarantees.");
-
-#define BUILTIN_LOCALS_METHODDEF    \
-    {"locals", (PyCFunction)builtin_locals, METH_NOARGS, builtin_locals__doc__},
-
-static PyObject *
-builtin_locals_impl(PyModuleDef *module);
-
-static PyObject *
-builtin_locals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
-{
-    return builtin_locals_impl(module);
-}
-
 static PyObject *
 builtin_locals_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8ac52522924346e2 input=7874018d478d5c4b]*/
+/*[clinic end generated code: output=8b5a41f12e19d13a input=7874018d478d5c4b]*/
 {
     PyObject *d;
 
@@ -2054,21 +1599,9 @@
    '0o1234567'
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_oct__doc__,
-"oct($module, number, /)\n"
-"--\n"
-"\n"
-"Return the octal representation of an integer.\n"
-"\n"
-"   >>> oct(342391)\n"
-"   \'0o1234567\'");
-
-#define BUILTIN_OCT_METHODDEF    \
-    {"oct", (PyCFunction)builtin_oct, METH_O, builtin_oct__doc__},
-
 static PyObject *
 builtin_oct(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=b99234d1d70a6673 input=a3a372b521b3dd13]*/
+/*[clinic end generated code: output=18f701bc6d8f804a input=a3a372b521b3dd13]*/
 {
     return PyNumber_ToBase(number, 8);
 }
@@ -2083,18 +1616,9 @@
 Return the Unicode code point for a one-character string.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_ord__doc__,
-"ord($module, c, /)\n"
-"--\n"
-"\n"
-"Return the Unicode code point for a one-character string.");
-
-#define BUILTIN_ORD_METHODDEF    \
-    {"ord", (PyCFunction)builtin_ord, METH_O, builtin_ord__doc__},
-
 static PyObject *
 builtin_ord(PyModuleDef *module, PyObject *c)
-/*[clinic end generated code: output=a8466d23bd76db3f input=762355f87451efa3]*/
+/*[clinic end generated code: output=04fd27272d9462f6 input=762355f87451efa3]*/
 {
     long ord;
     Py_ssize_t size;
@@ -2152,42 +1676,9 @@
 invoked using the three argument form.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_pow__doc__,
-"pow($module, x, y, z=None, /)\n"
-"--\n"
-"\n"
-"Equivalent to x**y (with two arguments) or x**y % z (with three arguments)\n"
-"\n"
-"Some types, such as ints, are able to use a more efficient algorithm when\n"
-"invoked using the three argument form.");
-
-#define BUILTIN_POW_METHODDEF    \
-    {"pow", (PyCFunction)builtin_pow, METH_VARARGS, builtin_pow__doc__},
-
-static PyObject *
-builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z);
-
-static PyObject *
-builtin_pow(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *x;
-    PyObject *y;
-    PyObject *z = Py_None;
-
-    if (!PyArg_UnpackTuple(args, "pow",
-        2, 3,
-        &x, &y, &z))
-        goto exit;
-    return_value = builtin_pow_impl(module, x, y, z);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
-/*[clinic end generated code: output=d0cdf314311dedba input=561a942d5f5c1899]*/
+/*[clinic end generated code: output=1fba268adba9b45f input=561a942d5f5c1899]*/
 {
     return PyNumber_Power(x, y, z);
 }
@@ -2304,43 +1795,9 @@
 On *nix systems, readline is used if available.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_input__doc__,
-"input($module, prompt=None, /)\n"
-"--\n"
-"\n"
-"Read a string from standard input.  The trailing newline is stripped.\n"
-"\n"
-"The prompt string, if given, is printed to standard output without a\n"
-"trailing newline before reading input.\n"
-"\n"
-"If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.\n"
-"On *nix systems, readline is used if available.");
-
-#define BUILTIN_INPUT_METHODDEF    \
-    {"input", (PyCFunction)builtin_input, METH_VARARGS, builtin_input__doc__},
-
-static PyObject *
-builtin_input_impl(PyModuleDef *module, PyObject *prompt);
-
-static PyObject *
-builtin_input(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *prompt = NULL;
-
-    if (!PyArg_UnpackTuple(args, "input",
-        0, 1,
-        &prompt))
-        goto exit;
-    return_value = builtin_input_impl(module, prompt);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_input_impl(PyModuleDef *module, PyObject *prompt)
-/*[clinic end generated code: output=69323bf5695f7c9c input=5e8bb70c2908fe3c]*/
+/*[clinic end generated code: output=b77731f59e1515c4 input=5e8bb70c2908fe3c]*/
 {
     PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
     PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
@@ -2523,20 +1980,9 @@
 For many object types, including most builtins, eval(repr(obj)) == obj.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_repr__doc__,
-"repr($module, obj, /)\n"
-"--\n"
-"\n"
-"Return the canonical string representation of the object.\n"
-"\n"
-"For many object types, including most builtins, eval(repr(obj)) == obj.");
-
-#define BUILTIN_REPR_METHODDEF    \
-    {"repr", (PyCFunction)builtin_repr, METH_O, builtin_repr__doc__},
-
 static PyObject *
 builtin_repr(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=988980120f39e2fa input=a2bca0f38a5a924d]*/
+/*[clinic end generated code: output=dc41784fa4341834 input=a2bca0f38a5a924d]*/
 {
     return PyObject_Repr(obj);
 }
@@ -2704,42 +2150,9 @@
 reject non-numeric types.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_sum__doc__,
-"sum($module, iterable, start=0, /)\n"
-"--\n"
-"\n"
-"Return the sum of a \'start\' value (default: 0) plus an iterable of numbers\n"
-"\n"
-"When the iterable is empty, return the start value.\n"
-"This function is intended specifically for use with numeric values and may\n"
-"reject non-numeric types.");
-
-#define BUILTIN_SUM_METHODDEF    \
-    {"sum", (PyCFunction)builtin_sum, METH_VARARGS, builtin_sum__doc__},
-
-static PyObject *
-builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start);
-
-static PyObject *
-builtin_sum(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *iterable;
-    PyObject *start = NULL;
-
-    if (!PyArg_UnpackTuple(args, "sum",
-        1, 2,
-        &iterable, &start))
-        goto exit;
-    return_value = builtin_sum_impl(module, iterable, start);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
-/*[clinic end generated code: output=b42652a0d5f64f6b input=90ae7a242cfcf025]*/
+/*[clinic end generated code: output=33655b248b21d581 input=90ae7a242cfcf025]*/
 {
     PyObject *result = start;
     PyObject *temp, *item, *iter;
@@ -2914,42 +2327,9 @@
 or ...`` etc.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_isinstance__doc__,
-"isinstance($module, obj, class_or_tuple, /)\n"
-"--\n"
-"\n"
-"Return whether an object is an instance of a class or of a subclass thereof.\n"
-"\n"
-"A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to\n"
-"check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)\n"
-"or ...`` etc.");
-
-#define BUILTIN_ISINSTANCE_METHODDEF    \
-    {"isinstance", (PyCFunction)builtin_isinstance, METH_VARARGS, builtin_isinstance__doc__},
-
-static PyObject *
-builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple);
-
-static PyObject *
-builtin_isinstance(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *obj;
-    PyObject *class_or_tuple;
-
-    if (!PyArg_UnpackTuple(args, "isinstance",
-        2, 2,
-        &obj, &class_or_tuple))
-        goto exit;
-    return_value = builtin_isinstance_impl(module, obj, class_or_tuple);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple)
-/*[clinic end generated code: output=847df57fef8ddea7 input=cf9eb0ad6bb9bad6]*/
+/*[clinic end generated code: output=5e234dc3872d75a2 input=cf9eb0ad6bb9bad6]*/
 {
     int retval;
 
@@ -2974,42 +2354,9 @@
 or ...`` etc.
 [clinic start generated code]*/
 
-PyDoc_STRVAR(builtin_issubclass__doc__,
-"issubclass($module, cls, class_or_tuple, /)\n"
-"--\n"
-"\n"
-"Return whether \'cls\' is a derived from another class or is the same class.\n"
-"\n"
-"A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to\n"
-"check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)\n"
-"or ...`` etc.");
-
-#define BUILTIN_ISSUBCLASS_METHODDEF    \
-    {"issubclass", (PyCFunction)builtin_issubclass, METH_VARARGS, builtin_issubclass__doc__},
-
-static PyObject *
-builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple);
-
-static PyObject *
-builtin_issubclass(PyModuleDef *module, PyObject *args)
-{
-    PyObject *return_value = NULL;
-    PyObject *cls;
-    PyObject *class_or_tuple;
-
-    if (!PyArg_UnpackTuple(args, "issubclass",
-        2, 2,
-        &cls, &class_or_tuple))
-        goto exit;
-    return_value = builtin_issubclass_impl(module, cls, class_or_tuple);
-
-exit:
-    return return_value;
-}
-
 static PyObject *
 builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple)
-/*[clinic end generated code: output=a0f8c03692e35474 input=923d03fa41fc352a]*/
+/*[clinic end generated code: output=6346a85ba15dbd7d input=923d03fa41fc352a]*/
 {
     int retval;
 
diff --git a/Python/bltinmodule.c b/Python/clinic/bltinmodule.c.h
copy from Python/bltinmodule.c
copy to Python/clinic/bltinmodule.c.h
--- a/Python/bltinmodule.c
+++ b/Python/clinic/bltinmodule.c.h
@@ -1,242 +1,5 @@
-/* Built-in functions */
-
-#include "Python.h"
-#include "Python-ast.h"
-
-#include "node.h"
-#include "code.h"
-
-#include "asdl.h"
-#include "ast.h"
-
-#include <ctype.h>
-
-#ifdef HAVE_LANGINFO_H
-#include <langinfo.h>   /* CODESET */
-#endif
-
-/* The default encoding used by the platform file system APIs
-   Can remain NULL for all platforms that don't have such a concept
-
-   Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
-   values for Py_FileSystemDefaultEncoding!
-*/
-#ifdef HAVE_MBCS
-const char *Py_FileSystemDefaultEncoding = "mbcs";
-int Py_HasFileSystemDefaultEncoding = 1;
-#elif defined(__APPLE__)
-const char *Py_FileSystemDefaultEncoding = "utf-8";
-int Py_HasFileSystemDefaultEncoding = 1;
-#else
-const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
-int Py_HasFileSystemDefaultEncoding = 0;
-#endif
-
-_Py_IDENTIFIER(__builtins__);
-_Py_IDENTIFIER(__dict__);
-_Py_IDENTIFIER(__prepare__);
-_Py_IDENTIFIER(__round__);
-_Py_IDENTIFIER(encoding);
-_Py_IDENTIFIER(errors);
-_Py_IDENTIFIER(fileno);
-_Py_IDENTIFIER(flush);
-_Py_IDENTIFIER(metaclass);
-_Py_IDENTIFIER(sort);
-_Py_IDENTIFIER(stdin);
-_Py_IDENTIFIER(stdout);
-_Py_IDENTIFIER(stderr);
-
-/* AC: cannot convert yet, waiting for *args support */
-static PyObject *
-builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
-    PyObject *cls = NULL;
-    Py_ssize_t nargs;
-    int isclass = 0;   /* initialize to prevent gcc warning */
-
-    assert(args != NULL);
-    if (!PyTuple_Check(args)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "__build_class__: args is not a tuple");
-        return NULL;
-    }
-    nargs = PyTuple_GET_SIZE(args);
-    if (nargs < 2) {
-        PyErr_SetString(PyExc_TypeError,
-                        "__build_class__: not enough arguments");
-        return NULL;
-    }
-    func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
-    if (!PyFunction_Check(func)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "__build_class__: func must be a function");
-        return NULL;
-    }
-    name = PyTuple_GET_ITEM(args, 1);
-    if (!PyUnicode_Check(name)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "__build_class__: name is not a string");
-        return NULL;
-    }
-    bases = PyTuple_GetSlice(args, 2, nargs);
-    if (bases == NULL)
-        return NULL;
-
-    if (kwds == NULL) {
-        meta = NULL;
-        mkw = NULL;
-    }
-    else {
-        mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
-        if (mkw == NULL) {
-            Py_DECREF(bases);
-            return NULL;
-        }
-        meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
-        if (meta != NULL) {
-            Py_INCREF(meta);
-            if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
-                Py_DECREF(meta);
-                Py_DECREF(mkw);
-                Py_DECREF(bases);
-                return NULL;
-            }
-            /* metaclass is explicitly given, check if it's indeed a class */
-            isclass = PyType_Check(meta);
-        }
-    }
-    if (meta == NULL) {
-        /* if there are no bases, use type: */
-        if (PyTuple_GET_SIZE(bases) == 0) {
-            meta = (PyObject *) (&PyType_Type);
-        }
-        /* else get the type of the first base */
-        else {
-            PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
-            meta = (PyObject *) (base0->ob_type);
-        }
-        Py_INCREF(meta);
-        isclass = 1;  /* meta is really a class */
-    }
-
-    if (isclass) {
-        /* meta is really a class, so check for a more derived
-           metaclass, or possible metaclass conflicts: */
-        winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
-                                                        bases);
-        if (winner == NULL) {
-            Py_DECREF(meta);
-            Py_XDECREF(mkw);
-            Py_DECREF(bases);
-            return NULL;
-        }
-        if (winner != meta) {
-            Py_DECREF(meta);
-            meta = winner;
-            Py_INCREF(meta);
-        }
-    }
-    /* else: meta is not a class, so we cannot do the metaclass
-       calculation, so we will use the explicitly given object as it is */
-    prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
-    if (prep == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
-            PyErr_Clear();
-            ns = PyDict_New();
-        }
-        else {
-            Py_DECREF(meta);
-            Py_XDECREF(mkw);
-            Py_DECREF(bases);
-            return NULL;
-        }
-    }
-    else {
-        PyObject *pargs = PyTuple_Pack(2, name, bases);
-        if (pargs == NULL) {
-            Py_DECREF(prep);
-            Py_DECREF(meta);
-            Py_XDECREF(mkw);
-            Py_DECREF(bases);
-            return NULL;
-        }
-        ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
-        Py_DECREF(pargs);
-        Py_DECREF(prep);
-    }
-    if (ns == NULL) {
-        Py_DECREF(meta);
-        Py_XDECREF(mkw);
-        Py_DECREF(bases);
-        return NULL;
-    }
-    cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
-                             NULL, 0, NULL, 0, NULL, 0, NULL,
-                             PyFunction_GET_CLOSURE(func));
-    if (cell != NULL) {
-        PyObject *margs;
-        margs = PyTuple_Pack(3, name, bases, ns);
-        if (margs != NULL) {
-            cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
-            Py_DECREF(margs);
-        }
-        if (cls != NULL && PyCell_Check(cell))
-            PyCell_Set(cell, cls);
-        Py_DECREF(cell);
-    }
-    Py_DECREF(ns);
-    Py_DECREF(meta);
-    Py_XDECREF(mkw);
-    Py_DECREF(bases);
-    return cls;
-}
-
-PyDoc_STRVAR(build_class_doc,
-"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
-\n\
-Internal helper function used by the class statement.");
-
-static PyObject *
-builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    static char *kwlist[] = {"name", "globals", "locals", "fromlist",
-                             "level", 0};
-    PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
-    int level = 0;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
-                    kwlist, &name, &globals, &locals, &fromlist, &level))
-        return NULL;
-    return PyImport_ImportModuleLevelObject(name, globals, locals,
-                                            fromlist, level);
-}
-
-PyDoc_STRVAR(import_doc,
-"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
-\n\
-Import a module. Because this function is meant for use by the Python\n\
-interpreter and not for general use it is better to use\n\
-importlib.import_module() to programmatically import a module.\n\
-\n\
-The globals argument is only used to determine the context;\n\
-they are not modified.  The locals argument is unused.  The fromlist\n\
-should be a list of names to emulate ``from name import ...'', or an\n\
-empty list to emulate ``import name''.\n\
-When importing a module from a package, note that __import__('A.B', ...)\n\
-returns package A when fromlist is empty, but its submodule B when\n\
-fromlist is not empty.  Level is used to determine whether to perform \n\
-absolute or relative imports. 0 is absolute while a positive number\n\
-is the number of parent directories to search relative to the current module.");
-
-
 /*[clinic input]
-abs as builtin_abs
-
-    x: 'O'
-    /
-
-Return the absolute value of the argument.
+preserve
 [clinic start generated code]*/
 
 PyDoc_STRVAR(builtin_abs__doc__,
@@ -248,24 +11,6 @@
 #define BUILTIN_ABS_METHODDEF    \
     {"abs", (PyCFunction)builtin_abs, METH_O, builtin_abs__doc__},
 
-static PyObject *
-builtin_abs(PyModuleDef *module, PyObject *x)
-/*[clinic end generated code: output=f85095528ce7e2e5 input=aa29cc07869b4732]*/
-{
-    return PyNumber_Absolute(x);
-}
-
-/*[clinic input]
-all as builtin_all
-
-    iterable: 'O'
-    /
-
-Return True if bool(x) is True for all values x in the iterable.
-
-If the iterable is empty, return True.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_all__doc__,
 "all($module, iterable, /)\n"
 "--\n"
@@ -277,55 +22,6 @@
 #define BUILTIN_ALL_METHODDEF    \
     {"all", (PyCFunction)builtin_all, METH_O, builtin_all__doc__},
 
-static PyObject *
-builtin_all(PyModuleDef *module, PyObject *iterable)
-/*[clinic end generated code: output=d001db739ba83b46 input=dd506dc9998d42bd]*/
-{
-    PyObject *it, *item;
-    PyObject *(*iternext)(PyObject *);
-    int cmp;
-
-    it = PyObject_GetIter(iterable);
-    if (it == NULL)
-        return NULL;
-    iternext = *Py_TYPE(it)->tp_iternext;
-
-    for (;;) {
-        item = iternext(it);
-        if (item == NULL)
-            break;
-        cmp = PyObject_IsTrue(item);
-        Py_DECREF(item);
-        if (cmp < 0) {
-            Py_DECREF(it);
-            return NULL;
-        }
-        if (cmp == 0) {
-            Py_DECREF(it);
-            Py_RETURN_FALSE;
-        }
-    }
-    Py_DECREF(it);
-    if (PyErr_Occurred()) {
-        if (PyErr_ExceptionMatches(PyExc_StopIteration))
-            PyErr_Clear();
-        else
-            return NULL;
-    }
-    Py_RETURN_TRUE;
-}
-
-/*[clinic input]
-any as builtin_any
-
-    iterable: 'O'
-    /
-
-Return True if bool(x) is True for any x in the iterable.
-
-If the iterable is empty, return False.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_any__doc__,
 "any($module, iterable, /)\n"
 "--\n"
@@ -337,58 +33,6 @@
 #define BUILTIN_ANY_METHODDEF    \
     {"any", (PyCFunction)builtin_any, METH_O, builtin_any__doc__},
 
-static PyObject *
-builtin_any(PyModuleDef *module, PyObject *iterable)
-/*[clinic end generated code: output=3a4b6dbe6a0d6f61 input=8fe8460f3fbbced8]*/
-{
-    PyObject *it, *item;
-    PyObject *(*iternext)(PyObject *);
-    int cmp;
-
-    it = PyObject_GetIter(iterable);
-    if (it == NULL)
-        return NULL;
-    iternext = *Py_TYPE(it)->tp_iternext;
-
-    for (;;) {
-        item = iternext(it);
-        if (item == NULL)
-            break;
-        cmp = PyObject_IsTrue(item);
-        Py_DECREF(item);
-        if (cmp < 0) {
-            Py_DECREF(it);
-            return NULL;
-        }
-        if (cmp == 1) {
-            Py_DECREF(it);
-            Py_RETURN_TRUE;
-        }
-    }
-    Py_DECREF(it);
-    if (PyErr_Occurred()) {
-        if (PyErr_ExceptionMatches(PyExc_StopIteration))
-            PyErr_Clear();
-        else
-            return NULL;
-    }
-    Py_RETURN_FALSE;
-}
-
-/*[clinic input]
-ascii as builtin_ascii
-
-    obj: 'O'
-    /
-
-Return an ASCII-only representation of an object.
-
-As repr(), return a string containing a printable representation of an
-object, but escape the non-ASCII characters in the string returned by
-repr() using \\x, \\u or \\U escapes. This generates a string similar
-to that returned by repr() in Python 2.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_ascii__doc__,
 "ascii($module, obj, /)\n"
 "--\n"
@@ -403,26 +47,6 @@
 #define BUILTIN_ASCII_METHODDEF    \
     {"ascii", (PyCFunction)builtin_ascii, METH_O, builtin_ascii__doc__},
 
-static PyObject *
-builtin_ascii(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=f0e6754154c2d30b input=0cbdc1420a306325]*/
-{
-    return PyObject_ASCII(obj);
-}
-
-
-/*[clinic input]
-bin as builtin_bin
-
-    number: 'O'
-    /
-
-Return the binary representation of an integer.
-
-   >>> bin(2796202)
-   '0b1010101010101010101010'
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_bin__doc__,
 "bin($module, number, /)\n"
 "--\n"
@@ -435,26 +59,6 @@
 #define BUILTIN_BIN_METHODDEF    \
     {"bin", (PyCFunction)builtin_bin, METH_O, builtin_bin__doc__},
 
-static PyObject *
-builtin_bin(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=18fed0e943650da1 input=2a6362ae9a9c9203]*/
-{
-    return PyNumber_ToBase(number, 2);
-}
-
-
-/*[clinic input]
-callable as builtin_callable
-
-    obj: 'O'
-    /
-
-Return whether the object is callable (i.e., some kind of function).
-
-Note that classes are callable, as are instances of classes with a
-__call__() method.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_callable__doc__,
 "callable($module, obj, /)\n"
 "--\n"
@@ -467,179 +71,6 @@
 #define BUILTIN_CALLABLE_METHODDEF    \
     {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__},
 
-static PyObject *
-builtin_callable(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=b3a92cbe635f32af input=bb3bb528fffdade4]*/
-{
-    return PyBool_FromLong((long)PyCallable_Check(obj));
-}
-
-
-typedef struct {
-    PyObject_HEAD
-    PyObject *func;
-    PyObject *it;
-} filterobject;
-
-static PyObject *
-filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *func, *seq;
-    PyObject *it;
-    filterobject *lz;
-
-    if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
-        return NULL;
-
-    if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
-        return NULL;
-
-    /* Get iterator. */
-    it = PyObject_GetIter(seq);
-    if (it == NULL)
-        return NULL;
-
-    /* create filterobject structure */
-    lz = (filterobject *)type->tp_alloc(type, 0);
-    if (lz == NULL) {
-        Py_DECREF(it);
-        return NULL;
-    }
-    Py_INCREF(func);
-    lz->func = func;
-    lz->it = it;
-
-    return (PyObject *)lz;
-}
-
-static void
-filter_dealloc(filterobject *lz)
-{
-    PyObject_GC_UnTrack(lz);
-    Py_XDECREF(lz->func);
-    Py_XDECREF(lz->it);
-    Py_TYPE(lz)->tp_free(lz);
-}
-
-static int
-filter_traverse(filterobject *lz, visitproc visit, void *arg)
-{
-    Py_VISIT(lz->it);
-    Py_VISIT(lz->func);
-    return 0;
-}
-
-static PyObject *
-filter_next(filterobject *lz)
-{
-    PyObject *item;
-    PyObject *it = lz->it;
-    long ok;
-    PyObject *(*iternext)(PyObject *);
-
-    iternext = *Py_TYPE(it)->tp_iternext;
-    for (;;) {
-        item = iternext(it);
-        if (item == NULL)
-            return NULL;
-
-        if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
-            ok = PyObject_IsTrue(item);
-        } else {
-            PyObject *good;
-            good = PyObject_CallFunctionObjArgs(lz->func,
-                                                item, NULL);
-            if (good == NULL) {
-                Py_DECREF(item);
-                return NULL;
-            }
-            ok = PyObject_IsTrue(good);
-            Py_DECREF(good);
-        }
-        if (ok > 0)
-            return item;
-        Py_DECREF(item);
-        if (ok < 0)
-            return NULL;
-    }
-}
-
-static PyObject *
-filter_reduce(filterobject *lz)
-{
-    return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
-}
-
-PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
-
-static PyMethodDef filter_methods[] = {
-    {"__reduce__",   (PyCFunction)filter_reduce,   METH_NOARGS, reduce_doc},
-    {NULL,           NULL}           /* sentinel */
-};
-
-PyDoc_STRVAR(filter_doc,
-"filter(function or None, iterable) --> filter object\n\
-\n\
-Return an iterator yielding those items of iterable for which function(item)\n\
-is true. If function is None, return the items that are true.");
-
-PyTypeObject PyFilter_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "filter",                           /* tp_name */
-    sizeof(filterobject),               /* tp_basicsize */
-    0,                                  /* tp_itemsize */
-    /* methods */
-    (destructor)filter_dealloc,         /* tp_dealloc */
-    0,                                  /* tp_print */
-    0,                                  /* tp_getattr */
-    0,                                  /* tp_setattr */
-    0,                                  /* tp_reserved */
-    0,                                  /* tp_repr */
-    0,                                  /* tp_as_number */
-    0,                                  /* tp_as_sequence */
-    0,                                  /* tp_as_mapping */
-    0,                                  /* tp_hash */
-    0,                                  /* tp_call */
-    0,                                  /* tp_str */
-    PyObject_GenericGetAttr,            /* tp_getattro */
-    0,                                  /* tp_setattro */
-    0,                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-        Py_TPFLAGS_BASETYPE,            /* tp_flags */
-    filter_doc,                         /* tp_doc */
-    (traverseproc)filter_traverse,      /* tp_traverse */
-    0,                                  /* tp_clear */
-    0,                                  /* tp_richcompare */
-    0,                                  /* tp_weaklistoffset */
-    PyObject_SelfIter,                  /* tp_iter */
-    (iternextfunc)filter_next,          /* tp_iternext */
-    filter_methods,                     /* tp_methods */
-    0,                                  /* tp_members */
-    0,                                  /* tp_getset */
-    0,                                  /* tp_base */
-    0,                                  /* tp_dict */
-    0,                                  /* tp_descr_get */
-    0,                                  /* tp_descr_set */
-    0,                                  /* tp_dictoffset */
-    0,                                  /* tp_init */
-    PyType_GenericAlloc,                /* tp_alloc */
-    filter_new,                         /* tp_new */
-    PyObject_GC_Del,                    /* tp_free */
-};
-
-
-/*[clinic input]
-format as builtin_format
-
-    value: 'O'
-    format_spec: unicode(c_default="NULL") = ''
-    /
-
-Return value.__format__(format_spec)
-
-format_spec defaults to the empty string
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_format__doc__,
 "format($module, value, format_spec=\'\', /)\n"
 "--\n"
@@ -671,22 +102,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_format_impl(PyModuleDef *module, PyObject *value, PyObject *format_spec)
-/*[clinic end generated code: output=39723a58c72e8871 input=e23f2f11e0098c64]*/
-{
-    return PyObject_Format(value, format_spec);
-}
-
-/*[clinic input]
-chr as builtin_chr
-
-    i: 'i'
-    /
-
-Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_chr__doc__,
 "chr($module, i, /)\n"
 "--\n"
@@ -715,70 +130,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_chr_impl(PyModuleDef *module, int i)
-/*[clinic end generated code: output=4d6bbe948f56e2ae input=9b1ced29615adf66]*/
-{
-    return PyUnicode_FromOrdinal(i);
-}
-
-
-static const char *
-source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, Py_buffer *view)
-{
-    const char *str;
-    Py_ssize_t size;
-
-    if (PyUnicode_Check(cmd)) {
-        cf->cf_flags |= PyCF_IGNORE_COOKIE;
-        str = PyUnicode_AsUTF8AndSize(cmd, &size);
-        if (str == NULL)
-            return NULL;
-    }
-    else if (PyObject_GetBuffer(cmd, view, PyBUF_SIMPLE) == 0) {
-        str = (const char *)view->buf;
-        size = view->len;
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-          "%s() arg 1 must be a %s object",
-          funcname, what);
-        return NULL;
-    }
-
-    if (strlen(str) != (size_t)size) {
-        PyErr_SetString(PyExc_ValueError,
-                        "source code string cannot contain null bytes");
-        PyBuffer_Release(view);
-        return NULL;
-    }
-    return str;
-}
-
-/*[clinic input]
-compile as builtin_compile
-
-    source: 'O'
-    filename: object(converter="PyUnicode_FSDecoder")
-    mode: 's'
-    flags: 'i' = 0
-    dont_inherit: 'i' = 0
-    optimize: 'i' = -1
-
-Compile source into a code object that can be executed by exec() or eval().
-
-The source code may represent a Python module, statement or expression.
-The filename will be used for run-time error messages.
-The mode must be 'exec' to compile a module, 'single' to compile a
-single (interactive) statement, or 'eval' to compile an expression.
-The flags argument, if present, controls which future statements influence
-the compilation of the code.
-The dont_inherit argument, if non-zero, stops the compilation inheriting
-the effects of any future statements in effect in the code calling
-compile; if absent or zero these statements do influence the compilation,
-in addition to any features explicitly specified.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_compile__doc__,
 "compile($module, /, source, filename, mode, flags=0, dont_inherit=0,\n"
 "        optimize=-1)\n"
@@ -825,132 +176,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize)
-/*[clinic end generated code: output=c72d197809d178fc input=c6212a9d21472f7e]*/
-{
-    Py_buffer view = {NULL, NULL};
-    const char *str;
-    int compile_mode = -1;
-    int is_ast;
-    PyCompilerFlags cf;
-    int start[] = {Py_file_input, Py_eval_input, Py_single_input};
-    PyObject *result;
-
-    cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
-
-    if (flags &
-        ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
-    {
-        PyErr_SetString(PyExc_ValueError,
-                        "compile(): unrecognised flags");
-        goto error;
-    }
-    /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
-
-    if (optimize < -1 || optimize > 2) {
-        PyErr_SetString(PyExc_ValueError,
-                        "compile(): invalid optimize value");
-        goto error;
-    }
-
-    if (!dont_inherit) {
-        PyEval_MergeCompilerFlags(&cf);
-    }
-
-    if (strcmp(mode, "exec") == 0)
-        compile_mode = 0;
-    else if (strcmp(mode, "eval") == 0)
-        compile_mode = 1;
-    else if (strcmp(mode, "single") == 0)
-        compile_mode = 2;
-    else {
-        PyErr_SetString(PyExc_ValueError,
-                        "compile() mode must be 'exec', 'eval' or 'single'");
-        goto error;
-    }
-
-    is_ast = PyAST_Check(source);
-    if (is_ast == -1)
-        goto error;
-    if (is_ast) {
-        if (flags & PyCF_ONLY_AST) {
-            Py_INCREF(source);
-            result = source;
-        }
-        else {
-            PyArena *arena;
-            mod_ty mod;
-
-            arena = PyArena_New();
-            if (arena == NULL)
-                goto error;
-            mod = PyAST_obj2mod(source, arena, compile_mode);
-            if (mod == NULL) {
-                PyArena_Free(arena);
-                goto error;
-            }
-            if (!PyAST_Validate(mod)) {
-                PyArena_Free(arena);
-                goto error;
-            }
-            result = (PyObject*)PyAST_CompileObject(mod, filename,
-                                                    &cf, optimize, arena);
-            PyArena_Free(arena);
-        }
-        goto finally;
-    }
-
-    str = source_as_string(source, "compile", "string, bytes or AST", &cf, &view);
-    if (str == NULL)
-        goto error;
-
-    result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
-    PyBuffer_Release(&view);
-    goto finally;
-
-error:
-    result = NULL;
-finally:
-    Py_DECREF(filename);
-    return result;
-}
-
-/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
-static PyObject *
-builtin_dir(PyObject *self, PyObject *args)
-{
-    PyObject *arg = NULL;
-
-    if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
-        return NULL;
-    return PyObject_Dir(arg);
-}
-
-PyDoc_STRVAR(dir_doc,
-"dir([object]) -> list of strings\n"
-"\n"
-"If called without an argument, return the names in the current scope.\n"
-"Else, return an alphabetized list of names comprising (some of) the attributes\n"
-"of the given object, and of attributes reachable from it.\n"
-"If the object supplies a method named __dir__, it will be used; otherwise\n"
-"the default dir() logic is used and returns:\n"
-"  for a module object: the module's attributes.\n"
-"  for a class object:  its attributes, and recursively the attributes\n"
-"    of its bases.\n"
-"  for any other object: its attributes, its class's attributes, and\n"
-"    recursively the attributes of its class's base classes.");
-
-/*[clinic input]
-divmod as builtin_divmod
-
-    x: 'O'
-    y: 'O'
-    /
-
-Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_divmod__doc__,
 "divmod($module, x, y, /)\n"
 "--\n"
@@ -980,31 +205,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
-/*[clinic end generated code: output=77e8d408b1338886 input=c9c617b7bb74c615]*/
-{
-    return PyNumber_Divmod(x, y);
-}
-
-
-/*[clinic input]
-eval as builtin_eval
-
-    source: 'O'
-    globals: 'O' = None
-    locals: 'O' = None
-    /
-
-Evaluate the given source in the context of globals and locals.
-
-The source may be a string representing a Python expression
-or a code object as returned by compile().
-The globals must be a dictionary and locals can be any mapping,
-defaulting to the current globals and locals.
-If only globals is given, locals defaults to it.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_eval__doc__,
 "eval($module, source, globals=None, locals=None, /)\n"
 "--\n"
@@ -1041,90 +241,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
-/*[clinic end generated code: output=644fd59012538ce6 input=31e42c1d2125b50b]*/
-{
-    PyObject *result, *tmp = NULL;
-    Py_buffer view = {NULL, NULL};
-    const char *str;
-    PyCompilerFlags cf;
-
-    if (locals != Py_None && !PyMapping_Check(locals)) {
-        PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
-        return NULL;
-    }
-    if (globals != Py_None && !PyDict_Check(globals)) {
-        PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
-            "globals must be a real dict; try eval(expr, {}, mapping)"
-            : "globals must be a dict");
-        return NULL;
-    }
-    if (globals == Py_None) {
-        globals = PyEval_GetGlobals();
-        if (locals == Py_None) {
-            locals = PyEval_GetLocals();
-            if (locals == NULL)
-                return NULL;
-        }
-    }
-    else if (locals == Py_None)
-        locals = globals;
-
-    if (globals == NULL || locals == NULL) {
-        PyErr_SetString(PyExc_TypeError,
-            "eval must be given globals and locals "
-            "when called without a frame");
-        return NULL;
-    }
-
-    if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
-        if (_PyDict_SetItemId(globals, &PyId___builtins__,
-                              PyEval_GetBuiltins()) != 0)
-            return NULL;
-    }
-
-    if (PyCode_Check(source)) {
-        if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
-            PyErr_SetString(PyExc_TypeError,
-        "code object passed to eval() may not contain free variables");
-            return NULL;
-        }
-        return PyEval_EvalCode(source, globals, locals);
-    }
-
-    cf.cf_flags = PyCF_SOURCE_IS_UTF8;
-    str = source_as_string(source, "eval", "string, bytes or code", &cf, &view);
-    if (str == NULL)
-        return NULL;
-
-    while (*str == ' ' || *str == '\t')
-        str++;
-
-    (void)PyEval_MergeCompilerFlags(&cf);
-    result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
-    PyBuffer_Release(&view);
-    Py_XDECREF(tmp);
-    return result;
-}
-
-/*[clinic input]
-exec as builtin_exec
-
-    source: 'O'
-    globals: 'O' = None
-    locals: 'O' = None
-    /
-
-Execute the given source in the context of globals and locals.
-
-The source may be a string representing one or more Python statements
-or a code object as returned by compile().
-The globals must be a dictionary and locals can be any mapping,
-defaulting to the current globals and locals.
-If only globals is given, locals defaults to it.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_exec__doc__,
 "exec($module, source, globals=None, locals=None, /)\n"
 "--\n"
@@ -1161,120 +277,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
-/*[clinic end generated code: output=0281b48bfa8e3c87 input=536e057b5e00d89e]*/
-{
-    PyObject *v;
-
-    if (globals == Py_None) {
-        globals = PyEval_GetGlobals();
-        if (locals == Py_None) {
-            locals = PyEval_GetLocals();
-            if (locals == NULL)
-                return NULL;
-        }
-        if (!globals || !locals) {
-            PyErr_SetString(PyExc_SystemError,
-                            "globals and locals cannot be NULL");
-            return NULL;
-        }
-    }
-    else if (locals == Py_None)
-        locals = globals;
-
-    if (!PyDict_Check(globals)) {
-        PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
-                     globals->ob_type->tp_name);
-        return NULL;
-    }
-    if (!PyMapping_Check(locals)) {
-        PyErr_Format(PyExc_TypeError,
-            "locals must be a mapping or None, not %.100s",
-            locals->ob_type->tp_name);
-        return NULL;
-    }
-    if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
-        if (_PyDict_SetItemId(globals, &PyId___builtins__,
-                              PyEval_GetBuiltins()) != 0)
-            return NULL;
-    }
-
-    if (PyCode_Check(source)) {
-        if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
-            PyErr_SetString(PyExc_TypeError,
-                "code object passed to exec() may not "
-                "contain free variables");
-            return NULL;
-        }
-        v = PyEval_EvalCode(source, globals, locals);
-    }
-    else {
-        Py_buffer view = {NULL, NULL};
-        const char *str;
-        PyCompilerFlags cf;
-        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
-        str = source_as_string(source, "exec",
-                                       "string, bytes or code", &cf, &view);
-        if (str == NULL)
-            return NULL;
-        if (PyEval_MergeCompilerFlags(&cf))
-            v = PyRun_StringFlags(str, Py_file_input, globals,
-                                  locals, &cf);
-        else
-            v = PyRun_String(str, Py_file_input, globals, locals);
-        PyBuffer_Release(&view);
-    }
-    if (v == NULL)
-        return NULL;
-    Py_DECREF(v);
-    Py_RETURN_NONE;
-}
-
-
-/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
-static PyObject *
-builtin_getattr(PyObject *self, PyObject *args)
-{
-    PyObject *v, *result, *dflt = NULL;
-    PyObject *name;
-
-    if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
-        return NULL;
-
-    if (!PyUnicode_Check(name)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "getattr(): attribute name must be string");
-        return NULL;
-    }
-    result = PyObject_GetAttr(v, name);
-    if (result == NULL && dflt != NULL &&
-        PyErr_ExceptionMatches(PyExc_AttributeError))
-    {
-        PyErr_Clear();
-        Py_INCREF(dflt);
-        result = dflt;
-    }
-    return result;
-}
-
-PyDoc_STRVAR(getattr_doc,
-"getattr(object, name[, default]) -> value\n\
-\n\
-Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
-When a default argument is given, it is returned when the attribute doesn't\n\
-exist; without it, an exception is raised in that case.");
-
-
-/*[clinic input]
-globals as builtin_globals
-
-Return the dictionary containing the current scope's global variables.
-
-NOTE: Updates to this dictionary *will* affect name lookups in the current
-global scope and vice-versa.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_globals__doc__,
 "globals($module, /)\n"
 "--\n"
@@ -1296,30 +298,6 @@
     return builtin_globals_impl(module);
 }
 
-static PyObject *
-builtin_globals_impl(PyModuleDef *module)
-/*[clinic end generated code: output=048640f58b1f20ad input=9327576f92bb48ba]*/
-{
-    PyObject *d;
-
-    d = PyEval_GetGlobals();
-    Py_XINCREF(d);
-    return d;
-}
-
-
-/*[clinic input]
-hasattr as builtin_hasattr
-
-    obj: 'O'
-    name: 'O'
-    /
-
-Return whether the object has an attribute with the given name.
-
-This is done by calling getattr(obj, name) and catching AttributeError.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_hasattr__doc__,
 "hasattr($module, obj, name, /)\n"
 "--\n"
@@ -1351,47 +329,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
-/*[clinic end generated code: output=e0bd996ef73d1217 input=b50bad5f739ea10d]*/
-{
-    PyObject *v;
-
-    if (!PyUnicode_Check(name)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "hasattr(): attribute name must be string");
-        return NULL;
-    }
-    v = PyObject_GetAttr(obj, name);
-    if (v == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
-            PyErr_Clear();
-            Py_RETURN_FALSE;
-        }
-        return NULL;
-    }
-    Py_DECREF(v);
-    Py_RETURN_TRUE;
-}
-
-
-/* AC: gdb's integration with CPython relies on builtin_id having
- * the *exact* parameter names of "self" and "v", so we ensure we
- * preserve those name rather than using the AC defaults.
- */
-/*[clinic input]
-id as builtin_id
-
-    self: self(type="PyModuleDef *")
-    obj as v: 'O'
-    /
-
-Return the identity of an object.
-
-This is guaranteed to be unique among simultaneously existing objects.
-(CPython uses the object's memory address.)
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_id__doc__,
 "id($module, obj, /)\n"
 "--\n"
@@ -1404,241 +341,6 @@
 #define BUILTIN_ID_METHODDEF    \
     {"id", (PyCFunction)builtin_id, METH_O, builtin_id__doc__},
 
-static PyObject *
-builtin_id(PyModuleDef *self, PyObject *v)
-/*[clinic end generated code: output=f54da09c91992e63 input=a1f988d98357341d]*/
-{
-    return PyLong_FromVoidPtr(v);
-}
-
-
-/* map object ************************************************************/
-
-typedef struct {
-    PyObject_HEAD
-    PyObject *iters;
-    PyObject *func;
-} mapobject;
-
-static PyObject *
-map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    PyObject *it, *iters, *func;
-    mapobject *lz;
-    Py_ssize_t numargs, i;
-
-    if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
-        return NULL;
-
-    numargs = PyTuple_Size(args);
-    if (numargs < 2) {
-        PyErr_SetString(PyExc_TypeError,
-           "map() must have at least two arguments.");
-        return NULL;
-    }
-
-    iters = PyTuple_New(numargs-1);
-    if (iters == NULL)
-        return NULL;
-
-    for (i=1 ; i<numargs ; i++) {
-        /* Get iterator. */
-        it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
-        if (it == NULL) {
-            Py_DECREF(iters);
-            return NULL;
-        }
-        PyTuple_SET_ITEM(iters, i-1, it);
-    }
-
-    /* create mapobject structure */
-    lz = (mapobject *)type->tp_alloc(type, 0);
-    if (lz == NULL) {
-        Py_DECREF(iters);
-        return NULL;
-    }
-    lz->iters = iters;
-    func = PyTuple_GET_ITEM(args, 0);
-    Py_INCREF(func);
-    lz->func = func;
-
-    return (PyObject *)lz;
-}
-
-static void
-map_dealloc(mapobject *lz)
-{
-    PyObject_GC_UnTrack(lz);
-    Py_XDECREF(lz->iters);
-    Py_XDECREF(lz->func);
-    Py_TYPE(lz)->tp_free(lz);
-}
-
-static int
-map_traverse(mapobject *lz, visitproc visit, void *arg)
-{
-    Py_VISIT(lz->iters);
-    Py_VISIT(lz->func);
-    return 0;
-}
-
-static PyObject *
-map_next(mapobject *lz)
-{
-    PyObject *val;
-    PyObject *argtuple;
-    PyObject *result;
-    Py_ssize_t numargs, i;
-
-    numargs = PyTuple_Size(lz->iters);
-    argtuple = PyTuple_New(numargs);
-    if (argtuple == NULL)
-        return NULL;
-
-    for (i=0 ; i<numargs ; i++) {
-        val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
-        if (val == NULL) {
-            Py_DECREF(argtuple);
-            return NULL;
-        }
-        PyTuple_SET_ITEM(argtuple, i, val);
-    }
-    result = PyObject_Call(lz->func, argtuple, NULL);
-    Py_DECREF(argtuple);
-    return result;
-}
-
-static PyObject *
-map_reduce(mapobject *lz)
-{
-    Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
-    PyObject *args = PyTuple_New(numargs+1);
-    Py_ssize_t i;
-    if (args == NULL)
-        return NULL;
-    Py_INCREF(lz->func);
-    PyTuple_SET_ITEM(args, 0, lz->func);
-    for (i = 0; i<numargs; i++){
-        PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
-        Py_INCREF(it);
-        PyTuple_SET_ITEM(args, i+1, it);
-    }
-
-    return Py_BuildValue("ON", Py_TYPE(lz), args);
-}
-
-static PyMethodDef map_methods[] = {
-    {"__reduce__",   (PyCFunction)map_reduce,   METH_NOARGS, reduce_doc},
-    {NULL,           NULL}           /* sentinel */
-};
-
-
-PyDoc_STRVAR(map_doc,
-"map(func, *iterables) --> map object\n\
-\n\
-Make an iterator that computes the function using arguments from\n\
-each of the iterables.  Stops when the shortest iterable is exhausted.");
-
-PyTypeObject PyMap_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "map",                              /* tp_name */
-    sizeof(mapobject),                  /* tp_basicsize */
-    0,                                  /* tp_itemsize */
-    /* methods */
-    (destructor)map_dealloc,            /* tp_dealloc */
-    0,                                  /* tp_print */
-    0,                                  /* tp_getattr */
-    0,                                  /* tp_setattr */
-    0,                                  /* tp_reserved */
-    0,                                  /* tp_repr */
-    0,                                  /* tp_as_number */
-    0,                                  /* tp_as_sequence */
-    0,                                  /* tp_as_mapping */
-    0,                                  /* tp_hash */
-    0,                                  /* tp_call */
-    0,                                  /* tp_str */
-    PyObject_GenericGetAttr,            /* tp_getattro */
-    0,                                  /* tp_setattro */
-    0,                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-        Py_TPFLAGS_BASETYPE,            /* tp_flags */
-    map_doc,                            /* tp_doc */
-    (traverseproc)map_traverse,         /* tp_traverse */
-    0,                                  /* tp_clear */
-    0,                                  /* tp_richcompare */
-    0,                                  /* tp_weaklistoffset */
-    PyObject_SelfIter,                  /* tp_iter */
-    (iternextfunc)map_next,     /* tp_iternext */
-    map_methods,                        /* tp_methods */
-    0,                                  /* tp_members */
-    0,                                  /* tp_getset */
-    0,                                  /* tp_base */
-    0,                                  /* tp_dict */
-    0,                                  /* tp_descr_get */
-    0,                                  /* tp_descr_set */
-    0,                                  /* tp_dictoffset */
-    0,                                  /* tp_init */
-    PyType_GenericAlloc,                /* tp_alloc */
-    map_new,                            /* tp_new */
-    PyObject_GC_Del,                    /* tp_free */
-};
-
-
-/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
-static PyObject *
-builtin_next(PyObject *self, PyObject *args)
-{
-    PyObject *it, *res;
-    PyObject *def = NULL;
-
-    if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
-        return NULL;
-    if (!PyIter_Check(it)) {
-        PyErr_Format(PyExc_TypeError,
-            "'%.200s' object is not an iterator",
-            it->ob_type->tp_name);
-        return NULL;
-    }
-
-    res = (*it->ob_type->tp_iternext)(it);
-    if (res != NULL) {
-        return res;
-    } else if (def != NULL) {
-        if (PyErr_Occurred()) {
-            if(!PyErr_ExceptionMatches(PyExc_StopIteration))
-                return NULL;
-            PyErr_Clear();
-        }
-        Py_INCREF(def);
-        return def;
-    } else if (PyErr_Occurred()) {
-        return NULL;
-    } else {
-        PyErr_SetNone(PyExc_StopIteration);
-        return NULL;
-    }
-}
-
-PyDoc_STRVAR(next_doc,
-"next(iterator[, default])\n\
-\n\
-Return the next item from the iterator. If default is given and the iterator\n\
-is exhausted, it is returned instead of raising StopIteration.");
-
-
-/*[clinic input]
-setattr as builtin_setattr
-
-    obj: 'O'
-    name: 'O'
-    value: 'O'
-    /
-
-Sets the named attribute on the given object to the specified value.
-
-setattr(x, 'y', v) is equivalent to ``x.y = v''
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_setattr__doc__,
 "setattr($module, obj, name, value, /)\n"
 "--\n"
@@ -1671,29 +373,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=4336dcbbf7691d2d input=fbe7e53403116b93]*/
-{
-    if (PyObject_SetAttr(obj, name, value) != 0)
-        return NULL;
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-
-/*[clinic input]
-delattr as builtin_delattr
-
-    obj: 'O'
-    name: 'O'
-    /
-
-Deletes the named attribute from the given object.
-
-delattr(x, 'y') is equivalent to ``del x.y''
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_delattr__doc__,
 "delattr($module, obj, name, /)\n"
 "--\n"
@@ -1725,29 +404,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
-/*[clinic end generated code: output=319c2d884aa769cf input=647af2ce9183a823]*/
-{
-    if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
-        return NULL;
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-
-/*[clinic input]
-hash as builtin_hash
-
-    obj: 'O'
-    /
-
-Return the hash value for the given object.
-
-Two objects that compare equal must also have the same hash value, but the
-reverse is not necessarily true.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_hash__doc__,
 "hash($module, obj, /)\n"
 "--\n"
@@ -1760,31 +416,6 @@
 #define BUILTIN_HASH_METHODDEF    \
     {"hash", (PyCFunction)builtin_hash, METH_O, builtin_hash__doc__},
 
-static PyObject *
-builtin_hash(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=1ec467611c13468b input=ccc4d2b9a351df4e]*/
-{
-    Py_hash_t x;
-
-    x = PyObject_Hash(obj);
-    if (x == -1)
-        return NULL;
-    return PyLong_FromSsize_t(x);
-}
-
-
-/*[clinic input]
-hex as builtin_hex
-
-    number: 'O'
-    /
-
-Return the hexadecimal representation of an integer.
-
-   >>> hex(12648430)
-   '0xc0ffee'
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_hex__doc__,
 "hex($module, number, /)\n"
 "--\n"
@@ -1797,50 +428,6 @@
 #define BUILTIN_HEX_METHODDEF    \
     {"hex", (PyCFunction)builtin_hex, METH_O, builtin_hex__doc__},
 
-static PyObject *
-builtin_hex(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=f18e9439aeaa2c6c input=e816200b0a728ebe]*/
-{
-    return PyNumber_ToBase(number, 16);
-}
-
-
-/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
-static PyObject *
-builtin_iter(PyObject *self, PyObject *args)
-{
-    PyObject *v, *w = NULL;
-
-    if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
-        return NULL;
-    if (w == NULL)
-        return PyObject_GetIter(v);
-    if (!PyCallable_Check(v)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "iter(v, w): v must be callable");
-        return NULL;
-    }
-    return PyCallIter_New(v, w);
-}
-
-PyDoc_STRVAR(iter_doc,
-"iter(iterable) -> iterator\n\
-iter(callable, sentinel) -> iterator\n\
-\n\
-Get an iterator from an object.  In the first form, the argument must\n\
-supply its own iterator, or be a sequence.\n\
-In the second form, the callable is called until it returns the sentinel.");
-
-
-/*[clinic input]
-len as builtin_len
-
-    obj: 'O'
-    /
-
-Return the number of items in a container.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_len__doc__,
 "len($module, obj, /)\n"
 "--\n"
@@ -1850,29 +437,6 @@
 #define BUILTIN_LEN_METHODDEF    \
     {"len", (PyCFunction)builtin_len, METH_O, builtin_len__doc__},
 
-static PyObject *
-builtin_len(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=5a38b0db40761705 input=2e5ff15db9a2de22]*/
-{
-    Py_ssize_t res;
-
-    res = PyObject_Size(obj);
-    if (res < 0 && PyErr_Occurred())
-        return NULL;
-    return PyLong_FromSsize_t(res);
-}
-
-
-/*[clinic input]
-locals as builtin_locals
-
-Return a dictionary containing the current scope's local variables.
-
-NOTE: Whether or not updates to this dictionary will affect name lookups in
-the local scope and vice-versa is *implementation dependent* and not
-covered by any backwards compatibility guarantees.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_locals__doc__,
 "locals($module, /)\n"
 "--\n"
@@ -1895,165 +459,6 @@
     return builtin_locals_impl(module);
 }
 
-static PyObject *
-builtin_locals_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8ac52522924346e2 input=7874018d478d5c4b]*/
-{
-    PyObject *d;
-
-    d = PyEval_GetLocals();
-    Py_XINCREF(d);
-    return d;
-}
-
-
-static PyObject *
-min_max(PyObject *args, PyObject *kwds, int op)
-{
-    PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
-    PyObject *emptytuple, *defaultval = NULL;
-    static char *kwlist[] = {"key", "default", NULL};
-    const char *name = op == Py_LT ? "min" : "max";
-    const int positional = PyTuple_Size(args) > 1;
-    int ret;
-
-    if (positional)
-        v = args;
-    else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
-        return NULL;
-
-    emptytuple = PyTuple_New(0);
-    if (emptytuple == NULL)
-        return NULL;
-    ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
-                                      &keyfunc, &defaultval);
-    Py_DECREF(emptytuple);
-    if (!ret)
-        return NULL;
-
-    if (positional && defaultval != NULL) {
-        PyErr_Format(PyExc_TypeError,
-                        "Cannot specify a default for %s() with multiple "
-                        "positional arguments", name);
-        return NULL;
-    }
-
-    it = PyObject_GetIter(v);
-    if (it == NULL) {
-        return NULL;
-    }
-
-    maxitem = NULL; /* the result */
-    maxval = NULL;  /* the value associated with the result */
-    while (( item = PyIter_Next(it) )) {
-        /* get the value from the key function */
-        if (keyfunc != NULL) {
-            val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
-            if (val == NULL)
-                goto Fail_it_item;
-        }
-        /* no key function; the value is the item */
-        else {
-            val = item;
-            Py_INCREF(val);
-        }
-
-        /* maximum value and item are unset; set them */
-        if (maxval == NULL) {
-            maxitem = item;
-            maxval = val;
-        }
-        /* maximum value and item are set; update them as necessary */
-        else {
-            int cmp = PyObject_RichCompareBool(val, maxval, op);
-            if (cmp < 0)
-                goto Fail_it_item_and_val;
-            else if (cmp > 0) {
-                Py_DECREF(maxval);
-                Py_DECREF(maxitem);
-                maxval = val;
-                maxitem = item;
-            }
-            else {
-                Py_DECREF(item);
-                Py_DECREF(val);
-            }
-        }
-    }
-    if (PyErr_Occurred())
-        goto Fail_it;
-    if (maxval == NULL) {
-        assert(maxitem == NULL);
-        if (defaultval != NULL) {
-            Py_INCREF(defaultval);
-            maxitem = defaultval;
-        } else {
-            PyErr_Format(PyExc_ValueError,
-                         "%s() arg is an empty sequence", name);
-        }
-    }
-    else
-        Py_DECREF(maxval);
-    Py_DECREF(it);
-    return maxitem;
-
-Fail_it_item_and_val:
-    Py_DECREF(val);
-Fail_it_item:
-    Py_DECREF(item);
-Fail_it:
-    Py_XDECREF(maxval);
-    Py_XDECREF(maxitem);
-    Py_DECREF(it);
-    return NULL;
-}
-
-/* AC: cannot convert yet, waiting for *args support */
-static PyObject *
-builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    return min_max(args, kwds, Py_LT);
-}
-
-PyDoc_STRVAR(min_doc,
-"min(iterable, *[, default=obj, key=func]) -> value\n\
-min(arg1, arg2, *args, *[, key=func]) -> value\n\
-\n\
-With a single iterable argument, return its smallest item. The\n\
-default keyword-only argument specifies an object to return if\n\
-the provided iterable is empty.\n\
-With two or more arguments, return the smallest argument.");
-
-
-/* AC: cannot convert yet, waiting for *args support */
-static PyObject *
-builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    return min_max(args, kwds, Py_GT);
-}
-
-PyDoc_STRVAR(max_doc,
-"max(iterable, *[, default=obj, key=func]) -> value\n\
-max(arg1, arg2, *args, *[, key=func]) -> value\n\
-\n\
-With a single iterable argument, return its biggest item. The\n\
-default keyword-only argument specifies an object to return if\n\
-the provided iterable is empty.\n\
-With two or more arguments, return the largest argument.");
-
-
-/*[clinic input]
-oct as builtin_oct
-
-    number: 'O'
-    /
-
-Return the octal representation of an integer.
-
-   >>> oct(342391)
-   '0o1234567'
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_oct__doc__,
 "oct($module, number, /)\n"
 "--\n"
@@ -2066,23 +471,6 @@
 #define BUILTIN_OCT_METHODDEF    \
     {"oct", (PyCFunction)builtin_oct, METH_O, builtin_oct__doc__},
 
-static PyObject *
-builtin_oct(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=b99234d1d70a6673 input=a3a372b521b3dd13]*/
-{
-    return PyNumber_ToBase(number, 8);
-}
-
-
-/*[clinic input]
-ord as builtin_ord
-
-    c: 'O'
-    /
-
-Return the Unicode code point for a one-character string.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_ord__doc__,
 "ord($module, c, /)\n"
 "--\n"
@@ -2092,66 +480,6 @@
 #define BUILTIN_ORD_METHODDEF    \
     {"ord", (PyCFunction)builtin_ord, METH_O, builtin_ord__doc__},
 
-static PyObject *
-builtin_ord(PyModuleDef *module, PyObject *c)
-/*[clinic end generated code: output=a8466d23bd76db3f input=762355f87451efa3]*/
-{
-    long ord;
-    Py_ssize_t size;
-
-    if (PyBytes_Check(c)) {
-        size = PyBytes_GET_SIZE(c);
-        if (size == 1) {
-            ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
-            return PyLong_FromLong(ord);
-        }
-    }
-    else if (PyUnicode_Check(c)) {
-        if (PyUnicode_READY(c) == -1)
-            return NULL;
-        size = PyUnicode_GET_LENGTH(c);
-        if (size == 1) {
-            ord = (long)PyUnicode_READ_CHAR(c, 0);
-            return PyLong_FromLong(ord);
-        }
-    }
-    else if (PyByteArray_Check(c)) {
-        /* XXX Hopefully this is temporary */
-        size = PyByteArray_GET_SIZE(c);
-        if (size == 1) {
-            ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
-            return PyLong_FromLong(ord);
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "ord() expected string of length 1, but " \
-                     "%.200s found", c->ob_type->tp_name);
-        return NULL;
-    }
-
-    PyErr_Format(PyExc_TypeError,
-                 "ord() expected a character, "
-                 "but string of length %zd found",
-                 size);
-    return NULL;
-}
-
-
-/*[clinic input]
-pow as builtin_pow
-
-    x: 'O'
-    y: 'O'
-    z: 'O' = None
-    /
-
-Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
-
-Some types, such as ints, are able to use a more efficient algorithm when
-invoked using the three argument form.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_pow__doc__,
 "pow($module, x, y, z=None, /)\n"
 "--\n"
@@ -2185,125 +513,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
-/*[clinic end generated code: output=d0cdf314311dedba input=561a942d5f5c1899]*/
-{
-    return PyNumber_Power(x, y, z);
-}
-
-
-/* AC: cannot convert yet, waiting for *args support */
-static PyObject *
-builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    static char *kwlist[] = {"sep", "end", "file", "flush", 0};
-    static PyObject *dummy_args;
-    PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
-    int i, err;
-
-    if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
-        return NULL;
-    if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
-                                     kwlist, &sep, &end, &file, &flush))
-        return NULL;
-    if (file == NULL || file == Py_None) {
-        file = _PySys_GetObjectId(&PyId_stdout);
-        if (file == NULL) {
-            PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
-            return NULL;
-        }
-
-        /* sys.stdout may be None when FILE* stdout isn't connected */
-        if (file == Py_None)
-            Py_RETURN_NONE;
-    }
-
-    if (sep == Py_None) {
-        sep = NULL;
-    }
-    else if (sep && !PyUnicode_Check(sep)) {
-        PyErr_Format(PyExc_TypeError,
-                     "sep must be None or a string, not %.200s",
-                     sep->ob_type->tp_name);
-        return NULL;
-    }
-    if (end == Py_None) {
-        end = NULL;
-    }
-    else if (end && !PyUnicode_Check(end)) {
-        PyErr_Format(PyExc_TypeError,
-                     "end must be None or a string, not %.200s",
-                     end->ob_type->tp_name);
-        return NULL;
-    }
-
-    for (i = 0; i < PyTuple_Size(args); i++) {
-        if (i > 0) {
-            if (sep == NULL)
-                err = PyFile_WriteString(" ", file);
-            else
-                err = PyFile_WriteObject(sep, file,
-                                         Py_PRINT_RAW);
-            if (err)
-                return NULL;
-        }
-        err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
-                                 Py_PRINT_RAW);
-        if (err)
-            return NULL;
-    }
-
-    if (end == NULL)
-        err = PyFile_WriteString("\n", file);
-    else
-        err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
-    if (err)
-        return NULL;
-
-    if (flush != NULL) {
-        PyObject *tmp;
-        int do_flush = PyObject_IsTrue(flush);
-        if (do_flush == -1)
-            return NULL;
-        else if (do_flush) {
-            tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
-            if (tmp == NULL)
-                return NULL;
-            else
-                Py_DECREF(tmp);
-        }
-    }
-
-    Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(print_doc,
-"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
-\n\
-Prints the values to a stream, or to sys.stdout by default.\n\
-Optional keyword arguments:\n\
-file:  a file-like object (stream); defaults to the current sys.stdout.\n\
-sep:   string inserted between values, default a space.\n\
-end:   string appended after the last value, default a newline.\n\
-flush: whether to forcibly flush the stream.");
-
-
-/*[clinic input]
-input as builtin_input
-
-    prompt: object(c_default="NULL") = None
-    /
-
-Read a string from standard input.  The trailing newline is stripped.
-
-The prompt string, if given, is printed to standard output without a
-trailing newline before reading input.
-
-If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
-On *nix systems, readline is used if available.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_input__doc__,
 "input($module, prompt=None, /)\n"
 "--\n"
@@ -2338,191 +547,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_input_impl(PyModuleDef *module, PyObject *prompt)
-/*[clinic end generated code: output=69323bf5695f7c9c input=5e8bb70c2908fe3c]*/
-{
-    PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
-    PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
-    PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
-    PyObject *tmp;
-    long fd;
-    int tty;
-
-    /* Check that stdin/out/err are intact */
-    if (fin == NULL || fin == Py_None) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "input(): lost sys.stdin");
-        return NULL;
-    }
-    if (fout == NULL || fout == Py_None) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "input(): lost sys.stdout");
-        return NULL;
-    }
-    if (ferr == NULL || ferr == Py_None) {
-        PyErr_SetString(PyExc_RuntimeError,
-                        "input(): lost sys.stderr");
-        return NULL;
-    }
-
-    /* First of all, flush stderr */
-    tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
-    if (tmp == NULL)
-        PyErr_Clear();
-    else
-        Py_DECREF(tmp);
-
-    /* We should only use (GNU) readline if Python's sys.stdin and
-       sys.stdout are the same as C's stdin and stdout, because we
-       need to pass it those. */
-    tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
-    if (tmp == NULL) {
-        PyErr_Clear();
-        tty = 0;
-    }
-    else {
-        fd = PyLong_AsLong(tmp);
-        Py_DECREF(tmp);
-        if (fd < 0 && PyErr_Occurred())
-            return NULL;
-        tty = fd == fileno(stdin) && isatty(fd);
-    }
-    if (tty) {
-        tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
-        if (tmp == NULL)
-            PyErr_Clear();
-        else {
-            fd = PyLong_AsLong(tmp);
-            Py_DECREF(tmp);
-            if (fd < 0 && PyErr_Occurred())
-                return NULL;
-            tty = fd == fileno(stdout) && isatty(fd);
-        }
-    }
-
-    /* If we're interactive, use (GNU) readline */
-    if (tty) {
-        PyObject *po = NULL;
-        char *promptstr;
-        char *s = NULL;
-        PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
-        PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
-        char *stdin_encoding_str, *stdin_errors_str;
-        PyObject *result;
-        size_t len;
-
-        stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
-        stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
-        if (!stdin_encoding || !stdin_errors)
-            /* stdin is a text stream, so it must have an
-               encoding. */
-            goto _readline_errors;
-        stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
-        stdin_errors_str = _PyUnicode_AsString(stdin_errors);
-        if (!stdin_encoding_str || !stdin_errors_str)
-            goto _readline_errors;
-        tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
-        if (tmp == NULL)
-            PyErr_Clear();
-        else
-            Py_DECREF(tmp);
-        if (prompt != NULL) {
-            /* We have a prompt, encode it as stdout would */
-            char *stdout_encoding_str, *stdout_errors_str;
-            PyObject *stringpo;
-            stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
-            stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
-            if (!stdout_encoding || !stdout_errors)
-                goto _readline_errors;
-            stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
-            stdout_errors_str = _PyUnicode_AsString(stdout_errors);
-            if (!stdout_encoding_str || !stdout_errors_str)
-                goto _readline_errors;
-            stringpo = PyObject_Str(prompt);
-            if (stringpo == NULL)
-                goto _readline_errors;
-            po = PyUnicode_AsEncodedString(stringpo,
-                stdout_encoding_str, stdout_errors_str);
-            Py_CLEAR(stdout_encoding);
-            Py_CLEAR(stdout_errors);
-            Py_CLEAR(stringpo);
-            if (po == NULL)
-                goto _readline_errors;
-            promptstr = PyBytes_AsString(po);
-            if (promptstr == NULL)
-                goto _readline_errors;
-        }
-        else {
-            po = NULL;
-            promptstr = "";
-        }
-        s = PyOS_Readline(stdin, stdout, promptstr);
-        if (s == NULL) {
-            PyErr_CheckSignals();
-            if (!PyErr_Occurred())
-                PyErr_SetNone(PyExc_KeyboardInterrupt);
-            goto _readline_errors;
-        }
-
-        len = strlen(s);
-        if (len == 0) {
-            PyErr_SetNone(PyExc_EOFError);
-            result = NULL;
-        }
-        else {
-            if (len > PY_SSIZE_T_MAX) {
-                PyErr_SetString(PyExc_OverflowError,
-                                "input: input too long");
-                result = NULL;
-            }
-            else {
-                len--;   /* strip trailing '\n' */
-                if (len != 0 && s[len-1] == '\r')
-                    len--;   /* strip trailing '\r' */
-                result = PyUnicode_Decode(s, len, stdin_encoding_str,
-                                                  stdin_errors_str);
-            }
-        }
-        Py_DECREF(stdin_encoding);
-        Py_DECREF(stdin_errors);
-        Py_XDECREF(po);
-        PyMem_FREE(s);
-        return result;
-    _readline_errors:
-        Py_XDECREF(stdin_encoding);
-        Py_XDECREF(stdout_encoding);
-        Py_XDECREF(stdin_errors);
-        Py_XDECREF(stdout_errors);
-        Py_XDECREF(po);
-        return NULL;
-    }
-
-    /* Fallback if we're not interactive */
-    if (prompt != NULL) {
-        if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
-            return NULL;
-    }
-    tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
-    if (tmp == NULL)
-        PyErr_Clear();
-    else
-        Py_DECREF(tmp);
-    return PyFile_GetLine(fin, -1);
-}
-
-
-/*[clinic input]
-repr as builtin_repr
-
-    obj: 'O'
-    /
-
-Return the canonical string representation of the object.
-
-For many object types, including most builtins, eval(repr(obj)) == obj.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_repr__doc__,
 "repr($module, obj, /)\n"
 "--\n"
@@ -2534,176 +558,6 @@
 #define BUILTIN_REPR_METHODDEF    \
     {"repr", (PyCFunction)builtin_repr, METH_O, builtin_repr__doc__},
 
-static PyObject *
-builtin_repr(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=988980120f39e2fa input=a2bca0f38a5a924d]*/
-{
-    return PyObject_Repr(obj);
-}
-
-
-/* AC: cannot convert yet, as needs PEP 457 group support in inspect
- *     or a semantic change to accept None for "ndigits"
- */
-static PyObject *
-builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    PyObject *ndigits = NULL;
-    static char *kwlist[] = {"number", "ndigits", 0};
-    PyObject *number, *round, *result;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
-                                     kwlist, &number, &ndigits))
-        return NULL;
-
-    if (Py_TYPE(number)->tp_dict == NULL) {
-        if (PyType_Ready(Py_TYPE(number)) < 0)
-            return NULL;
-    }
-
-    round = _PyObject_LookupSpecial(number, &PyId___round__);
-    if (round == NULL) {
-        if (!PyErr_Occurred())
-            PyErr_Format(PyExc_TypeError,
-                         "type %.100s doesn't define __round__ method",
-                         Py_TYPE(number)->tp_name);
-        return NULL;
-    }
-
-    if (ndigits == NULL)
-        result = PyObject_CallFunctionObjArgs(round, NULL);
-    else
-        result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
-    Py_DECREF(round);
-    return result;
-}
-
-PyDoc_STRVAR(round_doc,
-"round(number[, ndigits]) -> number\n\
-\n\
-Round a number to a given precision in decimal digits (default 0 digits).\n\
-This returns an int when called with one argument, otherwise the\n\
-same type as the number. ndigits may be negative.");
-
-
-/*AC: we need to keep the kwds dict intact to easily call into the
- * list.sort method, which isn't currently supported in AC. So we just use
- * the initially generated signature with a custom implementation.
- */
-/* [disabled clinic input]
-sorted as builtin_sorted
-
-    iterable as seq: 'O'
-    key as keyfunc: 'O' = None
-    reverse: 'O' = False
-
-Return a new list containing all items from the iterable in ascending order.
-
-A custom key function can be supplied to customise the sort order, and the
-reverse flag can be set to request the result in descending order.
-[end disabled clinic input]*/
-
-PyDoc_STRVAR(builtin_sorted__doc__,
-"sorted($module, iterable, key=None, reverse=False)\n"
-"--\n"
-"\n"
-"Return a new list containing all items from the iterable in ascending order.\n"
-"\n"
-"A custom key function can be supplied to customise the sort order, and the\n"
-"reverse flag can be set to request the result in descending order.");
-
-#define BUILTIN_SORTED_METHODDEF    \
-    {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
-
-static PyObject *
-builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
-{
-    PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
-    PyObject *callable;
-    static char *kwlist[] = {"iterable", "key", "reverse", 0};
-    int reverse;
-
-    /* args 1-3 should match listsort in Objects/listobject.c */
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
-        kwlist, &seq, &keyfunc, &reverse))
-        return NULL;
-
-    newlist = PySequence_List(seq);
-    if (newlist == NULL)
-        return NULL;
-
-    callable = _PyObject_GetAttrId(newlist, &PyId_sort);
-    if (callable == NULL) {
-        Py_DECREF(newlist);
-        return NULL;
-    }
-
-    newargs = PyTuple_GetSlice(args, 1, 4);
-    if (newargs == NULL) {
-        Py_DECREF(newlist);
-        Py_DECREF(callable);
-        return NULL;
-    }
-
-    v = PyObject_Call(callable, newargs, kwds);
-    Py_DECREF(newargs);
-    Py_DECREF(callable);
-    if (v == NULL) {
-        Py_DECREF(newlist);
-        return NULL;
-    }
-    Py_DECREF(v);
-    return newlist;
-}
-
-
-/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
-static PyObject *
-builtin_vars(PyObject *self, PyObject *args)
-{
-    PyObject *v = NULL;
-    PyObject *d;
-
-    if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
-        return NULL;
-    if (v == NULL) {
-        d = PyEval_GetLocals();
-        if (d == NULL)
-            return NULL;
-        Py_INCREF(d);
-    }
-    else {
-        d = _PyObject_GetAttrId(v, &PyId___dict__);
-        if (d == NULL) {
-            PyErr_SetString(PyExc_TypeError,
-                "vars() argument must have __dict__ attribute");
-            return NULL;
-        }
-    }
-    return d;
-}
-
-PyDoc_STRVAR(vars_doc,
-"vars([object]) -> dictionary\n\
-\n\
-Without arguments, equivalent to locals().\n\
-With an argument, equivalent to object.__dict__.");
-
-
-/*[clinic input]
-sum as builtin_sum
-
-    iterable: 'O'
-    start: object(c_default="NULL") = 0
-    /
-
-Return the sum of a 'start' value (default: 0) plus an iterable of numbers
-
-When the iterable is empty, return the start value.
-This function is intended specifically for use with numeric values and may
-reject non-numeric types.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_sum__doc__,
 "sum($module, iterable, start=0, /)\n"
 "--\n"
@@ -2737,183 +591,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
-/*[clinic end generated code: output=b42652a0d5f64f6b input=90ae7a242cfcf025]*/
-{
-    PyObject *result = start;
-    PyObject *temp, *item, *iter;
-
-    iter = PyObject_GetIter(iterable);
-    if (iter == NULL)
-        return NULL;
-
-    if (result == NULL) {
-        result = PyLong_FromLong(0);
-        if (result == NULL) {
-            Py_DECREF(iter);
-            return NULL;
-        }
-    } else {
-        /* reject string values for 'start' parameter */
-        if (PyUnicode_Check(result)) {
-            PyErr_SetString(PyExc_TypeError,
-                "sum() can't sum strings [use ''.join(seq) instead]");
-            Py_DECREF(iter);
-            return NULL;
-        }
-        if (PyBytes_Check(result)) {
-            PyErr_SetString(PyExc_TypeError,
-                "sum() can't sum bytes [use b''.join(seq) instead]");
-            Py_DECREF(iter);
-            return NULL;
-        }
-        if (PyByteArray_Check(result)) {
-            PyErr_SetString(PyExc_TypeError,
-                "sum() can't sum bytearray [use b''.join(seq) instead]");
-            Py_DECREF(iter);
-            return NULL;
-        }
-        Py_INCREF(result);
-    }
-
-#ifndef SLOW_SUM
-    /* Fast addition by keeping temporary sums in C instead of new Python objects.
-       Assumes all inputs are the same type.  If the assumption fails, default
-       to the more general routine.
-    */
-    if (PyLong_CheckExact(result)) {
-        int overflow;
-        long i_result = PyLong_AsLongAndOverflow(result, &overflow);
-        /* If this already overflowed, don't even enter the loop. */
-        if (overflow == 0) {
-            Py_DECREF(result);
-            result = NULL;
-        }
-        while(result == NULL) {
-            item = PyIter_Next(iter);
-            if (item == NULL) {
-                Py_DECREF(iter);
-                if (PyErr_Occurred())
-                    return NULL;
-                return PyLong_FromLong(i_result);
-            }
-            if (PyLong_CheckExact(item)) {
-                long b = PyLong_AsLongAndOverflow(item, &overflow);
-                long x = i_result + b;
-                if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
-                    i_result = x;
-                    Py_DECREF(item);
-                    continue;
-                }
-            }
-            /* Either overflowed or is not an int. Restore real objects and process normally */
-            result = PyLong_FromLong(i_result);
-            if (result == NULL) {
-                Py_DECREF(item);
-                Py_DECREF(iter);
-                return NULL;
-            }
-            temp = PyNumber_Add(result, item);
-            Py_DECREF(result);
-            Py_DECREF(item);
-            result = temp;
-            if (result == NULL) {
-                Py_DECREF(iter);
-                return NULL;
-            }
-        }
-    }
-
-    if (PyFloat_CheckExact(result)) {
-        double f_result = PyFloat_AS_DOUBLE(result);
-        Py_DECREF(result);
-        result = NULL;
-        while(result == NULL) {
-            item = PyIter_Next(iter);
-            if (item == NULL) {
-                Py_DECREF(iter);
-                if (PyErr_Occurred())
-                    return NULL;
-                return PyFloat_FromDouble(f_result);
-            }
-            if (PyFloat_CheckExact(item)) {
-                PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
-                f_result += PyFloat_AS_DOUBLE(item);
-                PyFPE_END_PROTECT(f_result)
-                Py_DECREF(item);
-                continue;
-            }
-            if (PyLong_CheckExact(item)) {
-                long value;
-                int overflow;
-                value = PyLong_AsLongAndOverflow(item, &overflow);
-                if (!overflow) {
-                    PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
-                    f_result += (double)value;
-                    PyFPE_END_PROTECT(f_result)
-                    Py_DECREF(item);
-                    continue;
-                }
-            }
-            result = PyFloat_FromDouble(f_result);
-            temp = PyNumber_Add(result, item);
-            Py_DECREF(result);
-            Py_DECREF(item);
-            result = temp;
-            if (result == NULL) {
-                Py_DECREF(iter);
-                return NULL;
-            }
-        }
-    }
-#endif
-
-    for(;;) {
-        item = PyIter_Next(iter);
-        if (item == NULL) {
-            /* error, or end-of-sequence */
-            if (PyErr_Occurred()) {
-                Py_DECREF(result);
-                result = NULL;
-            }
-            break;
-        }
-        /* It's tempting to use PyNumber_InPlaceAdd instead of
-           PyNumber_Add here, to avoid quadratic running time
-           when doing 'sum(list_of_lists, [])'.  However, this
-           would produce a change in behaviour: a snippet like
-
-             empty = []
-             sum([[x] for x in range(10)], empty)
-
-           would change the value of empty. */
-        temp = PyNumber_Add(result, item);
-        Py_DECREF(result);
-        Py_DECREF(item);
-        result = temp;
-        if (result == NULL)
-            break;
-    }
-    Py_DECREF(iter);
-    return result;
-}
-
-
-/*[clinic input]
-isinstance as builtin_isinstance
-
-    obj: 'O'
-    class_or_tuple: 'O'
-    /
-
-Return whether an object is an instance of a class or of a subclass thereof.
-
-A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
-check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
-or ...`` etc.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_isinstance__doc__,
 "isinstance($module, obj, class_or_tuple, /)\n"
 "--\n"
@@ -2947,33 +624,6 @@
     return return_value;
 }
 
-static PyObject *
-builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple)
-/*[clinic end generated code: output=847df57fef8ddea7 input=cf9eb0ad6bb9bad6]*/
-{
-    int retval;
-
-    retval = PyObject_IsInstance(obj, class_or_tuple);
-    if (retval < 0)
-        return NULL;
-    return PyBool_FromLong(retval);
-}
-
-
-/*[clinic input]
-issubclass as builtin_issubclass
-
-    cls: 'O'
-    class_or_tuple: 'O'
-    /
-
-Return whether 'cls' is a derived from another class or is the same class.
-
-A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
-check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
-or ...`` etc.
-[clinic start generated code]*/
-
 PyDoc_STRVAR(builtin_issubclass__doc__,
 "issubclass($module, cls, class_or_tuple, /)\n"
 "--\n"
@@ -3006,344 +656,4 @@
 exit:
     return return_value;
 }
-
-static PyObject *
-builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple)
-/*[clinic end generated code: output=a0f8c03692e35474 input=923d03fa41fc352a]*/
-{
-    int retval;
-
-    retval = PyObject_IsSubclass(cls, class_or_tuple);
-    if (retval < 0)
-        return NULL;
-    return PyBool_FromLong(retval);
-}
-
-
-typedef struct {
-    PyObject_HEAD
-    Py_ssize_t          tuplesize;
-    PyObject *ittuple;                  /* tuple of iterators */
-    PyObject *result;
-} zipobject;
-
-static PyObject *
-zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-    zipobject *lz;
-    Py_ssize_t i;
-    PyObject *ittuple;  /* tuple of iterators */
-    PyObject *result;
-    Py_ssize_t tuplesize = PySequence_Length(args);
-
-    if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
-        return NULL;
-
-    /* args must be a tuple */
-    assert(PyTuple_Check(args));
-
-    /* obtain iterators */
-    ittuple = PyTuple_New(tuplesize);
-    if (ittuple == NULL)
-        return NULL;
-    for (i=0; i < tuplesize; ++i) {
-        PyObject *item = PyTuple_GET_ITEM(args, i);
-        PyObject *it = PyObject_GetIter(item);
-        if (it == NULL) {
-            if (PyErr_ExceptionMatches(PyExc_TypeError))
-                PyErr_Format(PyExc_TypeError,
-                    "zip argument #%zd must support iteration",
-                    i+1);
-            Py_DECREF(ittuple);
-            return NULL;
-        }
-        PyTuple_SET_ITEM(ittuple, i, it);
-    }
-
-    /* create a result holder */
-    result = PyTuple_New(tuplesize);
-    if (result == NULL) {
-        Py_DECREF(ittuple);
-        return NULL;
-    }
-    for (i=0 ; i < tuplesize ; i++) {
-        Py_INCREF(Py_None);
-        PyTuple_SET_ITEM(result, i, Py_None);
-    }
-
-    /* create zipobject structure */
-    lz = (zipobject *)type->tp_alloc(type, 0);
-    if (lz == NULL) {
-        Py_DECREF(ittuple);
-        Py_DECREF(result);
-        return NULL;
-    }
-    lz->ittuple = ittuple;
-    lz->tuplesize = tuplesize;
-    lz->result = result;
-
-    return (PyObject *)lz;
-}
-
-static void
-zip_dealloc(zipobject *lz)
-{
-    PyObject_GC_UnTrack(lz);
-    Py_XDECREF(lz->ittuple);
-    Py_XDECREF(lz->result);
-    Py_TYPE(lz)->tp_free(lz);
-}
-
-static int
-zip_traverse(zipobject *lz, visitproc visit, void *arg)
-{
-    Py_VISIT(lz->ittuple);
-    Py_VISIT(lz->result);
-    return 0;
-}
-
-static PyObject *
-zip_next(zipobject *lz)
-{
-    Py_ssize_t i;
-    Py_ssize_t tuplesize = lz->tuplesize;
-    PyObject *result = lz->result;
-    PyObject *it;
-    PyObject *item;
-    PyObject *olditem;
-
-    if (tuplesize == 0)
-        return NULL;
-    if (Py_REFCNT(result) == 1) {
-        Py_INCREF(result);
-        for (i=0 ; i < tuplesize ; i++) {
-            it = PyTuple_GET_ITEM(lz->ittuple, i);
-            item = (*Py_TYPE(it)->tp_iternext)(it);
-            if (item == NULL) {
-                Py_DECREF(result);
-                return NULL;
-            }
-            olditem = PyTuple_GET_ITEM(result, i);
-            PyTuple_SET_ITEM(result, i, item);
-            Py_DECREF(olditem);
-        }
-    } else {
-        result = PyTuple_New(tuplesize);
-        if (result == NULL)
-            return NULL;
-        for (i=0 ; i < tuplesize ; i++) {
-            it = PyTuple_GET_ITEM(lz->ittuple, i);
-            item = (*Py_TYPE(it)->tp_iternext)(it);
-            if (item == NULL) {
-                Py_DECREF(result);
-                return NULL;
-            }
-            PyTuple_SET_ITEM(result, i, item);
-        }
-    }
-    return result;
-}
-
-static PyObject *
-zip_reduce(zipobject *lz)
-{
-    /* Just recreate the zip with the internal iterator tuple */
-    return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
-}
-
-static PyMethodDef zip_methods[] = {
-    {"__reduce__",   (PyCFunction)zip_reduce,   METH_NOARGS, reduce_doc},
-    {NULL,           NULL}           /* sentinel */
-};
-
-PyDoc_STRVAR(zip_doc,
-"zip(iter1 [,iter2 [...]]) --> zip object\n\
-\n\
-Return a zip object whose .__next__() method returns a tuple where\n\
-the i-th element comes from the i-th iterable argument.  The .__next__()\n\
-method continues until the shortest iterable in the argument sequence\n\
-is exhausted and then it raises StopIteration.");
-
-PyTypeObject PyZip_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "zip",                              /* tp_name */
-    sizeof(zipobject),                  /* tp_basicsize */
-    0,                                  /* tp_itemsize */
-    /* methods */
-    (destructor)zip_dealloc,            /* tp_dealloc */
-    0,                                  /* tp_print */
-    0,                                  /* tp_getattr */
-    0,                                  /* tp_setattr */
-    0,                                  /* tp_reserved */
-    0,                                  /* tp_repr */
-    0,                                  /* tp_as_number */
-    0,                                  /* tp_as_sequence */
-    0,                                  /* tp_as_mapping */
-    0,                                  /* tp_hash */
-    0,                                  /* tp_call */
-    0,                                  /* tp_str */
-    PyObject_GenericGetAttr,            /* tp_getattro */
-    0,                                  /* tp_setattro */
-    0,                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-        Py_TPFLAGS_BASETYPE,            /* tp_flags */
-    zip_doc,                            /* tp_doc */
-    (traverseproc)zip_traverse,    /* tp_traverse */
-    0,                                  /* tp_clear */
-    0,                                  /* tp_richcompare */
-    0,                                  /* tp_weaklistoffset */
-    PyObject_SelfIter,                  /* tp_iter */
-    (iternextfunc)zip_next,     /* tp_iternext */
-    zip_methods,                        /* tp_methods */
-    0,                                  /* tp_members */
-    0,                                  /* tp_getset */
-    0,                                  /* tp_base */
-    0,                                  /* tp_dict */
-    0,                                  /* tp_descr_get */
-    0,                                  /* tp_descr_set */
-    0,                                  /* tp_dictoffset */
-    0,                                  /* tp_init */
-    PyType_GenericAlloc,                /* tp_alloc */
-    zip_new,                            /* tp_new */
-    PyObject_GC_Del,                    /* tp_free */
-};
-
-
-static PyMethodDef builtin_methods[] = {
-    {"__build_class__", (PyCFunction)builtin___build_class__,
-     METH_VARARGS | METH_KEYWORDS, build_class_doc},
-    {"__import__",      (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
-    BUILTIN_ABS_METHODDEF
-    BUILTIN_ALL_METHODDEF
-    BUILTIN_ANY_METHODDEF
-    BUILTIN_ASCII_METHODDEF
-    BUILTIN_BIN_METHODDEF
-    BUILTIN_CALLABLE_METHODDEF
-    BUILTIN_CHR_METHODDEF
-    BUILTIN_COMPILE_METHODDEF
-    BUILTIN_DELATTR_METHODDEF
-    {"dir",             builtin_dir,        METH_VARARGS, dir_doc},
-    BUILTIN_DIVMOD_METHODDEF
-    BUILTIN_EVAL_METHODDEF
-    BUILTIN_EXEC_METHODDEF
-    BUILTIN_FORMAT_METHODDEF
-    {"getattr",         builtin_getattr,    METH_VARARGS, getattr_doc},
-    BUILTIN_GLOBALS_METHODDEF
-    BUILTIN_HASATTR_METHODDEF
-    BUILTIN_HASH_METHODDEF
-    BUILTIN_HEX_METHODDEF
-    BUILTIN_ID_METHODDEF
-    BUILTIN_INPUT_METHODDEF
-    BUILTIN_ISINSTANCE_METHODDEF
-    BUILTIN_ISSUBCLASS_METHODDEF
-    {"iter",            builtin_iter,       METH_VARARGS, iter_doc},
-    BUILTIN_LEN_METHODDEF
-    BUILTIN_LOCALS_METHODDEF
-    {"max",             (PyCFunction)builtin_max,        METH_VARARGS | METH_KEYWORDS, max_doc},
-    {"min",             (PyCFunction)builtin_min,        METH_VARARGS | METH_KEYWORDS, min_doc},
-    {"next",            (PyCFunction)builtin_next,       METH_VARARGS, next_doc},
-    BUILTIN_OCT_METHODDEF
-    BUILTIN_ORD_METHODDEF
-    BUILTIN_POW_METHODDEF
-    {"print",           (PyCFunction)builtin_print,      METH_VARARGS | METH_KEYWORDS, print_doc},
-    BUILTIN_REPR_METHODDEF
-    {"round",           (PyCFunction)builtin_round,      METH_VARARGS | METH_KEYWORDS, round_doc},
-    BUILTIN_SETATTR_METHODDEF
-    BUILTIN_SORTED_METHODDEF
-    BUILTIN_SUM_METHODDEF
-    {"vars",            builtin_vars,       METH_VARARGS, vars_doc},
-    {NULL,              NULL},
-};
-
-PyDoc_STRVAR(builtin_doc,
-"Built-in functions, exceptions, and other objects.\n\
-\n\
-Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
-
-static struct PyModuleDef builtinsmodule = {
-    PyModuleDef_HEAD_INIT,
-    "builtins",
-    builtin_doc,
-    -1, /* multiple "initialization" just copies the module dict. */
-    builtin_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-
-PyObject *
-_PyBuiltin_Init(void)
-{
-    PyObject *mod, *dict, *debug;
-
-    if (PyType_Ready(&PyFilter_Type) < 0 ||
-        PyType_Ready(&PyMap_Type) < 0 ||
-        PyType_Ready(&PyZip_Type) < 0)
-        return NULL;
-
-    mod = PyModule_Create(&builtinsmodule);
-    if (mod == NULL)
-        return NULL;
-    dict = PyModule_GetDict(mod);
-
-#ifdef Py_TRACE_REFS
-    /* "builtins" exposes a number of statically allocated objects
-     * that, before this code was added in 2.3, never showed up in
-     * the list of "all objects" maintained by Py_TRACE_REFS.  As a
-     * result, programs leaking references to None and False (etc)
-     * couldn't be diagnosed by examining sys.getobjects(0).
-     */
-#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
-#else
-#define ADD_TO_ALL(OBJECT) (void)0
-#endif
-
-#define SETBUILTIN(NAME, OBJECT) \
-    if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0)       \
-        return NULL;                                                    \
-    ADD_TO_ALL(OBJECT)
-
-    SETBUILTIN("None",                  Py_None);
-    SETBUILTIN("Ellipsis",              Py_Ellipsis);
-    SETBUILTIN("NotImplemented",        Py_NotImplemented);
-    SETBUILTIN("False",                 Py_False);
-    SETBUILTIN("True",                  Py_True);
-    SETBUILTIN("bool",                  &PyBool_Type);
-    SETBUILTIN("memoryview",        &PyMemoryView_Type);
-    SETBUILTIN("bytearray",             &PyByteArray_Type);
-    SETBUILTIN("bytes",                 &PyBytes_Type);
-    SETBUILTIN("classmethod",           &PyClassMethod_Type);
-    SETBUILTIN("complex",               &PyComplex_Type);
-    SETBUILTIN("dict",                  &PyDict_Type);
-    SETBUILTIN("enumerate",             &PyEnum_Type);
-    SETBUILTIN("filter",                &PyFilter_Type);
-    SETBUILTIN("float",                 &PyFloat_Type);
-    SETBUILTIN("frozenset",             &PyFrozenSet_Type);
-    SETBUILTIN("property",              &PyProperty_Type);
-    SETBUILTIN("int",                   &PyLong_Type);
-    SETBUILTIN("list",                  &PyList_Type);
-    SETBUILTIN("map",                   &PyMap_Type);
-    SETBUILTIN("object",                &PyBaseObject_Type);
-    SETBUILTIN("range",                 &PyRange_Type);
-    SETBUILTIN("reversed",              &PyReversed_Type);
-    SETBUILTIN("set",                   &PySet_Type);
-    SETBUILTIN("slice",                 &PySlice_Type);
-    SETBUILTIN("staticmethod",          &PyStaticMethod_Type);
-    SETBUILTIN("str",                   &PyUnicode_Type);
-    SETBUILTIN("super",                 &PySuper_Type);
-    SETBUILTIN("tuple",                 &PyTuple_Type);
-    SETBUILTIN("type",                  &PyType_Type);
-    SETBUILTIN("zip",                   &PyZip_Type);
-    debug = PyBool_FromLong(Py_OptimizeFlag == 0);
-    if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
-        Py_XDECREF(debug);
-        return NULL;
-    }
-    Py_XDECREF(debug);
-
-    return mod;
-#undef ADD_TO_ALL
-#undef SETBUILTIN
-}
+/*[clinic end generated code: output=2da46de189e48d26 input=a9049054013a1b77]*/
diff --git a/Python/import.c b/Python/import.c
--- a/Python/import.c
+++ b/Python/import.c
@@ -32,10 +32,9 @@
 static PyObject *initstr = NULL;
 
 /*[clinic input]
-output preset file
 module _imp
 [clinic start generated code]*/
-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=98c38221164579d5]*/
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
 
 #include "clinic/import.c.h"
 
diff --git a/Tools/clinic/clinic.py b/Tools/clinic/clinic.py
--- a/Tools/clinic/clinic.py
+++ b/Tools/clinic/clinic.py
@@ -1590,15 +1590,15 @@
 
         d = self.get_destination_buffer
         self.destination_buffers = collections.OrderedDict((
-            ('cpp_if', d('suppress')),
+            ('cpp_if', d('file')),
             ('docstring_prototype', d('suppress')),
-            ('docstring_definition', d('block')),
-            ('methoddef_define', d('block')),
-            ('impl_prototype', d('block')),
+            ('docstring_definition', d('file')),
+            ('methoddef_define', d('file')),
+            ('impl_prototype', d('file')),
             ('parser_prototype', d('suppress')),
-            ('parser_definition', d('block')),
-            ('cpp_endif', d('suppress')),
-            ('methoddef_ifndef', d('buffer', 1)),
+            ('parser_definition', d('file')),
+            ('cpp_endif', d('file')),
+            ('methoddef_ifndef', d('file', 1)),
             ('impl_definition', d('block')),
         ))
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list